basic_auth.cpp 15 KB

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