Pārlūkot izejas kodu

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.
Timothy Flynn 2 gadi atpakaļ
vecāks
revīzija
ed612d835d

+ 26 - 0
Tests/LibTimeZone/TestTimeZone.cpp

@@ -24,6 +24,26 @@ static void test_offset(StringView time_zone, i64 time, i64 expected_offset, Tim
 
 #    include <LibTimeZone/TimeZoneData.h>
 
+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);

+ 1 - 0
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