App: Remove use of dangerous localtime() function

This commit is contained in:
Chris Hennes
2025-08-09 18:51:06 -05:00
committed by Benjamin Nauck
parent abdd975089
commit d8168d33f3
2 changed files with 22 additions and 6 deletions

View File

@@ -216,11 +216,27 @@ void BackupPolicy::applyTimeStamp(const std::string& sourcename, const std::stri
std::stringstream str;
Base::TimeInfo ti = fi.lastModified();
time_t s = ti.getTime_t();
struct tm* timeinfo = localtime(&s);
char buffer[100];
strftime(buffer, sizeof(buffer), saveBackupDateFormat.c_str(), timeinfo);
str << bn << buffer;
std::tm local_tm {};
#if defined(_WIN32)
localtime_s(&local_tm, &s); // Windows
#else
localtime_r(&s, &local_tm); // POSIX
#endif
constexpr size_t bufferLength = 128;
std::array<char, bufferLength> buffer {};
if (size_t bytes = std::strftime(buffer.data(),
bufferLength,
saveBackupDateFormat.c_str(),
&local_tm);
bytes == 0) {
// An error here is typically that we over-ran the maximum buffer length (
// which should be a *very* unusual condition).
Base::Console().error("Failed to create valid backup file name from format string:\n");
Base::Console().error(saveBackupDateFormat.c_str());
const auto knownGoodFormat {"%Y-%m-%d_%H-%M-%S"};
std::strftime(buffer.data(), bufferLength, knownGoodFormat, &local_tm);
}
str << bn << buffer.data();
fn = str.str();
bool done = false;

View File

@@ -394,7 +394,7 @@ TEST_F(BackupPolicyTest, TimestampReplacesDotsWithDashes)
TEST_F(BackupPolicyTest, DISABLED_TimestampWithInvalidFormatStringThrows)
{
// THIS TEST IS DISABLED BECAUSE THE CURRENT CODE DOES NOT CORRECTLY HANDLE INVALID FORMAT
// OPERATIONS, AND CRASHES WHEN GIVEN ONE. FIXME.
// OPERATIONS, AND GENERATES UNEXPECTED FILENAMES WHEN GIVEN ONE. FIXME.
// Arrange
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Q-%W-%E");