httpd.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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. HSP_REFERER = 8 /* Use referer as body (for redirects) */
  123. };
  124. static void httpd_print_request(const httpd_req_t *req)
  125. {
  126. printf("[HTTP] %s %s\n", http_method_str(req->method), req->uri);
  127. }
  128. static char *httpd_req_get_hdr(httpd_req_t *req, const char *field, size_t *lenp)
  129. {
  130. size_t len = httpd_req_get_hdr_value_len(req, field);
  131. char *val = NULL;
  132. if (len) {
  133. val = malloc(len+1);
  134. if (val) {
  135. httpd_req_get_hdr_value_str(req, field, val, len+1);
  136. val[len] = '\0';
  137. }
  138. }
  139. if (lenp)
  140. *lenp = len;
  141. return val;
  142. }
  143. static esp_err_t httpd_send_plain(httpd_req_t *req,
  144. unsigned int rcode,
  145. const char *body, size_t blen,
  146. enum hsp_flags flags, unsigned int refresh)
  147. {
  148. char *header = NULL;
  149. esp_err_t err;
  150. int hlen;
  151. const char *now = http_now();
  152. MSG("http_send_plain %u \"%.*s\"\n", rcode, (int)blen, body);
  153. if (rcode > 499)
  154. flags |= HSP_CLOSE;
  155. const char *closer = flags & HSP_CLOSE ? "Connection: close\r\n" : "";
  156. bool redirect = rcode >= 300 && rcode <= 399;
  157. char *referer = NULL;
  158. char *refresher_buf = NULL;
  159. if (refresh || (flags & HSP_REFERER)) {
  160. size_t referer_len;
  161. referer = httpd_req_get_hdr(req, "Referer", &referer_len);
  162. /* "Effective" referer */
  163. const char * const ereferer = referer ? referer : "/";
  164. if (refresh) {
  165. asprintf(&refresher_buf, "Refresh: %u;url=%s\r\n",
  166. refresh, ereferer);
  167. }
  168. if (flags & HSP_REFERER) {
  169. body = ereferer;
  170. blen = referer ? referer_len : 1;
  171. }
  172. }
  173. const char * const refresher = refresher_buf ? refresher_buf : "";
  174. if (redirect) {
  175. /* \0 -> \n so don't include it */
  176. size_t blenadj = sizeof("3xx Redirect \r");
  177. /* Always CR LF */
  178. flags |= HSP_CRLF;
  179. /* Drop any CR LF already in the redirect string */
  180. for (size_t bchk = 0; bchk < blen; bchk++) {
  181. if (body[bchk] == '\r' || body[bchk] == '\n') {
  182. blen = bchk;
  183. break;
  184. }
  185. }
  186. hlen = asprintf(&header,
  187. "HTTP/1.1 %u\r\n"
  188. "Content-Type: %s\r\n"
  189. "Content-Length: %zu\r\n"
  190. "Date %s\r\n"
  191. "Location: %.*s\r\n"
  192. "%s%s"
  193. "\r\n"
  194. "%3u Redirect ",
  195. rcode, text_plain, blen + blenadj,
  196. now, (int)blen, body, closer, refresher, rcode);
  197. } else {
  198. size_t blenadj = (flags & HSP_CRLF) ? 2 : 0;
  199. hlen = asprintf(&header,
  200. "HTTP/1.1 %u\r\n"
  201. "Content-Type: %s\r\n"
  202. "Content-Length: %zu\r\n"
  203. "Cache-Control: no-cache\r\n"
  204. "Date: %s\r\n"
  205. "%s%s"
  206. "\r\n",
  207. rcode, text_plain, blen + blenadj, now,
  208. closer, refresher);
  209. }
  210. if (refresher_buf)
  211. free(refresher_buf);
  212. if (referer)
  213. free(referer);
  214. if (!header)
  215. return ESP_ERR_NO_MEM;
  216. err = httpd_send_all(req, header, hlen);
  217. if (!err && blen) {
  218. err = httpd_send_all(req, body, blen);
  219. }
  220. if (!err && (flags & HSP_CRLF)) {
  221. err = httpd_send_all(req, "\r\n", 2);
  222. }
  223. if (header)
  224. free(header);
  225. /* Sending ESP_FAIL causes the socket to be immediately closed */
  226. return err ? err : (flags & HSP_CLOSE_SOCKET) ? ESP_FAIL : ESP_OK;
  227. }
  228. #define SL(s) (s), (sizeof(s)-1)
  229. #define HTTP_ERR(r,e,s) httpd_send_plain((r), (e), SL(s), HSP_CRLF, 0)
  230. static esp_err_t httpd_err_enoent(httpd_req_t *req)
  231. {
  232. return HTTP_ERR(req, 404, "URI not found");
  233. }
  234. static esp_err_t httpd_send_ok(httpd_req_t *req)
  235. {
  236. return HTTP_ERR(req, 200, "OK");
  237. }
  238. static esp_err_t httpd_err_enomem(httpd_req_t *req)
  239. {
  240. return HTTP_ERR(req, 503, "Out of memory");
  241. }
  242. static esp_err_t httpd_update_done(httpd_req_t *req, const char *what, int err)
  243. {
  244. char *response = NULL;
  245. int len;
  246. unsigned int reboot_time = reboot_delayed();
  247. if (err) {
  248. len = asprintf(&response,
  249. "%s update failed: %s\r\n"
  250. "Rebooting in %u seconds\r\n",
  251. what, firmware_errstr(err), reboot_time);
  252. } else {
  253. len = asprintf(&response,
  254. "%s update complete\r\n"
  255. "Rebooting in %u seconds\r\n",
  256. what, reboot_time);
  257. }
  258. if (!response)
  259. len = 0;
  260. esp_err_t rv = httpd_send_plain(req, err ? 400 : 200, response, len,
  261. HSP_CLOSE, reboot_time+5);
  262. if (response)
  263. free(response);
  264. return rv;
  265. }
  266. static esp_err_t httpd_firmware_update(httpd_req_t *req)
  267. {
  268. int rv;
  269. /* XXX: use httpd_fopen_read() here */
  270. rv = firmware_update((read_func_t)httpd_req_recv, (token_t)req);
  271. return httpd_update_done(req, "Firmware", rv);
  272. }
  273. static esp_err_t httpd_set_config(httpd_req_t *req, const char *query)
  274. {
  275. FILE *f;
  276. size_t qlen;
  277. int rv1 = 0;
  278. if (query) {
  279. rv1 = set_config_url_string(query);
  280. }
  281. int rv2 = 0;
  282. f = NULL;
  283. if (req->content_len) {
  284. f = httpd_fopen_read(req);
  285. if (!f)
  286. return HTTP_ERR(req, 500, "Unable to get request handle");
  287. }
  288. rv2 = read_config(f, true);
  289. if (f)
  290. fclose(f);
  291. return httpd_update_done(req, "Configuration", rv1 ? rv1 : rv2);
  292. }
  293. static esp_err_t httpd_get_config(httpd_req_t *req)
  294. {
  295. FILE *f = httpd_fopen_write(req);
  296. if (!f)
  297. return HTTP_ERR(req, 500, "Unable to get request handle");
  298. httpd_resp_set_type(req, text_plain);
  299. httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
  300. int rv = write_config(f);
  301. fclose(f);
  302. return rv ? ESP_FAIL : ESP_OK;
  303. }
  304. static esp_err_t httpd_set_lang(httpd_req_t *req, const char *query)
  305. {
  306. if (query) {
  307. int qlen = strlen(query);
  308. setenv_config("LANG", qlen && qlen <= MAX_LANG_LEN ? query : NULL);
  309. read_config(NULL, true); /* Save configuration */
  310. }
  311. /*
  312. * 303 = "See other": proper return code saying "this is not what
  313. * you asked for, this is *about* what you asked for"; see spec
  314. * but this is exactly what we want here.
  315. */
  316. return httpd_send_plain(req, 303, NULL, 0, HSP_REFERER, 0);
  317. }
  318. static esp_err_t httpd_get_lang(httpd_req_t *req)
  319. {
  320. const char *lang = getenv_def("LANG", "");
  321. return httpd_send_plain(req, 200, lang, strlen(lang), HSP_CRLF, 0);
  322. }
  323. static esp_err_t httpd_lang_redirect(httpd_req_t *req)
  324. {
  325. char lang_buf[sizeof("/lang/") + MAX_LANG_LEN];
  326. int len = snprintf(lang_buf, sizeof lang_buf, "/lang/%s",
  327. getenv_def("LANG", fallback_language));
  328. return httpd_send_plain(req, 302, lang_buf, len, 0, 0);
  329. }
  330. #define STRING_MATCHES(str, len, what) \
  331. (((len) == sizeof(what)-1) && !memcmp((str), (what), sizeof(what)-1))
  332. static esp_err_t httpd_sys_handler(httpd_req_t *req)
  333. {
  334. httpd_print_request(req);
  335. if (req->method == HTTP_POST &&
  336. !httpd_req_get_hdr_value_len(req, "Content-Length")) {
  337. return HTTP_ERR(req, 411, "Length required");
  338. }
  339. const char *query = strchrnul(req->uri, '?');
  340. if (query < req->uri+5 || memcmp(req->uri, "/sys/", 5))
  341. return httpd_err_enoent(req); /* This should never happen */
  342. const char *file = req->uri + 5;
  343. size_t filelen = query - file;
  344. query = *query == '?' ? query+1 : NULL;
  345. if (STRING_MATCHES(file, filelen, "lang"))
  346. return httpd_lang_redirect(req);
  347. if (STRING_MATCHES(file, filelen, "getconfig"))
  348. return httpd_get_config(req);
  349. if (req->method == HTTP_POST && STRING_MATCHES(file, filelen, "fwupdate"))
  350. return httpd_firmware_update(req);
  351. if (STRING_MATCHES(file, filelen, "setconfig"))
  352. return httpd_set_config(req, query);
  353. if (STRING_MATCHES(file, filelen, "getlang"))
  354. return httpd_get_lang(req);
  355. if (STRING_MATCHES(file, filelen, "setlang"))
  356. return httpd_set_lang(req, query);
  357. return httpd_err_enoent(req);
  358. }
  359. INCBIN_EXTERN(wwwzip);
  360. struct mime_type {
  361. const char *ext;
  362. uint16_t ext_len;
  363. uint16_t flags;
  364. const char *mime;
  365. };
  366. #define MT_CHARSET 1 /* Add charset to Content-Type */
  367. #define MT_REDIR 2 /* It is a redirect */
  368. static const struct mime_type mime_types[] = {
  369. { ".html", 5, MT_CHARSET, "text/html" },
  370. { ".xhtml", 6, MT_CHARSET, "text/html" },
  371. { ".css", 4, MT_CHARSET, "text/css" },
  372. { ".webp", 5, 0, "image/webp" },
  373. { ".jpg", 4, 0, "image/jpeg" },
  374. { ".png", 4, 0, "image/png" },
  375. { ".ico", 4, 0, "image/png" }, /* favicon.ico */
  376. { ".svg", 4, MT_CHARSET, "image/svg+xml" },
  377. { ".otf", 4, 0, "font/otf" },
  378. { ".ttf", 4, 0, "font/ttf" },
  379. { ".woff", 5, 0, "font/woff" },
  380. { ".woff2", 6, 0, "font/woff2" },
  381. { ".pdf", 4, 0, "application/pdf" },
  382. { ".js", 3, MT_CHARSET, "text/javascript" },
  383. { ".mjs", 4, MT_CHARSET, "text/javascript" },
  384. { ".json", 5, MT_CHARSET, "application/json" },
  385. { ".xml", 4, MT_CHARSET, "text/xml" },
  386. { ".bin", 4, 0, "application/octet-stream" },
  387. { ".fw", 3, 0, "application/octet-stream" },
  388. { "_redir", 6, MT_REDIR, NULL },
  389. { NULL, 0, MT_CHARSET, "text/plain" } /* default */
  390. };
  391. static esp_err_t httpd_static_handler(httpd_req_t *req)
  392. {
  393. size_t buffer_size = UNZ_BUFSIZE;
  394. const char *uri, *enduri;
  395. bool is_dir;
  396. char *buffer = NULL;
  397. ZIPFILE *zip = NULL;
  398. unzFile unz = NULL;
  399. bool file_open = false;
  400. int err = 0;
  401. size_t len;
  402. httpd_print_request(req);
  403. uri = req->uri;
  404. while (*uri == '/')
  405. uri++; /* Skip leading slashes */
  406. const char *first_slash = NULL, *last_slash = NULL;
  407. for (enduri = uri; *enduri; enduri++) {
  408. if (*enduri == '/') {
  409. last_slash = enduri;
  410. if (!first_slash)
  411. first_slash = enduri;
  412. }
  413. }
  414. if (enduri == uri) {
  415. is_dir = true;
  416. } else if (last_slash == enduri-1) {
  417. is_dir = true;
  418. enduri--; /* Drop terminal slash */
  419. if (first_slash == last_slash)
  420. first_slash = NULL;
  421. } else {
  422. is_dir = false; /* Try the plain filename first */
  423. }
  424. const size_t filename_buffer_size =
  425. (enduri - uri) + 2 + sizeof redir_filename;
  426. if (buffer_size < filename_buffer_size)
  427. buffer_size = filename_buffer_size;
  428. buffer = malloc(buffer_size);
  429. zip = malloc(sizeof *zip);
  430. if (!buffer || !zip) {
  431. err = httpd_err_enomem(req);
  432. goto out;
  433. }
  434. char * const filebase = buffer + 1;
  435. char * const endbase = mempcpy(filebase, uri, enduri - uri);
  436. filebase[-1] = '/';
  437. unz = unzOpen(NULL, (void *)gwwwzipData, gwwwzipSize,
  438. zip, NULL, NULL, NULL, NULL);
  439. if (!unz) {
  440. MSG("[HTTP] unzOpen failed!\n");
  441. err = HTTP_ERR(req, 500, "Cannot open content archive");
  442. goto out;
  443. }
  444. char * const filename = filebase; /* Separate for future needs */
  445. char *endfile = endbase;
  446. unsigned int m;
  447. bool found = false;
  448. for (m = is_dir ? 2 : 0; m < 3; m++) {
  449. char *sx;
  450. switch (m) {
  451. default: /* filename = /url */
  452. endfile = endbase;
  453. break;
  454. case 1: /* filename = /url_redir */
  455. sx = endbase;
  456. endfile = mempcpy(sx, redir_filename, sizeof redir_filename) - 1;
  457. break;
  458. case 2: /* filename = /url/_redir */
  459. sx = endbase - (endbase[-1] == '/');
  460. *sx++ = '/';
  461. endfile = mempcpy(sx, redir_filename, sizeof redir_filename) - 1;
  462. break;
  463. }
  464. *endfile = '\0';
  465. if (!filename)
  466. continue;
  467. filename[-1] = '/';
  468. MSG("trying to open: %s... ", filename);
  469. if (unzLocateFile(unz, filename, 1) == UNZ_OK) {
  470. CMSG("found\n");
  471. found = true;
  472. break;
  473. } else {
  474. CMSG("not found\n");
  475. }
  476. }
  477. if (!found) {
  478. err = httpd_err_enoent(req);
  479. goto out;
  480. }
  481. size_t filelen = endfile - filename;
  482. const struct mime_type *mime_type = mime_types;
  483. /* The default entry with length 0 will always match */
  484. while (mime_type->ext_len) {
  485. len = mime_type->ext_len;
  486. if (len <= filelen && !memcmp(endfile - len, mime_type->ext, len))
  487. break;
  488. mime_type++;
  489. }
  490. MSG("found %s ext %s type %s\n",
  491. filename,
  492. mime_type->ext ? mime_type->ext : "(none)",
  493. mime_type->mime ? mime_type->mime : "(none)");
  494. unz_file_info fileinfo;
  495. memset(&fileinfo, 0, sizeof fileinfo);
  496. unzGetCurrentFileInfo(unz, &fileinfo, NULL, 0, NULL, 0, NULL, 0);
  497. MSG("len %u compressed %u\n",
  498. fileinfo.uncompressed_size,
  499. fileinfo.compressed_size);
  500. /*
  501. * Is it a redirect?
  502. */
  503. if (mime_type->flags & MT_REDIR) {
  504. if (fileinfo.uncompressed_size > buffer_size ||
  505. unzOpenCurrentFile(unz) != UNZ_OK) {
  506. err = HTTP_ERR(req, 500, "Cannot open file in archive");
  507. goto out;
  508. }
  509. file_open = true;
  510. len = fileinfo.uncompressed_size;
  511. if (unzReadCurrentFile(unz, buffer, len) != len) {
  512. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  513. goto out;
  514. }
  515. MSG("redirect: %.*s\n", (int)len, buffer);
  516. err = httpd_send_plain(req, 302, buffer, len, 0, 0);
  517. goto out;
  518. }
  519. /*
  520. * Hopefully the combination of date and CRC
  521. * is strong enough to quality for a "strong" ETag
  522. */
  523. char etag[16+3+1];
  524. snprintf(etag, sizeof etag, "\"%08x:%08x\"",
  525. fileinfo.dosDate, fileinfo.crc);
  526. bool skip_body = req->method == HTTP_HEAD || !fileinfo.uncompressed_size;
  527. bool skip_meta = false;
  528. const char *response = "200 OK";
  529. if (httpd_req_get_hdr_value_str(req, "If-None-Match",
  530. buffer, buffer_size) == ESP_OK &&
  531. strstr(buffer, etag)) {
  532. skip_body = skip_meta = true;
  533. response = "304 Not Modified";
  534. }
  535. len = snprintf(buffer, buffer_size-2,
  536. "HTTP/1.1 %s\r\n"
  537. "Date: %s\r\n"
  538. "Cache-Control: max-age=10, immutable\r\n"
  539. "ETag: %s\r\n",
  540. response,
  541. http_now(),
  542. etag);
  543. if (len < buffer_size-2 && !skip_meta) {
  544. const char *mime_extra =
  545. mime_type->flags & MT_CHARSET ? "; charset=\"UTF-8\"" : "";
  546. len += snprintf(buffer + len, buffer_size-2 - len,
  547. "Content-Type: %s%s\r\n"
  548. "Content-Length: %u\r\n"
  549. "Allow: GET, HEAD\r\n"
  550. "Connection: close\r\n"
  551. "Last-Modified: %s\r\n",
  552. mime_type->mime, mime_extra,
  553. fileinfo.uncompressed_size,
  554. http_dos_date(fileinfo.dosDate));
  555. }
  556. if (len >= buffer_size-2) {
  557. err = HTTP_ERR(req, 500, "buffer_size too small");
  558. goto out;
  559. }
  560. buffer[len++] = '\r';
  561. buffer[len++] = '\n';
  562. err = httpd_send_all(req, buffer, len);
  563. if (skip_body || err) {
  564. /* No need to spend time uncompressing the file content */
  565. goto out;
  566. }
  567. if (unzOpenCurrentFile(unz) != UNZ_OK) {
  568. err = HTTP_ERR(req, 400, "Cannot open file in archive");
  569. goto out;
  570. }
  571. file_open = true;
  572. len = fileinfo.uncompressed_size;
  573. while (len) {
  574. size_t chunk = len;
  575. if (chunk > buffer_size)
  576. chunk = buffer_size;
  577. if (unzReadCurrentFile(unz, buffer, chunk) != chunk) {
  578. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  579. goto out;
  580. }
  581. err = httpd_send_all(req, buffer, chunk);
  582. if (err)
  583. goto out;
  584. len -= chunk;
  585. }
  586. err = ESP_OK; /* All good! */
  587. out:
  588. if (file_open)
  589. unzCloseCurrentFile(unz);
  590. if (unz)
  591. unzClose(unz);
  592. if (zip)
  593. free(zip);
  594. if (buffer)
  595. free(buffer);
  596. return err;
  597. }
  598. /*
  599. * Match a URL against a path prefix. To keep httpd from refusing to
  600. * register subpaths, the root template does not include the leading
  601. * '/', but uri is required to have it. Do not include a trailing /
  602. * in prefix; it is implied.
  603. */
  604. static bool httpd_uri_match_prefix(const char *template, const char *uri,
  605. size_t len)
  606. {
  607. #if 0
  608. printf("[HTTP] matching URI \"%.*s\" against template \"%s\"\n",
  609. len, uri, template);
  610. #endif
  611. if (!len-- || *uri++ != '/')
  612. return false;
  613. /* Previous template character (leading '/' implied) */
  614. unsigned char tp = '/';
  615. while (1) {
  616. unsigned char t = *template++;
  617. unsigned char u;
  618. if (!len-- || !(u = *uri++)) {
  619. return !t;
  620. } else if (!t) {
  621. return tp == '/' || u == '/';
  622. } else if (t != u) {
  623. return false;
  624. }
  625. tp = t;
  626. }
  627. }
  628. /* Do not include leading or trailing /; most specific prefix first */
  629. static const httpd_uri_t uri_handlers[] = {
  630. {
  631. .uri = "sys",
  632. .method = HTTP_GET,
  633. .handler = httpd_sys_handler,
  634. .user_ctx = NULL
  635. },
  636. {
  637. .uri = "",
  638. .method = HTTP_GET,
  639. .handler = httpd_static_handler,
  640. .user_ctx = NULL
  641. },
  642. {
  643. .uri = "",
  644. .method = HTTP_HEAD,
  645. .handler = httpd_static_handler,
  646. .user_ctx = NULL
  647. },
  648. {
  649. .uri = "sys",
  650. .method = HTTP_POST,
  651. .handler = httpd_sys_handler,
  652. .user_ctx = NULL
  653. },
  654. };
  655. void my_httpd_stop(void)
  656. {
  657. if (httpd) {
  658. esp_unregister_shutdown_handler(my_httpd_stop);
  659. httpd_stop(httpd);
  660. httpd = NULL;
  661. }
  662. }
  663. void my_httpd_start(void)
  664. {
  665. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  666. httpd_handle_t server;
  667. if (httpd)
  668. return;
  669. config.task_priority = HTTPD_PRIORITY;
  670. config.max_open_sockets = 10;
  671. printf("[HTTP] Default stack size: %zu\n", config.stack_size);
  672. config.stack_size <<= 2;
  673. printf("[HTTP] Requesting stack size: %zu\n", config.stack_size);
  674. config.uri_match_fn = httpd_uri_match_prefix;
  675. if (httpd_start(&server, &config) != ESP_OK)
  676. return;
  677. esp_register_shutdown_handler(my_httpd_stop);
  678. httpd = server;
  679. for (size_t i = 0; i < ARRAY_SIZE(uri_handlers); i++) {
  680. const httpd_uri_t * const handler = &uri_handlers[i];
  681. if (httpd_register_uri_handler(httpd, handler))
  682. printf("[HTTP] failed to register URI handler: %s %s\n",
  683. http_method_str(handler->method), handler->uri);
  684. }
  685. printf("[HTTP] httpd started\n");
  686. }