From 85cf7349c24ce562b5473cf5bfdfd76896f3ee38 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Wed, 14 Jun 2023 15:51:44 +0000 Subject: [PATCH] util: Add function to copy all data from one fd to another Signed-off-by: Michael Tremer --- src/libpakfire/include/pakfire/util.h | 3 +++ src/libpakfire/pakfire.c | 6 +++--- src/libpakfire/util.c | 28 +++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/libpakfire/include/pakfire/util.h b/src/libpakfire/include/pakfire/util.h index c402b38f5..622fa3d7c 100644 --- a/src/libpakfire/include/pakfire/util.h +++ b/src/libpakfire/include/pakfire/util.h @@ -128,6 +128,9 @@ int pakfire_b64encode(struct pakfire* pakfire, char** output, int pakfire_b64decode(struct pakfire* pakfire, void** output, size_t* length, const char* buffer); +// Copy +int pakfire_copy(struct pakfire* pakfire, FILE* src, FILE* dst); + #endif #endif /* PAKFIRE_UTIL_H */ diff --git a/src/libpakfire/pakfire.c b/src/libpakfire/pakfire.c index 5094bb360..b1022e925 100644 --- a/src/libpakfire/pakfire.c +++ b/src/libpakfire/pakfire.c @@ -1207,7 +1207,7 @@ enum pakfire_copy_direction { PAKFIRE_COPY_OUT, }; -static int pakfire_copy(struct pakfire* pakfire, const char* src, const char* dst, +static int __pakfire_copy(struct pakfire* pakfire, const char* src, const char* dst, enum pakfire_copy_direction direction) { struct archive* reader = NULL; struct archive* writer = NULL; @@ -1292,7 +1292,7 @@ PAKFIRE_EXPORT int pakfire_copy_in(struct pakfire* pakfire, const char* src, con if (r) return r; - return pakfire_copy(pakfire, src, path, PAKFIRE_COPY_IN); + return __pakfire_copy(pakfire, src, path, PAKFIRE_COPY_IN); } PAKFIRE_EXPORT int pakfire_copy_out(struct pakfire* pakfire, const char* src, const char* dst) { @@ -1308,7 +1308,7 @@ PAKFIRE_EXPORT int pakfire_copy_out(struct pakfire* pakfire, const char* src, co if (r) return r; - return pakfire_copy(pakfire, path, dst, PAKFIRE_COPY_OUT); + return __pakfire_copy(pakfire, path, dst, PAKFIRE_COPY_OUT); } PAKFIRE_EXPORT const char* pakfire_get_arch(struct pakfire* pakfire) { diff --git a/src/libpakfire/util.c b/src/libpakfire/util.c index af58be28b..bb325a806 100644 --- a/src/libpakfire/util.c +++ b/src/libpakfire/util.c @@ -1106,3 +1106,31 @@ ERROR: return r; } + +// Copy + +int pakfire_copy(struct pakfire* pakfire, FILE* src, FILE* dst) { + char buffer[BUFFER_SIZE]; + size_t bytes_read; + size_t bytes_written; + + while (!feof(src)) { + // Read some data into the buffer + bytes_read = fread(buffer, 1, sizeof(buffer), src); + + // Check for any errors + if (ferror(src)) { + ERROR(pakfire, "Could not read data: %m\n"); + return 1; + } + + // Write the data + bytes_written = fwrite(buffer, 1, bytes_read, dst); + if (bytes_written < bytes_read) { + ERROR(pakfire, "Could not write data: %m\n"); + return 1; + } + } + + return 0; +} -- 2.39.5