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