2
0

httpd.c 20 KB

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