httpd_uri.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. * SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <errno.h>
  7. #include <esp_log.h>
  8. #include <esp_err.h>
  9. #include <http_parser.h>
  10. #include <esp_http_server.h>
  11. #include "esp_httpd_priv.h"
  12. static const char *TAG = "httpd_uri";
  13. static bool httpd_uri_match_simple(const char *uri1, const char *uri2, size_t len2)
  14. {
  15. return strlen(uri1) == len2 && // First match lengths
  16. (strncmp(uri1, uri2, len2) == 0); // Then match actual URIs
  17. }
  18. bool httpd_uri_match_wildcard(const char *template, const char *uri, size_t len)
  19. {
  20. const size_t tpl_len = strlen(template);
  21. size_t exact_match_chars = tpl_len;
  22. /* Check for trailing question mark and asterisk */
  23. const char last = (const char) (tpl_len > 0 ? template[tpl_len - 1] : 0);
  24. const char prevlast = (const char) (tpl_len > 1 ? template[tpl_len - 2] : 0);
  25. const bool asterisk = last == '*' || (prevlast == '*' && last == '?');
  26. const bool quest = last == '?' || (prevlast == '?' && last == '*');
  27. /* Minimum template string length must be:
  28. * 0 : if neither of '*' and '?' are present
  29. * 1 : if only '*' is present
  30. * 2 : if only '?' is present
  31. * 3 : if both are present
  32. *
  33. * The expression (asterisk + quest*2) serves as a
  34. * case wise generator of these length values
  35. */
  36. /* abort in cases such as "?" with no preceding character (invalid template) */
  37. if (exact_match_chars < asterisk + quest*2) {
  38. return false;
  39. }
  40. /* account for special characters and the optional character if "?" is used */
  41. exact_match_chars -= asterisk + quest*2;
  42. if (len < exact_match_chars) {
  43. return false;
  44. }
  45. if (!quest) {
  46. if (!asterisk && len != exact_match_chars) {
  47. /* no special characters and different length - strncmp would return false */
  48. return false;
  49. }
  50. /* asterisk allows arbitrary trailing characters, we ignore these using
  51. * exact_match_chars as the length limit */
  52. return (strncmp(template, uri, exact_match_chars) == 0);
  53. } else {
  54. /* question mark present */
  55. if (len > exact_match_chars && template[exact_match_chars] != uri[exact_match_chars]) {
  56. /* the optional character is present, but different */
  57. return false;
  58. }
  59. if (strncmp(template, uri, exact_match_chars) != 0) {
  60. /* the mandatory part differs */
  61. return false;
  62. }
  63. /* Now we know the URI is longer than the required part of template,
  64. * the mandatory part matches, and if the optional character is present, it is correct.
  65. * Match is OK if we have asterisk, i.e. any trailing characters are OK, or if
  66. * there are no characters beyond the optional character. */
  67. return asterisk || len <= exact_match_chars + 1;
  68. }
  69. }
  70. /* Find handler with matching URI and method, and set
  71. * appropriate error code if URI or method not found */
  72. static httpd_uri_t* httpd_find_uri_handler(struct httpd_data *hd,
  73. const char *uri, size_t uri_len,
  74. httpd_method_t method,
  75. httpd_err_code_t *err)
  76. {
  77. if (err) {
  78. *err = HTTPD_404_NOT_FOUND;
  79. }
  80. for (int i = 0; i < hd->config.max_uri_handlers; i++) {
  81. if (!hd->hd_calls[i]) {
  82. break;
  83. }
  84. ESP_LOGD(TAG, LOG_FMT("[%d] = %s"), i, hd->hd_calls[i]->uri);
  85. /* Check if custom URI matching function is set,
  86. * else use simple string compare */
  87. if (hd->config.uri_match_fn ?
  88. hd->config.uri_match_fn(hd->hd_calls[i]->uri, uri, uri_len) :
  89. httpd_uri_match_simple(hd->hd_calls[i]->uri, uri, uri_len)) {
  90. /* URIs match. Now check if method is supported */
  91. if (hd->hd_calls[i]->method == method) {
  92. /* Match found! */
  93. if (err) {
  94. /* Unset any error that may
  95. * have been set earlier */
  96. *err = 0;
  97. }
  98. return hd->hd_calls[i];
  99. }
  100. /* URI found but method not allowed.
  101. * If URI is found later then this
  102. * error must be set to 0 */
  103. if (err) {
  104. *err = HTTPD_405_METHOD_NOT_ALLOWED;
  105. }
  106. }
  107. }
  108. return NULL;
  109. }
  110. esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
  111. const httpd_uri_t *uri_handler)
  112. {
  113. if (handle == NULL || uri_handler == NULL) {
  114. return ESP_ERR_INVALID_ARG;
  115. }
  116. struct httpd_data *hd = (struct httpd_data *) handle;
  117. /* Make sure another handler with matching URI and method
  118. * is not already registered. This will also catch cases
  119. * when a registered URI wildcard pattern already accounts
  120. * for the new URI being registered */
  121. if (httpd_find_uri_handler(handle, uri_handler->uri,
  122. strlen(uri_handler->uri),
  123. uri_handler->method, NULL) != NULL) {
  124. ESP_LOGW(TAG, LOG_FMT("handler %s with method %d already registered"),
  125. uri_handler->uri, uri_handler->method);
  126. return ESP_ERR_HTTPD_HANDLER_EXISTS;
  127. }
  128. for (int i = 0; i < hd->config.max_uri_handlers; i++) {
  129. if (hd->hd_calls[i] == NULL) {
  130. hd->hd_calls[i] = malloc(sizeof(httpd_uri_t));
  131. if (hd->hd_calls[i] == NULL) {
  132. /* Failed to allocate memory */
  133. return ESP_ERR_HTTPD_ALLOC_MEM;
  134. }
  135. /* Copy URI string */
  136. hd->hd_calls[i]->uri = strdup(uri_handler->uri);
  137. if (hd->hd_calls[i]->uri == NULL) {
  138. /* Failed to allocate memory */
  139. free(hd->hd_calls[i]);
  140. return ESP_ERR_HTTPD_ALLOC_MEM;
  141. }
  142. /* Copy remaining members */
  143. hd->hd_calls[i]->method = uri_handler->method;
  144. hd->hd_calls[i]->handler = uri_handler->handler;
  145. hd->hd_calls[i]->user_ctx = uri_handler->user_ctx;
  146. #ifdef CONFIG_HTTPD_WS_SUPPORT
  147. hd->hd_calls[i]->is_websocket = uri_handler->is_websocket;
  148. hd->hd_calls[i]->handle_ws_control_frames = uri_handler->handle_ws_control_frames;
  149. if (uri_handler->supported_subprotocol) {
  150. hd->hd_calls[i]->supported_subprotocol = strdup(uri_handler->supported_subprotocol);
  151. } else {
  152. hd->hd_calls[i]->supported_subprotocol = NULL;
  153. }
  154. #endif
  155. ESP_LOGD(TAG, LOG_FMT("[%d] installed %s"), i, uri_handler->uri);
  156. return ESP_OK;
  157. }
  158. ESP_LOGD(TAG, LOG_FMT("[%d] exists %s"), i, hd->hd_calls[i]->uri);
  159. }
  160. ESP_LOGW(TAG, LOG_FMT("no slots left for registering handler"));
  161. return ESP_ERR_HTTPD_HANDLERS_FULL;
  162. }
  163. esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle,
  164. const char *uri, httpd_method_t method)
  165. {
  166. if (handle == NULL || uri == NULL) {
  167. return ESP_ERR_INVALID_ARG;
  168. }
  169. struct httpd_data *hd = (struct httpd_data *) handle;
  170. for (int i = 0; i < hd->config.max_uri_handlers; i++) {
  171. if (!hd->hd_calls[i]) {
  172. break;
  173. }
  174. if ((hd->hd_calls[i]->method == method) && // First match methods
  175. (strcmp(hd->hd_calls[i]->uri, uri) == 0)) { // Then match URI string
  176. ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
  177. free((char*)hd->hd_calls[i]->uri);
  178. free(hd->hd_calls[i]);
  179. hd->hd_calls[i] = NULL;
  180. /* Shift the remaining non null handlers in the array
  181. * forward by 1 so that order of insertion is maintained */
  182. for (i += 1; i < hd->config.max_uri_handlers; i++) {
  183. if (!hd->hd_calls[i]) {
  184. break;
  185. }
  186. hd->hd_calls[i-1] = hd->hd_calls[i];
  187. }
  188. /* Nullify the following non null entry */
  189. hd->hd_calls[i-1] = NULL;
  190. return ESP_OK;
  191. }
  192. }
  193. ESP_LOGW(TAG, LOG_FMT("handler %s with method %d not found"), uri, method);
  194. return ESP_ERR_NOT_FOUND;
  195. }
  196. esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri)
  197. {
  198. if (handle == NULL || uri == NULL) {
  199. return ESP_ERR_INVALID_ARG;
  200. }
  201. struct httpd_data *hd = (struct httpd_data *) handle;
  202. bool found = false;
  203. int i = 0, j = 0; // For keeping count of removed entries
  204. for (; i < hd->config.max_uri_handlers; i++) {
  205. if (!hd->hd_calls[i]) {
  206. break;
  207. }
  208. if (strcmp(hd->hd_calls[i]->uri, uri) == 0) { // Match URI strings
  209. ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, uri);
  210. free((char*)hd->hd_calls[i]->uri);
  211. free(hd->hd_calls[i]);
  212. hd->hd_calls[i] = NULL;
  213. found = true;
  214. j++; // Update count of removed entries
  215. } else {
  216. /* Shift the remaining non null handlers in the array
  217. * forward by j so that order of insertion is maintained */
  218. hd->hd_calls[i-j] = hd->hd_calls[i];
  219. }
  220. }
  221. /* Nullify the following non null entries */
  222. for (int k = (i - j); k < i; k++) {
  223. hd->hd_calls[k] = NULL;
  224. }
  225. if (!found) {
  226. ESP_LOGW(TAG, LOG_FMT("no handler found for URI %s"), uri);
  227. }
  228. return (found ? ESP_OK : ESP_ERR_NOT_FOUND);
  229. }
  230. void httpd_unregister_all_uri_handlers(struct httpd_data *hd)
  231. {
  232. for (unsigned i = 0; i < hd->config.max_uri_handlers; i++) {
  233. if (!hd->hd_calls[i]) {
  234. break;
  235. }
  236. ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
  237. free((char*)hd->hd_calls[i]->uri);
  238. free(hd->hd_calls[i]);
  239. hd->hd_calls[i] = NULL;
  240. }
  241. }
  242. esp_err_t httpd_uri(struct httpd_data *hd)
  243. {
  244. httpd_uri_t *uri = NULL;
  245. httpd_req_t *req = &hd->hd_req;
  246. struct http_parser_url *res = &hd->hd_req_aux.url_parse_res;
  247. /* For conveying URI not found/method not allowed */
  248. httpd_err_code_t err = 0;
  249. ESP_LOGD(TAG, LOG_FMT("request for %s with type %d"), req->uri, req->method);
  250. /* URL parser result contains offset and length of path string */
  251. if (res->field_set & (1 << UF_PATH)) {
  252. uri = httpd_find_uri_handler(hd, req->uri + res->field_data[UF_PATH].off,
  253. res->field_data[UF_PATH].len, req->method, &err);
  254. }
  255. /* If URI with method not found, respond with error code */
  256. if (uri == NULL) {
  257. switch (err) {
  258. case HTTPD_404_NOT_FOUND:
  259. ESP_LOGW(TAG, LOG_FMT("URI '%s' not found"), req->uri);
  260. return httpd_req_handle_err(req, HTTPD_404_NOT_FOUND);
  261. case HTTPD_405_METHOD_NOT_ALLOWED:
  262. ESP_LOGW(TAG, LOG_FMT("Method '%d' not allowed for URI '%s'"),
  263. req->method, req->uri);
  264. return httpd_req_handle_err(req, HTTPD_405_METHOD_NOT_ALLOWED);
  265. default:
  266. return ESP_FAIL;
  267. }
  268. }
  269. /* Attach user context data (passed during URI registration) into request */
  270. req->user_ctx = uri->user_ctx;
  271. /* Final step for a WebSocket handshake verification */
  272. #ifdef CONFIG_HTTPD_WS_SUPPORT
  273. struct httpd_req_aux *aux = req->aux;
  274. if (uri->is_websocket && aux->ws_handshake_detect && uri->method == HTTP_GET) {
  275. ESP_LOGD(TAG, LOG_FMT("Responding WS handshake to sock %d"), aux->sd->fd);
  276. esp_err_t ret = httpd_ws_respond_server_handshake(&hd->hd_req, uri->supported_subprotocol);
  277. if (ret != ESP_OK) {
  278. return ret;
  279. }
  280. aux->sd->ws_handshake_done = true;
  281. aux->sd->ws_handler = uri->handler;
  282. aux->sd->ws_control_frames = uri->handle_ws_control_frames;
  283. aux->sd->ws_user_ctx = uri->user_ctx;
  284. }
  285. #endif
  286. /* Invoke handler */
  287. if (uri->handler(req) != ESP_OK) {
  288. /* Handler returns error, this socket should be closed */
  289. ESP_LOGW(TAG, LOG_FMT("uri handler execution failed"));
  290. return ESP_FAIL;
  291. }
  292. return ESP_OK;
  293. }