]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
copy: Add COPY_TRUNCATE
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Thu, 1 Jun 2023 09:44:03 +0000 (11:44 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Thu, 1 Jun 2023 10:16:15 +0000 (12:16 +0200)
The file might grow more than the amount of data we end up writing,
so let's add a flag to truncate after writing to make sure the file
is only as large as it needs to be.

src/shared/copy.c
src/shared/copy.h

index 14b9b61d8a24e961e00635a42733ea6869061444..1ed5c7424c969e5a2134f3b1939528dff7bd4fce 100644 (file)
@@ -245,7 +245,7 @@ int copy_bytes_full(
                 ssize_t n;
 
                 if (max_bytes <= 0)
-                        return 1; /* return > 0 if we hit the max_bytes limit */
+                        break;
 
                 r = look_for_signals(copy_flags);
                 if (r < 0)
@@ -468,7 +468,16 @@ int copy_bytes_full(
                 copied_something = true;
         }
 
-        return 0; /* return 0 if we hit EOF earlier than the size limit */
+        if (copy_flags & COPY_TRUNCATE) {
+                off_t off = lseek(fdt, 0, SEEK_CUR);
+                if (off < 0)
+                        return -errno;
+
+                if (ftruncate(fdt, off) < 0)
+                        return -errno;
+        }
+
+        return max_bytes <= 0; /* return 0 if we hit EOF earlier than the size limit */
 }
 
 static int fd_copy_symlink(
index c4482eba7e1faf3f21e2cc32c6e4de07a383de96..b02fb946943818ca431b1c3a1736a21ec682232f 100644 (file)
@@ -28,6 +28,7 @@ typedef enum CopyFlags {
         COPY_ALL_XATTRS    = 1 << 13, /* Preserve all xattrs when copying, not just those in the user namespace */
         COPY_HOLES         = 1 << 14, /* Copy holes */
         COPY_GRACEFUL_WARN = 1 << 15, /* Skip copying file types that aren't supported by the target filesystem */
+        COPY_TRUNCATE      = 1 << 16, /* Truncate to current file offset after copying */
 } CopyFlags;
 
 typedef enum DenyType {