2
0

httpd.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. #define MODULE "httpd"
  2. #include "common.h"
  3. #include "fw.h"
  4. #include "httpd.h"
  5. #include "config.h"
  6. #include "boardinfo_esp.h"
  7. #include <incbin.h>
  8. #include <unzipLIB.h>
  9. #define HTTPD_PRIORITY 4
  10. static httpd_handle_t httpd;
  11. static const char fallback_language[] = "en"; /* For unknown language */
  12. static const char redir_filename[] = "_redir"; /* For a directory "file" */
  13. #define MAX_LANG_LEN 16
  14. /* Looping version of httpd_send(); this is a hidden function in the server */
  15. static esp_err_t httpd_send_all(httpd_req_t *req, const void *buf, size_t len)
  16. {
  17. const char *p = buf;
  18. while (len) {
  19. int sent = httpd_send(req, p, len);
  20. if (sent <= 0)
  21. return ESP_ERR_HTTPD_RESP_SEND;
  22. p += sent;
  23. len -= sent;
  24. }
  25. return ESP_OK;
  26. }
  27. /* Create a file pointer from an http request */
  28. static ssize_t httpd_io_read(void *cookie, char *buf, size_t n)
  29. {
  30. int rv = httpd_req_recv(cookie, buf, n);
  31. return rv < 0 ? -1 : rv;
  32. }
  33. static ssize_t httpd_io_write(void *cookie, const char *buf, size_t n)
  34. {
  35. return httpd_resp_send_chunk(cookie, buf, n) ? 0 : n;
  36. }
  37. static int httpd_io_close_write(void *cookie)
  38. {
  39. return httpd_resp_send_chunk(cookie, NULL, 0) ? -1 : 0;
  40. }
  41. static FILE *httpd_fopen_read(httpd_req_t *req)
  42. {
  43. static const cookie_io_functions_t http_io_read_funcs = {
  44. .read = httpd_io_read,
  45. .write = NULL, /* Not writeable */
  46. .seek = NULL, /* Not seekable */
  47. .close = NULL,
  48. };
  49. return fopencookie((void *)req, "r", http_io_read_funcs);
  50. }
  51. static FILE *httpd_fopen_write(httpd_req_t *req)
  52. {
  53. static const cookie_io_functions_t http_io_write_funcs = {
  54. .read = httpd_io_read,
  55. .write = httpd_io_write,
  56. .seek = NULL, /* Not seekable */
  57. .close = httpd_io_close_write
  58. };
  59. return fopencookie((void *)req, "r+", http_io_write_funcs);
  60. }
  61. #define TIMEBUF_LEN 32
  62. static const char *http_date(const struct tm *when)
  63. {
  64. static char timebuf[32];
  65. strftime(timebuf, sizeof timebuf,
  66. "%a, %d %b %Y %H:%M:%S GMT", when);
  67. return timebuf;
  68. }
  69. static const char *http_now(void)
  70. {
  71. time_t t = time(NULL);
  72. return http_date(gmtime(&t));
  73. }
  74. static struct tm *set_weekday(struct tm *tm)
  75. {
  76. /*
  77. * This is a variation on Zeller's congruence with a table lookup
  78. * for the month. The table contains the number of days since March 1,
  79. * mod 7 (for Jan and Feb, from March 1 of the *previous year*.)
  80. *
  81. * Sample test cases:
  82. * Wed Mar 1 0000
  83. * Thu Jan 1 1970
  84. * Wed Apr 27 2022
  85. * Mon Feb 28 2000
  86. * Wed Mar 1 2000
  87. * Sun Feb 28 2100
  88. * Mon Mar 1 2100
  89. */
  90. static const uint8_t md[12] = { 5, 1, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2 };
  91. unsigned int c, y, m, d;
  92. y = tm->tm_year + 1900;
  93. m = tm->tm_mon;
  94. d = tm->tm_mday;
  95. if (m < 2)
  96. y--; /* Jan, Feb */
  97. c = y/100;
  98. /*
  99. * 2 represents the base date of Tue Feb 29 0000
  100. *
  101. * 0 = Sun, 6 = Sat
  102. */
  103. tm->tm_wday = (d + md[m] + y + (y >> 2) - c + (c >> 2) + 2) % 7;
  104. return tm;
  105. }
  106. static const char *http_dos_date(uint32_t dos_date)
  107. {
  108. struct tm tm;
  109. tm.tm_sec = (dos_date << 1) & 63;
  110. tm.tm_min = (dos_date >> 5) & 63;
  111. tm.tm_hour = (dos_date >> 11) & 31;
  112. tm.tm_mday = (dos_date >> 16) & 31;
  113. tm.tm_mon = ((dos_date >> 21) & 15) - 1;
  114. tm.tm_year = (dos_date >> 25) + 80;
  115. tm.tm_isdst = 0; /* Times are stored in GMT */
  116. return http_date(set_weekday(&tm));
  117. }
  118. static const char text_plain[] = "text/plain; charset=\"UTF-8\"";
  119. static void httpd_print_request(const httpd_req_t *req)
  120. {
  121. printf("[HTTP] %s %s\n", http_method_str(req->method), req->uri);
  122. }
  123. static char *httpd_req_get_hdr(httpd_req_t *req, const char *field, size_t *lenp)
  124. {
  125. size_t len = httpd_req_get_hdr_value_len(req, field);
  126. char *val = NULL;
  127. if (len) {
  128. val = malloc(len+1);
  129. if (val) {
  130. httpd_req_get_hdr_value_str(req, field, val, len+1);
  131. val[len] = '\0';
  132. }
  133. }
  134. if (lenp)
  135. *lenp = len;
  136. return val;
  137. }
  138. enum hsp_flags {
  139. HSP_CRLF = 1, /* Append CR LF to the body */
  140. HSP_CLOSE = 2, /* Add a Connection: close header */
  141. HSP_REFERER = 4, /* Use referer as body (for redirects) */
  142. HSP_UNCACHE = 8 /* Wipe caches, please... */
  143. };
  144. static esp_err_t httpd_send_plain(httpd_req_t *req,
  145. unsigned int rcode,
  146. const char *body, size_t blen,
  147. enum hsp_flags flags, unsigned int refresh)
  148. {
  149. char *header = NULL;
  150. esp_err_t err;
  151. int hlen;
  152. const char *now = http_now();
  153. MSG("http_send_plain %u \"%.*s\"\n", rcode, (int)blen, body);
  154. if (rcode > 499)
  155. flags |= HSP_CLOSE;
  156. const char *closer = flags & HSP_CLOSE ? "Connection: close\r\n" : "";
  157. bool redirect = rcode >= 300 && rcode <= 399;
  158. char *referer = NULL;
  159. char *refresher_buf = NULL;
  160. if (refresh || (flags & HSP_REFERER)) {
  161. size_t referer_len;
  162. referer = httpd_req_get_hdr(req, "Referer", &referer_len);
  163. /* "Effective" referer */
  164. const char * const ereferer = referer ? referer : "/";
  165. if (refresh) {
  166. asprintf(&refresher_buf, "Refresh: %u;url=%s\r\n",
  167. refresh, ereferer);
  168. }
  169. if (flags & HSP_REFERER) {
  170. body = ereferer;
  171. blen = referer ? referer_len : 1;
  172. }
  173. }
  174. const char * const refresher = refresher_buf ? refresher_buf : "";
  175. const char * const uncacher = (flags & HSP_UNCACHE)
  176. ? "Clear-Site-Data: \"cache\"\r\n" : "";
  177. if (redirect) {
  178. /* \0 -> \n so don't include it */
  179. size_t blenadj = sizeof("3xx Redirect \r");
  180. /* Always CR LF */
  181. flags |= HSP_CRLF;
  182. /* Drop any CR LF already in the redirect string */
  183. for (size_t bchk = 0; bchk < blen; bchk++) {
  184. if (body[bchk] == '\r' || body[bchk] == '\n') {
  185. blen = bchk;
  186. break;
  187. }
  188. }
  189. hlen = asprintf(&header,
  190. "HTTP/1.1 %u\r\n"
  191. "Content-Type: %s\r\n"
  192. "Content-Length: %zu\r\n"
  193. "Date %s\r\n"
  194. "Location: %.*s\r\n"
  195. "%s%s%s"
  196. "\r\n"
  197. "%3u Redirect ",
  198. rcode, text_plain, blen + blenadj,
  199. now, (int)blen, body,
  200. closer, refresher, uncacher,
  201. rcode);
  202. } else {
  203. size_t blenadj = (flags & HSP_CRLF) ? 2 : 0;
  204. hlen = asprintf(&header,
  205. "HTTP/1.1 %u\r\n"
  206. "Content-Type: %s\r\n"
  207. "Content-Length: %zu\r\n"
  208. "Cache-Control: no-cache\r\n"
  209. "Date: %s\r\n"
  210. "%s%s%s"
  211. "\r\n",
  212. rcode, text_plain, blen + blenadj, now,
  213. closer, refresher, uncacher);
  214. }
  215. if (refresher_buf)
  216. free(refresher_buf);
  217. if (referer)
  218. free(referer);
  219. if (!header)
  220. return ESP_ERR_NO_MEM;
  221. err = httpd_send_all(req, header, hlen);
  222. if (!err && blen) {
  223. err = httpd_send_all(req, body, blen);
  224. }
  225. if (!err && (flags & HSP_CRLF)) {
  226. err = httpd_send_all(req, "\r\n", 2);
  227. }
  228. if (header)
  229. free(header);
  230. return err;
  231. }
  232. #define SL(s) (s), (sizeof(s)-1)
  233. #define HTTP_ERR(r,e,s) httpd_send_plain((r), (e), SL(s), HSP_CRLF, 0)
  234. static esp_err_t httpd_err_enoent(httpd_req_t *req)
  235. {
  236. return HTTP_ERR(req, 404, "URI not found");
  237. }
  238. static esp_err_t httpd_send_ok(httpd_req_t *req)
  239. {
  240. return HTTP_ERR(req, 200, "OK");
  241. }
  242. static esp_err_t httpd_err_enomem(httpd_req_t *req)
  243. {
  244. return HTTP_ERR(req, 503, "Out of memory");
  245. }
  246. static esp_err_t httpd_err_not_post(httpd_req_t *req)
  247. {
  248. return HTTP_ERR(req, 405, "Only POST allowed");
  249. }
  250. #define HTTPD_ASSERT_POST(req) \
  251. do { \
  252. if ((req)->method != HTTP_POST) \
  253. return httpd_err_not_post(req); \
  254. } while (0)
  255. static esp_err_t httpd_update_done(httpd_req_t *req, const char *what, int err)
  256. {
  257. char *response = NULL;
  258. int len;
  259. unsigned int reboot_time = reboot_delayed();
  260. if (err) {
  261. len = asprintf(&response,
  262. "%s update failed: %s\r\n"
  263. "Rebooting in %u seconds\r\n",
  264. what, firmware_errstr(err), reboot_time);
  265. } else {
  266. len = asprintf(&response,
  267. "%s update complete\r\n"
  268. "Rebooting in %u seconds\r\n",
  269. what, reboot_time);
  270. }
  271. if (!response)
  272. len = 0;
  273. esp_err_t rv = httpd_send_plain(req, err ? 400 : 200, response, len,
  274. HSP_CLOSE|HSP_UNCACHE, reboot_time+5);
  275. if (response)
  276. free(response);
  277. return rv;
  278. }
  279. static esp_err_t httpd_firmware_update(httpd_req_t *req)
  280. {
  281. int rv;
  282. HTTPD_ASSERT_POST(req);
  283. /* XXX: use httpd_fopen_read() here */
  284. rv = firmware_update_start((read_func_t)httpd_req_recv, (token_t)req, false);
  285. if (!rv)
  286. rv = firmware_update_wait(portMAX_DELAY);
  287. return httpd_update_done(req, "Firmware", rv);
  288. }
  289. static esp_err_t httpd_set_config(httpd_req_t *req, const char *query)
  290. {
  291. FILE *f;
  292. size_t qlen;
  293. int rv1 = 0;
  294. if (query) {
  295. rv1 = set_config_url_string(query);
  296. }
  297. int rv2 = 0;
  298. f = NULL;
  299. if (req->content_len) {
  300. f = httpd_fopen_read(req);
  301. if (!f)
  302. return HTTP_ERR(req, 500, "Unable to get request handle");
  303. }
  304. rv2 = read_config(f, true);
  305. if (f)
  306. fclose(f);
  307. return httpd_update_done(req, "Configuration", rv1 ? rv1 : rv2);
  308. }
  309. static inline bool is_eol(int c)
  310. {
  311. return c == EOF || c == '\0' || c == '\r' || c == '\n';
  312. }
  313. static esp_err_t httpd_set_board_rev(httpd_req_t *req)
  314. {
  315. FILE *f = NULL;
  316. static const char rev_prefix[] = "max80.hw.ver";
  317. static const char rev_valid[] = "MAX80 v";
  318. char *rev_str;
  319. int err = Z_DATA_ERROR;
  320. enum sbr_parse_state {
  321. ps_start,
  322. ps_prefix,
  323. ps_string,
  324. ps_skipline
  325. };
  326. enum sbr_parse_state state;
  327. const char *match_ptr = NULL;
  328. char *p = NULL;
  329. int c;
  330. HTTPD_ASSERT_POST(req);
  331. rev_str = malloc(sizeof board_info.version_str);
  332. if (!rev_str)
  333. return httpd_err_enomem(req);
  334. f = httpd_fopen_read(req);
  335. if (!f) {
  336. free(rev_str);
  337. return HTTP_ERR(req, 500, "Unable to get request handle");
  338. }
  339. state = ps_start;
  340. do {
  341. bool eol;
  342. c = getc(f);
  343. eol = is_eol(c);
  344. switch (state) {
  345. case ps_start:
  346. match_ptr = rev_prefix;
  347. state = ps_prefix;
  348. /* fall through */
  349. case ps_prefix:
  350. if (eol) {
  351. state = ps_start;
  352. } else if (*match_ptr && c == *match_ptr) {
  353. match_ptr++;
  354. } else if (!*match_ptr && c == '=') {
  355. p = rev_str;
  356. state = ps_string;
  357. } else {
  358. state = ps_skipline;
  359. }
  360. break;
  361. case ps_string:
  362. if (eol) {
  363. *p = '\0';
  364. if (!memcmp(rev_str, rev_valid, sizeof rev_valid - 1)) {
  365. /* Otherwise input truncated or invalid */
  366. printf("[HTTP] setting board revision: %s\n", rev_str);
  367. if (!board_info_set(rev_str)) {
  368. setenv_cond("status.max80.hw.ver",
  369. board_info.version_str);
  370. err = Z_OK;
  371. } else {
  372. err = FWUPDATE_ERR_CONFIG_SAVE;
  373. }
  374. }
  375. state = ps_start;
  376. } else if (p - rev_str >= sizeof board_info.version_str - 1) {
  377. state = ps_skipline;
  378. } else {
  379. *p++ = c;
  380. }
  381. break;
  382. case ps_skipline:
  383. if (eol)
  384. state = ps_start;
  385. break;
  386. }
  387. } while (c != EOF);
  388. fclose(f);
  389. free(rev_str);
  390. return httpd_update_done(req, "board revision", err);
  391. }
  392. #define MIN_STATUS_REF 1 /* Minimum refresh time in s */
  393. static void httpd_get_status_extra(FILE *f, httpd_req_t *req)
  394. {
  395. static const char refresh_time_config[] = "http.status.refresh";
  396. char timebuf[64];
  397. size_t len;
  398. struct timeval tv;
  399. unsigned long statref;
  400. statref = Max(getenv_ul(refresh_time_config, 0), MIN_STATUS_REF);
  401. if (httpd_req_get_url_query_str(req, timebuf, sizeof timebuf) == ESP_OK &&
  402. *timebuf) {
  403. char *ep;
  404. unsigned long newstatref = strtoul(timebuf, &ep, 10);
  405. if (!*ep && newstatref >= MIN_STATUS_REF && newstatref != statref) {
  406. statref = newstatref;
  407. setenv_config(refresh_time_config, timebuf);
  408. read_config(NULL, true); /* Save changed config */
  409. }
  410. }
  411. fprintf(f, "%s=%lu\n", refresh_time_config, statref);
  412. gettimeofday(&tv,NULL);
  413. const struct tm *tm = localtime(&tv.tv_sec);
  414. len = strftime(timebuf, sizeof timebuf, "localtime=%Y-%m-%d %H:%M:%S.", tm);
  415. snprintf(timebuf+len, sizeof timebuf - len, "%06u",
  416. (unsigned long)tv.tv_usec);
  417. len += 3;
  418. len += strftime(timebuf+len, sizeof timebuf - len, " %z (%Z)\n", tm);
  419. fwrite(timebuf, 1, len, f);
  420. }
  421. static esp_err_t httpd_get_config_status(httpd_req_t *req, bool status)
  422. {
  423. FILE *f = httpd_fopen_write(req);
  424. if (!f)
  425. return HTTP_ERR(req, 500, "Unable to get request handle");
  426. httpd_resp_set_type(req, text_plain);
  427. httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
  428. if (status)
  429. httpd_get_status_extra(f, req);
  430. int rv = write_env(f, status);
  431. fclose(f);
  432. return rv ? ESP_FAIL : ESP_OK;
  433. }
  434. static esp_err_t httpd_set_lang(httpd_req_t *req, const char *query)
  435. {
  436. if (query) {
  437. int qlen = strlen(query);
  438. setenv_config("LANG", qlen && qlen <= MAX_LANG_LEN ? query : NULL);
  439. read_config(NULL, true); /* Save configuration */
  440. }
  441. /*
  442. * 303 = "See other": proper return code saying "this is not what
  443. * you asked for, this is *about* what you asked for"; see spec
  444. * but this is exactly what we want here.
  445. */
  446. return httpd_send_plain(req, 303, NULL, 0, HSP_REFERER, 0);
  447. }
  448. static esp_err_t httpd_get_lang(httpd_req_t *req)
  449. {
  450. const char *lang = getenv_def("LANG", "");
  451. return httpd_send_plain(req, 200, lang, strlen(lang), HSP_CRLF, 0);
  452. }
  453. static esp_err_t httpd_lang_redirect(httpd_req_t *req)
  454. {
  455. char lang_buf[sizeof req->uri + MAX_LANG_LEN];
  456. int len = snprintf(lang_buf, sizeof lang_buf, "/lang/%s%s",
  457. getenv_def("LANG", fallback_language),
  458. req->uri + (sizeof("/sys/lang")-1));
  459. return httpd_send_plain(req, 302, lang_buf, len, 0, 0);
  460. }
  461. #define STRING_MATCHES(str, len, what) \
  462. (((len) == sizeof(what)-1) && !memcmp((str), (what), sizeof(what)-1))
  463. #define STRING_MATCHES_PREFIX(str, len, what) \
  464. (((len) >= sizeof(what)-1) && !memcmp((str), (what), sizeof(what)-1))
  465. static esp_err_t httpd_sys_handler(httpd_req_t *req)
  466. {
  467. httpd_print_request(req);
  468. if (req->method == HTTP_POST &&
  469. !httpd_req_get_hdr_value_len(req, "Content-Length")) {
  470. return HTTP_ERR(req, 411, "Length required");
  471. }
  472. const char *query = strchrnul(req->uri, '?');
  473. if (query < req->uri+5 || memcmp(req->uri, "/sys/", 5))
  474. return httpd_err_enoent(req); /* This should never happen */
  475. const char *file = req->uri + 5;
  476. size_t filelen = query - file;
  477. query = *query == '?' ? query+1 : NULL;
  478. if (STRING_MATCHES_PREFIX(file, filelen, "lang"))
  479. return httpd_lang_redirect(req);
  480. if (STRING_MATCHES(file, filelen, "getstatus"))
  481. return httpd_get_config_status(req, true);
  482. if (STRING_MATCHES(file, filelen, "getconfig"))
  483. return httpd_get_config_status(req, false);
  484. if (STRING_MATCHES(file, filelen, "fwupdate"))
  485. return httpd_firmware_update(req);
  486. if (STRING_MATCHES(file, filelen, "setconfig"))
  487. return httpd_set_config(req, query);
  488. if (STRING_MATCHES(file, filelen, "getlang"))
  489. return httpd_get_lang(req);
  490. if (STRING_MATCHES(file, filelen, "setlang"))
  491. return httpd_set_lang(req, query);
  492. if (STRING_MATCHES(file, filelen, "setboardrev"))
  493. return httpd_set_board_rev(req);
  494. return httpd_err_enoent(req);
  495. }
  496. INCBIN_EXTERN(wwwzip);
  497. struct mime_type {
  498. const char *ext;
  499. uint16_t ext_len;
  500. uint16_t flags;
  501. const char *mime;
  502. };
  503. #define MT_CHARSET 1 /* Add charset to Content-Type */
  504. #define MT_REDIR 2 /* It is a redirect */
  505. static const struct mime_type mime_types[] = {
  506. { ".html", 5, MT_CHARSET, "text/html" },
  507. { ".xhtml", 6, MT_CHARSET, "text/html" },
  508. { ".css", 4, MT_CHARSET, "text/css" },
  509. { ".webp", 5, 0, "image/webp" },
  510. { ".jpg", 4, 0, "image/jpeg" },
  511. { ".png", 4, 0, "image/png" },
  512. { ".ico", 4, 0, "image/png" }, /* favicon.ico */
  513. { ".svg", 4, MT_CHARSET, "image/svg+xml" },
  514. { ".otf", 4, 0, "font/otf" },
  515. { ".ttf", 4, 0, "font/ttf" },
  516. { ".woff", 5, 0, "font/woff" },
  517. { ".woff2", 6, 0, "font/woff2" },
  518. { ".pdf", 4, 0, "application/pdf" },
  519. { ".js", 3, MT_CHARSET, "text/javascript" },
  520. { ".mjs", 4, MT_CHARSET, "text/javascript" },
  521. { ".json", 5, MT_CHARSET, "application/json" },
  522. { ".xml", 4, MT_CHARSET, "text/xml" },
  523. { ".bin", 4, 0, "application/octet-stream" },
  524. { ".fw", 3, 0, "application/octet-stream" },
  525. { ".capt", 5, 0, "application/captive+json" },
  526. { "_redir", 6, MT_REDIR, NULL },
  527. { NULL, 0, MT_CHARSET, "text/plain" } /* default */
  528. };
  529. static esp_err_t httpd_static_handler(httpd_req_t *req)
  530. {
  531. size_t buffer_size = UNZ_BUFSIZE;
  532. const char *uri, *enduri;
  533. bool is_dir;
  534. char *buffer = NULL;
  535. ZIPFILE *zip = NULL;
  536. unzFile unz = NULL;
  537. bool file_open = false;
  538. int err = 0;
  539. size_t len;
  540. httpd_print_request(req);
  541. uri = req->uri;
  542. while (*uri == '/')
  543. uri++; /* Skip leading slashes */
  544. const char *first_slash = NULL, *last_slash = NULL;
  545. for (enduri = uri; *enduri; enduri++) {
  546. if (*enduri == '/') {
  547. last_slash = enduri;
  548. if (!first_slash)
  549. first_slash = enduri;
  550. }
  551. }
  552. if (enduri == uri) {
  553. is_dir = true;
  554. } else if (last_slash == enduri-1) {
  555. is_dir = true;
  556. enduri--; /* Drop terminal slash */
  557. if (first_slash == last_slash)
  558. first_slash = NULL;
  559. } else {
  560. is_dir = false; /* Try the plain filename first */
  561. }
  562. const size_t filename_buffer_size =
  563. (enduri - uri) + 2 + sizeof redir_filename;
  564. if (buffer_size < filename_buffer_size)
  565. buffer_size = filename_buffer_size;
  566. buffer = malloc(buffer_size);
  567. zip = malloc(sizeof *zip);
  568. if (!buffer || !zip) {
  569. err = httpd_err_enomem(req);
  570. goto out;
  571. }
  572. char * const filebase = buffer + 1;
  573. char * const endbase = mempcpy(filebase, uri, enduri - uri);
  574. filebase[-1] = '/';
  575. unz = unzOpen(NULL, (void *)gwwwzipData, gwwwzipSize,
  576. zip, NULL, NULL, NULL, NULL);
  577. if (!unz) {
  578. MSG("[HTTP] unzOpen failed!\n");
  579. err = HTTP_ERR(req, 500, "Cannot open content archive");
  580. goto out;
  581. }
  582. char * const filename = filebase; /* Separate for future needs */
  583. char *endfile = endbase;
  584. unsigned int m;
  585. bool found = false;
  586. for (m = is_dir ? 2 : 0; m < 3; m++) {
  587. char *sx;
  588. switch (m) {
  589. default: /* filename = /url */
  590. endfile = endbase;
  591. break;
  592. case 1: /* filename = /url_redir */
  593. sx = endbase;
  594. endfile = mempcpy(sx, redir_filename, sizeof redir_filename) - 1;
  595. break;
  596. case 2: /* filename = /url/_redir */
  597. sx = endbase - (endbase[-1] == '/');
  598. *sx++ = '/';
  599. endfile = mempcpy(sx, redir_filename, sizeof redir_filename) - 1;
  600. break;
  601. }
  602. *endfile = '\0';
  603. if (!filename)
  604. continue;
  605. filename[-1] = '/';
  606. MSG("trying to open: %s... ", filename);
  607. if (unzLocateFile(unz, filename, 1) == UNZ_OK) {
  608. CMSG("found\n");
  609. found = true;
  610. break;
  611. } else {
  612. CMSG("not found\n");
  613. }
  614. }
  615. if (!found) {
  616. err = httpd_err_enoent(req);
  617. goto out;
  618. }
  619. size_t filelen = endfile - filename;
  620. const struct mime_type *mime_type = mime_types;
  621. /* The default entry with length 0 will always match */
  622. while (mime_type->ext_len) {
  623. len = mime_type->ext_len;
  624. if (len <= filelen && !memcmp(endfile - len, mime_type->ext, len))
  625. break;
  626. mime_type++;
  627. }
  628. MSG("found %s ext %s type %s\n",
  629. filename,
  630. mime_type->ext ? mime_type->ext : "(none)",
  631. mime_type->mime ? mime_type->mime : "(none)");
  632. unz_file_info fileinfo;
  633. memset(&fileinfo, 0, sizeof fileinfo);
  634. unzGetCurrentFileInfo(unz, &fileinfo, NULL, 0, NULL, 0, NULL, 0);
  635. MSG("len %u compressed %u\n",
  636. fileinfo.uncompressed_size,
  637. fileinfo.compressed_size);
  638. /*
  639. * Is it a redirect?
  640. */
  641. if (mime_type->flags & MT_REDIR) {
  642. if (fileinfo.uncompressed_size > buffer_size ||
  643. unzOpenCurrentFile(unz) != UNZ_OK) {
  644. err = HTTP_ERR(req, 500, "Cannot open file in archive");
  645. goto out;
  646. }
  647. file_open = true;
  648. len = fileinfo.uncompressed_size;
  649. if (unzReadCurrentFile(unz, buffer, len) != len) {
  650. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  651. goto out;
  652. }
  653. MSG("redirect: %.*s\n", (int)len, buffer);
  654. err = httpd_send_plain(req, 302, buffer, len, 0, 0);
  655. goto out;
  656. }
  657. /*
  658. * Hopefully the combination of date and CRC
  659. * is strong enough to quality for a "strong" ETag
  660. */
  661. char etag[16+3+1];
  662. snprintf(etag, sizeof etag, "\"%08x:%08x\"",
  663. fileinfo.dosDate, fileinfo.crc);
  664. bool skip_body = req->method == HTTP_HEAD || !fileinfo.uncompressed_size;
  665. bool skip_meta = false;
  666. const char *response = "200 OK";
  667. if (httpd_req_get_hdr_value_str(req, "If-None-Match",
  668. buffer, buffer_size) == ESP_OK &&
  669. strstr(buffer, etag)) {
  670. skip_body = skip_meta = true;
  671. response = "304 Not Modified";
  672. }
  673. len = snprintf(buffer, buffer_size-2,
  674. "HTTP/1.1 %s\r\n"
  675. "Date: %s\r\n"
  676. "Cache-Control: max-age=10, immutable\r\n"
  677. "ETag: %s\r\n",
  678. response,
  679. http_now(),
  680. etag);
  681. if (len < buffer_size-2 && !skip_meta) {
  682. const char *mime_extra =
  683. mime_type->flags & MT_CHARSET ? "; charset=\"UTF-8\"" : "";
  684. len += snprintf(buffer + len, buffer_size-2 - len,
  685. "Content-Type: %s%s\r\n"
  686. "Content-Length: %u\r\n"
  687. "Allow: GET, HEAD\r\n"
  688. "Connection: close\r\n"
  689. "Last-Modified: %s\r\n",
  690. mime_type->mime, mime_extra,
  691. fileinfo.uncompressed_size,
  692. http_dos_date(fileinfo.dosDate));
  693. }
  694. if (len >= buffer_size-2) {
  695. err = HTTP_ERR(req, 500, "buffer_size too small");
  696. goto out;
  697. }
  698. buffer[len++] = '\r';
  699. buffer[len++] = '\n';
  700. err = httpd_send_all(req, buffer, len);
  701. if (skip_body || err) {
  702. /* No need to spend time uncompressing the file content */
  703. goto out;
  704. }
  705. if (unzOpenCurrentFile(unz) != UNZ_OK) {
  706. err = HTTP_ERR(req, 400, "Cannot open file in archive");
  707. goto out;
  708. }
  709. file_open = true;
  710. len = fileinfo.uncompressed_size;
  711. while (len) {
  712. size_t chunk = len;
  713. if (chunk > buffer_size)
  714. chunk = buffer_size;
  715. if (unzReadCurrentFile(unz, buffer, chunk) != chunk) {
  716. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  717. goto out;
  718. }
  719. err = httpd_send_all(req, buffer, chunk);
  720. if (err)
  721. goto out;
  722. len -= chunk;
  723. }
  724. err = ESP_OK; /* All good! */
  725. out:
  726. if (file_open)
  727. unzCloseCurrentFile(unz);
  728. if (unz)
  729. unzClose(unz);
  730. if (zip)
  731. free(zip);
  732. if (buffer)
  733. free(buffer);
  734. return err;
  735. }
  736. /*
  737. * Match a URL against a path prefix. To keep httpd from refusing to
  738. * register subpaths, the root template does not include the leading
  739. * '/', but uri is required to have it. Do not include a trailing /
  740. * in prefix; it is implied.
  741. */
  742. static bool httpd_uri_match_prefix(const char *template, const char *uri,
  743. size_t len)
  744. {
  745. #if 0
  746. printf("[HTTP] matching URI \"%.*s\" against template \"%s\"\n",
  747. len, uri, template);
  748. #endif
  749. if (!len-- || *uri++ != '/')
  750. return false;
  751. /* Previous template character (leading '/' implied) */
  752. unsigned char tp = '/';
  753. while (1) {
  754. unsigned char t = *template++;
  755. unsigned char u;
  756. if (!len-- || !(u = *uri++)) {
  757. return !t;
  758. } else if (!t) {
  759. return tp == '/' || u == '/';
  760. } else if (t != u) {
  761. return false;
  762. }
  763. tp = t;
  764. }
  765. }
  766. /* Do not include leading or trailing /; most specific prefix first */
  767. static const httpd_uri_t uri_handlers[] = {
  768. {
  769. .uri = "sys",
  770. .method = HTTP_GET,
  771. .handler = httpd_sys_handler,
  772. .user_ctx = NULL
  773. },
  774. {
  775. .uri = "",
  776. .method = HTTP_GET,
  777. .handler = httpd_static_handler,
  778. .user_ctx = NULL
  779. },
  780. {
  781. .uri = "",
  782. .method = HTTP_HEAD,
  783. .handler = httpd_static_handler,
  784. .user_ctx = NULL
  785. },
  786. {
  787. .uri = "sys",
  788. .method = HTTP_POST,
  789. .handler = httpd_sys_handler,
  790. .user_ctx = NULL
  791. },
  792. };
  793. void my_httpd_stop(void)
  794. {
  795. if (httpd) {
  796. esp_unregister_shutdown_handler(my_httpd_stop);
  797. httpd_stop(httpd);
  798. httpd = NULL;
  799. }
  800. }
  801. void my_httpd_start(void)
  802. {
  803. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  804. httpd_handle_t server;
  805. if (httpd)
  806. return;
  807. config.task_priority = HTTPD_PRIORITY;
  808. config.max_open_sockets = 10;
  809. printf("[HTTP] Default stack size: %zu\n", config.stack_size);
  810. config.stack_size <<= 2;
  811. printf("[HTTP] Requesting stack size: %zu\n", config.stack_size);
  812. config.uri_match_fn = httpd_uri_match_prefix;
  813. if (httpd_start(&server, &config) != ESP_OK)
  814. return;
  815. esp_register_shutdown_handler(my_httpd_stop);
  816. httpd = server;
  817. for (size_t i = 0; i < ARRAY_SIZE(uri_handlers); i++) {
  818. const httpd_uri_t * const handler = &uri_handlers[i];
  819. if (httpd_register_uri_handler(httpd, handler))
  820. printf("[HTTP] failed to register URI handler: %s %s\n",
  821. http_method_str(handler->method), handler->uri);
  822. }
  823. printf("[HTTP] httpd started\n");
  824. }