| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388 |
- #include "basic_auth.h"
- #include "read_wlanini.h"
- #include <esp_tls_crypto.h>
- #include <esp_log.h>
- #include <string>
- #include "esp_timer.h"
- #include "ClassLogFile.h"
- #include "freertos/FreeRTOS.h"
- #include "freertos/queue.h"
- #include "freertos/semphr.h"
- #include "freertos/task.h"
- #include <new>
- #include <cstring>
- #include <string.h>
- #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<long long>(elapsedUs / 1000)) +
- " ms (result=" + std::to_string(static_cast<int>(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;
- // Keep one of the five HTTP server sockets available for short control/status requests.
- // The independent camera worker can occupy one additional socket.
- static SemaphoreHandle_t httpAsyncRequestSlots = NULL;
- static constexpr UBaseType_t MAX_ASYNC_HTTP_REQUESTS = 3;
- 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<long long>(elapsedUs / 1000)) +
- " ms (result=" + std::to_string(static_cast<int>(result)) + ")");
- }
- httpd_req_async_handler_complete(work.request);
- if (httpAsyncRequestSlots != NULL) {
- xSemaphoreGive(httpAsyncRequestSlots);
- }
- }
- 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 || httpAsyncRequestSlots == NULL) {
- return handler(req);
- }
- // Do not let slow assets consume every HTTP server socket. With five sockets
- // configured and one reserved for camera work, at most three general async
- // responses may be queued or active at the same time.
- if (xSemaphoreTake(httpAsyncRequestSlots, 0) != pdTRUE) {
- LogFile.WriteToFile(ESP_LOG_WARN, TAG,
- std::string("Async HTTP response capacity reached for ") + req->uri);
- httpd_resp_set_status(req, "503 Service Unavailable");
- httpd_resp_sendstr(req, "HTTP response worker is busy");
- 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(httpAsyncRequestSlots);
- 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);
- xSemaphoreGive(httpAsyncRequestSlots);
- 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<long long>(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 || httpAsyncRequestSlots == NULL) {
- httpAsyncRequestQueue = xQueueCreate(MAX_ASYNC_HTTP_REQUESTS, sizeof(AsyncHttpRequest));
- httpAsyncRequestSlots = xSemaphoreCreateCounting(MAX_ASYNC_HTTP_REQUESTS,
- MAX_ASYNC_HTTP_REQUESTS);
- if (httpAsyncRequestQueue == NULL || httpAsyncRequestSlots == NULL ||
- xTaskCreatePinnedToCore(async_http_request_task, "http_io",
- 8 * 1024, NULL, tskIDLE_PRIORITY + 3,
- NULL, 1) != pdPASS) {
- if (httpAsyncRequestQueue != NULL) {
- vQueueDelete(httpAsyncRequestQueue);
- httpAsyncRequestQueue = NULL;
- }
- if (httpAsyncRequestSlots != NULL) {
- vSemaphoreDelete(httpAsyncRequestSlots);
- httpAsyncRequestSlots = 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<char*>(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<char*>(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;
- }
|