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

Generated by: LCOV version 1.13