httpd.c 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. #if 0
  239. static esp_err_t httpd_send_ok(httpd_req_t *req)
  240. {
  241. return HTTP_ERR(req, 200, "OK");
  242. }
  243. #endif
  244. static esp_err_t httpd_err_enomem(httpd_req_t *req)
  245. {
  246. return HTTP_ERR(req, 503, "Out of memory");
  247. }
  248. static esp_err_t httpd_err_not_post(httpd_req_t *req)
  249. {
  250. return HTTP_ERR(req, 405, "Only POST allowed");
  251. }
  252. #define HTTPD_ASSERT_POST(req) \
  253. do { \
  254. if ((req)->method != HTTP_POST) \
  255. return httpd_err_not_post(req); \
  256. } while (0)
  257. static esp_err_t httpd_update_done(httpd_req_t *req, const char *what, int err)
  258. {
  259. char *response = NULL;
  260. int len;
  261. unsigned int reboot_time = reboot_delayed();
  262. if (err) {
  263. len = asprintf(&response,
  264. "%s update failed: %s\r\n"
  265. "Rebooting in %u seconds\r\n",
  266. what, firmware_errstr(err), reboot_time);
  267. } else {
  268. len = asprintf(&response,
  269. "%s update complete\r\n"
  270. "Rebooting in %u seconds\r\n",
  271. what, reboot_time);
  272. }
  273. if (!response)
  274. len = 0;
  275. esp_err_t rv = httpd_send_plain(req, err ? 400 : 200, response, len,
  276. HSP_CLOSE|HSP_UNCACHE, reboot_time+5);
  277. if (response)
  278. free(response);
  279. return rv;
  280. }
  281. static esp_err_t httpd_firmware_update(httpd_req_t *req)
  282. {
  283. int rv;
  284. HTTPD_ASSERT_POST(req);
  285. /* XXX: use httpd_fopen_read() here */
  286. rv = firmware_update_start((read_func_t)httpd_req_recv, (token_t)req, false);
  287. if (!rv)
  288. rv = firmware_update_wait(portMAX_DELAY);
  289. return httpd_update_done(req, "Firmware", rv);
  290. }
  291. static esp_err_t httpd_set_config(httpd_req_t *req, const char *query)
  292. {
  293. FILE *f;
  294. int rv1 = 0;
  295. if (query) {
  296. rv1 = set_config_url_string(query);
  297. }
  298. int rv2 = 0;
  299. f = NULL;
  300. if (req->content_len) {
  301. f = httpd_fopen_read(req);
  302. if (!f)
  303. return HTTP_ERR(req, 500, "Unable to get request handle");
  304. }
  305. rv2 = read_config(f, true);
  306. if (f)
  307. fclose(f);
  308. return httpd_update_done(req, "Configuration", rv1 ? rv1 : rv2);
  309. }
  310. static inline bool is_eol(int c)
  311. {
  312. return c == EOF || c == '\0' || c == '\r' || c == '\n';
  313. }
  314. static esp_err_t httpd_set_board_rev(httpd_req_t *req)
  315. {
  316. FILE *f = NULL;
  317. static const char rev_prefix[] = "max80.hw.ver";
  318. static const char rev_valid[] = "MAX80 v";
  319. char *rev_str;
  320. int err = Z_DATA_ERROR;
  321. enum sbr_parse_state {
  322. ps_start,
  323. ps_prefix,
  324. ps_string,
  325. ps_skipline
  326. };
  327. enum sbr_parse_state state;
  328. const char *match_ptr = NULL;
  329. char *p = NULL;
  330. int c;
  331. HTTPD_ASSERT_POST(req);
  332. rev_str = malloc(sizeof board_info.version_str);
  333. if (!rev_str)
  334. return httpd_err_enomem(req);
  335. f = httpd_fopen_read(req);
  336. if (!f) {
  337. free(rev_str);
  338. return HTTP_ERR(req, 500, "Unable to get request handle");
  339. }
  340. state = ps_start;
  341. do {
  342. bool eol;
  343. c = getc(f);
  344. eol = is_eol(c);
  345. switch (state) {
  346. case ps_start:
  347. match_ptr = rev_prefix;
  348. state = ps_prefix;
  349. /* fall through */
  350. case ps_prefix:
  351. if (eol) {
  352. state = ps_start;
  353. } else if (*match_ptr && c == *match_ptr) {
  354. match_ptr++;
  355. } else if (!*match_ptr && c == '=') {
  356. p = rev_str;
  357. state = ps_string;
  358. } else {
  359. state = ps_skipline;
  360. }
  361. break;
  362. case ps_string:
  363. if (eol) {
  364. *p = '\0';
  365. if (!memcmp(rev_str, rev_valid, sizeof rev_valid - 1)) {
  366. /* Otherwise input truncated or invalid */
  367. printf("[HTTP] setting board revision: %s\n", rev_str);
  368. if (!board_info_set(rev_str)) {
  369. setvar_str(status_max80_hw_ver, 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. char timebuf[64];
  396. size_t len;
  397. struct timeval tv;
  398. unsigned long statref;
  399. statref = Max(getvar_uint(config_http_status_refresh), MIN_STATUS_REF);
  400. if (httpd_req_get_url_query_str(req, timebuf, sizeof timebuf) == ESP_OK &&
  401. *timebuf) {
  402. char *ep;
  403. unsigned long newstatref = strtoul(timebuf, &ep, 10);
  404. if (!*ep && newstatref >= MIN_STATUS_REF && newstatref != statref) {
  405. statref = newstatref;
  406. setvar_uint(config_http_status_refresh, statref);
  407. read_config(NULL, true); /* Save changed config */
  408. }
  409. }
  410. fprintf(f, "http.status.refresh=%lu\n", statref);
  411. gettimeofday(&tv,NULL);
  412. const struct tm *tm = localtime(&tv.tv_sec);
  413. len = strftime(timebuf, sizeof timebuf, "localtime=%Y-%m-%d %H:%M:%S.", tm);
  414. snprintf(timebuf+len, sizeof timebuf - len, "%06lu",
  415. (unsigned long)tv.tv_usec);
  416. len += 3;
  417. len += strftime(timebuf+len, sizeof timebuf - len, " %z (%Z)\n", tm);
  418. fwrite(timebuf, 1, len, f);
  419. }
  420. static esp_err_t httpd_get_config_status(httpd_req_t *req, bool status)
  421. {
  422. FILE *f = httpd_fopen_write(req);
  423. if (!f)
  424. return HTTP_ERR(req, 500, "Unable to get request handle");
  425. httpd_resp_set_type(req, text_plain);
  426. httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
  427. if (status)
  428. httpd_get_status_extra(f, req);
  429. int rv = write_sysvars(f, status);
  430. fclose(f);
  431. return rv ? ESP_FAIL : ESP_OK;
  432. }
  433. static esp_err_t httpd_set_lang(httpd_req_t *req, const char *query)
  434. {
  435. if (query) {
  436. int qlen = strlen(query);
  437. setvar_str(config_LANG, qlen && qlen <= MAX_LANG_LEN ? query : NULL);
  438. read_config(NULL, true); /* Save configuration */
  439. }
  440. /*
  441. * 303 = "See other": proper return code saying "this is not what
  442. * you asked for, this is *about* what you asked for"; see spec
  443. * but this is exactly what we want here.
  444. */
  445. return httpd_send_plain(req, 303, NULL, 0, HSP_REFERER, 0);
  446. }
  447. static const char *get_lang(void)
  448. {
  449. const char *lang = getvar_str(config_LANG);
  450. if (!lang)
  451. lang = fallback_language;
  452. return lang;
  453. }
  454. static esp_err_t httpd_get_lang(httpd_req_t *req)
  455. {
  456. const char *lang = get_lang();
  457. return httpd_send_plain(req, 200, lang, strlen(lang), HSP_CRLF, 0);
  458. }
  459. static esp_err_t httpd_lang_redirect(httpd_req_t *req)
  460. {
  461. char lang_buf[sizeof req->uri + MAX_LANG_LEN];
  462. int len = snprintf(lang_buf, sizeof lang_buf, "/lang/%s%s", get_lang(),
  463. req->uri + (sizeof("/sys/lang")-1));
  464. return httpd_send_plain(req, 302, lang_buf, len, 0, 0);
  465. }
  466. #define STRING_MATCHES(str, len, what) \
  467. (((len) == sizeof(what)-1) && !memcmp((str), (what), sizeof(what)-1))
  468. #define STRING_MATCHES_PREFIX(str, len, what) \
  469. (((len) >= sizeof(what)-1) && !memcmp((str), (what), sizeof(what)-1))
  470. static esp_err_t httpd_sys_handler(httpd_req_t *req)
  471. {
  472. httpd_print_request(req);
  473. if (req->method == HTTP_POST &&
  474. !httpd_req_get_hdr_value_len(req, "Content-Length")) {
  475. return HTTP_ERR(req, 411, "Length required");
  476. }
  477. const char *query = strchrnul(req->uri, '?');
  478. if (query < req->uri+5 || memcmp(req->uri, "/sys/", 5))
  479. return httpd_err_enoent(req); /* This should never happen */
  480. const char *file = req->uri + 5;
  481. size_t filelen = query - file;
  482. query = *query == '?' ? query+1 : NULL;
  483. if (STRING_MATCHES_PREFIX(file, filelen, "lang"))
  484. return httpd_lang_redirect(req);
  485. if (STRING_MATCHES(file, filelen, "getstatus"))
  486. return httpd_get_config_status(req, true);
  487. if (STRING_MATCHES(file, filelen, "getconfig"))
  488. return httpd_get_config_status(req, false);
  489. if (STRING_MATCHES(file, filelen, "fwupdate"))
  490. return httpd_firmware_update(req);
  491. if (STRING_MATCHES(file, filelen, "setconfig"))
  492. return httpd_set_config(req, query);
  493. if (STRING_MATCHES(file, filelen, "getlang"))
  494. return httpd_get_lang(req);
  495. if (STRING_MATCHES(file, filelen, "setlang"))
  496. return httpd_set_lang(req, query);
  497. if (STRING_MATCHES(file, filelen, "setboardrev"))
  498. return httpd_set_board_rev(req);
  499. return httpd_err_enoent(req);
  500. }
  501. INCBIN_EXTERN(wwwzip);
  502. struct mime_type {
  503. const char *ext;
  504. uint16_t ext_len;
  505. uint16_t flags;
  506. const char *mime;
  507. };
  508. #define MT_CHARSET 1 /* Add charset to Content-Type */
  509. #define MT_REDIR 2 /* It is a redirect */
  510. static const struct mime_type mime_types[] = {
  511. { ".html", 5, MT_CHARSET, "text/html" },
  512. { ".xhtml", 6, MT_CHARSET, "text/html" },
  513. { ".css", 4, MT_CHARSET, "text/css" },
  514. { ".webp", 5, 0, "image/webp" },
  515. { ".jpg", 4, 0, "image/jpeg" },
  516. { ".png", 4, 0, "image/png" },
  517. { ".ico", 4, 0, "image/png" }, /* favicon.ico */
  518. { ".svg", 4, MT_CHARSET, "image/svg+xml" },
  519. { ".otf", 4, 0, "font/otf" },
  520. { ".ttf", 4, 0, "font/ttf" },
  521. { ".woff", 5, 0, "font/woff" },
  522. { ".woff2", 6, 0, "font/woff2" },
  523. { ".pdf", 4, 0, "application/pdf" },
  524. { ".js", 3, MT_CHARSET, "text/javascript" },
  525. { ".mjs", 4, MT_CHARSET, "text/javascript" },
  526. { ".json", 5, MT_CHARSET, "application/json" },
  527. { ".xml", 4, MT_CHARSET, "text/xml" },
  528. { ".bin", 4, 0, "application/octet-stream" },
  529. { ".fw", 3, 0, "application/octet-stream" },
  530. { ".capt", 5, 0, "application/captive+json" },
  531. { "_redir", 6, MT_REDIR, NULL },
  532. { NULL, 0, MT_CHARSET, "text/plain" } /* default */
  533. };
  534. static esp_err_t httpd_static_handler(httpd_req_t *req)
  535. {
  536. size_t buffer_size = UNZ_BUFSIZE;
  537. const char *uri, *enduri;
  538. bool is_dir;
  539. char *buffer = NULL;
  540. ZIPFILE *zip = NULL;
  541. unzFile unz = NULL;
  542. bool file_open = false;
  543. int err = 0;
  544. size_t len;
  545. httpd_print_request(req);
  546. uri = req->uri;
  547. while (*uri == '/')
  548. uri++; /* Skip leading slashes */
  549. const char *first_slash = NULL, *last_slash = NULL;
  550. for (enduri = uri; *enduri; enduri++) {
  551. if (*enduri == '/') {
  552. last_slash = enduri;
  553. if (!first_slash)
  554. first_slash = enduri;
  555. }
  556. }
  557. if (enduri == uri) {
  558. is_dir = true;
  559. } else if (last_slash == enduri-1) {
  560. is_dir = true;
  561. enduri--; /* Drop terminal slash */
  562. if (first_slash == last_slash)
  563. first_slash = NULL;
  564. } else {
  565. is_dir = false; /* Try the plain filename first */
  566. }
  567. const size_t filename_buffer_size =
  568. (enduri - uri) + 2 + sizeof redir_filename;
  569. if (buffer_size < filename_buffer_size)
  570. buffer_size = filename_buffer_size;
  571. buffer = malloc(buffer_size);
  572. zip = malloc(sizeof *zip);
  573. if (!buffer || !zip) {
  574. err = httpd_err_enomem(req);
  575. goto out;
  576. }
  577. char * const filebase = buffer + 1;
  578. char * const endbase = mempcpy(filebase, uri, enduri - uri);
  579. filebase[-1] = '/';
  580. unz = unzOpen(NULL, (void *)gwwwzipData, gwwwzipSize,
  581. zip, NULL, NULL, NULL, NULL);
  582. if (!unz) {
  583. MSG("[HTTP] unzOpen failed!\n");
  584. err = HTTP_ERR(req, 500, "Cannot open content archive");
  585. goto out;
  586. }
  587. char * const filename = filebase; /* Separate for future needs */
  588. char *endfile = endbase;
  589. unsigned int m;
  590. bool found = false;
  591. for (m = is_dir ? 2 : 0; m < 3; m++) {
  592. char *sx;
  593. switch (m) {
  594. default: /* filename = /url */
  595. endfile = endbase;
  596. break;
  597. case 1: /* filename = /url_redir */
  598. sx = endbase;
  599. endfile = mempcpy(sx, redir_filename, sizeof redir_filename) - 1;
  600. break;
  601. case 2: /* filename = /url/_redir */
  602. sx = endbase - (endbase[-1] == '/');
  603. *sx++ = '/';
  604. endfile = mempcpy(sx, redir_filename, sizeof redir_filename) - 1;
  605. break;
  606. }
  607. *endfile = '\0';
  608. if (!filename)
  609. continue;
  610. filename[-1] = '/';
  611. MSG("trying to open: %s... ", filename);
  612. if (unzLocateFile(unz, filename, 1) == UNZ_OK) {
  613. CMSG("found\n");
  614. found = true;
  615. break;
  616. } else {
  617. CMSG("not found\n");
  618. }
  619. }
  620. if (!found) {
  621. err = httpd_err_enoent(req);
  622. goto out;
  623. }
  624. size_t filelen = endfile - filename;
  625. const struct mime_type *mime_type = mime_types;
  626. /* The default entry with length 0 will always match */
  627. while (mime_type->ext_len) {
  628. len = mime_type->ext_len;
  629. if (len <= filelen && !memcmp(endfile - len, mime_type->ext, len))
  630. break;
  631. mime_type++;
  632. }
  633. MSG("found %s ext %s type %s\n",
  634. filename,
  635. mime_type->ext ? mime_type->ext : "(none)",
  636. mime_type->mime ? mime_type->mime : "(none)");
  637. unz_file_info fileinfo;
  638. memset(&fileinfo, 0, sizeof fileinfo);
  639. unzGetCurrentFileInfo(unz, &fileinfo, NULL, 0, NULL, 0, NULL, 0);
  640. MSG("len %u compressed %u\n",
  641. fileinfo.uncompressed_size,
  642. fileinfo.compressed_size);
  643. /*
  644. * Is it a redirect?
  645. */
  646. if (mime_type->flags & MT_REDIR) {
  647. if (fileinfo.uncompressed_size > buffer_size ||
  648. unzOpenCurrentFile(unz) != UNZ_OK) {
  649. err = HTTP_ERR(req, 500, "Cannot open file in archive");
  650. goto out;
  651. }
  652. file_open = true;
  653. len = fileinfo.uncompressed_size;
  654. if (unzReadCurrentFile(unz, buffer, len) != len) {
  655. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  656. goto out;
  657. }
  658. MSG("redirect: %.*s\n", (int)len, buffer);
  659. err = httpd_send_plain(req, 302, buffer, len, 0, 0);
  660. goto out;
  661. }
  662. /*
  663. * Hopefully the combination of date and CRC
  664. * is strong enough to quality for a "strong" ETag
  665. */
  666. char etag[16+3+1];
  667. snprintf(etag, sizeof etag, "\"%08lx:%08lx\"",
  668. fileinfo.dosDate, fileinfo.crc);
  669. bool skip_body = req->method == HTTP_HEAD || !fileinfo.uncompressed_size;
  670. bool skip_meta = false;
  671. const char *response = "200 OK";
  672. if (httpd_req_get_hdr_value_str(req, "If-None-Match",
  673. buffer, buffer_size) == ESP_OK &&
  674. strstr(buffer, etag)) {
  675. skip_body = skip_meta = true;
  676. response = "304 Not Modified";
  677. }
  678. len = snprintf(buffer, buffer_size-2,
  679. "HTTP/1.1 %s\r\n"
  680. "Date: %s\r\n"
  681. "Cache-Control: max-age=10, immutable\r\n"
  682. "ETag: %s\r\n",
  683. response,
  684. http_now(),
  685. etag);
  686. if (len < buffer_size-2 && !skip_meta) {
  687. const char *mime_extra =
  688. mime_type->flags & MT_CHARSET ? "; charset=\"UTF-8\"" : "";
  689. len += snprintf(buffer + len, buffer_size-2 - len,
  690. "Content-Type: %s%s\r\n"
  691. "Content-Length: %lu\r\n"
  692. "Allow: GET, HEAD\r\n"
  693. "Connection: close\r\n"
  694. "Last-Modified: %s\r\n",
  695. mime_type->mime, mime_extra,
  696. fileinfo.uncompressed_size,
  697. http_dos_date(fileinfo.dosDate));
  698. }
  699. if (len >= buffer_size-2) {
  700. err = HTTP_ERR(req, 500, "buffer_size too small");
  701. goto out;
  702. }
  703. buffer[len++] = '\r';
  704. buffer[len++] = '\n';
  705. err = httpd_send_all(req, buffer, len);
  706. if (skip_body || err) {
  707. /* No need to spend time uncompressing the file content */
  708. goto out;
  709. }
  710. if (unzOpenCurrentFile(unz) != UNZ_OK) {
  711. err = HTTP_ERR(req, 400, "Cannot open file in archive");
  712. goto out;
  713. }
  714. file_open = true;
  715. len = fileinfo.uncompressed_size;
  716. while (len) {
  717. size_t chunk = len;
  718. if (chunk > buffer_size)
  719. chunk = buffer_size;
  720. if (unzReadCurrentFile(unz, buffer, chunk) != chunk) {
  721. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  722. goto out;
  723. }
  724. err = httpd_send_all(req, buffer, chunk);
  725. if (err)
  726. goto out;
  727. len -= chunk;
  728. }
  729. err = ESP_OK; /* All good! */
  730. out:
  731. if (file_open)
  732. unzCloseCurrentFile(unz);
  733. if (unz)
  734. unzClose(unz);
  735. if (zip)
  736. free(zip);
  737. if (buffer)
  738. free(buffer);
  739. return err;
  740. }
  741. /*
  742. * Match a URL against a path prefix. To keep httpd from refusing to
  743. * register subpaths, the root template does not include the leading
  744. * '/', but uri is required to have it. Do not include a trailing /
  745. * in prefix; it is implied.
  746. */
  747. static bool httpd_uri_match_prefix(const char *template, const char *uri,
  748. size_t len)
  749. {
  750. #if 0
  751. printf("[HTTP] matching URI \"%.*s\" against template \"%s\"\n",
  752. len, uri, template);
  753. #endif
  754. if (!len-- || *uri++ != '/')
  755. return false;
  756. /* Previous template character (leading '/' implied) */
  757. unsigned char tp = '/';
  758. while (1) {
  759. unsigned char t = *template++;
  760. unsigned char u;
  761. if (!len-- || !(u = *uri++)) {
  762. return !t;
  763. } else if (!t) {
  764. return tp == '/' || u == '/';
  765. } else if (t != u) {
  766. return false;
  767. }
  768. tp = t;
  769. }
  770. }
  771. /* Do not include leading or trailing /; most specific prefix first */
  772. static const httpd_uri_t uri_handlers[] = {
  773. {
  774. .uri = "sys",
  775. .method = HTTP_GET,
  776. .handler = httpd_sys_handler,
  777. .user_ctx = NULL
  778. },
  779. {
  780. .uri = "",
  781. .method = HTTP_GET,
  782. .handler = httpd_static_handler,
  783. .user_ctx = NULL
  784. },
  785. {
  786. .uri = "",
  787. .method = HTTP_HEAD,
  788. .handler = httpd_static_handler,
  789. .user_ctx = NULL
  790. },
  791. {
  792. .uri = "sys",
  793. .method = HTTP_POST,
  794. .handler = httpd_sys_handler,
  795. .user_ctx = NULL
  796. },
  797. };
  798. void my_httpd_stop(void)
  799. {
  800. if (httpd) {
  801. esp_unregister_shutdown_handler(my_httpd_stop);
  802. httpd_stop(httpd);
  803. httpd = NULL;
  804. }
  805. }
  806. void my_httpd_start(void)
  807. {
  808. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  809. httpd_handle_t server;
  810. if (httpd)
  811. return;
  812. config.task_priority = HTTPD_PRIORITY;
  813. config.max_open_sockets = 10;
  814. printf("[HTTP] Default stack size: %zu\n", config.stack_size);
  815. config.stack_size <<= 2;
  816. printf("[HTTP] Requesting stack size: %zu\n", config.stack_size);
  817. config.uri_match_fn = httpd_uri_match_prefix;
  818. if (httpd_start(&server, &config) != ESP_OK)
  819. return;
  820. esp_register_shutdown_handler(my_httpd_stop);
  821. httpd = server;
  822. for (size_t i = 0; i < ARRAY_SIZE(uri_handlers); i++) {
  823. const httpd_uri_t * const handler = &uri_handlers[i];
  824. if (httpd_register_uri_handler(httpd, handler))
  825. printf("[HTTP] failed to register URI handler: %s %s\n",
  826. http_method_str(handler->method), handler->uri);
  827. }
  828. printf("[HTTP] httpd started\n");
  829. }