Просмотр исходного кода

Merge pull request #4182 from alfeg/fix/http-server-robustness

fix(http): web server hangs, cross-task races and leaks in the HTTP handlers
SybexXx 1 месяц назад
Родитель
Сommit
dc368ced7a

+ 2 - 0
code/components/jomjol_controlcamera/ClassControllCamera.cpp

@@ -1195,6 +1195,7 @@ void CCamera::useDemoMode(void)
     if (demoImage == NULL)
     {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to acquire required memory for demo image!");
+        fclose(fd);
         return;
     }
 
@@ -1243,6 +1244,7 @@ bool CCamera::loadNextDemoImage(camera_fb_t *fb)
         char buf[100];
         snprintf(buf, sizeof(buf), "Demo Image (%d bytes) is larger than provided buffer (%d bytes)!", (int)fileSize, DEMO_IMAGE_SIZE);
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, std::string(buf));
+        fclose(fp);
         return false;
     }
 

+ 19 - 16
code/components/jomjol_fileserver_ota/server_file.cpp

@@ -377,6 +377,7 @@ static esp_err_t send_datafile(httpd_req_t *req, bool send_full_file)
         if (fseek(fd, 0, SEEK_END))
         {
             LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to get to end of file!");
+            fclose(fd);
             return ESP_FAIL;
         }
         else
@@ -387,18 +388,17 @@ static esp_err_t send_datafile(httpd_req_t *req, bool send_full_file)
             if (fseek(fd, pos - std::min((long)LOGFILE_LAST_PART_BYTES, pos), SEEK_SET))
             { // Go LOGFILE_LAST_PART_BYTES bytes back from EOF
                 LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to go back " + to_string(std::min((long)LOGFILE_LAST_PART_BYTES, pos)) + " bytes within the file!");
+                fclose(fd);
                 return ESP_FAIL;
             }
         }
 
-        /* Find end of line */
-        while (1)
+        /* Find end of line (a file without a newline, e.g. empty after a power cut, must not loop forever) */
+        int c;
+        do
         {
-            if (fgetc(fd) == '\n')
-            {
-                break;
-            }
-        }
+            c = fgetc(fd);
+        } while ((c != EOF) && (c != '\n'));
     }
 
     /* Retrieve the pointer to scratch buffer for temporary storage */
@@ -468,6 +468,7 @@ static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file)
         if (fseek(fd, 0, SEEK_END))
         {
             LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to get to end of file!");
+            fclose(fd);
             return ESP_FAIL;
         }
         else
@@ -478,18 +479,17 @@ static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file)
             if (fseek(fd, pos - std::min((long)LOGFILE_LAST_PART_BYTES, pos), SEEK_SET))
             { // Go LOGFILE_LAST_PART_BYTES bytes back from EOF
                 LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to go back " + to_string(std::min((long)LOGFILE_LAST_PART_BYTES, pos)) + " bytes within the file!");
+                fclose(fd);
                 return ESP_FAIL;
             }
         }
 
-        /* Find end of line */
-        while (1)
+        /* Find end of line (a file without a newline, e.g. empty after a power cut, must not loop forever) */
+        int c;
+        do
         {
-            if (fgetc(fd) == '\n')
-            {
-                break;
-            }
-        }
+            c = fgetc(fd);
+        } while ((c != EOF) && (c != '\n'));
     }
 
     /* Retrieve the pointer to scratch buffer for temporary storage */
@@ -700,6 +700,7 @@ static esp_err_t upload_post_handler(httpd_req_t *req)
     /* Content length of the request gives
      * the size of the file being uploaded */
     int remaining = req->content_len;
