server_file.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. /* HTTP File Server Example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include "server_file.h"
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <string>
  11. #include <sys/param.h>
  12. #include <sys/unistd.h>
  13. #include <sys/stat.h>
  14. #include "esp_err.h"
  15. #include "esp_log.h"
  16. #include "esp_timer.h"
  17. #include <iostream>
  18. #include <sys/types.h>
  19. #include <dirent.h>
  20. #include "esp_vfs.h"
  21. #include <esp_spiffs.h>
  22. #include "esp_http_server.h"
  23. #include "../../include/defines.h"
  24. #include "ClassLogFile.h"
  25. #include "MainFlowControl.h"
  26. #include "server_help.h"
  27. #include "md5.h"
  28. #ifdef ENABLE_MQTT
  29. #include "interface_mqtt.h"
  30. #endif // ENABLE_MQTT
  31. #include "server_GPIO.h"
  32. #include "Helper.h"
  33. #include "basic_auth.h"
  34. static const char *TAG = "OTA FILE";
  35. // Measure file/log HTTP handlers that share the single esp_http_server task.
  36. // Log only slow handlers to keep the instrumentation lightweight.
  37. class FileHandlerTiming
  38. {
  39. public:
  40. FileHandlerTiming(const char *handlerName, httpd_req_t *request)
  41. : name(handlerName), uri(request->uri), startUs(esp_timer_get_time())
  42. {
  43. }
  44. ~FileHandlerTiming()
  45. {
  46. const int64_t elapsedUs = esp_timer_get_time() - startUs;
  47. if (elapsedUs >= 250000)
  48. {
  49. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  50. std::string("Slow HTTP file handler: ") + name + " " + uri +
  51. " took " + std::to_string((long long)(elapsedUs / 1000)) + " ms");
  52. }
  53. }
  54. private:
  55. const char *name;
  56. const char *uri;
  57. int64_t startUs;
  58. };
  59. struct file_server_data
  60. {
  61. /* Base path of file storage */
  62. char base_path[ESP_VFS_PATH_MAX + 1];
  63. /* Scratch buffer for temporary storage during file transfer */
  64. char scratch[SERVER_FILER_SCRATCH_BUFSIZE];
  65. };
  66. static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file);
  67. static esp_err_t send_datafile(httpd_req_t *req, bool send_full_file);
  68. esp_err_t get_numbers_file_handler(httpd_req_t *req)
  69. {
  70. std::string ret = flowctrl.getNumbersName();
  71. // ESP_LOGI(TAG, "Result get_numbers_file_handler: %s", ret.c_str());
  72. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  73. httpd_resp_set_type(req, "text/plain");
  74. httpd_resp_sendstr_chunk(req, ret.c_str());
  75. httpd_resp_sendstr_chunk(req, NULL);
  76. return ESP_OK;
  77. }
  78. esp_err_t get_data_file_handler(httpd_req_t *req)
  79. {
  80. struct dirent *entry;
  81. std::string _filename, _fileext;
  82. size_t pos = 0;
  83. const char verz_name[] = "/sdcard/log/data";
  84. ESP_LOGD(TAG, "Suche data files in /sdcard/log/data");
  85. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  86. httpd_resp_set_type(req, "text/plain");
  87. DIR *dir = opendir(verz_name);
  88. while ((entry = readdir(dir)) != NULL)
  89. {
  90. _filename = std::string(entry->d_name);
  91. ESP_LOGD(TAG, "File: %s", _filename.c_str());
  92. // ignore all files with starting dot (hidden files)
  93. if (_filename.rfind(".", 0) == 0)
  94. {
  95. continue;
  96. }
  97. _fileext = _filename;
  98. pos = _fileext.find_last_of(".");
  99. if (pos != std::string::npos)
  100. _fileext = _fileext.erase(0, pos + 1);
  101. ESP_LOGD(TAG, " Extension: %s", _fileext.c_str());
  102. if (_fileext == "csv")
  103. {
  104. _filename = _filename + "\t";
  105. httpd_resp_sendstr_chunk(req, _filename.c_str());
  106. }
  107. }
  108. closedir(dir);
  109. httpd_resp_sendstr_chunk(req, NULL);
  110. return ESP_OK;
  111. }
  112. static void append_json_string(std::string &json, const std::string &value)
  113. {
  114. static const char hex[] = "0123456789abcdef";
  115. json += '"';
  116. for (unsigned char c : value)
  117. {
  118. switch (c)
  119. {
  120. case '"': json += "\\\""; break;
  121. case '\\': json += "\\\\"; break;
  122. case '\b': json += "\\b"; break;
  123. case '\f': json += "\\f"; break;
  124. case '\n': json += "\\n"; break;
  125. case '\r': json += "\\r"; break;
  126. case '\t': json += "\\t"; break;
  127. default:
  128. if (c < 0x20)
  129. {
  130. json += "\\u00";
  131. json += hex[(c >> 4) & 0x0f];
  132. json += hex[c & 0x0f];
  133. }
  134. else
  135. {
  136. json += static_cast<char>(c);
  137. }
  138. break;
  139. }
  140. }
  141. json += '"';
  142. }
  143. static std::string collect_file_list(const char *directory, bool model_files)
  144. {
  145. std::string result;
  146. DIR *dir = opendir(directory);
  147. if (!dir)
  148. {
  149. ESP_LOGW(TAG, "Cannot open list directory: %s", directory);
  150. return result;
  151. }
  152. struct dirent *entry;
  153. while ((entry = readdir(dir)) != NULL)
  154. {
  155. const std::string filename(entry->d_name);
  156. if (filename.empty() || filename[0] == '.')
  157. continue;
  158. const size_t dot = filename.find_last_of('.');
  159. const std::string extension = dot == std::string::npos ? "" : filename.substr(dot + 1);
  160. const bool accepted = model_files
  161. ? (extension == "tfl" || extension == "tflite")
  162. : (extension == "csv");
  163. if (accepted)
  164. {
  165. if (model_files)
  166. result += "/config/";
  167. result += filename;
  168. result += '\t';
  169. }
  170. }
  171. closedir(dir);
  172. return result;
  173. }
  174. esp_err_t get_editflow_lists_file_handler(httpd_req_t *req)
  175. {
  176. const std::string numbers = flowctrl.getNumbersName();
  177. const std::string data = collect_file_list("/sdcard/log/data", false);
  178. const std::string tflite = collect_file_list("/sdcard/config", true);
  179. std::string response;
  180. response.reserve(numbers.size() + data.size() + tflite.size() + 64);
  181. response += "{\"numbers\":";
  182. append_json_string(response, numbers);
  183. response += ",\"data\":";
  184. append_json_string(response, data);
  185. response += ",\"tflite\":";
  186. append_json_string(response, tflite);
  187. response += "}";
  188. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  189. httpd_resp_set_type(req, "application/json");
  190. return httpd_resp_send(req, response.c_str(), response.length());
  191. }
  192. esp_err_t get_tflite_file_handler(httpd_req_t *req)
  193. {
  194. struct dirent *entry;
  195. std::string _filename, _fileext;
  196. size_t pos = 0;
  197. const char verz_name[] = "/sdcard/config";
  198. ESP_LOGD(TAG, "Suche TFLITE in /sdcard/config/");
  199. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  200. httpd_resp_set_type(req, "text/plain");
  201. DIR *dir = opendir(verz_name);
  202. while ((entry = readdir(dir)) != NULL)
  203. {
  204. _filename = std::string(entry->d_name);
  205. ESP_LOGD(TAG, "File: %s", _filename.c_str());
  206. // ignore all files with starting dot (hidden files)
  207. if (_filename.rfind(".", 0) == 0)
  208. {
  209. continue;
  210. }
  211. _fileext = _filename;
  212. pos = _fileext.find_last_of(".");
  213. if (pos != std::string::npos)
  214. _fileext = _fileext.erase(0, pos + 1);
  215. ESP_LOGD(TAG, " Extension: %s", _fileext.c_str());
  216. if ((_fileext == "tfl") || (_fileext == "tflite"))
  217. {
  218. _filename = "/config/" + _filename + "\t";
  219. httpd_resp_sendstr_chunk(req, _filename.c_str());
  220. }
  221. }
  222. closedir(dir);
  223. httpd_resp_sendstr_chunk(req, NULL);
  224. return ESP_OK;
  225. }
  226. /* Send HTTP response with a run-time generated html consisting of
  227. * a list of all files and folders under the requested path.
  228. * In case of SPIFFS this returns empty list when path is any
  229. * string other than '/', since SPIFFS doesn't support directories */
  230. static esp_err_t http_resp_dir_html(httpd_req_t *req, const char *dirpath, const char *uripath, bool readonly)
  231. {
  232. char entrypath[FILE_PATH_MAX];
  233. char entrysize[16];
  234. const char *entrytype;
  235. struct dirent *entry;
  236. struct stat entry_stat;
  237. char dirpath_corrected[FILE_PATH_MAX];
  238. strcpy(dirpath_corrected, dirpath);
  239. file_server_data *server_data = (file_server_data *)req->user_ctx;
  240. if ((strlen(dirpath_corrected) - 1) > strlen(server_data->base_path))
  241. {
  242. // if dirpath is not mountpoint, the last "\" needs to be removed
  243. dirpath_corrected[strlen(dirpath_corrected) - 1] = '\0';
  244. }
  245. DIR *pdir = opendir(dirpath_corrected);
  246. const size_t dirpath_len = strlen(dirpath);
  247. ESP_LOGD(TAG, "Dirpath: <%s>, Pathlength: %d", dirpath, dirpath_len);
  248. // Retrieve the base path of file storage to construct the full path
  249. strlcpy(entrypath, dirpath, sizeof(entrypath));
  250. ESP_LOGD(TAG, "entrypath: <%s>", entrypath);
  251. if (!pdir)
  252. {
  253. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to stat dir: " + std::string(dirpath) + "!");
  254. // Respond with 404 Not Found
  255. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404());
  256. return ESP_FAIL;
  257. }
  258. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  259. // Send HTML file header
  260. httpd_resp_sendstr_chunk(req, "<!DOCTYPE html><html lang=\"en\" xml:lang=\"en\"><head>");
  261. httpd_resp_sendstr_chunk(req, "<link href=\"/file_server.css\" rel=\"stylesheet\">");
  262. httpd_resp_sendstr_chunk(req, "<link href=\"/firework.css\" rel=\"stylesheet\">");
  263. httpd_resp_sendstr_chunk(req, "<script type=\"text/javascript\" src=\"/jquery-3.6.0.min.js\"></script>");
  264. httpd_resp_sendstr_chunk(req, "<script type=\"text/javascript\" src=\"/firework.js\"></script></head>");
  265. httpd_resp_sendstr_chunk(req, "<body>");
  266. httpd_resp_sendstr_chunk(req, "<table class=\"fixed\" border=\"0\" width=100% style=\"font-family: arial\">");
  267. httpd_resp_sendstr_chunk(req, "<tr><td style=\"vertical-align: top;width: 300px;\"><h2>Fileserver</h2></td>"
  268. "<td rowspan=\"2\"><table border=\"0\" style=\"width:100%\"><tr><td style=\"width:80px\">"
  269. "<label for=\"newfile\">Source</label></td><td colspan=\"2\">"
  270. "<input id=\"newfile\" type=\"file\" onchange=\"setpath()\" style=\"width:100%;\"></td></tr>"
  271. "<tr><td><label for=\"filepath\">Destination</label></td><td>"
  272. "<input id=\"filepath\" type=\"text\" style=\"width:94%;\"></td><td>"
  273. "<button id=\"upload\" type=\"button\" class=\"button\" onclick=\"upload()\">Upload</button></td></tr>"
  274. "</table></td></tr><tr></tr><tr><td colspan=\"2\">"
  275. "<button style=\"font-size:16px; padding: 5px 10px\" id=\"dirup\" type=\"button\" onclick=\"dirup()\""
  276. "disabled>&#129145; Directory up</button><span style=\"padding-left:15px\" id=\"currentpath\">"
  277. "</span></td></tr>");
  278. httpd_resp_sendstr_chunk(req, "</table>");
  279. httpd_resp_sendstr_chunk(req, "<script type=\"text/javascript\" src=\"/file_server.js\"></script>");
  280. httpd_resp_sendstr_chunk(req, "<script type=\"text/javascript\">initFileServer();</script>");
  281. std::string _zw = std::string(dirpath);
  282. _zw = _zw.substr(8, _zw.length() - 8);
  283. _zw = "/delete/" + _zw + "?task=deldircontent";
  284. // Send file-list table definition and column labels
  285. httpd_resp_sendstr_chunk(req, "<table id=\"files_table\">"
  286. "<col width=\"800px\"><col width=\"300px\"><col width=\"300px\"><col width=\"100px\">"
  287. "<thead><tr><th>Name</th><th>Type</th><th>Size</th>");
  288. if (!readonly)
  289. {
  290. httpd_resp_sendstr_chunk(req, "<th><form method=\"post\" action=\"");
  291. httpd_resp_sendstr_chunk(req, _zw.c_str());
  292. httpd_resp_sendstr_chunk(req, "\"><button type=\"submit\">DELETE ALL!</button></form></th></tr>");
  293. }
  294. httpd_resp_sendstr_chunk(req, "</thead><tbody>\n");
  295. // Iterate over all files / folders and fetch their names and sizes
  296. while ((entry = readdir(pdir)) != NULL)
  297. {
  298. // wlan.ini soll nicht angezeigt werden!
  299. if (strcmp("wlan.ini", entry->d_name) != 0)
  300. {
  301. entrytype = (entry->d_type == DT_DIR ? "directory" : "file");
  302. strlcpy(entrypath + dirpath_len, entry->d_name, sizeof(entrypath) - dirpath_len);
  303. ESP_LOGD(TAG, "Entrypath: %s", entrypath);
  304. if (stat(entrypath, &entry_stat) == -1)
  305. {
  306. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to stat " + std::string(entrytype) + ": " + std::string(entry->d_name));
  307. continue;
  308. }
  309. if (entry->d_type == DT_DIR)
  310. {
  311. strcpy(entrysize, "-\0");
  312. }
  313. else
  314. {
  315. if (entry_stat.st_size >= 1024)
  316. {
  317. sprintf(entrysize, "%ld KiB", entry_stat.st_size / 1024); // kBytes
  318. }
  319. else
  320. {
  321. sprintf(entrysize, "%ld B", entry_stat.st_size); // Bytes
  322. }
  323. }
  324. ESP_LOGD(TAG, "Found %s: %s (%s bytes)", entrytype, entry->d_name, entrysize);
  325. // Send chunk of HTML file containing table entries with file name and size
  326. httpd_resp_sendstr_chunk(req, "<tr><td><a href=\"");
  327. httpd_resp_sendstr_chunk(req, "/fileserver");
  328. httpd_resp_sendstr_chunk(req, uripath);
  329. httpd_resp_sendstr_chunk(req, entry->d_name);
  330. if (entry->d_type == DT_DIR)
  331. {
  332. httpd_resp_sendstr_chunk(req, "/");
  333. }
  334. httpd_resp_sendstr_chunk(req, "\">");
  335. httpd_resp_sendstr_chunk(req, entry->d_name);
  336. httpd_resp_sendstr_chunk(req, "</a></td><td>");
  337. httpd_resp_sendstr_chunk(req, entrytype);
  338. httpd_resp_sendstr_chunk(req, "</td><td>");
  339. httpd_resp_sendstr_chunk(req, entrysize);
  340. if (!readonly)
  341. {
  342. httpd_resp_sendstr_chunk(req, "</td><td>");
  343. httpd_resp_sendstr_chunk(req, "<form method=\"post\" action=\"/delete");
  344. httpd_resp_sendstr_chunk(req, uripath);
  345. httpd_resp_sendstr_chunk(req, entry->d_name);
  346. httpd_resp_sendstr_chunk(req, "\"><button type=\"submit\">Delete</button></form>");
  347. }
  348. httpd_resp_sendstr_chunk(req, "</td></tr>\n");
  349. }
  350. }
  351. closedir(pdir);
  352. // Finish the file list table
  353. httpd_resp_sendstr_chunk(req, "</tbody></table>");
  354. // Send remaining chunk of HTML file to complete it
  355. httpd_resp_sendstr_chunk(req, "</body></html>");
  356. // Send empty chunk to signal HTTP response completion
  357. httpd_resp_sendstr_chunk(req, NULL);
  358. return ESP_OK;
  359. }
  360. static esp_err_t logfileact_get_full_handler(httpd_req_t *req)
  361. {
  362. return send_logfile(req, true);
  363. }
  364. static esp_err_t logfileact_get_last_part_handler(httpd_req_t *req)
  365. {
  366. return send_logfile(req, false);
  367. }
  368. static esp_err_t datafileact_get_full_handler(httpd_req_t *req)
  369. {
  370. return send_datafile(req, true);
  371. }
  372. static esp_err_t datafileact_get_last_part_handler(httpd_req_t *req)
  373. {
  374. return send_datafile(req, false);
  375. }
  376. static esp_err_t send_datafile(httpd_req_t *req, bool send_full_file)
  377. {
  378. FileHandlerTiming timing("send_datafile", req);
  379. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "data_get_last_part_handler");
  380. FILE *fd = NULL;
  381. // struct stat file_stat;
  382. ESP_LOGD(TAG, "uri: %s", req->uri);
  383. std::string currentfilename = LogFile.GetCurrentFileNameData();
  384. ESP_LOGD(TAG, "uri: %s, filename: %s, filepath: %s", req->uri, currentfilename.c_str(), currentfilename.c_str());
  385. fd = fopen(currentfilename.c_str(), "r");
  386. if (!fd)
  387. {
  388. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read file: " + currentfilename + "!");
  389. /* Respond with 404 Error */
  390. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404());
  391. return ESP_FAIL;
  392. }
  393. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  394. // ESP_LOGI(TAG, "Sending file: %s (%ld bytes)...", &filename, file_stat.st_size);
  395. set_content_type_from_file(req, currentfilename.c_str());
  396. if (!send_full_file)
  397. { // Send only last part of file
  398. ESP_LOGD(TAG, "Sending last %d bytes of the actual datafile!", LOGFILE_LAST_PART_BYTES);
  399. /* Adapted from https://www.geeksforgeeks.org/implement-your-own-tail-read-last-n-lines-of-a-huge-file/ */
  400. if (fseek(fd, 0, SEEK_END))
  401. {
  402. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to get to end of file!");
  403. fclose(fd);
  404. return ESP_FAIL;
  405. }
  406. else
  407. {
  408. long pos = ftell(fd); // Number of bytes in the file
  409. ESP_LOGI(TAG, "File contains %ld bytes", pos);
  410. if (fseek(fd, pos - std::min((long)LOGFILE_LAST_PART_BYTES, pos), SEEK_SET))
  411. { // Go LOGFILE_LAST_PART_BYTES bytes back from EOF
  412. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to go back " + to_string(std::min((long)LOGFILE_LAST_PART_BYTES, pos)) + " bytes within the file!");
  413. fclose(fd);
  414. return ESP_FAIL;
  415. }
  416. }
  417. /* Find end of line (a file without a newline, e.g. empty after a power cut, must not loop forever) */
  418. int c;
  419. do
  420. {
  421. c = fgetc(fd);
  422. } while ((c != EOF) && (c != '\n'));
  423. }
  424. /* Retrieve the pointer to scratch buffer for temporary storage */
  425. char *chunk = ((struct file_server_data *)req->user_ctx)->scratch;
  426. size_t chunksize;
  427. do
  428. {
  429. /* Read file in chunks into the scratch buffer */
  430. chunksize = fread(chunk, 1, SERVER_FILER_SCRATCH_BUFSIZE, fd);
  431. /* Send the buffer contents as HTTP response chunk */
  432. if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK)
  433. {
  434. fclose(fd);
  435. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File sending failed!");
  436. /* Abort sending file */
  437. httpd_resp_sendstr_chunk(req, NULL);
  438. /* Respond with 500 Internal Server Error */
  439. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file");
  440. return ESP_FAIL;
  441. }
  442. /* Keep looping till the whole file is sent (the last, empty chunk terminates the response) */
  443. } while (chunksize != 0);
  444. /* Close file after sending complete */
  445. fclose(fd);
  446. ESP_LOGI(TAG, "File sending complete");
  447. return ESP_OK;
  448. }
  449. static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file)
  450. {
  451. FileHandlerTiming timing("send_logfile", req);
  452. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "log_get_last_part_handler");
  453. FILE *fd = NULL;
  454. // struct stat file_stat;
  455. ESP_LOGI(TAG, "uri: %s", req->uri);
  456. const char *filename = "";
  457. std::string currentfilename = LogFile.GetCurrentFileName();
  458. ESP_LOGD(TAG, "uri: %s, filename: %s, filepath: %s", req->uri, filename, currentfilename.c_str());
  459. // Since the log file is still could open for writing, we need to close it first
  460. LogFile.CloseLogFileAppendHandle();
  461. fd = fopen(currentfilename.c_str(), "r");
  462. if (!fd)
  463. {
  464. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read file: " + currentfilename + "!");
  465. /* Respond with 404 Error */
  466. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404());
  467. return ESP_FAIL;
  468. }
  469. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  470. // ESP_LOGI(TAG, "Sending file: %s (%ld bytes)...", &filename, file_stat.st_size);
  471. set_content_type_from_file(req, filename);
  472. if (!send_full_file)
  473. { // Send only last part of file
  474. ESP_LOGD(TAG, "Sending last %d bytes of the actual logfile!", LOGFILE_LAST_PART_BYTES);
  475. /* Adapted from https://www.geeksforgeeks.org/implement-your-own-tail-read-last-n-lines-of-a-huge-file/ */
  476. if (fseek(fd, 0, SEEK_END))
  477. {
  478. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to get to end of file!");
  479. fclose(fd);
  480. return ESP_FAIL;
  481. }
  482. else
  483. {
  484. long pos = ftell(fd); // Number of bytes in the file
  485. ESP_LOGI(TAG, "File contains %ld bytes", pos);
  486. if (fseek(fd, pos - std::min((long)LOGFILE_LAST_PART_BYTES, pos), SEEK_SET))
  487. { // Go LOGFILE_LAST_PART_BYTES bytes back from EOF
  488. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to go back " + to_string(std::min((long)LOGFILE_LAST_PART_BYTES, pos)) + " bytes within the file!");
  489. fclose(fd);
  490. return ESP_FAIL;
  491. }
  492. }
  493. /* Find end of line (a file without a newline, e.g. empty after a power cut, must not loop forever) */
  494. int c;
  495. do
  496. {
  497. c = fgetc(fd);
  498. } while ((c != EOF) && (c != '\n'));
  499. }
  500. /* Retrieve the pointer to scratch buffer for temporary storage */
  501. char *chunk = ((struct file_server_data *)req->user_ctx)->scratch;
  502. size_t chunksize;
  503. do
  504. {
  505. /* Read file in chunks into the scratch buffer */
  506. chunksize = fread(chunk, 1, SERVER_FILER_SCRATCH_BUFSIZE, fd);
  507. /* Send the buffer contents as HTTP response chunk */
  508. if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK)
  509. {
  510. fclose(fd);
  511. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File sending failed!");
  512. /* Abort sending file */
  513. httpd_resp_sendstr_chunk(req, NULL);
  514. /* Respond with 500 Internal Server Error */
  515. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file");
  516. return ESP_FAIL;
  517. }
  518. /* Keep looping till the whole file is sent (the last, empty chunk terminates the response) */
  519. } while (chunksize != 0);
  520. /* Close file after sending complete */
  521. fclose(fd);
  522. ESP_LOGD(TAG, "File sending complete");
  523. return ESP_OK;
  524. }
  525. /* Handler to download a file kept on the server */
  526. static esp_err_t download_get_handler(httpd_req_t *req)
  527. {
  528. FileHandlerTiming timing("download_get_handler", req);
  529. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "download_get_handler");
  530. char filepath[FILE_PATH_MAX];
  531. FILE *fd = NULL;
  532. struct stat file_stat;
  533. ESP_LOGD(TAG, "uri: %s", req->uri);
  534. const char *filename = get_path_from_uri(filepath, ((struct file_server_data *)req->user_ctx)->base_path,
  535. req->uri + sizeof("/fileserver") - 1, sizeof(filepath));
  536. ESP_LOGD(TAG, "uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  537. // filename = get_path_from_uri(filepath, ((struct file_server_data *)req->user_ctx)->base_path,
  538. // req->uri, sizeof(filepath));
  539. if (!filename)
  540. {
  541. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Filename is too long");
  542. /* Respond with 414 Error */
  543. httpd_resp_send_err(req, HTTPD_414_URI_TOO_LONG, "Filename too long");
  544. return ESP_FAIL;
  545. }
  546. /* If name has trailing '/', respond with directory contents */
  547. if (filename[strlen(filename) - 1] == '/')
  548. {
  549. bool readonly = false;
  550. size_t buf_len = httpd_req_get_url_query_len(req) + 1;
  551. if (buf_len > 1)
  552. {
  553. char buf[buf_len];
  554. if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK)
  555. {
  556. ESP_LOGI(TAG, "Found URL query => %s", buf);
  557. char param[32];
  558. /* Get value of expected key from query string */
  559. if (httpd_query_key_value(buf, "readonly", param, sizeof(param)) == ESP_OK)
  560. {
  561. ESP_LOGI(TAG, "Found URL query parameter => readonly=%s", param);
  562. readonly = (strcmp(param, "true") == 0);
  563. }
  564. }
  565. }
  566. ESP_LOGD(TAG, "uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  567. return http_resp_dir_html(req, filepath, filename, readonly);
  568. }
  569. std::string testwlan = toUpper(std::string(filename));
  570. if ((stat(filepath, &file_stat) == -1) || (testwlan.compare("/WLAN.INI") == 0))
  571. { // wlan.ini soll nicht angezeigt werden!
  572. /* If file not present on SPIFFS check if URI
  573. * corresponds to one of the hardcoded paths */
  574. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to stat file: " + std::string(filepath) + "!");
  575. /* Respond with 404 Not Found */
  576. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404());
  577. return ESP_FAIL;
  578. }
  579. fd = fopen(filepath, "r");
  580. if (!fd)
  581. {
  582. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read file: " + std::string(filepath) + "!");
  583. /* Respond with 404 Error */
  584. httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404());
  585. return ESP_FAIL;
  586. }
  587. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  588. ESP_LOGD(TAG, "Sending file: %s (%ld bytes)...", filename, file_stat.st_size);
  589. set_content_type_from_file(req, filename);
  590. /* Retrieve the pointer to scratch buffer for temporary storage */
  591. char *chunk = ((struct file_server_data *)req->user_ctx)->scratch;
  592. size_t chunksize;
  593. do
  594. {
  595. /* Read file in chunks into the scratch buffer */
  596. chunksize = fread(chunk, 1, SERVER_FILER_SCRATCH_BUFSIZE, fd);
  597. /* Send buffer contents as HTTP chunk. If empty this functions as a
  598. * last-chunk message, signaling end-of-response, to the HTTP client.
  599. * See RFC 2616, section 3.6.1 for details on Chunked Transfer Encoding. */
  600. if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK)
  601. {
  602. fclose(fd);
  603. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File sending failed!");
  604. /* Abort sending file */
  605. httpd_resp_sendstr_chunk(req, NULL);
  606. /* Respond with 500 Internal Server Error */
  607. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file!");
  608. return ESP_FAIL;
  609. }
  610. /* Keep looping till the whole file is sent */
  611. } while (chunksize != 0);
  612. /* Close file after sending complete */
  613. fclose(fd);
  614. ESP_LOGD(TAG, "File successfully sent");
  615. return ESP_OK;
  616. }
  617. /* Handler to upload a file onto the server */
  618. static esp_err_t upload_post_handler(httpd_req_t *req)
  619. {
  620. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "upload_post_handler");
  621. char filepath[FILE_PATH_MAX];
  622. FILE *fd = NULL;
  623. struct stat file_stat;
  624. ESP_LOGI(TAG, "uri: %s", req->uri);
  625. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  626. /* Skip leading "/upload" from URI to get filename */
  627. /* Note sizeof() counts NULL termination hence the -1 */
  628. const char *filename = get_path_from_uri(filepath, ((struct file_server_data *)req->user_ctx)->base_path,
  629. req->uri + sizeof("/upload") - 1, sizeof(filepath));
  630. if (!filename)
  631. {
  632. /* Respond with 413 Error */
  633. httpd_resp_send_err(req, HTTPD_414_URI_TOO_LONG, "Filename too long");
  634. return ESP_FAIL;
  635. }
  636. /* Filename cannot have a trailing '/' */
  637. if (filename[strlen(filename) - 1] == '/')
  638. {
  639. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Invalid filename: " + string(filename));
  640. /* Respond with 400 Bad Request */
  641. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid filename");
  642. return ESP_FAIL;
  643. }
  644. if (stat(filepath, &file_stat) == 0)
  645. {
  646. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File already exists: " + string(filepath));
  647. /* Respond with 400 Bad Request */
  648. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "File already exists");
  649. return ESP_FAIL;
  650. }
  651. /* File cannot be larger than a limit */
  652. if (req->content_len > MAX_FILE_SIZE)
  653. {
  654. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File too large: " + to_string(req->content_len) + " bytes");
  655. /* Respond with 400 Bad Request */
  656. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST,
  657. "File size must be less than " MAX_FILE_SIZE_STR "!");
  658. /* Return failure to close underlying connection else the
  659. * incoming file content will keep the socket busy */
  660. return ESP_FAIL;
  661. }
  662. fd = fopen(filepath, "w");
  663. if (!fd)
  664. {
  665. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create file: " + string(filepath));
  666. /* Respond with 500 Internal Server Error */
  667. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to create file");
  668. return ESP_FAIL;
  669. }
  670. ESP_LOGI(TAG, "Receiving file: %s...", filename);
  671. /* Retrieve the pointer to scratch buffer for temporary storage */
  672. char *buf = ((struct file_server_data *)req->user_ctx)->scratch;
  673. int received;
  674. /* Content length of the request gives
  675. * the size of the file being uploaded */
  676. int remaining = req->content_len;
  677. int timeouts = 0;
  678. while (remaining > 0)
  679. {
  680. ESP_LOGI(TAG, "Remaining size: %d", remaining);
  681. /* Receive the file part by part into a buffer */
  682. if ((received = httpd_req_recv(req, buf, MIN(remaining, SERVER_FILER_SCRATCH_BUFSIZE))) <= 0)
  683. {
  684. /* Retry if timeout occurred, but give up when the client is gone (no FIN/RST after a
  685. * Wi-Fi drop): retrying forever blocks the only HTTP server task */
  686. if ((received == HTTPD_SOCK_ERR_TIMEOUT) && (++timeouts < UPLOAD_MAX_RECV_TIMEOUTS))
  687. {
  688. continue;
  689. }
  690. /* In case of unrecoverable error,
  691. * close and delete the unfinished file*/
  692. fclose(fd);
  693. unlink(filepath);
  694. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File reception failed!");
  695. /* Respond with 500 Internal Server Error */
  696. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to receive file");
  697. return ESP_FAIL;
  698. }
  699. /* Write buffer content to file on storage */
  700. if (received && (received != fwrite(buf, 1, received, fd)))
  701. {
  702. /* Couldn't write everything to file!
  703. * Storage may be full? */
  704. fclose(fd);
  705. unlink(filepath);
  706. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File write failed!");
  707. /* Respond with 500 Internal Server Error */
  708. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to write file to storage");
  709. return ESP_FAIL;
  710. }
  711. /* Keep track of remaining size of
  712. * the file left to be uploaded */
  713. remaining -= received;
  714. timeouts = 0;
  715. }
  716. /* Close file upon upload completion */
  717. fclose(fd);
  718. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "File saved: " + string(filename));
  719. ESP_LOGI(TAG, "File reception completed");
  720. string s = req->uri;
  721. if (isInString(s, "?md5"))
  722. {
  723. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Calculate and return MD5 sum...");
  724. fd = fopen(filepath, "r");
  725. if (!fd)
  726. {
  727. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to open file for reading: " + string(filepath));
  728. /* Respond with 500 Internal Server Error */
  729. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to open file for reading");
  730. return ESP_FAIL;
  731. }
  732. uint8_t result[16];
  733. string md5hex = "";
  734. string response = "{\"md5\":";
  735. char hex[3];
  736. md5File(fd, result);
  737. fclose(fd);
  738. for (int i = 0; i < sizeof(result); i++)
  739. {
  740. snprintf(hex, sizeof(hex), "%02x", result[i]);
  741. md5hex.append(hex);
  742. }
  743. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "MD5 of " + string(filepath) + ": " + md5hex);
  744. response.append("\"" + md5hex + "\"");
  745. response.append("}");
  746. httpd_resp_sendstr(req, response.c_str());
  747. }
  748. else
  749. { // Return file server page
  750. std::string directory = std::string(filepath);
  751. size_t zw = directory.find("/");
  752. size_t found = zw;
  753. while (zw != std::string::npos)
  754. {
  755. zw = directory.find("/", found + 1);
  756. if (zw != std::string::npos)
  757. found = zw;
  758. }
  759. int start_fn = strlen(((struct file_server_data *)req->user_ctx)->base_path);
  760. ESP_LOGD(TAG, "Directory: %s, start_fn: %d, found: %d", directory.c_str(), start_fn, found);
  761. directory = directory.substr(start_fn, found - start_fn + 1);
  762. directory = "/fileserver" + directory;
  763. // ESP_LOGD(TAG, "Directory danach 2: %s", directory.c_str());
  764. /* Redirect onto root to see the updated file list */
  765. if (strcmp(filename, "/config/config.ini") == 0 ||
  766. strcmp(filename, "/config/ref0.jpg") == 0 ||
  767. strcmp(filename, "/config/ref0_org.jpg") == 0 ||
  768. strcmp(filename, "/config/ref1.jpg") == 0 ||
  769. strcmp(filename, "/config/ref1_org.jpg") == 0 ||
  770. strcmp(filename, "/config/reference.jpg") == 0 ||
  771. strcmp(filename, "/img_tmp/ref0.jpg") == 0 ||
  772. strcmp(filename, "/img_tmp/ref0_org.jpg") == 0 ||
  773. strcmp(filename, "/img_tmp/ref1.jpg") == 0 ||
  774. strcmp(filename, "/img_tmp/ref1_org.jpg") == 0 ||
  775. strcmp(filename, "/img_tmp/reference.jpg") == 0)
  776. {
  777. httpd_resp_set_status(req, HTTPD_200); // Avoid reloading of folder content
  778. }
  779. else
  780. {
  781. httpd_resp_set_status(req, "303 See Other"); // Reload folder content after upload
  782. }
  783. httpd_resp_set_hdr(req, "Location", directory.c_str());
  784. httpd_resp_sendstr(req, "File uploaded successfully");
  785. }
  786. return ESP_OK;
  787. }
  788. /* Handler to delete a file from the server */
  789. static esp_err_t delete_post_handler(httpd_req_t *req)
  790. {
  791. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "delete_post_handler");
  792. char filepath[FILE_PATH_MAX];
  793. struct stat file_stat;
  794. //////////////////////////////////////////////////////////////
  795. char _query[200];
  796. char _valuechar[30];
  797. std::string fn = "/sdcard/firmware/";
  798. std::string _task;
  799. std::string directory;
  800. std::string zw;
  801. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  802. if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK)
  803. {
  804. ESP_LOGD(TAG, "Query: %s", _query);
  805. if (httpd_query_key_value(_query, "task", _valuechar, 30) == ESP_OK)
  806. {
  807. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "task is found: " + string(_valuechar));
  808. _task = std::string(_valuechar);
  809. }
  810. }
  811. if (_task.compare("deldircontent") == 0)
  812. {
  813. /* Skip leading "/delete" from URI to get filename */
  814. /* Note sizeof() counts NULL termination hence the -1 */
  815. const char *filename = get_path_from_uri(filepath, ((struct file_server_data *)req->user_ctx)->base_path,
  816. req->uri + sizeof("/delete") - 1, sizeof(filepath));
  817. if (!filename)
  818. {
  819. /* Respond with 414 Error */
  820. httpd_resp_send_err(req, HTTPD_414_URI_TOO_LONG, "Filename too long");
  821. return ESP_FAIL;
  822. }
  823. zw = std::string(filename);
  824. zw = zw.substr(0, zw.length() - 1);
  825. directory = "/fileserver" + zw + "/";
  826. zw = "/sdcard" + zw;
  827. ESP_LOGD(TAG, "Directory to delete: %s", zw.c_str());
  828. delete_all_in_directory(zw);
  829. // directory = std::string(filepath);
  830. // directory = "/fileserver" + directory;
  831. ESP_LOGD(TAG, "Location after delete directory content: %s", directory.c_str());
  832. /* Redirect onto root to see the updated file list */
  833. // httpd_resp_set_status(req, "303 See Other");
  834. // httpd_resp_set_hdr(req, "Location", directory.c_str());
  835. // httpd_resp_sendstr(req, "File deleted successfully");
  836. // return ESP_OK;
  837. }
  838. else
  839. {
  840. /* Skip leading "/delete" from URI to get filename */
  841. /* Note sizeof() counts NULL termination hence the -1 */
  842. const char *filename = get_path_from_uri(filepath, ((struct file_server_data *)req->user_ctx)->base_path,
  843. req->uri + sizeof("/delete") - 1, sizeof(filepath));
  844. if (!filename)
  845. {
  846. /* Respond with 500 Internal Server Error */
  847. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Filename too long");
  848. return ESP_FAIL;
  849. }
  850. /* Filename cannot have a trailing '/' */
  851. if (filename[strlen(filename) - 1] == '/')
  852. {
  853. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Invalid filename: " + string(filename));
  854. /* Respond with 400 Bad Request */
  855. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid filename");
  856. return ESP_FAIL;
  857. }
  858. if (strcmp(filename, "wlan.ini") == 0)
  859. {
  860. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to delete protected file : " + string(filename));
  861. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Not allowed to delete wlan.ini");
  862. return ESP_FAIL;
  863. }
  864. if (stat(filepath, &file_stat) == -1)
  865. { // File does not exist
  866. /* This is ok, we would delete it anyway */
  867. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "File does not exist: " + string(filename));
  868. }
  869. /* Delete file */
  870. unlink(filepath);
  871. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "File deleted: " + string(filename));
  872. ESP_LOGI(TAG, "File deletion completed");
  873. directory = std::string(filepath);
  874. size_t zw = directory.find("/");
  875. size_t found = zw;
  876. while (zw != std::string::npos)
  877. {
  878. zw = directory.find("/", found + 1);
  879. if (zw != std::string::npos)
  880. found = zw;
  881. }
  882. int start_fn = strlen(((struct file_server_data *)req->user_ctx)->base_path);
  883. ESP_LOGD(TAG, "Directory: %s, start_fn: %d, found: %d", directory.c_str(), start_fn, found);
  884. directory = directory.substr(start_fn, found - start_fn + 1);
  885. directory = "/fileserver" + directory;
  886. ESP_LOGD(TAG, "Directory danach 4: %s", directory.c_str());
  887. //////////////////////////////////////////////////////////////
  888. /* Redirect onto root to see the updated file list */
  889. if (strcmp(filename, "/config/config.ini") == 0 ||
  890. strcmp(filename, "/config/ref0.jpg") == 0 ||
  891. strcmp(filename, "/config/ref0_org.jpg") == 0 ||
  892. strcmp(filename, "/config/ref1.jpg") == 0 ||
  893. strcmp(filename, "/config/ref1_org.jpg") == 0 ||
  894. strcmp(filename, "/config/reference.jpg") == 0 ||
  895. strcmp(filename, "/img_tmp/ref0.jpg") == 0 ||
  896. strcmp(filename, "/img_tmp/ref0_org.jpg") == 0 ||
  897. strcmp(filename, "/img_tmp/ref1.jpg") == 0 ||
  898. strcmp(filename, "/img_tmp/ref1_org.jpg") == 0 ||
  899. strcmp(filename, "/img_tmp/reference.jpg") == 0)
  900. {
  901. httpd_resp_set_status(req, HTTPD_200); // Avoid reloading of folder content
  902. }
  903. else
  904. {
  905. httpd_resp_set_status(req, "303 See Other"); // Reload folder content after upload
  906. }
  907. }
  908. httpd_resp_set_hdr(req, "Location", directory.c_str());
  909. httpd_resp_sendstr(req, "File successfully deleted");
  910. return ESP_OK;
  911. }
  912. void delete_all_in_directory(std::string _directory)
  913. {
  914. struct dirent *entry;
  915. DIR *dir = opendir(_directory.c_str());
  916. std::string filename;
  917. if (!dir)
  918. {
  919. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to stat dir: " + _directory);
  920. return;
  921. }
  922. /* Iterate over all files / folders and fetch their names and sizes */
  923. while ((entry = readdir(dir)) != NULL)
  924. {
  925. if (!(entry->d_type == DT_DIR))
  926. {
  927. if (strcmp("wlan.ini", entry->d_name) != 0)
  928. { // auf wlan.ini soll nicht zugegriffen werden !!!
  929. filename = _directory + "/" + std::string(entry->d_name);
  930. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Deleting file: " + filename);
  931. /* Delete file */
  932. unlink(filename.c_str());
  933. }
  934. };
  935. }
  936. closedir(dir);
  937. }
  938. void register_server_file_uri(httpd_handle_t server, const char *base_path)
  939. {
  940. static struct file_server_data *server_data = NULL;
  941. if (server == NULL)
  942. {
  943. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File server handle is not available");
  944. return;
  945. }
  946. /* Validate file storage base path */
  947. if (base_path == NULL || base_path[0] == '\0')
  948. {
  949. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File server base_path not set");
  950. return;
  951. }
  952. /* Reuse the same context on server restarts instead of overwriting and leaking it. */
  953. if (server_data == NULL)
  954. {
  955. server_data = (file_server_data *)calloc(1, sizeof(struct file_server_data));
  956. if (server_data == NULL)
  957. {
  958. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate memory for server data");
  959. return;
  960. }
  961. }
  962. strlcpy(server_data->base_path, base_path,
  963. sizeof(server_data->base_path));
  964. /* URI handler for getting uploaded files */
  965. // char zw[sizeof(serverprefix)+1];
  966. // strcpy(zw, serverprefix);
  967. // zw[strlen(serverprefix)] = '*';
  968. // zw[strlen(serverprefix)+1] = '\0';
  969. // ESP_LOGD(TAG, "zw: %s", zw);
  970. httpd_uri_t file_download = {
  971. .uri = "/fileserver*", // Match all URIs of type /path/to/file
  972. .method = HTTP_GET,
  973. .handler = APPLY_BASIC_AUTH_FILTER(download_get_handler),
  974. .user_ctx = server_data // Pass server data as context
  975. };
  976. httpd_register_uri_handler(server, &file_download);
  977. httpd_uri_t file_datafileact = {
  978. .uri = "/datafileact", // Match all URIs of type /path/to/file
  979. .method = HTTP_GET,
  980. .handler = APPLY_BASIC_AUTH_FILTER(datafileact_get_full_handler),
  981. .user_ctx = server_data // Pass server data as context
  982. };
  983. httpd_register_uri_handler(server, &file_datafileact);
  984. httpd_uri_t file_datafile_last_part_handle = {
  985. .uri = "/data", // Match all URIs of type /path/to/file
  986. .method = HTTP_GET,
  987. .handler = APPLY_BASIC_AUTH_FILTER(datafileact_get_last_part_handler),
  988. .user_ctx = server_data // Pass server data as context
  989. };
  990. httpd_register_uri_handler(server, &file_datafile_last_part_handle);
  991. httpd_uri_t file_logfileact = {
  992. .uri = "/logfileact", // Match all URIs of type /path/to/file
  993. .method = HTTP_GET,
  994. .handler = APPLY_BASIC_AUTH_FILTER(logfileact_get_full_handler),
  995. .user_ctx = server_data // Pass server data as context
  996. };
  997. httpd_register_uri_handler(server, &file_logfileact);
  998. httpd_uri_t file_logfile_last_part_handle = {
  999. .uri = "/log", // Match all URIs of type /path/to/file
  1000. .method = HTTP_GET,
  1001. .handler = APPLY_BASIC_AUTH_FILTER(logfileact_get_last_part_handler),
  1002. .user_ctx = server_data // Pass server data as context
  1003. };
  1004. httpd_register_uri_handler(server, &file_logfile_last_part_handle);
  1005. /* URI handler for uploading files to server */
  1006. httpd_uri_t file_upload = {
  1007. .uri = "/upload/*", // Match all URIs of type /upload/path/to/file
  1008. .method = HTTP_POST,
  1009. .handler = APPLY_BASIC_AUTH_FILTER(upload_post_handler),
  1010. .user_ctx = server_data // Pass server data as context
  1011. };
  1012. httpd_register_uri_handler(server, &file_upload);
  1013. /* URI handler for deleting files from server */
  1014. httpd_uri_t file_delete = {
  1015. .uri = "/delete/*", // Match all URIs of type /delete/path/to/file
  1016. .method = HTTP_POST,
  1017. .handler = APPLY_BASIC_AUTH_FILTER(delete_post_handler),
  1018. .user_ctx = server_data // Pass server data as context
  1019. };
  1020. httpd_register_uri_handler(server, &file_delete);
  1021. }