basic_auth.cpp 9.1 KB

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