+    int timeouts = 0;
 
     while (remaining > 0)
     {
@@ -708,9 +709,10 @@ static esp_err_t upload_post_handler(httpd_req_t *req)
         /* Receive the file part by part into a buffer */
         if ((received = httpd_req_recv(req, buf, MIN(remaining, SERVER_FILER_SCRATCH_BUFSIZE))) <= 0)
         {
-            if (received == HTTPD_SOCK_ERR_TIMEOUT)
+            /* Retry if timeout occurred, but give up when the client is gone (no FIN/RST after a
+             * Wi-Fi drop): retrying forever blocks the only HTTP server task */
+            if ((received == HTTPD_SOCK_ERR_TIMEOUT) && (++timeouts < UPLOAD_MAX_RECV_TIMEOUTS))
             {
-                /* Retry if timeout occurred */
                 continue;
             }
 
@@ -742,6 +744,7 @@ static esp_err_t upload_post_handler(httpd_req_t *req)
         /* Keep track of remaining size of
          * the file left to be uploaded */
         remaining -= received;
+        timeouts = 0;
     }
 
     /* Close file upon upload completion */

+ 5 - 0
code/components/jomjol_flowcontroll/ClassFlowAlignment.cpp

@@ -273,6 +273,11 @@ void ClassFlowAlignment::SaveReferenceAlignmentValues()
 
     pFile = fopen(FileStoreRefAlignment.c_str(), "w");
 
+    if (pFile == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SaveReferenceAlignmentValues: Failed to open " + FileStoreRefAlignment);
+        return;
+    }
+
     if (strlen(zwtime.c_str()) == 0) {
         time_t rawtime;
         struct tm *timeinfo;

+ 28 - 20
code/components/jomjol_flowcontroll/ClassFlowControll.cpp

@@ -214,8 +214,7 @@ void ClassFlowControll::SetInitialParameter(void)
     flowpostprocessing = NULL;
     disabled = false;
     aktRunNr = 0;
-    aktstatus = "Flow task not yet created";
-    aktstatusWithTime = aktstatus;
+    setStatus("Flow task not yet created", "Flow task not yet created");
 }
 
 bool ClassFlowControll::getIsAutoStart(void)
@@ -308,8 +307,7 @@ ClassFlow* ClassFlowControll::CreateClassFlow(std::string _type)
 
 void ClassFlowControll::InitFlow(std::string config)
 {
-    aktstatus = "Initialization";
-    aktstatusWithTime = aktstatus;
+    setStatus("Initialization", "Initialization");
 
     //#ifdef ENABLE_MQTT
         //MQTTPublish(mqttServer_getMainTopic() + "/" + "status", "Initialization", 1, false); // Right now, not possible -> MQTT Service is going to be started later
@@ -354,20 +352,28 @@ void ClassFlowControll::InitFlow(std::string config)
     fclose(pFile);
 }
 
-std::string* ClassFlowControll::getActStatusWithTime()
+std::string ClassFlowControll::getActStatusWithTime()
 {
-    return &aktstatusWithTime;
+    std::lock_guard<std::mutex> lock(statusMutex);
+    return aktstatusWithTime;
 }
 
-std::string* ClassFlowControll::getActStatus()
+std::string ClassFlowControll::getActStatus()
 {
-    return &aktstatus;
+    std::lock_guard<std::mutex> lock(statusMutex);
+    return aktstatus;
+}
+
+void ClassFlowControll::setStatus(const std::string &_status, const std::string &_statusWithTime)
+{
+    std::lock_guard<std::mutex> lock(statusMutex);
+    aktstatus = _status;
+    aktstatusWithTime = _statusWithTime;
 }
 
 void ClassFlowControll::setActStatus(std::string _aktstatus)
 {
-    aktstatus = _aktstatus;
-    aktstatusWithTime = aktstatus;
+    setStatus(_aktstatus, _aktstatus);
 }
 
 void ClassFlowControll::doFlowTakeImageOnly(string time)
@@ -377,8 +383,8 @@ void ClassFlowControll::doFlowTakeImageOnly(string time)
     for (int i = 0; i < FlowControll.size(); ++i) {
         if (FlowControll[i]->name() == "ClassFlowTakeImage") {
             zw_time = getCurrentTimeString("%H:%M:%S");
-            aktstatus = TranslateAktstatus(FlowControll[i]->name());
-            aktstatusWithTime = aktstatus + " (" + zw_time + ")";
+            std::string status = TranslateAktstatus(FlowControll[i]->name());
+            setStatus(status, status + " (" + zw_time + ")");
             #ifdef ENABLE_MQTT
                 MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, 1, false);
             #endif //ENABLE_MQTT
@@ -409,8 +415,8 @@ bool ClassFlowControll::doFlow(string time)
 
     for (int i = 0; i < FlowControll.size(); ++i) {
         zw_time = getCurrentTimeString("%H:%M:%S");
-        aktstatus = TranslateAktstatus(FlowControll[i]->name());
-        aktstatusWithTime = aktstatus + " (" + zw_time + ")";
+        std::string status = TranslateAktstatus(FlowControll[i]->name());
+        setStatus(status, status + " (" + zw_time + ")");
         LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Status: " + aktstatusWithTime);
         #ifdef ENABLE_MQTT
             MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, qos, false);
@@ -442,8 +448,7 @@ bool ClassFlowControll::doFlow(string time)
     }
 
     zw_time = getCurrentTimeString("%H:%M:%S");
-    aktstatus = "Flow finished";
-    aktstatusWithTime = aktstatus + " (" + zw_time + ")";
+    setStatus("Flow finished", std::string("Flow finished (") + zw_time + ")");
     //LogFile.WriteToFile(ESP_LOG_INFO, TAG, aktstatusWithTime);
     #ifdef ENABLE_MQTT
         MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, qos, false);
