diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md index dcf3640..beadc36 100644 --- a/docs/features/feature-catalog.md +++ b/docs/features/feature-catalog.md @@ -36,6 +36,7 @@ Every feature — user-facing or significant internal mechanism — is listed he | F-024 | V1 playback segment_duration fix (single-segment mode) | v2.0.4 | Stable | | F-025 | V2 playback command namespace (`playback.play` / `playback.stop`) | v2.0.4 | Stable | | F-026 | V2 playback `mode` field (`single` / `timed` / `interval` / `infinite`) | v2.0.4 | Stable | +| F-027 | FileManager HTTPS removed — melody downloads over plain HTTP only | v2.0.4 | Stable | --- @@ -290,6 +291,22 @@ Subsystem: `src/Player/Player.cpp:setMelodyAttributes()` --- +### F-027 — FileManager HTTPS removed — melody downloads over plain HTTP only + +`FileManager::downloadFile` no longer supports HTTPS URLs. Any URL starting with `https://` is rejected immediately with an error log. + +**Why:** The ESP32's mbedTLS context requires ~40 KB of contiguous heap for the TLS handshake. After the device has been running for a while, heap fragmentation makes this allocation unreliable, causing intermittent download failures. Melody `.bsm` files contain only note sequences and carry no credentials, so plain HTTP is acceptable for this use case. + +**What was removed:** `WiFiClientSecure`, the SSL heap guard (`largestBlock < 40000` check), `esp_task_wdt_delete/add` calls around the GET, and all `secureClient` cleanup paths. The `esp_task_wdt` include was also dropped from `FileManager.cpp` and `WiFiClientSecure.h` from `FileManager.hpp`. + +**Also fixed in this change:** `ensureDirectoryExists` now strips trailing slashes instead of appending one — `SD.exists()` returns false for directories when a trailing slash is present. + +Melody files must be served via plain HTTP. The Firebase Storage URLs (currently used) must be proxied or replaced with an HTTP endpoint before downloads will work. + +Subsystem: `src/FileManager/FileManager.cpp`, `src/FileManager/FileManager.hpp` + +--- + ### F-023 — Telemetry bell max load default raised to 500 `bellMaxLoad[i]` initialised to `500` (was `200`). This is the denominator used to calculate bell load percentage in telemetry reports. The old value caused false "overload" warnings on normal use patterns. diff --git a/src/FileManager/FileManager.cpp b/src/FileManager/FileManager.cpp index a8fb0be..77d23d2 100644 --- a/src/FileManager/FileManager.cpp +++ b/src/FileManager/FileManager.cpp @@ -1,5 +1,4 @@ #include "FileManager.hpp" -#include #define TAG "FileManager" #include "../BuiltInMelodies/BuiltInMelodies.hpp" @@ -50,68 +49,44 @@ bool FileManager::ensureDirectoryExists(const String& dirPath) { return false; } - // Ensure the directory ends with '/' + // Strip trailing slash — SD.exists() returns false for directories when a + // trailing slash is present, even if the directory exists. String normalizedPath = dirPath; - if (!normalizedPath.endsWith("/")) { - normalizedPath += "/"; + while (normalizedPath.endsWith("/")) { + normalizedPath.remove(normalizedPath.length() - 1); } - // Check if directory already exists if (SD.exists(normalizedPath.c_str())) { - return true; // Directory already exists, success + return true; } - // Create directory if it doesn't exist return SD.mkdir(normalizedPath.c_str()); } bool FileManager::downloadFile(const String& url, const String& directory, const String& filename) { LOG_INFO(TAG, "Starting download from: %s", url.c_str()); - // Check if URL is HTTPS - bool isHttps = url.startsWith("https://"); - - HTTPClient http; - WiFiClientSecure* secureClient = nullptr; - - // Configure HTTP client based on protocol - if (isHttps) { - size_t largestBlock = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); - LOG_DEBUG(TAG, "Largest free heap block before SSL alloc: %u bytes", largestBlock); - if (largestBlock < 40000) { - LOG_ERROR(TAG, "Insufficient contiguous heap for SSL context (%u bytes free, need ~40KB)", largestBlock); - return false; - } - secureClient = new WiFiClientSecure(); - secureClient->setInsecure(); // Skip certificate validation for Firebase - secureClient->setTimeout(15); // 15 second timeout for TLS operations - http.begin(*secureClient, url); - LOG_DEBUG(TAG, "Using HTTPS with secure client"); - } else { - http.begin(url); - LOG_DEBUG(TAG, "Using HTTP"); + if (url.startsWith("https://")) { + LOG_ERROR(TAG, "HTTPS URLs are not supported — serve melody files over HTTP"); + return false; } - http.setTimeout(30000); // 30 second timeout for large files - http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); // Follow redirects automatically + HTTPClient http; + http.begin(url); + http.setTimeout(30000); + http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); - // Remove this task from the WDT while the TLS handshake blocks. - // The handshake can take several seconds and would otherwise starve async_tcp. - esp_task_wdt_delete(NULL); LOG_DEBUG(TAG, "Sending HTTP GET request..."); int httpCode = http.GET(); - esp_task_wdt_add(NULL); if (httpCode != HTTP_CODE_OK && httpCode != HTTP_CODE_MOVED_PERMANENTLY && httpCode != HTTP_CODE_FOUND) { LOG_ERROR(TAG, "HTTP GET failed, code: %d, error: %s", httpCode, http.errorToString(httpCode).c_str()); http.end(); - if (secureClient) delete secureClient; return false; } if (!initializeSD()) { http.end(); - if (secureClient) delete secureClient; return false; } @@ -119,7 +94,6 @@ bool FileManager::downloadFile(const String& url, const String& directory, const if (!ensureDirectoryExists(directory)) { LOG_ERROR(TAG, "Failed to create directory: %s", directory.c_str()); http.end(); - if (secureClient) delete secureClient; return false; } @@ -132,7 +106,6 @@ bool FileManager::downloadFile(const String& url, const String& directory, const if (!file) { LOG_ERROR(TAG, "Failed to open file for writing: %s", fullPath.c_str()); http.end(); - if (secureClient) delete secureClient; return false; } @@ -189,7 +162,6 @@ bool FileManager::downloadFile(const String& url, const String& directory, const file.close(); http.end(); - if (secureClient) delete secureClient; LOG_INFO(TAG, "Download complete, file saved to: %s (%u bytes)", fullPath.c_str(), totalBytes); return true; } diff --git a/src/FileManager/FileManager.hpp b/src/FileManager/FileManager.hpp index ab0339f..9f6a0e1 100644 --- a/src/FileManager/FileManager.hpp +++ b/src/FileManager/FileManager.hpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include "../Logging/Logging.hpp" #include "../ConfigManager/ConfigManager.hpp" diff --git a/src/FileManager/README.md b/src/FileManager/README.md index 47fca4e..d06351b 100644 --- a/src/FileManager/README.md +++ b/src/FileManager/README.md @@ -11,7 +11,7 @@ FileManager is the single access point for all SD card I/O in Vesper. It abstrac | Method | Signature | Description | |---|---|---| | Constructor | `FileManager(ConfigManager* config)` | Stores the ConfigManager pointer; does not initialize the SD card. | -| `downloadFile` | `bool downloadFile(const String& url, const String& directory, const String& filename)` | Downloads a file over HTTP or HTTPS (TLS, no cert validation) and writes it to `directory/filename` on the SD card. Creates the target directory if it does not exist. | +| `downloadFile` | `bool downloadFile(const String& url, const String& directory, const String& filename)` | Downloads a file over HTTP and writes it to `directory/filename` on the SD card. Creates the target directory if it does not exist. HTTPS URLs are rejected with an error — melody files must be served over plain HTTP. | | `addMelody` | `bool addMelody(JsonVariant doc)` | High-level helper: extracts `download_url` and `melodys_uid` from a JSON object and calls `downloadFile` into `/melodies/`. Skips the download silently if the UID matches a built-in melody. | | `listFilesAsJson` | `String listFilesAsJson(const char* dirPath)` | Returns a JSON string `{"files": [...]}` listing all non-directory entries in `dirPath`. Returns `"{}"` on any error. | | `fileExists` | `bool fileExists(const String& filePath)` | Returns `true` if the file can be opened on the SD card. | @@ -58,9 +58,8 @@ The `setFileManagerReference` call on `CommunicationRouter` is particularly impo |---|---|---| | `ConfigManager` | Subsystem pointer | Reads `hardwareConfig.sdChipSelect` to get the CS pin for `SD.begin()`. | | Arduino `SD` library | Platform library | All card I/O. | -| `HTTPClient`, `WiFiClient`, `WiFiClientSecure` | Platform libraries | HTTP/HTTPS file downloads. | +| `HTTPClient`, `WiFiClient` | Platform libraries | HTTP file downloads. | | `ArduinoJson` | Library | JSON serialization and deserialization. | -| `esp_task_wdt` | ESP-IDF | Watchdog disable/re-enable around blocking HTTPS operations in `downloadFile`. | | `BuiltInMelodies` | Subsystem | Consulted by `addMelody` to skip unnecessary downloads. | | `Logging` | Subsystem | `LOG_*` macros throughout. | @@ -72,9 +71,7 @@ The `setFileManagerReference` call on `CommunicationRouter` is particularly impo **No internal mutex.** FileManager does not acquire `SDCardMutex` internally. The ESP32 `SD` library is not thread-safe. If FileManager methods are called from multiple FreeRTOS tasks concurrently, callers must coordinate via `SDCardMutex` / `SDCardLock` themselves. Currently `downloadFile` (called from the CommandBus task via `FileHandler`) and `appendLine` (called from the Logging callback, which fires from whatever task emits the log) are the most likely concurrent paths — audit this before adding new callers from additional tasks. -**Watchdog is temporarily disabled during downloads.** `downloadFile` calls `esp_task_wdt_delete(NULL)` before the HTTP GET and `esp_task_wdt_add(NULL)` after. This removes watchdog coverage for the calling task for the duration of the TLS handshake (can be several seconds). Avoid calling `downloadFile` from tasks where watchdog removal is inappropriate. - -**HTTPS uses `setInsecure()`.** TLS certificate validation is skipped. This is intentional for compatibility with Firebase/CDN redirect chains, but means downloads are not authenticated — file content is trusted implicitly. +**Melody files must be served over plain HTTP.** HTTPS is not supported for downloads — the ESP32's mbedTLS context requires ~40KB of contiguous heap for the TLS handshake, which is not reliably available after the device has been running for a while (heap fragmentation). Melody `.bsm` files contain only note sequences and carry no credentials, so plain HTTP is acceptable. The manifest or any sensitive API calls can still use HTTPS via other subsystems. **`SD.begin()` called on every operation.** Because `initializeSD()` runs at the top of every method, a card inserted after boot is detected automatically on the next call. Calling `SD.begin()` on an already-mounted card is harmless but adds ~1 ms overhead per call.