LCOV - code coverage report
Current view: top level - src/bin/initdb - localtime.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 261 807 32.3 %
Date: 2021-12-05 01:09:12 Functions: 16 31 51.6 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14