Kaynağa Gözat

Fix PreValue file cleanup and malformed input handling

SybexXx 2 gün önce
ebeveyn
işleme
bf0b4c9a18

+ 109 - 83
code/components/jomjol_flowcontroll/ClassFlowPostProcessing.cpp

@@ -5,6 +5,7 @@
 #include <iomanip>
 #include <sstream>
 #include <new>
+#include <memory>
 
 #include <time.h>
 
@@ -151,102 +152,108 @@ bool ClassFlowPostProcessing::SetPreValue(double _newvalue, string _numbers, boo
 
 bool ClassFlowPostProcessing::LoadPreValue(void) {
     std::vector<string> splitted;
-    FILE* pFile;
-    char zw[1024];
+    char zw[1024] = {};
     string zwtime, zwvalue, name;
-    bool _done = false;
 
     UpdatePreValueINI = false;       // Conversion to the new format
 
-    pFile = fopen(FilePreValue.c_str(), "r");
-	
-    if (pFile == NULL) {
+    // Close the descriptor on every return path, including empty or malformed files.
+    std::unique_ptr<FILE, int(*)(FILE*)> pFile(fopen(FilePreValue.c_str(), "r"), fclose);
+    if (!pFile) {
         return false;
     }
 
-    // Makes sure that an empty file is treated as such.
-    zw[0] = '\0';
-
-    fgets(zw, 1024, pFile);
+    if (fgets(zw, sizeof(zw), pFile.get()) == NULL) {
+        return false;
+    }
     ESP_LOGD(TAG, "Read line Prevalue.ini: %s", zw);
     zwtime = trim(std::string(zw));
-	
-    if (zwtime.length() == 0) {
+    if (zwtime.empty()) {
         return false;
     }
 
     splitted = HelperZerlegeZeile(zwtime, "\t");
-	
-    //  Conversion to the new format
+
+    // Conversion to the current tab-separated format: name, timestamp, value.
     if (splitted.size() > 1) {
-        while ((splitted.size() > 1) && !_done) {
+        while (true) {
+            if (splitted.size() < 3) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid PreValue entry: expected name, timestamp and value");
+                return false;
+            }
+
             name = trim(splitted[0]);
             zwtime = trim(splitted[1]);
             zwvalue = trim(splitted[2]);
+            if (name.empty() || !isStringNumeric(zwvalue)) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid PreValue entry for '" + name + "'");
+                return false;
+            }
+
+            int yy = 0, month = 0, dd = 0, hh = 0, mm = 0, ss = 0;
+            struct tm whenStart = {};
+            if (sscanf(zwtime.c_str(), PREVALUE_TIME_FORMAT_INPUT,
+                       &yy, &month, &dd, &hh, &mm, &ss) != 6) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid PreValue timestamp for '" + name + "'");
+                return false;
+            }
+            whenStart.tm_year = yy - 1900;
+            whenStart.tm_mon = month - 1;
+            whenStart.tm_mday = dd;
+            whenStart.tm_hour = hh;
+            whenStart.tm_min = mm;
+            whenStart.tm_sec = ss;
+            whenStart.tm_isdst = -1;
+            const time_t parsedTime = mktime(&whenStart);
+            if (parsedTime == static_cast<time_t>(-1)) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to parse PreValue timestamp for '" + name + "'");
+                return false;
+            }
 
             for (int j = 0; j < NUMBERS.size(); ++j) {
                 if (NUMBERS[j]->name == name) {
                     NUMBERS[j]->PreValue = stod(zwvalue.c_str());
-                    NUMBERS[j]->ReturnPreValue = RundeOutput(NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma + 1);      // To be on the safe side, 1 digit more, as Exgtended Resolution may be on (will only be set during the first run).
+                    NUMBERS[j]->ReturnPreValue = RundeOutput(NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma + 1);
+                    NUMBERS[j]->timeStampLastPreValue = parsedTime;
 
                     time_t tStart;
-                    int yy, month, dd, hh, mm, ss;
-                    struct tm whenStart;
-
-                    sscanf(zwtime.c_str(), PREVALUE_TIME_FORMAT_INPUT, &yy, &month, &dd, &hh, &mm, &ss);
-                    whenStart.tm_year = yy - 1900;
-                    whenStart.tm_mon = month - 1;
-                    whenStart.tm_mday = dd;
-                    whenStart.tm_hour = hh;
-                    whenStart.tm_min = mm;
-                    whenStart.tm_sec = ss;
-                    whenStart.tm_isdst = -1;
-
-                    NUMBERS[j]->timeStampLastPreValue = mktime(&whenStart);
-
                     time(&tStart);
-                    localtime(&tStart);
-                    double difference = difftime(tStart, NUMBERS[j]->timeStampLastPreValue);
-                    difference /= 60;
-			
-                    if (difference > PreValueAgeStartup) {
-                        NUMBERS[j]->PreValueOkay = false;
-                    }
-                    else {
-                        NUMBERS[j]->PreValueOkay = true;
-                    }
+                    const double difference = difftime(tStart, parsedTime) / 60.0;
+                    NUMBERS[j]->PreValueOkay = (difference <= PreValueAgeStartup);
                 }
             }
 
-            if (!fgets(zw, 1024, pFile)) {
-                _done = true;
+            if (fgets(zw, sizeof(zw), pFile.get()) == NULL) {
+                break;
             }
-            else {
-                ESP_LOGD(TAG, "Read line Prevalue.ini: %s", zw);
-                splitted = HelperZerlegeZeile(trim(std::string(zw)), "\t");
-		    
-                if (splitted.size() > 1) {
-                    name = trim(splitted[0]);
-                    zwtime = trim(splitted[1]);
-                    zwvalue = trim(splitted[2]);
-                }
+
+            const std::string nextLine = trim(std::string(zw));
+            if (nextLine.empty()) {
+                continue;
             }
+            ESP_LOGD(TAG, "Read line Prevalue.ini: %s", zw);
+            splitted = HelperZerlegeZeile(nextLine, "\t");
         }
-        fclose(pFile);
-    }   
+    }
     else {
-        // Old Format
-        fgets(zw, 1024, pFile);
-        fclose(pFile);
+        // Old format stores the timestamp in the first line and the value in the second.
+        if (NUMBERS.empty() || fgets(zw, sizeof(zw), pFile.get()) == NULL) {
+            return false;
+        }
         ESP_LOGD(TAG, "%s", zw);
         zwvalue = trim(std::string(zw));
-        NUMBERS[0]->PreValue = stod(zwvalue.c_str());
-
-        time_t tStart;
-        int yy, month, dd, hh, mm, ss;
-        struct tm whenStart;
+        if (!isStringNumeric(zwvalue)) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid legacy PreValue number");
+            return false;
+        }
 
-        sscanf(zwtime.c_str(), PREVALUE_TIME_FORMAT_INPUT, &yy, &month, &dd, &hh, &mm, &ss);
+        int yy = 0, month = 0, dd = 0, hh = 0, mm = 0, ss = 0;
+        struct tm whenStart = {};
+        if (sscanf(zwtime.c_str(), PREVALUE_TIME_FORMAT_INPUT,
+                   &yy, &month, &dd, &hh, &mm, &ss) != 6) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid legacy PreValue timestamp");
+            return false;
+        }
         whenStart.tm_year = yy - 1900;
         whenStart.tm_mon = month - 1;
         whenStart.tm_mday = dd;
@@ -255,19 +262,21 @@ bool ClassFlowPostProcessing::LoadPreValue(void) {
         whenStart.tm_sec = ss;
         whenStart.tm_isdst = -1;
 
-        ESP_LOGD(TAG, "TIME: %d, %d, %d, %d, %d, %d", whenStart.tm_year, whenStart.tm_mon, whenStart.tm_wday, whenStart.tm_hour, whenStart.tm_min, whenStart.tm_sec);
-
-        NUMBERS[0]->timeStampLastPreValue = mktime(&whenStart);
+        const time_t parsedTime = mktime(&whenStart);
+        if (parsedTime == static_cast<time_t>(-1)) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to parse legacy PreValue timestamp");
+            return false;
+        }
 
+        time_t tStart;
         time(&tStart);
-        localtime(&tStart);
-        double difference = difftime(tStart, NUMBERS[0]->timeStampLastPreValue);
-        difference /= 60;
-			
+        const double difference = difftime(tStart, parsedTime) / 60.0;
         if (difference > PreValueAgeStartup) {
             return false;
         }
 
+        NUMBERS[0]->PreValue = stod(zwvalue.c_str());
+        NUMBERS[0]->timeStampLastPreValue = parsedTime;
         NUMBERS[0]->Value = NUMBERS[0]->PreValue;
         NUMBERS[0]->ReturnValue = to_string(NUMBERS[0]->Value);
 
@@ -275,15 +284,16 @@ bool ClassFlowPostProcessing::LoadPreValue(void) {
             NUMBERS[0]->ReturnValue = RundeOutput(NUMBERS[0]->Value, NUMBERS[0]->Nachkomma);
         }
 
-        UpdatePreValueINI = true;       // Conversion to the new format
+        // Close the input before rewriting the file in the current format.
+        pFile.reset();
+        UpdatePreValueINI = true;
         SavePreValue();
-    } 
+    }
 
     return true;
 }
 
 void ClassFlowPostProcessing::SavePreValue() {
-    FILE* pFile;
     string _zw;
 
     // PreValues unchanged --> File does not have to be rewritten
@@ -291,27 +301,43 @@ void ClassFlowPostProcessing::SavePreValue() {
         return;
     }
 
-    pFile = fopen(FilePreValue.c_str(), "w");
+    FILE* rawFile = fopen(FilePreValue.c_str(), "w");
+    if (rawFile == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SavePreValue: unable to open " + FilePreValue);
+        return;
+    }
+    std::unique_ptr<FILE, int(*)(FILE*)> pFile(rawFile, fclose);
+    bool writeOkay = true;
 
     for (int j = 0; j < NUMBERS.size(); ++j) {
-        char buffer[80];
+        char buffer[80] = {};
         struct tm* timeinfo = localtime(&NUMBERS[j]->timeStampLastPreValue);
-        strftime(buffer, 80, PREVALUE_TIME_FORMAT_OUTPUT, timeinfo);
+        if (timeinfo == NULL || strftime(buffer, sizeof(buffer), PREVALUE_TIME_FORMAT_OUTPUT, timeinfo) == 0) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SavePreValue: unable to format timestamp");
+            writeOkay = false;
+            break;
+        }
         NUMBERS[j]->timeStamp = std::string(buffer);
         NUMBERS[j]->timeStampTimeUTC = NUMBERS[j]->timeStampLastPreValue;
-        // ESP_LOGD(TAG, "SaverPreValue %d, Value: %f, Nachkomma %d", j, NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma);
 
-        _zw = NUMBERS[j]->name + "\t" + NUMBERS[j]->timeStamp + "\t" + RundeOutput(NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma) + "\n";
+        _zw = NUMBERS[j]->name + "\t" + NUMBERS[j]->timeStamp + "\t" +
+              RundeOutput(NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma) + "\n";
         ESP_LOGD(TAG, "Write PreValue line: %s", _zw.c_str());
-			
-        if (pFile) {
-            fputs(_zw.c_str(), pFile);
+
+        if (fputs(_zw.c_str(), pFile.get()) < 0) {
+            writeOkay = false;
+            break;
         }
     }
 
-    UpdatePreValueINI = false;
-
-    fclose(pFile);
+    if (fclose(pFile.release()) != 0) {
+        writeOkay = false;
+    }
+    if (writeOkay) {
+        UpdatePreValueINI = false;
+    } else {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SavePreValue: failed while writing " + FilePreValue);
+    }
 }
 
 ClassFlowPostProcessing::ClassFlowPostProcessing(std::vector<ClassFlow*>* lfc, ClassFlowCNNGeneral *_analog, ClassFlowCNNGeneral *_digit) {