server_help.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. #include "server_help.h"
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <sys/param.h>
  5. #include <sys/unistd.h>
  6. #include <sys/stat.h>
  7. #include <dirent.h>
  8. #include <memory>
  9. #include <new>
  10. #include "esp_err.h"
  11. #include "esp_log.h"
  12. #include "esp_http_server.h"
  13. #include "esp_timer.h"
  14. #include "miniz.h"
  15. #include "Helper.h"
  16. #include "ClassLogFile.h"
  17. #include "../../include/defines.h"
  18. static const char *TAG = "SERVER HELP";
  19. string SUFFIX_ZW = "_tmp";
  20. bool endsWith(std::string const &str, std::string const &suffix)
  21. {
  22. if (str.length() < suffix.length())
  23. {
  24. return false;
  25. }
  26. return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
  27. }
  28. esp_err_t send_file(httpd_req_t *req, std::string filename)
  29. {
  30. const int64_t totalStartUs = esp_timer_get_time();
  31. int64_t openUs = 0;
  32. int64_t readUs = 0;
  33. int64_t sendUs = 0;
  34. size_t totalBytes = 0;
  35. size_t chunkCount = 0;
  36. auto logSlowTransfer = [&](const char *result) {
  37. const int64_t totalUs = esp_timer_get_time() - totalStartUs;
  38. // Static assets (HTML, JS, CSS and images) are requested during page load.
  39. // A 50 ms threshold exposes repeated moderate delays that add up to a
  40. // visibly slow page build, while keeping normal requests out of the log.
  41. if (totalUs >= 50000) {
  42. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  43. std::string("Slow static file response: uri=") + req->uri +
  44. ", file=" + filename +
  45. ", result=" + result +
  46. ", total=" + std::to_string(static_cast<long long>(totalUs / 1000)) + " ms" +
  47. ", open=" + std::to_string(static_cast<long long>(openUs / 1000)) + " ms" +
  48. ", read=" + std::to_string(static_cast<long long>(readUs / 1000)) + " ms" +
  49. ", send=" + std::to_string(static_cast<long long>(sendUs / 1000)) + " ms" +
  50. ", bytes=" + std::to_string(totalBytes) +
  51. ", chunks=" + std::to_string(chunkCount));
  52. }
  53. };
  54. std::string _filename_old = filename;
  55. struct stat file_stat;
  56. bool _gz_file_exists = false;
  57. ESP_LOGD(TAG, "old filename: %s", filename.c_str());
  58. std::string _filename_temp = std::string(filename) + ".gz";
  59. // Checks whether the file is available as .gz
  60. const int64_t openStartUs = esp_timer_get_time();
  61. if (stat(_filename_temp.c_str(), &file_stat) == 0)
  62. {
  63. filename = _filename_temp;
  64. ESP_LOGD(TAG, "new filename: %s", filename.c_str());
  65. _gz_file_exists = true;
  66. }
  67. FILE *fd = fopen(filename.c_str(), "r");
  68. openUs += esp_timer_get_time() - openStartUs;
  69. if (!fd)
  70. {
  71. ESP_LOGE(TAG, "Failed to read file: %s", filename.c_str());
  72. /* Respond with 404 Error */
  73. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404());
  74. logSlowTransfer("open failed");
  75. return ESP_FAIL;
  76. }
  77. ESP_LOGD(TAG, "Sending file: %s ...", filename.c_str());
  78. /* For all files with the following file extention tell the webbrowser to cache them for 12h */
  79. if (endsWith(filename, ".html") ||
  80. endsWith(filename, ".htm") ||
  81. endsWith(filename, ".xml") ||
  82. endsWith(filename, ".css") ||
  83. endsWith(filename, ".js") ||
  84. endsWith(filename, ".map") ||
  85. endsWith(filename, ".jpg") ||
  86. endsWith(filename, ".jpeg") ||
  87. endsWith(filename, ".ico") ||
  88. endsWith(filename, ".png") ||
  89. endsWith(filename, ".gif") ||
  90. // endsWith(filename, ".zip") ||
  91. endsWith(filename, ".gz"))
  92. {
  93. if (filename == "/sdcard/html/setup.html")
  94. {
  95. httpd_resp_set_hdr(req, "Clear-Site-Data", "\"*\"");
  96. set_content_type_from_file(req, filename.c_str());
  97. }
  98. else if (_gz_file_exists)
  99. {
  100. httpd_resp_set_hdr(req, "Cache-Control", "max-age=43200");
  101. httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
  102. set_content_type_from_file(req, _filename_old.c_str());
  103. }
  104. else
  105. {
  106. httpd_resp_set_hdr(req, "Cache-Control", "max-age=43200");
  107. set_content_type_from_file(req, filename.c_str());
  108. }
  109. }
  110. else
  111. {
  112. set_content_type_from_file(req, filename.c_str());
  113. }
  114. // Each async transfer owns its buffer; a process-global scratch array would
  115. // race if another file response is ever served from a different task.
  116. std::unique_ptr<char[]> chunkBuffer(
  117. new (std::nothrow) char[SERVER_HELPER_SCRATCH_BUFSIZE]);
  118. if (!chunkBuffer)
  119. {
  120. fclose(fd);
  121. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Not enough memory for file response");
  122. logSlowTransfer("buffer allocation failed");
  123. return ESP_ERR_NO_MEM;
  124. }
  125. char *chunk = chunkBuffer.get();
  126. size_t chunksize;
  127. do
  128. {
  129. /* Measure SD/VFS read time separately from socket send time. */
  130. int64_t phaseStartUs = esp_timer_get_time();
  131. chunksize = fread(chunk, 1, SERVER_HELPER_SCRATCH_BUFSIZE, fd);
  132. readUs += esp_timer_get_time() - phaseStartUs;
  133. totalBytes += chunksize;
  134. ++chunkCount;
  135. /* Measure time spent sending this chunk to the HTTP client. */
  136. phaseStartUs = esp_timer_get_time();
  137. const esp_err_t sendResult = httpd_resp_send_chunk(req, chunk, chunksize);
  138. sendUs += esp_timer_get_time() - phaseStartUs;
  139. if (sendResult != ESP_OK)
  140. {
  141. fclose(fd);
  142. // The response headers/body may already have been sent. A failed
  143. // chunk send usually means the peer closed/reset the connection;
  144. // trying to send a final chunk or a second HTTP 500 response on
  145. // that socket only creates secondary errors and cannot reach the
  146. // client.
  147. ESP_LOGW(TAG, "File transfer interrupted for %s (send error %d)",
  148. filename.c_str(), static_cast<int>(sendResult));
  149. logSlowTransfer("send failed");
  150. return ESP_FAIL;
  151. }
  152. /* Keep looping till the whole file is sent */
  153. } while (chunksize != 0);
  154. /* Close file after sending complete */
  155. fclose(fd);
  156. ESP_LOGD(TAG, "File sending complete");
  157. logSlowTransfer("ok");
  158. return ESP_OK;
  159. }
  160. /* Copies the full path into destination buffer and returns
  161. * pointer to path (skipping the preceding base path) */
  162. const char *get_path_from_uri(char *dest, const char *base_path, const char *uri, size_t destsize)
  163. {
  164. const size_t base_pathlen = strlen(base_path);
  165. size_t pathlen = strlen(uri);
  166. const char *quest = strchr(uri, '?');
  167. if (quest)
  168. {
  169. pathlen = MIN(pathlen, quest - uri);
  170. }
  171. const char *hash = strchr(uri, '#');
  172. if (hash)
  173. {
  174. pathlen = MIN(pathlen, hash - uri);
  175. }
  176. if (base_pathlen + pathlen + 1 > destsize)
  177. {
  178. /* Full path string won't fit into destination buffer */
  179. return NULL;
  180. }
  181. /* Construct full path (base + path) */
  182. strcpy(dest, base_path);
  183. strlcpy(dest + base_pathlen, uri, pathlen + 1);
  184. /* Return pointer to path, skipping the base */
  185. return dest + base_pathlen;
  186. }
  187. /* Set HTTP response content type according to file extension */
  188. esp_err_t set_content_type_from_file(httpd_req_t *req, const char *filename)
  189. {
  190. if (IS_FILE_EXT(filename, ".pdf"))
  191. {
  192. return httpd_resp_set_type(req, "application/x-pdf");
  193. }
  194. else if (IS_FILE_EXT(filename, ".htm"))
  195. {
  196. return httpd_resp_set_type(req, "text/html");
  197. }
  198. else if (IS_FILE_EXT(filename, ".html"))
  199. {
  200. return httpd_resp_set_type(req, "text/html");
  201. }
  202. else if (IS_FILE_EXT(filename, ".jpeg"))
  203. {
  204. return httpd_resp_set_type(req, "image/jpeg");
  205. }
  206. else if (IS_FILE_EXT(filename, ".jpg"))
  207. {
  208. return httpd_resp_set_type(req, "image/jpeg");
  209. }
  210. else if (IS_FILE_EXT(filename, ".gif"))
  211. {
  212. return httpd_resp_set_type(req, "image/gif");
  213. }
  214. else if (IS_FILE_EXT(filename, ".png"))
  215. {
  216. return httpd_resp_set_type(req, "image/png");
  217. }
  218. else if (IS_FILE_EXT(filename, ".ico"))
  219. {
  220. return httpd_resp_set_type(req, "image/x-icon");
  221. }
  222. else if (IS_FILE_EXT(filename, ".js"))
  223. {
  224. return httpd_resp_set_type(req, "application/javascript");
  225. }
  226. else if (IS_FILE_EXT(filename, ".css"))
  227. {
  228. return httpd_resp_set_type(req, "text/css");
  229. }
  230. else if (IS_FILE_EXT(filename, ".xml"))
  231. {
  232. return httpd_resp_set_type(req, "text/xml");
  233. }
  234. else if (IS_FILE_EXT(filename, ".zip"))
  235. {
  236. return httpd_resp_set_type(req, "application/x-zip");
  237. }
  238. else if (IS_FILE_EXT(filename, ".gz"))
  239. {
  240. return httpd_resp_set_type(req, "application/x-gzip");
  241. }
  242. /* This is a limited set only */
  243. /* For any other type always set as plain text */
  244. return httpd_resp_set_type(req, "text/plain");
  245. }
  246. struct unzip_context_t
  247. {
  248. FILE *file;
  249. };
  250. static size_t unzip_write_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)
  251. {
  252. (void)file_ofs;
  253. unzip_context_t *ctx = (unzip_context_t *)pOpaque;
  254. if (!ctx || !ctx->file)
  255. {
  256. return 0;
  257. }
  258. size_t written = fwrite(pBuf, 1, n, ctx->file);
  259. if (written != n)
  260. {
  261. return 0;
  262. }
  263. return written;
  264. }
  265. static bool unzip_extract_file(mz_zip_archive *zip_archive, int i, const std::string &output_file, const mz_zip_archive_file_stat &file_stat)
  266. {
  267. DeleteFile(output_file);
  268. FILE *pFile = fopen(output_file.c_str(), "wb");
  269. if (!pFile)
  270. {
  271. return false;
  272. }
  273. setvbuf(pFile, NULL, _IOFBF, SERVER_FILER_SCRATCH_BUFSIZE);
  274. unzip_context_t ctx;
  275. ctx.file = pFile;
  276. mz_bool status = mz_zip_reader_extract_to_callback(zip_archive, i, unzip_write_callback, &ctx, 0);
  277. fclose(pFile);
  278. if (!status)
  279. {
  280. DeleteFile(output_file);
  281. return false;
  282. }
  283. return true;
  284. }
  285. void unzip_file(std::string _in_zip_file, std::string _target_directory)
  286. {
  287. mz_zip_archive zip_archive;
  288. ESP_LOGD(TAG, "Zipfile: %s", _in_zip_file.c_str());
  289. ESP_LOGD(TAG, "Target Dir: %s", _target_directory.c_str());
  290. memset(&zip_archive, 0, sizeof(zip_archive));
  291. if (!mz_zip_reader_init_file(&zip_archive, _in_zip_file.c_str(), 0))
  292. {
  293. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "mz_zip_reader_init_file() failed!");
  294. return;
  295. }
  296. int numberoffiles = (int)mz_zip_reader_get_num_files(&zip_archive);
  297. for (int i = 0; i < numberoffiles; i++)
  298. {
  299. mz_zip_archive_file_stat file_stat;
  300. if (!mz_zip_reader_file_stat(&zip_archive, i, &file_stat))
  301. {
  302. continue;
  303. }
  304. if (file_stat.m_is_directory)
  305. {
  306. continue;
  307. }
  308. std::string out_file = _target_directory + std::string(file_stat.m_filename);
  309. ESP_LOGD(TAG, "Extract: %s", out_file.c_str());
  310. bool ok = unzip_extract_file(&zip_archive, i, out_file, file_stat);
  311. if (!ok)
  312. {
  313. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Extract failed: " + std::string(file_stat.m_filename));
  314. continue;
  315. }
  316. }
  317. mz_zip_reader_end(&zip_archive);
  318. }
  319. std::string unzip_firmware(std::string _in_zip_file, std::string _html_tmp, std::string _html_final, std::string _target_bin, std::string _main, bool _initial_setup)
  320. {
  321. mz_zip_archive zip_archive;
  322. ESP_LOGD(TAG, "Zipfile: %s", _in_zip_file.c_str());
  323. memset(&zip_archive, 0, sizeof(zip_archive));
  324. if (!mz_zip_reader_init_file(&zip_archive, _in_zip_file.c_str(), 0))
  325. {
  326. ESP_LOGD(TAG, "mz_zip_reader_init_file() failed!");
  327. return "";
  328. }
  329. int numberoffiles = (int)mz_zip_reader_get_num_files(&zip_archive);
  330. std::string ret = "";
  331. for (int i = 0; i < numberoffiles; i++)
  332. {
  333. mz_zip_archive_file_stat file_stat;
  334. if (!mz_zip_reader_file_stat(&zip_archive, i, &file_stat))
  335. {
  336. continue;
  337. }
  338. if (file_stat.m_is_directory)
  339. {
  340. continue;
  341. }
  342. std::string path(file_stat.m_filename);
  343. std::string logical_path;
  344. if (toUpper(path) == "FIRMWARE.BIN")
  345. {
  346. logical_path = _target_bin + path;
  347. ret = logical_path;
  348. }
  349. else
  350. {
  351. std::string dir = getDirectory(path);
  352. if (dir == "config-initial" && !_initial_setup)
  353. {
  354. continue;
  355. }
  356. std::string modified = path;
  357. std::string _s1 = "config-initial";
  358. std::string _dir_new = "config";
  359. FindReplace(modified, _s1, _dir_new);
  360. if (!dir.empty())
  361. {
  362. logical_path = _main + modified;
  363. }
  364. else
  365. {
  366. logical_path = _html_tmp + modified;
  367. }
  368. }
  369. if (logical_path.find(_html_final) == 0)
  370. {
  371. FindReplace(logical_path, _html_final, _html_tmp);
  372. }
  373. std::string temp_file = logical_path + SUFFIX_ZW;
  374. std::string folder = temp_file.substr(0, temp_file.find_last_of('/'));
  375. MakeDir(folder);
  376. ESP_LOGI(TAG, "Extract: %s", temp_file.c_str());
  377. bool ok = unzip_extract_file(&zip_archive, i, temp_file, file_stat);
  378. if (!ok)
  379. {
  380. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Extract failed: " + std::string(file_stat.m_filename));
  381. ret = "ERROR";
  382. continue;
  383. }
  384. DeleteFile(logical_path);
  385. if (!RenameFile(temp_file, logical_path))
  386. {
  387. DeleteFile(temp_file);
  388. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Rename failed: " + temp_file);
  389. ret = "ERROR";
  390. continue;
  391. }
  392. }
  393. mz_zip_reader_end(&zip_archive);
  394. return ret;
  395. }