| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
| 2 |
* vim: set ts=8 sts=2 et sw=2 tw=80: |
| 3 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
#include "vm/DateTime.h" |
| 8 |
|
| 9 |
#if JS_HAS_INTL_API |
| 10 |
# include "mozilla/intl/TimeZone.h" |
| 11 |
#endif |
| 12 |
#include "mozilla/ScopeExit.h" |
| 13 |
#include "mozilla/TextUtils.h" |
| 14 |
|
| 15 |
#include <algorithm> |
| 16 |
#include <cstdlib> |
| 17 |
#include <cstring> |
| 18 |
#include <iterator> |
| 19 |
#include <string_view> |
| 20 |
#include <time.h> |
| 21 |
|
| 22 |
#if !defined(XP_WIN) |
| 23 |
# include <limits.h> |
| 24 |
# include <unistd.h> |
| 25 |
#endif /* !defined(XP_WIN) */ |
| 26 |
|
| 27 |
#if JS_HAS_INTL_API |
| 28 |
# include "builtin/intl/FormatBuffer.h" |
| 29 |
#endif |
| 30 |
#include "js/AllocPolicy.h" |
| 31 |
#include "js/Date.h" |
| 32 |
#include "js/GCAPI.h" |
| 33 |
#include "js/Vector.h" |
| 34 |
#include "threading/ExclusiveData.h" |
| 35 |
|
| 36 |
#include "util/Text.h" |
| 37 |
#include "vm/MutexIDs.h" |
| 38 |
#include "vm/Realm.h" |
| 39 |
|
| 40 |
/* static */ |
| 41 |
js::DateTimeInfo::ForceUTC js::DateTimeInfo::forceUTC(JS::Realm* realm) { |
| 42 |
return realm->creationOptions().forceUTC() ? DateTimeInfo::ForceUTC::Yes |
| 43 |
: DateTimeInfo::ForceUTC::No; |
| 44 |
} |
| 45 |
|
| 46 |
static bool ComputeLocalTime(time_t local, struct tm* ptm) { |
| 47 |
// Neither localtime_s nor localtime_r are required to act as if tzset has |
| 48 |
// been called, therefore we need to explicitly call it to ensure any time |
| 49 |
// zone changes are correctly picked up. |
| 50 |
|
| 51 |
#if defined(_WIN32) |
| 52 |
_tzset(); |
| 53 |
return localtime_s(ptm, &local) == 0; |
| 54 |
#elif defined(HAVE_LOCALTIME_R) |
| 55 |
# ifndef __wasi__ |
| 56 |
tzset(); |
| 57 |
# endif |
| 58 |
return localtime_r(&local, ptm); |
| 59 |
#else |
| 60 |
struct tm* otm = localtime(&local); |
| 61 |
if (!otm) { |
| 62 |
return false; |
| 63 |
} |
| 64 |
*ptm = *otm; |
| 65 |
return true; |
| 66 |
#endif |
| 67 |
} |
| 68 |
|
| 69 |
static bool ComputeUTCTime(time_t t, struct tm* ptm) { |
| 70 |
#if defined(_WIN32) |
| 71 |
return gmtime_s(ptm, &t) == 0; |
| 72 |
#elif defined(HAVE_GMTIME_R) |
| 73 |
return gmtime_r(&t, ptm); |
| 74 |
#else |
| 75 |
struct tm* otm = gmtime(&t); |
| 76 |
if (!otm) { |
| 77 |
return false; |
| 78 |
} |
| 79 |
*ptm = *otm; |
| 80 |
return true; |
| 81 |
#endif |
| 82 |
} |
| 83 |
|
| 84 |
/* |
| 85 |
* Compute the offset in seconds from the current UTC time to the current local |
| 86 |
* standard time (i.e. not including any offset due to DST). |
| 87 |
* |
| 88 |
* Examples: |
| 89 |
* |
| 90 |
* Suppose we are in California, USA on January 1, 2013 at 04:00 PST (UTC-8, no |
| 91 |
* DST in effect), corresponding to 12:00 UTC. This function would then return |
| 92 |
* -8 * SecondsPerHour, or -28800. |
| 93 |
* |
| 94 |
* Or suppose we are in Berlin, Germany on July 1, 2013 at 17:00 CEST (UTC+2, |
| 95 |
* DST in effect), corresponding to 15:00 UTC. This function would then return |
| 96 |
* +1 * SecondsPerHour, or +3600. |
| 97 |
*/ |
| 98 |
static int32_t UTCToLocalStandardOffsetSeconds() { |
| 99 |
using js::SecondsPerDay; |
| 100 |
using js::SecondsPerHour; |
| 101 |
using js::SecondsPerMinute; |
| 102 |
|
| 103 |
// Get the current time. |
| 104 |
time_t currentMaybeWithDST = time(nullptr); |
| 105 |
if (currentMaybeWithDST == time_t(-1)) { |
| 106 |
return 0; |
| 107 |
} |
| 108 |
|
| 109 |
// Break down the current time into its (locally-valued, maybe with DST) |
| 110 |
// components. |
| 111 |
struct tm local; |
| 112 |
if (!ComputeLocalTime(currentMaybeWithDST, &local)) { |
| 113 |
return 0; |
| 114 |
} |
| 115 |
|
| 116 |
// Compute a |time_t| corresponding to |local| interpreted without DST. |
| 117 |
time_t currentNoDST; |
| 118 |
if (local.tm_isdst == 0) { |
| 119 |
// If |local| wasn't DST, we can use the same time. |
| 120 |
currentNoDST = currentMaybeWithDST; |
| 121 |
} else { |
| 122 |
// If |local| respected DST, we need a time broken down into components |
| 123 |
// ignoring DST. Turn off DST in the broken-down time. Create a fresh |
| 124 |
// copy of |local|, because mktime() will reset tm_isdst = 1 and will |
| 125 |
// adjust tm_hour and tm_hour accordingly. |
| 126 |
struct tm localNoDST = local; |
| 127 |
localNoDST.tm_isdst = 0; |
| 128 |
|
| 129 |
// Compute a |time_t t| corresponding to the broken-down time with DST |
| 130 |
// off. This has boundary-condition issues (for about the duration of |
| 131 |
// a DST offset) near the time a location moves to a different time |
| 132 |
// zone. But 1) errors will be transient; 2) locations rarely change |
| 133 |
// time zone; and 3) in the absence of an API that provides the time |
| 134 |
// zone offset directly, this may be the best we can do. |
| 135 |
currentNoDST = mktime(&localNoDST); |
| 136 |
if (currentNoDST == time_t(-1)) { |
| 137 |
return 0; |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
// Break down the time corresponding to the no-DST |local| into UTC-based |
| 142 |
// components. |
| 143 |
struct tm utc; |
| 144 |
if (!ComputeUTCTime(currentNoDST, &utc)) { |
| 145 |
return 0; |
| 146 |
} |
| 147 |
|
| 148 |
// Finally, compare the seconds-based components of the local non-DST |
| 149 |
// representation and the UTC representation to determine the actual |
| 150 |
// difference. |
| 151 |
int utc_secs = utc.tm_hour * SecondsPerHour + utc.tm_min * SecondsPerMinute; |
| 152 |
int local_secs = |
| 153 |
local.tm_hour * SecondsPerHour + local.tm_min * SecondsPerMinute; |
| 154 |
|
| 155 |
// Same-day? Just subtract the seconds counts. |
| 156 |
if (utc.tm_mday == local.tm_mday) { |
| 157 |
return local_secs - utc_secs; |
| 158 |
} |
| 159 |
|
| 160 |
// If we have more UTC seconds, move local seconds into the UTC seconds' |
| 161 |
// frame of reference and then subtract. |
| 162 |
if (utc_secs > local_secs) { |
| 163 |
return (SecondsPerDay + local_secs) - utc_secs; |
| 164 |
} |
| 165 |
|
| 166 |
// Otherwise we have more local seconds, so move the UTC seconds into the |
| 167 |
// local seconds' frame of reference and then subtract. |
| 168 |
return local_secs - (utc_secs + SecondsPerDay); |
| 169 |
} |
| 170 |
|
| 171 |
void js::DateTimeInfo::internalResetTimeZone(ResetTimeZoneMode mode) { |
| 172 |
// Nothing to do when an update request is already enqueued. |
| 173 |
if (timeZoneStatus_ == TimeZoneStatus::NeedsUpdate) { |
| 174 |
return; |
| 175 |
} |
| 176 |
|
| 177 |
// Mark the state as needing an update, but defer the actual update until it's |
| 178 |
// actually needed to delay any system calls to the last possible moment. This |
| 179 |
// is beneficial when this method is called during start-up, because it avoids |
| 180 |
// main-thread I/O blocking the process. |
| 181 |
if (mode == ResetTimeZoneMode::ResetEvenIfOffsetUnchanged) { |
| 182 |
timeZoneStatus_ = TimeZoneStatus::NeedsUpdate; |
| 183 |
} else { |
| 184 |
timeZoneStatus_ = TimeZoneStatus::UpdateIfChanged; |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
void js::DateTimeInfo::updateTimeZone() { |
| 189 |
MOZ_ASSERT(timeZoneStatus_ != TimeZoneStatus::Valid); |
| 190 |
|
| 191 |
bool updateIfChanged = timeZoneStatus_ == TimeZoneStatus::UpdateIfChanged; |
| 192 |
|
| 193 |
timeZoneStatus_ = TimeZoneStatus::Valid; |
| 194 |
|
| 195 |
/* |
| 196 |
* The difference between local standard time and UTC will never change for |
| 197 |
* a given time zone. |
| 198 |
*/ |
| 199 |
int32_t newOffset = UTCToLocalStandardOffsetSeconds(); |
| 200 |
|
| 201 |
if (updateIfChanged && newOffset == utcToLocalStandardOffsetSeconds_) { |
| 202 |
return; |
| 203 |
} |
| 204 |
|
| 205 |
utcToLocalStandardOffsetSeconds_ = newOffset; |
| 206 |
|
| 207 |
dstRange_.reset(); |
| 208 |
|
| 209 |
#if JS_HAS_INTL_API |
| 210 |
utcRange_.reset(); |
| 211 |
localRange_.reset(); |
| 212 |
|
| 213 |
{ |
| 214 |
// Tell the analysis the |pFree| function pointer called by uprv_free |
| 215 |
// cannot GC. |
| 216 |
JS::AutoSuppressGCAnalysis nogc; |
| 217 |
|
| 218 |
timeZone_ = nullptr; |
| 219 |
} |
| 220 |
|
| 221 |
standardName_ = nullptr; |
| 222 |
daylightSavingsName_ = nullptr; |
| 223 |
#endif /* JS_HAS_INTL_API */ |
| 224 |
|
| 225 |
// Propagate the time zone change to ICU, too. |
| 226 |
{ |
| 227 |
// Tell the analysis calling into ICU cannot GC. |
| 228 |
JS::AutoSuppressGCAnalysis nogc; |
| 229 |
|
| 230 |
internalResyncICUDefaultTimeZone(); |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
js::DateTimeInfo::DateTimeInfo(bool forceUTC) : forceUTC_(forceUTC) { |
| 235 |
// Set the time zone status into the invalid state, so we compute the actual |
| 236 |
// defaults on first access. We don't yet want to initialize neither <ctime> |
| 237 |
// nor ICU's time zone classes, because that may cause I/O operations slowing |
| 238 |
// down the JS engine initialization, which we're currently in the middle of. |
| 239 |
timeZoneStatus_ = TimeZoneStatus::NeedsUpdate; |
| 240 |
} |
| 241 |
|
| 242 |
js::DateTimeInfo::~DateTimeInfo() = default; |
| 243 |
|
| 244 |
int64_t js::DateTimeInfo::toClampedSeconds(int64_t milliseconds) { |
| 245 |
int64_t seconds = milliseconds / msPerSecond; |
| 246 |
int64_t millis = milliseconds % msPerSecond; |
| 247 |
|
| 248 |
// Round towards the start of time. |
| 249 |
if (millis < 0) { |
| 250 |
seconds -= 1; |
| 251 |
} |
| 252 |
|
| 253 |
if (seconds > MaxTimeT) { |
| 254 |
seconds = MaxTimeT; |
| 255 |
} else if (seconds < MinTimeT) { |
| 256 |
/* Go ahead a day to make localtime work (does not work with 0). */ |
| 257 |
seconds = MinTimeT + SecondsPerDay; |
| 258 |
} |
| 259 |
return seconds; |
| 260 |
} |
| 261 |
|
| 262 |
int32_t js::DateTimeInfo::computeDSTOffsetMilliseconds(int64_t utcSeconds) { |
| 263 |
MOZ_ASSERT(utcSeconds >= MinTimeT); |
| 264 |
MOZ_ASSERT(utcSeconds <= MaxTimeT); |
| 265 |
|
| 266 |
#if JS_HAS_INTL_API |
| 267 |
int64_t utcMilliseconds = utcSeconds * msPerSecond; |
| 268 |
|
| 269 |
return timeZone()->GetDSTOffsetMs(utcMilliseconds).unwrapOr(0); |
| 270 |
#else |
| 271 |
struct tm tm; |
| 272 |
if (!ComputeLocalTime(static_cast<time_t>(utcSeconds), &tm)) { |
| 273 |
return 0; |
| 274 |
} |
| 275 |
|
| 276 |
// NB: The offset isn't computed correctly when the standard local offset |
| 277 |
// at |utcSeconds| is different from |utcToLocalStandardOffsetSeconds|. |
| 278 |
int32_t dayoff = |
| 279 |
int32_t((utcSeconds + utcToLocalStandardOffsetSeconds_) % SecondsPerDay); |
| 280 |
int32_t tmoff = tm.tm_sec + (tm.tm_min * SecondsPerMinute) + |
| 281 |
(tm.tm_hour * SecondsPerHour); |
| 282 |
|
| 283 |
int32_t diff = tmoff - dayoff; |
| 284 |
|
| 285 |
if (diff < 0) { |
| 286 |
diff += SecondsPerDay; |
| 287 |
} else if (uint32_t(diff) >= SecondsPerDay) { |
| 288 |
diff -= SecondsPerDay; |
| 289 |
} |
| 290 |
|
| 291 |
return diff * int32_t(msPerSecond); |
| 292 |
#endif /* JS_HAS_INTL_API */ |
| 293 |
} |
| 294 |
|
| 295 |
int32_t js::DateTimeInfo::internalGetDSTOffsetMilliseconds( |
| 296 |
int64_t utcMilliseconds) { |
| 297 |
int64_t utcSeconds = toClampedSeconds(utcMilliseconds); |
| 298 |
return getOrComputeValue(dstRange_, utcSeconds, |
| 299 |
&DateTimeInfo::computeDSTOffsetMilliseconds); |
| 300 |
} |
| 301 |
|
| 302 |
int32_t js::DateTimeInfo::getOrComputeValue(RangeCache& range, int64_t seconds, |
| 303 |
ComputeFn compute) { |
| 304 |
range.sanityCheck(); |
| 305 |
|
| 306 |
auto checkSanity = |
| 307 |
mozilla::MakeScopeExit([&range]() { range.sanityCheck(); }); |
| 308 |
|
| 309 |
// NB: Be aware of the initial range values when making changes to this |
| 310 |
// code: the first call to this method, with those initial range |
| 311 |
// values, must result in a cache miss. |
| 312 |
MOZ_ASSERT(seconds != INT64_MIN); |
| 313 |
|
| 314 |
if (range.startSeconds <= seconds && seconds <= range.endSeconds) { |
| 315 |
return range.offsetMilliseconds; |
| 316 |
} |
| 317 |
|
| 318 |
if (range.oldStartSeconds <= seconds && seconds <= range.oldEndSeconds) { |
| 319 |
return range.oldOffsetMilliseconds; |
| 320 |
} |
| 321 |
|
| 322 |
range.oldOffsetMilliseconds = range.offsetMilliseconds; |
| 323 |
range.oldStartSeconds = range.startSeconds; |
| 324 |
range.oldEndSeconds = range.endSeconds; |
| 325 |
|
| 326 |
if (range.startSeconds <= seconds) { |
| 327 |
int64_t newEndSeconds = |
| 328 |
std::min({range.endSeconds + RangeExpansionAmount, MaxTimeT}); |
| 329 |
if (newEndSeconds >= seconds) { |
| 330 |
int32_t endOffsetMilliseconds = (this->*compute)(newEndSeconds); |
| 331 |
if (endOffsetMilliseconds == range.offsetMilliseconds) { |
| 332 |
range.endSeconds = newEndSeconds; |
| 333 |
return range.offsetMilliseconds; |
| 334 |
} |
| 335 |
|
| 336 |
range.offsetMilliseconds = (this->*compute)(seconds); |
| 337 |
if (range.offsetMilliseconds == endOffsetMilliseconds) { |
| 338 |
range.startSeconds = seconds; |
| 339 |
range.endSeconds = newEndSeconds; |
| 340 |
} else { |
| 341 |
range.endSeconds = seconds; |
| 342 |
} |
| 343 |
return range.offsetMilliseconds; |
| 344 |
} |
| 345 |
|
| 346 |
range.offsetMilliseconds = (this->*compute)(seconds); |
| 347 |
range.startSeconds = range.endSeconds = seconds; |
| 348 |
return range.offsetMilliseconds; |
| 349 |
} |
| 350 |
|
| 351 |
int64_t newStartSeconds = |
| 352 |
std::max<int64_t>({range.startSeconds - RangeExpansionAmount, MinTimeT}); |
| 353 |
if (newStartSeconds <= seconds) { |
| 354 |
int32_t startOffsetMilliseconds = (this->*compute)(newStartSeconds); |
| 355 |
if (startOffsetMilliseconds == range.offsetMilliseconds) { |
| 356 |
range.startSeconds = newStartSeconds; |
| 357 |
return range.offsetMilliseconds; |
| 358 |
} |
| 359 |
|
| 360 |
range.offsetMilliseconds = (this->*compute)(seconds); |
| 361 |
if (range.offsetMilliseconds == startOffsetMilliseconds) { |
| 362 |
range.startSeconds = newStartSeconds; |
| 363 |
range.endSeconds = seconds; |
| 364 |
} else { |
| 365 |
range.startSeconds = seconds; |
| 366 |
} |
| 367 |
return range.offsetMilliseconds; |
| 368 |
} |
| 369 |
|
| 370 |
range.startSeconds = range.endSeconds = seconds; |
| 371 |
range.offsetMilliseconds = (this->*compute)(seconds); |
| 372 |
return range.offsetMilliseconds; |
| 373 |
} |
| 374 |
|
| 375 |
void js::DateTimeInfo::RangeCache::reset() { |
| 376 |
// The initial range values are carefully chosen to result in a cache miss |
| 377 |
// on first use given the range of possible values. Be careful to keep |
| 378 |
// these values and the caching algorithm in sync! |
| 379 |
offsetMilliseconds = 0; |
| 380 |
startSeconds = endSeconds = INT64_MIN; |
| 381 |
oldOffsetMilliseconds = 0; |
| 382 |
oldStartSeconds = oldEndSeconds = INT64_MIN; |
| 383 |
|
| 384 |
sanityCheck(); |
| 385 |
} |
| 386 |
|
| 387 |
void js::DateTimeInfo::RangeCache::sanityCheck() { |
| 388 |
auto assertRange = [](int64_t start, int64_t end) { |
| 389 |
MOZ_ASSERT(start <= end); |
| 390 |
MOZ_ASSERT_IF(start == INT64_MIN, end == INT64_MIN); |
| 391 |
MOZ_ASSERT_IF(end == INT64_MIN, start == INT64_MIN); |
| 392 |
MOZ_ASSERT_IF(start != INT64_MIN, start >= MinTimeT && end >= MinTimeT); |
| 393 |
MOZ_ASSERT_IF(start != INT64_MIN, start <= MaxTimeT && end <= MaxTimeT); |
| 394 |
}; |
| 395 |
|
| 396 |
assertRange(startSeconds, endSeconds); |
| 397 |
assertRange(oldStartSeconds, oldEndSeconds); |
| 398 |
} |
| 399 |
|
| 400 |
#if JS_HAS_INTL_API |
| 401 |
int32_t js::DateTimeInfo::computeUTCOffsetMilliseconds(int64_t localSeconds) { |
| 402 |
MOZ_ASSERT(localSeconds >= MinTimeT); |
| 403 |
MOZ_ASSERT(localSeconds <= MaxTimeT); |
| 404 |
|
| 405 |
int64_t localMilliseconds = localSeconds * msPerSecond; |
| 406 |
|
| 407 |
return timeZone()->GetUTCOffsetMs(localMilliseconds).unwrapOr(0); |
| 408 |
} |
| 409 |
|
| 410 |
int32_t js::DateTimeInfo::computeLocalOffsetMilliseconds(int64_t utcSeconds) { |
| 411 |
MOZ_ASSERT(utcSeconds >= MinTimeT); |
| 412 |
MOZ_ASSERT(utcSeconds <= MaxTimeT); |
| 413 |
|
| 414 |
UDate utcMilliseconds = UDate(utcSeconds * msPerSecond); |
| 415 |
|
| 416 |
return timeZone()->GetOffsetMs(utcMilliseconds).unwrapOr(0); |
| 417 |
} |
| 418 |
|
| 419 |
int32_t js::DateTimeInfo::internalGetOffsetMilliseconds(int64_t milliseconds, |
| 420 |
TimeZoneOffset offset) { |
| 421 |
int64_t seconds = toClampedSeconds(milliseconds); |
| 422 |
return offset == TimeZoneOffset::UTC |
| 423 |
? getOrComputeValue(localRange_, seconds, |
| 424 |
&DateTimeInfo::computeLocalOffsetMilliseconds) |
| 425 |
: getOrComputeValue(utcRange_, seconds, |
| 426 |
&DateTimeInfo::computeUTCOffsetMilliseconds); |
| 427 |
} |
| 428 |
|
| 429 |
bool js::DateTimeInfo::internalTimeZoneDisplayName(char16_t* buf, size_t buflen, |
| 430 |
int64_t utcMilliseconds, |
| 431 |
const char* locale) { |
| 432 |
MOZ_ASSERT(buf != nullptr); |
| 433 |
MOZ_ASSERT(buflen > 0); |
| 434 |
MOZ_ASSERT(locale != nullptr); |
| 435 |
|
| 436 |
// Clear any previously cached names when the default locale changed. |
| 437 |
if (!locale_ || std::strcmp(locale_.get(), locale) != 0) { |
| 438 |
locale_ = DuplicateString(locale); |
| 439 |
if (!locale_) { |
| 440 |
return false; |
| 441 |
} |
| 442 |
|
| 443 |
standardName_.reset(); |
| 444 |
daylightSavingsName_.reset(); |
| 445 |
} |
| 446 |
|
| 447 |
using DaylightSavings = mozilla::intl::TimeZone::DaylightSavings; |
| 448 |
|
| 449 |
auto daylightSavings = internalGetDSTOffsetMilliseconds(utcMilliseconds) != 0 |
| 450 |
? DaylightSavings::Yes |
| 451 |
: DaylightSavings::No; |
| 452 |
|
| 453 |
JS::UniqueTwoByteChars& cachedName = (daylightSavings == DaylightSavings::Yes) |
| 454 |
? daylightSavingsName_ |
| 455 |
: standardName_; |
| 456 |
if (!cachedName) { |
| 457 |
// Retrieve the display name for the given locale. |
| 458 |
|
| 459 |
intl::FormatBuffer<char16_t, 0, js::SystemAllocPolicy> buffer; |
| 460 |
if (timeZone()->GetDisplayName(locale, daylightSavings, buffer).isErr()) { |
| 461 |
return false; |
| 462 |
} |
| 463 |
|
| 464 |
cachedName = buffer.extractStringZ(); |
| 465 |
if (!cachedName) { |
| 466 |
return false; |
| 467 |
} |
| 468 |
} |
| 469 |
|
| 470 |
// Return an empty string if the display name doesn't fit into the buffer. |
| 471 |
size_t length = js_strlen(cachedName.get()); |
| 472 |
if (length < buflen) { |
| 473 |
std::copy(cachedName.get(), cachedName.get() + length, buf); |
| 474 |
} else { |
| 475 |
length = 0; |
| 476 |
} |
| 477 |
|
| 478 |
buf[length] = '\0'; |
| 479 |
return true; |
| 480 |
} |
| 481 |
|
| 482 |
mozilla::intl::TimeZone* js::DateTimeInfo::timeZone() { |
| 483 |
if (!timeZone_) { |
| 484 |
// For resist finger printing mode we always use the Atlantic/Reykjavik time |
| 485 |
// zone as a "real world" UTC equivalent. |
| 486 |
mozilla::Maybe<mozilla::Span<const char16_t>> timeZoneOverride; |
| 487 |
if (forceUTC_) { |
| 488 |
timeZoneOverride = |
| 489 |
mozilla::Some(mozilla::MakeStringSpan(u"Atlantic/Reykjavik")); |
| 490 |
} |
| 491 |
|
| 492 |
auto timeZone = mozilla::intl::TimeZone::TryCreate(timeZoneOverride); |
| 493 |
|
| 494 |
// Creating the default or UTC time zone should never fail. If it should |
| 495 |
// fail nonetheless for some reason, just crash because we don't have a way |
| 496 |
// to propagate any errors. |
| 497 |
MOZ_RELEASE_ASSERT(timeZone.isOk()); |
| 498 |
|
| 499 |
timeZone_ = timeZone.unwrap(); |
| 500 |
MOZ_ASSERT(timeZone_); |
| 501 |
} |
| 502 |
|
| 503 |
return timeZone_.get(); |
| 504 |
} |
| 505 |
#endif /* JS_HAS_INTL_API */ |
| 506 |
|
| 507 |
/* static */ js::ExclusiveData<js::DateTimeInfo>* js::DateTimeInfo::instance; |
| 508 |
/* static */ js::ExclusiveData<js::DateTimeInfo>* js::DateTimeInfo::instanceUTC; |
| 509 |
|
| 510 |
bool js::InitDateTimeState() { |
| 511 |
MOZ_ASSERT(!DateTimeInfo::instance && !DateTimeInfo::instanceUTC, |
| 512 |
"we should be initializing only once"); |
| 513 |
|
| 514 |
DateTimeInfo::instance = |
| 515 |
js_new<ExclusiveData<DateTimeInfo>>(mutexid::DateTimeInfoMutex, false); |
| 516 |
DateTimeInfo::instanceUTC = |
| 517 |
js_new<ExclusiveData<DateTimeInfo>>(mutexid::DateTimeInfoMutex, true); |
| 518 |
return DateTimeInfo::instance && DateTimeInfo::instanceUTC; |
| 519 |
} |
| 520 |
|
| 521 |
/* static */ |
| 522 |
void js::FinishDateTimeState() { |
| 523 |
js_delete(DateTimeInfo::instance); |
| 524 |
DateTimeInfo::instance = nullptr; |
| 525 |
} |
| 526 |
|
| 527 |
void js::ResetTimeZoneInternal(ResetTimeZoneMode mode) { |
| 528 |
js::DateTimeInfo::resetTimeZone(mode); |
| 529 |
} |
| 530 |
|
| 531 |
JS_PUBLIC_API void JS::ResetTimeZone() { |
| 532 |
js::ResetTimeZoneInternal(js::ResetTimeZoneMode::ResetEvenIfOffsetUnchanged); |
| 533 |
} |
| 534 |
|
| 535 |
#if JS_HAS_INTL_API |
| 536 |
# if defined(XP_WIN) |
| 537 |
static bool IsOlsonCompatibleWindowsTimeZoneId(std::string_view tz) { |
| 538 |
// ICU ignores the TZ environment variable on Windows and instead directly |
| 539 |
// invokes Win API functions to retrieve the current time zone. But since |
| 540 |
// we're still using the POSIX-derived localtime_s() function on Windows |
| 541 |
// and localtime_s() does return a time zone adjusted value based on the |
| 542 |
// TZ environment variable, we need to manually adjust the default ICU |
| 543 |
// time zone if TZ is set. |
| 544 |
// |
| 545 |
// Windows supports the following format for TZ: tzn[+|-]hh[:mm[:ss]][dzn] |
| 546 |
// where "tzn" is the time zone name for standard time, the time zone |
| 547 |
// offset is positive for time zones west of GMT, and "dzn" is the |
| 548 |
// optional time zone name when daylight savings are observed. Daylight |
| 549 |
// savings are always based on the U.S. daylight saving rules, that means |
| 550 |
// for example it's not possible to use "TZ=CET-1CEST" to select the IANA |
| 551 |
// time zone "CET". |
| 552 |
// |
| 553 |
// When comparing this restricted format for TZ to all IANA time zone |
| 554 |
// names, the following time zones are in the intersection of what's |
| 555 |
// supported by Windows and is also a valid IANA time zone identifier. |
| 556 |
// |
| 557 |
// Even though the time zone offset is marked as mandatory on MSDN, it |
| 558 |
// appears it defaults to zero when omitted. This in turn means we can |
| 559 |
// also allow the time zone identifiers "UCT", "UTC", and "GMT". |
| 560 |
|
| 561 |
static const char* const allowedIds[] = { |
| 562 |
// From tzdata's "northamerica" file: |
| 563 |
"EST5EDT", |
| 564 |
"CST6CDT", |
| 565 |
"MST7MDT", |
| 566 |
"PST8PDT", |
| 567 |
|
| 568 |
// From tzdata's "backward" file: |
| 569 |
"GMT+0", |
| 570 |
"GMT-0", |
| 571 |
"GMT0", |
| 572 |
"UCT", |
| 573 |
"UTC", |
| 574 |
|
| 575 |
// From tzdata's "etcetera" file: |
| 576 |
"GMT", |
| 577 |
}; |
| 578 |
for (const auto& allowedId : allowedIds) { |
| 579 |
if (tz == allowedId) { |
| 580 |
return true; |
| 581 |
} |
| 582 |
} |
| 583 |
return false; |
| 584 |
} |
| 585 |
# else |
| 586 |
static std::string_view TZContainsAbsolutePath(std::string_view tzVar) { |
| 587 |
// A TZ environment variable may be an absolute path. The path |
| 588 |
// format of TZ may begin with a colon. (ICU handles relative paths.) |
| 589 |
if (tzVar.length() > 1 && tzVar[0] == ':' && tzVar[1] == '/') { |
| 590 |
return tzVar.substr(1); |
| 591 |
} |
| 592 |
if (tzVar.length() > 0 && tzVar[0] == '/') { |
| 593 |
return tzVar; |
| 594 |
} |
| 595 |
return {}; |
| 596 |
} |
| 597 |
|
| 598 |
/** |
| 599 |
* Reject the input if it doesn't match the time zone id pattern or legacy time |
| 600 |
* zone names. |
| 601 |
* |
| 602 |
* See <https://github.com/eggert/tz/blob/master/theory.html>. |
| 603 |
*/ |
| 604 |
static bool IsTimeZoneId(std::string_view timeZone) { |
| 605 |
size_t timeZoneLen = timeZone.length(); |
| 606 |
|
| 607 |
if (timeZoneLen == 0) { |
| 608 |
return false; |
| 609 |
} |
| 610 |
|
| 611 |
for (size_t i = 0; i < timeZoneLen; i++) { |
| 612 |
char c = timeZone[i]; |
| 613 |
|
| 614 |
// According to theory.html, '.' is allowed in time zone ids, but the |
| 615 |
// accompanying zic.c file doesn't allow it. Assume the source file is |
| 616 |
// correct and disallow '.' here, too. |
| 617 |
if (mozilla::IsAsciiAlphanumeric(c) || c == '_' || c == '-' || c == '+') { |
| 618 |
continue; |
| 619 |
} |
| 620 |
|
| 621 |
// Reject leading, trailing, or consecutive '/' characters. |
| 622 |
if (c == '/' && i > 0 && i + 1 < timeZoneLen && timeZone[i + 1] != '/') { |
| 623 |
continue; |
| 624 |
} |
| 625 |
|
| 626 |
return false; |
| 627 |
} |
| 628 |
|
| 629 |
return true; |
| 630 |
} |
| 631 |
|
| 632 |
using TimeZoneIdentifierVector = |
| 633 |
js::Vector<char, mozilla::intl::TimeZone::TimeZoneIdentifierLength, |
| 634 |
js::SystemAllocPolicy>; |
| 635 |
|
| 636 |
/** |
| 637 |
* Given a presumptive path |tz| to a zoneinfo time zone file |
| 638 |
* (e.g. /etc/localtime), attempt to compute the time zone encoded by that |
| 639 |
* path by repeatedly resolving symlinks until a path containing "/zoneinfo/" |
| 640 |
* followed by time zone looking components is found. If a symlink is broken, |
| 641 |
* symlink-following recurs too deeply, non time zone looking components are |
| 642 |
* encountered, or some other error is encountered, then the |result| buffer is |
| 643 |
* left empty. |
| 644 |
* |
| 645 |
* If |result| is set to a non-empty string, it's only guaranteed to have |
| 646 |
* certain syntactic validity. It might not actually *be* a time zone name. |
| 647 |
* |
| 648 |
* If there's an (OOM) error, |false| is returned. |
| 649 |
*/ |
| 650 |
static bool ReadTimeZoneLink(std::string_view tz, |
| 651 |
TimeZoneIdentifierVector& result) { |
| 652 |
MOZ_ASSERT(!tz.empty()); |
| 653 |
MOZ_ASSERT(result.empty()); |
| 654 |
|
| 655 |
// The resolved link name can have different paths depending on the OS. |
| 656 |
// Follow ICU and only search for "/zoneinfo/"; see $ICU/common/putil.cpp. |
| 657 |
static constexpr char ZoneInfoPath[] = "/zoneinfo/"; |
| 658 |
constexpr size_t ZoneInfoPathLength = js_strlen(ZoneInfoPath); |
| 659 |
|
| 660 |
// Stop following symlinks after a fixed depth, because some common time |
| 661 |
// zones are stored in files whose name doesn't match an Olson time zone |
| 662 |
// name. For example on Ubuntu, "/usr/share/zoneinfo/America/New_York" is a |
| 663 |
// symlink to "/usr/share/zoneinfo/posixrules" and "posixrules" is not an |
| 664 |
// Olson time zone name. |
| 665 |
// Four hops should be a reasonable limit for most use cases. |
| 666 |
constexpr uint32_t FollowDepthLimit = 4; |
| 667 |
|
| 668 |
# ifdef PATH_MAX |
| 669 |
constexpr size_t PathMax = PATH_MAX; |
| 670 |
# else |
| 671 |
constexpr size_t PathMax = 4096; |
| 672 |
# endif |
| 673 |
static_assert(PathMax > 0, "PathMax should be larger than zero"); |
| 674 |
|
| 675 |
char linkName[PathMax]; |
| 676 |
constexpr size_t linkNameLen = |
| 677 |
std::size(linkName) - 1; // -1 to null-terminate. |
| 678 |
|
| 679 |
// Return if the TZ value is too large. |
| 680 |
if (tz.length() > linkNameLen) { |
| 681 |
return true; |
| 682 |
} |
| 683 |
|
| 684 |
tz.copy(linkName, tz.length()); |
| 685 |
linkName[tz.length()] = '\0'; |
| 686 |
|
| 687 |
char linkTarget[PathMax]; |
| 688 |
constexpr size_t linkTargetLen = |
| 689 |
std::size(linkTarget) - 1; // -1 to null-terminate. |
| 690 |
|
| 691 |
uint32_t depth = 0; |
| 692 |
|
| 693 |
// Search until we find "/zoneinfo/" in the link name. |
| 694 |
const char* timeZoneWithZoneInfo; |
| 695 |
while (!(timeZoneWithZoneInfo = std::strstr(linkName, ZoneInfoPath))) { |
| 696 |
// Return if the symlink nesting is too deep. |
| 697 |
if (++depth > FollowDepthLimit) { |
| 698 |
return true; |
| 699 |
} |
| 700 |
|
| 701 |
// Return on error or if the result was truncated. |
| 702 |
ssize_t slen = readlink(linkName, linkTarget, linkTargetLen); |
| 703 |
if (slen < 0 || size_t(slen) >= linkTargetLen) { |
| 704 |
return true; |
| 705 |
} |
| 706 |
|
| 707 |
// Ensure linkTarget is null-terminated. (readlink may not necessarily |
| 708 |
// null-terminate the string.) |
| 709 |
size_t len = size_t(slen); |
| 710 |
linkTarget[len] = '\0'; |
| 711 |
|
| 712 |
// If the target is absolute, continue with that. |
| 713 |
if (linkTarget[0] == '/') { |
| 714 |
std::strcpy(linkName, linkTarget); |
| 715 |
continue; |
| 716 |
} |
| 717 |
|
| 718 |
// If the target is relative, it must be resolved against either the |
| 719 |
// directory the link was in, or against the current working directory. |
| 720 |
char* separator = std::strrchr(linkName, '/'); |
| 721 |
|
| 722 |
// If the link name is just something like "foo", resolve linkTarget |
| 723 |
// against the current working directory. |
| 724 |
if (!separator) { |
| 725 |
std::strcpy(linkName, linkTarget); |
| 726 |
continue; |
| 727 |
} |
| 728 |
|
| 729 |
// Remove everything after the final path separator in linkName. |
| 730 |
separator[1] = '\0'; |
| 731 |
|
| 732 |
// Return if the concatenated path name is too large. |
| 733 |
if (std::strlen(linkName) + len > linkNameLen) { |
| 734 |
return true; |
| 735 |
} |
| 736 |
|
| 737 |
// Keep it simple and just concatenate the path names. |
| 738 |
std::strcat(linkName, linkTarget); |
| 739 |
} |
| 740 |
|
| 741 |
std::string_view timeZone(timeZoneWithZoneInfo + ZoneInfoPathLength); |
| 742 |
if (!IsTimeZoneId(timeZone)) { |
| 743 |
return true; |
| 744 |
} |
| 745 |
return result.append(timeZone.data(), timeZone.length()); |
| 746 |
} |
| 747 |
# endif /* defined(XP_WIN) */ |
| 748 |
#endif /* JS_HAS_INTL_API */ |
| 749 |
|
| 750 |
void js::DateTimeInfo::internalResyncICUDefaultTimeZone() { |
| 751 |
#if JS_HAS_INTL_API |
| 752 |
// In the future we should not be setting a default ICU time zone at all, |
| 753 |
// instead all accesses should go through the appropriate DateTimeInfo |
| 754 |
// instance depending on the resist fingerprinting status. For now we return |
| 755 |
// early to prevent overwriting the default time zone with the UTC time zone |
| 756 |
// used by RFP. |
| 757 |
if (forceUTC_) { |
| 758 |
return; |
| 759 |
} |
| 760 |
|
| 761 |
if (const char* tzenv = std::getenv("TZ")) { |
| 762 |
std::string_view tz(tzenv); |
| 763 |
|
| 764 |
mozilla::Span<const char> tzid; |
| 765 |
|
| 766 |
# if defined(XP_WIN) |
| 767 |
// If TZ is set and its value is valid under Windows' and IANA's time zone |
| 768 |
// identifier rules, update the ICU default time zone to use this value. |
| 769 |
if (IsOlsonCompatibleWindowsTimeZoneId(tz)) { |
| 770 |
tzid = mozilla::Span(tz.data(), tz.length()); |
| 771 |
} else { |
| 772 |
// If |tz| isn't a supported time zone identifier, use the default Windows |
| 773 |
// time zone for ICU. |
| 774 |
// TODO: Handle invalid time zone identifiers (bug 342068). |
| 775 |
} |
| 776 |
# else |
| 777 |
// The TZ environment variable allows both absolute and relative paths, |
| 778 |
// optionally beginning with a colon (':'). (Relative paths, without the |
| 779 |
// colon, are just Olson time zone names.) We need to handle absolute paths |
| 780 |
// ourselves, including handling that they might be symlinks. |
| 781 |
// <https://unicode-org.atlassian.net/browse/ICU-13694> |
| 782 |
TimeZoneIdentifierVector tzidVector; |
| 783 |
std::string_view tzlink = TZContainsAbsolutePath(tz); |
| 784 |
if (!tzlink.empty()) { |
| 785 |
if (!ReadTimeZoneLink(tzlink, tzidVector)) { |
| 786 |
// Ignore OOM. |
| 787 |
return; |
| 788 |
} |
| 789 |
tzid = tzidVector; |
| 790 |
} |
| 791 |
|
| 792 |
# ifdef ANDROID |
| 793 |
// ICU ignores the TZ environment variable on Android. If it doesn't contain |
| 794 |
// an absolute path, try to parse it as a time zone name. |
| 795 |
else if (IsTimeZoneId(tz)) { |
| 796 |
tzid = mozilla::Span(tz.data(), tz.length()); |
| 797 |
} |
| 798 |
# endif |
| 799 |
# endif /* defined(XP_WIN) */ |
| 800 |
|
| 801 |
if (!tzid.empty()) { |
| 802 |
auto result = mozilla::intl::TimeZone::SetDefaultTimeZone(tzid); |
| 803 |
if (result.isErr()) { |
| 804 |
// Intentionally ignore any errors, because we don't have a good way to |
| 805 |
// report errors from this function. |
| 806 |
return; |
| 807 |
} |
| 808 |
|
| 809 |
// Return if the default time zone was successfully updated. |
| 810 |
if (result.unwrap()) { |
| 811 |
return; |
| 812 |
} |
| 813 |
|
| 814 |
// If SetDefaultTimeZone() succeeded, but the default time zone wasn't |
| 815 |
// changed, proceed to set the default time zone from the host time zone. |
| 816 |
} |
| 817 |
} |
| 818 |
|
| 819 |
// Intentionally ignore any errors, because we don't have a good way to report |
| 820 |
// errors from this function. |
| 821 |
(void)mozilla::intl::TimeZone::SetDefaultTimeZoneFromHostTimeZone(); |
| 822 |
#endif |
| 823 |
} |