httpd_uri.c 12 KB

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