LCOV - code coverage report
Current view: top level - src/bin/initdb - findtimezone.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta2 Lines: 101 206 49.0 %
Date: 2019-06-18 07:06:57 Functions: 11 14 78.6 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * findtimezone.c
       4             :  *    Functions for determining the default timezone to use.
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  *
       8             :  * IDENTIFICATION
       9             :  *    src/bin/initdb/findtimezone.c
      10             :  *
      11             :  *-------------------------------------------------------------------------
      12             :  */
      13             : #include "postgres_fe.h"
      14             : 
      15             : #include <fcntl.h>
      16             : #include <sys/stat.h>
      17             : #include <time.h>
      18             : #include <unistd.h>
      19             : 
      20             : #include "pgtz.h"
      21             : 
      22             : /* Ideally this would be in a .h file, but it hardly seems worth the trouble */
      23             : extern const char *select_default_timezone(const char *share_path);
      24             : 
      25             : 
      26             : #ifndef SYSTEMTZDIR
      27             : static char tzdirpath[MAXPGPATH];
      28             : #endif
      29             : 
      30             : 
      31             : /*
      32             :  * Return full pathname of timezone data directory
      33             :  *
      34             :  * In this file, tzdirpath is assumed to be set up by select_default_timezone.
      35             :  */
      36             : static const char *
      37        1272 : pg_TZDIR(void)
      38             : {
      39             : #ifndef SYSTEMTZDIR
      40             :     /* normal case: timezone stuff is under our share dir */
      41        1272 :     return tzdirpath;
      42             : #else
      43             :     /* we're configured to use system's timezone database */
      44             :     return SYSTEMTZDIR;
      45             : #endif
      46             : }
      47             : 
      48             : 
      49             : /*
      50             :  * Given a timezone name, open() the timezone data file.  Return the
      51             :  * file descriptor if successful, -1 if not.
      52             :  *
      53             :  * This is simpler than the backend function of the same name because
      54             :  * we assume that the input string has the correct case already, so there
      55             :  * is no need for case-folding.  (This is obviously true if we got the file
      56             :  * name from the filesystem to start with.  The only other place it can come
      57             :  * from is the environment variable TZ, and there seems no need to allow
      58             :  * case variation in that; other programs aren't likely to.)
      59             :  *
      60             :  * If "canonname" is not NULL, then on success the canonical spelling of the
      61             :  * given name is stored there (the buffer must be > TZ_STRLEN_MAX bytes!).
      62             :  * This is redundant but kept for compatibility with the backend code.
      63             :  */
      64             : int
      65        1272 : pg_open_tzfile(const char *name, char *canonname)
      66             : {
      67             :     char        fullname[MAXPGPATH];
      68             : 
      69        1272 :     if (canonname)
      70           0 :         strlcpy(canonname, name, TZ_STRLEN_MAX + 1);
      71             : 
      72        1272 :     strlcpy(fullname, pg_TZDIR(), sizeof(fullname));
      73        1272 :     if (strlen(fullname) + 1 + strlen(name) >= MAXPGPATH)
      74           0 :         return -1;              /* not gonna fit */
      75        1272 :     strcat(fullname, "/");
      76        1272 :     strcat(fullname, name);
      77             : 
      78        1272 :     return open(fullname, O_RDONLY | PG_BINARY, 0);
      79             : }
      80             : 
      81             : 
      82             : 
      83             : /*
      84             :  * Load a timezone definition.
      85             :  * Does not verify that the timezone is acceptable!
      86             :  *
      87             :  * This corresponds to the backend's pg_tzset(), except that we only support
      88             :  * one loaded timezone at a time.
      89             :  */
      90             : static pg_tz *
      91        1272 : pg_load_tz(const char *name)
      92             : {
      93             :     static pg_tz tz;
      94             : 
      95        1272 :     if (strlen(name) > TZ_STRLEN_MAX)
      96           0 :         return NULL;            /* not going to fit */
      97             : 
      98             :     /*
      99             :      * "GMT" is always sent to tzparse(); see comments for pg_tzset().
     100             :      */
     101        1272 :     if (strcmp(name, "GMT") == 0)
     102             :     {
     103           0 :         if (!tzparse(name, &tz.state, true))
     104             :         {
     105             :             /* This really, really should not happen ... */
     106           0 :             return NULL;
     107             :         }
     108             :     }
     109        1272 :     else if (tzload(name, NULL, &tz.state, true) != 0)
     110             :     {
     111         636 :         if (name[0] == ':' || !tzparse(name, &tz.state, false))
     112             :         {
     113         636 :             return NULL;        /* unknown timezone */
     114             :         }
     115             :     }
     116             : 
     117         636 :     strcpy(tz.TZname, name);
     118             : 
     119         636 :     return &tz;
     120             : }
     121             : 
     122             : 
     123             : /*
     124             :  * The following block of code attempts to determine which timezone in our
     125             :  * timezone database is the best match for the active system timezone.
     126             :  *
     127             :  * On most systems, we rely on trying to match the observable behavior of
     128             :  * the C library's localtime() function.  The database zone that matches
     129             :  * furthest into the past is the one to use.  Often there will be several
     130             :  * zones with identical rankings (since the IANA database assigns multiple
     131             :  * names to many zones).  We break ties by first checking for "preferred"
     132             :  * names (such as "UTC"), and then arbitrarily by preferring shorter, then
     133             :  * alphabetically earlier zone names.  (If we did not explicitly prefer
     134             :  * "UTC", we would get the alias name "UCT" instead due to alphabetic
     135             :  * ordering.)
     136             :  *
     137             :  * Many modern systems use the IANA database, so if we can determine the
     138             :  * system's idea of which zone it is using and its behavior matches our zone
     139             :  * of the same name, we can skip the rather-expensive search through all the
     140             :  * zones in our database.  This short-circuit path also ensures that we spell
     141             :  * the zone name the same way the system setting does, even in the presence
     142             :  * of multiple aliases for the same zone.
     143             :  *
     144             :  * Win32's native knowledge about timezones appears to be too incomplete
     145             :  * and too different from the IANA database for the above matching strategy
     146             :  * to be of any use. But there is just a limited number of timezones
     147             :  * available, so we can rely on a handmade mapping table instead.
     148             :  */
     149             : 
     150             : #ifndef WIN32
     151             : 
     152             : #define T_DAY   ((time_t) (60*60*24))
     153             : #define T_WEEK  ((time_t) (60*60*24*7))
     154             : #define T_MONTH ((time_t) (60*60*24*31))
     155             : 
     156             : #define MAX_TEST_TIMES (52*100) /* 100 years */
     157             : 
     158             : struct tztry
     159             : {
     160             :     int         n_test_times;
     161             :     time_t      test_times[MAX_TEST_TIMES];
     162             : };
     163             : 
     164             : static bool check_system_link_file(const char *linkname, struct tztry *tt,
     165             :                                    char *bestzonename);
     166             : static void scan_available_timezones(char *tzdir, char *tzdirsub,
     167             :                                      struct tztry *tt,
     168             :                                      int *bestscore, char *bestzonename);
     169             : 
     170             : 
     171             : /*
     172             :  * Get GMT offset from a system struct tm
     173             :  */
     174             : static int
     175           0 : get_timezone_offset(struct tm *tm)
     176             : {
     177             : #if defined(HAVE_STRUCT_TM_TM_ZONE)
     178           0 :     return tm->tm_gmtoff;
     179             : #elif defined(HAVE_INT_TIMEZONE)
     180             :     return -TIMEZONE_GLOBAL;
     181             : #else
     182             : #error No way to determine TZ? Can this happen?
     183             : #endif
     184             : }
     185             : 
     186             : /*
     187             :  * Convenience subroutine to convert y/m/d to time_t (NOT pg_time_t)
     188             :  */
     189             : static time_t
     190         636 : build_time_t(int year, int month, int day)
     191             : {
     192             :     struct tm   tm;
     193             : 
     194         636 :     memset(&tm, 0, sizeof(tm));
     195         636 :     tm.tm_mday = day;
     196         636 :     tm.tm_mon = month - 1;
     197         636 :     tm.tm_year = year - 1900;
     198             : 
     199         636 :     return mktime(&tm);
     200             : }
     201             : 
     202             : /*
     203             :  * Does a system tm value match one we computed ourselves?
     204             :  */
     205             : static bool
     206     1653600 : compare_tm(struct tm *s, struct pg_tm *p)
     207             : {
     208     3307200 :     if (s->tm_sec != p->tm_sec ||
     209     3307200 :         s->tm_min != p->tm_min ||
     210     3307200 :         s->tm_hour != p->tm_hour ||
     211     3307200 :         s->tm_mday != p->tm_mday ||
     212     3307200 :         s->tm_mon != p->tm_mon ||
     213     3307200 :         s->tm_year != p->tm_year ||
     214     3307200 :         s->tm_wday != p->tm_wday ||
     215     3307200 :         s->tm_yday != p->tm_yday ||
     216     1653600 :         s->tm_isdst != p->tm_isdst)
     217           0 :         return false;
     218     1653600 :     return true;
     219             : }
     220             : 
     221             : /*
     222             :  * See how well a specific timezone setting matches the system behavior
     223             :  *
     224             :  * We score a timezone setting according to the number of test times it
     225             :  * matches.  (The test times are ordered later-to-earlier, but this routine
     226             :  * doesn't actually know that; it just scans until the first non-match.)
     227             :  *
     228             :  * We return -1 for a completely unusable setting; this is worse than the
     229             :  * score of zero for a setting that works but matches not even the first
     230             :  * test time.
     231             :  */
     232             : static int
     233         954 : score_timezone(const char *tzname, struct tztry *tt)
     234             : {
     235             :     int         i;
     236             :     pg_time_t   pgtt;
     237             :     struct tm  *systm;
     238             :     struct pg_tm *pgtm;
     239             :     char        cbuf[TZ_STRLEN_MAX + 1];
     240             :     pg_tz      *tz;
     241             : 
     242             :     /* Load timezone definition */
     243         954 :     tz = pg_load_tz(tzname);
     244         954 :     if (!tz)
     245         636 :         return -1;              /* unrecognized zone name */
     246             : 
     247             :     /* Reject if leap seconds involved */
     248         318 :     if (!pg_tz_acceptable(tz))
     249             :     {
     250             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     251             :         fprintf(stderr, "Reject TZ \"%s\": uses leap seconds\n", tzname);
     252             : #endif
     253           0 :         return -1;
     254             :     }
     255             : 
     256             :     /* Check for match at all the test times */
     257     1653918 :     for (i = 0; i < tt->n_test_times; i++)
     258             :     {
     259     1653600 :         pgtt = (pg_time_t) (tt->test_times[i]);
     260     1653600 :         pgtm = pg_localtime(&pgtt, tz);
     261     1653600 :         if (!pgtm)
     262           0 :             return -1;          /* probably shouldn't happen */
     263     1653600 :         systm = localtime(&(tt->test_times[i]));
     264     1653600 :         if (!systm)
     265             :         {
     266             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     267             :             fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data\n",
     268             :                     tzname, i, (long) pgtt,
     269             :                     pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
     270             :                     pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
     271             :                     pgtm->tm_isdst ? "dst" : "std");
     272             : #endif
     273           0 :             return i;
     274             :         }
     275     1653600 :         if (!compare_tm(systm, pgtm))
     276             :         {
     277             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     278             :             fprintf(stderr, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s\n",
     279             :                     tzname, i, (long) pgtt,
     280             :                     pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
     281             :                     pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
     282             :                     pgtm->tm_isdst ? "dst" : "std",
     283             :                     systm->tm_year + 1900, systm->tm_mon + 1, systm->tm_mday,
     284             :                     systm->tm_hour, systm->tm_min, systm->tm_sec,
     285             :                     systm->tm_isdst ? "dst" : "std");
     286             : #endif
     287           0 :             return i;
     288             :         }
     289     1653600 :         if (systm->tm_isdst >= 0)
     290             :         {
     291             :             /* Check match of zone names, too */
     292     1653600 :             if (pgtm->tm_zone == NULL)
     293           0 :                 return -1;      /* probably shouldn't happen */
     294     1653600 :             memset(cbuf, 0, sizeof(cbuf));
     295     1653600 :             strftime(cbuf, sizeof(cbuf) - 1, "%Z", systm);    /* zone abbr */
     296     1653600 :             if (strcmp(cbuf, pgtm->tm_zone) != 0)
     297             :             {
     298             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     299             :                 fprintf(stderr, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"\n",
     300             :                         tzname, i, (long) pgtt,
     301             :                         pgtm->tm_zone, cbuf);
     302             : #endif
     303           0 :                 return i;
     304             :             }
     305             :         }
     306             :     }
     307             : 
     308             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     309             :     fprintf(stderr, "TZ \"%s\" gets max score %d\n", tzname, i);
     310             : #endif
     311             : 
     312         318 :     return i;
     313             : }
     314             : 
     315             : /*
     316             :  * Test whether given zone name is a perfect match to localtime() behavior
     317             :  */
     318             : static bool
     319         954 : perfect_timezone_match(const char *tzname, struct tztry *tt)
     320             : {
     321         954 :     return (score_timezone(tzname, tt) == tt->n_test_times);
     322             : }
     323             : 
     324             : 
     325             : /*
     326             :  * Try to identify a timezone name (in our terminology) that best matches the
     327             :  * observed behavior of the system localtime() function.
     328             :  */
     329             : static const char *
     330         318 : identify_system_timezone(void)
     331             : {
     332             :     static char resultbuf[TZ_STRLEN_MAX + 1];
     333             :     time_t      tnow;
     334             :     time_t      t;
     335             :     struct tztry tt;
     336             :     struct tm  *tm;
     337             :     int         thisyear;
     338             :     int         bestscore;
     339             :     char        tmptzdir[MAXPGPATH];
     340             :     int         std_ofs;
     341             :     char        std_zone_name[TZ_STRLEN_MAX + 1],
     342             :                 dst_zone_name[TZ_STRLEN_MAX + 1];
     343             :     char        cbuf[TZ_STRLEN_MAX + 1];
     344             : 
     345             :     /* Initialize OS timezone library */
     346         318 :     tzset();
     347             : 
     348             :     /*
     349             :      * Set up the list of dates to be probed to see how well our timezone
     350             :      * matches the system zone.  We first probe January and July of the
     351             :      * current year; this serves to quickly eliminate the vast majority of the
     352             :      * TZ database entries.  If those dates match, we probe every week for 100
     353             :      * years backwards from the current July.  (Weekly resolution is good
     354             :      * enough to identify DST transition rules, since everybody switches on
     355             :      * Sundays.)  This is sufficient to cover most of the Unix time_t range,
     356             :      * and we don't want to look further than that since many systems won't
     357             :      * have sane TZ behavior further back anyway.  The further back the zone
     358             :      * matches, the better we score it.  This may seem like a rather random
     359             :      * way of doing things, but experience has shown that system-supplied
     360             :      * timezone definitions are likely to have DST behavior that is right for
     361             :      * the recent past and not so accurate further back. Scoring in this way
     362             :      * allows us to recognize zones that have some commonality with the IANA
     363             :      * database, without insisting on exact match. (Note: we probe Thursdays,
     364             :      * not Sundays, to avoid triggering DST-transition bugs in localtime
     365             :      * itself.)
     366             :      */
     367         318 :     tnow = time(NULL);
     368         318 :     tm = localtime(&tnow);
     369         318 :     if (!tm)
     370           0 :         return NULL;            /* give up if localtime is broken... */
     371         318 :     thisyear = tm->tm_year + 1900;
     372             : 
     373         318 :     t = build_time_t(thisyear, 1, 15);
     374             : 
     375             :     /*
     376             :      * Round back to GMT midnight Thursday.  This depends on the knowledge
     377             :      * that the time_t origin is Thu Jan 01 1970.  (With a different origin
     378             :      * we'd be probing some other day of the week, but it wouldn't matter
     379             :      * anyway unless localtime() had DST-transition bugs.)
     380             :      */
     381         318 :     t -= (t % T_WEEK);
     382             : 
     383         318 :     tt.n_test_times = 0;
     384         318 :     tt.test_times[tt.n_test_times++] = t;
     385             : 
     386         318 :     t = build_time_t(thisyear, 7, 15);
     387         318 :     t -= (t % T_WEEK);
     388             : 
     389         318 :     tt.test_times[tt.n_test_times++] = t;
     390             : 
     391     1653600 :     while (tt.n_test_times < MAX_TEST_TIMES)
     392             :     {
     393     1652964 :         t -= T_WEEK;
     394     1652964 :         tt.test_times[tt.n_test_times++] = t;
     395             :     }
     396             : 
     397             :     /*
     398             :      * Try to avoid the brute-force search by seeing if we can recognize the
     399             :      * system's timezone setting directly.
     400             :      *
     401             :      * Currently we just check /etc/localtime; there are other conventions for
     402             :      * this, but that seems to be the only one used on enough platforms to be
     403             :      * worth troubling over.
     404             :      */
     405         318 :     if (check_system_link_file("/etc/localtime", &tt, resultbuf))
     406         318 :         return resultbuf;
     407             : 
     408             :     /* No luck, so search for the best-matching timezone file */
     409           0 :     strlcpy(tmptzdir, pg_TZDIR(), sizeof(tmptzdir));
     410           0 :     bestscore = -1;
     411           0 :     resultbuf[0] = '\0';
     412           0 :     scan_available_timezones(tmptzdir, tmptzdir + strlen(tmptzdir) + 1,
     413             :                              &tt,
     414             :                              &bestscore, resultbuf);
     415           0 :     if (bestscore > 0)
     416             :     {
     417             :         /* Ignore IANA's rather silly "Factory" zone; use GMT instead */
     418           0 :         if (strcmp(resultbuf, "Factory") == 0)
     419           0 :             return NULL;
     420           0 :         return resultbuf;
     421             :     }
     422             : 
     423             :     /*
     424             :      * Couldn't find a match in the database, so next we try constructed zone
     425             :      * names (like "PST8PDT").
     426             :      *
     427             :      * First we need to determine the names of the local standard and daylight
     428             :      * zones.  The idea here is to scan forward from today until we have seen
     429             :      * both zones, if both are in use.
     430             :      */
     431           0 :     memset(std_zone_name, 0, sizeof(std_zone_name));
     432           0 :     memset(dst_zone_name, 0, sizeof(dst_zone_name));
     433           0 :     std_ofs = 0;
     434             : 
     435           0 :     tnow = time(NULL);
     436             : 
     437             :     /*
     438             :      * Round back to a GMT midnight so results don't depend on local time of
     439             :      * day
     440             :      */
     441           0 :     tnow -= (tnow % T_DAY);
     442             : 
     443             :     /*
     444             :      * We have to look a little further ahead than one year, in case today is
     445             :      * just past a DST boundary that falls earlier in the year than the next
     446             :      * similar boundary.  Arbitrarily scan up to 14 months.
     447             :      */
     448           0 :     for (t = tnow; t <= tnow + T_MONTH * 14; t += T_MONTH)
     449             :     {
     450           0 :         tm = localtime(&t);
     451           0 :         if (!tm)
     452           0 :             continue;
     453           0 :         if (tm->tm_isdst < 0)
     454           0 :             continue;
     455           0 :         if (tm->tm_isdst == 0 && std_zone_name[0] == '\0')
     456             :         {
     457             :             /* found STD zone */
     458           0 :             memset(cbuf, 0, sizeof(cbuf));
     459           0 :             strftime(cbuf, sizeof(cbuf) - 1, "%Z", tm); /* zone abbr */
     460           0 :             strcpy(std_zone_name, cbuf);
     461           0 :             std_ofs = get_timezone_offset(tm);
     462             :         }
     463           0 :         if (tm->tm_isdst > 0 && dst_zone_name[0] == '\0')
     464             :         {
     465             :             /* found DST zone */
     466           0 :             memset(cbuf, 0, sizeof(cbuf));
     467           0 :             strftime(cbuf, sizeof(cbuf) - 1, "%Z", tm); /* zone abbr */
     468           0 :             strcpy(dst_zone_name, cbuf);
     469             :         }
     470             :         /* Done if found both */
     471           0 :         if (std_zone_name[0] && dst_zone_name[0])
     472           0 :             break;
     473             :     }
     474             : 
     475             :     /* We should have found a STD zone name by now... */
     476           0 :     if (std_zone_name[0] == '\0')
     477             :     {
     478             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     479             :         fprintf(stderr, "could not determine system time zone\n");
     480             : #endif
     481           0 :         return NULL;            /* go to GMT */
     482             :     }
     483             : 
     484             :     /* If we found DST then try STD<ofs>DST */
     485           0 :     if (dst_zone_name[0] != '\0')
     486             :     {
     487           0 :         snprintf(resultbuf, sizeof(resultbuf), "%s%d%s",
     488           0 :                  std_zone_name, -std_ofs / 3600, dst_zone_name);
     489           0 :         if (score_timezone(resultbuf, &tt) > 0)
     490           0 :             return resultbuf;
     491             :     }
     492             : 
     493             :     /* Try just the STD timezone (works for GMT at least) */
     494           0 :     strcpy(resultbuf, std_zone_name);
     495           0 :     if (score_timezone(resultbuf, &tt) > 0)
     496           0 :         return resultbuf;
     497             : 
     498             :     /* Try STD<ofs> */
     499           0 :     snprintf(resultbuf, sizeof(resultbuf), "%s%d",
     500           0 :              std_zone_name, -std_ofs / 3600);
     501           0 :     if (score_timezone(resultbuf, &tt) > 0)
     502           0 :         return resultbuf;
     503             : 
     504             :     /*
     505             :      * Did not find the timezone.  Fallback to use a GMT zone.  Note that the
     506             :      * IANA timezone database names the GMT-offset zones in POSIX style: plus
     507             :      * is west of Greenwich.  It's unfortunate that this is opposite of SQL
     508             :      * conventions.  Should we therefore change the names? Probably not...
     509             :      */
     510           0 :     snprintf(resultbuf, sizeof(resultbuf), "Etc/GMT%s%d",
     511           0 :              (-std_ofs > 0) ? "+" : "", -std_ofs / 3600);
     512             : 
     513             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     514             :     fprintf(stderr, "could not recognize system time zone, using \"%s\"\n",
     515             :             resultbuf);
     516             : #endif
     517           0 :     return resultbuf;
     518             : }
     519             : 
     520             : /*
     521             :  * Examine a system-provided symlink file to see if it tells us the timezone.
     522             :  *
     523             :  * Unfortunately, there is little standardization of how the system default
     524             :  * timezone is determined in the absence of a TZ environment setting.
     525             :  * But a common strategy is to create a symlink at a well-known place.
     526             :  * If "linkname" identifies a readable symlink, and the tail of its contents
     527             :  * matches a zone name we know, and the actual behavior of localtime() agrees
     528             :  * with what we think that zone means, then we may use that zone name.
     529             :  *
     530             :  * We insist on a perfect behavioral match, which might not happen if the
     531             :  * system has a different IANA database version than we do; but in that case
     532             :  * it seems best to fall back to the brute-force search.
     533             :  *
     534             :  * linkname is the symlink file location to probe.
     535             :  *
     536             :  * tt tells about the system timezone behavior we need to match.
     537             :  *
     538             :  * If we successfully identify a zone name, store it in *bestzonename and
     539             :  * return true; else return false.  bestzonename must be a buffer of length
     540             :  * TZ_STRLEN_MAX + 1.
     541             :  */
     542             : static bool
     543         318 : check_system_link_file(const char *linkname, struct tztry *tt,
     544             :                        char *bestzonename)
     545             : {
     546             : #ifdef HAVE_READLINK
     547             :     char        link_target[MAXPGPATH];
     548             :     int         len;
     549             :     const char *cur_name;
     550             : 
     551             :     /*
     552             :      * Try to read the symlink.  If not there, not a symlink, etc etc, just
     553             :      * quietly fail; the precise reason needn't concern us.
     554             :      */
     555         318 :     len = readlink(linkname, link_target, sizeof(link_target));
     556         318 :     if (len < 0 || len >= sizeof(link_target))
     557           0 :         return false;
     558         318 :     link_target[len] = '\0';
     559             : 
     560             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     561             :     fprintf(stderr, "symbolic link \"%s\" contains \"%s\"\n",
     562             :             linkname, link_target);
     563             : #endif
     564             : 
     565             :     /*
     566             :      * The symlink is probably of the form "/path/to/zones/zone/name", or
     567             :      * possibly it is a relative path.  Nobody puts their zone DB directly in
     568             :      * the root directory, so we can definitely skip the first component; but
     569             :      * after that it's trial-and-error to identify which path component begins
     570             :      * the zone name.
     571             :      */
     572         318 :     cur_name = link_target;
     573        1272 :     while (*cur_name)
     574             :     {
     575             :         /* Advance to next segment of path */
     576         954 :         cur_name = strchr(cur_name + 1, '/');
     577         954 :         if (cur_name == NULL)
     578           0 :             break;
     579             :         /* If there are consecutive slashes, skip all, as the kernel would */
     580             :         do
     581             :         {
     582         954 :             cur_name++;
     583         954 :         } while (*cur_name == '/');
     584             : 
     585             :         /*
     586             :          * Test remainder of path to see if it is a matching zone name.
     587             :          * Relative paths might contain ".."; we needn't bother testing if the
     588             :          * first component is that.  Also defend against overlength names.
     589             :          */
     590        1908 :         if (*cur_name && *cur_name != '.' &&
     591        1908 :             strlen(cur_name) <= TZ_STRLEN_MAX &&
     592         954 :             perfect_timezone_match(cur_name, tt))
     593             :         {
     594             :             /* Success! */
     595         318 :             strcpy(bestzonename, cur_name);
     596         318 :             return true;
     597             :         }
     598             :     }
     599             : 
     600             :     /* Couldn't extract a matching zone name */
     601           0 :     return false;
     602             : #else
     603             :     /* No symlinks?  Forget it */
     604             :     return false;
     605             : #endif
     606             : }
     607             : 
     608             : /*
     609             :  * Given a timezone name, determine whether it should be preferred over other
     610             :  * names which are equally good matches. The output is arbitrary but we will
     611             :  * use 0 for "neutral" default preference.
     612             :  *
     613             :  * Ideally we'd prefer the zone.tab/zone1970.tab names, since in general those
     614             :  * are the ones offered to the user to select from. But for the moment, to
     615             :  * minimize changes in behaviour, simply prefer UTC over alternative spellings
     616             :  * such as UCT that otherwise cause confusion. The existing "shortest first"
     617             :  * rule would prefer "UTC" over "Etc/UTC" so keep that the same way (while
     618             :  * still preferring Etc/UTC over Etc/UCT).
     619             :  */
     620             : static int
     621           0 : zone_name_pref(const char *zonename)
     622             : {
     623           0 :     if (strcmp(zonename, "UTC") == 0)
     624           0 :         return 50;
     625           0 :     if (strcmp(zonename, "Etc/UTC") == 0)
     626           0 :         return 40;
     627           0 :     return 0;
     628             : }
     629             : 
     630             : /*
     631             :  * Recursively scan the timezone database looking for the best match to
     632             :  * the system timezone behavior.
     633             :  *
     634             :  * tzdir points to a buffer of size MAXPGPATH.  On entry, it holds the
     635             :  * pathname of a directory containing TZ files.  We internally modify it
     636             :  * to hold pathnames of sub-directories and files, but must restore it
     637             :  * to its original contents before exit.
     638             :  *
     639             :  * tzdirsub points to the part of tzdir that represents the subfile name
     640             :  * (ie, tzdir + the original directory name length, plus one for the
     641             :  * first added '/').
     642             :  *
     643             :  * tt tells about the system timezone behavior we need to match.
     644             :  *
     645             :  * *bestscore and *bestzonename on entry hold the best score found so far
     646             :  * and the name of the best zone.  We overwrite them if we find a better
     647             :  * score.  bestzonename must be a buffer of length TZ_STRLEN_MAX + 1.
     648             :  */
     649             : static void
     650           0 : scan_available_timezones(char *tzdir, char *tzdirsub, struct tztry *tt,
     651             :                          int *bestscore, char *bestzonename)
     652             : {
     653           0 :     int         tzdir_orig_len = strlen(tzdir);
     654             :     char      **names;
     655             :     char      **namep;
     656             : 
     657           0 :     names = pgfnames(tzdir);
     658           0 :     if (!names)
     659           0 :         return;
     660             : 
     661           0 :     for (namep = names; *namep; namep++)
     662             :     {
     663           0 :         char       *name = *namep;
     664             :         struct stat statbuf;
     665             : 
     666             :         /* Ignore . and .., plus any other "hidden" files */
     667           0 :         if (name[0] == '.')
     668           0 :             continue;
     669             : 
     670           0 :         snprintf(tzdir + tzdir_orig_len, MAXPGPATH - tzdir_orig_len,
     671             :                  "/%s", name);
     672             : 
     673           0 :         if (stat(tzdir, &statbuf) != 0)
     674             :         {
     675             : #ifdef DEBUG_IDENTIFY_TIMEZONE
     676             :             fprintf(stderr, "could not stat \"%s\": %s\n",
     677             :                     tzdir, strerror(errno));
     678             : #endif
     679           0 :             tzdir[tzdir_orig_len] = '\0';
     680           0 :             continue;
     681             :         }
     682             : 
     683           0 :         if (S_ISDIR(statbuf.st_mode))
     684             :         {
     685             :             /* Recurse into subdirectory */
     686           0 :             scan_available_timezones(tzdir, tzdirsub, tt,
     687             :                                      bestscore, bestzonename);
     688             :         }
     689             :         else
     690             :         {
     691             :             /* Load and test this file */
     692           0 :             int         score = score_timezone(tzdirsub, tt);
     693             : 
     694           0 :             if (score > *bestscore)
     695             :             {
     696           0 :                 *bestscore = score;
     697           0 :                 strlcpy(bestzonename, tzdirsub, TZ_STRLEN_MAX + 1);
     698             :             }
     699           0 :             else if (score == *bestscore)
     700             :             {
     701             :                 /* Consider how to break a tie */
     702           0 :                 int     namepref = (zone_name_pref(tzdirsub) -
     703           0 :                                     zone_name_pref(bestzonename));
     704           0 :                 if (namepref > 0 ||
     705           0 :                     (namepref == 0 &&
     706           0 :                      (strlen(tzdirsub) < strlen(bestzonename) ||
     707           0 :                       (strlen(tzdirsub) == strlen(bestzonename) &&
     708           0 :                        strcmp(tzdirsub, bestzonename) < 0))))
     709           0 :                     strlcpy(bestzonename, tzdirsub, TZ_STRLEN_MAX + 1);
     710             :             }
     711             :         }
     712             : 
     713             :         /* Restore tzdir */
     714           0 :         tzdir[tzdir_orig_len] = '\0';
     715             :     }
     716             : 
     717           0 :     pgfnames_cleanup(names);
     718             : }
     719             : #else                           /* WIN32 */
     720             : 
     721             : static const struct
     722             : {
     723             :     const char *stdname;        /* Windows name of standard timezone */
     724             :     const char *dstname;        /* Windows name of daylight timezone */
     725             :     const char *pgtzname;       /* Name of pgsql timezone to map to */
     726             : }           win32_tzmap[] =
     727             : 
     728             : {
     729             :     /*
     730             :      * This list was built from the contents of the registry at
     731             :      * HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time
     732             :      * Zones on Windows 10 and Windows 7.
     733             :      *
     734             :      * The zones have been matched to IANA timezones by looking at the cities
     735             :      * listed in the win32 display name (in the comment here) in most cases.
     736             :      */
     737             :     {
     738             :         "Afghanistan Standard Time", "Afghanistan Daylight Time",
     739             :         "Asia/Kabul"
     740             :     },                          /* (UTC+04:30) Kabul */
     741             :     {
     742             :         "Alaskan Standard Time", "Alaskan Daylight Time",
     743             :         "US/Alaska"
     744             :     },                          /* (UTC-09:00) Alaska */
     745             :     {
     746             :         "Aleutian Standard Time", "Aleutian Daylight Time",
     747             :         "US/Aleutan"
     748             :     },                          /* (UTC-10:00) Aleutian Islands */
     749             :     {
     750             :         "Altai Standard Time", "Altai Daylight Time",
     751             :         "Asia/Barnaul"
     752             :     },                          /* (UTC+07:00) Barnaul, Gorno-Altaysk */
     753             :     {
     754             :         "Arab Standard Time", "Arab Daylight Time",
     755             :         "Asia/Kuwait"
     756             :     },                          /* (UTC+03:00) Kuwait, Riyadh */
     757             :     {
     758             :         "Arabian Standard Time", "Arabian Daylight Time",
     759             :         "Asia/Muscat"
     760             :     },                          /* (UTC+04:00) Abu Dhabi, Muscat */
     761             :     {
     762             :         "Arabic Standard Time", "Arabic Daylight Time",
     763             :         "Asia/Baghdad"
     764             :     },                          /* (UTC+03:00) Baghdad */
     765             :     {
     766             :         "Argentina Standard Time", "Argentina Daylight Time",
     767             :         "America/Buenos_Aires"
     768             :     },                          /* (UTC-03:00) City of Buenos Aires */
     769             :     {
     770             :         "Armenian Standard Time", "Armenian Daylight Time",
     771             :         "Asia/Yerevan"
     772             :     },                          /* (UTC+04:00) Baku, Tbilisi, Yerevan */
     773             :     {
     774             :         "Astrakhan Standard Time", "Astrakhan Daylight Time",
     775             :         "Europe/Astrakhan"
     776             :     },                          /* (UTC+04:00) Astrakhan, Ulyanovsk */
     777             :     {
     778             :         "Atlantic Standard Time", "Atlantic Daylight Time",
     779             :         "Canada/Atlantic"
     780             :     },                          /* (UTC-04:00) Atlantic Time (Canada) */
     781             :     {
     782             :         "AUS Central Standard Time", "AUS Central Daylight Time",
     783             :         "Australia/Darwin"
     784             :     },                          /* (UTC+09:30) Darwin */
     785             :     {
     786             :         "Aus Central W. Standard Time", "Aus Central W. Daylight Time",
     787             :         "Australia/Eucla"
     788             :     },                          /* (UTC+08:45) Eucla */
     789             :     {
     790             :         "AUS Eastern Standard Time", "AUS Eastern Daylight Time",
     791             :         "Australia/Canberra"
     792             :     },                          /* (UTC+10:00) Canberra, Melbourne, Sydney */
     793             :     {
     794             :         "Azerbaijan Standard Time", "Azerbaijan Daylight Time",
     795             :         "Asia/Baku"
     796             :     },                          /* (UTC+04:00) Baku */
     797             :     {
     798             :         "Azores Standard Time", "Azores Daylight Time",
     799             :         "Atlantic/Azores"
     800             :     },                          /* (UTC-01:00) Azores */
     801             :     {
     802             :         "Bahia Standard Time", "Bahia Daylight Time",
     803             :         "America/Salvador"
     804             :     },                          /* (UTC-03:00) Salvador */
     805             :     {
     806             :         "Bangladesh Standard Time", "Bangladesh Daylight Time",
     807             :         "Asia/Dhaka"
     808             :     },                          /* (UTC+06:00) Dhaka */
     809             :     {
     810             :         "Bougainville Standard Time", "Bougainville Daylight Time",
     811             :         "Pacific/Bougainville"
     812             :     },                          /* (UTC+11:00) Bougainville Island */
     813             :     {
     814             :         "Belarus Standard Time", "Belarus Daylight Time",
     815             :         "Europe/Minsk"
     816             :     },                          /* (UTC+03:00) Minsk */
     817             :     {
     818             :         "Cabo Verde Standard Time", "Cabo Verde Daylight Time",
     819             :         "Atlantic/Cape_Verde"
     820             :     },                          /* (UTC-01:00) Cabo Verde Is. */
     821             :     {
     822             :         "Chatham Islands Standard Time", "Chatham Islands Daylight Time",
     823             :         "Pacific/Chatham"
     824             :     },                          /* (UTC+12:45) Chatham Islands */
     825             :     {
     826             :         "Canada Central Standard Time", "Canada Central Daylight Time",
     827             :         "Canada/Saskatchewan"
     828             :     },                          /* (UTC-06:00) Saskatchewan */
     829             :     {
     830             :         "Cape Verde Standard Time", "Cape Verde Daylight Time",
     831             :         "Atlantic/Cape_Verde"
     832             :     },                          /* (UTC-01:00) Cape Verde Is. */
     833             :     {
     834             :         "Caucasus Standard Time", "Caucasus Daylight Time",
     835             :         "Asia/Baku"
     836             :     },                          /* (UTC+04:00) Yerevan */
     837             :     {
     838             :         "Cen. Australia Standard Time", "Cen. Australia Daylight Time",
     839             :         "Australia/Adelaide"
     840             :     },                          /* (UTC+09:30) Adelaide */
     841             :     /* Central America (other than Mexico) generally does not observe DST */
     842             :     {
     843             :         "Central America Standard Time", "Central America Daylight Time",
     844             :         "CST6"
     845             :     },                          /* (UTC-06:00) Central America */
     846             :     {
     847             :         "Central Asia Standard Time", "Central Asia Daylight Time",
     848             :         "Asia/Dhaka"
     849             :     },                          /* (UTC+06:00) Astana */
     850             :     {
     851             :         "Central Brazilian Standard Time", "Central Brazilian Daylight Time",
     852             :         "America/Cuiaba"
     853             :     },                          /* (UTC-04:00) Cuiaba */
     854             :     {
     855             :         "Central Europe Standard Time", "Central Europe Daylight Time",
     856             :         "Europe/Belgrade"
     857             :     },                          /* (UTC+01:00) Belgrade, Bratislava, Budapest,
     858             :                                  * Ljubljana, Prague */
     859             :     {
     860             :         "Central European Standard Time", "Central European Daylight Time",
     861             :         "Europe/Sarajevo"
     862             :     },                          /* (UTC+01:00) Sarajevo, Skopje, Warsaw,
     863             :                                  * Zagreb */
     864             :     {
     865             :         "Central Pacific Standard Time", "Central Pacific Daylight Time",
     866             :         "Pacific/Noumea"
     867             :     },                          /* (UTC+11:00) Solomon Is., New Caledonia */
     868             :     {
     869             :         "Central Standard Time", "Central Daylight Time",
     870             :         "US/Central"
     871             :     },                          /* (UTC-06:00) Central Time (US & Canada) */
     872             :     {
     873             :         "Central Standard Time (Mexico)", "Central Daylight Time (Mexico)",
     874             :         "America/Mexico_City"
     875             :     },                          /* (UTC-06:00) Guadalajara, Mexico City,
     876             :                                  * Monterrey */
     877             :     {
     878             :         "China Standard Time", "China Daylight Time",
     879             :         "Asia/Hong_Kong"
     880             :     },                          /* (UTC+08:00) Beijing, Chongqing, Hong Kong,
     881             :                                  * Urumqi */
     882             :     {
     883             :         "Cuba Standard Time", "Cuba Daylight Time",
     884             :         "America/Havana"
     885             :     },                          /* (UTC-05:00) Havana */
     886             :     {
     887             :         "Dateline Standard Time", "Dateline Daylight Time",
     888             :         "Etc/UTC+12"
     889             :     },                          /* (UTC-12:00) International Date Line West */
     890             :     {
     891             :         "E. Africa Standard Time", "E. Africa Daylight Time",
     892             :         "Africa/Nairobi"
     893             :     },                          /* (UTC+03:00) Nairobi */
     894             :     {
     895             :         "E. Australia Standard Time", "E. Australia Daylight Time",
     896             :         "Australia/Brisbane"
     897             :     },                          /* (UTC+10:00) Brisbane */
     898             :     {
     899             :         "E. Europe Standard Time", "E. Europe Daylight Time",
     900             :         "Europe/Bucharest"
     901             :     },                          /* (UTC+02:00) E. Europe */
     902             :     {
     903             :         "E. South America Standard Time", "E. South America Daylight Time",
     904             :         "America/Araguaina"
     905             :     },                          /* (UTC-03:00) Brasilia */
     906             :     {
     907             :         "Eastern Standard Time", "Eastern Daylight Time",
     908             :         "US/Eastern"
     909             :     },                          /* (UTC-05:00) Eastern Time (US & Canada) */
     910             :     {
     911             :         "Eastern Standard Time (Mexico)", "Eastern Daylight Time (Mexico)",
     912             :         "America/Mexico_City"
     913             :     },                          /* (UTC-05:00) Chetumal */
     914             :     {
     915             :         "Easter Island Standard Time", "Easter Island Daylight Time",
     916             :         "Pacific/Easter"
     917             :     },                          /* (UTC-06:00) Easter Island */
     918             :     {
     919             :         "Egypt Standard Time", "Egypt Daylight Time",
     920             :         "Africa/Cairo"
     921             :     },                          /* (UTC+02:00) Cairo */
     922             :     {
     923             :         "Ekaterinburg Standard Time (RTZ 4)", "Ekaterinburg Daylight Time",
     924             :         "Asia/Yekaterinburg"
     925             :     },                          /* (UTC+05:00) Ekaterinburg */
     926             :     {
     927             :         "Fiji Standard Time", "Fiji Daylight Time",
     928             :         "Pacific/Fiji"
     929             :     },                          /* (UTC+12:00) Fiji */
     930             :     {
     931             :         "FLE Standard Time", "FLE Daylight Time",
     932             :         "Europe/Helsinki"
     933             :     },                          /* (UTC+02:00) Helsinki, Kyiv, Riga, Sofia,
     934             :                                  * Tallinn, Vilnius */
     935             :     {
     936             :         "Georgian Standard Time", "Georgian Daylight Time",
     937             :         "Asia/Tbilisi"
     938             :     },                          /* (UTC+04:00) Tbilisi */
     939             :     {
     940             :         "GMT Standard Time", "GMT Daylight Time",
     941             :         "Europe/London"
     942             :     },                          /* (UTC) Dublin, Edinburgh, Lisbon, London */
     943             :     {
     944             :         "Greenland Standard Time", "Greenland Daylight Time",
     945             :         "America/Godthab"
     946             :     },                          /* (UTC-03:00) Greenland */
     947             :     {
     948             :         "Greenwich Standard Time", "Greenwich Daylight Time",
     949             :         "Africa/Casablanca"
     950             :     },                          /* (UTC) Monrovia, Reykjavik */
     951             :     {
     952             :         "GTB Standard Time", "GTB Daylight Time",
     953             :         "Europe/Athens"
     954             :     },                          /* (UTC+02:00) Athens, Bucharest */
     955             :     {
     956             :         "Haiti Standard Time", "Haiti Daylight Time",
     957             :         "US/Eastern"
     958             :     },                          /* (UTC-05:00) Haiti */
     959             :     {
     960             :         "Hawaiian Standard Time", "Hawaiian Daylight Time",
     961             :         "US/Hawaii"
     962             :     },                          /* (UTC-10:00) Hawaii */
     963             :     {
     964             :         "India Standard Time", "India Daylight Time",
     965             :         "Asia/Calcutta"
     966             :     },                          /* (UTC+05:30) Chennai, Kolkata, Mumbai, New
     967             :                                  * Delhi */
     968             :     {
     969             :         "Iran Standard Time", "Iran Daylight Time",
     970             :         "Asia/Tehran"
     971             :     },                          /* (UTC+03:30) Tehran */
     972             :     {
     973             :         "Jerusalem Standard Time", "Jerusalem Daylight Time",
     974             :         "Asia/Jerusalem"
     975             :     },                          /* (UTC+02:00) Jerusalem */
     976             :     {
     977             :         "Jordan Standard Time", "Jordan Daylight Time",
     978             :         "Asia/Amman"
     979             :     },                          /* (UTC+02:00) Amman */
     980             :     {
     981             :         "Kamchatka Standard Time", "Kamchatka Daylight Time",
     982             :         "Asia/Kamchatka"
     983             :     },                          /* (UTC+12:00) Petropavlovsk-Kamchatsky - Old */
     984             :     {
     985             :         "Korea Standard Time", "Korea Daylight Time",
     986             :         "Asia/Seoul"
     987             :     },                          /* (UTC+09:00) Seoul */
     988             :     {
     989             :         "Libya Standard Time", "Libya Daylight Time",
     990             :         "Africa/Tripoli"
     991             :     },                          /* (UTC+02:00) Tripoli */
     992             :     {
     993             :         "Line Islands Standard Time", "Line Islands Daylight Time",
     994             :         "Pacific/Kiritimati"
     995             :     },                          /* (UTC+14:00) Kiritimati Island */
     996             :     {
     997             :         "Lord Howe Standard Time", "Lord Howe Daylight Time",
     998             :         "Australia/Lord_Howe"
     999             :     },                          /* (UTC+10:30) Lord Howe Island */
    1000             :     {
    1001             :         "Magadan Standard Time", "Magadan Daylight Time",
    1002             :         "Asia/Magadan"
    1003             :     },                          /* (UTC+10:00) Magadan */
    1004             :     {
    1005             :         "Marquesas Standard Time", "Marquesas Daylight Time",
    1006             :         "Pacific/Marquesas"
    1007             :     },                          /* (UTC-09:30) Marquesas Islands */
    1008             :     {
    1009             :         "Mauritius Standard Time", "Mauritius Daylight Time",
    1010             :         "Indian/Mauritius"
    1011             :     },                          /* (UTC+04:00) Port Louis */
    1012             :     {
    1013             :         "Mexico Standard Time", "Mexico Daylight Time",
    1014             :         "America/Mexico_City"
    1015             :     },                          /* (UTC-06:00) Guadalajara, Mexico City,
    1016             :                                  * Monterrey */
    1017             :     {
    1018             :         "Mexico Standard Time 2", "Mexico Daylight Time 2",
    1019             :         "America/Chihuahua"
    1020             :     },                          /* (UTC-07:00) Chihuahua, La Paz, Mazatlan */
    1021             :     {
    1022             :         "Mid-Atlantic Standard Time", "Mid-Atlantic Daylight Time",
    1023             :         "Atlantic/South_Georgia"
    1024             :     },                          /* (UTC-02:00) Mid-Atlantic - Old */
    1025             :     {
    1026             :         "Middle East Standard Time", "Middle East Daylight Time",
    1027             :         "Asia/Beirut"
    1028             :     },                          /* (UTC+02:00) Beirut */
    1029             :     {
    1030             :         "Montevideo Standard Time", "Montevideo Daylight Time",
    1031             :         "America/Montevideo"
    1032             :     },                          /* (UTC-03:00) Montevideo */
    1033             :     {
    1034             :         "Morocco Standard Time", "Morocco Daylight Time",
    1035             :         "Africa/Casablanca"
    1036             :     },                          /* (UTC) Casablanca */
    1037             :     {
    1038             :         "Mountain Standard Time", "Mountain Daylight Time",
    1039             :         "US/Mountain"
    1040             :     },                          /* (UTC-07:00) Mountain Time (US & Canada) */
    1041             :     {
    1042             :         "Mountain Standard Time (Mexico)", "Mountain Daylight Time (Mexico)",
    1043             :         "America/Chihuahua"
    1044             :     },                          /* (UTC-07:00) Chihuahua, La Paz, Mazatlan */
    1045             :     {
    1046             :         "Myanmar Standard Time", "Myanmar Daylight Time",
    1047             :         "Asia/Rangoon"
    1048             :     },                          /* (UTC+06:30) Yangon (Rangoon) */
    1049             :     {
    1050             :         "N. Central Asia Standard Time", "N. Central Asia Daylight Time",
    1051             :         "Asia/Novosibirsk"
    1052             :     },                          /* (UTC+06:00) Novosibirsk (RTZ 5) */
    1053             :     {
    1054             :         "Namibia Standard Time", "Namibia Daylight Time",
    1055             :         "Africa/Windhoek"
    1056             :     },                          /* (UTC+01:00) Windhoek */
    1057             :     {
    1058             :         "Nepal Standard Time", "Nepal Daylight Time",
    1059             :         "Asia/Katmandu"
    1060             :     },                          /* (UTC+05:45) Kathmandu */
    1061             :     {
    1062             :         "New Zealand Standard Time", "New Zealand Daylight Time",
    1063             :         "Pacific/Auckland"
    1064             :     },                          /* (UTC+12:00) Auckland, Wellington */
    1065             :     {
    1066             :         "Newfoundland Standard Time", "Newfoundland Daylight Time",
    1067             :         "Canada/Newfoundland"
    1068             :     },                          /* (UTC-03:30) Newfoundland */
    1069             :     {
    1070             :         "Norfolk Standard Time", "Norfolk Daylight Time",
    1071             :         "Pacific/Norfolk"
    1072             :     },                          /* (UTC+11:00) Norfolk Island */
    1073             :     {
    1074             :         "North Asia East Standard Time", "North Asia East Daylight Time",
    1075             :         "Asia/Irkutsk"
    1076             :     },                          /* (UTC+08:00) Irkutsk, Ulaan Bataar */
    1077             :     {
    1078             :         "North Asia Standard Time", "North Asia Daylight Time",
    1079             :         "Asia/Krasnoyarsk"
    1080             :     },                          /* (UTC+07:00) Krasnoyarsk */
    1081             :     {
    1082             :         "North Korea Standard Time", "North Korea Daylight Time",
    1083             :         "Asia/Pyongyang"
    1084             :     },                          /* (UTC+08:30) Pyongyang */
    1085             :     {
    1086             :         "Pacific SA Standard Time", "Pacific SA Daylight Time",
    1087             :         "America/Santiago"
    1088             :     },                          /* (UTC-03:00) Santiago */
    1089             :     {
    1090             :         "Pacific Standard Time", "Pacific Daylight Time",
    1091             :         "US/Pacific"
    1092             :     },                          /* (UTC-08:00) Pacific Time (US & Canada) */
    1093             :     {
    1094             :         "Pacific Standard Time (Mexico)", "Pacific Daylight Time (Mexico)",
    1095             :         "America/Tijuana"
    1096             :     },                          /* (UTC-08:00) Baja California */
    1097             :     {
    1098             :         "Pakistan Standard Time", "Pakistan Daylight Time",
    1099             :         "Asia/Karachi"
    1100             :     },                          /* (UTC+05:00) Islamabad, Karachi */
    1101             :     {
    1102             :         "Paraguay Standard Time", "Paraguay Daylight Time",
    1103             :         "America/Asuncion"
    1104             :     },                          /* (UTC-04:00) Asuncion */
    1105             :     {
    1106             :         "Romance Standard Time", "Romance Daylight Time",
    1107             :         "Europe/Brussels"
    1108             :     },                          /* (UTC+01:00) Brussels, Copenhagen, Madrid,
    1109             :                                  * Paris */
    1110             :     {
    1111             :         "Russia TZ 1 Standard Time", "Russia TZ 1 Daylight Time",
    1112             :         "Europe/Kaliningrad"
    1113             :     },                          /* (UTC+02:00) Kaliningrad (RTZ 1) */
    1114             :     {
    1115             :         "Russia TZ 2 Standard Time", "Russia TZ 2 Daylight Time",
    1116             :         "Europe/Moscow"
    1117             :     },                          /* (UTC+03:00) Moscow, St. Petersburg,
    1118             :                                  * Volgograd (RTZ 2) */
    1119             :     {
    1120             :         "Russia TZ 3 Standard Time", "Russia TZ 3 Daylight Time",
    1121             :         "Europe/Samara"
    1122             :     },                          /* (UTC+04:00) Izhevsk, Samara (RTZ 3) */
    1123             :     {
    1124             :         "Russia TZ 4 Standard Time", "Russia TZ 4 Daylight Time",
    1125             :         "Asia/Yekaterinburg"
    1126             :     },                          /* (UTC+05:00) Ekaterinburg (RTZ 4) */
    1127             :     {
    1128             :         "Russia TZ 5 Standard Time", "Russia TZ 5 Daylight Time",
    1129             :         "Asia/Novosibirsk"
    1130             :     },                          /* (UTC+06:00) Novosibirsk (RTZ 5) */
    1131             :     {
    1132             :         "Russia TZ 6 Standard Time", "Russia TZ 6 Daylight Time",
    1133             :         "Asia/Krasnoyarsk"
    1134             :     },                          /* (UTC+07:00) Krasnoyarsk (RTZ 6) */
    1135             :     {
    1136             :         "Russia TZ 7 Standard Time", "Russia TZ 7 Daylight Time",
    1137             :         "Asia/Irkutsk"
    1138             :     },                          /* (UTC+08:00) Irkutsk (RTZ 7) */
    1139             :     {
    1140             :         "Russia TZ 8 Standard Time", "Russia TZ 8 Daylight Time",
    1141             :         "Asia/Yakutsk"
    1142             :     },                          /* (UTC+09:00) Yakutsk (RTZ 8) */
    1143             :     {
    1144             :         "Russia TZ 9 Standard Time", "Russia TZ 9 Daylight Time",
    1145             :         "Asia/Vladivostok"
    1146             :     },                          /* (UTC+10:00) Vladivostok, Magadan (RTZ 9) */
    1147             :     {
    1148             :         "Russia TZ 10 Standard Time", "Russia TZ 10 Daylight Time",
    1149             :         "Asia/Magadan"
    1150             :     },                          /* (UTC+11:00) Chokurdakh (RTZ 10) */
    1151             :     {
    1152             :         "Russia TZ 11 Standard Time", "Russia TZ 11 Daylight Time",
    1153             :         "Asia/Anadyr"
    1154             :     },                          /* (UTC+12:00) Anadyr,
    1155             :                                  * Petropavlovsk-Kamchatsky (RTZ 11) */
    1156             :     {
    1157             :         "Russian Standard Time", "Russian Daylight Time",
    1158             :         "Europe/Moscow"
    1159             :     },                          /* (UTC+03:00) Moscow, St. Petersburg,
    1160             :                                  * Volgograd */
    1161             :     {
    1162             :         "SA Eastern Standard Time", "SA Eastern Daylight Time",
    1163             :         "America/Buenos_Aires"
    1164             :     },                          /* (UTC-03:00) Cayenne, Fortaleza */
    1165             :     {
    1166             :         "SA Pacific Standard Time", "SA Pacific Daylight Time",
    1167             :         "America/Bogota"
    1168             :     },                          /* (UTC-05:00) Bogota, Lima, Quito, Rio Branco */
    1169             :     {
    1170             :         "SA Western Standard Time", "SA Western Daylight Time",
    1171             :         "America/Caracas"
    1172             :     },                          /* (UTC-04:00) Georgetown, La Paz, Manaus, San
    1173             :                                  * Juan */
    1174             :     {
    1175             :         "Saint Pierre Standard Time", "Saint Pierre Daylight Time",
    1176             :         "America/Miquelon"
    1177             :     },                          /* (UTC-03:00) Saint Pierre and Miquelon */
    1178             :     {
    1179             :         "Samoa Standard Time", "Samoa Daylight Time",
    1180             :         "Pacific/Samoa"
    1181             :     },                          /* (UTC+13:00) Samoa */
    1182             :     {
    1183             :         "SE Asia Standard Time", "SE Asia Daylight Time",
    1184             :         "Asia/Bangkok"
    1185             :     },                          /* (UTC+07:00) Bangkok, Hanoi, Jakarta */
    1186             :     {
    1187             :         "Malay Peninsula Standard Time", "Malay Peninsula Daylight Time",
    1188             :         "Asia/Kuala_Lumpur"
    1189             :     },                          /* (UTC+08:00) Kuala Lumpur, Singapore */
    1190             :     {
    1191             :         "Sakhalin Standard Time", "Sakhalin Daylight Time",
    1192             :         "Asia/Sakhalin"
    1193             :     },                          /* (UTC+11:00) Sakhalin */
    1194             :     {
    1195             :         "South Africa Standard Time", "South Africa Daylight Time",
    1196             :         "Africa/Harare"
    1197             :     },                          /* (UTC+02:00) Harare, Pretoria */
    1198             :     {
    1199             :         "Sri Lanka Standard Time", "Sri Lanka Daylight Time",
    1200             :         "Asia/Colombo"
    1201             :     },                          /* (UTC+05:30) Sri Jayawardenepura */
    1202             :     {
    1203             :         "Syria Standard Time", "Syria Daylight Time",
    1204             :         "Asia/Damascus"
    1205             :     },                          /* (UTC+02:00) Damascus */
    1206             :     {
    1207             :         "Taipei Standard Time", "Taipei Daylight Time",
    1208             :         "Asia/Taipei"
    1209             :     },                          /* (UTC+08:00) Taipei */
    1210             :     {
    1211             :         "Tasmania Standard Time", "Tasmania Daylight Time",
    1212             :         "Australia/Hobart"
    1213             :     },                          /* (UTC+10:00) Hobart */
    1214             :     {
    1215             :         "Tocantins Standard Time", "Tocantins Daylight Time",
    1216             :         "America/Araguaina"
    1217             :     },                          /* (UTC-03:00) Araguaina */
    1218             :     {
    1219             :         "Tokyo Standard Time", "Tokyo Daylight Time",
    1220             :         "Asia/Tokyo"
    1221             :     },                          /* (UTC+09:00) Osaka, Sapporo, Tokyo */
    1222             :     {
    1223             :         "Tonga Standard Time", "Tonga Daylight Time",
    1224             :         "Pacific/Tongatapu"
    1225             :     },                          /* (UTC+13:00) Nuku'alofa */
    1226             :     {
    1227             :         "Tomsk Standard Time", "Tomsk Daylight Time",
    1228             :         "Asia/Tomsk"
    1229             :     },                          /* (UTC+07:00) Tomsk */
    1230             :     {
    1231             :         "Transbaikal Standard Time", "Transbaikal Daylight Time",
    1232             :         "Asia/Chita"
    1233             :     },                          /* (UTC+09:00) Chita */
    1234             :     {
    1235             :         "Turkey Standard Time", "Turkey Daylight Time",
    1236             :         "Europe/Istanbul"
    1237             :     },                          /* (UTC+02:00) Istanbul */
    1238             :     {
    1239             :         "Turks and Caicos Standard Time", "Turks and Caicos Daylight Time",
    1240             :         "America/Grand_Turk"
    1241             :     },                          /* (UTC-04:00) Turks and Caicos */
    1242             :     {
    1243             :         "Ulaanbaatar Standard Time", "Ulaanbaatar Daylight Time",
    1244             :         "Asia/Ulaanbaatar",
    1245             :     },                          /* (UTC+08:00) Ulaanbaatar */
    1246             :     {
    1247             :         "US Eastern Standard Time", "US Eastern Daylight Time",
    1248             :         "US/Eastern"
    1249             :     },                          /* (UTC-05:00) Indiana (East) */
    1250             :     {
    1251             :         "US Mountain Standard Time", "US Mountain Daylight Time",
    1252             :         "US/Arizona"
    1253             :     },                          /* (UTC-07:00) Arizona */
    1254             :     {
    1255             :         "Coordinated Universal Time", "Coordinated Universal Time",
    1256             :         "UTC"
    1257             :     },                          /* (UTC) Coordinated Universal Time */
    1258             :     {
    1259             :         "UTC+12", "UTC+12",
    1260             :         "Etc/GMT+12"
    1261             :     },                          /* (UTC+12:00) Coordinated Universal Time+12 */
    1262             :     {
    1263             :         "UTC-02", "UTC-02",
    1264             :         "Etc/GMT-02"
    1265             :     },                          /* (UTC-02:00) Coordinated Universal Time-02 */
    1266             :     {
    1267             :         "UTC-08", "UTC-08",
    1268             :         "Etc/GMT-08"
    1269             :     },                          /* (UTC-08:00) Coordinated Universal Time-08 */
    1270             :     {
    1271             :         "UTC-09", "UTC-09",
    1272             :         "Etc/GMT-09"
    1273             :     },                          /* (UTC-09:00) Coordinated Universal Time-09 */
    1274             :     {
    1275             :         "UTC-11", "UTC-11",
    1276             :         "Etc/GMT-11"
    1277             :     },                          /* (UTC-11:00) Coordinated Universal Time-11 */
    1278             :     {
    1279             :         "Venezuela Standard Time", "Venezuela Daylight Time",
    1280             :         "America/Caracas",
    1281             :     },                          /* (UTC-04:30) Caracas */
    1282             :     {
    1283             :         "Vladivostok Standard Time", "Vladivostok Daylight Time",
    1284             :         "Asia/Vladivostok"
    1285             :     },                          /* (UTC+10:00) Vladivostok (RTZ 9) */
    1286             :     {
    1287             :         "W. Australia Standard Time", "W. Australia Daylight Time",
    1288             :         "Australia/Perth"
    1289             :     },                          /* (UTC+08:00) Perth */
    1290             : #ifdef NOT_USED
    1291             :     /* Could not find a match for this one (just a guess). Excluded for now. */
    1292             :     {
    1293             :         "W. Central Africa Standard Time", "W. Central Africa Daylight Time",
    1294             :         "WAT"
    1295             :     },                          /* (UTC+01:00) West Central Africa */
    1296             : #endif
    1297             :     {
    1298             :         "W. Europe Standard Time", "W. Europe Daylight Time",
    1299             :         "CET"
    1300             :     },                          /* (UTC+01:00) Amsterdam, Berlin, Bern, Rome,
    1301             :                                  * Stockholm, Vienna */
    1302             :     {
    1303             :         "W. Mongolia Standard Time", "W. Mongolia Daylight Time",
    1304             :         "Asia/Hovd"
    1305             :     },                          /* (UTC+07:00) Hovd */
    1306             :     {
    1307             :         "West Asia Standard Time", "West Asia Daylight Time",
    1308             :         "Asia/Karachi"
    1309             :     },                          /* (UTC+05:00) Ashgabat, Tashkent */
    1310             :     {
    1311             :         "West Bank Gaza Standard Time", "West Bank Gaza Daylight Time",
    1312             :         "Asia/Gaza"
    1313             :     },                          /* (UTC+02:00) Gaza, Hebron */
    1314             :     {
    1315             :         "West Pacific Standard Time", "West Pacific Daylight Time",
    1316             :         "Pacific/Guam"
    1317             :     },                          /* (UTC+10:00) Guam, Port Moresby */
    1318             :     {
    1319             :         "Yakutsk Standard Time", "Yakutsk Daylight Time",
    1320             :         "Asia/Yakutsk"
    1321             :     },                          /* (UTC+09:00) Yakutsk */
    1322             :     {
    1323             :         NULL, NULL, NULL
    1324             :     }
    1325             : };
    1326             : 
    1327             : static const char *
    1328             : identify_system_timezone(void)
    1329             : {
    1330             :     int         i;
    1331             :     char        tzname[128];
    1332             :     char        localtzname[256];
    1333             :     time_t      t = time(NULL);
    1334             :     struct tm  *tm = localtime(&t);
    1335             :     HKEY        rootKey;
    1336             :     int         idx;
    1337             : 
    1338             :     if (!tm)
    1339             :     {
    1340             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1341             :         fprintf(stderr, "could not identify system time zone: localtime() failed\n");
    1342             : #endif
    1343             :         return NULL;            /* go to GMT */
    1344             :     }
    1345             : 
    1346             :     memset(tzname, 0, sizeof(tzname));
    1347             :     strftime(tzname, sizeof(tzname) - 1, "%Z", tm);
    1348             : 
    1349             :     for (i = 0; win32_tzmap[i].stdname != NULL; i++)
    1350             :     {
    1351             :         if (strcmp(tzname, win32_tzmap[i].stdname) == 0 ||
    1352             :             strcmp(tzname, win32_tzmap[i].dstname) == 0)
    1353             :         {
    1354             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1355             :             fprintf(stderr, "TZ \"%s\" matches system time zone \"%s\"\n",
    1356             :                     win32_tzmap[i].pgtzname, tzname);
    1357             : #endif
    1358             :             return win32_tzmap[i].pgtzname;
    1359             :         }
    1360             :     }
    1361             : 
    1362             :     /*
    1363             :      * Localized Windows versions return localized names for the timezone.
    1364             :      * Scan the registry to find the English name, and then try matching
    1365             :      * against our table again.
    1366             :      */
    1367             :     memset(localtzname, 0, sizeof(localtzname));
    1368             :     if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
    1369             :                      "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
    1370             :                      0,
    1371             :                      KEY_READ,
    1372             :                      &rootKey) != ERROR_SUCCESS)
    1373             :     {
    1374             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1375             :         fprintf(stderr, "could not open registry key to identify system time zone: error code %lu\n",
    1376             :                 GetLastError());
    1377             : #endif
    1378             :         return NULL;            /* go to GMT */
    1379             :     }
    1380             : 
    1381             :     for (idx = 0;; idx++)
    1382             :     {
    1383             :         char        keyname[256];
    1384             :         char        zonename[256];
    1385             :         DWORD       namesize;
    1386             :         FILETIME    lastwrite;
    1387             :         HKEY        key;
    1388             :         LONG        r;
    1389             : 
    1390             :         memset(keyname, 0, sizeof(keyname));
    1391             :         namesize = sizeof(keyname);
    1392             :         if ((r = RegEnumKeyEx(rootKey,
    1393             :                               idx,
    1394             :                               keyname,
    1395             :                               &namesize,
    1396             :                               NULL,
    1397             :                               NULL,
    1398             :                               NULL,
    1399             :                               &lastwrite)) != ERROR_SUCCESS)
    1400             :         {
    1401             :             if (r == ERROR_NO_MORE_ITEMS)
    1402             :                 break;
    1403             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1404             :             fprintf(stderr, "could not enumerate registry subkeys to identify system time zone: %d\n",
    1405             :                     (int) r);
    1406             : #endif
    1407             :             break;
    1408             :         }
    1409             : 
    1410             :         if ((r = RegOpenKeyEx(rootKey, keyname, 0, KEY_READ, &key)) != ERROR_SUCCESS)
    1411             :         {
    1412             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1413             :             fprintf(stderr, "could not open registry subkey to identify system time zone: %d\n",
    1414             :                     (int) r);
    1415             : #endif
    1416             :             break;
    1417             :         }
    1418             : 
    1419             :         memset(zonename, 0, sizeof(zonename));
    1420             :         namesize = sizeof(zonename);
    1421             :         if ((r = RegQueryValueEx(key, "Std", NULL, NULL, (unsigned char *) zonename, &namesize)) != ERROR_SUCCESS)
    1422             :         {
    1423             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1424             :             fprintf(stderr, "could not query value for key \"std\" to identify system time zone \"%s\": %d\n",
    1425             :                     keyname, (int) r);
    1426             : #endif
    1427             :             RegCloseKey(key);
    1428             :             continue;           /* Proceed to look at the next timezone */
    1429             :         }
    1430             :         if (strcmp(tzname, zonename) == 0)
    1431             :         {
    1432             :             /* Matched zone */
    1433             :             strcpy(localtzname, keyname);
    1434             :             RegCloseKey(key);
    1435             :             break;
    1436             :         }
    1437             :         memset(zonename, 0, sizeof(zonename));
    1438             :         namesize = sizeof(zonename);
    1439             :         if ((r = RegQueryValueEx(key, "Dlt", NULL, NULL, (unsigned char *) zonename, &namesize)) != ERROR_SUCCESS)
    1440             :         {
    1441             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1442             :             fprintf(stderr, "could not query value for key \"dlt\" to identify system time zone \"%s\": %d\n",
    1443             :                     keyname, (int) r);
    1444             : #endif
    1445             :             RegCloseKey(key);
    1446             :             continue;           /* Proceed to look at the next timezone */
    1447             :         }
    1448             :         if (strcmp(tzname, zonename) == 0)
    1449             :         {
    1450             :             /* Matched DST zone */
    1451             :             strcpy(localtzname, keyname);
    1452             :             RegCloseKey(key);
    1453             :             break;
    1454             :         }
    1455             : 
    1456             :         RegCloseKey(key);
    1457             :     }
    1458             : 
    1459             :     RegCloseKey(rootKey);
    1460             : 
    1461             :     if (localtzname[0])
    1462             :     {
    1463             :         /* Found a localized name, so scan for that one too */
    1464             :         for (i = 0; win32_tzmap[i].stdname != NULL; i++)
    1465             :         {
    1466             :             if (strcmp(localtzname, win32_tzmap[i].stdname) == 0 ||
    1467             :                 strcmp(localtzname, win32_tzmap[i].dstname) == 0)
    1468             :             {
    1469             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1470             :                 fprintf(stderr, "TZ \"%s\" matches localized system time zone \"%s\" (\"%s\")\n",
    1471             :                         win32_tzmap[i].pgtzname, tzname, localtzname);
    1472             : #endif
    1473             :                 return win32_tzmap[i].pgtzname;
    1474             :             }
    1475             :         }
    1476             :     }
    1477             : 
    1478             : #ifdef DEBUG_IDENTIFY_TIMEZONE
    1479             :     fprintf(stderr, "could not find a match for system time zone \"%s\"\n",
    1480             :             tzname);
    1481             : #endif
    1482             :     return NULL;                /* go to GMT */
    1483             : }
    1484             : #endif                          /* WIN32 */
    1485             : 
    1486             : 
    1487             : /*
    1488             :  * Return true if the given zone name is valid and is an "acceptable" zone.
    1489             :  */
    1490             : static bool
    1491         636 : validate_zone(const char *tzname)
    1492             : {
    1493             :     pg_tz      *tz;
    1494             : 
    1495         636 :     if (!tzname || !tzname[0])
    1496         318 :         return false;
    1497             : 
    1498         318 :     tz = pg_load_tz(tzname);
    1499         318 :     if (!tz)
    1500           0 :         return false;
    1501             : 
    1502         318 :     if (!pg_tz_acceptable(tz))
    1503           0 :         return false;
    1504             : 
    1505         318 :     return true;
    1506             : }
    1507             : 
    1508             : /*
    1509             :  * Identify a suitable default timezone setting based on the environment.
    1510             :  *
    1511             :  * The installation share_path must be passed in, as that is the default
    1512             :  * location for the timezone database directory.
    1513             :  *
    1514             :  * We first look to the TZ environment variable.  If not found or not
    1515             :  * recognized by our own code, we see if we can identify the timezone
    1516             :  * from the behavior of the system timezone library.  When all else fails,
    1517             :  * return NULL, indicating that we should default to GMT.
    1518             :  */
    1519             : const char *
    1520         318 : select_default_timezone(const char *share_path)
    1521             : {
    1522             :     const char *tzname;
    1523             : 
    1524             :     /* Initialize timezone directory path, if needed */
    1525             : #ifndef SYSTEMTZDIR
    1526         318 :     snprintf(tzdirpath, sizeof(tzdirpath), "%s/timezone", share_path);
    1527             : #endif
    1528             : 
    1529             :     /* Check TZ environment variable */
    1530         318 :     tzname = getenv("TZ");
    1531         318 :     if (validate_zone(tzname))
    1532           0 :         return tzname;
    1533             : 
    1534             :     /* Nope, so try to identify the system timezone */
    1535         318 :     tzname = identify_system_timezone();
    1536         318 :     if (validate_zone(tzname))
    1537         318 :         return tzname;
    1538             : 
    1539           0 :     return NULL;
    1540             : }

Generated by: LCOV version 1.13