httpd.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. #define MODULE "httpd"
  2. #include "common.h"
  3. #include "fw.h"
  4. #include "httpd.h"
  5. #include "config.h"
  6. #include <incbin.h>
  7. #include <unzipLIB.h>
  8. static httpd_handle_t httpd;
  9. /* Looping version of httpd_send(); this is a hidden function in the server */
  10. static esp_err_t httpd_send_all(httpd_req_t *req, const void *buf, size_t len)
  11. {
  12. const char *p = buf;
  13. while (len) {
  14. int sent = httpd_send(req, p, len);
  15. if (sent <= 0)
  16. return ESP_ERR_HTTPD_RESP_SEND;
  17. p += sent;
  18. len -= sent;
  19. }
  20. return ESP_OK;
  21. }
  22. /* Create a file pointer from an http request */
  23. static ssize_t httpd_io_read(void *cookie, char *buf, size_t n)
  24. {
  25. int rv = httpd_req_recv(cookie, buf, n);
  26. return rv < 0 ? -1 : rv;
  27. }
  28. static ssize_t httpd_io_write(void *cookie, const char *buf, size_t n)
  29. {
  30. return httpd_resp_send_chunk(cookie, buf, n) ? 0 : n;
  31. }
  32. static int httpd_io_close_write(void *cookie)
  33. {
  34. return httpd_resp_send_chunk(cookie, NULL, 0) ? -1 : 0;
  35. }
  36. static FILE *httpd_fopen_read(httpd_req_t *req)
  37. {
  38. static const cookie_io_functions_t http_io_read_funcs = {
  39. .read = httpd_io_read,
  40. .write = NULL, /* Not writeable */
  41. .seek = NULL, /* Not seekable */
  42. .close = NULL,
  43. };
  44. return fopencookie((void *)req, "r", http_io_read_funcs);
  45. }
  46. static FILE *httpd_fopen_write(httpd_req_t *req)
  47. {
  48. static const cookie_io_functions_t http_io_write_funcs = {
  49. .read = httpd_io_read,
  50. .write = httpd_io_write,
  51. .seek = NULL, /* Not seekable */
  52. .close = httpd_io_close_write
  53. };
  54. return fopencookie((void *)req, "r+", http_io_write_funcs);
  55. }
  56. #define TIMEBUF_LEN 32
  57. static const char *http_date(const struct tm *when)
  58. {
  59. static char timebuf[32];
  60. strftime(timebuf, sizeof timebuf,
  61. "%a, %d %b %Y %H:%M:%S GMT", when);
  62. return timebuf;
  63. }
  64. static const char *http_now(void)
  65. {
  66. time_t t = time(NULL);
  67. return http_date(gmtime(&t));
  68. }
  69. static struct tm *set_weekday(struct tm *tm)
  70. {
  71. /*
  72. * This is a variation on Zeller's congruence with a table lookup
  73. * for the month. The table contains the number of days since March 1,
  74. * mod 7 (for Jan and Feb, from March 1 of the *previous year*.)
  75. *
  76. * Sample test cases:
  77. * Wed Mar 1 0000
  78. * Thu Jan 1 1970
  79. * Wed Apr 27 2022
  80. * Mon Feb 28 2000
  81. * Wed Mar 1 2000
  82. * Sun Feb 28 2100
  83. * Mon Mar 1 2100
  84. */
  85. static const uint8_t md[12] = { 5, 1, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2 };
  86. unsigned int c, y, m, d;
  87. y = tm->tm_year + 1900;
  88. m = tm->tm_mon;
  89. d = tm->tm_mday;
  90. if (m < 2)
  91. y--; /* Jan, Feb */
  92. c = y/100;
  93. /*
  94. * 2 represents the base date of Tue Feb 29 0000
  95. *
  96. * 0 = Sun, 6 = Sat
  97. */
  98. tm->tm_wday = (d + md[m] + y + (y >> 2) - c + (c >> 2) + 2) % 7;
  99. return tm;
  100. }
  101. static const char *http_dos_date(uint32_t dos_date)
  102. {
  103. struct tm tm;
  104. tm.tm_sec = (dos_date << 1) & 63;
  105. tm.tm_min = (dos_date >> 5) & 63;
  106. tm.tm_hour = (dos_date >> 11) & 31;
  107. tm.tm_mday = (dos_date >> 16) & 31;
  108. tm.tm_mon = ((dos_date >> 21) & 15) - 1;
  109. tm.tm_year = (dos_date >> 25) + 80;
  110. tm.tm_isdst = 0; /* Times are stored in GMT */
  111. return http_date(set_weekday(&tm));
  112. }
  113. static const char text_plain[] = "text/plain; charset=\"UTF-8\"";
  114. enum hsp_flags {
  115. HSP_CLOSE = 1,
  116. HSP_CRLF = 2
  117. };
  118. static esp_err_t httpd_send_plain(httpd_req_t *req,
  119. unsigned int rcode,
  120. const char *body, size_t blen,
  121. enum hsp_flags flags)
  122. {
  123. char *header = NULL;
  124. esp_err_t err;
  125. int hlen;
  126. const char *now = http_now();
  127. if (rcode > 499)
  128. flags |= HSP_CLOSE;
  129. const char *closer = flags & HSP_CLOSE ? "Connection: close\r\n" : "";
  130. bool redirect = rcode >= 300 && rcode <= 399;
  131. if (redirect) {
  132. size_t blenadj = sizeof("3xx Redirect \r"); /* \0 -> \n so don't include it */
  133. flags |= HSP_CRLF;
  134. hlen = asprintf(&header,
  135. "HTTP/1.1 %u\r\n"
  136. "Content-Type: %s\r\n"
  137. "Content-Length: %zu\r\n"
  138. "Date %s\r\n"
  139. "Location: %.*s\r\n"
  140. "%s"
  141. "\r\n"
  142. "%3u Redirect ",
  143. rcode, text_plain, blen + blenadj,
  144. now, (int)blen, body, closer, rcode);
  145. } else {
  146. size_t blenadj = (flags & HSP_CRLF) ? 2 : 0;
  147. hlen = asprintf(&header,
  148. "HTTP/1.1 %u\r\n"
  149. "Content-Type: %s\r\n"
  150. "Content-Length: %zu\r\n"
  151. "Date: %s\r\n"
  152. "%s"
  153. "\r\n",
  154. rcode, text_plain, blen + blenadj, now, closer);
  155. }
  156. if (!header)
  157. return ESP_ERR_NO_MEM;
  158. err = httpd_send_all(req, header, hlen);
  159. if (!err && blen) {
  160. err = httpd_send_all(req, body, blen);
  161. }
  162. if (!err && (flags & HSP_CRLF)) {
  163. err = httpd_send_all(req, "\r\n", 2);
  164. }
  165. if (header)
  166. free(header);
  167. return err;
  168. }
  169. #define HTTP_ERR(r,e,s) httpd_send_plain((r), (e), s, sizeof(s)-1, HSP_CRLF)
  170. static esp_err_t httpd_err_404(httpd_req_t *req)
  171. {
  172. return HTTP_ERR(req, 404, "URI not found");
  173. }
  174. static esp_err_t httpd_send_ok(httpd_req_t *req)
  175. {
  176. return HTTP_ERR(req, 200, "OK");
  177. }
  178. static esp_err_t httpd_update_done(httpd_req_t *req, const char *what, int err)
  179. {
  180. char *response = NULL;
  181. int len;
  182. unsigned int reboot_time = reboot_delayed();
  183. if (err) {
  184. len = asprintf(&response,
  185. "%s update failed: %s\r\n"
  186. "Rebooting in %u seconds\r\n",
  187. what, firmware_errstr(err), reboot_time);
  188. } else {
  189. len = asprintf(&response,
  190. "%s update complete\r\n"
  191. "Rebooting in %u seconds\r\n",
  192. what, reboot_time);
  193. }
  194. if (!response)
  195. len = 0;
  196. esp_err_t rv = httpd_send_plain(req, err ? 400 : 200, response, len,
  197. HSP_CLOSE|HSP_CRLF);
  198. if (response)
  199. free(response);
  200. return rv;
  201. }
  202. static esp_err_t httpd_firmware_update(httpd_req_t *req)
  203. {
  204. int rv;
  205. /* XXX: use httpd_fopen_read() here */
  206. rv = firmware_update((read_func_t)httpd_req_recv, (token_t)req);
  207. return httpd_update_done(req, "Firmware", rv);
  208. }
  209. static esp_err_t httpd_set_config(httpd_req_t *req)
  210. {
  211. FILE *f = httpd_fopen_read(req);
  212. if (!f)
  213. return HTTP_ERR(req, 500, "Unable to get request handle");
  214. int rv = read_config(f);
  215. fclose(f);
  216. if (rv) {
  217. rv = FWUPDATE_ERR_CONFIG_READ;
  218. } else {
  219. rv = save_config();
  220. if (rv)
  221. rv = FWUPDATE_ERR_CONFIG_SAVE;
  222. }
  223. return httpd_update_done(req, "Configuration", rv);
  224. }
  225. static esp_err_t httpd_sys_post_handler(httpd_req_t *req)
  226. {
  227. printf("[POST] len = %zu uri = \"%s\"\n",
  228. req->content_len, req->uri);
  229. if (!req->content_len)
  230. return HTTP_ERR(req, 411, "Length required");
  231. if (!strcmp(req->uri, "/sys/fwupdate"))
  232. return httpd_firmware_update(req);
  233. if (!strcmp(req->uri, "/sys/setconfig"))
  234. return httpd_set_config(req);
  235. return httpd_err_404(req);
  236. }
  237. static esp_err_t httpd_get_config(httpd_req_t *req)
  238. {
  239. FILE *f = httpd_fopen_write(req);
  240. if (!f)
  241. return HTTP_ERR(req, 500, "Unable to get request handle");
  242. httpd_resp_set_type(req, text_plain);
  243. int rv = write_config(f);
  244. fclose(f);
  245. return rv ? ESP_FAIL : ESP_OK;
  246. }
  247. static esp_err_t httpd_sys_get_handler(httpd_req_t *req)
  248. {
  249. if (!strcmp(req->uri, "/sys/getconfig"))
  250. return httpd_get_config(req);
  251. return httpd_err_404(req);
  252. }
  253. INCBIN_EXTERN(wwwzip);
  254. struct mime_type {
  255. const char *ext;
  256. uint16_t ext_len;
  257. uint16_t flags;
  258. const char *mime;
  259. };
  260. #define MT_CHARSET 1 /* Add charset to Content-Type */
  261. static const struct mime_type mime_types[] = {
  262. { ".html", 5, MT_CHARSET, "text/html" },
  263. { ".xhtml", 6, MT_CHARSET, "text/html" },
  264. { ".css", 4, MT_CHARSET, "text/css" },
  265. { ".webp", 5, 0, "image/webp" },
  266. { ".jpg", 4, 0, "image/jpeg" },
  267. { ".png", 4, 0, "image/png" },
  268. { ".ico", 4, 0, "image/png" }, /* favicon.ico */
  269. { ".svg", 4, MT_CHARSET, "image/svg+xml" },
  270. { ".otf", 4, 0, "font/otf" },
  271. { ".ttf", 4, 0, "font/ttf" },
  272. { ".woff", 5, 0, "font/woff" },
  273. { ".woff2", 6, 0, "font/woff2" },
  274. { ".pdf", 4, 0, "application/pdf" },
  275. { ".js", 3, MT_CHARSET, "text/javascript" },
  276. { ".mjs", 4, MT_CHARSET, "text/javascript" },
  277. { ".json", 5, MT_CHARSET, "application/json" },
  278. { ".xml", 4, MT_CHARSET, "text/xml" },
  279. { ".bin", 4, 0, "application/octet-stream" },
  280. { ".fw", 3, 0, "application/octet-stream" },
  281. { NULL, 0, MT_CHARSET, "text/plain" } /* default */
  282. };
  283. static esp_err_t httpd_static_handler(httpd_req_t *req)
  284. {
  285. static const char index_filename[] = "index.html";
  286. static const char default_lang[] = "en";
  287. size_t buffer_size = UNZ_BUFSIZE;
  288. const char *uri, *enduri;
  289. bool add_index;
  290. char *buffer = NULL;
  291. ZIPFILE *zip = NULL;
  292. unzFile unz = NULL;
  293. bool file_open = false;
  294. int err = 0;
  295. size_t len;
  296. uri = req->uri;
  297. while (*uri == '/')
  298. uri++; /* Skip leading slashes */
  299. const char *first_slash = NULL, *last_slash = NULL;
  300. for (enduri = uri; *enduri; enduri++) {
  301. if (*enduri == '/') {
  302. last_slash = enduri;
  303. if (!first_slash)
  304. first_slash = enduri;
  305. }
  306. }
  307. if (enduri == uri) {
  308. add_index = true;
  309. } else if (last_slash == enduri-1) {
  310. add_index = true;
  311. enduri--; /* Drop terminal slash */
  312. if (first_slash == last_slash)
  313. first_slash = NULL;
  314. } else {
  315. add_index = false; /* Try the plain filename first */
  316. }
  317. MSG("requesting: /%.*s\n", enduri - uri, uri);
  318. if (first_slash)
  319. MSG("first_slash = %.*s\n", enduri - first_slash, first_slash);
  320. else
  321. MSG("first_slash = NULL\n");
  322. const char *lang = getenv("LANG");
  323. const size_t lang_size = lang ? strlen(lang)+1 : 0;
  324. const size_t lang_space = (lang_size < sizeof default_lang
  325. ? sizeof default_lang : lang_size) + 1;
  326. const size_t filename_buffer_size =
  327. (enduri - uri) + lang_space + 2 + sizeof index_filename;
  328. if (buffer_size < filename_buffer_size)
  329. buffer_size = filename_buffer_size;
  330. buffer = malloc(buffer_size);
  331. zip = malloc(sizeof *zip);
  332. if (!buffer || !zip) {
  333. err = HTTP_ERR(req, 503, "Out of memory");
  334. goto out;
  335. }
  336. char * const filebase = buffer + lang_space;
  337. char * const endbase = mempcpy(filebase, uri, enduri - uri);
  338. filebase[-1] = '/';
  339. unz = unzOpen(NULL, (void *)gwwwzipData, gwwwzipSize,
  340. zip, NULL, NULL, NULL, NULL);
  341. if (!unz) {
  342. MSG("[HTTP] unzOpen failed!\n");
  343. err = HTTP_ERR(req, 500, "Cannot open content archive");
  344. goto out;
  345. }
  346. char *filename, *endfile;
  347. unsigned int m;
  348. bool found = false;
  349. for (m = add_index; m < 6; m += (add_index+1)) {
  350. if (m & 1) {
  351. char *sx = endbase - (endbase[-1] == '/');
  352. *sx++ = '/';
  353. endfile = mempcpy(sx, index_filename, sizeof index_filename) - 1;
  354. } else {
  355. endfile = endbase;
  356. }
  357. *endfile = '\0';
  358. switch (m >> 1) {
  359. case 1:
  360. if (!lang) {
  361. filename = NULL;
  362. } else {
  363. filename = filebase - lang_size;
  364. memcpy(filename, lang, lang_size-1);
  365. }
  366. break;
  367. case 2:
  368. filename = filebase - sizeof default_lang;
  369. memcpy(filename, default_lang, sizeof default_lang - 1);
  370. break;
  371. default:
  372. filename = filebase;
  373. break;
  374. }
  375. if (!filename)
  376. continue;
  377. filename[-1] = '/';
  378. MSG("trying to open: %s\n", filename);
  379. if (unzLocateFile(unz, filename, 1) == UNZ_OK) {
  380. found = true;
  381. break;
  382. }
  383. }
  384. size_t filelen = endfile - filename;
  385. if (!found) {
  386. err = httpd_err_404(req);
  387. goto out;
  388. } else if (m) {
  389. err = httpd_send_plain(req, 302 - (m == 1), filename-1, filelen+1, 0);
  390. goto out;
  391. }
  392. /* Note: p points to the end of the filename string */
  393. const struct mime_type *mime_type = mime_types;
  394. /* The default entry with length 0 will always match */
  395. while (mime_type->ext_len) {
  396. len = mime_type->ext_len;
  397. if (len < filelen && !memcmp(endfile - len, mime_type->ext, len))
  398. break;
  399. mime_type++;
  400. }
  401. unz_file_info fileinfo;
  402. memset(&fileinfo, 0, sizeof fileinfo);
  403. unzGetCurrentFileInfo(unz, &fileinfo, NULL, 0, NULL, 0, NULL, 0);
  404. /*
  405. * Hopefully the combination of date and CRC
  406. * is strong enough to quality for a "strong" ETag
  407. */
  408. char etag[16+3+1];
  409. snprintf(etag, sizeof etag, "\"%08x:%08x\"",
  410. fileinfo.dosDate, fileinfo.crc);
  411. bool skip_body = req->method == HTTP_HEAD || !fileinfo.uncompressed_size;
  412. bool skip_meta = false;
  413. const char *response = "200 OK";
  414. if (httpd_req_get_hdr_value_str(req, "If-None-Match",
  415. buffer, buffer_size) == ESP_OK &&
  416. strstr(buffer, etag)) {
  417. skip_body = skip_meta = true;
  418. response = "304 Not Modified";
  419. }
  420. len = snprintf(buffer, buffer_size-2,
  421. "HTTP/1.1 %s\r\n"
  422. "Date: %s\r\n"
  423. "ETag: %s\r\n",
  424. response,
  425. http_now(),
  426. etag);
  427. if (len < buffer_size-2 && !skip_meta) {
  428. const char *mime_extra =
  429. mime_type->flags & MT_CHARSET ? "; charset=\"UTF-8\"" : "";
  430. len += snprintf(buffer + len, buffer_size-2 - len,
  431. "Content-Type: %s%s\r\n"
  432. "Content-Length: %u\r\n"
  433. "Allow: GET, HEAD\r\n"
  434. "Last-Modified: %s\r\n",
  435. mime_type->mime, mime_extra,
  436. fileinfo.uncompressed_size,
  437. http_dos_date(fileinfo.dosDate));
  438. }
  439. if (len >= buffer_size-2) {
  440. err = HTTP_ERR(req, 500, "buffer_size too small");
  441. goto out;
  442. }
  443. buffer[len++] = '\r';
  444. buffer[len++] = '\n';
  445. err = httpd_send_all(req, buffer, len);
  446. if (skip_body || err) {
  447. /* No need to spend time uncompressing the file content */
  448. goto out;
  449. }
  450. if (unzOpenCurrentFile(unz) != UNZ_OK) {
  451. err = httpd_resp_send_err(req, 500, "Cannot open file in archive");
  452. goto out;
  453. }
  454. file_open = true;
  455. len = fileinfo.uncompressed_size;
  456. while (len) {
  457. size_t chunk = len;
  458. if (chunk > buffer_size)
  459. chunk = buffer_size;
  460. if (unzReadCurrentFile(unz, buffer, chunk) != chunk) {
  461. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  462. goto out;
  463. }
  464. err = httpd_send_all(req, buffer, chunk);
  465. if (err)
  466. goto out;
  467. len -= chunk;
  468. }
  469. err = ESP_OK; /* All good! */
  470. out:
  471. if (file_open)
  472. unzCloseCurrentFile(unz);
  473. if (unz)
  474. unzClose(unz);
  475. if (zip)
  476. free(zip);
  477. if (buffer)
  478. free(buffer);
  479. return err;
  480. }
  481. /*
  482. * Match a URL against a path prefix. To keep httpd from refusing to
  483. * register subpaths, the root template does not include the leading
  484. * '/', but uri is required to have it. Do not include a trailing /
  485. * in prefix; it is implied.
  486. */
  487. static bool httpd_uri_match_prefix(const char *template, const char *uri,
  488. size_t len)
  489. {
  490. #if 0
  491. printf("[HTTP] matching URI \"%.*s\" against template \"%s\"\n",
  492. len, uri, template);
  493. #endif
  494. if (!len-- || *uri++ != '/')
  495. return false;
  496. /* Previous template character (leading '/' implied) */
  497. unsigned char tp = '/';
  498. while (1) {
  499. unsigned char t = *template++;
  500. unsigned char u;
  501. if (!len-- || !(u = *uri++)) {
  502. return !t;
  503. } else if (!t) {
  504. return tp == '/' || u == '/';
  505. } else if (t != u) {
  506. return false;
  507. }
  508. tp = t;
  509. }
  510. }
  511. /* Do not include leading or trailing /; most specific prefix first */
  512. static const httpd_uri_t uri_handlers[] = {
  513. {
  514. .uri = "sys",
  515. .method = HTTP_GET,
  516. .handler = httpd_sys_get_handler,
  517. .user_ctx = NULL
  518. },
  519. {
  520. .uri = "",
  521. .method = HTTP_GET,
  522. .handler = httpd_static_handler,
  523. .user_ctx = NULL
  524. },
  525. {
  526. .uri = "",
  527. .method = HTTP_HEAD,
  528. .handler = httpd_static_handler,
  529. .user_ctx = NULL
  530. },
  531. {
  532. .uri = "sys",
  533. .method = HTTP_POST,
  534. .handler = httpd_sys_post_handler,
  535. .user_ctx = NULL
  536. },
  537. };
  538. void my_httpd_stop(void)
  539. {
  540. if (httpd) {
  541. httpd_stop(httpd);
  542. httpd = NULL;
  543. }
  544. }
  545. void my_httpd_start(void)
  546. {
  547. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  548. httpd_handle_t server;
  549. if (httpd)
  550. return;
  551. config.task_priority = 2;
  552. config.max_open_sockets = 8;
  553. printf("[HTTP] Default stack size: %zu\n", config.stack_size);
  554. config.stack_size <<= 2;
  555. printf("[HTTP] Requesting stack size: %zu\n", config.stack_size);
  556. config.uri_match_fn = httpd_uri_match_prefix;
  557. if (httpd_start(&server, &config) != ESP_OK)
  558. return;
  559. httpd = server;
  560. for (size_t i = 0; i < ARRAY_SIZE(uri_handlers); i++) {
  561. const httpd_uri_t * const handler = &uri_handlers[i];
  562. if (httpd_register_uri_handler(httpd, handler))
  563. printf("[HTTP] failed to register URI handler: %s %s\n",
  564. http_method_str(handler->method), handler->uri);
  565. }
  566. printf("[HTTP] httpd started\n");
  567. }