PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
localtime.c
Go to the documentation of this file.
1 /*
2  * This file is in the public domain, so clarified as of
3  * 1996-06-05 by Arthur David Olson.
4  *
5  * IDENTIFICATION
6  * src/timezone/localtime.c
7  */
8 
9 /*
10  * Leap second handling from Bradley White.
11  * POSIX-style TZ environment variable handling from Guy Harris.
12  */
13 
14 /* this file needs to build in both frontend and backend contexts */
15 #include "c.h"
16 
17 #include <fcntl.h>
18 
19 #include "datatype/timestamp.h"
20 #include "pgtz.h"
21 
22 #include "private.h"
23 #include "tzfile.h"
24 
25 
26 #ifndef WILDABBR
27 /*
28  * Someone might make incorrect use of a time zone abbreviation:
29  * 1. They might reference tzname[0] before calling tzset (explicitly
30  * or implicitly).
31  * 2. They might reference tzname[1] before calling tzset (explicitly
32  * or implicitly).
33  * 3. They might reference tzname[1] after setting to a time zone
34  * in which Daylight Saving Time is never observed.
35  * 4. They might reference tzname[0] after setting to a time zone
36  * in which Standard Time is never observed.
37  * 5. They might reference tm.TM_ZONE after calling offtime.
38  * What's best to do in the above cases is open to debate;
39  * for now, we just set things up so that in any of the five cases
40  * WILDABBR is used. Another possibility: initialize tzname[0] to the
41  * string "tzname[0] used before set", and similarly for the other cases.
42  * And another: initialize tzname[0] to "ERA", with an explanation in the
43  * manual page of what this "time zone abbreviation" means (doing this so
44  * that tzname[0] has the "normal" length of three characters).
45  */
46 #define WILDABBR " "
47 #endif /* !defined WILDABBR */
48 
49 static const char wildabbr[] = WILDABBR;
50 
51 static const char gmt[] = "GMT";
52 
53 /* The minimum and maximum finite time values. This assumes no padding. */
56 
57 /*
58  * The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
59  * We default to US rules as of 1999-08-17.
60  * POSIX 1003.1 section 8.1.1 says that the default DST rules are
61  * implementation dependent; for historical reasons, US rules are a
62  * common default.
63  */
64 #define TZDEFRULESTRING ",M4.1.0,M10.5.0"
65 
66 /* structs ttinfo, lsinfo, state have been moved to pgtz.h */
67 
68 enum r_type
69 {
70  JULIAN_DAY, /* Jn = Julian day */
71  DAY_OF_YEAR, /* n = day of year */
72  MONTH_NTH_DAY_OF_WEEK /* Mm.n.d = month, week, day of week */
73 };
74 
75 struct rule
76 {
77  enum r_type r_type; /* type of rule */
78  int r_day; /* day number of rule */
79  int r_week; /* week number of rule */
80  int r_mon; /* month number of rule */
81  int32 r_time; /* transition time of rule */
82 };
83 
84 /*
85  * Prototypes for static functions.
86  */
87 
88 static struct pg_tm *gmtsub(pg_time_t const *, int32, struct pg_tm *);
89 static bool increment_overflow(int *, int);
91 static struct pg_tm *timesub(pg_time_t const *, int32, struct state const *,
92  struct pg_tm *);
93 static bool typesequiv(struct state const *, int, int);
94 
95 
96 /*
97  * Section 4.12.3 of X3.159-1989 requires that
98  * Except for the strftime function, these functions [asctime,
99  * ctime, gmtime, localtime] return values in one of two static
100  * objects: a broken-down time structure and an array of char.
101  * Thanks to Paul Eggert for noting this.
102  */
103 
104 static struct pg_tm tm;
105 
106 /* Initialize *S to a value based on GMTOFF, ISDST, and ABBRIND. */
107 static void
108 init_ttinfo(struct ttinfo * s, int32 gmtoff, bool isdst, int abbrind)
109 {
110  s->tt_gmtoff = gmtoff;
111  s->tt_isdst = isdst;
112  s->tt_abbrind = abbrind;
113  s->tt_ttisstd = false;
114  s->tt_ttisgmt = false;
115 }
116 
117 static int32
118 detzcode(const char *codep)
119 {
120  int32 result;
121  int i;
122  int32 one = 1;
123  int32 halfmaxval = one << (32 - 2);
124  int32 maxval = halfmaxval - 1 + halfmaxval;
125  int32 minval = -1 - maxval;
126 
127  result = codep[0] & 0x7f;
128  for (i = 1; i < 4; ++i)
129  result = (result << 8) | (codep[i] & 0xff);
130 
131  if (codep[0] & 0x80)
132  {
133  /*
134  * Do two's-complement negation even on non-two's-complement machines.
135  * If the result would be minval - 1, return minval.
136  */
137  result -= !TWOS_COMPLEMENT(int32) &&result != 0;
138  result += minval;
139  }
140  return result;
141 }
142 
143 static int64
144 detzcode64(const char *codep)
145 {
146  uint64 result;
147  int i;
148  int64 one = 1;
149  int64 halfmaxval = one << (64 - 2);
150  int64 maxval = halfmaxval - 1 + halfmaxval;
151  int64 minval = -TWOS_COMPLEMENT(int64) -maxval;
152 
153  result = codep[0] & 0x7f;
154  for (i = 1; i < 8; ++i)
155  result = (result << 8) | (codep[i] & 0xff);
156 
157  if (codep[0] & 0x80)
158  {
159  /*
160  * Do two's-complement negation even on non-two's-complement machines.
161  * If the result would be minval - 1, return minval.
162  */
163  result -= !TWOS_COMPLEMENT(int64) &&result != 0;
164  result += minval;
165  }
166  return result;
167 }
168 
169 static bool
171 {
173  return 0;
174  return t1 - t0 == SECSPERREPEAT;
175 }
176 
177 /* Input buffer for data read from a compiled tz file. */
179 {
180  /* The first part of the buffer, interpreted as a header. */
181  struct tzhead tzhead;
182 
183  /* The entire buffer. */
184  char buf[2 * sizeof(struct tzhead) + 2 * sizeof(struct state)
185  + 4 * TZ_MAX_TIMES];
186 };
187 
188 /* Local storage needed for 'tzloadbody'. */
190 {
191  /* We don't need the "fullname" member */
192 
193  /* The results of analyzing the file's contents after it is opened. */
194  struct
195  {
196  /* The input buffer. */
198 
199  /* A temporary state used for parsing a TZ string in the file. */
200  struct state st;
201  } u;
202 };
203 
204 /* Load tz data from the file named NAME into *SP. Read extended
205  * format if DOEXTEND. Use *LSP for temporary storage. Return 0 on
206  * success, an errno value on failure.
207  * PG: If "canonname" is not NULL, then on success the canonical spelling of
208  * given name is stored there (the buffer must be > TZ_STRLEN_MAX bytes!).
209  */
210 static int
211 tzloadbody(char const * name, char *canonname, struct state * sp, bool doextend,
212  union local_storage * lsp)
213 {
214  int i;
215  int fid;
216  int stored;
217  ssize_t nread;
218  union input_buffer *up = &lsp->u.u;
219  int tzheadsize = sizeof(struct tzhead);
220 
221  sp->goback = sp->goahead = false;
222 
223  if (!name)
224  {
225  name = TZDEFAULT;
226  if (!name)
227  return EINVAL;
228  }
229 
230  if (name[0] == ':')
231  ++name;
232 
233  fid = pg_open_tzfile(name, canonname);
234  if (fid < 0)
235  return ENOENT; /* pg_open_tzfile may not set errno */
236 
237  nread = read(fid, up->buf, sizeof up->buf);
238  if (nread < tzheadsize)
239  {
240  int err = nread < 0 ? errno : EINVAL;
241 
242  close(fid);
243  return err;
244  }
245  if (close(fid) < 0)
246  return errno;
247  for (stored = 4; stored <= 8; stored *= 2)
248  {
249  int32 ttisstdcnt = detzcode(up->tzhead.tzh_ttisstdcnt);
250  int32 ttisgmtcnt = detzcode(up->tzhead.tzh_ttisgmtcnt);
255  char const *p = up->buf + tzheadsize;
256 
257  if (!(0 <= leapcnt && leapcnt < TZ_MAX_LEAPS
258  && 0 < typecnt && typecnt < TZ_MAX_TYPES
259  && 0 <= timecnt && timecnt < TZ_MAX_TIMES
260  && 0 <= charcnt && charcnt < TZ_MAX_CHARS
261  && (ttisstdcnt == typecnt || ttisstdcnt == 0)
262  && (ttisgmtcnt == typecnt || ttisgmtcnt == 0)))
263  return EINVAL;
264  if (nread
265  < (tzheadsize /* struct tzhead */
266  + timecnt * stored /* ats */
267  + timecnt /* types */
268  + typecnt * 6 /* ttinfos */
269  + charcnt /* chars */
270  + leapcnt * (stored + 4) /* lsinfos */
271  + ttisstdcnt /* ttisstds */
272  + ttisgmtcnt)) /* ttisgmts */
273  return EINVAL;
274  sp->leapcnt = leapcnt;
275  sp->timecnt = timecnt;
276  sp->typecnt = typecnt;
277  sp->charcnt = charcnt;
278 
279  /*
280  * Read transitions, discarding those out of pg_time_t range. But
281  * pretend the last transition before time_t_min occurred at
282  * time_t_min.
283  */
284  timecnt = 0;
285  for (i = 0; i < sp->timecnt; ++i)
286  {
287  int64 at
288  = stored == 4 ? detzcode(p) : detzcode64(p);
289 
290  sp->types[i] = at <= time_t_max;
291  if (sp->types[i])
292  {
293  pg_time_t attime
294  = ((TYPE_SIGNED(pg_time_t) ? at < time_t_min : at < 0)
295  ? time_t_min : at);
296 
297  if (timecnt && attime <= sp->ats[timecnt - 1])
298  {
299  if (attime < sp->ats[timecnt - 1])
300  return EINVAL;
301  sp->types[i - 1] = 0;
302  timecnt--;
303  }
304  sp->ats[timecnt++] = attime;
305  }
306  p += stored;
307  }
308 
309  timecnt = 0;
310  for (i = 0; i < sp->timecnt; ++i)
311  {
312  unsigned char typ = *p++;
313 
314  if (sp->typecnt <= typ)
315  return EINVAL;
316  if (sp->types[i])
317  sp->types[timecnt++] = typ;
318  }
319  sp->timecnt = timecnt;
320  for (i = 0; i < sp->typecnt; ++i)
321  {
322  struct ttinfo *ttisp;
323  unsigned char isdst,
324  abbrind;
325 
326  ttisp = &sp->ttis[i];
327  ttisp->tt_gmtoff = detzcode(p);
328  p += 4;
329  isdst = *p++;
330  if (!(isdst < 2))
331  return EINVAL;
332  ttisp->tt_isdst = isdst;
333  abbrind = *p++;
334  if (!(abbrind < sp->charcnt))
335  return EINVAL;
336  ttisp->tt_abbrind = abbrind;
337  }
338  for (i = 0; i < sp->charcnt; ++i)
339  sp->chars[i] = *p++;
340  sp->chars[i] = '\0'; /* ensure '\0' at end */
341 
342  /* Read leap seconds, discarding those out of pg_time_t range. */
343  leapcnt = 0;
344  for (i = 0; i < sp->leapcnt; ++i)
345  {
346  int64 tr = stored == 4 ? detzcode(p) : detzcode64(p);
347  int32 corr = detzcode(p + stored);
348 
349  p += stored + 4;
350  if (tr <= time_t_max)
351  {
353  = ((TYPE_SIGNED(pg_time_t) ? tr < time_t_min : tr < 0)
354  ? time_t_min : tr);
355 
356  if (leapcnt && trans <= sp->lsis[leapcnt - 1].ls_trans)
357  {
358  if (trans < sp->lsis[leapcnt - 1].ls_trans)
359  return EINVAL;
360  leapcnt--;
361  }
362  sp->lsis[leapcnt].ls_trans = trans;
363  sp->lsis[leapcnt].ls_corr = corr;
364  leapcnt++;
365  }
366  }
367  sp->leapcnt = leapcnt;
368 
369  for (i = 0; i < sp->typecnt; ++i)
370  {
371  struct ttinfo *ttisp;
372 
373  ttisp = &sp->ttis[i];
374  if (ttisstdcnt == 0)
375  ttisp->tt_ttisstd = false;
376  else
377  {
378  if (*p != true && *p != false)
379  return EINVAL;
380  ttisp->tt_ttisstd = *p++;
381  }
382  }
383  for (i = 0; i < sp->typecnt; ++i)
384  {
385  struct ttinfo *ttisp;
386 
387  ttisp = &sp->ttis[i];
388  if (ttisgmtcnt == 0)
389  ttisp->tt_ttisgmt = false;
390  else
391  {
392  if (*p != true && *p != false)
393  return EINVAL;
394  ttisp->tt_ttisgmt = *p++;
395  }
396  }
397 
398  /*
399  * If this is an old file, we're done.
400  */
401  if (up->tzhead.tzh_version[0] == '\0')
402  break;
403  nread -= p - up->buf;
404  memmove(up->buf, p, nread);
405  }
406  if (doextend && nread > 2 &&
407  up->buf[0] == '\n' && up->buf[nread - 1] == '\n' &&
408  sp->typecnt + 2 <= TZ_MAX_TYPES)
409  {
410  struct state *ts = &lsp->u.st;
411 
412  up->buf[nread - 1] = '\0';
413  if (tzparse(&up->buf[1], ts, false)
414  && ts->typecnt == 2)
415  {
416  /*
417  * Attempt to reuse existing abbreviations. Without this,
418  * America/Anchorage would be right on the edge after 2037 when
419  * TZ_MAX_CHARS is 50, as sp->charcnt equals 40 (for LMT AST AWT
420  * APT AHST AHDT YST AKDT AKST) and ts->charcnt equals 10 (for
421  * AKST AKDT). Reusing means sp->charcnt can stay 40 in this
422  * example.
423  */
424  int gotabbr = 0;
425  int charcnt = sp->charcnt;
426 
427  for (i = 0; i < 2; i++)
428  {
429  char *tsabbr = ts->chars + ts->ttis[i].tt_abbrind;
430  int j;
431 
432  for (j = 0; j < charcnt; j++)
433  if (strcmp(sp->chars + j, tsabbr) == 0)
434  {
435  ts->ttis[i].tt_abbrind = j;
436  gotabbr++;
437  break;
438  }
439  if (!(j < charcnt))
440  {
441  int tsabbrlen = strlen(tsabbr);
442 
443  if (j + tsabbrlen < TZ_MAX_CHARS)
444  {
445  strcpy(sp->chars + j, tsabbr);
446  charcnt = j + tsabbrlen + 1;
447  ts->ttis[i].tt_abbrind = j;
448  gotabbr++;
449  }
450  }
451  }
452  if (gotabbr == 2)
453  {
454  sp->charcnt = charcnt;
455 
456  /*
457  * Ignore any trailing, no-op transitions generated by zic as
458  * they don't help here and can run afoul of bugs in zic 2016j
459  * or earlier.
460  */
461  while (1 < sp->timecnt
462  && (sp->types[sp->timecnt - 1]
463  == sp->types[sp->timecnt - 2]))
464  sp->timecnt--;
465 
466  for (i = 0; i < ts->timecnt; i++)
467  if (sp->ats[sp->timecnt - 1] < ts->ats[i])
468  break;
469  while (i < ts->timecnt
470  && sp->timecnt < TZ_MAX_TIMES)
471  {
472  sp->ats[sp->timecnt] = ts->ats[i];
473  sp->types[sp->timecnt] = (sp->typecnt
474  + ts->types[i]);
475  sp->timecnt++;
476  i++;
477  }
478  sp->ttis[sp->typecnt++] = ts->ttis[0];
479  sp->ttis[sp->typecnt++] = ts->ttis[1];
480  }
481  }
482  }
483  if (sp->timecnt > 1)
484  {
485  for (i = 1; i < sp->timecnt; ++i)
486  if (typesequiv(sp, sp->types[i], sp->types[0]) &&
487  differ_by_repeat(sp->ats[i], sp->ats[0]))
488  {
489  sp->goback = true;
490  break;
491  }
492  for (i = sp->timecnt - 2; i >= 0; --i)
493  if (typesequiv(sp, sp->types[sp->timecnt - 1],
494  sp->types[i]) &&
495  differ_by_repeat(sp->ats[sp->timecnt - 1],
496  sp->ats[i]))
497  {
498  sp->goahead = true;
499  break;
500  }
501  }
502 
503  /*
504  * If type 0 is unused in transitions, it's the type to use for early
505  * times.
506  */
507  for (i = 0; i < sp->timecnt; ++i)
508  if (sp->types[i] == 0)
509  break;
510  i = i < sp->timecnt ? -1 : 0;
511 
512  /*
513  * Absent the above, if there are transition times and the first
514  * transition is to a daylight time find the standard type less than and
515  * closest to the type of the first transition.
516  */
517  if (i < 0 && sp->timecnt > 0 && sp->ttis[sp->types[0]].tt_isdst)
518  {
519  i = sp->types[0];
520  while (--i >= 0)
521  if (!sp->ttis[i].tt_isdst)
522  break;
523  }
524 
525  /*
526  * If no result yet, find the first standard type. If there is none, punt
527  * to type zero.
528  */
529  if (i < 0)
530  {
531  i = 0;
532  while (sp->ttis[i].tt_isdst)
533  if (++i >= sp->typecnt)
534  {
535  i = 0;
536  break;
537  }
538  }
539  sp->defaulttype = i;
540  return 0;
541 }
542 
543 /* Load tz data from the file named NAME into *SP. Read extended
544  * format if DOEXTEND. Return 0 on success, an errno value on failure.
545  * PG: If "canonname" is not NULL, then on success the canonical spelling of
546  * given name is stored there (the buffer must be > TZ_STRLEN_MAX bytes!).
547  */
548 int
549 tzload(const char *name, char *canonname, struct state * sp, bool doextend)
550 {
551  union local_storage *lsp = malloc(sizeof *lsp);
552 
553  if (!lsp)
554  return errno;
555  else
556  {
557  int err = tzloadbody(name, canonname, sp, doextend, lsp);
558 
559  free(lsp);
560  return err;
561  }
562 }
563 
564 static bool
565 typesequiv(const struct state * sp, int a, int b)
566 {
567  bool result;
568 
569  if (sp == NULL ||
570  a < 0 || a >= sp->typecnt ||
571  b < 0 || b >= sp->typecnt)
572  result = false;
573  else
574  {
575  const struct ttinfo *ap = &sp->ttis[a];
576  const struct ttinfo *bp = &sp->ttis[b];
577 
578  result = ap->tt_gmtoff == bp->tt_gmtoff &&
579  ap->tt_isdst == bp->tt_isdst &&
580  ap->tt_ttisstd == bp->tt_ttisstd &&
581  ap->tt_ttisgmt == bp->tt_ttisgmt &&
582  strcmp(&sp->chars[ap->tt_abbrind],
583  &sp->chars[bp->tt_abbrind]) == 0;
584  }
585  return result;
586 }
587 
588 static const int mon_lengths[2][MONSPERYEAR] = {
589  {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
590  {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
591 };
592 
593 static const int year_lengths[2] = {
595 };
596 
597 /*
598  * Given a pointer into a time zone string, scan until a character that is not
599  * a valid character in a zone name is found. Return a pointer to that
600  * character.
601  */
602 static const char *
603 getzname(const char *strp)
604 {
605  char c;
606 
607  while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
608  c != '+')
609  ++strp;
610  return strp;
611 }
612 
613 /*
614  * Given a pointer into an extended time zone string, scan until the ending
615  * delimiter of the zone name is located. Return a pointer to the delimiter.
616  *
617  * As with getzname above, the legal character set is actually quite
618  * restricted, with other characters producing undefined results.
619  * We don't do any checking here; checking is done later in common-case code.
620  */
621 static const char *
622 getqzname(const char *strp, int delim)
623 {
624  int c;
625 
626  while ((c = *strp) != '\0' && c != delim)
627  ++strp;
628  return strp;
629 }
630 
631 /*
632  * Given a pointer into a time zone string, extract a number from that string.
633  * Check that the number is within a specified range; if it is not, return
634  * NULL.
635  * Otherwise, return a pointer to the first character not part of the number.
636  */
637 static const char *
638 getnum(const char *strp, int *nump, int min, int max)
639 {
640  char c;
641  int num;
642 
643  if (strp == NULL || !is_digit(c = *strp))
644  return NULL;
645  num = 0;
646  do
647  {
648  num = num * 10 + (c - '0');
649  if (num > max)
650  return NULL; /* illegal value */
651  c = *++strp;
652  } while (is_digit(c));
653  if (num < min)
654  return NULL; /* illegal value */
655  *nump = num;
656  return strp;
657 }
658 
659 /*
660  * Given a pointer into a time zone string, extract a number of seconds,
661  * in hh[:mm[:ss]] form, from the string.
662  * If any error occurs, return NULL.
663  * Otherwise, return a pointer to the first character not part of the number
664  * of seconds.
665  */
666 static const char *
667 getsecs(const char *strp, int32 *secsp)
668 {
669  int num;
670 
671  /*
672  * 'HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
673  * "M10.4.6/26", which does not conform to Posix, but which specifies the
674  * equivalent of "02:00 on the first Sunday on or after 23 Oct".
675  */
676  strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
677  if (strp == NULL)
678  return NULL;
679  *secsp = num * (int32) SECSPERHOUR;
680  if (*strp == ':')
681  {
682  ++strp;
683  strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
684  if (strp == NULL)
685  return NULL;
686  *secsp += num * SECSPERMIN;
687  if (*strp == ':')
688  {
689  ++strp;
690  /* 'SECSPERMIN' allows for leap seconds. */
691  strp = getnum(strp, &num, 0, SECSPERMIN);
692  if (strp == NULL)
693  return NULL;
694  *secsp += num;
695  }
696  }
697  return strp;
698 }
699 
700 /*
701  * Given a pointer into a time zone string, extract an offset, in
702  * [+-]hh[:mm[:ss]] form, from the string.
703  * If any error occurs, return NULL.
704  * Otherwise, return a pointer to the first character not part of the time.
705  */
706 static const char *
707 getoffset(const char *strp, int32 *offsetp)
708 {
709  bool neg = false;
710 
711  if (*strp == '-')
712  {
713  neg = true;
714  ++strp;
715  }
716  else if (*strp == '+')
717  ++strp;
718  strp = getsecs(strp, offsetp);
719  if (strp == NULL)
720  return NULL; /* illegal time */
721  if (neg)
722  *offsetp = -*offsetp;
723  return strp;
724 }
725 
726 /*
727  * Given a pointer into a time zone string, extract a rule in the form
728  * date[/time]. See POSIX section 8 for the format of "date" and "time".
729  * If a valid rule is not found, return NULL.
730  * Otherwise, return a pointer to the first character not part of the rule.
731  */
732 static const char *
733 getrule(const char *strp, struct rule * rulep)
734 {
735  if (*strp == 'J')
736  {
737  /*
738  * Julian day.
739  */
740  rulep->r_type = JULIAN_DAY;
741  ++strp;
742  strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
743  }
744  else if (*strp == 'M')
745  {
746  /*
747  * Month, week, day.
748  */
749  rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
750  ++strp;
751  strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
752  if (strp == NULL)
753  return NULL;
754  if (*strp++ != '.')
755  return NULL;
756  strp = getnum(strp, &rulep->r_week, 1, 5);
757  if (strp == NULL)
758  return NULL;
759  if (*strp++ != '.')
760  return NULL;
761  strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
762  }
763  else if (is_digit(*strp))
764  {
765  /*
766  * Day of year.
767  */
768  rulep->r_type = DAY_OF_YEAR;
769  strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
770  }
771  else
772  return NULL; /* invalid format */
773  if (strp == NULL)
774  return NULL;
775  if (*strp == '/')
776  {
777  /*
778  * Time specified.
779  */
780  ++strp;
781  strp = getoffset(strp, &rulep->r_time);
782  }
783  else
784  rulep->r_time = 2 * SECSPERHOUR; /* default = 2:00:00 */
785  return strp;
786 }
787 
788 /*
789  * Given a year, a rule, and the offset from UT at the time that rule takes
790  * effect, calculate the year-relative time that rule takes effect.
791  */
792 static int32
793 transtime(int year, const struct rule * rulep,
794  int32 offset)
795 {
796  bool leapyear;
797  int32 value;
798  int i,
799  d,
800  m1,
801  yy0,
802  yy1,
803  yy2,
804  dow;
805 
806  INITIALIZE(value);
807  leapyear = isleap(year);
808  switch (rulep->r_type)
809  {
810 
811  case JULIAN_DAY:
812 
813  /*
814  * Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
815  * years. In non-leap years, or if the day number is 59 or less,
816  * just add SECSPERDAY times the day number-1 to the time of
817  * January 1, midnight, to get the day.
818  */
819  value = (rulep->r_day - 1) * SECSPERDAY;
820  if (leapyear && rulep->r_day >= 60)
821  value += SECSPERDAY;
822  break;
823 
824  case DAY_OF_YEAR:
825 
826  /*
827  * n - day of year. Just add SECSPERDAY times the day number to
828  * the time of January 1, midnight, to get the day.
829  */
830  value = rulep->r_day * SECSPERDAY;
831  break;
832 
834 
835  /*
836  * Mm.n.d - nth "dth day" of month m.
837  */
838 
839  /*
840  * Use Zeller's Congruence to get day-of-week of first day of
841  * month.
842  */
843  m1 = (rulep->r_mon + 9) % 12 + 1;
844  yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
845  yy1 = yy0 / 100;
846  yy2 = yy0 % 100;
847  dow = ((26 * m1 - 2) / 10 +
848  1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
849  if (dow < 0)
850  dow += DAYSPERWEEK;
851 
852  /*
853  * "dow" is the day-of-week of the first day of the month. Get the
854  * day-of-month (zero-origin) of the first "dow" day of the month.
855  */
856  d = rulep->r_day - dow;
857  if (d < 0)
858  d += DAYSPERWEEK;
859  for (i = 1; i < rulep->r_week; ++i)
860  {
861  if (d + DAYSPERWEEK >=
862  mon_lengths[(int) leapyear][rulep->r_mon - 1])
863  break;
864  d += DAYSPERWEEK;
865  }
866 
867  /*
868  * "d" is the day-of-month (zero-origin) of the day we want.
869  */
870  value = d * SECSPERDAY;
871  for (i = 0; i < rulep->r_mon - 1; ++i)
872  value += mon_lengths[(int) leapyear][i] * SECSPERDAY;
873  break;
874  }
875 
876  /*
877  * "value" is the year-relative time of 00:00:00 UT on the day in
878  * question. To get the year-relative time of the specified local time on
879  * that day, add the transition time and the current offset from UT.
880  */
881  return value + rulep->r_time + offset;
882 }
883 
884 /*
885  * Given a POSIX section 8-style TZ string, fill in the rule tables as
886  * appropriate.
887  * Returns true on success, false on failure.
888  */
889 bool
890 tzparse(const char *name, struct state * sp, bool lastditch)
891 {
892  const char *stdname;
893  const char *dstname = NULL;
894  size_t stdlen;
895  size_t dstlen;
896  size_t charcnt;
897  int32 stdoffset;
898  int32 dstoffset;
899  char *cp;
900  bool load_ok;
901 
902  stdname = name;
903  if (lastditch)
904  {
905  /*
906  * This is intentionally somewhat different from the IANA code. We do
907  * not want to invoke tzload() in the lastditch case: we can't assume
908  * pg_open_tzfile() is sane yet, and we don't care about leap seconds
909  * anyway.
910  */
911  stdlen = strlen(name); /* length of standard zone name */
912  name += stdlen;
913  if (stdlen >= sizeof sp->chars)
914  stdlen = (sizeof sp->chars) - 1;
915  charcnt = stdlen + 1;
916  stdoffset = 0;
917  sp->goback = sp->goahead = false; /* simulate failed tzload() */
918  load_ok = false;
919  }
920  else
921  {
922  if (*name == '<')
923  {
924  name++;
925  stdname = name;
926  name = getqzname(name, '>');
927  if (*name != '>')
928  return false;
929  stdlen = name - stdname;
930  name++;
931  }
932  else
933  {
934  name = getzname(name);
935  stdlen = name - stdname;
936  }
937  if (*name == '\0') /* we allow empty STD abbrev, unlike IANA */
938  return false;
939  name = getoffset(name, &stdoffset);
940  if (name == NULL)
941  return false;
942  charcnt = stdlen + 1;
943  if (sizeof sp->chars < charcnt)
944  return false;
945  load_ok = tzload(TZDEFRULES, NULL, sp, false) == 0;
946  }
947  if (!load_ok)
948  sp->leapcnt = 0; /* so, we're off a little */
949  if (*name != '\0')
950  {
951  if (*name == '<')
952  {
953  dstname = ++name;
954  name = getqzname(name, '>');
955  if (*name != '>')
956  return false;
957  dstlen = name - dstname;
958  name++;
959  }
960  else
961  {
962  dstname = name;
963  name = getzname(name);
964  dstlen = name - dstname; /* length of DST zone name */
965  }
966  if (!dstlen)
967  return false;
968  charcnt += dstlen + 1;
969  if (sizeof sp->chars < charcnt)
970  return false;
971  if (*name != '\0' && *name != ',' && *name != ';')
972  {
973  name = getoffset(name, &dstoffset);
974  if (name == NULL)
975  return false;
976  }
977  else
978  dstoffset = stdoffset - SECSPERHOUR;
979  if (*name == '\0' && !load_ok)
980  name = TZDEFRULESTRING;
981  if (*name == ',' || *name == ';')
982  {
983  struct rule start;
984  struct rule end;
985  int year;
986  int yearlim;
987  int timecnt;
988  pg_time_t janfirst;
989  int32 janoffset = 0;
990  int yearbeg;
991 
992  ++name;
993  if ((name = getrule(name, &start)) == NULL)
994  return false;
995  if (*name++ != ',')
996  return false;
997  if ((name = getrule(name, &end)) == NULL)
998  return false;
999  if (*name != '\0')
1000  return false;
1001  sp->typecnt = 2; /* standard time and DST */
1002 
1003  /*
1004  * Two transitions per year, from EPOCH_YEAR forward.
1005  */
1006  init_ttinfo(&sp->ttis[0], -dstoffset, true, stdlen + 1);
1007  init_ttinfo(&sp->ttis[1], -stdoffset, false, 0);
1008  sp->defaulttype = 0;
1009  timecnt = 0;
1010  janfirst = 0;
1011  yearbeg = EPOCH_YEAR;
1012 
1013  do
1014  {
1015  int32 yearsecs
1016  = year_lengths[isleap(yearbeg - 1)] * SECSPERDAY;
1017 
1018  yearbeg--;
1019  if (increment_overflow_time(&janfirst, -yearsecs))
1020  {
1021  janoffset = -yearsecs;
1022  break;
1023  }
1024  } while (EPOCH_YEAR - YEARSPERREPEAT / 2 < yearbeg);
1025 
1026  yearlim = yearbeg + YEARSPERREPEAT + 1;
1027  for (year = yearbeg; year < yearlim; year++)
1028  {
1029  int32
1030  starttime = transtime(year, &start, stdoffset),
1031  endtime = transtime(year, &end, dstoffset);
1032  int32
1033  yearsecs = (year_lengths[isleap(year)]
1034  * SECSPERDAY);
1035  bool reversed = endtime < starttime;
1036 
1037  if (reversed)
1038  {
1039  int32 swap = starttime;
1040 
1041  starttime = endtime;
1042  endtime = swap;
1043  }
1044  if (reversed
1045  || (starttime < endtime
1046  && (endtime - starttime
1047  < (yearsecs
1048  + (stdoffset - dstoffset)))))
1049  {
1050  if (TZ_MAX_TIMES - 2 < timecnt)
1051  break;
1052  sp->ats[timecnt] = janfirst;
1054  (&sp->ats[timecnt],
1055  janoffset + starttime))
1056  sp->types[timecnt++] = reversed;
1057  else if (janoffset)
1058  sp->defaulttype = reversed;
1059  sp->ats[timecnt] = janfirst;
1061  (&sp->ats[timecnt],
1062  janoffset + endtime))
1063  {
1064  sp->types[timecnt++] = !reversed;
1065  yearlim = year + YEARSPERREPEAT + 1;
1066  }
1067  else if (janoffset)
1068  sp->defaulttype = !reversed;
1069  }
1071  (&janfirst, janoffset + yearsecs))
1072  break;
1073  janoffset = 0;
1074  }
1075  sp->timecnt = timecnt;
1076  if (!timecnt)
1077  sp->typecnt = 1; /* Perpetual DST. */
1078  else if (YEARSPERREPEAT < year - yearbeg)
1079  sp->goback = sp->goahead = true;
1080  }
1081  else
1082  {
1083  int32 theirstdoffset;
1084  int32 theirdstoffset;
1085  int32 theiroffset;
1086  bool isdst;
1087  int i;
1088  int j;
1089 
1090  if (*name != '\0')
1091  return false;
1092 
1093  /*
1094  * Initial values of theirstdoffset and theirdstoffset.
1095  */
1096  theirstdoffset = 0;
1097  for (i = 0; i < sp->timecnt; ++i)
1098  {
1099  j = sp->types[i];
1100  if (!sp->ttis[j].tt_isdst)
1101  {
1102  theirstdoffset =
1103  -sp->ttis[j].tt_gmtoff;
1104  break;
1105  }
1106  }
1107  theirdstoffset = 0;
1108  for (i = 0; i < sp->timecnt; ++i)
1109  {
1110  j = sp->types[i];
1111  if (sp->ttis[j].tt_isdst)
1112  {
1113  theirdstoffset =
1114  -sp->ttis[j].tt_gmtoff;
1115  break;
1116  }
1117  }
1118 
1119  /*
1120  * Initially we're assumed to be in standard time.
1121  */
1122  isdst = false;
1123  theiroffset = theirstdoffset;
1124 
1125  /*
1126  * Now juggle transition times and types tracking offsets as you
1127  * do.
1128  */
1129  for (i = 0; i < sp->timecnt; ++i)
1130  {
1131  j = sp->types[i];
1132  sp->types[i] = sp->ttis[j].tt_isdst;
1133  if (sp->ttis[j].tt_ttisgmt)
1134  {
1135  /* No adjustment to transition time */
1136  }
1137  else
1138  {
1139  /*
1140  * If summer time is in effect, and the transition time
1141  * was not specified as standard time, add the summer time
1142  * offset to the transition time; otherwise, add the
1143  * standard time offset to the transition time.
1144  */
1145 
1146  /*
1147  * Transitions from DST to DDST will effectively disappear
1148  * since POSIX provides for only one DST offset.
1149  */
1150  if (isdst && !sp->ttis[j].tt_ttisstd)
1151  {
1152  sp->ats[i] += dstoffset -
1153  theirdstoffset;
1154  }
1155  else
1156  {
1157  sp->ats[i] += stdoffset -
1158  theirstdoffset;
1159  }
1160  }
1161  theiroffset = -sp->ttis[j].tt_gmtoff;
1162  if (sp->ttis[j].tt_isdst)
1163  theirdstoffset = theiroffset;
1164  else
1165  theirstdoffset = theiroffset;
1166  }
1167 
1168  /*
1169  * Finally, fill in ttis.
1170  */
1171  init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
1172  init_ttinfo(&sp->ttis[1], -dstoffset, true, stdlen + 1);
1173  sp->typecnt = 2;
1174  sp->defaulttype = 0;
1175  }
1176  }
1177  else
1178  {
1179  dstlen = 0;
1180  sp->typecnt = 1; /* only standard time */
1181  sp->timecnt = 0;
1182  init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
1183  sp->defaulttype = 0;
1184  }
1185  sp->charcnt = charcnt;
1186  cp = sp->chars;
1187  memcpy(cp, stdname, stdlen);
1188  cp += stdlen;
1189  *cp++ = '\0';
1190  if (dstlen != 0)
1191  {
1192  memcpy(cp, dstname, dstlen);
1193  *(cp + dstlen) = '\0';
1194  }
1195  return true;
1196 }
1197 
1198 static void
1199 gmtload(struct state * sp)
1200 {
1201  if (tzload(gmt, NULL, sp, true) != 0)
1202  tzparse(gmt, sp, true);
1203 }
1204 
1205 
1206 /*
1207  * The easy way to behave "as if no library function calls" localtime
1208  * is to not call it, so we drop its guts into "localsub", which can be
1209  * freely called. (And no, the PANS doesn't require the above behavior,
1210  * but it *is* desirable.)
1211  */
1212 static struct pg_tm *
1213 localsub(struct state const * sp, pg_time_t const * timep,
1214  struct pg_tm * tmp)
1215 {
1216  const struct ttinfo *ttisp;
1217  int i;
1218  struct pg_tm *result;
1219  const pg_time_t t = *timep;
1220 
1221  if (sp == NULL)
1222  return gmtsub(timep, 0, tmp);
1223  if ((sp->goback && t < sp->ats[0]) ||
1224  (sp->goahead && t > sp->ats[sp->timecnt - 1]))
1225  {
1226  pg_time_t newt = t;
1227  pg_time_t seconds;
1228  pg_time_t years;
1229 
1230  if (t < sp->ats[0])
1231  seconds = sp->ats[0] - t;
1232  else
1233  seconds = t - sp->ats[sp->timecnt - 1];
1234  --seconds;
1235  years = (seconds / SECSPERREPEAT + 1) * YEARSPERREPEAT;
1236  seconds = years * AVGSECSPERYEAR;
1237  if (t < sp->ats[0])
1238  newt += seconds;
1239  else
1240  newt -= seconds;
1241  if (newt < sp->ats[0] ||
1242  newt > sp->ats[sp->timecnt - 1])
1243  return NULL; /* "cannot happen" */
1244  result = localsub(sp, &newt, tmp);
1245  if (result)
1246  {
1247  int64 newy;
1248 
1249  newy = result->tm_year;
1250  if (t < sp->ats[0])
1251  newy -= years;
1252  else
1253  newy += years;
1254  if (!(INT_MIN <= newy && newy <= INT_MAX))
1255  return NULL;
1256  result->tm_year = newy;
1257  }
1258  return result;
1259  }
1260  if (sp->timecnt == 0 || t < sp->ats[0])
1261  {
1262  i = sp->defaulttype;
1263  }
1264  else
1265  {
1266  int lo = 1;
1267  int hi = sp->timecnt;
1268 
1269  while (lo < hi)
1270  {
1271  int mid = (lo + hi) >> 1;
1272 
1273  if (t < sp->ats[mid])
1274  hi = mid;
1275  else
1276  lo = mid + 1;
1277  }
1278  i = (int) sp->types[lo - 1];
1279  }
1280  ttisp = &sp->ttis[i];
1281 
1282  result = timesub(&t, ttisp->tt_gmtoff, sp, tmp);
1283  if (result)
1284  {
1285  result->tm_isdst = ttisp->tt_isdst;
1286  result->tm_zone = (char *) &sp->chars[ttisp->tt_abbrind];
1287  }
1288  return result;
1289 }
1290 
1291 
1292 struct pg_tm *
1293 pg_localtime(const pg_time_t *timep, const pg_tz *tz)
1294 {
1295  return localsub(&tz->state, timep, &tm);
1296 }
1297 
1298 
1299 /*
1300  * gmtsub is to gmtime as localsub is to localtime.
1301  *
1302  * Except we have a private "struct state" for GMT, so no sp is passed in.
1303  */
1304 static struct pg_tm *
1305 gmtsub(pg_time_t const * timep, int32 offset, struct pg_tm * tmp)
1306 {
1307  struct pg_tm *result;
1308 
1309  /* GMT timezone state data is kept here */
1310  static struct state gmtmem;
1311  static bool gmt_is_set = false;
1312 #define gmtptr (&gmtmem)
1313 
1314  if (!gmt_is_set)
1315  {
1316  gmt_is_set = true;
1317  gmtload(gmtptr);
1318  }
1319  result = timesub(timep, offset, gmtptr, tmp);
1320 
1321  /*
1322  * Could get fancy here and deliver something such as "+xx" or "-xx" if
1323  * offset is non-zero, but this is no time for a treasure hunt.
1324  */
1325  if (offset != 0)
1326  tmp->tm_zone = wildabbr;
1327  else
1328  tmp->tm_zone = gmtptr->chars;
1329 
1330  return result;
1331 }
1332 
1333 struct pg_tm *
1334 pg_gmtime(const pg_time_t *timep)
1335 {
1336  return gmtsub(timep, 0, &tm);
1337 }
1338 
1339 /*
1340  * Return the number of leap years through the end of the given year
1341  * where, to make the math easy, the answer for year zero is defined as zero.
1342  */
1343 static int
1344 leaps_thru_end_of(const int y)
1345 {
1346  return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
1347  -(leaps_thru_end_of(-(y + 1)) + 1);
1348 }
1349 
1350 static struct pg_tm *
1351 timesub(const pg_time_t *timep, int32 offset,
1352  const struct state * sp, struct pg_tm * tmp)
1353 {
1354  const struct lsinfo *lp;
1355  pg_time_t tdays;
1356  int idays; /* unsigned would be so 2003 */
1357  int64 rem;
1358  int y;
1359  const int *ip;
1360  int64 corr;
1361  bool hit;
1362  int i;
1363 
1364  corr = 0;
1365  hit = false;
1366  i = (sp == NULL) ? 0 : sp->leapcnt;
1367  while (--i >= 0)
1368  {
1369  lp = &sp->lsis[i];
1370  if (*timep >= lp->ls_trans)
1371  {
1372  if (*timep == lp->ls_trans)
1373  {
1374  hit = ((i == 0 && lp->ls_corr > 0) ||
1375  lp->ls_corr > sp->lsis[i - 1].ls_corr);
1376  if (hit)
1377  while (i > 0 &&
1378  sp->lsis[i].ls_trans ==
1379  sp->lsis[i - 1].ls_trans + 1 &&
1380  sp->lsis[i].ls_corr ==
1381  sp->lsis[i - 1].ls_corr + 1)
1382  {
1383  ++hit;
1384  --i;
1385  }
1386  }
1387  corr = lp->ls_corr;
1388  break;
1389  }
1390  }
1391  y = EPOCH_YEAR;
1392  tdays = *timep / SECSPERDAY;
1393  rem = *timep % SECSPERDAY;
1394  while (tdays < 0 || tdays >= year_lengths[isleap(y)])
1395  {
1396  int newy;
1397  pg_time_t tdelta;
1398  int idelta;
1399  int leapdays;
1400 
1401  tdelta = tdays / DAYSPERLYEAR;
1402  if (!((!TYPE_SIGNED(pg_time_t) ||INT_MIN <= tdelta)
1403  && tdelta <= INT_MAX))
1404  goto out_of_range;
1405  idelta = tdelta;
1406  if (idelta == 0)
1407  idelta = (tdays < 0) ? -1 : 1;
1408  newy = y;
1409  if (increment_overflow(&newy, idelta))
1410  goto out_of_range;
1411  leapdays = leaps_thru_end_of(newy - 1) -
1412  leaps_thru_end_of(y - 1);
1413  tdays -= ((pg_time_t) newy - y) * DAYSPERNYEAR;
1414  tdays -= leapdays;
1415  y = newy;
1416  }
1417 
1418  /*
1419  * Given the range, we can now fearlessly cast...
1420  */
1421  idays = tdays;
1422  rem += offset - corr;
1423  while (rem < 0)
1424  {
1425  rem += SECSPERDAY;
1426  --idays;
1427  }
1428  while (rem >= SECSPERDAY)
1429  {
1430  rem -= SECSPERDAY;
1431  ++idays;
1432  }
1433  while (idays < 0)
1434  {
1435  if (increment_overflow(&y, -1))
1436  goto out_of_range;
1437  idays += year_lengths[isleap(y)];
1438  }
1439  while (idays >= year_lengths[isleap(y)])
1440  {
1441  idays -= year_lengths[isleap(y)];
1442  if (increment_overflow(&y, 1))
1443  goto out_of_range;
1444  }
1445  tmp->tm_year = y;
1447  goto out_of_range;
1448  tmp->tm_yday = idays;
1449 
1450  /*
1451  * The "extra" mods below avoid overflow problems.
1452  */
1453  tmp->tm_wday = EPOCH_WDAY +
1454  ((y - EPOCH_YEAR) % DAYSPERWEEK) *
1456  leaps_thru_end_of(y - 1) -
1458  idays;
1459  tmp->tm_wday %= DAYSPERWEEK;
1460  if (tmp->tm_wday < 0)
1461  tmp->tm_wday += DAYSPERWEEK;
1462  tmp->tm_hour = (int) (rem / SECSPERHOUR);
1463  rem %= SECSPERHOUR;
1464  tmp->tm_min = (int) (rem / SECSPERMIN);
1465 
1466  /*
1467  * A positive leap second requires a special representation. This uses
1468  * "... ??:59:60" et seq.
1469  */
1470  tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1471  ip = mon_lengths[isleap(y)];
1472  for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
1473  idays -= ip[tmp->tm_mon];
1474  tmp->tm_mday = (int) (idays + 1);
1475  tmp->tm_isdst = 0;
1476  tmp->tm_gmtoff = offset;
1477  return tmp;
1478 
1479 out_of_range:
1480  errno = EOVERFLOW;
1481  return NULL;
1482 }
1483 
1484 /*
1485  * Normalize logic courtesy Paul Eggert.
1486  */
1487 
1488 static bool
1489 increment_overflow(int *ip, int j)
1490 {
1491  int const i = *ip;
1492 
1493  /*----------
1494  * If i >= 0 there can only be overflow if i + j > INT_MAX
1495  * or if j > INT_MAX - i; given i >= 0, INT_MAX - i cannot overflow.
1496  * If i < 0 there can only be overflow if i + j < INT_MIN
1497  * or if j < INT_MIN - i; given i < 0, INT_MIN - i cannot overflow.
1498  *----------
1499  */
1500  if ((i >= 0) ? (j > INT_MAX - i) : (j < INT_MIN - i))
1501  return true;
1502  *ip += j;
1503  return false;
1504 }
1505 
1506 static bool
1508 {
1509  /*----------
1510  * This is like
1511  * 'if (! (time_t_min <= *tp + j && *tp + j <= time_t_max)) ...',
1512  * except that it does the right thing even if *tp + j would overflow.
1513  *----------
1514  */
1515  if (!(j < 0
1516  ? (TYPE_SIGNED(pg_time_t) ? time_t_min - j <= *tp : -1 - j < *tp)
1517  : *tp <= time_t_max - j))
1518  return true;
1519  *tp += j;
1520  return false;
1521 }
1522 
1523 /*
1524  * Find the next DST transition time in the given zone after the given time
1525  *
1526  * *timep and *tz are input arguments, the other parameters are output values.
1527  *
1528  * When the function result is 1, *boundary is set to the pg_time_t
1529  * representation of the next DST transition time after *timep,
1530  * *before_gmtoff and *before_isdst are set to the GMT offset and isdst
1531  * state prevailing just before that boundary (in particular, the state
1532  * prevailing at *timep), and *after_gmtoff and *after_isdst are set to
1533  * the state prevailing just after that boundary.
1534  *
1535  * When the function result is 0, there is no known DST transition
1536  * after *timep, but *before_gmtoff and *before_isdst indicate the GMT
1537  * offset and isdst state prevailing at *timep. (This would occur in
1538  * DST-less time zones, or if a zone has permanently ceased using DST.)
1539  *
1540  * A function result of -1 indicates failure (this case does not actually
1541  * occur in our current implementation).
1542  */
1543 int
1545  long int *before_gmtoff,
1546  int *before_isdst,
1547  pg_time_t *boundary,
1548  long int *after_gmtoff,
1549  int *after_isdst,
1550  const pg_tz *tz)
1551 {
1552  const struct state *sp;
1553  const struct ttinfo *ttisp;
1554  int i;
1555  int j;
1556  const pg_time_t t = *timep;
1557 
1558  sp = &tz->state;
1559  if (sp->timecnt == 0)
1560  {
1561  /* non-DST zone, use lowest-numbered standard type */
1562  i = 0;
1563  while (sp->ttis[i].tt_isdst)
1564  if (++i >= sp->typecnt)
1565  {
1566  i = 0;
1567  break;
1568  }
1569  ttisp = &sp->ttis[i];
1570  *before_gmtoff = ttisp->tt_gmtoff;
1571  *before_isdst = ttisp->tt_isdst;
1572  return 0;
1573  }
1574  if ((sp->goback && t < sp->ats[0]) ||
1575  (sp->goahead && t > sp->ats[sp->timecnt - 1]))
1576  {
1577  /* For values outside the transition table, extrapolate */
1578  pg_time_t newt = t;
1579  pg_time_t seconds;
1580  pg_time_t tcycles;
1581  int64 icycles;
1582  int result;
1583 
1584  if (t < sp->ats[0])
1585  seconds = sp->ats[0] - t;
1586  else
1587  seconds = t - sp->ats[sp->timecnt - 1];
1588  --seconds;
1589  tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
1590  ++tcycles;
1591  icycles = tcycles;
1592  if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
1593  return -1;
1594  seconds = icycles;
1595  seconds *= YEARSPERREPEAT;
1596  seconds *= AVGSECSPERYEAR;
1597  if (t < sp->ats[0])
1598  newt += seconds;
1599  else
1600  newt -= seconds;
1601  if (newt < sp->ats[0] ||
1602  newt > sp->ats[sp->timecnt - 1])
1603  return -1; /* "cannot happen" */
1604 
1605  result = pg_next_dst_boundary(&newt, before_gmtoff,
1606  before_isdst,
1607  boundary,
1608  after_gmtoff,
1609  after_isdst,
1610  tz);
1611  if (t < sp->ats[0])
1612  *boundary -= seconds;
1613  else
1614  *boundary += seconds;
1615  return result;
1616  }
1617 
1618  if (t >= sp->ats[sp->timecnt - 1])
1619  {
1620  /* No known transition > t, so use last known segment's type */
1621  i = sp->types[sp->timecnt - 1];
1622  ttisp = &sp->ttis[i];
1623  *before_gmtoff = ttisp->tt_gmtoff;
1624  *before_isdst = ttisp->tt_isdst;
1625  return 0;
1626  }
1627  if (t < sp->ats[0])
1628  {
1629  /* For "before", use lowest-numbered standard type */
1630  i = 0;
1631  while (sp->ttis[i].tt_isdst)
1632  if (++i >= sp->typecnt)
1633  {
1634  i = 0;
1635  break;
1636  }
1637  ttisp = &sp->ttis[i];
1638  *before_gmtoff = ttisp->tt_gmtoff;
1639  *before_isdst = ttisp->tt_isdst;
1640  *boundary = sp->ats[0];
1641  /* And for "after", use the first segment's type */
1642  i = sp->types[0];
1643  ttisp = &sp->ttis[i];
1644  *after_gmtoff = ttisp->tt_gmtoff;
1645  *after_isdst = ttisp->tt_isdst;
1646  return 1;
1647  }
1648  /* Else search to find the boundary following t */
1649  {
1650  int lo = 1;
1651  int hi = sp->timecnt - 1;
1652 
1653  while (lo < hi)
1654  {
1655  int mid = (lo + hi) >> 1;
1656 
1657  if (t < sp->ats[mid])
1658  hi = mid;
1659  else
1660  lo = mid + 1;
1661  }
1662  i = lo;
1663  }
1664  j = sp->types[i - 1];
1665  ttisp = &sp->ttis[j];
1666  *before_gmtoff = ttisp->tt_gmtoff;
1667  *before_isdst = ttisp->tt_isdst;
1668  *boundary = sp->ats[i];
1669  j = sp->types[i];
1670  ttisp = &sp->ttis[j];
1671  *after_gmtoff = ttisp->tt_gmtoff;
1672  *after_isdst = ttisp->tt_isdst;
1673  return 1;
1674 }
1675 
1676 /*
1677  * Identify a timezone abbreviation's meaning in the given zone
1678  *
1679  * Determine the GMT offset and DST flag associated with the abbreviation.
1680  * This is generally used only when the abbreviation has actually changed
1681  * meaning over time; therefore, we also take a UTC cutoff time, and return
1682  * the meaning in use at or most recently before that time, or the meaning
1683  * in first use after that time if the abbrev was never used before that.
1684  *
1685  * On success, returns true and sets *gmtoff and *isdst. If the abbreviation
1686  * was never used at all in this zone, returns false.
1687  *
1688  * Note: abbrev is matched case-sensitively; it should be all-upper-case.
1689  */
1690 bool
1691 pg_interpret_timezone_abbrev(const char *abbrev,
1692  const pg_time_t *timep,
1693  long int *gmtoff,
1694  int *isdst,
1695  const pg_tz *tz)
1696 {
1697  const struct state *sp;
1698  const char *abbrs;
1699  const struct ttinfo *ttisp;
1700  int abbrind;
1701  int cutoff;
1702  int i;
1703  const pg_time_t t = *timep;
1704 
1705  sp = &tz->state;
1706 
1707  /*
1708  * Locate the abbreviation in the zone's abbreviation list. We assume
1709  * there are not duplicates in the list.
1710  */
1711  abbrs = sp->chars;
1712  abbrind = 0;
1713  while (abbrind < sp->charcnt)
1714  {
1715  if (strcmp(abbrev, abbrs + abbrind) == 0)
1716  break;
1717  while (abbrs[abbrind] != '\0')
1718  abbrind++;
1719  abbrind++;
1720  }
1721  if (abbrind >= sp->charcnt)
1722  return false; /* not there! */
1723 
1724  /*
1725  * Unlike pg_next_dst_boundary, we needn't sweat about extrapolation
1726  * (goback/goahead zones). Finding the newest or oldest meaning of the
1727  * abbreviation should get us what we want, since extrapolation would just
1728  * be repeating the newest or oldest meanings.
1729  *
1730  * Use binary search to locate the first transition > cutoff time.
1731  */
1732  {
1733  int lo = 0;
1734  int hi = sp->timecnt;
1735 
1736  while (lo < hi)
1737  {
1738  int mid = (lo + hi) >> 1;
1739 
1740  if (t < sp->ats[mid])
1741  hi = mid;
1742  else
1743  lo = mid + 1;
1744  }
1745  cutoff = lo;
1746  }
1747 
1748  /*
1749  * Scan backwards to find the latest interval using the given abbrev
1750  * before the cutoff time.
1751  */
1752  for (i = cutoff - 1; i >= 0; i--)
1753  {
1754  ttisp = &sp->ttis[sp->types[i]];
1755  if (ttisp->tt_abbrind == abbrind)
1756  {
1757  *gmtoff = ttisp->tt_gmtoff;
1758  *isdst = ttisp->tt_isdst;
1759  return true;
1760  }
1761  }
1762 
1763  /*
1764  * Not there, so scan forwards to find the first one after.
1765  */
1766  for (i = cutoff; i < sp->timecnt; i++)
1767  {
1768  ttisp = &sp->ttis[sp->types[i]];
1769  if (ttisp->tt_abbrind == abbrind)
1770  {
1771  *gmtoff = ttisp->tt_gmtoff;
1772  *isdst = ttisp->tt_isdst;
1773  return true;
1774  }
1775  }
1776 
1777  return false; /* hm, not actually used in any interval? */
1778 }
1779 
1780 /*
1781  * If the given timezone uses only one GMT offset, store that offset
1782  * into *gmtoff and return true, else return false.
1783  */
1784 bool
1785 pg_get_timezone_offset(const pg_tz *tz, long int *gmtoff)
1786 {
1787  /*
1788  * The zone could have more than one ttinfo, if it's historically used
1789  * more than one abbreviation. We return true as long as they all have
1790  * the same gmtoff.
1791  */
1792  const struct state *sp;
1793  int i;
1794 
1795  sp = &tz->state;
1796  for (i = 1; i < sp->typecnt; i++)
1797  {
1798  if (sp->ttis[i].tt_gmtoff != sp->ttis[0].tt_gmtoff)
1799  return false;
1800  }
1801  *gmtoff = sp->ttis[0].tt_gmtoff;
1802  return true;
1803 }
1804 
1805 /*
1806  * Return the name of the current timezone
1807  */
1808 const char *
1810 {
1811  if (tz)
1812  return tz->TZname;
1813  return NULL;
1814 }
1815 
1816 /*
1817  * Check whether timezone is acceptable.
1818  *
1819  * What we are doing here is checking for leap-second-aware timekeeping.
1820  * We need to reject such TZ settings because they'll wreak havoc with our
1821  * date/time arithmetic.
1822  */
1823 bool
1825 {
1826  struct pg_tm *tt;
1827  pg_time_t time2000;
1828 
1829  /*
1830  * To detect leap-second timekeeping, run pg_localtime for what should be
1831  * GMT midnight, 2000-01-01. Insist that the tm_sec value be zero; any
1832  * other result has to be due to leap seconds.
1833  */
1835  tt = pg_localtime(&time2000, tz);
1836  if (!tt || tt->tm_sec != 0)
1837  return false;
1838 
1839  return true;
1840 }
#define AVGSECSPERYEAR
Definition: private.h:164
#define TZDEFAULT
Definition: tzfile.h:24
static void gmtload(struct state *sp)
Definition: localtime.c:1199
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
Definition: localtime.c:1293
#define SECSPERMIN
Definition: private.h:107
static int typecnt
Definition: zic.c:184
#define swap(a, b)
Definition: qsort.c:94
static const char * getoffset(const char *strp, int32 *offsetp)
Definition: localtime.c:707
static void init_ttinfo(struct ttinfo *s, int32 gmtoff, bool isdst, int abbrind)
Definition: localtime.c:108
int64 pg_time_t
Definition: pgtime.h:23
int tm_wday
Definition: pgtime.h:33
bool pg_tz_acceptable(pg_tz *tz)
Definition: localtime.c:1824
#define WILDABBR
Definition: localtime.c:46
int tm_isdst
Definition: pgtime.h:35
int tzload(const char *name, char *canonname, struct state *sp, bool doextend)
Definition: localtime.c:549
int charcnt
Definition: pgtz.h:46
static int32 detzcode(const char *codep)
Definition: localtime.c:118
int tm_hour
Definition: pgtime.h:29
static zic_t corr[TZ_MAX_LEAPS]
Definition: zic.c:383
bool goback
Definition: pgtz.h:47
static int tzloadbody(char const *name, char *canonname, struct state *sp, bool doextend, union local_storage *lsp)
Definition: localtime.c:211
int32 tt_gmtoff
Definition: pgtz.h:28
#define SECSPERDAY
Definition: private.h:114
static const char * getsecs(const char *strp, int32 *secsp)
Definition: localtime.c:667
#define isleap(y)
Definition: datetime.h:273
int leapcnt
Definition: pgtz.h:43
#define INITIALIZE(x)
Definition: private.h:98
Definition: pgtz.h:26
static const char * getrule(const char *strp, struct rule *rulep)
Definition: localtime.c:733
#define SECSPERHOUR
Definition: private.h:113
static const int mon_lengths[2][MONSPERYEAR]
Definition: localtime.c:588
#define MONSPERYEAR
Definition: private.h:115
#define HOURSPERDAY
Definition: private.h:109
#define TZ_MAX_TIMES
Definition: tzfile.h:93
return result
Definition: formatting.c:1618
#define DAYSPERNYEAR
Definition: private.h:111
struct tzhead tzhead
Definition: localtime.c:181
char tzh_timecnt[4]
Definition: tzfile.h:41
long int tm_gmtoff
Definition: pgtime.h:36
Definition: pgtime.h:25
r_type
Definition: localtime.c:68
int r_mon
Definition: localtime.c:80
pg_time_t ats[TZ_MAX_TIMES]
Definition: pgtz.h:49
#define TZDEFRULESTRING
Definition: localtime.c:64
#define is_digit(c)
Definition: private.h:49
Definition: localtime.c:75
signed int int32
Definition: c.h:256
#define DAYSPERLYEAR
Definition: private.h:112
static struct pg_tm tm
Definition: localtime.c:104
struct state st
Definition: localtime.c:200
#define malloc(a)
Definition: header.h:50
#define TZ_MAX_LEAPS
Definition: tzfile.h:101
int r_week
Definition: localtime.c:79
bool tt_isdst
Definition: pgtz.h:29
struct lsinfo lsis[TZ_MAX_LEAPS]
Definition: pgtz.h:54
static int64 detzcode64(const char *codep)
Definition: localtime.c:144
#define SECS_PER_DAY
Definition: timestamp.h:86
#define TM_YEAR_BASE
Definition: private.h:138
const char * pg_get_timezone_name(pg_tz *tz)
Definition: localtime.c:1809
#define DAYSPERWEEK
Definition: private.h:110
static const pg_time_t time_t_max
Definition: localtime.c:55
int64 ls_corr
Definition: pgtz.h:38
#define MINVAL(t, b)
Definition: private.h:82
char * c
int tm_mday
Definition: pgtime.h:30
#define memmove(d, s, c)
Definition: c.h:1058
int tm_mon
Definition: pgtime.h:31
static const pg_time_t time_t_min
Definition: localtime.c:54
static const char wildabbr[]
Definition: localtime.c:49
static int leapcnt
Definition: zic.c:167
#define SECSPERREPEAT_BITS
Definition: private.h:167
pg_time_t ls_trans
Definition: pgtz.h:37
char tzh_leapcnt[4]
Definition: tzfile.h:40
static bool typesequiv(struct state const *, int, int)
Definition: localtime.c:565
const char * tm_zone
Definition: pgtime.h:37
enum r_type r_type
Definition: localtime.c:77
int32 r_time
Definition: localtime.c:81
bool tzparse(const char *name, struct state *sp, bool lastditch)
Definition: localtime.c:890
char chars[BIGGEST(BIGGEST(TZ_MAX_CHARS+1, 3),(2 *(TZ_STRLEN_MAX+1)))]
Definition: pgtz.h:53
int r_day
Definition: localtime.c:78
static int32 transtime(int year, const struct rule *rulep, int32 offset)
Definition: localtime.c:793
#define TZ_MAX_CHARS
Definition: tzfile.h:98
#define EPOCH_YEAR
Definition: private.h:140
char buf[2 *sizeof(struct tzhead)+2 *sizeof(struct state)+4 *TZ_MAX_TIMES]
Definition: localtime.c:185
struct state state
Definition: pgtz.h:63
Definition: pgtz.h:59
struct ttinfo ttis[TZ_MAX_TYPES]
Definition: pgtz.h:51
unsigned char types[TZ_MAX_TIMES]
Definition: pgtz.h:50
Definition: tzfile.h:33
int pg_next_dst_boundary(const pg_time_t *timep, long int *before_gmtoff, int *before_isdst, pg_time_t *boundary, long int *after_gmtoff, int *after_isdst, const pg_tz *tz)
Definition: localtime.c:1544
char tzh_typecnt[4]
Definition: tzfile.h:42
#define free(a)
Definition: header.h:65
char tzh_version[1]
Definition: tzfile.h:36
#define NULL
Definition: c.h:229
char tzh_charcnt[4]
Definition: tzfile.h:43
Definition: regguts.h:298
#define TZDEFRULES
Definition: tzfile.h:25
static ptrdiff_t timecnt
Definition: zic.c:182
int timecnt
Definition: pgtz.h:44
bool pg_get_timezone_offset(const pg_tz *tz, long int *gmtoff)
Definition: localtime.c:1785
#define gmtptr
Definition: pgtz.h:35
#define EPOCH_WDAY
Definition: private.h:141
static int leaps_thru_end_of(const int y)
Definition: localtime.c:1344
static int charcnt
Definition: zic.c:163
char TZname[TZ_STRLEN_MAX+1]
Definition: pgtz.h:62
bool pg_interpret_timezone_abbrev(const char *abbrev, const pg_time_t *timep, long int *gmtoff, int *isdst, const pg_tz *tz)
Definition: localtime.c:1691
bool tt_ttisstd
Definition: pgtz.h:31
const char * name
Definition: encode.c:521
#define YEARSPERREPEAT
Definition: private.h:105
static bool increment_overflow_time(pg_time_t *, int32)
Definition: localtime.c:1507
#define MAXVAL(t, b)
Definition: private.h:79
static const char * getnum(const char *strp, int *nump, int min, int max)
Definition: localtime.c:638
static const int year_lengths[2]
Definition: localtime.c:593
union input_buffer u
Definition: localtime.c:197
static bool increment_overflow(int *, int)
Definition: localtime.c:1489
int tm_year
Definition: pgtime.h:32
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:382
#define TZ_MAX_TYPES
Definition: tzfile.h:96
int tt_abbrind
Definition: pgtz.h:30
char tzh_ttisstdcnt[4]
Definition: tzfile.h:39
#define TYPE_BIT(type)
Definition: private.h:70
int i
int pg_open_tzfile(const char *name, char *canonname)
Definition: findtimezone.c:64
static struct pg_tm * localsub(struct state const *sp, pg_time_t const *timep, struct pg_tm *tmp)
Definition: localtime.c:1213
int tm_yday
Definition: pgtime.h:34
#define UNIX_EPOCH_JDATE
Definition: timestamp.h:162
#define POSTGRES_EPOCH_JDATE
Definition: timestamp.h:163
struct pg_tm * pg_gmtime(const pg_time_t *timep)
Definition: localtime.c:1334
bool tt_ttisgmt
Definition: pgtz.h:32
bool goahead
Definition: pgtz.h:48
#define SECSPERREPEAT
Definition: private.h:165
static const char * getqzname(const char *strp, int delim)
Definition: localtime.c:622
static struct @121 value
#define TYPE_SIGNED(type)
Definition: private.h:71
#define close(a)
Definition: win32.h:12
int typecnt
Definition: pgtz.h:45
int tm_sec
Definition: pgtime.h:27
#define EOVERFLOW
Definition: private.h:38
static struct pg_tm * timesub(pg_time_t const *, int32, struct state const *, struct pg_tm *)
Definition: localtime.c:1351
static const char gmt[]
Definition: localtime.c:51
int tm_min
Definition: pgtime.h:28
#define MINSPERHOUR
Definition: private.h:108
#define read(a, b, c)
Definition: win32.h:13
static bool differ_by_repeat(const pg_time_t t1, const pg_time_t t0)
Definition: localtime.c:170
#define TWOS_COMPLEMENT(t)
Definition: private.h:72
static struct pg_tm * gmtsub(pg_time_t const *, int32, struct pg_tm *)
Definition: localtime.c:1305
int defaulttype
Definition: pgtz.h:55
static const char * getzname(const char *strp)
Definition: localtime.c:603
char tzh_ttisgmtcnt[4]
Definition: tzfile.h:38