httpd.c 9.9 KB

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