basic_auth.cpp 9.1 KB

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