httpd.c 25 KB

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