basic_auth.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. #include "basic_auth.h"
  2. #include "read_wlanini.h"
  3. #include <esp_tls_crypto.h>
  4. #include <esp_log.h>
  5. #include <string>
  6. #include "esp_timer.h"
  7. #include "ClassLogFile.h"
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/queue.h"
  10. #include "freertos/semphr.h"
  11. #include "freertos/task.h"
  12. #include <new>
  13. #include <cstring>
  14. #include <string.h>
  15. #define HTTPD_401 "401 UNAUTHORIZED"
  16. static const char *TAG = "HTTPAUTH";
  17. typedef struct {
  18. const char *username;
  19. const char *password;
  20. } basic_auth_info_t;
  21. basic_auth_info_t basic_auth_info = { NULL, NULL };
  22. // Camera operations share one physical camera. A single worker serializes
  23. // long-running camera responses outside the HTTP server task. A short queue
  24. // lets a capture wait behind a live-stream request without blocking /info.
  25. static QueueHandle_t cameraAsyncRequestQueue = NULL;
  26. static SemaphoreHandle_t cameraAsyncRequestSlot = NULL;
  27. struct AsyncCameraHttpRequest
  28. {
  29. httpd_req_t *request;
  30. basic_auth_async_handler_t handler;
  31. char handlerName[32];
  32. char uri[128];
  33. int64_t startUs;
  34. };
  35. static void async_camera_http_request_task(void *argument)
  36. {
  37. (void)argument;
  38. AsyncCameraHttpRequest work = {};
  39. while (cameraAsyncRequestQueue != NULL &&
  40. xQueueReceive(cameraAsyncRequestQueue, &work, portMAX_DELAY) == pdTRUE)
  41. {
  42. const esp_err_t result = work.handler(work.request);
  43. const int64_t elapsedUs = esp_timer_get_time() - work.startUs;
  44. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  45. std::string("Async camera HTTP request: ") + work.handlerName +
  46. " " + work.uri + " took " +
  47. std::to_string(static_cast<long long>(elapsedUs / 1000)) +
  48. " ms (result=" + std::to_string(static_cast<int>(result)) + ")");
  49. // Complete the async request on every worker exit path so the HTTP server
  50. // can release the socket and accept subsequent requests.
  51. httpd_req_async_handler_complete(work.request);
  52. if (cameraAsyncRequestSlot != NULL) {
  53. xSemaphoreGive(cameraAsyncRequestSlot);
  54. }
  55. }
  56. vTaskDelete(NULL);
  57. }
  58. esp_err_t dispatch_camera_http_request_async(httpd_req_t *req,
  59. basic_auth_async_handler_t handler,
  60. const char *handler_name)
  61. {
  62. if (req == NULL || handler == NULL) {
  63. return ESP_ERR_INVALID_ARG;
  64. }
  65. if (cameraAsyncRequestQueue == NULL || cameraAsyncRequestSlot == NULL ||
  66. xSemaphoreTake(cameraAsyncRequestSlot, 0) != pdTRUE) {
  67. httpd_resp_set_status(req, "503 Service Unavailable");
  68. httpd_resp_sendstr(req, "Camera is busy with another capture or stream");
  69. return ESP_OK;
  70. }
  71. httpd_req_t *asyncRequest = NULL;
  72. const esp_err_t copyResult = httpd_req_async_handler_begin(req, &asyncRequest);
  73. if (copyResult != ESP_OK) {
  74. xSemaphoreGive(cameraAsyncRequestSlot);
  75. httpd_resp_set_status(req, "503 Service Unavailable");
  76. httpd_resp_sendstr(req, "Could not queue camera request");
  77. return ESP_OK;
  78. }
  79. AsyncCameraHttpRequest work = {};
  80. work.request = asyncRequest;
  81. work.handler = handler;
  82. strlcpy(work.handlerName, handler_name != NULL ? handler_name : "camera",
  83. sizeof(work.handlerName));
  84. strlcpy(work.uri, asyncRequest->uri, sizeof(work.uri));
  85. work.startUs = esp_timer_get_time();
  86. if (xQueueSend(cameraAsyncRequestQueue, &work, 0) != pdTRUE) {
  87. // Restore ownership of the socket before returning a busy response.
  88. httpd_req_async_handler_complete(asyncRequest);
  89. xSemaphoreGive(cameraAsyncRequestSlot);
  90. httpd_resp_set_status(req, "503 Service Unavailable");
  91. httpd_resp_sendstr(req, "Camera request queue is full");
  92. }
  93. return ESP_OK;
  94. }
  95. // All URI handlers are registered through APPLY_BASIC_AUTH_FILTER. Measuring here
  96. // gives us a common duration for every HTTP endpoint, including static HTML/CSS/JS
  97. // and image handlers. Time spent waiting in the ESP-IDF server queue is not included.
  98. class HttpRequestTiming
  99. {
  100. public:
  101. explicit HttpRequestTiming(httpd_req_t *request)
  102. : uri(request->uri),
  103. method(request->method == HTTP_GET ? "GET" :
  104. request->method == HTTP_POST ? "POST" :
  105. request->method == HTTP_PUT ? "PUT" :
  106. request->method == HTTP_DELETE ? "DELETE" : "OTHER"),
  107. startUs(esp_timer_get_time())
  108. {
  109. }
  110. ~HttpRequestTiming()
  111. {
  112. const int64_t elapsedUs = esp_timer_get_time() - startUs;
  113. // Catch noticeable handler stalls without logging every normal poll.
  114. if (elapsedUs >= 100000)
  115. {
  116. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  117. std::string("Slow HTTP request: ") + method + " " + uri +
  118. " handler time " +
  119. std::to_string(static_cast<long long>(elapsedUs / 1000)) + " ms");
  120. }
  121. }
  122. private:
  123. std::string uri;
  124. const char *method;
  125. int64_t startUs;
  126. };
  127. void init_basic_auth() {
  128. if (!wlan_config.http_username.empty() && !wlan_config.http_password.empty()) {
  129. basic_auth_info.username = wlan_config.http_username.c_str();
  130. basic_auth_info.password = wlan_config.http_password.c_str();
  131. }
  132. if (cameraAsyncRequestQueue == NULL) {
  133. cameraAsyncRequestQueue = xQueueCreate(1, sizeof(AsyncCameraHttpRequest));
  134. cameraAsyncRequestSlot = xSemaphoreCreateBinary();
  135. if (cameraAsyncRequestSlot != NULL) {
  136. xSemaphoreGive(cameraAsyncRequestSlot);
  137. }
  138. if (cameraAsyncRequestQueue == NULL || cameraAsyncRequestSlot == NULL) {
  139. if (cameraAsyncRequestQueue != NULL) {
  140. vQueueDelete(cameraAsyncRequestQueue);
  141. cameraAsyncRequestQueue = NULL;
  142. }
  143. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  144. "Failed to create asynchronous camera request queue/slot");
  145. return;
  146. }
  147. if (xTaskCreatePinnedToCore(async_camera_http_request_task, "camera_http",
  148. 8 * 1024, NULL, tskIDLE_PRIORITY + 3,
  149. NULL, 1) != pdPASS) {
  150. vQueueDelete(cameraAsyncRequestQueue);
  151. cameraAsyncRequestQueue = NULL;
  152. vSemaphoreDelete(cameraAsyncRequestSlot);
  153. cameraAsyncRequestSlot = NULL;
  154. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  155. "Failed to start asynchronous camera request worker");
  156. }
  157. }
  158. }
  159. static char *http_auth_basic(const char *username, const char *password)
  160. {
  161. int out;
  162. char *user_info = NULL;
  163. char *digest = NULL;
  164. size_t n = 0;
  165. asprintf(&user_info, "%s:%s", username, password);
  166. if (!user_info) {
  167. ESP_LOGE(TAG, "No enough memory for user information");
  168. return NULL;
  169. }
  170. esp_crypto_base64_encode(NULL, 0, &n, (const unsigned char *)user_info, strlen(user_info));
  171. /* 6: The length of the "Basic " string
  172. * n: Number of bytes for a base64 encode format
  173. * 1: Number of bytes for a reserved which be used to fill zero
  174. */
  175. digest = static_cast<char*>(calloc(1, 6 + n + 1));
  176. if (digest) {
  177. strcpy(digest, "Basic ");
  178. esp_crypto_base64_encode((unsigned char *)digest + 6, n, (size_t *)&out, (const unsigned char *)user_info, strlen(user_info));
  179. }
  180. free(user_info);
  181. return digest;
  182. }
  183. esp_err_t basic_auth_request_filter(httpd_req_t *req, esp_err_t original_handler(httpd_req_t *))
  184. {
  185. HttpRequestTiming requestTiming(req);
  186. char *buf = NULL;
  187. size_t buf_len = 0;
  188. esp_err_t ret = ESP_OK;
  189. char unauthorized[] = "You are not authorized to use this website!";
  190. if (basic_auth_info.username == NULL || basic_auth_info.password == NULL) {
  191. ret = original_handler(req);
  192. } else {
  193. buf_len = httpd_req_get_hdr_value_len(req, "Authorization") + 1;
  194. if (buf_len > 1) {
  195. buf = static_cast<char*>(calloc(1, buf_len));
  196. if (!buf) {
  197. ESP_LOGE(TAG, "No enough memory for basic authorization");
  198. return ESP_ERR_NO_MEM;
  199. }
  200. if (httpd_req_get_hdr_value_str(req, "Authorization", buf, buf_len) == ESP_OK) {
  201. ESP_LOGI(TAG, "Found header => Authorization: %s", buf);
  202. } else {
  203. ESP_LOGE(TAG, "No auth value received");
  204. }
  205. char *auth_credentials = http_auth_basic(basic_auth_info.username, basic_auth_info.password);
  206. if (!auth_credentials) {
  207. ESP_LOGE(TAG, "No enough memory for basic authorization credentials");
  208. free(buf);
  209. return ESP_ERR_NO_MEM;
  210. }
  211. if (strncmp(auth_credentials, buf, buf_len)) {
  212. ESP_LOGE(TAG, "Not authenticated");
  213. httpd_resp_set_status(req, HTTPD_401);
  214. httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  215. httpd_resp_set_hdr(req, "Connection", "keep-alive");
  216. httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\"");
  217. httpd_resp_send(req, unauthorized, strlen(unauthorized));
  218. } else {
  219. ESP_LOGI(TAG, "Authenticated calling http handler now!");
  220. ret=original_handler(req);
  221. }
  222. free(auth_credentials);
  223. free(buf);
  224. } else {
  225. ESP_LOGE(TAG, "No auth header received");
  226. httpd_resp_set_status(req, HTTPD_401);
  227. httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  228. httpd_resp_set_hdr(req, "Connection", "keep-alive");
  229. httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\"");
  230. httpd_resp_send(req, unauthorized, strlen(unauthorized));
  231. }
  232. }
  233. return ret;
  234. }