#include "basic_auth.h" #include "read_wlanini.h" #include #include #include #include "esp_timer.h" #include "ClassLogFile.h" #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #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 and are therefore dispatched through // one bounded asynchronous slot. This keeps long captures/streams out of the // single esp_http_server task without allowing concurrent camera requests. 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) { AsyncCameraHttpRequest *work = static_cast(argument); 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); } delete work; 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 (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; } AsyncCameraHttpRequest *work = new (std::nothrow) AsyncCameraHttpRequest{}; if (work == NULL) { xSemaphoreGive(cameraAsyncRequestSlot); httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Not enough memory for camera request"); return ESP_OK; } httpd_req_t *asyncRequest = NULL; const esp_err_t copyResult = httpd_req_async_handler_begin(req, &asyncRequest); if (copyResult != ESP_OK) { delete work; xSemaphoreGive(cameraAsyncRequestSlot); httpd_resp_send_err(req, HTTPD_503_SERVICE_UNAVAILABLE, "Could not queue camera request"); return ESP_OK; } 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(); // Lower priority than the HTTP server task. Socket sends and camera waits // happen on this worker, while short UI/API requests remain serviceable. if (xTaskCreatePinnedToCore(async_camera_http_request_task, "camera_http", 8 * 1024, work, tskIDLE_PRIORITY + 3, NULL, 1) != pdPASS) { httpd_resp_send_err(req, HTTPD_503_SERVICE_UNAVAILABLE, "Could not start camera request worker"); httpd_req_async_handler_complete(asyncRequest); delete work; xSemaphoreGive(cameraAsyncRequestSlot); return ESP_OK; } 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 (cameraAsyncRequestSlot == NULL) { cameraAsyncRequestSlot = xSemaphoreCreateBinary(); if (cameraAsyncRequestSlot != NULL) { xSemaphoreGive(cameraAsyncRequestSlot); } else { LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create asynchronous camera request slot"); } } } 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; }