#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
-#include "alarmmonitor.h"
+#include <errno.h>
-static CURLM* curl_multi_handle;
+static CURLM* curl_multi_handle = NULL;
static uv_timer_t timeout;
// libcurl socket回调
// 初始化下载模块
void download_init(uv_loop_t* loop) {
+ if (curl_multi_handle) return; // 防止重复初始化
+
curl_global_init(CURL_GLOBAL_ALL);
curl_multi_handle = curl_multi_init();
+ if (!curl_multi_handle) {
+ fprintf(stderr, "Failed to create curl multi handle\n");
+ return;
+ }
+
curl_multi_setopt(curl_multi_handle, CURLMOPT_SOCKETFUNCTION, curl_socket_cb);
curl_multi_setopt(curl_multi_handle, CURLMOPT_SOCKETDATA, loop);
-
+
uv_timer_init(loop, &timeout);
}
) {
// 创建请求对象
download_request* req = calloc(1, sizeof(download_request));
+ if (!req) {
+ fprintf(stderr, "Failed to allocate download_request\n");
+ return NULL;
+ }
+
+ // 设置基本属性
strncpy(req->url, url, sizeof(req->url)-1);
strncpy(req->output_path, output_path, sizeof(req->output_path)-1);
req->loop = loop;
req->userdata = userdata;
req->total_size = -1;
req->downloaded = 0;
-
- // 打开文件前检查目录是否存在
- char* dir_path = strdup(output_path);
- char* dir_end = strrchr(dir_path, '/');
- if (dir_end) {
- *dir_end = '\0'; // 截断到目录部分
-
- // 检查目录是否存在
- if (access(dir_path, F_OK) != 0) {
- fprintf(stderr, "Directory does not exist: %s\n", dir_path);
- free(dir_path);
- if (complete_cb) complete_cb(-1, userdata);
- free(req);
- return NULL;
- }
- }
- free(dir_path);
-
+
// 打开文件
- int fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
- if (fd < 0) {
- perror("open file failed");
- if (complete_cb) complete_cb(-1, userdata);
+ req->file_ptr = fopen(output_path, "wb");
+ if (!req->file_ptr) {
+ fprintf(stderr, "Failed to open file: %s, error: %s\n",
+ output_path, strerror(errno));
free(req);
return NULL;
}
- req->file_handle.data = req;
- uv_fs_open(loop, &req->file_handle, output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644, NULL);
- req->file_ptr = fdopen(fd, "wb");
-
+
// 配置CURL
req->curl_handle = curl_easy_init();
+ if (!req->curl_handle) {
+ fprintf(stderr, "Failed to create curl easy handle\n");
+ fclose(req->file_ptr);
+ free(req);
+ return NULL;
+ }
+
curl_easy_setopt(req->curl_handle, CURLOPT_URL, url);
curl_easy_setopt(req->curl_handle, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(req->curl_handle, CURLOPT_WRITEDATA, req);
curl_easy_setopt(req->curl_handle, CURLOPT_PROGRESSDATA, req);
curl_easy_setopt(req->curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(req->curl_handle, CURLOPT_TIMEOUT, 30L); // 30秒超时
- curl_easy_setopt(req->curl_handle, CURLOPT_PRIVATE, req);
-
- // 添加 HTTP 状态码和错误重定向设置
- curl_easy_setopt(req->curl_handle, CURLOPT_FAILONERROR, 1L); // 400+ 状态码视为错误
- curl_easy_setopt(req->curl_handle, CURLOPT_FOLLOWLOCATION, 1L); // 跟随重定向
- curl_easy_setopt(req->curl_handle, CURLOPT_MAXREDIRS, 5L); // 最大重定向次数
-
+ curl_easy_setopt(req->curl_handle, CURLOPT_PRIVATE, req); // 关联请求对象
+ curl_easy_setopt(req->curl_handle, CURLOPT_FAILONERROR, 1L); // 将HTTP错误视为失败
+
// 添加到multi handle
- curl_multi_add_handle(curl_multi_handle, req->curl_handle);
-
+ CURLMcode res = curl_multi_add_handle(curl_multi_handle, req->curl_handle);
+ if (res != CURLM_OK) {
+ fprintf(stderr, "curl_multi_add_handle failed: %s\n", curl_multi_strerror(res));
+ curl_easy_cleanup(req->curl_handle);
+ fclose(req->file_ptr);
+ free(req);
+ return NULL;
+ }
+
// 检查超时
int running_handles;
curl_multi_socket_action(curl_multi_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles);
timeout_cb(NULL); // 立即检查超时
-
+
return req;
}
// 清理下载资源
void download_cleanup(download_request* req) {
if (!req) return;
-
+
+ // 关闭文件
if (req->file_ptr) {
- fclose(req->file_ptr);
+ if (fclose(req->file_ptr)) {
+ perror("Failed to close file");
+ }
req->file_ptr = NULL;
}
-
+
+ // 清理CURL资源
if (req->curl_handle) {
curl_multi_remove_handle(curl_multi_handle, req->curl_handle);
curl_easy_cleanup(req->curl_handle);
req->curl_handle = NULL;
}
-
+
+ // 释放请求对象
free(req);
}
uv_loop_t* loop = (uv_loop_t*)userp;
uv_poll_t* poll_handle;
int events = 0;
-
+
if (action == CURL_POLL_IN || action == CURL_POLL_OUT || action == CURL_POLL_INOUT) {
if (!socketp) {
// 新建poll handle
poll_handle = malloc(sizeof(uv_poll_t));
- uv_poll_init_socket(loop, poll_handle, s);
+ if (!poll_handle) {
+ fprintf(stderr, "Failed to allocate poll_handle\n");
+ return -1;
+ }
+
+ if (uv_poll_init_socket(loop, poll_handle, s)) {
+ fprintf(stderr, "uv_poll_init_socket failed\n");
+ free(poll_handle);
+ return -1;
+ }
+
curl_multi_assign(curl_multi_handle, s, poll_handle);
} else {
poll_handle = (uv_poll_t*)socketp;
}
-
+
if (action == CURL_POLL_IN) events = UV_READABLE;
else if (action == CURL_POLL_OUT) events = UV_WRITABLE;
else if (action == CURL_POLL_INOUT) events = UV_READABLE | UV_WRITABLE;
-
- uv_poll_start(poll_handle, events, poll_cb);
+
+ if (uv_poll_start(poll_handle, events, poll_cb)) {
+ fprintf(stderr, "uv_poll_start failed\n");
+ return -1;
+ }
} else if (action == CURL_POLL_REMOVE) {
if (socketp) {
uv_poll_t* poll_handle = (uv_poll_t*)socketp;
curl_multi_assign(curl_multi_handle, s, NULL);
}
}
-
+
return 0;
}
static void destroy_curl_handle(uv_poll_t* poll_handle) {
+ if (!poll_handle) return;
uv_close((uv_handle_t*)poll_handle, (uv_close_cb)free);
}
static void poll_cb(uv_poll_t* handle, int status, int events) {
+ if (status < 0) {
+ fprintf(stderr, "poll_cb error: %s\n", uv_strerror(status));
+ return;
+ }
+
int flags = 0;
if (events & UV_READABLE) flags |= CURL_CSELECT_IN;
if (events & UV_WRITABLE) flags |= CURL_CSELECT_OUT;
-
+
int running_handles;
- curl_multi_socket_action(curl_multi_handle, handle->io_watcher.fd, flags, &running_handles);
+ CURLMcode res = curl_multi_socket_action(curl_multi_handle, handle->io_watcher.fd, flags, &running_handles);
+ if (res != CURLM_OK) {
+ fprintf(stderr, "curl_multi_socket_action failed: %s\n", curl_multi_strerror(res));
+ }
+
timeout_cb(NULL);
}
static void timeout_cb(uv_timer_t* handle) {
int running_handles;
curl_multi_socket_action(curl_multi_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles);
-
+
// 检查完成传输
CURLMsg* msg;
int msgs_left;
CURL* easy = msg->easy_handle;
download_request* req;
CURLcode res = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &req);
-
- // 错误处理
+
+ // 错误检查
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_getinfo error: %s\n", curl_easy_strerror(res));
}
-
+
if (!req) {
fprintf(stderr, "Error: Request object is NULL\n");
curl_multi_remove_handle(curl_multi_handle, easy);
curl_easy_cleanup(easy);
continue;
}
-
+
// 获取 HTTP 状态码
long http_code = 0;
curl_easy_getinfo(easy, CURLINFO_RESPONSE_CODE, &http_code);
-
+
int result = -1; // 默认失败
-
+
// 检查传输错误和 HTTP 状态码
- if (msg->data.result == CURLE_OK && http_code == 200) {
- result = 0; // 成功
+ if (msg->data.result == CURLE_OK && http_code >= 200 && http_code < 300) {
+ result = 0; // 成功 (2xx 状态码)
} else {
// 记录错误信息
if (msg->data.result != CURLE_OK) {
fprintf(stderr, "HTTP error: %ld\n", http_code);
}
}
-
- // 如果失败,删除无效文件
- if (result != 0 && req->file_ptr) {
- fclose(req->file_ptr);
- req->file_ptr = NULL;
-
- // 删除无效文件
- if (access(req->output_path, F_OK) == 0) {
- unlink(req->output_path);
- fprintf(stderr, "Deleted invalid file: %s\n", req->output_path);
- }
- }
- // 成功时正常关闭文件
- else if (req->file_ptr) {
- fclose(req->file_ptr);
- req->file_ptr = NULL;
- }
-
+
// 调用完成回调
if (req->complete_cb) {
req->complete_cb(result, req->userdata);
}
-
- // 清理资源
- curl_multi_remove_handle(curl_multi_handle, easy);
- curl_easy_cleanup(easy);
- free(req);
+
+ // 注意:不要在这里清理 req,由 complete_cb 处理
}
}
-
+
// 设置下次超时检查
long timeout_ms;
curl_multi_timeout(curl_multi_handle, &timeout_ms);
- if (timeout_ms < 0) timeout_ms = 100;
-
+ if (timeout_ms < 0) timeout_ms = 100; // 默认100ms
+
uv_timer_start(&timeout, timeout_cb, timeout_ms, 0);
}
static int progress_callback(void* clientp, double dltotal, double dlnow, double ultotal, double ulnow) {
download_request* req = (download_request*)clientp;
-
+
+ if (!req) return -1;
+
// 更新进度
if (dltotal > 0) {
double percentage = (dlnow / dltotal) * 100.0;
if (req->progress_cb) {
req->progress_cb(percentage, req->userdata);
}
-
+
// 更新内部状态
req->total_size = (int64_t)dltotal;
req->downloaded = (int64_t)dlnow;
}
-
+
return 0;
}
static size_t write_data(void* ptr, size_t size, size_t nmemb, void* userdata) {
download_request* req = (download_request*)userdata;
+ if (!req || !req->file_ptr) return 0;
+
size_t written = fwrite(ptr, size, nmemb, req->file_ptr);
- return written;
-}
-
-//test
-#include "downloader.h"
-#include <stdio.h>
-
-void progress_cb(double percentage, void* userdata) {
- printf("下载进度: %.2f%%\n", percentage);
-}
-
-void complete_cb(int status, void* userdata) {
- if (status == 0) {
- printf("下载成功!\n");
- } else {
- printf("下载失败!\n");
+ if (written < nmemb) {
+ perror("fwrite error");
}
+static int64_t total = 0;
+total += size*nmemb;
+printf("写入数据块: %zu 字节, 累计: %ld\n", size*nmemb, total );
+ return written;
}
-int download_test( void )
+//--------------------------------------------------------------------------------------------------------
+int http_download( char * url, char *save_path, progress_cb_t progress_cb, complete_cb_t complete_cb )
{
+ progress_cb_t p_cb;
+ complete_cb_t c_cb;
// 初始化下载器
download_init(uv_default_loop());
+ p_cb = progress_cb;
+ c_cb = complete_cb;
+
+ if( !p_cb ) p_cb = progress_cb;
+ if( !c_cb ) c_cb = complete_cb;
+
// 开始下载
download_file(
- uv_default_loop(),
- "http://kyz.pub/download/test_100M.bin",
- "/tmp/firmware.bin",
- progress_cb,
- complete_cb,
- NULL
- );
+ uv_default_loop(),
+ url,
+ save_path,
+ p_cb,
+ c_cb,
+ NULL
+ );
return 0;
}
+
+int download_test( void )
+{
+// http_download( "http://kyz.pub/download/test.bin", "/tmp/firmware.bin", progress_cb, complete_cb );
+ return 0;
+}
+
uv_timer_start( &ota_timer, ota_timer_cb, 2000, 0);
}
+
+//---------------------------
+#include <stdint.h>
+
+#define HEADER_SIZE 512
+#define MAGIC_NUMBER 0x4F544121 // "OTA!" in hex
+
+#pragma pack(push, 1)
+typedef struct {
+ uint32_t magic; // 0x4F544121 ("OTA!")
+ char version[32]; // Version string (null-terminated)
+ uint64_t file_size; // Size of actual application
+ uint32_t crc32; // CRC32 of application data
+ uint8_t reserved[464]; // Reserved area
+} FirmwareHeader;
+#pragma pack(pop)
+
+// 验证固件文件
+int validate_firmware(const char *file_path);
+
+// 提取应用程序
+int extract_application(const char *input_path, const char *output_path);
+
+//---------------------------
+#include <zlib.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+// 验证固件文件
+int validate_firmware(const char *file_path)
+{
+
+char cmd[256];
+sprintf( cmd, "cp %s /tmp/app.bin", file_path );
+system( cmd );
+
+ FILE *fp = fopen(file_path, "rb");
+ if (!fp) {
+ perror("fopen");
+ return -1;
+ }
+
+ // 读取文件头
+ FirmwareHeader header;
+ size_t read = fread(&header, 1, sizeof(header), fp);
+ if (read != sizeof(header)) {
+ if (ferror(fp)) {
+ perror("Error reading header");
+ } else {
+ fprintf(stderr, "Incomplete header read: %zu/%zu bytes\n",
+ read, sizeof(header));
+ }
+ fclose(fp);
+ return -1;
+ }
+
+ // 验证魔数
+ if (header.magic != MAGIC_NUMBER) {
+ fprintf(stderr, "Invalid magic number: 0x%08X (expected 0x%08X)\n",
+ header.magic, MAGIC_NUMBER);
+ fclose(fp);
+ return -1;
+ }
+
+ // 获取文件总大小
+ fseek(fp, 0, SEEK_END);
+ long total_size = ftell(fp);
+ fseek(fp, sizeof(header), SEEK_SET); // 回到数据开始位置
+
+ // 验证文件大小
+ if (total_size < HEADER_SIZE) {
+ fprintf(stderr, "File too small: %ld bytes (min %d)\n", total_size, HEADER_SIZE);
+ fclose(fp);
+ return -1;
+ }
+
+ if (total_size != (long)(HEADER_SIZE + header.file_size)) {
+ fprintf(stderr, "Size mismatch: header claims %lu, file has %ld\n",
+ HEADER_SIZE + header.file_size, total_size);
+ fclose(fp);
+ return -1;
+ }
+
+ // 读取应用程序数据
+ uint8_t *file_data = malloc(header.file_size);
+ if (!file_data) {
+ perror("malloc");
+ fclose(fp);
+ return -1;
+ }
+
+ read = fread(file_data, 1, header.file_size, fp);
+ if (read != header.file_size) {
+ fprintf(stderr, "Incomplete data read: %zu/%lu bytes\n",
+ read, (unsigned long)header.file_size);
+ free(file_data);
+ fclose(fp);
+ return -1;
+ }
+ fclose(fp);
+
+ // 计算CRC32
+ uint32_t calculated_crc = crc32(0L, Z_NULL, 0);
+ calculated_crc = crc32(calculated_crc, file_data, header.file_size);
+
+ // 验证CRC32
+ if (calculated_crc != header.crc32) {
+ fprintf(stderr, "CRC32 mismatch: expected 0x%08X, calculated 0x%08X\n",
+ header.crc32, calculated_crc);
+ free(file_data);
+ return -1;
+ }
+
+ printf("Firmware validation successful\n");
+ printf("Version: %s\n", header.version);
+ printf("Size: %lu bytes\n", (unsigned long)header.file_size);
+ printf("CRC32: 0x%08X\n", header.crc32);
+
+ free(file_data);
+ return 0;
+}
+
+// 提取应用程序
+int extract_application(const char *input_path, const char *output_path) {
+ FILE *in_fp = fopen(input_path, "rb");
+ if (!in_fp) {
+ perror("fopen input");
+ return -1;
+ }
+
+ // 跳过文件头
+ if (fseek(in_fp, HEADER_SIZE, SEEK_SET)) {
+ perror("fseek");
+ fclose(in_fp);
+ return -1;
+ }
+
+ FILE *out_fp = fopen(output_path, "wb");
+ if (!out_fp) {
+ fclose(in_fp);
+ perror("fopen output");
+ return -1;
+ }
+
+ // 复制内容
+ uint8_t buffer[4096];
+ size_t bytes_read;
+ while ((bytes_read = fread(buffer, 1, sizeof(buffer), in_fp))) {
+ size_t written = fwrite(buffer, 1, bytes_read, out_fp);
+ if (written != bytes_read) {
+ perror("fwrite");
+ fclose(in_fp);
+ fclose(out_fp);
+ return -1;
+ }
+ }
+
+ if (ferror(in_fp)) {
+ perror("fread");
+ fclose(in_fp);
+ fclose(out_fp);
+ return -1;
+ }
+
+ fclose(in_fp);
+
+ if (fclose(out_fp)) {
+ perror("fclose output");
+ return -1;
+ }
+
+ // 设置可执行权限
+ if (chmod(output_path, 0755)) {
+ perror("chmod");
+ return -1;
+ }
+
+ printf("Application extracted to %s\n", output_path);
+ return 0;
+}
+
+
+//--------------------------
+#include "downloader.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <uv.h>
+
+// 全局变量保存程序参数
+char** saved_argv;
+int saved_argc;
+
+// 下载进度回调
+void download_progress_cb(double percentage, void* userdata) {
+ printf("下载进度: %.2f%%\n", percentage);
+}
+
+// 下载完成回调
+void download_complete_cb(int status, void* userdata) {
+ ota_context* ctx = (ota_context*)userdata;
+
+ if (!ctx) {
+ fprintf(stderr, "错误: 完成回调中缺少上下文\n");
+ return;
+ }
+
+ printf("下载完成回调: ctx:%p, 状态:%d, 文件:%s\n",
+ (void*)ctx, status, ctx->temp_path);
+
+ if (status == 0) {
+ printf("下载成功,开始验证和安装...\n");
+
+ if( ctx->req->file_ptr )
+ fflush( ctx->req->file_ptr);
+
+ // 验证固件
+ if (validate_firmware(ctx->temp_path)) {
+ fprintf(stderr, "固件验证失败\n");
+ unlink(ctx->temp_path);
+ free(ctx);
+ return;
+ }
+
+ printf("固件验证成功,开始安装...\n");
+
+ sleep(3);
+ lcd_write_ota_info( 2 );
+
+ const char* target_path = "/app/alarmmonitor";
+ const char* backup_path = "/app/alarmmonitor.bak";
+
+ // 备份当前版本
+ if (rename(target_path, backup_path)) {
+ perror("备份失败");
+ unlink(ctx->temp_path);
+ free(ctx);
+ return;
+ }
+
+ // 提取应用程序
+ if (extract_application(ctx->temp_path, target_path)) {
+ fprintf(stderr, "提取失败,恢复备份\n");
+ rename(backup_path, target_path);
+ unlink(ctx->temp_path);
+ free(ctx);
+ return;
+ }
+
+ // 清理
+ unlink(ctx->temp_path);
+ unlink(backup_path);
+
+ printf("固件升级成功,重启应用程序\n");
+ sleep(3);
+ lcd_write_ota_info( 0 );
+
+ // 重启应用程序
+ execv(target_path, ctx->saved_argv);
+ perror("execv 失败");
+ exit(EXIT_FAILURE);
+ } else {
+ fprintf(stderr, "下载失败,清理临时文件\n");
+
+ // 删除无效文件
+ if (access(ctx->temp_path, F_OK) == 0) {
+ if (unlink(ctx->temp_path)) {
+ perror("删除临时文件失败");
+ } else {
+ printf("已删除无效文件: %s\n", ctx->temp_path);
+ }
+ }
+ }
+
+ // 清理上下文
+ free(ctx);
+
+ sleep(3);
+ lcd_write_ota_info( 0 );
+}
+
+
+int app_update( char *url )
+{
+ // 初始化下载器
+ download_init(uv_default_loop());
+
+ // 创建临时文件路径 (使用PID确保唯一性)
+ char temp_path[256];
+ snprintf(temp_path, sizeof(temp_path), "/tmp/firmware_%d.bin", getpid());
+
+ // 创建OTA上下文
+ ota_context* ctx = calloc(1, sizeof(ota_context));
+ if (!ctx) {
+ fprintf(stderr, "分配OTA上下文失败\n");
+ return EXIT_FAILURE;
+ }
+
+ snprintf(ctx->temp_path, sizeof(ctx->temp_path)-1, "/tmp/firmware_%d.bin", getpid());
+
+ printf("开始下载: %s -> %s\n", url, temp_path);
+
+ // 开始下载
+ lcd_write_ota_info( 1 );
+ download_request* req = download_file(
+ uv_default_loop(),
+ url,
+ temp_path,
+ download_progress_cb,
+ download_complete_cb,
+ ctx
+ );
+ ctx->req = req;
+
+ if (!req) {
+ fprintf(stderr, "启动下载失败\n");
+ free(ctx);
+ return EXIT_FAILURE;
+ }
+
+
+
+ return EXIT_SUCCESS;
+}
+
+int ota_start( char * http_url )
+{
+ if( strstr( http_url, "rfjb_app" )){
+ app_update( http_url);
+ return 0;
+ }
+ char cmd[256];
+ sprintf( cmd, "echo %s > /userdata/ota_req.txt", http_url );
+ system( cmd );
+ ota_prompt_start();
+ return 0;
+}