httpd.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #define MODULE "httpd"
  2. #include "common.h"
  3. #include "fw.h"
  4. #include "httpd.h"
  5. #include <incbin.h>
  6. #include <unzipLIB.h>
  7. /*
  8. * Allow the client to cache static content for this many seconds;
  9. * this improves responsiveness signficantly.
  10. */
  11. #define HTTPD_STATIC_CACHE_AGE 300 /* 5 min */
  12. static httpd_handle_t httpd;
  13. #define TIMEBUF_LEN 32
  14. static const char *http_date(const struct tm *when)
  15. {
  16. static char timebuf[TIMEBUF_LEN];
  17. strftime(timebuf, TIMEBUF_LEN,
  18. "%a, %d %b %Y %H:%M:%S GMT", when);
  19. return timebuf;
  20. }
  21. static const char *http_now(void)
  22. {
  23. time_t t = time(NULL);
  24. return http_date(gmtime(&t));
  25. }
  26. static struct tm *set_weekday(struct tm *tm)
  27. {
  28. /*
  29. * A variation on Zeller's congruence.
  30. */
  31. unsigned int c, y, m, d;
  32. y = tm->tm_year + 1900;
  33. m = tm->tm_mon + 2;
  34. d = tm->tm_mday;
  35. if (m < 4) {
  36. m += 12;
  37. y--;
  38. }
  39. c = y/100;
  40. tm->tm_wday = (d + ((13*m)/5) + y + (y >> 2) - c + (c >> 2) + 6) % 7;
  41. return tm;
  42. }
  43. static const char *http_dos_date(uint32_t dos_date)
  44. {
  45. struct tm tm;
  46. tm.tm_sec = (dos_date << 1) & 63;
  47. tm.tm_min = (dos_date >> 5) & 63;
  48. tm.tm_hour = (dos_date >> 11) & 31;
  49. tm.tm_mday = (dos_date >> 16) & 31;
  50. tm.tm_mon = ((dos_date >> 21) & 15) - 1;
  51. tm.tm_year = (dos_date >> 25) + 80;
  52. tm.tm_isdst = 0; /* Times are stored in GMT */
  53. return http_date(set_weekday(&tm));
  54. }
  55. static esp_err_t httpd_error(httpd_req_t *req,
  56. unsigned int errcode, const char *msg)
  57. {
  58. char *header = NULL;
  59. char *body = NULL;
  60. int hlen, blen;
  61. int rv = ESP_ERR_NO_MEM;
  62. blen = asprintf(&body, "%u %s\r\n", errcode, msg);
  63. if (!body)
  64. goto out;
  65. hlen = asprintf(&header,
  66. "HTTP/1.1 %u %s\r\n"
  67. "Content-Type: text/plain; charset=\"UTF-8\"\r\n"
  68. "Content-Length: %d\r\n"
  69. "Date: %s\r\n"
  70. "Cache-Control: no-cache\r\n"
  71. "Connection: close\r\n"
  72. "\r\n",
  73. errcode, msg, blen, http_now());
  74. if (!header)
  75. goto out;
  76. rv = httpd_send(req, header, hlen);
  77. if (!rv)
  78. rv = httpd_send(req, body, blen);
  79. out:
  80. if (header)
  81. free(header);
  82. if (body)
  83. free(body);
  84. return rv;
  85. }
  86. esp_err_t httpd_firmware_upgrade_handler(httpd_req_t *req)
  87. {
  88. char *response;
  89. esp_err_t err;
  90. int rv, len;
  91. printf("[POST] len = %zu uri = \"%s\"\n",
  92. req->content_len, req->uri);
  93. if (!req->content_len) {
  94. return httpd_error(req, 411, "Length required");
  95. }
  96. rv = firmware_update((read_func_t)httpd_req_recv, (token_t)req);
  97. if (rv == FWUPDATE_ERR_IN_PROGRESS)
  98. return httpd_error(req, 409, "Firmware update already in progress");
  99. else if (rv)
  100. return httpd_error(req, 500, "Firmware update failed");
  101. len = asprintf(&response,
  102. "Firmware update completed\r\n"
  103. "Rebooting in %u seconds\r\n",
  104. reboot_delayed());
  105. /* 200 is default, no need to set */
  106. httpd_resp_set_type(req, "text/plain; charset=\"UTF-8\"");
  107. httpd_resp_set_hdr(req, "Date", http_now());
  108. httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
  109. httpd_resp_set_hdr(req, "Connection", "close");
  110. err = httpd_resp_send(req, response, len);
  111. free(response);
  112. return err;
  113. }
  114. INCBIN_EXTERN(wwwzip);
  115. struct mime_type {
  116. const char *ext;
  117. uint16_t ext_len;
  118. uint16_t flags;
  119. const char *mime;
  120. };
  121. #define MT_CHARSET 1 /* Add charset to Content-Type */
  122. static const struct mime_type mime_types[] = {
  123. { ".html", 5, MT_CHARSET, "text/html" },
  124. { ".xhtml", 6, MT_CHARSET, "text/html" },
  125. { ".css", 4, MT_CHARSET, "text/css" },
  126. { ".webp", 5, 0, "image/webp" },
  127. { ".jpg", 4, 0, "image/jpeg" },
  128. { ".png", 4, 0, "image/png" },
  129. { ".ico", 4, 0, "image/png" }, /* favicon.ico */
  130. { ".svg", 4, MT_CHARSET, "image/svg+xml" },
  131. { ".otf", 4, 0, "font/otf" },
  132. { ".ttf", 4, 0, "font/ttf" },
  133. { ".woff", 5, 0, "font/woff" },
  134. { ".woff2", 6, 0, "font/woff2" },
  135. { ".pdf", 4, 0, "application/pdf" },
  136. { ".js", 3, MT_CHARSET, "text/javascript" },
  137. { ".mjs", 4, MT_CHARSET, "text/javascript" },
  138. { ".json", 5, MT_CHARSET, "application/json" },
  139. { ".xml", 4, MT_CHARSET, "text/xml" },
  140. { ".bin", 4, 0, "application/octet-stream" },
  141. { ".fw", 3, 0, "application/octet-stream" },
  142. { NULL, 0, MT_CHARSET, "text/plain" } /* default */
  143. };
  144. static esp_err_t httpd_static_handler(httpd_req_t *req)
  145. {
  146. static const char index_filename[] = "index.html";
  147. const size_t buffer_size = UNZ_BUFSIZE;
  148. const char *uri, *enduri;
  149. bool add_index;
  150. char *buffer = NULL;
  151. ZIPFILE *zip = NULL;
  152. unzFile unz = NULL;
  153. bool file_open = false;
  154. int err = 0;
  155. size_t len;
  156. uri = req->uri;
  157. while (*uri == '/')
  158. uri++; /* Skip leading slashes */
  159. enduri = strchr(uri, '\0');
  160. if (enduri == uri) {
  161. add_index = true;
  162. } else if (enduri[-1] == '/') {
  163. add_index = true;
  164. enduri--; /* Drop terminal slash */
  165. } else {
  166. add_index = false; /* Try the plain filename first */
  167. }
  168. MSG("requesting: /%.*s\n", enduri - uri, uri);
  169. buffer = malloc(buffer_size);
  170. zip = malloc(sizeof *zip);
  171. if (!buffer || !zip) {
  172. err = httpd_error(req, 503, "Out of memory");
  173. goto out;
  174. }
  175. if (enduri - uri + 1 + sizeof index_filename >= buffer_size) {
  176. err = httpd_error(req, 414, "URI too long");
  177. goto out;
  178. }
  179. char *p = mempcpy(buffer, uri, enduri - uri);
  180. *p = '\0';
  181. unz = unzOpen(NULL, (void *)gwwwzipData, gwwwzipSize,
  182. zip, NULL, NULL, NULL, NULL);
  183. if (!unz) {
  184. MSG("[HTTP] unzOpen failed!\n");
  185. err = httpd_error(req, 500, "Cannot open content archive");
  186. goto out;
  187. }
  188. while (1) {
  189. if (add_index) {
  190. if (p > buffer)
  191. *p++ = '/';
  192. memcpy(p, index_filename, sizeof index_filename);
  193. p += sizeof index_filename - 1; /* Point to final NUL */
  194. }
  195. MSG("trying to open: %s\n", buffer);
  196. if (unzLocateFile(unz, buffer, 1) == UNZ_OK)
  197. break;
  198. if (add_index) {
  199. err = httpd_error(req, 404, "File not found");
  200. goto out;
  201. }
  202. add_index = true; /* Try again with the index filename */
  203. }
  204. /* Note: p points to the end of the filename string */
  205. size_t filelen = p - buffer;
  206. const struct mime_type *mime_type = mime_types;
  207. /* The default entry with length 0 will always match */
  208. while (mime_type->ext_len) {
  209. len = mime_type->ext_len;
  210. if (len < filelen && !memcmp(p - len, mime_type->ext, len))
  211. break;
  212. mime_type++;
  213. }
  214. unz_file_info fileinfo;
  215. memset(&fileinfo, 0, sizeof fileinfo);
  216. unzGetCurrentFileInfo(unz, &fileinfo, NULL, 0, NULL, 0, NULL, 0);
  217. /*
  218. * Hopefully the combination of date and CRC
  219. * is strong enough to quality for a "strong" ETag
  220. */
  221. char etag[16+3+1];
  222. snprintf(etag, sizeof etag, "\"%08x:%08x\"",
  223. fileinfo.dosDate, fileinfo.crc);
  224. bool skip_body = req->method == HTTP_HEAD || !fileinfo.uncompressed_size;
  225. bool skip_meta = false;
  226. const char *response = "200 OK";
  227. if (req->method == HTTP_GET &&
  228. httpd_req_get_hdr_value_str(req, "If-None-Match",
  229. buffer, buffer_size) == ESP_OK &&
  230. strstr(buffer, etag)) {
  231. skip_body = skip_meta = true;
  232. response = "304 Not Modified";
  233. }
  234. len = snprintf(buffer, buffer_size-2,
  235. "HTTP/1.1 %s\r\n"
  236. "Date: %s\r\n"
  237. "ETag: %s\r\n"
  238. "Cache-Control: max-age=%d\r\n",
  239. response,
  240. http_now(),
  241. etag,
  242. HTTPD_STATIC_CACHE_AGE);
  243. if (len < buffer_size-2 && !skip_meta) {
  244. const char *mime_extra =
  245. mime_type->flags & MT_CHARSET ? "; charset=\"UTF-8\"" : "";
  246. len += snprintf(buffer + len, buffer_size-2 - len,
  247. "Content-Type: %s%s\r\n"
  248. "Content-Length: %u\r\n"
  249. "Allow: GET, HEAD\r\n"
  250. "Last-Modified: %s\r\n"
  251. "%s",
  252. mime_type->mime, mime_extra,
  253. fileinfo.uncompressed_size,
  254. http_dos_date(fileinfo.dosDate),
  255. skip_body ? "" : "Connection: close\r\n");
  256. }
  257. if (len >= buffer_size-2) {
  258. err = httpd_resp_send_err(req, 500, "buffer_size too small");
  259. goto out;
  260. }
  261. buffer[len++] = '\r';
  262. buffer[len++] = '\n';
  263. err = httpd_send(req, buffer, len);
  264. if (skip_body || err != len) {
  265. /* No need to spend time uncompressing the file content */
  266. goto out;
  267. }
  268. if (unzOpenCurrentFile(unz) != UNZ_OK) {
  269. err = httpd_resp_send_err(req, 500, "Cannot open file in archive");
  270. goto out;
  271. }
  272. file_open = true;
  273. len = fileinfo.uncompressed_size;
  274. while (len) {
  275. size_t chunk = len;
  276. if (chunk > buffer_size)
  277. chunk = buffer_size;
  278. if (unzReadCurrentFile(unz, buffer, chunk) != chunk) {
  279. err = ESP_ERR_HTTPD_RESULT_TRUNC;
  280. goto out;
  281. }
  282. err = httpd_send(req, buffer, chunk);
  283. if (err != chunk)
  284. goto out;
  285. len -= chunk;
  286. }
  287. err = ESP_OK; /* All good! */
  288. out:
  289. if (file_open)
  290. unzCloseCurrentFile(unz);
  291. if (unz)
  292. unzClose(unz);
  293. if (zip)
  294. free(zip);
  295. if (buffer)
  296. free(buffer);
  297. return err;
  298. }
  299. static const httpd_uri_t uri_handlers[] = {
  300. {
  301. .uri = "/*",
  302. .method = HTTP_GET,
  303. .handler = httpd_static_handler,
  304. .user_ctx = NULL
  305. },
  306. {
  307. .uri = "/*",
  308. .method = HTTP_HEAD,
  309. .handler = httpd_static_handler,
  310. .user_ctx = NULL
  311. },
  312. {
  313. .uri = "/fwupdate/?",
  314. .method = HTTP_POST,
  315. .handler = httpd_firmware_upgrade_handler,
  316. .user_ctx = NULL
  317. }
  318. };
  319. void my_httpd_stop(void)
  320. {
  321. if (httpd) {
  322. httpd_stop(httpd);
  323. httpd = NULL;
  324. }
  325. }
  326. void my_httpd_start(void)
  327. {
  328. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  329. httpd_handle_t server;
  330. if (httpd)
  331. return;
  332. config.task_priority = 2;
  333. printf("[HTTP] Default stack size: %zu\n", config.stack_size);
  334. config.stack_size <<= 2;
  335. printf("[HTTP] Requesting stack size: %zu\n", config.stack_size);
  336. config.uri_match_fn = httpd_uri_match_wildcard;
  337. if (httpd_start(&server, &config) != ESP_OK)
  338. return;
  339. httpd = server;
  340. for (size_t i = 0; i < ARRAY_SIZE(uri_handlers); i++)
  341. httpd_register_uri_handler(httpd, &uri_handlers[i]);
  342. printf("[HTTP] httpd started\n");
  343. }