httpd.c 20 KB

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