]> git.ipfire.org Git - pakfire.git/commitdiff
file: Truncate file before rewriting it
authorMichael Tremer <michael.tremer@ipfire.org>
Thu, 14 Sep 2023 11:49:57 +0000 (11:49 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Thu, 14 Sep 2023 11:49:57 +0000 (11:49 +0000)
It can happen that the file is shorter after we have fixed the
interpreter, which causes that the remaining data is still in the file.

Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/libpakfire/file.c

index 7a994c48fc4b16f86a31e2b31f26569b4a96d8ea..5655b4b7190cb16c6baf92472f387bd6724c44fc 100644 (file)
@@ -2421,6 +2421,7 @@ static int pakfire_file_fix_interpreter(struct pakfire_file* file, const char* i
        int r;
 
        char* buffer = NULL;
+       size_t l = 0;
        char* line = NULL;
        size_t length = 0;
        char* p = NULL;
@@ -2526,6 +2527,9 @@ static int pakfire_file_fix_interpreter(struct pakfire_file* file, const char* i
                                if (r < 0)
                                        goto ERROR;
 
+                               // Store length of the buffer
+                               l = r;
+
                                // Process the next line
                                break;
 
@@ -2534,6 +2538,10 @@ static int pakfire_file_fix_interpreter(struct pakfire_file* file, const char* i
                                r = asprintf(&buffer, "%s%s", buffer, line);
                                if (r < 0)
                                        goto ERROR;
+
+                               // Store length of the buffer
+                               l = r;
+
                                break;
                }
        }
@@ -2541,10 +2549,18 @@ static int pakfire_file_fix_interpreter(struct pakfire_file* file, const char* i
        // Go back to the beginning of the file
        rewind(f);
 
+       // Truncate the existing content
+       r = ftruncate(fileno(f), 0);
+       if (r) {
+               ERROR(file->pakfire, "Could not truncate %s: %m\n", path);
+               r = -errno;
+               goto ERROR;
+       }
+
        // Write back the buffer
        if (buffer) {
-               size_t bytes_written = fwrite(buffer, 1, strlen(buffer), f);
-               if (bytes_written < length) {
+               size_t bytes_written = fwrite(buffer, 1, l, f);
+               if (bytes_written < l) {
                        ERROR(file->pakfire, "%s: Could not write the payload: %m\n", path);
                        r = -errno;
                        goto ERROR;