server_help.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK)
  94. {
  95. fclose(fd);
  96. ESP_LOGE(TAG, "File sending failed!");
  97. /* Abort sending file */
  98. httpd_resp_sendstr_chunk(req, NULL);
  99. /* Respond with 500 Internal Server Error */
  100. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file");
  101. return ESP_FAIL;
  102. }
  103. /* Keep looping till the whole file is sent */
  104. } while (chunksize != 0);
  105. /* Close file after sending complete */
  106. fclose(fd);
  107. ESP_LOGD(TAG, "File sending complete");
  108. return ESP_OK;
  109. }
  110. /* Copies the full path into destination buffer and returns
  111. * pointer to path (skipping the preceding base path) */
  112. const char *get_path_from_uri(char *dest, const char *base_path, const char *uri, size_t destsize)
  113. {
  114. const size_t base_pathlen = strlen(base_path);
  115. size_t pathlen = strlen(uri);
  116. const char *quest = strchr(uri, '?');
  117. if (quest)
  118. {
  119. pathlen = MIN(pathlen, quest - uri);
  120. }
  121. const char *hash = strchr(uri, '#');
  122. if (hash)
  123. {
  124. pathlen = MIN(pathlen, hash - uri);
  125. }
  126. if (base_pathlen + pathlen + 1 > destsize)
  127. {
  128. /* Full path string won't fit into destination buffer */
  129. return NULL;
  130. }
  131. /* Construct full path (base + path) */
  132. strcpy(dest, base_path);
  133. strlcpy(dest + base_pathlen, uri, pathlen + 1);
  134. /* Return pointer to path, skipping the base */
  135. return dest + base_pathlen;
  136. }
  137. /* Set HTTP response content type according to file extension */
  138. esp_err_t set_content_type_from_file(httpd_req_t *req, const char *filename)
  139. {
  140. if (IS_FILE_EXT(filename, ".pdf"))
  141. {
  142. return httpd_resp_set_type(req, "application/x-pdf");
  143. }
  144. else if (IS_FILE_EXT(filename, ".htm"))
  145. {
  146. return httpd_resp_set_type(req, "text/html");
  147. }
  148. else if (IS_FILE_EXT(filename, ".html"))
  149. {
  150. return httpd_resp_set_type(req, "text/html");
  151. }
  152. else if (IS_FILE_EXT(filename, ".jpeg"))
  153. {
  154. return httpd_resp_set_type(req, "image/jpeg");
  155. }
  156. else if (IS_FILE_EXT(filename, ".jpg"))
  157. {
  158. return httpd_resp_set_type(req, "image/jpeg");
  159. }
  160. else if (IS_FILE_EXT(filename, ".gif"))
  161. {
  162. return httpd_resp_set_type(req, "image/gif");
  163. }
  164. else if (IS_FILE_EXT(filename, ".png"))
  165. {
  166. return httpd_resp_set_type(req, "image/png");
  167. }
  168. else if (IS_FILE_EXT(filename, ".ico"))
  169. {
  170. return httpd_resp_set_type(req, "image/x-icon");
  171. }
  172. else if (IS_FILE_EXT(filename, ".js"))
  173. {
  174. return httpd_resp_set_type(req, "application/javascript");
  175. }
  176. else if (IS_FILE_EXT(filename, ".css"))
  177. {
  178. return httpd_resp_set_type(req, "text/css");
  179. }
  180. else if (IS_FILE_EXT(filename, ".xml"))
  181. {
  182. return httpd_resp_set_type(req, "text/xml");
  183. }
  184. else if (IS_FILE_EXT(filename, ".zip"))
  185. {
  186. return httpd_resp_set_type(req, "application/x-zip");
  187. }
  188. else if (IS_FILE_EXT(filename, ".gz"))
  189. {
  190. return httpd_resp_set_type(req, "application/x-gzip");
  191. }
  192. /* This is a limited set only */
  193. /* For any other type always set as plain text */
  194. return httpd_resp_set_type(req, "text/plain");
  195. }
  196. struct unzip_context_t
  197. {
  198. FILE *file;
  199. };
  200. static size_t unzip_write_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)
  201. {
  202. (void)file_ofs;
  203. unzip_context_t *ctx = (unzip_context_t *)pOpaque;
  204. if (!ctx || !ctx->file)
  205. {
  206. return 0;
  207. }
  208. size_t written = fwrite(pBuf, 1, n, ctx->file);
  209. if (written != n)
  210. {
  211. return 0;
  212. }
  213. return written;
  214. }
  215. 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)
  216. {
  217. DeleteFile(output_file);
  218. FILE *pFile = fopen(output_file.c_str(), "wb");
  219. if (!pFile)
  220. {
  221. return false;
  222. }
  223. setvbuf(pFile, NULL, _IOFBF, SERVER_FILER_SCRATCH_BUFSIZE);
  224. unzip_context_t ctx;
  225. ctx.file = pFile;
  226. mz_bool status = mz_zip_reader_extract_to_callback(zip_archive, i, unzip_write_callback, &ctx, 0);
  227. fclose(pFile);
  228. if (!status)
  229. {
  230. DeleteFile(output_file);
  231. return false;
  232. }
  233. return true;
  234. }
  235. void unzip_file(std::string _in_zip_file, std::string _target_directory)
  236. {
  237. mz_zip_archive zip_archive;
  238. ESP_LOGD(TAG, "Zipfile: %s", _in_zip_file.c_str());
  239. ESP_LOGD(TAG, "Target Dir: %s", _target_directory.c_str());
  240. memset(&zip_archive, 0, sizeof(zip_archive));
  241. if (!mz_zip_reader_init_file(&zip_archive, _in_zip_file.c_str(), 0))
  242. {
  243. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "mz_zip_reader_init_file() failed!");
  244. return;
  245. }
  246. int numberoffiles = (int)mz_zip_reader_get_num_files(&zip_archive);
  247. for (int i = 0; i < numberoffiles; i++)
  248. {
  249. mz_zip_archive_file_stat file_stat;
  250. if (!mz_zip_reader_file_stat(&zip_archive, i, &file_stat))
  251. {
  252. continue;
  253. }
  254. if (file_stat.m_is_directory)
  255. {
  256. continue;
  257. }
  258. std::string out_file = _target_directory + std::string(file_stat.m_filename);
  259. ESP_LOGD(TAG, "Extract: %s", out_file.c_str());
  260. bool ok = unzip_extract_file(&zip_archive, i, out_file, file_stat);
  261. if (!ok)
  262. {
  263. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Extract failed: " + std::string(file_stat.m_filename));
  264. continue;
  265. }
  266. }
  267. mz_zip_reader_end(&zip_archive);
  268. }
  269. 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)
  270. {
  271. mz_zip_archive zip_archive;
  272. ESP_LOGD(TAG, "Zipfile: %s", _in_zip_file.c_str());
  273. memset(&zip_archive, 0, sizeof(zip_archive));
  274. if (!mz_zip_reader_init_file(&zip_archive, _in_zip_file.c_str(), 0))
  275. {
  276. ESP_LOGD(TAG, "mz_zip_reader_init_file() failed!");
  277. return "";
  278. }
  279. int numberoffiles = (int)mz_zip_reader_get_num_files(&zip_archive);
  280. std::string ret = "";
  281. for (int i = 0; i < numberoffiles; i++)
  282. {
  283. mz_zip_archive_file_stat file_stat;
  284. if (!mz_zip_reader_file_stat(&zip_archive, i, &file_stat))
  285. {
  286. continue;
  287. }
  288. if (file_stat.m_is_directory)
  289. {
  290. continue;
  291. }
  292. std::string path(file_stat.m_filename);
  293. std::string logical_path;
  294. if (toUpper(path) == "FIRMWARE.BIN")
  295. {
  296. logical_path = _target_bin + path;
  297. ret = logical_path;
  298. }
  299. else
  300. {
  301. std::string dir = getDirectory(path);
  302. if (dir == "config-initial" && !_initial_setup)
  303. {
  304. continue;
  305. }
  306. std::string modified = path;
  307. std::string _s1 = "config-initial";
  308. std::string _dir_new = "config";
  309. FindReplace(modified, _s1, _dir_new);
  310. if (!dir.empty())
  311. {
  312. logical_path = _main + modified;
  313. }
  314. else
  315. {
  316. logical_path = _html_tmp + modified;
  317. }
  318. }
  319. if (logical_path.find(_html_final) == 0)
  320. {
  321. FindReplace(logical_path, _html_final, _html_tmp);
  322. }
  323. std::string temp_file = logical_path + SUFFIX_ZW;
  324. std::string folder = temp_file.substr(0, temp_file.find_last_of('/'));
  325. MakeDir(folder);
  326. ESP_LOGI(TAG, "Extract: %s", temp_file.c_str());
  327. bool ok = unzip_extract_file(&zip_archive, i, temp_file, file_stat);
  328. if (!ok)
  329. {
  330. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Extract failed: " + std::string(file_stat.m_filename));
  331. ret = "ERROR";
  332. continue;
  333. }
  334. DeleteFile(logical_path);
  335. if (!RenameFile(temp_file, logical_path))
  336. {
  337. DeleteFile(temp_file);
  338. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Rename failed: " + temp_file);
  339. ret = "ERROR";
  340. continue;
  341. }
  342. }
  343. mz_zip_reader_end(&zip_archive);
  344. return ret;
  345. }