@@ -706,8 +711,9 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
         }
     }
     else if (_fn == "alg_roi.jpg") {
+        std::string status = getActStatus(); // copy: the flow task changes it while this handler runs
         #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG      // no CImageBasis needed to create alg_roi.jpg (ca. 790kB less RAM)
-            if (aktstatus.find("Initialization (delayed)") != -1) {
+            if (status.find("Initialization (delayed)") != -1) {
                 std::string filename = "/sdcard/html/Flowstate_initialization_delayed.jpg";
                 result = send_file(req, filename);
                 /*    
@@ -738,7 +744,7 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
                 free(fileBuffer);
                 */
             }
-            else if (aktstatus.find("Initialization") != -1) {
+            else if (status.find("Initialization") != -1) {
                 std::string filename = "/sdcard/html/Flowstate_initialization.jpg";
                 result = send_file(req, filename);
                 /*
@@ -769,7 +775,7 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
                 free(fileBuffer);
                 */
             }
-            else if (aktstatus.find("Take Image") != -1) {
+            else if (status.find("Take Image") != -1) {
                 if (flowalignment && flowalignment->AlgROI) {
                     std::string filename = "/sdcard/html/Flowstate_take_image.jpg";
                     result = send_file(req, filename);
@@ -843,7 +849,9 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
             }
             else {
                 LogFile.WriteToFile(ESP_LOG_WARN, TAG, "ClassFlowControll::GetJPGStream: Not enough memory to create alg_roi.jpg -> alg.jpg is going to be served!");
-                
+                delete _send;
+                _send = NULL;
+
                 if (flowalignment && flowalignment->ImageBasis->ImageOkay()) {
                     _send = flowalignment->ImageBasis;
                 }

+ 5 - 2
code/components/jomjol_flowcontroll/ClassFlowControll.h

@@ -4,6 +4,7 @@
 #define CLASSFLOWCONTROLL_H
 
 #include <string>
+#include <mutex>
 
 #include "ClassFlow.h"
 #include "ClassFlowTakeImage.h"
@@ -40,6 +41,8 @@ protected:
 	void SetInitialParameter(void);	
 	std::string aktstatusWithTime;
 	std::string aktstatus;
+	std::mutex statusMutex;	// status is written by the flow task and read by HTTP handlers
+	void setStatus(const std::string &_status, const std::string &_statusWithTime);
 	int aktRunNr;
 
 public:
@@ -73,8 +76,8 @@ public:
 	bool getIsAutoStart();
 	void setAutoStartInterval(long &_interval);
 
-	std::string* getActStatusWithTime();
-	std::string* getActStatus();
+	std::string getActStatusWithTime();
+	std::string getActStatus();
 	void setActStatus(std::string _aktstatus);
 
 	std::vector<HTMLInfo*> GetAllDigit();

+ 2 - 0
code/components/jomjol_flowcontroll/ClassFlowPostProcessing.cpp

@@ -102,6 +102,7 @@ string ClassFlowPostProcessing::GetPreValue(std::string _number) {
 }
 
 bool ClassFlowPostProcessing::SetPreValue(double _newvalue, string _numbers, bool _extern) {
+    std::lock_guard<std::mutex> lock(preValueMutex);
     //ESP_LOGD(TAG, "SetPrevalue: %f, %s", zw, _numbers.c_str());
 
     for (int j = 0; j < NUMBERS.size(); ++j) {
@@ -759,6 +760,7 @@ string ClassFlowPostProcessing::ShiftDecimal(string in, int _decShift) {
 }
 
 bool ClassFlowPostProcessing::doFlow(string zwtime) {
+    std::lock_guard<std::mutex> lock(preValueMutex);
     string zwvalue;
     time_t imagetime = flowTakeImage->getTimeImageTaken();
 	

+ 3 - 0
code/components/jomjol_flowcontroll/ClassFlowPostProcessing.h

@@ -9,11 +9,14 @@
 #include "ClassFlowDefineTypes.h"
 
 #include <string>
+#include <mutex>
 
 class ClassFlowPostProcessing :
     public ClassFlow
 {
 protected:
+    std::mutex preValueMutex;   // PreValue is set from HTTP/MQTT tasks while the flow task post-processes
+
     bool UpdatePreValueINI;
 
     int PreValueAgeStartup; 

+ 26 - 23
code/components/jomjol_flowcontroll/MainFlowControl.cpp

@@ -23,6 +23,7 @@
 #include "server_GPIO.h"
 
 #include "server_file.h"
+#include "server_ota.h"
 
 #include "read_wlanini.h"
 #include "connect_wlan.h"
@@ -359,14 +360,16 @@ esp_err_t handler_init(httpd_req_t *req)
 #endif
 
     httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
-    const char *resp_str = "Init started<br>";
-    httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
-
-    doInit();
 
-    resp_str = "Init done<br>";
+    // Rebuilding the flow at runtime is not safe: InitFlow() keeps the old ClassFlow objects (a second full
+    // pipeline, ~1.2 MB PSRAM, until allocations fail and the device panics) and races with a running round.
+    // Apply the configuration with a reboot instead.
+    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "/doinit requested -> rebooting to apply the configuration");
+    const char *resp_str = "Reboot to apply the configuration<br>";
     httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
 
+    doReboot();
+
 #ifdef DEBUG_DETAIL_ON
     LogFile.WriteHeapInfo("handler_init - Done");
 #endif
@@ -381,7 +384,7 @@ esp_err_t handler_stream(httpd_req_t *req)
     ESP_LOGD(TAG, "handler_stream uri: %s", req->uri);
 #endif
 
-    char _query[50];
+    char _query[50] = ""; // stays empty when the request has no query string
     char _value[10];
     bool flashlightOn = false;
 
@@ -583,7 +586,7 @@ esp_err_t handler_wasserzaehler(httpd_req_t *req)
 
         ESP_LOGD(TAG, "handler water counter uri: %s", req->uri);
 
-        char _query[100];
+        char _query[100] = ""; // stays empty when the request has no query string
         char _size[10];
 
         if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
@@ -656,7 +659,7 @@ esp_err_t handler_wasserzaehler(httpd_req_t *req)
             return ESP_OK;
         }
 
-        std::string *status = flowctrl.getActStatus();
+        std::string status = flowctrl.getActStatus();
         std::string query = std::string(_query);
         //    ESP_LOGD(TAG, "Query: %s, query.c_str());
 
@@ -665,10 +668,10 @@ esp_err_t handler_wasserzaehler(httpd_req_t *req)
             std::string txt;
             txt = "<body style=\"font-family: arial\">";
 
-            if ((countRounds <= 1) && (*status != std::string("Flow finished")))
+            if ((countRounds <= 1) && (status != std::string("Flow finished")))
             {
                 // First round not completed yet
-                txt += "<h3>Please wait for the first round to complete!</h3><h3>Current state: " + *status + "</h3>\n";
+                txt += "<h3>Please wait for the first round to complete!</h3><h3>Current state: " + status + "</h3>\n";
             }
             else
             {
@@ -689,7 +692,7 @@ esp_err_t handler_wasserzaehler(httpd_req_t *req)
         {
             std::string txt, zw;
 
-            if ((countRounds <= 1) && (*status != std::string("Flow finished")))
+            if ((countRounds <= 1) && (status != std::string("Flow finished")))
             {
                 // First round not completed yet
                 // Nothing to do
@@ -774,11 +777,11 @@ esp_err_t handler_wasserzaehler(httpd_req_t *req)
                  * Only show it after the image got taken */
                 txt = "<hr><h3>Full Image (current round)</h3>\n";
 
-                if ((*status == std::string("Initialization")) ||
-                    (*status == std::string("Initialization (delayed)")) ||
-                    (*status == std::string("Take Image")))
+                if ((status == std::string("Initialization")) ||
+                    (status == std::string("Initialization (delayed)")) ||
+                    (status == std::string("Take Image")))
                 {
-                    txt += "<p>Current state: " + *status + "</p>\n";
+                    txt += "<p>Current state: " + status + "</p>\n";
                 }
                 else
                 {
@@ -812,7 +815,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
 
     ESP_LOGD(TAG, "handler_editflow uri: %s", req->uri);
 
-    char _query[512];
+    char _query[512] = ""; // stays empty when the request has no query string
     char _valuechar[30];
     std::string _task;
 
@@ -932,7 +935,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
 
         std::string out2 = out.substr(0, out.length() - 4) + "_org.jpg";
 
-        if ((flowctrl.SetupModeActive || (*flowctrl.getActStatus() == std::string("Flow finished"))) && psram_init_shared_memory_for_take_image_step())
+        if ((flowctrl.SetupModeActive || (flowctrl.getActStatus() == std::string("Flow finished"))) && psram_init_shared_memory_for_take_image_step())
         {
             LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Taking image for Alignment Mark Update...");
 
@@ -955,7 +958,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
         }
         else
         {
-            LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Taking image for Alignment Mark not possible while device") + " is busy with a round (Current State: '" + *flowctrl.getActStatus() + "')!");
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Taking image for Alignment Mark not possible while device") + " is busy with a round (Current State: '" + flowctrl.getActStatus() + "')!");
             zw = "Device Busy";
         }
 
@@ -964,9 +967,9 @@ esp_err_t handler_editflow(httpd_req_t *req)
     }
 
     // wird beim Erstellen eines neuen Referenzbildes aufgerufen
-    std::string *sys_status = flowctrl.getActStatus();
+    std::string sys_status = flowctrl.getActStatus();
 
-    if ((sys_status->c_str() != std::string("Take Image")) && (sys_status->c_str() != std::string("Aligning")))
+    if ((sys_status != "Take Image") && (sys_status != "Aligning"))
     {
         if ((_task.compare("test_take") == 0) || (_task.compare("cam_settings") == 0))
         {
@@ -1450,8 +1453,8 @@ esp_err_t handler_statusflow(httpd_req_t *req)
         ESP_LOGD(TAG, "handler_statusflow: %s", req->uri);
 #endif
 
-        string *zw = flowctrl.getActStatusWithTime();
-        resp_str = zw->c_str();
+        std::string zw = flowctrl.getActStatusWithTime();
+        resp_str = zw.c_str();
 
         httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
     }
@@ -1564,7 +1567,7 @@ esp_err_t handler_prevalue(httpd_req_t *req)
     // Default return error message when no return is programmed
     std::string sReturnMessage = "E90: Uninitialized";
 
-    char _query[100];
+    char _query[100] = ""; // stays empty when the request has no query string
     char _numbersname[50] = "default";
     char _value[20] = "";
 

+ 1 - 1
code/components/jomjol_image_proc/CAlignAndCutImage.cpp

@@ -129,7 +129,7 @@ void CAlignAndCutImage::CutAndSave(std::string _template1, int x1, int y1, int d
     
     RGBImageRelease();
 
-    stbi_image_free(odata);
+    free_psram_heap(std::string(TAG) + "->odata", odata);
 }
 
 void CAlignAndCutImage::CutAndSave(int x1, int y1, int dx, int dy, CImageBasis *_target)

+ 26 - 6
code/components/jomjol_image_proc/CImageBasis.cpp

@@ -705,20 +705,40 @@ void CImageBasis::SaveToFile(std::string _imageout)
 
 void CImageBasis::Resize(int _new_dx, int _new_dy)
 {
-    memsize = _new_dx * _new_dy * channels;
-    uint8_t* odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
+    // tmpImage lives in the shared PSRAM region and its destructor relies on that; never resize it in place
+    if ((rgb_image == NULL) || (name == "tmpImage")) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: not possible for image " + name);
+        return;
+    }
+
+    int new_memsize = _new_dx * _new_dy * channels;
+    uint8_t* odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis Resize (" + name + ")", new_memsize, MALLOC_CAP_SPIRAM);
+
+    if (odata == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: Can't allocate enough memory: " + std::to_string(new_memsize));
+        return;
+    }
 
     RGBImageLock();
 
     stbir_resize_uint8(rgb_image, width, height, 0, odata, _new_dx, _new_dy, 0, channels);
 
-    rgb_image = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis Resize (" + name + ")", memsize, MALLOC_CAP_SPIRAM);
-    memCopy(odata, rgb_image, memsize);
+    // Release the old buffer with the allocator it came from (same rule as the destructor)
+    if (!externalImage) {
+        if (memsize == 0) { // Loaded via STBI (STBI_MALLOC)
+            stbi_image_free(rgb_image);
+        }
+        else {
+            free_psram_heap(std::string(TAG) + "->CImageBasis Resize old (" + name + ")", rgb_image);
+        }
+    }
+
+    rgb_image = odata;
+    memsize = new_memsize;
+    externalImage = false; // The image now owns a normal PSRAM buffer
     width = _new_dx;
     height = _new_dy;
 
-    free_psram_heap(std::string(TAG) + "->odata", odata);
-
     RGBImageRelease();
 }
 

+ 1 - 1
code/components/jomjol_image_proc/CImageBasis.h

@@ -61,7 +61,7 @@ class CImageBasis
         bool ImageOkay();
         bool CopyFromMemory(uint8_t* _source, int _size);
 
-        void SetIndepended(){externalImage = false;};
+        void SetIndepended(){externalImage = false; memsize = width * height * channels;};
 
         void CreateEmptyImage(int _width, int _height, int _channels);
         void EmptyImage();

+ 2 - 0
code/components/jomjol_wlan/read_wlanini.cpp

@@ -233,6 +233,7 @@ bool ChangeHostName(std::string fn, std::string _newhostname)
     if (fgets(zw, sizeof(zw), pFile) == NULL) {
         line = "";
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ChangeHostName: File opened, but empty or content not readable");
+        fclose(pFile);
         return false;
     }
     else {
@@ -317,6 +318,7 @@ bool ChangeRSSIThreshold(std::string fn, int _newrssithreshold)
     if (fgets(zw, sizeof(zw), pFile) == NULL) {
         line = "";
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ChangeRSSIThreshold: File opened, but empty or content not readable");
+        fclose(pFile);
         return false;
     }
     else {

+ 3 - 1
code/include/defines.h

@@ -93,7 +93,9 @@
          
     #define LOGFILE_LAST_PART_BYTES 80 * 1024 // 80 kBytes  // Size of partial log file to return 
 
-    #define SERVER_FILER_SCRATCH_BUFSIZE  4096 
+    #define UPLOAD_MAX_RECV_TIMEOUTS 6 // Uploads give up after this many consecutive receive timeouts (recv_wait_timeout = 5 s each)
+
+    #define SERVER_FILER_SCRATCH_BUFSIZE  4096
     #define SERVER_HELPER_SCRATCH_BUFSIZE  4096
     #define SERVER_OTA_SCRATCH_BUFSIZE  1024 
 

+ 5 - 1
code/main/softAP.cpp

@@ -409,11 +409,14 @@ esp_err_t upload_post_handlerAP(httpd_req_t *req)
 
 
 
+    int timeouts = 0;
+
     while (remaining > 0) {
 
         ESP_LOGI(TAG, "Remaining size: %d", remaining);
         if ((received = httpd_req_recv(req, buf, MIN(remaining, 1024))) <= 0) {
-            if (received == HTTPD_SOCK_ERR_TIMEOUT) {
+            // Give up when the client is gone, retrying forever blocks the HTTP server task
+            if ((received == HTTPD_SOCK_ERR_TIMEOUT) && (++timeouts < UPLOAD_MAX_RECV_TIMEOUTS)) {
                 continue;
             }
 
@@ -435,6 +438,7 @@ esp_err_t upload_post_handlerAP(httpd_req_t *req)
         }
 
         remaining -= received;
+        timeouts = 0;
     }
     fclose(fd);
     isConfigINI = true;