From: Michael Tremer Date: Tue, 31 Dec 2024 12:10:38 +0000 (+0000) Subject: file: Add function to replace file content from another fd X-Git-Tag: 0.9.30~640 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=131d27a02e8e00d9931c1eaf9bbdc36feddc2a22;p=pakfire.git file: Add function to replace file content from another fd Signed-off-by: Michael Tremer --- diff --git a/src/libpakfire/file.c b/src/libpakfire/file.c index 144c917d3..141bca85c 100644 --- a/src/libpakfire/file.c +++ b/src/libpakfire/file.c @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -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; +} diff --git a/src/libpakfire/include/pakfire/file.h b/src/libpakfire/include/pakfire/file.h index 3c2bb104e..07005b0ae 100644 --- a/src/libpakfire/include/pakfire/file.h +++ b/src/libpakfire/include/pakfire/file.h @@ -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 */