From ed612d835db151b4a69d1ec3640d00ed9a9a1077 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Mon, 17 Oct 2022 12:41:19 +0000 Subject: [PATCH] LibTimeZone: Default to UTC if parsing the TZ environment variable fails Commit c3fd455 changed LibTimeZone to fall back to the system time zone when we fail to parse the TZ environment variable. This behavior differs from both our LibC and glibc; they abort parsing and default to UTC. This changes LibTimeZone to behave the same way to avoid a very awkward situation where some parts of the codebase thinks the timezone is UTC, and others think the timezone is whatever /etc/timezone indicates. --- Tests/LibTimeZone/TestTimeZone.cpp | 26 +++++++++++++++++++++ Userland/Libraries/LibTimeZone/TimeZone.cpp | 1 + 2 files changed, 27 insertions(+) diff --git a/Tests/LibTimeZone/TestTimeZone.cpp b/Tests/LibTimeZone/TestTimeZone.cpp index 7cf8a6fc2e..06785441a1 100644 --- a/Tests/LibTimeZone/TestTimeZone.cpp +++ b/Tests/LibTimeZone/TestTimeZone.cpp @@ -24,6 +24,26 @@ static void test_offset(StringView time_zone, i64 time, i64 expected_offset, Tim # include +class TimeZoneGuard { +public: + explicit TimeZoneGuard(char const* tz) + : m_tz(getenv("TZ")) + { + setenv("TZ", tz, 1); + } + + ~TimeZoneGuard() + { + if (m_tz) + setenv("TZ", m_tz, 1); + else + unsetenv("TZ"); + } + +private: + char const* m_tz { nullptr }; +}; + TEST_CASE(time_zone_from_string) { EXPECT_EQ(TimeZone::time_zone_from_string("America/New_York"sv), TimeZone::TimeZone::America_New_York); @@ -95,6 +115,12 @@ TEST_CASE(canonicalize_time_zone) EXPECT(!TimeZone::canonicalize_time_zone("I don't exist"sv).has_value()); } +TEST_CASE(invalid_time_zone) +{ + TimeZoneGuard guard { "ladybird" }; + EXPECT_EQ(TimeZone::current_time_zone(), "UTC"sv); +} + static i64 offset(i64 sign, i64 hours, i64 minutes, i64 seconds) { return sign * ((hours * 3600) + (minutes * 60) + seconds); diff --git a/Userland/Libraries/LibTimeZone/TimeZone.cpp b/Userland/Libraries/LibTimeZone/TimeZone.cpp index 4bc21a27d7..8d3107586a 100644 --- a/Userland/Libraries/LibTimeZone/TimeZone.cpp +++ b/Userland/Libraries/LibTimeZone/TimeZone.cpp @@ -99,6 +99,7 @@ StringView current_time_zone() return *maybe_time_zone; dbgln_if(TIME_ZONE_DEBUG, "Could not determine time zone from TZ environment: {}", time_zone); + return "UTC"sv; } #ifdef AK_OS_SERENITY