#include "basic_auth.h" #include "read_wlanini.h" #include #include #include #include "esp_timer.h" #include "ClassLogFile.h" #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/semphr.h" #include "freertos/task.h" #include #include #include #define HTTPD_401 "401 UNAUTHORIZED" static const char *TAG = "HTTPAUTH"; typedef struct { const char *username; const char *password; } basic_auth_info_t; basic_auth_info_t basic_auth_info = { NULL, NULL }; // Camera operations share one physical camera. A single worker serializes // long-running camera responses outside the HTTP server task. A short queue // lets a capture wait behind a live-stream request without blocking /info. static QueueHandle_t cameraAsyncRequestQueue = NULL; static SemaphoreHandle_t cameraAsyncRequestSlot = NULL; struct AsyncCameraHttpRequest { httpd_req_t *request; basic_auth_async_handler_t handler; char handlerName[32]; char uri[128]; int64_t startUs; }; static void async_camera_http_request_task(void *argument) { (void)argument; AsyncCameraHttpRequest work = {}; while (cameraAsyncRequestQueue != NULL && xQueueReceive(cameraAsyncRequestQueue, &work, portMAX_DELAY) == pdTRUE) { const esp_err_t result = work.handler(work.request); const int64_t elapsedUs = esp_timer_get_time() - work.startUs; LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Async camera HTTP request: ") + work.handlerName + " " + work.uri + " took " + std::to_string(static_cast(elapsedUs / 1000)) + " ms (result=" + std::to_string(static_cast(result)) + ")"); // Complete the async request on every worker exit path so the HTTP server // can release the socket and accept subsequent requests. httpd_req_async_handler_complete(work.request); if (cameraAsyncRequestSlot != NULL) { xSemaphoreGive(cameraAsyncRequestSlot); } } vTaskDelete(NULL); } esp_err_t dispatch_camera_http_request_async(httpd_req_t *req, basic_auth_async_handler_t handler, const char *handler_name) { if (req == NULL || handler == NULL) { return ESP_ERR_INVALID_ARG; } if (cameraAsyncRequestQueue == NULL || cameraAsyncRequestSlot == NULL || xSemaphoreTake(cameraAsyncRequestSlot, 0) != pdTRUE) { httpd_resp_set_status(req, "503 Service Unavailable"); httpd_resp_sendstr(req, "Camera is busy with another capture or stream"); return ESP_OK; } httpd_req_t *asyncRequest = NULL; const esp_err_t copyResult = httpd_req_async_handler_begin(req, &asyncRequest); if (copyResult != ESP_OK) { xSemaphoreGive(cameraAsyncRequestSlot); httpd_resp_set_status(req, "503 Service Unavailable"); httpd_resp_sendstr(req, "Could not queue camera request"); return ESP_OK; } AsyncCameraHttpRequest work = {}; work.request = asyncRequest; work.handler = handler; strlcpy(work.handlerName, handler_name != NULL ? handler_name : "camera", sizeof(work.handlerName)); strlcpy(work.uri, asyncRequest->uri, sizeof(work.uri)); work.startUs = esp_timer_get_time(); if (xQueueSend(cameraAsyncRequestQueue, &work, 0) != pdTRUE) { // Restore ownership of the socket before returning a busy response. httpd_req_async_handler_complete(asyncRequest); xSemaphoreGive(cameraAsyncRequestSlot); httpd_resp_set_status(req, "503 Service Unavailable"); httpd_resp_sendstr(req, "Camera request queue is full"); } return ESP_OK; } // General bounded worker for responses that may block on socket transmission. // Unlike camera requests, normal asset/image responses may arrive concurrently, // so they are queued instead of rejected while another transfer is active. static QueueHandle_t httpAsyncRequestQueue = NULL; struct AsyncHttpRequest { httpd_req_t *request; basic_auth_async_handler_t handler; char handlerName[32]; char uri[128]; int64_t startUs; }; static void async_http_request_task(void *argument) { (void)argument; AsyncHttpRequest work = {}; while (httpAsyncRequestQueue != NULL && xQueueReceive(httpAsyncRequestQueue, &work, portMAX_DELAY) == pdTRUE) { const esp_err_t result = work.handler(work.request); const int64_t elapsedUs = esp_timer_get_time() - work.startUs; if (elapsedUs >= 100000) { LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Async HTTP response: ") + work.handlerName + " " + work.uri + " took " + std::to_string(static_cast(elapsedUs / 1000)) + " ms (result=" + std::to_string(static_cast(result)) + ")"); } httpd_req_async_handler_complete(work.request); } vTaskDelete(NULL); } esp_err_t dispatch_http_request_async(httpd_req_t *req, basic_auth_async_handler_t handler, const char *handler_name) { if (req == NULL || handler == NULL) { return ESP_ERR_INVALID_ARG; } // Preserve normal serving behaviour if worker initialization failed. if (httpAsyncRequestQueue == NULL) { return handler(req); } httpd_req_t *asyncRequest = NULL; const esp_err_t copyResult = httpd_req_async_handler_begin(req, &asyncRequest); if (copyResult != ESP_OK) { httpd_resp_set_status(req, "503 Service Unavailable"); httpd_resp_sendstr(req, "Could not queue HTTP response"); return ESP_OK; } AsyncHttpRequest work = {}; work.request = asyncRequest; work.handler = handler; strlcpy(work.handlerName, handler_name != NULL ? handler_name : "http", sizeof(work.handlerName)); strlcpy(work.uri, asyncRequest->uri, sizeof(work.uri)); work.startUs = esp_timer_get_time(); if (xQueueSend(httpAsyncRequestQueue, &work, 0) != pdTRUE) { // Queue full: complete the async copy and return an explicit overload // response on the original request rather than blocking the HTTP task. httpd_req_async_handler_complete(asyncRequest); httpd_resp_set_status(req, "503 Service Unavailable"); httpd_resp_sendstr(req, "HTTP response worker is busy"); } return ESP_OK; } // All URI handlers are registered through APPLY_BASIC_AUTH_FILTER. Measuring here // gives us a common duration for every HTTP endpoint, including static HTML/CSS/JS // and image handlers. Time spent waiting in the ESP-IDF server queue is not included. class HttpRequestTiming { public: explicit HttpRequestTiming(httpd_req_t *request) : uri(request->uri), method(request->method == HTTP_GET ? "GET" : request->method == HTTP_POST ? "POST" : request->method == HTTP_PUT ? "PUT" : request->method == HTTP_DELETE ? "DELETE" : "OTHER"), startUs(esp_timer_get_time()) { } ~HttpRequestTiming() { const int64_t elapsedUs = esp_timer_get_time() - startUs; // Catch noticeable handler stalls without logging every normal poll. if (elapsedUs >= 100000) { LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Slow HTTP request: ") + method + " " + uri + " handler time " + std::to_string(static_cast(elapsedUs / 1000)) + " ms"); } } private: std::string uri; const char *method; int64_t startUs; }; void init_basic_auth() { if (!wlan_config.http_username.empty() && !wlan_config.http_password.empty()) { basic_auth_info.username = wlan_config.http_username.c_str(); basic_auth_info.password = wlan_config.http_password.c_str(); } if (cameraAsyncRequestQueue == NULL) { cameraAsyncRequestQueue = xQueueCreate(1, sizeof(AsyncCameraHttpRequest)); cameraAsyncRequestSlot = xSemaphoreCreateBinary(); if (cameraAsyncRequestSlot != NULL) { xSemaphoreGive(cameraAsyncRequestSlot); } if (cameraAsyncRequestQueue == NULL || cameraAsyncRequestSlot == NULL) { if (cameraAsyncRequestQueue != NULL) { vQueueDelete(cameraAsyncRequestQueue); cameraAsyncRequestQueue = NULL; } LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create asynchronous camera request queue/slot"); return; } if (xTaskCreatePinnedToCore(async_camera_http_request_task, "camera_http", 8 * 1024, NULL, tskIDLE_PRIORITY + 3, NULL, 1) != pdPASS) { vQueueDelete(cameraAsyncRequestQueue); cameraAsyncRequestQueue = NULL; vSemaphoreDelete(cameraAsyncRequestSlot); cameraAsyncRequestSlot = NULL; LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to start asynchronous camera request worker"); } } // File and image transfers can block in httpd_resp_send_chunk() when the // client/network is slow. Keep them out of the single HTTP server task. if (httpAsyncRequestQueue == NULL) { httpAsyncRequestQueue = xQueueCreate(4, sizeof(AsyncHttpRequest)); if (httpAsyncRequestQueue == NULL || xTaskCreatePinnedToCore(async_http_request_task, "http_io", 8 * 1024, NULL, tskIDLE_PRIORITY + 3, NULL, 1) != pdPASS) { if (httpAsyncRequestQueue != NULL) { vQueueDelete(httpAsyncRequestQueue); httpAsyncRequestQueue = NULL; } LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to start asynchronous HTTP response worker"); } } } static char *http_auth_basic(const char *username, const char *password) { int out; char *user_info = NULL; char *digest = NULL; size_t n = 0; asprintf(&user_info, "%s:%s", username, password); if (!user_info) { ESP_LOGE(TAG, "No enough memory for user information"); return NULL; } esp_crypto_base64_encode(NULL, 0, &n, (const unsigned char *)user_info, strlen(user_info)); /* 6: The length of the "Basic " string * n: Number of bytes for a base64 encode format * 1: Number of bytes for a reserved which be used to fill zero */ digest = static_cast(calloc(1, 6 + n + 1)); if (digest) { strcpy(digest, "Basic "); esp_crypto_base64_encode((unsigned char *)digest + 6, n, (size_t *)&out, (const unsigned char *)user_info, strlen(user_info)); } free(user_info); return digest; } esp_err_t basic_auth_request_filter(httpd_req_t *req, esp_err_t original_handler(httpd_req_t *)) { HttpRequestTiming requestTiming(req); char *buf = NULL; size_t buf_len = 0; esp_err_t ret = ESP_OK; char unauthorized[] = "You are not authorized to use this website!"; if (basic_auth_info.username == NULL || basic_auth_info.password == NULL) { ret = original_handler(req); } else { buf_len = httpd_req_get_hdr_value_len(req, "Authorization") + 1; if (buf_len > 1) { buf = static_cast(calloc(1, buf_len)); if (!buf) { ESP_LOGE(TAG, "No enough memory for basic authorization"); return ESP_ERR_NO_MEM; } if (httpd_req_get_hdr_value_str(req, "Authorization", buf, buf_len) == ESP_OK) { ESP_LOGI(TAG, "Found header => Authorization: %s", buf); } else { ESP_LOGE(TAG, "No auth value received"); } char *auth_credentials = http_auth_basic(basic_auth_info.username, basic_auth_info.password); if (!auth_credentials) { ESP_LOGE(TAG, "No enough memory for basic authorization credentials"); free(buf); return ESP_ERR_NO_MEM; } if (strncmp(auth_credentials, buf, buf_len)) { ESP_LOGE(TAG, "Not authenticated"); httpd_resp_set_status(req, HTTPD_401); httpd_resp_set_type(req, HTTPD_TYPE_TEXT); httpd_resp_set_hdr(req, "Connection", "keep-alive"); httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\""); httpd_resp_send(req, unauthorized, strlen(unauthorized)); } else { ESP_LOGI(TAG, "Authenticated calling http handler now!"); ret=original_handler(req); } free(auth_credentials); free(buf); } else { ESP_LOGE(TAG, "No auth header received"); httpd_resp_set_status(req, HTTPD_401); httpd_resp_set_type(req, HTTPD_TYPE_TEXT); httpd_resp_set_hdr(req, "Connection", "keep-alive"); httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\""); httpd_resp_send(req, unauthorized, strlen(unauthorized)); } } return ret; }