From 5e279292ce60e1a0c5fa37c735256fd625a56f9f Mon Sep 17 00:00:00 2001 From: Simon Quigley Date: Sat, 21 Dec 2024 01:26:40 -0600 Subject: [PATCH] Correctly set a default time for files so they don't end up as the epoch --- cpp/common.cpp | 25 +++++++++++++++++++++++++ cpp/common.h | 1 + 2 files changed, 26 insertions(+) diff --git a/cpp/common.cpp b/cpp/common.cpp index 4cd6fc0..0c5ef8e 100644 --- a/cpp/common.cpp +++ b/cpp/common.cpp @@ -16,6 +16,7 @@ #include "common.h" #include "/usr/include/archive.h" #include "/usr/include/archive_entry.h" +#include #include #include #include @@ -114,6 +115,7 @@ void clean_old_logs(const fs::path &log_dir, int max_age_seconds) { } } + void create_tarball(const std::string& tarballPath, const std::string& directory, const std::vector& exclusions) { std::cout << "[INFO] Creating tarball: " << tarballPath << std::endl; @@ -174,6 +176,7 @@ void create_tarball(const std::string& tarballPath, const std::string& directory archive_entry_set_pathname(entry, relativePath.c_str()); + // Set file type, permissions, and size if (fs::is_regular_file(fstatus)) { // Regular file uintmax_t filesize = fs::file_size(path, ec); @@ -208,6 +211,20 @@ void create_tarball(const std::string& tarballPath, const std::string& directory continue; } + // Retrieve and set the modification time + fs::file_time_type ftime = fs::last_write_time(path, ec); + std::time_t mtime; + if (ec) { + log_error("Failed to get last write time for: " + path.string() + " Error: " + ec.message()); + // Obtain current UTC time as fallback + auto now = std::chrono::system_clock::now(); + mtime = std::chrono::system_clock::to_time_t(now); + log_info("Setting default mtime (current UTC time) for: " + path.string()); + } else { + mtime = to_time_t(ftime); + } + archive_entry_set_mtime(entry, mtime, 0); + if (archive_write_header(a, entry) != ARCHIVE_OK) { log_error("Failed to write header for: " + path.string() + " Error: " + archive_error_string(a)); archive_entry_free(entry); @@ -268,3 +285,11 @@ std::string get_current_utc_time() { std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &tm_utc); return std::string(buf); } + +std::time_t to_time_t(const fs::file_time_type& ftime) { + using namespace std::chrono; + // Convert to system_clock time_point + auto sctp = time_point_cast(ftime - fs::file_time_type::clock::now() + + system_clock::now()); + return system_clock::to_time_t(sctp); +} diff --git a/cpp/common.h b/cpp/common.h index 0b93123..19c6615 100644 --- a/cpp/common.h +++ b/cpp/common.h @@ -25,6 +25,7 @@ void run_command(const std::vector &cmd, const std::optional& exclusions); std::string get_current_utc_time(); +std::time_t to_time_t(const fs::file_time_type& ftime); static std::counting_semaphore<5> semaphore(5); struct semaphore_guard {