From b8a56288be4f747f7ae626923a3786a6c36ccfdc Mon Sep 17 00:00:00 2001 From: Anon2026 Date: Wed, 7 Jan 2026 20:24:59 +0300 Subject: [PATCH] Fix thread-unsafe localtime() --- daemon/HTTPServer.cpp | 10 ++++++++-- libi2pd/Log.cpp | 10 +++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/daemon/HTTPServer.cpp b/daemon/HTTPServer.cpp index 148d6ad7..934f726b 100644 --- a/daemon/HTTPServer.cpp +++ b/daemon/HTTPServer.cpp @@ -6,6 +6,7 @@ * See full license text in LICENSE file at top of project tree */ +#include #include #include #include @@ -93,11 +94,16 @@ namespace http { static std::string ConvertTime (uint64_t time) { + struct tm caltime; lldiv_t divTime = lldiv(time, 1000); time_t t = divTime.quot; - struct tm *tm = localtime(&t); +#ifdef _WIN32 + localtime_s(&caltime, &t); +#else + localtime_r(&t, &caltime); +#endif char date[128]; - snprintf(date, sizeof(date), "%02d/%02d/%d %02d:%02d:%02d.%03lld", tm->tm_mday, tm->tm_mon + 1, tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec, divTime.rem); + snprintf(date, sizeof(date), "%02d/%02d/%d %02d:%02d:%02d.%03lld", caltime.tm_mday, caltime.tm_mon + 1, caltime.tm_year + 1900, caltime.tm_hour, caltime.tm_min, caltime.tm_sec, divTime.rem); return date; } diff --git a/libi2pd/Log.cpp b/libi2pd/Log.cpp index 76e85d4a..eef5d196 100644 --- a/libi2pd/Log.cpp +++ b/libi2pd/Log.cpp @@ -6,6 +6,8 @@ * See full license text in LICENSE file at top of project tree */ +#include + #include "Log.h" #include "util.h" @@ -140,8 +142,14 @@ namespace log { } const char * Log::TimeAsString(std::time_t t) { + struct tm caltime; if (t != m_LastTimestamp) { - strftime(m_LastDateTime, sizeof(m_LastDateTime), m_TimeFormat.c_str(), localtime(&t)); +#ifdef _WIN32 + localtime_s(&caltime, &t); +#else + localtime_r(&t, &caltime); +#endif + strftime(m_LastDateTime, sizeof(m_LastDateTime), m_TimeFormat.c_str(), &caltime); m_LastTimestamp = t; } return m_LastDateTime;