httpd.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. #define MODULE "httpd"
  2. #include "common.h"
  3. #include "fw.h"
  4. #include "httpd.h"
  5. #include "config.h"
  6. #include <incbin.h>
  7. #include <unzipLIB.h>
  8. static httpd_handle_t httpd;
  9. static const char fallback_language[] = "en"; /* For unknown language */
  10. static const char index_filename[] = "index.html"; /* For a directory "file" */
  11. #define MAX_LANG_LEN 16
  12. /* Looping version of httpd_send(); this is a hidden function in the server */
  13. static esp_err_t httpd_send_all(httpd_req_t *req, const void *buf, size_t len)
  14. {
  15. const char *p = buf;
  16. while (len) {
  17. int sent = httpd_send(req, p, len);
  18. if (sent <= 0)
  19. return ESP_ERR_HTTPD_RESP_SEND;
  20. p += sent;
  21. len -= sent;
  22. }
  23. return ESP_OK;
  24. }
  25. /* Create a file pointer from an http request */
  26. static ssize_t httpd_io_read(void *cookie, char *buf, size_t n)
  27. {
  28. int rv = httpd_req_recv(cookie, buf, n);
  29. return rv < 0 ? -1 : rv;
  30. }
  31. static ssize_t httpd_io_write(void *cookie, const char *buf, size_t n)
  32. {
  33. return httpd_resp_send_chunk(cookie, buf, n) ? 0 : n;
  34. }
  35. static int httpd_io_close_write(void *cookie)
  36. {
  37. return httpd_resp_send_chunk(cookie, NULL, 0) ? -1 : 0;
  38. }
  39. static FILE *httpd_fopen_read(httpd_req_t *req)
  40. {
  41. static const cookie_io_functions_t http_io_read_funcs = {
  42. .read = httpd_io_read,
  43. .write = NULL, /* Not writeable */
  44. .seek = NULL, /* Not seekable */
  45. .close = NULL,
  46. };
  47. return fopencookie((void *)req, "r", http_io_read_funcs);
  48. }
  49. static FILE *httpd_fopen_write(httpd_req_t *req)
  50. {
  51. static const cookie_io_functions_t http_io_write_funcs = {
  52. .read = httpd_io_read,
  53. .write = httpd_io_write,
  54. .seek = NULL, /* Not seekable */
  55. .close = httpd_io_close_write
  56. };
  57. return fopencookie((void *)req, "r+", http_io_write_funcs);
  58. }
  59. #define TIMEBUF_LEN 32
  60. static const char *http_date(const struct tm *when)
  61. {
  62. static char timebuf[32];
  63. strftime(timebuf, sizeof timebuf,
  64. "%a, %d %b %Y %H:%M:%S GMT", when);
  65. return timebuf;
  66. }
  67. static const char *http_now(void)
  68. {
  69. time_t t = time(NULL);
  70. return http_date(gmtime(&t));
  71. }
  72. static struct tm *set_weekday(struct tm *tm)
  73. {
  74. /*
  75. * This is a variation on Zeller's congruence with a table lookup
  76. * for the month. The table contains the number of days since March 1,
  77. * mod 7 (for Jan and Feb, from March 1 of the *previous year*.)
  78. *
  79. * Sample test cases:
  80. * Wed Mar 1 0000
  81. * Thu Jan 1 1970
  82. * Wed Apr 27 2022
  83. * Mon Feb 28 2000
  84. * Wed Mar 1 2000
  85. * Sun Feb 28 2100
  86. * Mon Mar 1 2100
  87. */
  88. static const uint8_t md[12] = { 5, 1, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2 };
  89. unsigned int c, y, m, d;
  90. y = tm->tm_year + 1900;
  91. m = tm->tm_mon;
  92. d = tm->tm_mday;
  93. if (m < 2)
  94. y--; /* Jan, Feb */
  95. c = y/100;
  96. /*
  97. * 2 represents the base date of Tue Feb 29 0000
  98. *
  99. * 0 = Sun, 6 = Sat
  100. */
  101. tm->tm_wday = (d + md[m] + y + (y >> 2) - c + (c >> 2) + 2) % 7;
  102. return tm;
  103. }
  104. static const char *http_dos_date(uint32_t dos_date)
  105. {
  106. struct tm tm;
  107. tm.tm_sec = (dos_date << 1) & 63;
  108. tm.tm_min = (dos_date >> 5) & 63;
  109. tm.tm_hour = (dos_date >> 11) & 31;
  110. tm.tm_mday = (dos_date >> 16) & 31;
  111. tm.tm_mon = ((dos_date >> 21) & 15) - 1;
  112. tm.tm_year = (dos_date >> 25) + 80;
  113. tm.tm_isdst = 0; /* Times are stored in GMT */
  114. return http_date(set_weekday(&tm));
  115. }
  116. static const char text_plain[] = "text/plain; charset=\"UTF-8\"";
  117. enum hsp_flags {
  118. HSP_CLOSE = 1,
  119. HSP_CRLF = 2,
  120. HSP_CLOSE_SOCKET = 4
  121. };
  122. static void httpd_print_request(const httpd_req_t *req)
  123. {
  124. printf("[HTTP] %s %s\n", http_method_str(req->method), req->uri);
  125. }
  126. static esp_err_t httpd_send_plain(httpd_req_t *req,
  127. unsigned int rcode,
  128. const char *body, size_t blen,
  129. enum hsp_flags flags, unsigned int refresh)
  130. {
  131. char *header = NULL;
  132. esp_err_t err;
  133. int hlen;
  134. const char *now = http_now();
  135. if (rcode > 499)
  136. flags |= HSP_CLOSE;
  137. const char *closer = flags & HSP_CLOSE ? "Connection: close\r\n" : "";
  138. bool redirect = rcode >= 300 && rcode <= 399;
  139. char *refresher = NULL;
  140. if (refresh) {
  141. size_t referer_length = httpd_req_get_hdr_value_len(req, "Referer");
  142. if (referer_length) {
  143. size_t refbufsize = sizeof("Refresh: ;url=\r\n")
  144. + 3*sizeof(unsigned int) + referer_length;
  145. refresher = malloc(refbufsize);
  146. size_t rlen = snprintf(refresher, refbufsize, "Refresh: %u;url=", refresh);
  147. httpd_req_get_hdr_value_str(req, "Referer", refresher+rlen,
  148. refbufsize-rlen);
  149. memcpy(refresher+rlen+referer_length, "\r\n", 3);
  150. }
  151. }
  152. if (!refresher)
  153. refresher = (char *)"";
  154. if (redirect) {
  155. size_t blenadj = sizeof("3xx Redirect \r"); /* \0 -> \n so don't include it */
  156. flags |= HSP_CRLF;
  157. hlen = asprintf(&header,
  158. "HTTP/1.1 %u\r\n"
  159. "Content-Type: %s\r\n"
  160. "Content-Length: %zu\r\n"
  161. "Date %s\r\n"
  162. "Location: %.*s\r\n"
  163. "%s%s"
  164. "\r\n"
  165. "%3u Redirect ",
  166. rcode, text_plain, blen + blenadj,
  167. now, (int)blen, body, closer, refresher, rcode);
  168. } else {
  169. size_t blenadj = (flags & HSP_CRLF) ? 2 : 0;
  170. hlen = asprintf(&header,
  171. "HTTP/1.1 %u\r\n"
  172. "Content-Type: %s\r\n"
  173. "Content-Length: %zu\r\n"
  174. "Cache-Control: no-store\r\n"
  175. "Date: %s\r\n"
  176. "%s%s"
  177. "\r\n",
  178. rcode, text_plain, blen + blenadj, now,
  179. closer, refresher);
  180. }
  181. if (*refresher)
  182. free(refresher);
  183. if (!header)
  184. return ESP_ERR_NO_MEM;
  185. err = httpd_send_all(req, header, hlen);
  186. if (!err && blen) {
  187. err = httpd_send_all(req, body, blen);
  188. }
  189. if (!err && (flags & HSP_CRLF)) {
  190. err = httpd_send_all(req, "\r\n", 2);
  191. }
  192. if (header)
  193. free(header);
  194. /* Sending ESP_FAIL causes the socket to be immediately closed */
  195. return err ? err : (flags & HSP_CLOSE_SOCKET) ? ESP_FAIL : ESP_OK;
  196. }
  197. #define SL(s) (s), (sizeof(s)-1)
  198. #define HTTP_ERR(r,e,s) httpd_send_plain((r), (e), SL(s), HSP_CRLF, 0)
  199. static esp_err_t httpd_err_enoent(httpd_req_t *req)
  200. {
  201. return HTTP_ERR(req, 404, "URI not found");
  202. }
  203. static esp_err_t httpd_send_ok(httpd_req_t *req)
  204. {
  205. return HTTP_ERR(req, 200, "OK");
  206. }
  207. static esp_err_t httpd_err_enomem(httpd_req_t *req)
  208. {
  209. return HTTP_ERR(req, 503, "Out of memory");
  210. }
  211. static esp_err_t httpd_update_done(httpd_req_t *req, const char *what, int err)
  212. {
  213. char *response = NULL;
  214. int len;
  215. unsigned int reboot_time = reboot_delayed();
  216. if (err) {
  217. len = asprintf(&response,
  218. "%s update failed: %s\r\n"
  219. "Rebooting in %u seconds\r\n",
  220. what, firmware_errstr(err), reboot_time);
  221. } else {
  222. len = asprintf(&response,
  223. "%s update complete\r\n"
  224. "Rebooting in %u seconds\r\n",
  225. what, reboot_time);
  226. }
  227. if (!response)
  228. len = 0;
  229. esp_err_t rv = httpd_send_plain(req, err ? 400 : 200, response, len,
  230. HSP_CLOSE|HSP_CLOSE_SOCKET|HSP_CRLF,
  231. reboot_time+5);
  232. if (response)
  233. free(response);
  234. return rv;
  235. }
  236. static esp_err_t httpd_firmware_update(httpd_req_t *req)
  237. {
  238. int rv;
  239. /* XXX: use httpd_fopen_read() here */
  240. rv = firmware_update((read_func_t)httpd_req_recv, (token_t)req);
  241. return httpd_update_done(req, "Firmware", rv);
  242. }
  243. static esp_err_t httpd_set_config(httpd_req_t *req, const char *query)
  244. {
  245. FILE *f;
  246. size_t qlen;
  247. int rv1 = 0;
  248. if (query) {
  249. rv1 = set_config_url_string(query);
  250. }
  251. int rv2 = 0;
  252. f = NULL;
  253. if (req->content_len) {
  254. f = httpd_fopen_read(req);
  255. if (!f)
  256. return HTTP_ERR(req, 500, "Unable to get request handle");
  257. }
  258. rv2 = read_config(f, true);
  259. if (f)
  260. fclose(f);
  261. return httpd_update_done(req, "Configuration", rv1 ? rv1 : rv2);
  262. }
  263. static esp_err_t httpd_get_config(httpd_req_t *req)
  264. {
  265. FILE *f = httpd_fopen_write(req);
  266. if (!f)
  267. return HTTP_ERR(req, 500, "Unable to get request handle");
  268. httpd_resp_set_type(req, text_plain);
  269. httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
  270. int rv = write_config(f);
  271. fclose(f);
  272. return rv ? ESP_FAIL : ESP_OK;
  273. }
  274. static esp_err_t httpd_set_lang(httpd_req_t *req, const char *query)
  275. {
  276. if (query) {
  277. int qlen = strlen(query);
  278. setenv_config("LANG", qlen && qlen <= MAX_LANG_LEN ? query : NULL);
  279. read_config(NULL, true); /* Save configuration */
  280. }
  281. return httpd_send_plain(req, 200, SL("Language set"), HSP_CRLF, 1);
  282. }
  283. static esp_err_t httpd_get_lang(httpd_req_t *req)
  284. {
  285. const char *lang = getenv_def("LANG", "");
  286. return httpd_send_plain(req, 200, lang, strlen(lang), HSP_CRLF, 0);
  287. }
  288. static esp_err_t httpd_lang_redirect(httpd_req_t *req)
  289. {
  290. char lang_buf[sizeof("/lang/") + MAX_LANG_LEN];
  291. int len = snprintf(lang_buf, sizeof lang_buf, "/lang/%s",
  292. getenv_def("LANG", fallback_language));
  293. return httpd_send_plain(req, 302, lang_buf, len, 0, 0);
  294. }
  295. #define STRING_MATCHES(str, len, what) \
  296. (((len) == sizeof(what)-1) && !memcmp((str), (what), sizeof(what)-1))
  297. static esp_err_t httpd_sys_handler(httpd_req_t *req)
  298. {
  299. httpd_print_request(req);
  300. if (req->method == HTTP_POST &&
  301. !httpd_req_get_hdr_value_len(req, "Content-Length")) {
  302. return HTTP_ERR(req, 411, "Length required");
  303. }
  304. const char *query = strchrnul(req->uri, '?');
  305. if (query < req->uri+5 || memcmp(req->uri, "/sys/", 5))
  306. return httpd_err_enoent(req); /* This should never happen */
  307. const char *file = req->uri + 5;
  308. size_t filelen = query - file;
  309. query = *query == '?' ? query+1 : NULL;
  310. if (STRING_MATCHES(file, filelen, "lang"))
  311. return httpd_lang_redirect(req);
  312. if (STRING_MATCHES(file, filelen, "getconfig"))
  313. return httpd_get_config(req);
  314. if (req->method == HTTP_POST && STRING_MATCHES(file, filelen, "fwupdate"))
  315. return httpd_firmware_update(req);
  316. if (STRING_MATCHES(file, filelen, "setconfig"))
  317. return httpd_set_config(req, query);
  318. if (STRING_MATCHES(file, filelen, "getlang"))
  319. return httpd_get_lang(req);
  320. if (STRING_MATCHES(file, filelen, "setlang"))
  321. return httpd_set_lang(req, query);
  322. return httpd_err_enoent(req);
  323. }
  324. INCBIN_EXTERN(wwwzip);
  325. struct mime_type {
  326. const char *ext;
  327. uint16_t ext_len;
  328. uint16_t flags;
  329. const char *mime;
  330. };
  331. #define MT_CHARSET 1 /* Add charset to Content-Type */
  332. static const struct mime_type mime_types[] = {
  333. { ".html", 5, MT_CHARSET, "text/html" },
  334. { ".xhtml", 6, MT_CHARSET, "text/html" },
  335. { ".css", 4, MT_CHARSET, "text/css" },
  336. { ".webp", 5, 0, "image/webp" },
  337. { ".jpg", 4, 0, "image/jpeg" },
  338. { ".png", 4, 0, "image/png" },
  339. { ".ico", 4, 0, "image/png" }, /* favicon.ico */
  340. { ".svg", 4, MT_CHARSET, "image/svg+xml" },
  341. { ".otf", 4, 0, "font/otf" },
  342. { ".ttf", 4, 0, "font/ttf" },
  343. { ".woff", 5, 0, "font/woff" },
  344. { ".woff2", 6, 0, "font/woff2" },
  345. { ".pdf", 4, 0, "application/pdf" },
  346. { ".js", 3, MT_CHARSET, "text/javascript" },
  347. { ".mjs", 4, MT_CHARSET, "text/javascript" },
  348. { ".json", 5, MT_CHARSET, "application/json" },
  349. { ".xml", 4, MT_CHARSET, "text/xml" },
  350. { ".bin", 4, 0, "application/octet-stream" },
  351. { ".fw", 3, 0, "application/octet-stream" },
  352. { NULL, 0, MT_CHARSET, "text/plain" } /* default */
  353. };
  354. static esp_err_t httpd_static_handler(httpd_req_t *req)
  355. {
  356. size_t buffer_size = UNZ_BUFSIZE;
  357. const char *uri, *enduri;
  358. bool add_index;
  359. char *buffer = NULL;
  360. ZIPFILE *zip = NULL;
  361. unzFile unz = NULL;
  362. bool file_open = false;
  363. int err = 0;
  364. size_t len;
  365. httpd_print_request(req);
  366. uri = req->uri;
  367. while (*uri == '/')
  368. uri++; /* Skip leading slashes */
  369. const char *first_slash = NULL, *last_slash = NULL;
  370. for (enduri = uri; *enduri; enduri++) {
  371. if (*enduri == '/') {
  372. last_slash = enduri;
  373. if (!first_slash)
  374. first_slash = enduri;
  375. }
  376. }
  377. if (enduri == uri) {
  378. add_index = true;
  379. } else if (last_slash == enduri-1) {
  380. add_index = true;
  381. enduri--; /* Drop terminal slash */
  382. if (first_slash == last_slash)
  383. first_slash = NULL;
  384. } else {
  385. add_index = false; /* Try the plain filename first */
  386. }
  387. const char *lang = getenv_def("LANG", "");
  388. const size_t lang_size = lang ? strlen(lang)+1 : 0;
  389. const size_t lang_space = (lang_size < sizeof fallback_language
  390. ? sizeof fallback_language : lang_size) + 1;
  391. const size_t filename_buffer_size =
  392. (enduri - uri) + lang_space + 2 + sizeof index_filename;
  393. if (buffer_size < filename_buffer_size)
  394. buffer_size = filename_buffer_size;
  395. buffer = malloc(buffer_size);
  396. zip = malloc(sizeof *zip);
  397. if (!buffer || !zip) {
  398. err = httpd_err_enomem(req);
  399. goto out;
  400. }
  401. char * const filebase = buffer + lang_space;
  402. char * const endbase = mempcpy(filebase, uri, enduri - uri);
  403. filebase[-1] = '/';
  404. unz = unzOpen(NULL, (void *)gwwwzipData, gwwwzipSize,
  405. zip, NULL, NULL, NULL, NULL);
  406. if (!unz) {
  407. MSG("[HTTP] unzOpen failed!\n");
  408. err = HTTP_ERR(req, 500, "Cannot open content archive");
  409. goto out;
  410. }
  411. char *filename, *endfile;
  412. unsigned int m;
  413. bool found = false;
  414. for (m = add_index; m < 6; m += (add_index+1)) {
  415. if (m & 1) {
  416. char *sx = endbase - (endbase[-1] == '/');
  417. *sx++ = '/';
  418. endfile = mempcpy(sx, index_filename, sizeof index_filename) - 1;
  419. } else {
  420. endfile = endbase;
  421. }
  422. *endfile = '\0';
  423. switch (m >> 1) {
  424. case 1:
  425. if (!lang) {
  426. filename = NULL;
  427. } else {
  428. filename = filebase - lang_size;
  429. memcpy(filename, lang, lang_size-1);
  430. }
  431. break;
  432. case 2:
  433. filename = filebase - sizeof fallback_language;
  434. memcpy(filename, fallback_language, sizeof fallback_language - 1);
  435. break;
  436. default:
  437. filename = filebase;
  438. break;
  439. }
  440. if (!filename)
  441. continue;
  442. filename[-1] = '/';
  443. MSG("trying to open: %s\n", filename);
  444. if (unzLocateFile(unz, filename, 1) == UNZ_OK) {
  445. found = true;
  446. break;
  447. }
  448. }
  449. size_t filelen = endfile - filename;
  450. if (!found) {
  451. err = httpd_err_enoent(req);
  452. goto out;
  453. } else if (m) {
  454. err = httpd_send_plain(req, 302 - (m == 1), filename-1, filelen+1, 0, 0);
  455. goto out;
  456. }
  457. /* Note: p points to the end of the filename string */
  458. const struct mime_type *mime_type = mime_types;
  459. /* The default entry with length 0 will always match */
  460. while (mime_type->ext_len) {
  461. len = mime_type->ext_len;
  462. if (len < filelen && !memcmp(endfile - len, mime_type->ext, len))
  463. break;
  464. mime_type++;
  465. }
  466. unz_file_info fileinfo;
  467. memset(&fileinfo, 0, sizeof fileinfo);
  468. unzGetCurrentFileInfo(unz, &fileinfo, NULL, 0, NULL, 0, NULL, 0);
  469. /*
  470. * Hopefully the combination of date and CRC
  471. * is strong enough to quality for a "strong" ETag
  472. */
  473. char etag[16+3+1];
  474. snprintf(etag, sizeof etag, "\"%08x:%08x\"",
  475. fileinfo.dosDate, fileinfo.crc);
  476. bool skip_body = req->method == HTTP_HEAD || !fileinfo.uncompressed_size;
  477. bool skip_meta = false;
  478. const char *response = "200 OK";
  479. if (httpd_req_get_hdr_value_str(req, "If-None-Match",
  480. buffer, buffer_size) == ESP_OK &&
  481. strstr(buffer, etag)) {
  482. skip_body = skip_meta = true;
  483. response = "304 Not Modified";
  484. }
  485. len = snprintf(buffer, buffer_size-2,
  486. "HTTP/1.1 %s\r\n"
  487. "Date: %s\r\n"
  488. "Cache-Control: max-age=10\r\n"
  489. "ETag: %s\r\n",
  490. response,
  491. http_now(),
  492. etag);
  493. if (len < buffer_size-2 && !skip_meta) {
  494. const char *mime_extra =
  495. mime_type->flags & MT_CHARSET ? "; charset=\"UTF-8\"" : "";
  496. len += snprintf(buffer + len, buffer_size-2 - len,
  497. "Content-Type: %s%s\r\n"
  498. "Content-Length: %u\r\n"
  499. "Allow: GET, HEAD\r\n"
  500. "Connection: close\r\n"
  501. "Last-Modified: %s\r\n",
  502. mime_type->mime, mime_extra,
  503. fileinfo.uncompressed_size,
  504. http_dos_date(fileinfo.dosDate));
  505. }
  506. if (len >= buffer_size-2) {
  507. err = HTTP_ERR(req, 500, "buffer_size too small");
  508. goto out;
  509. }
  510. buffer[len++] = '\r';
  511. buffer[len++] = '\n';
  512. err = httpd_send_all(req, buffer, len);
  513. if (skip_body || err) {
  514. /* No need to spend time uncompressing the file content */
  515. goto out;
  516. }
  517. if (unzOpenCurrentFile(unz) != UNZ_OK) {
  518. err = HTTP_ERR(req, 500, "Cannot open file in archive");
  519. goto out;
  520. }
  521. file_open = true;
  522. len = fileinfo.uncompressed_size;
  523. while (len) {
  524. size_t chunk = len;
  525. if (chunk > buffer_size)
  526. chunk = buffer_size;
  527. if (unzReadCurrentFile(unz, buffer, chunk) != chunk) {
  528. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  529. goto out;
  530. }
  531. err = httpd_send_all(req, buffer, chunk);
  532. if (err)
  533. goto out;
  534. len -= chunk;
  535. }
  536. err = ESP_OK; /* All good! */
  537. out:
  538. if (file_open)
  539. unzCloseCurrentFile(unz);
  540. if (unz)
  541. unzClose(unz);
  542. if (zip)
  543. free(zip);
  544. if (buffer)
  545. free(buffer);
  546. return err;
  547. }
  548. /*
  549. * Match a URL against a path prefix. To keep httpd from refusing to
  550. * register subpaths, the root template does not include the leading
  551. * '/', but uri is required to have it. Do not include a trailing /
  552. * in prefix; it is implied.
  553. */
  554. static bool httpd_uri_match_prefix(const char *template, const char *uri,
  555. size_t len)
  556. {
  557. #if 0
  558. printf("[HTTP] matching URI \"%.*s\" against template \"%s\"\n",
  559. len, uri, template);
  560. #endif
  561. if (!len-- || *uri++ != '/')
  562. return false;
  563. /* Previous template character (leading '/' implied) */
  564. unsigned char tp = '/';
  565. while (1) {
  566. unsigned char t = *template++;
  567. unsigned char u;
  568. if (!len-- || !(u = *uri++)) {
  569. return !t;
  570. } else if (!t) {
  571. return tp == '/' || u == '/';
  572. } else if (t != u) {
  573. return false;
  574. }
  575. tp = t;
  576. }
  577. }
  578. /* Do not include leading or trailing /; most specific prefix first */
  579. static const httpd_uri_t uri_handlers[] = {
  580. {
  581. .uri = "sys",
  582. .method = HTTP_GET,
  583. .handler = httpd_sys_handler,
  584. .user_ctx = NULL
  585. },
  586. {
  587. .uri = "",
  588. .method = HTTP_GET,
  589. .handler = httpd_static_handler,
  590. .user_ctx = NULL
  591. },
  592. {
  593. .uri = "",
  594. .method = HTTP_HEAD,
  595. .handler = httpd_static_handler,
  596. .user_ctx = NULL
  597. },
  598. {
  599. .uri = "sys",
  600. .method = HTTP_POST,
  601. .handler = httpd_sys_handler,
  602. .user_ctx = NULL
  603. },
  604. };
  605. void my_httpd_stop(void)
  606. {
  607. if (httpd) {
  608. esp_unregister_shutdown_handler(my_httpd_stop);
  609. httpd_stop(httpd);
  610. httpd = NULL;
  611. }
  612. }
  613. void my_httpd_start(void)
  614. {
  615. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  616. httpd_handle_t server;
  617. if (httpd)
  618. return;
  619. config.task_priority = 2;
  620. config.max_open_sockets = 8;
  621. printf("[HTTP] Default stack size: %zu\n", config.stack_size);
  622. config.stack_size <<= 2;
  623. printf("[HTTP] Requesting stack size: %zu\n", config.stack_size);
  624. config.uri_match_fn = httpd_uri_match_prefix;
  625. if (httpd_start(&server, &config) != ESP_OK)
  626. return;
  627. esp_register_shutdown_handler(my_httpd_stop);
  628. httpd = server;
  629. for (size_t i = 0; i < ARRAY_SIZE(uri_handlers); i++) {
  630. const httpd_uri_t * const handler = &uri_handlers[i];
  631. if (httpd_register_uri_handler(httpd, handler))
  632. printf("[HTTP] failed to register URI handler: %s %s\n",
  633. http_method_str(handler->method), handler->uri);
  634. }
  635. printf("[HTTP] httpd started\n");
  636. }