]> git.ipfire.org Git - people/ms/pakfire.git/commitdiff
file: Add function to replace file content from another fd
authorMichael Tremer <michael.tremer@ipfire.org>
Tue, 31 Dec 2024 12:10:38 +0000 (12:10 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Tue, 31 Dec 2024 12:10:38 +0000 (12:10 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/libpakfire/file.c
src/libpakfire/include/pakfire/file.h

index 144c917d3ef08d7a667ede504e22dfbc6de4e683..141bca85c78a04efa72730d22315817fcd3aaf52 100644 (file)
@@ -28,6 +28,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/capability.h>
+#include <sys/sendfile.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <time.h>
@@ -1791,3 +1792,42 @@ PAKFIRE_EXPORT int pakfire_file_matches(struct pakfire_file* file, const char* p
 
        return pakfire_path_match(pattern, path);
 }
+
+int pakfire_file_consume(struct pakfire_file* file, int srcfd) {
+       ssize_t bytes_written = 0;
+       struct stat st = {};
+       int fd = -EBADF;
+       int r;
+
+       // Stat the source
+       r = fstat(srcfd, &st);
+       if (r < 0) {
+               ERROR(file->ctx, "Could not stat the source file descriptor: %m\n");
+               r = -errno;
+               goto ERROR;
+       }
+
+       // Open the file for writing
+       fd = r = pakfire_file_open(file, O_WRONLY|O_TRUNC);
+       if (r < 0)
+               goto ERROR;
+
+       // Write everything to the file
+       bytes_written = sendfile(fd, srcfd, 0, st.st_size);
+       if (bytes_written < st.st_size) {
+               ERROR(file->ctx, "Could not sendfile() to %s: %m\n", pakfire_file_get_path(file));
+               r = -errno;
+               goto ERROR;
+       }
+
+       DEBUG(file->ctx, "Wrote %zd byte(s) to %s\n", bytes_written, pakfire_file_get_abspath(file));
+
+       // Reset r
+       r = 0;
+
+ERROR:
+       if (fd >= 0)
+               close(fd);
+
+       return r;
+}
index 3c2bb104eecae9f2964bfdbeb8646d96d64c7481..07005b0aef9f0cb87db8975cb1cd7989fc3b9083 100644 (file)
@@ -179,5 +179,7 @@ int pakfire_file_matches_class(struct pakfire_file* file, const int class);
 
 int pakfire_file_verify(struct pakfire_file* file, int* status);
 
+int pakfire_file_consume(struct pakfire_file* file, int srcfd);
+
 #endif /* PAKFIRE_PRIVATE */
 #endif /* PAKFIRE_FILE_H */