server_help.cpp 11 KB

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