basic_auth.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. // General bounded worker for responses that may block on socket transmission.
  96. // Unlike camera requests, normal asset/image responses may arrive concurrently,
  97. // so they are queued instead of rejected while another transfer is active.
  98. static QueueHandle_t httpAsyncRequestQueue = NULL;
  99. struct AsyncHttpRequest
  100. {
  101. httpd_req_t *request;
  102. basic_auth_async_handler_t handler;
  103. char handlerName[32];
  104. char uri[128];
  105. int64_t startUs;
  106. };
  107. static void async_http_request_task(void *argument)
  108. {
  109. (void)argument;
  110. AsyncHttpRequest work = {};
  111. while (httpAsyncRequestQueue != NULL &&
  112. xQueueReceive(httpAsyncRequestQueue, &work, portMAX_DELAY) == pdTRUE)
  113. {
  114. const esp_err_t result = work.handler(work.request);
  115. const int64_t elapsedUs = esp_timer_get_time() - work.startUs;
  116. if (elapsedUs >= 100000)
  117. {
  118. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  119. std::string("Async HTTP response: ") + work.handlerName +
  120. " " + work.uri + " took " +
  121. std::to_string(static_cast<long long>(elapsedUs / 1000)) +
  122. " ms (result=" + std::to_string(static_cast<int>(result)) + ")");
  123. }
  124. httpd_req_async_handler_complete(work.request);
  125. }
  126. vTaskDelete(NULL);
  127. }
  128. esp_err_t dispatch_http_request_async(httpd_req_t *req,
  129. basic_auth_async_handler_t handler,
  130. const char *handler_name)
  131. {
  132. if (req == NULL || handler == NULL) {
  133. return ESP_ERR_INVALID_ARG;
  134. }
  135. // Preserve normal serving behaviour if worker initialization failed.
  136. if (httpAsyncRequestQueue == NULL) {
  137. return handler(req);
  138. }
  139. httpd_req_t *asyncRequest = NULL;
  140. const esp_err_t copyResult = httpd_req_async_handler_begin(req, &asyncRequest);
  141. if (copyResult != ESP_OK) {
  142. httpd_resp_set_status(req, "503 Service Unavailable");
  143. httpd_resp_sendstr(req, "Could not queue HTTP response");
  144. return ESP_OK;
  145. }
  146. AsyncHttpRequest work = {};
  147. work.request = asyncRequest;
  148. work.handler = handler;
  149. strlcpy(work.handlerName, handler_name != NULL ? handler_name : "http",
  150. sizeof(work.handlerName));
  151. strlcpy(work.uri, asyncRequest->uri, sizeof(work.uri));
  152. work.startUs = esp_timer_get_time();
  153. if (xQueueSend(httpAsyncRequestQueue, &work, 0) != pdTRUE) {
  154. // Queue full: complete the async copy and return an explicit overload
  155. // response on the original request rather than blocking the HTTP task.
  156. httpd_req_async_handler_complete(asyncRequest);
  157. httpd_resp_set_status(req, "503 Service Unavailable");
  158. httpd_resp_sendstr(req, "HTTP response worker is busy");
  159. }
  160. return ESP_OK;
  161. }
  162. // All URI handlers are registered through APPLY_BASIC_AUTH_FILTER. Measuring here
  163. // gives us a common duration for every HTTP endpoint, including static HTML/CSS/JS
  164. // and image handlers. Time spent waiting in the ESP-IDF server queue is not included.
  165. class HttpRequestTiming
  166. {
  167. public:
  168. explicit HttpRequestTiming(httpd_req_t *request)
  169. : uri(request->uri),
  170. method(request->method == HTTP_GET ? "GET" :
  171. request->method == HTTP_POST ? "POST" :
  172. request->method == HTTP_PUT ? "PUT" :
  173. request->method == HTTP_DELETE ? "DELETE" : "OTHER"),
  174. startUs(esp_timer_get_time())
  175. {
  176. }
  177. ~HttpRequestTiming()
  178. {
  179. const int64_t elapsedUs = esp_timer_get_time() - startUs;
  180. // Catch noticeable handler stalls without logging every normal poll.
  181. if (elapsedUs >= 100000)
  182. {
  183. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  184. std::string("Slow HTTP request: ") + method + " " + uri +
  185. " handler time " +
  186. std::to_string(static_cast<long long>(elapsedUs / 1000)) + " ms");
  187. }
  188. }
  189. private:
  190. std::string uri;
  191. const char *method;
  192. int64_t startUs;
  193. };
  194. void init_basic_auth() {
  195. if (!wlan_config.http_username.empty() && !wlan_config.http_password.empty()) {
  196. basic_auth_info.username = wlan_config.http_username.c_str();
  197. basic_auth_info.password = wlan_config.http_password.c_str();
  198. }
  199. if (cameraAsyncRequestQueue == NULL) {
  200. cameraAsyncRequestQueue = xQueueCreate(1, sizeof(AsyncCameraHttpRequest));
  201. cameraAsyncRequestSlot = xSemaphoreCreateBinary();
  202. if (cameraAsyncRequestSlot != NULL) {
  203. xSemaphoreGive(cameraAsyncRequestSlot);
  204. }
  205. if (cameraAsyncRequestQueue == NULL || cameraAsyncRequestSlot == NULL) {
  206. if (cameraAsyncRequestQueue != NULL) {
  207. vQueueDelete(cameraAsyncRequestQueue);
  208. cameraAsyncRequestQueue = NULL;
  209. }
  210. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  211. "Failed to create asynchronous camera request queue/slot");
  212. return;
  213. }
  214. if (xTaskCreatePinnedToCore(async_camera_http_request_task, "camera_http",
  215. 8 * 1024, NULL, tskIDLE_PRIORITY + 3,
  216. NULL, 1) != pdPASS) {
  217. vQueueDelete(cameraAsyncRequestQueue);
  218. cameraAsyncRequestQueue = NULL;
  219. vSemaphoreDelete(cameraAsyncRequestSlot);
  220. cameraAsyncRequestSlot = NULL;
  221. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  222. "Failed to start asynchronous camera request worker");
  223. }
  224. }
  225. // File and image transfers can block in httpd_resp_send_chunk() when the
  226. // client/network is slow. Keep them out of the single HTTP server task.
  227. if (httpAsyncRequestQueue == NULL) {
  228. httpAsyncRequestQueue = xQueueCreate(4, sizeof(AsyncHttpRequest));
  229. if (httpAsyncRequestQueue == NULL ||
  230. xTaskCreatePinnedToCore(async_http_request_task, "http_io",
  231. 8 * 1024, NULL, tskIDLE_PRIORITY + 3,
  232. NULL, 1) != pdPASS) {
  233. if (httpAsyncRequestQueue != NULL) {
  234. vQueueDelete(httpAsyncRequestQueue);
  235. httpAsyncRequestQueue = NULL;
  236. }
  237. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  238. "Failed to start asynchronous HTTP response worker");
  239. }
  240. }
  241. }
  242. static char *http_auth_basic(const char *username, const char *password)
  243. {
  244. int out;
  245. char *user_info = NULL;
  246. char *digest = NULL;
  247. size_t n = 0;
  248. asprintf(&user_info, "%s:%s", username, password);
  249. if (!user_info) {
  250. ESP_LOGE(TAG, "No enough memory for user information");
  251. return NULL;
  252. }
  253. esp_crypto_base64_encode(NULL, 0, &n, (const unsigned char *)user_info, strlen(user_info));
  254. /* 6: The length of the "Basic " string
  255. * n: Number of bytes for a base64 encode format
  256. * 1: Number of bytes for a reserved which be used to fill zero
  257. */
  258. digest = static_cast<char*>(calloc(1, 6 + n + 1));
  259. if (digest) {
  260. strcpy(digest, "Basic ");
  261. esp_crypto_base64_encode((unsigned char *)digest + 6, n, (size_t *)&out, (const unsigned char *)user_info, strlen(user_info));
  262. }
  263. free(user_info);
  264. return digest;
  265. }
  266. esp_err_t basic_auth_request_filter(httpd_req_t *req, esp_err_t original_handler(httpd_req_t *))
  267. {
  268. HttpRequestTiming requestTiming(req);
  269. char *buf = NULL;
  270. size_t buf_len = 0;
  271. esp_err_t ret = ESP_OK;
  272. char unauthorized[] = "You are not authorized to use this website!";
  273. if (basic_auth_info.username == NULL || basic_auth_info.password == NULL) {
  274. ret = original_handler(req);
  275. } else {
  276. buf_len = httpd_req_get_hdr_value_len(req, "Authorization") + 1;
  277. if (buf_len > 1) {
  278. buf = static_cast<char*>(calloc(1, buf_len));
  279. if (!buf) {
  280. ESP_LOGE(TAG, "No enough memory for basic authorization");
  281. return ESP_ERR_NO_MEM;
  282. }
  283. if (httpd_req_get_hdr_value_str(req, "Authorization", buf, buf_len) == ESP_OK) {
  284. ESP_LOGI(TAG, "Found header => Authorization: %s", buf);
  285. } else {
  286. ESP_LOGE(TAG, "No auth value received");
  287. }
  288. char *auth_credentials = http_auth_basic(basic_auth_info.username, basic_auth_info.password);
  289. if (!auth_credentials) {
  290. ESP_LOGE(TAG, "No enough memory for basic authorization credentials");
  291. free(buf);
  292. return ESP_ERR_NO_MEM;
  293. }
  294. if (strncmp(auth_credentials, buf, buf_len)) {
  295. ESP_LOGE(TAG, "Not authenticated");
  296. httpd_resp_set_status(req, HTTPD_401);
  297. httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  298. httpd_resp_set_hdr(req, "Connection", "keep-alive");
  299. httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\"");
  300. httpd_resp_send(req, unauthorized, strlen(unauthorized));
  301. } else {
  302. ESP_LOGI(TAG, "Authenticated calling http handler now!");
  303. ret=original_handler(req);
  304. }
  305. free(auth_credentials);
  306. free(buf);
  307. } else {
  308. ESP_LOGE(TAG, "No auth header received");
  309. httpd_resp_set_status(req, HTTPD_401);
  310. httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  311. httpd_resp_set_hdr(req, "Connection", "keep-alive");
  312. httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\"");
  313. httpd_resp_send(req, unauthorized, strlen(unauthorized));
  314. }
  315. }
  316. return ret;
  317. }