server_help.cpp 13 KB

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