time_zone_info.cc (41698B)
1 // Copyright 2016 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // This file implements the TimeZoneIf interface using the "zoneinfo" 16 // data provided by the IANA Time Zone Database (i.e., the only real game 17 // in town). 18 // 19 // TimeZoneInfo represents the history of UTC-offset changes within a time 20 // zone. Most changes are due to daylight-saving rules, but occasionally 21 // shifts are made to the time-zone's base offset. The database only attempts 22 // to be definitive for times since 1970, so be wary of local-time conversions 23 // before that. Also, rule and zone-boundary changes are made at the whim 24 // of governments, so the conversion of future times needs to be taken with 25 // a grain of salt. 26 // 27 // For more information see tzfile(5), http://www.iana.org/time-zones, or 28 // https://en.wikipedia.org/wiki/Zoneinfo. 29 // 30 // Note that we assume the proleptic Gregorian calendar and 60-second 31 // minutes throughout. 32 33 #include "absl/time/internal/cctz/src/time_zone_info.h" 34 35 #include <algorithm> 36 #include <cassert> 37 #include <chrono> 38 #include <cstdint> 39 #include <cstdio> 40 #include <cstdlib> 41 #include <cstring> 42 #include <fstream> 43 #include <functional> 44 #include <memory> 45 #include <sstream> 46 #include <string> 47 #include <utility> 48 #include <vector> 49 50 #include "absl/base/config.h" 51 #include "absl/time/internal/cctz/include/cctz/civil_time.h" 52 #include "absl/time/internal/cctz/src/time_zone_fixed.h" 53 #include "absl/time/internal/cctz/src/time_zone_posix.h" 54 55 namespace absl { 56 ABSL_NAMESPACE_BEGIN 57 namespace time_internal { 58 namespace cctz { 59 60 namespace { 61 62 inline bool IsLeap(year_t year) { 63 return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0); 64 } 65 66 // The number of days in non-leap and leap years respectively. 67 const std::int_least32_t kDaysPerYear[2] = {365, 366}; 68 69 // The day offsets of the beginning of each (1-based) month in non-leap and 70 // leap years respectively (e.g., 335 days before December in a leap year). 71 const std::int_least16_t kMonthOffsets[2][1 + 12 + 1] = { 72 {-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}, 73 {-1, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}, 74 }; 75 76 // We reject leap-second encoded zoneinfo and so assume 60-second minutes. 77 const std::int_least32_t kSecsPerDay = 24 * 60 * 60; 78 79 // 400-year chunks always have 146097 days (20871 weeks). 80 const std::int_least64_t kSecsPer400Years = 146097LL * kSecsPerDay; 81 82 // Like kDaysPerYear[] but scaled up by a factor of kSecsPerDay. 83 const std::int_least32_t kSecsPerYear[2] = { 84 365 * kSecsPerDay, 85 366 * kSecsPerDay, 86 }; 87 88 // Convert a cctz::weekday to a POSIX TZ weekday number (0==Sun, ..., 6=Sat). 89 inline int ToPosixWeekday(weekday wd) { 90 switch (wd) { 91 case weekday::sunday: 92 return 0; 93 case weekday::monday: 94 return 1; 95 case weekday::tuesday: 96 return 2; 97 case weekday::wednesday: 98 return 3; 99 case weekday::thursday: 100 return 4; 101 case weekday::friday: 102 return 5; 103 case weekday::saturday: 104 return 6; 105 } 106 return 0; /*NOTREACHED*/ 107 } 108 109 // Single-byte, unsigned numeric values are encoded directly. 110 inline std::uint_fast8_t Decode8(const char* cp) { 111 return static_cast<std::uint_fast8_t>(*cp) & 0xff; 112 } 113 114 // Multi-byte, numeric values are encoded using a MSB first, 115 // twos-complement representation. These helpers decode, from 116 // the given address, 4-byte and 8-byte values respectively. 117 // Note: If int_fastXX_t == intXX_t and this machine is not 118 // twos complement, then there will be at least one input value 119 // we cannot represent. 120 std::int_fast32_t Decode32(const char* cp) { 121 std::uint_fast32_t v = 0; 122 for (int i = 0; i != (32 / 8); ++i) v = (v << 8) | Decode8(cp++); 123 const std::int_fast32_t s32max = 0x7fffffff; 124 const auto s32maxU = static_cast<std::uint_fast32_t>(s32max); 125 if (v <= s32maxU) return static_cast<std::int_fast32_t>(v); 126 return static_cast<std::int_fast32_t>(v - s32maxU - 1) - s32max - 1; 127 } 128 129 std::int_fast64_t Decode64(const char* cp) { 130 std::uint_fast64_t v = 0; 131 for (int i = 0; i != (64 / 8); ++i) v = (v << 8) | Decode8(cp++); 132 const std::int_fast64_t s64max = 0x7fffffffffffffff; 133 const auto s64maxU = static_cast<std::uint_fast64_t>(s64max); 134 if (v <= s64maxU) return static_cast<std::int_fast64_t>(v); 135 return static_cast<std::int_fast64_t>(v - s64maxU - 1) - s64max - 1; 136 } 137 138 struct Header { // counts of: 139 std::size_t timecnt; // transition times 140 std::size_t typecnt; // transition types 141 std::size_t charcnt; // zone abbreviation characters 142 std::size_t leapcnt; // leap seconds (we expect none) 143 std::size_t ttisstdcnt; // UTC/local indicators (unused) 144 std::size_t ttisutcnt; // standard/wall indicators (unused) 145 146 bool Build(const tzhead& tzh); 147 std::size_t DataLength(std::size_t time_len) const; 148 }; 149 150 // Builds the in-memory header using the raw bytes from the file. 151 bool Header::Build(const tzhead& tzh) { 152 std::int_fast32_t v; 153 if ((v = Decode32(tzh.tzh_timecnt)) < 0) return false; 154 timecnt = static_cast<std::size_t>(v); 155 if ((v = Decode32(tzh.tzh_typecnt)) < 0) return false; 156 typecnt = static_cast<std::size_t>(v); 157 if ((v = Decode32(tzh.tzh_charcnt)) < 0) return false; 158 charcnt = static_cast<std::size_t>(v); 159 if ((v = Decode32(tzh.tzh_leapcnt)) < 0) return false; 160 leapcnt = static_cast<std::size_t>(v); 161 if ((v = Decode32(tzh.tzh_ttisstdcnt)) < 0) return false; 162 ttisstdcnt = static_cast<std::size_t>(v); 163 if ((v = Decode32(tzh.tzh_ttisutcnt)) < 0) return false; 164 ttisutcnt = static_cast<std::size_t>(v); 165 return true; 166 } 167 168 // How many bytes of data are associated with this header. The result 169 // depends upon whether this is a section with 4-byte or 8-byte times. 170 std::size_t Header::DataLength(std::size_t time_len) const { 171 std::size_t len = 0; 172 len += (time_len + 1) * timecnt; // unix_time + type_index 173 len += (4 + 1 + 1) * typecnt; // utc_offset + is_dst + abbr_index 174 len += 1 * charcnt; // abbreviations 175 len += (time_len + 4) * leapcnt; // leap-time + TAI-UTC 176 len += 1 * ttisstdcnt; // UTC/local indicators 177 len += 1 * ttisutcnt; // standard/wall indicators 178 return len; 179 } 180 181 // Does the rule for future transitions call for year-round daylight time? 182 // See tz/zic.c:stringzone() for the details on how such rules are encoded. 183 bool AllYearDST(const PosixTimeZone& posix) { 184 if (posix.dst_start.date.fmt != PosixTransition::N) return false; 185 if (posix.dst_start.date.n.day != 0) return false; 186 if (posix.dst_start.time.offset != 0) return false; 187 188 if (posix.dst_end.date.fmt != PosixTransition::J) return false; 189 if (posix.dst_end.date.j.day != kDaysPerYear[0]) return false; 190 const auto offset = posix.std_offset - posix.dst_offset; 191 if (posix.dst_end.time.offset + offset != kSecsPerDay) return false; 192 193 return true; 194 } 195 196 // Generate a year-relative offset for a PosixTransition. 197 std::int_fast64_t TransOffset(bool leap_year, int jan1_weekday, 198 const PosixTransition& pt) { 199 std::int_fast64_t days = 0; 200 switch (pt.date.fmt) { 201 case PosixTransition::J: { 202 days = pt.date.j.day; 203 if (!leap_year || days < kMonthOffsets[1][3]) days -= 1; 204 break; 205 } 206 case PosixTransition::N: { 207 days = pt.date.n.day; 208 break; 209 } 210 case PosixTransition::M: { 211 const bool last_week = (pt.date.m.week == 5); 212 days = kMonthOffsets[leap_year][pt.date.m.month + last_week]; 213 const std::int_fast64_t weekday = (jan1_weekday + days) % 7; 214 if (last_week) { 215 days -= (weekday + 7 - 1 - pt.date.m.weekday) % 7 + 1; 216 } else { 217 days += (pt.date.m.weekday + 7 - weekday) % 7; 218 days += (pt.date.m.week - 1) * 7; 219 } 220 break; 221 } 222 } 223 return (days * kSecsPerDay) + pt.time.offset; 224 } 225 226 inline time_zone::civil_lookup MakeUnique(const time_point<seconds>& tp) { 227 time_zone::civil_lookup cl; 228 cl.kind = time_zone::civil_lookup::UNIQUE; 229 cl.pre = cl.trans = cl.post = tp; 230 return cl; 231 } 232 233 inline time_zone::civil_lookup MakeUnique(std::int_fast64_t unix_time) { 234 return MakeUnique(FromUnixSeconds(unix_time)); 235 } 236 237 inline time_zone::civil_lookup MakeSkipped(const Transition& tr, 238 const civil_second& cs) { 239 time_zone::civil_lookup cl; 240 cl.kind = time_zone::civil_lookup::SKIPPED; 241 cl.pre = FromUnixSeconds(tr.unix_time - 1 + (cs - tr.prev_civil_sec)); 242 cl.trans = FromUnixSeconds(tr.unix_time); 243 cl.post = FromUnixSeconds(tr.unix_time - (tr.civil_sec - cs)); 244 return cl; 245 } 246 247 inline time_zone::civil_lookup MakeRepeated(const Transition& tr, 248 const civil_second& cs) { 249 time_zone::civil_lookup cl; 250 cl.kind = time_zone::civil_lookup::REPEATED; 251 cl.pre = FromUnixSeconds(tr.unix_time - 1 - (tr.prev_civil_sec - cs)); 252 cl.trans = FromUnixSeconds(tr.unix_time); 253 cl.post = FromUnixSeconds(tr.unix_time + (cs - tr.civil_sec)); 254 return cl; 255 } 256 257 inline civil_second YearShift(const civil_second& cs, year_t shift) { 258 return civil_second(cs.year() + shift, cs.month(), cs.day(), cs.hour(), 259 cs.minute(), cs.second()); 260 } 261 262 } // namespace 263 264 // Find/make a transition type with these attributes. 265 bool TimeZoneInfo::GetTransitionType(std::int_fast32_t utc_offset, bool is_dst, 266 const std::string& abbr, 267 std::uint_least8_t* index) { 268 std::size_t type_index = 0; 269 std::size_t abbr_index = abbreviations_.size(); 270 for (; type_index != transition_types_.size(); ++type_index) { 271 const TransitionType& tt(transition_types_[type_index]); 272 const char* tt_abbr = &abbreviations_[tt.abbr_index]; 273 if (tt_abbr == abbr) abbr_index = tt.abbr_index; 274 if (tt.utc_offset == utc_offset && tt.is_dst == is_dst) { 275 if (abbr_index == tt.abbr_index) break; // reuse 276 } 277 } 278 if (type_index > 255 || abbr_index > 255) { 279 // No index space (8 bits) available for a new type or abbreviation. 280 return false; 281 } 282 if (type_index == transition_types_.size()) { 283 TransitionType& tt(*transition_types_.emplace(transition_types_.end())); 284 tt.utc_offset = static_cast<std::int_least32_t>(utc_offset); 285 tt.is_dst = is_dst; 286 if (abbr_index == abbreviations_.size()) { 287 abbreviations_.append(abbr); 288 abbreviations_.append(1, '\0'); 289 } 290 tt.abbr_index = static_cast<std::uint_least8_t>(abbr_index); 291 } 292 *index = static_cast<std::uint_least8_t>(type_index); 293 return true; 294 } 295 296 // zic(8) can generate no-op transitions when a zone changes rules at an 297 // instant when there is actually no discontinuity. So we check whether 298 // two transitions have equivalent types (same offset/is_dst/abbr). 299 bool TimeZoneInfo::EquivTransitions(std::uint_fast8_t tt1_index, 300 std::uint_fast8_t tt2_index) const { 301 if (tt1_index == tt2_index) return true; 302 const TransitionType& tt1(transition_types_[tt1_index]); 303 const TransitionType& tt2(transition_types_[tt2_index]); 304 if (tt1.utc_offset != tt2.utc_offset) return false; 305 if (tt1.is_dst != tt2.is_dst) return false; 306 if (tt1.abbr_index != tt2.abbr_index) return false; 307 return true; 308 } 309 310 // Use the POSIX-TZ-environment-variable-style string to handle times 311 // in years after the last transition stored in the zoneinfo data. 312 bool TimeZoneInfo::ExtendTransitions() { 313 extended_ = false; 314 if (future_spec_.empty()) return true; // last transition prevails 315 316 PosixTimeZone posix; 317 if (!ParsePosixSpec(future_spec_, &posix)) return false; 318 319 // Find transition type for the future std specification. 320 std::uint_least8_t std_ti; 321 if (!GetTransitionType(posix.std_offset, false, posix.std_abbr, &std_ti)) 322 return false; 323 324 if (posix.dst_abbr.empty()) { // std only 325 // The future specification should match the last transition, and 326 // that means that handling the future will fall out naturally. 327 return EquivTransitions(transitions_.back().type_index, std_ti); 328 } 329 330 // Find transition type for the future dst specification. 331 std::uint_least8_t dst_ti; 332 if (!GetTransitionType(posix.dst_offset, true, posix.dst_abbr, &dst_ti)) 333 return false; 334 335 if (AllYearDST(posix)) { // dst only 336 // The future specification should match the last transition, and 337 // that means that handling the future will fall out naturally. 338 return EquivTransitions(transitions_.back().type_index, dst_ti); 339 } 340 341 // Extend the transitions for an additional 401 years using the future 342 // specification. Years beyond those can be handled by mapping back to 343 // a cycle-equivalent year within that range. Note that we need 401 344 // (well, at least the first transition in the 401st year) so that the 345 // end of the 400th year is mapped back to an extended year. And first 346 // we may also need two additional transitions for the current year. 347 transitions_.reserve(transitions_.size() + 2 + 401 * 2); 348 extended_ = true; 349 350 const Transition& last(transitions_.back()); 351 const std::int_fast64_t last_time = last.unix_time; 352 const TransitionType& last_tt(transition_types_[last.type_index]); 353 last_year_ = LocalTime(last_time, last_tt).cs.year(); 354 bool leap_year = IsLeap(last_year_); 355 const civil_second jan1(last_year_); 356 std::int_fast64_t jan1_time = jan1 - civil_second(); 357 int jan1_weekday = ToPosixWeekday(get_weekday(jan1)); 358 359 Transition dst = {0, dst_ti, civil_second(), civil_second()}; 360 Transition std = {0, std_ti, civil_second(), civil_second()}; 361 for (const year_t limit = last_year_ + 401;; ++last_year_) { 362 auto dst_trans_off = TransOffset(leap_year, jan1_weekday, posix.dst_start); 363 auto std_trans_off = TransOffset(leap_year, jan1_weekday, posix.dst_end); 364 dst.unix_time = jan1_time + dst_trans_off - posix.std_offset; 365 std.unix_time = jan1_time + std_trans_off - posix.dst_offset; 366 const auto* ta = dst.unix_time < std.unix_time ? &dst : &std; 367 const auto* tb = dst.unix_time < std.unix_time ? &std : &dst; 368 if (last_time < tb->unix_time) { 369 if (last_time < ta->unix_time) transitions_.push_back(*ta); 370 transitions_.push_back(*tb); 371 } 372 if (last_year_ == limit) break; 373 jan1_time += kSecsPerYear[leap_year]; 374 jan1_weekday = (jan1_weekday + kDaysPerYear[leap_year]) % 7; 375 leap_year = !leap_year && IsLeap(last_year_ + 1); 376 } 377 378 return true; 379 } 380 381 namespace { 382 383 using FilePtr = std::unique_ptr<FILE, int (*)(FILE*)>; 384 385 // fopen(3) adaptor. 386 inline FilePtr FOpen(const char* path, const char* mode) { 387 #if defined(_MSC_VER) 388 FILE* fp; 389 if (fopen_s(&fp, path, mode) != 0) fp = nullptr; 390 return FilePtr(fp, fclose); 391 #else 392 // TODO: Enable the close-on-exec flag. 393 return FilePtr(fopen(path, mode), fclose); 394 #endif 395 } 396 397 // A stdio(3)-backed implementation of ZoneInfoSource. 398 class FileZoneInfoSource : public ZoneInfoSource { 399 public: 400 static std::unique_ptr<ZoneInfoSource> Open(const std::string& name); 401 402 std::size_t Read(void* ptr, std::size_t size) override { 403 size = std::min(size, len_); 404 std::size_t nread = fread(ptr, 1, size, fp_.get()); 405 len_ -= nread; 406 return nread; 407 } 408 int Skip(std::size_t offset) override { 409 offset = std::min(offset, len_); 410 int rc = fseek(fp_.get(), static_cast<long>(offset), SEEK_CUR); 411 if (rc == 0) len_ -= offset; 412 return rc; 413 } 414 std::string Version() const override { 415 // TODO: It would nice if the zoneinfo data included the tzdb version. 416 return std::string(); 417 } 418 419 protected: 420 explicit FileZoneInfoSource( 421 FilePtr fp, std::size_t len = std::numeric_limits<std::size_t>::max()) 422 : fp_(std::move(fp)), len_(len) {} 423 424 private: 425 FilePtr fp_; 426 std::size_t len_; 427 }; 428 429 std::unique_ptr<ZoneInfoSource> FileZoneInfoSource::Open( 430 const std::string& name) { 431 // Use of the "file:" prefix is intended for testing purposes only. 432 const std::size_t pos = (name.compare(0, 5, "file:") == 0) ? 5 : 0; 433 434 // Map the time-zone name to a path name. 435 std::string path; 436 if (pos == name.size() || name[pos] != '/') { 437 const char* tzdir = "/usr/share/zoneinfo"; 438 char* tzdir_env = nullptr; 439 #if defined(_MSC_VER) 440 _dupenv_s(&tzdir_env, nullptr, "TZDIR"); 441 #else 442 tzdir_env = std::getenv("TZDIR"); 443 #endif 444 if (tzdir_env && *tzdir_env) tzdir = tzdir_env; 445 path += tzdir; 446 path += '/'; 447 #if defined(_MSC_VER) 448 free(tzdir_env); 449 #endif 450 } 451 path.append(name, pos, std::string::npos); 452 453 // Open the zoneinfo file. 454 auto fp = FOpen(path.c_str(), "rb"); 455 if (fp == nullptr) return nullptr; 456 return std::unique_ptr<ZoneInfoSource>(new FileZoneInfoSource(std::move(fp))); 457 } 458 459 class AndroidZoneInfoSource : public FileZoneInfoSource { 460 public: 461 static std::unique_ptr<ZoneInfoSource> Open(const std::string& name); 462 std::string Version() const override { return version_; } 463 464 private: 465 explicit AndroidZoneInfoSource(FilePtr fp, std::size_t len, 466 std::string version) 467 : FileZoneInfoSource(std::move(fp), len), version_(std::move(version)) {} 468 std::string version_; 469 }; 470 471 std::unique_ptr<ZoneInfoSource> AndroidZoneInfoSource::Open( 472 const std::string& name) { 473 // Use of the "file:" prefix is intended for testing purposes only. 474 const std::size_t pos = (name.compare(0, 5, "file:") == 0) ? 5 : 0; 475 476 // See Android's libc/tzcode/bionic.cpp for additional information. 477 for (const char* tzdata : {"/apex/com.android.tzdata/etc/tz/tzdata", 478 "/data/misc/zoneinfo/current/tzdata", 479 "/system/usr/share/zoneinfo/tzdata"}) { 480 auto fp = FOpen(tzdata, "rb"); 481 if (fp == nullptr) continue; 482 483 char hbuf[24]; // covers header.zonetab_offset too 484 if (fread(hbuf, 1, sizeof(hbuf), fp.get()) != sizeof(hbuf)) continue; 485 if (strncmp(hbuf, "tzdata", 6) != 0) continue; 486 const char* vers = (hbuf[11] == '\0') ? hbuf + 6 : ""; 487 const std::int_fast32_t index_offset = Decode32(hbuf + 12); 488 const std::int_fast32_t data_offset = Decode32(hbuf + 16); 489 if (index_offset < 0 || data_offset < index_offset) continue; 490 if (fseek(fp.get(), static_cast<long>(index_offset), SEEK_SET) != 0) 491 continue; 492 493 char ebuf[52]; // covers entry.unused too 494 const std::size_t index_size = 495 static_cast<std::size_t>(data_offset - index_offset); 496 const std::size_t zonecnt = index_size / sizeof(ebuf); 497 if (zonecnt * sizeof(ebuf) != index_size) continue; 498 for (std::size_t i = 0; i != zonecnt; ++i) { 499 if (fread(ebuf, 1, sizeof(ebuf), fp.get()) != sizeof(ebuf)) break; 500 const std::int_fast32_t start = data_offset + Decode32(ebuf + 40); 501 const std::int_fast32_t length = Decode32(ebuf + 44); 502 if (start < 0 || length < 0) break; 503 ebuf[40] = '\0'; // ensure zone name is NUL terminated 504 if (strcmp(name.c_str() + pos, ebuf) == 0) { 505 if (fseek(fp.get(), static_cast<long>(start), SEEK_SET) != 0) break; 506 return std::unique_ptr<ZoneInfoSource>(new AndroidZoneInfoSource( 507 std::move(fp), static_cast<std::size_t>(length), vers)); 508 } 509 } 510 } 511 512 return nullptr; 513 } 514 515 // A zoneinfo source for use inside Fuchsia components. This attempts to 516 // read zoneinfo files from one of several known paths in a component's 517 // incoming namespace. [Config data][1] is preferred, but package-specific 518 // resources are also supported. 519 // 520 // Fuchsia's implementation supports `FileZoneInfoSource::Version()`. 521 // 522 // [1]: 523 // https://fuchsia.dev/fuchsia-src/development/components/data#using_config_data_in_your_component 524 class FuchsiaZoneInfoSource : public FileZoneInfoSource { 525 public: 526 static std::unique_ptr<ZoneInfoSource> Open(const std::string& name); 527 std::string Version() const override { return version_; } 528 529 private: 530 explicit FuchsiaZoneInfoSource(FilePtr fp, std::string version) 531 : FileZoneInfoSource(std::move(fp)), version_(std::move(version)) {} 532 std::string version_; 533 }; 534 535 std::unique_ptr<ZoneInfoSource> FuchsiaZoneInfoSource::Open( 536 const std::string& name) { 537 // Use of the "file:" prefix is intended for testing purposes only. 538 const std::size_t pos = (name.compare(0, 5, "file:") == 0) ? 5 : 0; 539 540 // Prefixes where a Fuchsia component might find zoneinfo files, 541 // in descending order of preference. 542 const auto kTzdataPrefixes = { 543 // The tzdata from `config-data`. 544 "/config/data/tzdata/", 545 // The tzdata bundled in the component's package. 546 "/pkg/data/tzdata/", 547 // General data storage. 548 "/data/tzdata/", 549 // The recommended path for routed-in tzdata files. 550 // See for details: 551 // https://fuchsia.dev/fuchsia-src/concepts/process/namespaces?hl=en#typical_directory_structure 552 "/config/tzdata/", 553 }; 554 const auto kEmptyPrefix = {""}; 555 const bool name_absolute = (pos != name.size() && name[pos] == '/'); 556 const auto prefixes = name_absolute ? kEmptyPrefix : kTzdataPrefixes; 557 558 // Fuchsia builds place zoneinfo files at "<prefix><format><name>". 559 for (const std::string prefix : prefixes) { 560 std::string path = prefix; 561 if (!prefix.empty()) path += "zoneinfo/tzif2/"; // format 562 path.append(name, pos, std::string::npos); 563 564 auto fp = FOpen(path.c_str(), "rb"); 565 if (fp == nullptr) continue; 566 567 std::string version; 568 if (!prefix.empty()) { 569 // Fuchsia builds place the version in "<prefix>revision.txt". 570 std::ifstream version_stream(prefix + "revision.txt"); 571 if (version_stream.is_open()) { 572 // revision.txt should contain no newlines, but to be 573 // defensive we read just the first line. 574 std::getline(version_stream, version); 575 } 576 } 577 578 return std::unique_ptr<ZoneInfoSource>( 579 new FuchsiaZoneInfoSource(std::move(fp), std::move(version))); 580 } 581 582 return nullptr; 583 } 584 585 } // namespace 586 587 // What (no leap-seconds) UTC+seconds zoneinfo would look like. 588 bool TimeZoneInfo::ResetToBuiltinUTC(const seconds& offset) { 589 transition_types_.resize(1); 590 TransitionType& tt(transition_types_.back()); 591 tt.utc_offset = static_cast<std::int_least32_t>(offset.count()); 592 tt.is_dst = false; 593 tt.abbr_index = 0; 594 595 // We temporarily add some redundant, contemporary (2015 through 2025) 596 // transitions for performance reasons. See TimeZoneInfo::LocalTime(). 597 // TODO: Fix the performance issue and remove the extra transitions. 598 transitions_.clear(); 599 transitions_.reserve(12); 600 for (const std::int_fast64_t unix_time : { 601 -(1LL << 59), // a "first half" transition 602 1420070400LL, // 2015-01-01T00:00:00+00:00 603 1451606400LL, // 2016-01-01T00:00:00+00:00 604 1483228800LL, // 2017-01-01T00:00:00+00:00 605 1514764800LL, // 2018-01-01T00:00:00+00:00 606 1546300800LL, // 2019-01-01T00:00:00+00:00 607 1577836800LL, // 2020-01-01T00:00:00+00:00 608 1609459200LL, // 2021-01-01T00:00:00+00:00 609 1640995200LL, // 2022-01-01T00:00:00+00:00 610 1672531200LL, // 2023-01-01T00:00:00+00:00 611 1704067200LL, // 2024-01-01T00:00:00+00:00 612 1735689600LL, // 2025-01-01T00:00:00+00:00 613 }) { 614 Transition& tr(*transitions_.emplace(transitions_.end())); 615 tr.unix_time = unix_time; 616 tr.type_index = 0; 617 tr.civil_sec = LocalTime(tr.unix_time, tt).cs; 618 tr.prev_civil_sec = tr.civil_sec - 1; 619 } 620 621 default_transition_type_ = 0; 622 abbreviations_ = FixedOffsetToAbbr(offset); 623 abbreviations_.append(1, '\0'); 624 future_spec_.clear(); // never needed for a fixed-offset zone 625 extended_ = false; 626 627 tt.civil_max = LocalTime(seconds::max().count(), tt).cs; 628 tt.civil_min = LocalTime(seconds::min().count(), tt).cs; 629 630 transitions_.shrink_to_fit(); 631 return true; 632 } 633 634 bool TimeZoneInfo::Load(ZoneInfoSource* zip) { 635 // Read and validate the header. 636 tzhead tzh; 637 if (zip->Read(&tzh, sizeof(tzh)) != sizeof(tzh)) return false; 638 if (strncmp(tzh.tzh_magic, TZ_MAGIC, sizeof(tzh.tzh_magic)) != 0) 639 return false; 640 Header hdr; 641 if (!hdr.Build(tzh)) return false; 642 std::size_t time_len = 4; 643 if (tzh.tzh_version[0] != '\0') { 644 // Skip the 4-byte data. 645 if (zip->Skip(hdr.DataLength(time_len)) != 0) return false; 646 // Read and validate the header for the 8-byte data. 647 if (zip->Read(&tzh, sizeof(tzh)) != sizeof(tzh)) return false; 648 if (strncmp(tzh.tzh_magic, TZ_MAGIC, sizeof(tzh.tzh_magic)) != 0) 649 return false; 650 if (tzh.tzh_version[0] == '\0') return false; 651 if (!hdr.Build(tzh)) return false; 652 time_len = 8; 653 } 654 if (hdr.typecnt == 0) return false; 655 if (hdr.leapcnt != 0) { 656 // This code assumes 60-second minutes so we do not want 657 // the leap-second encoded zoneinfo. We could reverse the 658 // compensation, but the "right" encoding is rarely used 659 // so currently we simply reject such data. 660 return false; 661 } 662 if (hdr.ttisstdcnt != 0 && hdr.ttisstdcnt != hdr.typecnt) return false; 663 if (hdr.ttisutcnt != 0 && hdr.ttisutcnt != hdr.typecnt) return false; 664 665 // Read the data into a local buffer. 666 std::size_t len = hdr.DataLength(time_len); 667 std::vector<char> tbuf(len); 668 if (zip->Read(tbuf.data(), len) != len) return false; 669 const char* bp = tbuf.data(); 670 671 // Decode and validate the transitions. 672 transitions_.reserve(hdr.timecnt + 2); 673 transitions_.resize(hdr.timecnt); 674 for (std::size_t i = 0; i != hdr.timecnt; ++i) { 675 transitions_[i].unix_time = (time_len == 4) ? Decode32(bp) : Decode64(bp); 676 bp += time_len; 677 if (i != 0) { 678 // Check that the transitions are ordered by time (as zic guarantees). 679 if (!Transition::ByUnixTime()(transitions_[i - 1], transitions_[i])) 680 return false; // out of order 681 } 682 } 683 bool seen_type_0 = false; 684 for (std::size_t i = 0; i != hdr.timecnt; ++i) { 685 transitions_[i].type_index = Decode8(bp++); 686 if (transitions_[i].type_index >= hdr.typecnt) return false; 687 if (transitions_[i].type_index == 0) seen_type_0 = true; 688 } 689 690 // Decode and validate the transition types. 691 transition_types_.reserve(hdr.typecnt + 2); 692 transition_types_.resize(hdr.typecnt); 693 for (std::size_t i = 0; i != hdr.typecnt; ++i) { 694 transition_types_[i].utc_offset = 695 static_cast<std::int_least32_t>(Decode32(bp)); 696 if (transition_types_[i].utc_offset >= kSecsPerDay || 697 transition_types_[i].utc_offset <= -kSecsPerDay) 698 return false; 699 bp += 4; 700 transition_types_[i].is_dst = (Decode8(bp++) != 0); 701 transition_types_[i].abbr_index = Decode8(bp++); 702 if (transition_types_[i].abbr_index >= hdr.charcnt) return false; 703 } 704 705 // Determine the before-first-transition type. 706 default_transition_type_ = 0; 707 if (seen_type_0 && hdr.timecnt != 0) { 708 std::uint_fast8_t index = 0; 709 if (transition_types_[0].is_dst) { 710 index = transitions_[0].type_index; 711 while (index != 0 && transition_types_[index].is_dst) --index; 712 } 713 while (index != hdr.typecnt && transition_types_[index].is_dst) ++index; 714 if (index != hdr.typecnt) default_transition_type_ = index; 715 } 716 717 // Copy all the abbreviations. 718 abbreviations_.reserve(hdr.charcnt + 10); 719 abbreviations_.assign(bp, hdr.charcnt); 720 bp += hdr.charcnt; 721 722 // Skip the unused portions. We've already dispensed with leap-second 723 // encoded zoneinfo. The ttisstd/ttisgmt indicators only apply when 724 // interpreting a POSIX spec that does not include start/end rules, and 725 // that isn't the case here (see "zic -p"). 726 bp += (time_len + 4) * hdr.leapcnt; // leap-time + TAI-UTC 727 bp += 1 * hdr.ttisstdcnt; // UTC/local indicators 728 bp += 1 * hdr.ttisutcnt; // standard/wall indicators 729 assert(bp == tbuf.data() + tbuf.size()); 730 731 future_spec_.clear(); 732 if (tzh.tzh_version[0] != '\0') { 733 // Snarf up the NL-enclosed future POSIX spec. Note 734 // that version '3' files utilize an extended format. 735 auto get_char = [](ZoneInfoSource* azip) -> int { 736 unsigned char ch; // all non-EOF results are positive 737 return (azip->Read(&ch, 1) == 1) ? ch : EOF; 738 }; 739 if (get_char(zip) != '\n') return false; 740 for (int c = get_char(zip); c != '\n'; c = get_char(zip)) { 741 if (c == EOF) return false; 742 future_spec_.push_back(static_cast<char>(c)); 743 } 744 } 745 746 // We don't check for EOF so that we're forwards compatible. 747 748 // If we did not find version information during the standard loading 749 // process (as of tzh_version '3' that is unsupported), then ask the 750 // ZoneInfoSource for any out-of-bound version string it may be privy to. 751 if (version_.empty()) { 752 version_ = zip->Version(); 753 } 754 755 // Ensure that there is always a transition in the first half of the 756 // time line (the second half is handled below) so that the signed 757 // difference between a civil_second and the civil_second of its 758 // previous transition is always representable, without overflow. 759 if (transitions_.empty() || transitions_.front().unix_time >= 0) { 760 Transition& tr(*transitions_.emplace(transitions_.begin())); 761 tr.unix_time = -(1LL << 59); // -18267312070-10-26T17:01:52+00:00 762 tr.type_index = default_transition_type_; 763 } 764 765 // Extend the transitions using the future specification. 766 if (!ExtendTransitions()) return false; 767 768 // Ensure that there is always a transition in the second half of the 769 // time line (the first half is handled above) so that the signed 770 // difference between a civil_second and the civil_second of its 771 // previous transition is always representable, without overflow. 772 const Transition& last(transitions_.back()); 773 if (last.unix_time < 0) { 774 const std::uint_fast8_t type_index = last.type_index; 775 Transition& tr(*transitions_.emplace(transitions_.end())); 776 tr.unix_time = 2147483647; // 2038-01-19T03:14:07+00:00 777 tr.type_index = type_index; 778 } 779 780 // Compute the local civil time for each transition and the preceding 781 // second. These will be used for reverse conversions in MakeTime(). 782 const TransitionType* ttp = &transition_types_[default_transition_type_]; 783 for (std::size_t i = 0; i != transitions_.size(); ++i) { 784 Transition& tr(transitions_[i]); 785 tr.prev_civil_sec = LocalTime(tr.unix_time, *ttp).cs - 1; 786 ttp = &transition_types_[tr.type_index]; 787 tr.civil_sec = LocalTime(tr.unix_time, *ttp).cs; 788 if (i != 0) { 789 // Check that the transitions are ordered by civil time. Essentially 790 // this means that an offset change cannot cross another such change. 791 // No one does this in practice, and we depend on it in MakeTime(). 792 if (!Transition::ByCivilTime()(transitions_[i - 1], tr)) 793 return false; // out of order 794 } 795 } 796 797 // Compute the maximum/minimum civil times that can be converted to a 798 // time_point<seconds> for each of the zone's transition types. 799 for (auto& tt : transition_types_) { 800 tt.civil_max = LocalTime(seconds::max().count(), tt).cs; 801 tt.civil_min = LocalTime(seconds::min().count(), tt).cs; 802 } 803 804 transitions_.shrink_to_fit(); 805 return true; 806 } 807 808 bool TimeZoneInfo::Load(const std::string& name) { 809 // We can ensure that the loading of UTC or any other fixed-offset 810 // zone never fails because the simple, fixed-offset state can be 811 // internally generated. Note that this depends on our choice to not 812 // accept leap-second encoded ("right") zoneinfo. 813 auto offset = seconds::zero(); 814 if (FixedOffsetFromName(name, &offset)) { 815 return ResetToBuiltinUTC(offset); 816 } 817 818 // Find and use a ZoneInfoSource to load the named zone. 819 auto zip = cctz_extension::zone_info_source_factory( 820 name, [](const std::string& n) -> std::unique_ptr<ZoneInfoSource> { 821 if (auto z = FileZoneInfoSource::Open(n)) return z; 822 if (auto z = AndroidZoneInfoSource::Open(n)) return z; 823 if (auto z = FuchsiaZoneInfoSource::Open(n)) return z; 824 return nullptr; 825 }); 826 return zip != nullptr && Load(zip.get()); 827 } 828 829 std::unique_ptr<TimeZoneInfo> TimeZoneInfo::UTC() { 830 auto tz = std::unique_ptr<TimeZoneInfo>(new TimeZoneInfo); 831 tz->ResetToBuiltinUTC(seconds::zero()); 832 return tz; 833 } 834 835 std::unique_ptr<TimeZoneInfo> TimeZoneInfo::Make(const std::string& name) { 836 auto tz = std::unique_ptr<TimeZoneInfo>(new TimeZoneInfo); 837 if (!tz->Load(name)) tz.reset(); // fallback to UTC 838 return tz; 839 } 840 841 // BreakTime() translation for a particular transition type. 842 time_zone::absolute_lookup TimeZoneInfo::LocalTime( 843 std::int_fast64_t unix_time, const TransitionType& tt) const { 844 // A civil time in "+offset" looks like (time+offset) in UTC. 845 // Note: We perform two additions in the civil_second domain to 846 // sidestep the chance of overflow in (unix_time + tt.utc_offset). 847 return {(civil_second() + unix_time) + tt.utc_offset, tt.utc_offset, 848 tt.is_dst, &abbreviations_[tt.abbr_index]}; 849 } 850 851 // BreakTime() translation for a particular transition. 852 time_zone::absolute_lookup TimeZoneInfo::LocalTime(std::int_fast64_t unix_time, 853 const Transition& tr) const { 854 const TransitionType& tt = transition_types_[tr.type_index]; 855 // Note: (unix_time - tr.unix_time) will never overflow as we 856 // have ensured that there is always a "nearby" transition. 857 return {tr.civil_sec + (unix_time - tr.unix_time), // TODO: Optimize. 858 tt.utc_offset, tt.is_dst, &abbreviations_[tt.abbr_index]}; 859 } 860 861 // MakeTime() translation with a conversion-preserving +N * 400-year shift. 862 time_zone::civil_lookup TimeZoneInfo::TimeLocal(const civil_second& cs, 863 year_t c4_shift) const { 864 assert(last_year_ - 400 < cs.year() && cs.year() <= last_year_); 865 time_zone::civil_lookup cl = MakeTime(cs); 866 if (c4_shift > seconds::max().count() / kSecsPer400Years) { 867 cl.pre = cl.trans = cl.post = time_point<seconds>::max(); 868 } else { 869 const auto offset = seconds(c4_shift * kSecsPer400Years); 870 const auto limit = time_point<seconds>::max() - offset; 871 for (auto* tp : {&cl.pre, &cl.trans, &cl.post}) { 872 if (*tp > limit) { 873 *tp = time_point<seconds>::max(); 874 } else { 875 *tp += offset; 876 } 877 } 878 } 879 return cl; 880 } 881 882 time_zone::absolute_lookup TimeZoneInfo::BreakTime( 883 const time_point<seconds>& tp) const { 884 std::int_fast64_t unix_time = ToUnixSeconds(tp); 885 const std::size_t timecnt = transitions_.size(); 886 assert(timecnt != 0); // We always add a transition. 887 888 if (unix_time < transitions_[0].unix_time) { 889 return LocalTime(unix_time, transition_types_[default_transition_type_]); 890 } 891 if (unix_time >= transitions_[timecnt - 1].unix_time) { 892 // After the last transition. If we extended the transitions using 893 // future_spec_, shift back to a supported year using the 400-year 894 // cycle of calendaric equivalence and then compensate accordingly. 895 if (extended_) { 896 const std::int_fast64_t diff = 897 unix_time - transitions_[timecnt - 1].unix_time; 898 const year_t shift = diff / kSecsPer400Years + 1; 899 const auto d = seconds(shift * kSecsPer400Years); 900 time_zone::absolute_lookup al = BreakTime(tp - d); 901 al.cs = YearShift(al.cs, shift * 400); 902 return al; 903 } 904 return LocalTime(unix_time, transitions_[timecnt - 1]); 905 } 906 907 const std::size_t hint = local_time_hint_.load(std::memory_order_relaxed); 908 if (0 < hint && hint < timecnt) { 909 if (transitions_[hint - 1].unix_time <= unix_time) { 910 if (unix_time < transitions_[hint].unix_time) { 911 return LocalTime(unix_time, transitions_[hint - 1]); 912 } 913 } 914 } 915 916 const Transition target = {unix_time, 0, civil_second(), civil_second()}; 917 const Transition* begin = &transitions_[0]; 918 const Transition* tr = std::upper_bound(begin, begin + timecnt, target, 919 Transition::ByUnixTime()); 920 local_time_hint_.store(static_cast<std::size_t>(tr - begin), 921 std::memory_order_relaxed); 922 return LocalTime(unix_time, *--tr); 923 } 924 925 time_zone::civil_lookup TimeZoneInfo::MakeTime(const civil_second& cs) const { 926 const std::size_t timecnt = transitions_.size(); 927 assert(timecnt != 0); // We always add a transition. 928 929 // Find the first transition after our target civil time. 930 const Transition* tr = nullptr; 931 const Transition* begin = &transitions_[0]; 932 const Transition* end = begin + timecnt; 933 if (cs < begin->civil_sec) { 934 tr = begin; 935 } else if (cs >= transitions_[timecnt - 1].civil_sec) { 936 tr = end; 937 } else { 938 const std::size_t hint = time_local_hint_.load(std::memory_order_relaxed); 939 if (0 < hint && hint < timecnt) { 940 if (transitions_[hint - 1].civil_sec <= cs) { 941 if (cs < transitions_[hint].civil_sec) { 942 tr = begin + hint; 943 } 944 } 945 } 946 if (tr == nullptr) { 947 const Transition target = {0, 0, cs, civil_second()}; 948 tr = std::upper_bound(begin, end, target, Transition::ByCivilTime()); 949 time_local_hint_.store(static_cast<std::size_t>(tr - begin), 950 std::memory_order_relaxed); 951 } 952 } 953 954 if (tr == begin) { 955 if (tr->prev_civil_sec >= cs) { 956 // Before first transition, so use the default offset. 957 const TransitionType& tt(transition_types_[default_transition_type_]); 958 if (cs < tt.civil_min) return MakeUnique(time_point<seconds>::min()); 959 return MakeUnique(cs - (civil_second() + tt.utc_offset)); 960 } 961 // tr->prev_civil_sec < cs < tr->civil_sec 962 return MakeSkipped(*tr, cs); 963 } 964 965 if (tr == end) { 966 if (cs > (--tr)->prev_civil_sec) { 967 // After the last transition. If we extended the transitions using 968 // future_spec_, shift back to a supported year using the 400-year 969 // cycle of calendaric equivalence and then compensate accordingly. 970 if (extended_ && cs.year() > last_year_) { 971 const year_t shift = (cs.year() - last_year_ - 1) / 400 + 1; 972 return TimeLocal(YearShift(cs, shift * -400), shift); 973 } 974 const TransitionType& tt(transition_types_[tr->type_index]); 975 if (cs > tt.civil_max) return MakeUnique(time_point<seconds>::max()); 976 return MakeUnique(tr->unix_time + (cs - tr->civil_sec)); 977 } 978 // tr->civil_sec <= cs <= tr->prev_civil_sec 979 return MakeRepeated(*tr, cs); 980 } 981 982 if (tr->prev_civil_sec < cs) { 983 // tr->prev_civil_sec < cs < tr->civil_sec 984 return MakeSkipped(*tr, cs); 985 } 986 987 if (cs <= (--tr)->prev_civil_sec) { 988 // tr->civil_sec <= cs <= tr->prev_civil_sec 989 return MakeRepeated(*tr, cs); 990 } 991 992 // In between transitions. 993 return MakeUnique(tr->unix_time + (cs - tr->civil_sec)); 994 } 995 996 std::string TimeZoneInfo::Version() const { return version_; } 997 998 std::string TimeZoneInfo::Description() const { 999 std::ostringstream oss; 1000 oss << "#trans=" << transitions_.size(); 1001 oss << " #types=" << transition_types_.size(); 1002 oss << " spec='" << future_spec_ << "'"; 1003 return oss.str(); 1004 } 1005 1006 bool TimeZoneInfo::NextTransition(const time_point<seconds>& tp, 1007 time_zone::civil_transition* trans) const { 1008 if (transitions_.empty()) return false; 1009 const Transition* begin = &transitions_[0]; 1010 const Transition* end = begin + transitions_.size(); 1011 if (begin->unix_time <= -(1LL << 59)) { 1012 // Do not report the BIG_BANG found in some zoneinfo data as it is 1013 // really a sentinel, not a transition. See pre-2018f tz/zic.c. 1014 ++begin; 1015 } 1016 std::int_fast64_t unix_time = ToUnixSeconds(tp); 1017 const Transition target = {unix_time, 0, civil_second(), civil_second()}; 1018 const Transition* tr = 1019 std::upper_bound(begin, end, target, Transition::ByUnixTime()); 1020 for (; tr != end; ++tr) { // skip no-op transitions 1021 std::uint_fast8_t prev_type_index = 1022 (tr == begin) ? default_transition_type_ : tr[-1].type_index; 1023 if (!EquivTransitions(prev_type_index, tr[0].type_index)) break; 1024 } 1025 // When tr == end we return false, ignoring future_spec_. 1026 if (tr == end) return false; 1027 trans->from = tr->prev_civil_sec + 1; 1028 trans->to = tr->civil_sec; 1029 return true; 1030 } 1031 1032 bool TimeZoneInfo::PrevTransition(const time_point<seconds>& tp, 1033 time_zone::civil_transition* trans) const { 1034 if (transitions_.empty()) return false; 1035 const Transition* begin = &transitions_[0]; 1036 const Transition* end = begin + transitions_.size(); 1037 if (begin->unix_time <= -(1LL << 59)) { 1038 // Do not report the BIG_BANG found in some zoneinfo data as it is 1039 // really a sentinel, not a transition. See pre-2018f tz/zic.c. 1040 ++begin; 1041 } 1042 std::int_fast64_t unix_time = ToUnixSeconds(tp); 1043 if (FromUnixSeconds(unix_time) != tp) { 1044 if (unix_time == std::numeric_limits<std::int_fast64_t>::max()) { 1045 if (end == begin) return false; // Ignore future_spec_. 1046 trans->from = (--end)->prev_civil_sec + 1; 1047 trans->to = end->civil_sec; 1048 return true; 1049 } 1050 unix_time += 1; // ceils 1051 } 1052 const Transition target = {unix_time, 0, civil_second(), civil_second()}; 1053 const Transition* tr = 1054 std::lower_bound(begin, end, target, Transition::ByUnixTime()); 1055 for (; tr != begin; --tr) { // skip no-op transitions 1056 std::uint_fast8_t prev_type_index = 1057 (tr - 1 == begin) ? default_transition_type_ : tr[-2].type_index; 1058 if (!EquivTransitions(prev_type_index, tr[-1].type_index)) break; 1059 } 1060 // When tr == end we return the "last" transition, ignoring future_spec_. 1061 if (tr == begin) return false; 1062 trans->from = (--tr)->prev_civil_sec + 1; 1063 trans->to = tr->civil_sec; 1064 return true; 1065 } 1066 1067 } // namespace cctz 1068 } // namespace time_internal 1069 ABSL_NAMESPACE_END 1070 } // namespace absl