#include "ota/ota_service.h" #include "diagnostics/trace_context.h" #include "ota/ota_endpoint.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP #define CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP 0 #endif namespace borla { namespace { // Wall-clock milliseconds, or 0 while the clock still reads 1970 because NTP // has not landed yet — which is the normal case for the boot-time OTA check. int64_t EpochMs() { struct timeval now {}; if (gettimeofday(&now, nullptr) != 0 || now.tv_sec < 1700000000) { return 0; } return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; } constexpr const char* kTag = "OtaService2"; constexpr uint32_t kCheckFailedError = 3401; constexpr uint32_t kManifestInvalidError = 3402; constexpr uint32_t kPartitionError = 3403; constexpr uint32_t kDownloadError = 3404; constexpr uint32_t kSizeMismatchError = 3405; constexpr uint32_t kShaMismatchError = 3406; constexpr uint32_t kImageValidationError = 3407; constexpr size_t kMaximumCheckResponseBytes = 4096; constexpr uint32_t kUpgradeAnnouncementDelayMs = 8000; constexpr uint32_t kAnnouncementChannelWaitMs = 10000; constexpr uint32_t kAnnouncementPollMs = 500; // Kept verbatim from the legacy firmware so the server-side TTS cache and the // parent-facing copy do not change during the migration. constexpr const char* kAutoUpgradeText = "当前有最新版本,即将开始升级!请耐心等候"; constexpr const char* kForcedUpgradeText = "目前有大版本需要升级,否则设备将不可用,即将升级请耐心等候!"; constexpr const char* kOptionalUpgradeText = "当前设备有最新版本,是否进行升级?"; constexpr const char* kAutoUpgradeUnavailableText = "检测到新版本,升级文件准备中,请稍后重试"; constexpr const char* kForcedUpgradeUnavailableText = "检测到需要升级的版本,升级文件准备中,请稍后重试"; // NOTE: the legacy firmware also announced "升级成功,正在重启" after flashing. // firmware2 cannot: kUpgradeRequested deterministically closes the realtime // channel before the download starts, so there is no socket left to speak on. // The server learns the outcome from the post-reboot hello version instead. struct ResponseBuffer { std::array data{}; size_t size = 0; bool overflow = false; }; esp_err_t CaptureResponse(esp_http_client_event_t* event) { if (event == nullptr || event->user_data == nullptr) { return ESP_OK; } if (event->event_id != HTTP_EVENT_ON_DATA || event->data == nullptr || event->data_len <= 0) { return ESP_OK; } auto* response = static_cast(event->user_data); const size_t incoming = static_cast(event->data_len); if (response->size + incoming >= response->data.size()) { response->overflow = true; return ESP_FAIL; } std::memcpy( response->data.data() + response->size, event->data, incoming); response->size += incoming; response->data[response->size] = '\0'; return ESP_OK; } bool SecureUrlAllowed(const char* url) { if (url == nullptr) { return false; } if (std::strncmp(url, "https://", 8) == 0) { return true; } #if CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP return std::strncmp(url, "http://", 7) == 0; #else return false; #endif } esp_http_client_handle_t CreateHttpClient( const char* url, http_event_handle_cb event_handler = nullptr, void* user_data = nullptr) { if (!SecureUrlAllowed(url)) { return nullptr; } esp_http_client_config_t config{}; config.url = url; config.event_handler = event_handler; config.user_data = user_data; config.timeout_ms = 30000; config.buffer_size = 4096; config.buffer_size_tx = 1024; if (std::strncmp(url, "https://", 8) == 0) { config.crt_bundle_attach = esp_crt_bundle_attach; } return esp_http_client_init(&config); } } // namespace bool OtaService::Initialize( const DeviceIdentity& identity, IEventPublisher& publisher) { identity_ = identity; publisher_ = &publisher; if (task_ != nullptr) { return true; } request_ = xSemaphoreCreateBinaryStatic(&request_storage_); if (request_ == nullptr) { ESP_LOGE(kTag, "OTA request semaphore creation failed"); return false; } task_ = xTaskCreateStatic( &OtaService::TaskEntry, "ota_service2", task_stack_.size(), this, 5, task_stack_.data(), &task_control_); if (task_ == nullptr) { ESP_LOGE(kTag, "OTA worker creation failed"); return false; } return true; } void OtaService::OnApplicationEvent( const AppEvent& event, const RuntimeState& state) { // 记录实时通道是否已握手完成:RunOnce 用它把版本检查的 TLS 错开 // (原因见 kCheckStaggerMaxMs 的注释)。 realtime_open_.store(state.realtime == RealtimeState::kOpen); if (event.type != AppEventType::kNetworkConnected || task_ == nullptr || check_started_.exchange(true)) { return; } if (busy_.exchange(true)) { check_started_.store(false); return; } task_mode_.store(TaskMode::kCheck); xSemaphoreGive(request_); } void OtaService::StartUpgrade(uint32_t request_id) { request_id_.store(request_id); upgrade_requested_.store(true); if (task_ == nullptr) { PublishFailure(kDownloadError); return; } if (busy_.exchange(true)) { // A check-mode run is already waiting for this flag and will perform // the upgrade itself. return; } task_mode_.store(TaskMode::kUpgrade); xSemaphoreGive(request_); } bool OtaService::ConfirmCurrentImage() { const esp_partition_t* running = esp_ota_get_running_partition(); esp_ota_img_states_t state = ESP_OTA_IMG_UNDEFINED; const esp_err_t result = esp_ota_get_state_partition(running, &state); if (result == ESP_ERR_NOT_SUPPORTED || state != ESP_OTA_IMG_PENDING_VERIFY) { return result == ESP_OK || result == ESP_ERR_NOT_SUPPORTED; } const esp_err_t mark_result = esp_ota_mark_app_valid_cancel_rollback(); ESP_LOGI(kTag, "current image confirmation: %s", esp_err_to_name(mark_result)); return mark_result == ESP_OK; } void OtaService::RejectCurrentImageAndRollback() { const esp_partition_t* running = esp_ota_get_running_partition(); esp_ota_img_states_t state = ESP_OTA_IMG_UNDEFINED; if (esp_ota_get_state_partition(running, &state) == ESP_OK && state == ESP_OTA_IMG_PENDING_VERIFY) { ESP_LOGE(kTag, "boot self-test failed; rolling back image"); esp_ota_mark_app_invalid_rollback_and_reboot(); } } OtaDiagnostics OtaService::GetDiagnostics() const { portENTER_CRITICAL(&lock_); const OtaDiagnostics result = diagnostics_; portEXIT_CRITICAL(&lock_); return result; } void OtaService::TaskEntry(void* context) { static_cast(context)->Run(); } [[noreturn]] void OtaService::Run() { for (;;) { if (xSemaphoreTake(request_, portMAX_DELAY) != pdTRUE) { continue; } RunOnce(); busy_.store(false); } } void OtaService::RunOnce() { const TaskMode mode = task_mode_.load(); if (mode == TaskMode::kCheck) { TraceContext::RefreshTrace("ota"); // 先让实时通道把 TLS 握完(两条 TLS 并发会让 WiFi 拿不到内部 DMA // 缓冲,见 kCheckStaggerMaxMs)。通道已经打开时一次都不等。 uint32_t staggered_ms = 0; while (!realtime_open_.load() && staggered_ms < kCheckStaggerMaxMs) { vTaskDelay(pdMS_TO_TICKS(kCheckStaggerStepMs)); staggered_ms += kCheckStaggerStepMs; } if (staggered_ms > 0) { ESP_LOGI(kTag, "staggered version check waited=%ums realtime_open=%d", static_cast(staggered_ms), realtime_open_.load() ? 1 : 0); } bool checked = false; for (uint32_t attempt = 0; attempt < 3 && !checked; ++attempt) { portENTER_CRITICAL(&lock_); diagnostics_.checking = true; diagnostics_.check_attempts++; portEXIT_CRITICAL(&lock_); checked = CheckVersion(); if (!checked && attempt < 2) { vTaskDelay(pdMS_TO_TICKS(10000)); } } portENTER_CRITICAL(&lock_); diagnostics_.checking = false; portEXIT_CRITICAL(&lock_); OtaManifest manifest; portENTER_CRITICAL(&lock_); manifest = manifest_; portEXIT_CRITICAL(&lock_); if (checked && manifest.policy == OtaUpgradePolicy::kOptional) { // Advisory only: tell the parent a version exists, install nothing. AnnounceUpgrade(manifest); } if (checked && manifest.ShouldStartAutomatically()) { // Announce first. kUpgradeRequested deterministically closes the // realtime channel, so anything said after it would never reach // the server. AnnounceUpgrade(manifest); publisher_->Publish(AppEvent::Make( AppEventType::kUpgradeRequested, request_id_.load())); for (uint32_t waited = 0; !upgrade_requested_.load() && waited < 5000; waited += 50) { vTaskDelay(pdMS_TO_TICKS(50)); } if (upgrade_requested_.load()) { PerformUpgrade(); } else { PublishFailure(kDownloadError); } } } else { PerformUpgrade(); } } bool OtaService::CheckVersion() { // 碎片防护:内部RAM最大连续块不足,直接跳过版本检查,避免触发socket分配失败 const size_t largest_int_ram = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); ESP_LOGI(kTag, "CheckVersion largest_int_ram=%zu", largest_int_ram); if (largest_int_ram < 12 * 1024U) { ESP_LOGW(kTag, "internal ram fragmented, skip ota version check"); PublishFailure(kCheckFailedError); return false; } ResponseBuffer response; esp_http_client_handle_t client = CreateHttpClient( CONFIG_BORLA_OTA_URL, &CaptureResponse, &response); if (client == nullptr) { PublishFailure(kCheckFailedError); return false; } std::array body{}; const int body_size = std::snprintf( body.data(), body.size(), "{\"mac_address\":\"%s\",\"board_type\":\"%s\"," "\"app_version\":\"%s\",\"idf_version\":\"%s\"," "\"chip_model\":\"%s\",\"free_heap\":%lu}", identity_.mac, identity_.board, identity_.app_version, esp_get_idf_version(), identity_.chip_model, static_cast( heap_caps_get_free_size(MALLOC_CAP_8BIT))); if (body_size <= 0 || static_cast(body_size) >= body.size()) { esp_http_client_cleanup(client); PublishFailure(kCheckFailedError); return false; } esp_http_client_set_method(client, HTTP_METHOD_POST); esp_http_client_set_header( client, "Content-Type", "application/json"); esp_http_client_set_header(client, "Device-Id", identity_.mac); // Correlation headers: server and backend grep the same ids to stitch the // device-side OTA call into their own request logs. const char* request_id = TraceContext::NewRequestId(); esp_http_client_set_header( client, "X-Borla-Trace-Id", TraceContext::TraceId()); esp_http_client_set_header( client, "X-Borla-Session-Id", TraceContext::SessionId()); esp_http_client_set_header(client, "X-Request-Id", request_id); // http_server.py reads these two to time the call and derive the device's // clock offset. The epoch header is skipped while the wall clock still // reads 1970, since OTA check runs before NTP on a cold boot and a 1970 // stamp would be read as a 56-year skew rather than as "unknown". char send_ms[24]{}; std::snprintf( send_ms, sizeof(send_ms), "%llu", static_cast(esp_timer_get_time() / 1000)); esp_http_client_set_header( client, "X-Borla-Client-Send-Ms", send_ms); const int64_t client_epoch_ms = EpochMs(); if (client_epoch_ms > 0) { char epoch_ms[24]{}; std::snprintf( epoch_ms, sizeof(epoch_ms), "%lld", static_cast(client_epoch_ms)); esp_http_client_set_header( client, "X-Borla-Client-Epoch-Ms", epoch_ms); } ESP_LOGI(kTag, "version check trace=%s request=%s", TraceContext::TraceId(), request_id); esp_http_client_set_post_field( client, body.data(), body_size); const esp_err_t result = esp_http_client_perform(client); const int status = esp_http_client_get_status_code(client); esp_http_client_close(client);//释放内存 esp_http_client_cleanup(client); if (result != ESP_OK || status != 200 || response.overflow || response.size == 0) { ESP_LOGW(kTag, "version check failed result=%s status=%d", esp_err_to_name(result), status); PublishFailure(kCheckFailedError); return false; } OtaManifest parsed; OtaEndpointConfig endpoint; const OtaParseStatus parse_status = parser_.Parse( response.data.data(), response.size, identity_.app_version, CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP, &parsed, &endpoint); const esp_partition_t* target = esp_ota_get_next_update_partition(nullptr); if (parse_status != OtaParseStatus::kOk || (parsed.HasUpdate() && (target == nullptr || parsed.size > target->size))) { portENTER_CRITICAL(&lock_); diagnostics_.last_parse_status = parse_status; portEXIT_CRITICAL(&lock_); PublishFailure(kManifestInvalidError); return false; } portENTER_CRITICAL(&lock_); manifest_ = parsed; diagnostics_.manifest = parsed; diagnostics_.last_parse_status = parse_status; portEXIT_CRITICAL(&lock_); ESP_LOGI(kTag, "version check policy=%s version=%s size=%lu", ToString(parsed.policy), parsed.version.data(), static_cast(parsed.size)); // Endpoint handling is deliberately independent of HasUpdate(): the OTA // response is the only channel that can repoint a fielded device, and it // routinely carries a websocket block with no firmware block at all. ApplyEndpoint(endpoint); return true; } void OtaService::ApplyEndpoint(const OtaEndpointConfig& endpoint) { if (config_store_ == nullptr || !endpoint.HasAny()) { return; } std::array resolved{}; const bool has_url = endpoint.has_url && ResolveRealtimeUrl( endpoint.url.data(), CONFIG_BORLA_OTA_URL, kDefaultRealtimeUrl, resolved.data(), resolved.size()); if (!has_url && !endpoint.has_token) { ESP_LOGW(kTag, "OTA endpoint block unusable; keeping stored value"); return; } if (!config_store_->SaveEndpoint( has_url ? resolved.data() : nullptr, endpoint.has_token ? endpoint.token.data() : nullptr)) { ESP_LOGW(kTag, "OTA endpoint persistence failed"); return; } // Applied on the next Open(): RealtimeProtocol loads its transport config // once at Initialize(), so a changed endpoint takes effect after reboot. ESP_LOGI(kTag, "OTA endpoint stored url=%s", has_url ? resolved.data() : "(unchanged)"); } void OtaService::AnnounceUpgrade(const OtaManifest& manifest) { if (realtime_ == nullptr || !manifest.HasUpdate()) { return; } const bool forced = manifest.policy == OtaUpgradePolicy::kForced; const bool optional = manifest.policy == OtaUpgradePolicy::kOptional; const char* text = nullptr; if (optional) { text = kOptionalUpgradeText; } else if (manifest.url[0] == '\0') { text = forced ? kForcedUpgradeUnavailableText : kAutoUpgradeUnavailableText; } else { text = forced ? kForcedUpgradeText : kAutoUpgradeText; } // The check can finish before the realtime channel has finished opening // (both are triggered by the same kNetworkConnected edge), so give the // channel a bounded grace period rather than dropping the announcement. bool sent = false; for (uint32_t waited = 0; !sent && waited < kAnnouncementChannelWaitMs; waited += kAnnouncementPollMs) { sent = realtime_->SendOtaNotify(text, optional); if (!sent) { vTaskDelay(pdMS_TO_TICKS(kAnnouncementPollMs)); } } if (!sent) { ESP_LOGW(kTag, "upgrade announcement skipped: channel not open"); return; } ESP_LOGI(kTag, "upgrade announcement sent policy=%s", ToString(manifest.policy)); if (optional) { return; } // Give the server time to synthesise and the device time to play the // announcement before the download saturates the link. vTaskDelay(pdMS_TO_TICKS(kUpgradeAnnouncementDelayMs)); } bool OtaService::PerformUpgrade() { portENTER_CRITICAL(&lock_); diagnostics_.upgrading = true; portEXIT_CRITICAL(&lock_); const bool success = DownloadToPartition(); portENTER_CRITICAL(&lock_); diagnostics_.upgrading = false; portEXIT_CRITICAL(&lock_); if (success) { publisher_->Publish(AppEvent::Make( AppEventType::kUpgradeCompleted, request_id_.load())); } return success; } bool OtaService::DownloadToPartition() { OtaManifest manifest; portENTER_CRITICAL(&lock_); manifest = manifest_; diagnostics_.downloaded_bytes = 0; portEXIT_CRITICAL(&lock_); if (!manifest.HasUpdate()) { PublishFailure(kManifestInvalidError); return false; } const esp_partition_t* partition = esp_ota_get_next_update_partition(nullptr); if (partition == nullptr || manifest.size > partition->size) { PublishFailure(kPartitionError); return false; } // 碎片防护 const size_t largest_int_ram = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); ESP_LOGI(kTag, "DownloadToPartition largest_int_ram=%zu", largest_int_ram); if (largest_int_ram < 12 * 1024U) { ESP_LOGW(kTag, "internal ram fragmented, abort download"); PublishFailure(kDownloadError); return false; }///// esp_http_client_handle_t client = CreateHttpClient(manifest.url.data()); if (client == nullptr) { PublishFailure(kDownloadError); return false; } esp_http_client_set_method(client, HTTP_METHOD_GET); esp_err_t result = esp_http_client_open(client, 0); if (result != ESP_OK) { esp_http_client_cleanup(client); PublishFailure(kDownloadError); return false; } const int64_t content_length = esp_http_client_fetch_headers(client); const int status = esp_http_client_get_status_code(client); if (status != 200 || (content_length > 0 && static_cast(content_length) != manifest.size)) { esp_http_client_close(client); esp_http_client_cleanup(client); PublishFailure( status == 200 ? kSizeMismatchError : kDownloadError); return false; } esp_ota_handle_t ota_handle = 0; result = esp_ota_begin( partition, manifest.size, &ota_handle); if (result != ESP_OK) { esp_http_client_close(client); esp_http_client_cleanup(client); PublishFailure(kPartitionError); return false; } mbedtls_sha256_context sha; mbedtls_sha256_init(&sha); mbedtls_sha256_starts(&sha, 0); std::array buffer{}; uint32_t total = 0; bool valid = true; while (total < manifest.size) { const int read = esp_http_client_read( client, reinterpret_cast(buffer.data()), std::min( buffer.size(), manifest.size - total)); if (read <= 0) { valid = false; break; } if (esp_ota_write( ota_handle, buffer.data(), read) != ESP_OK) { valid = false; break; } mbedtls_sha256_update( &sha, buffer.data(), static_cast(read)); total += static_cast(read); portENTER_CRITICAL(&lock_); diagnostics_.downloaded_bytes = total; portEXIT_CRITICAL(&lock_); } esp_http_client_close(client); esp_http_client_cleanup(client); uint8_t actual_digest[32]{}; uint8_t expected_digest[32]{}; mbedtls_sha256_finish(&sha, actual_digest); mbedtls_sha256_free(&sha); if (!valid || total != manifest.size) { esp_ota_abort(ota_handle); PublishFailure(kSizeMismatchError); return false; } if (!OtaResponseParser::DecodeSha256( manifest.sha256.data(), expected_digest) || std::memcmp(actual_digest, expected_digest, 32) != 0) { esp_ota_abort(ota_handle); PublishFailure(kShaMismatchError); return false; } if (esp_ota_end(ota_handle) != ESP_OK || esp_ota_set_boot_partition(partition) != ESP_OK) { PublishFailure(kImageValidationError); return false; } ESP_LOGI(kTag, "OTA image verified version=%s bytes=%lu", manifest.version.data(), static_cast(total)); return true; } void OtaService::PublishFailure(uint32_t error) { portENTER_CRITICAL(&lock_); diagnostics_.last_error = error; portEXIT_CRITICAL(&lock_); if (publisher_ != nullptr) { publisher_->Publish(AppEvent::Make( AppEventType::kUpgradeFailed, error)); } } } // namespace borla