]> granicus.if.org Git - postgresql/blob - src/timezone/pgtz.c
Revert part of recent include patch not ready for application.
[postgresql] / src / timezone / pgtz.c
1 /*-------------------------------------------------------------------------
2  *
3  * pgtz.c
4  *        Timezone Library Integration Functions
5  *
6  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  *        $PostgreSQL: pgsql/src/timezone/pgtz.c,v 1.42 2006/07/14 04:59:30 momjian Exp $
10  *
11  *-------------------------------------------------------------------------
12  */
13 #define NO_REDEFINE_TIMEFUNCS
14
15 #include "postgres.h"
16
17 #include <ctype.h>
18 #include <sys/stat.h>
19 #include <time.h>
20
21 #include "miscadmin.h"
22 #include "pgtime.h"
23 #include "pgtz.h"
24 #include "storage/fd.h"
25 #include "tzfile.h"
26 #include "utils/datetime.h"
27 #include "utils/elog.h"
28 #include "utils/guc.h"
29 #include "utils/hsearch.h"
30
31 /* Current global timezone */
32 pg_tz      *global_timezone = NULL;
33
34
35 static char tzdir[MAXPGPATH];
36 static int      done_tzdir = 0;
37
38 static const char *identify_system_timezone(void);
39 static const char *select_default_timezone(void);
40 static bool set_global_timezone(const char *tzname);
41
42
43 /*
44  * Return full pathname of timezone data directory
45  */
46 char *
47 pg_TZDIR(void)
48 {
49         if (done_tzdir)
50                 return tzdir;
51
52         get_share_path(my_exec_path, tzdir);
53         strcat(tzdir, "/timezone");
54
55         done_tzdir = 1;
56         return tzdir;
57 }
58
59
60 /*
61  * The following block of code attempts to determine which timezone in our
62  * timezone database is the best match for the active system timezone.
63  *
64  * On most systems, we rely on trying to match the observable behavior of
65  * the C library's localtime() function.  The database zone that matches
66  * furthest into the past is the one to use.  Often there will be several
67  * zones with identical rankings (since the zic database assigns multiple
68  * names to many zones).  We break ties arbitrarily by preferring shorter,
69  * then alphabetically earlier zone names.
70  *
71  * Win32's native knowledge about timezones appears to be too incomplete
72  * and too different from the zic database for the above matching strategy
73  * to be of any use. But there is just a limited number of timezones
74  * available, so we can rely on a handmade mapping table instead.
75  */
76
77 #ifndef WIN32
78
79 #define T_DAY   ((time_t) (60*60*24))
80 #define T_WEEK  ((time_t) (60*60*24*7))
81 #define T_MONTH ((time_t) (60*60*24*31))
82
83 #define MAX_TEST_TIMES (52*100) /* 100 years, or 1904..2004 */
84
85 struct tztry
86 {
87         int                     n_test_times;
88         time_t          test_times[MAX_TEST_TIMES];
89 };
90
91 static void scan_available_timezones(char *tzdir, char *tzdirsub,
92                                                  struct tztry * tt,
93                                                  int *bestscore, char *bestzonename);
94
95
96 /*
97  * Get GMT offset from a system struct tm
98  */
99 static int
100 get_timezone_offset(struct tm * tm)
101 {
102 #if defined(HAVE_STRUCT_TM_TM_ZONE)
103         return tm->tm_gmtoff;
104 #elif defined(HAVE_INT_TIMEZONE)
105         return -TIMEZONE_GLOBAL;
106 #else
107 #error No way to determine TZ? Can this happen?
108 #endif
109 }
110
111 /*
112  * Convenience subroutine to convert y/m/d to time_t (NOT pg_time_t)
113  */
114 static time_t
115 build_time_t(int year, int month, int day)
116 {
117         struct tm       tm;
118
119         memset(&tm, 0, sizeof(tm));
120         tm.tm_mday = day;
121         tm.tm_mon = month - 1;
122         tm.tm_year = year - 1900;
123
124         return mktime(&tm);
125 }
126
127 /*
128  * Does a system tm value match one we computed ourselves?
129  */
130 static bool
131 compare_tm(struct tm * s, struct pg_tm * p)
132 {
133         if (s->tm_sec != p->tm_sec ||
134                 s->tm_min != p->tm_min ||
135                 s->tm_hour != p->tm_hour ||
136                 s->tm_mday != p->tm_mday ||
137                 s->tm_mon != p->tm_mon ||
138                 s->tm_year != p->tm_year ||
139                 s->tm_wday != p->tm_wday ||
140                 s->tm_yday != p->tm_yday ||
141                 s->tm_isdst != p->tm_isdst)
142                 return false;
143         return true;
144 }
145
146 /*
147  * See how well a specific timezone setting matches the system behavior
148  *
149  * We score a timezone setting according to the number of test times it
150  * matches.  (The test times are ordered later-to-earlier, but this routine
151  * doesn't actually know that; it just scans until the first non-match.)
152  *
153  * We return -1 for a completely unusable setting; this is worse than the
154  * score of zero for a setting that works but matches not even the first
155  * test time.
156  */
157 static int
158 score_timezone(const char *tzname, struct tztry * tt)
159 {
160         int                     i;
161         pg_time_t       pgtt;
162         struct tm  *systm;
163         struct pg_tm *pgtm;
164         char            cbuf[TZ_STRLEN_MAX + 1];
165         pg_tz           tz;
166
167
168         /*
169          * Load timezone directly. Don't use pg_tzset, because we don't want all
170          * timezones loaded in the cache at startup.
171          */
172         if (tzload(tzname, &tz.state) != 0)
173         {
174                 if (tzname[0] == ':' || tzparse(tzname, &tz.state, FALSE) != 0)
175                 {
176                         return -1;                      /* can't handle the TZ name at all */
177                 }
178         }
179
180         /* Reject if leap seconds involved */
181         if (!tz_acceptable(&tz))
182         {
183                 elog(DEBUG4, "Reject TZ \"%s\": uses leap seconds", tzname);
184                 return -1;
185         }
186
187         /* Check for match at all the test times */
188         for (i = 0; i < tt->n_test_times; i++)
189         {
190                 pgtt = (pg_time_t) (tt->test_times[i]);
191                 pgtm = pg_localtime(&pgtt, &tz);
192                 if (!pgtm)
193                         return -1;                      /* probably shouldn't happen */
194                 systm = localtime(&(tt->test_times[i]));
195                 if (!systm)
196                 {
197                         elog(DEBUG4, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s, system had no data",
198                                  tzname, i, (long) pgtt,
199                                  pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
200                                  pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
201                                  pgtm->tm_isdst ? "dst" : "std");
202                         return i;
203                 }
204                 if (!compare_tm(systm, pgtm))
205                 {
206                         elog(DEBUG4, "TZ \"%s\" scores %d: at %ld %04d-%02d-%02d %02d:%02d:%02d %s versus %04d-%02d-%02d %02d:%02d:%02d %s",
207                                  tzname, i, (long) pgtt,
208                                  pgtm->tm_year + 1900, pgtm->tm_mon + 1, pgtm->tm_mday,
209                                  pgtm->tm_hour, pgtm->tm_min, pgtm->tm_sec,
210                                  pgtm->tm_isdst ? "dst" : "std",
211                                  systm->tm_year + 1900, systm->tm_mon + 1, systm->tm_mday,
212                                  systm->tm_hour, systm->tm_min, systm->tm_sec,
213                                  systm->tm_isdst ? "dst" : "std");
214                         return i;
215                 }
216                 if (systm->tm_isdst >= 0)
217                 {
218                         /* Check match of zone names, too */
219                         if (pgtm->tm_zone == NULL)
220                                 return -1;              /* probably shouldn't happen */
221                         memset(cbuf, 0, sizeof(cbuf));
222                         strftime(cbuf, sizeof(cbuf) - 1, "%Z", systm);          /* zone abbr */
223                         if (strcmp(cbuf, pgtm->tm_zone) != 0)
224                         {
225                                 elog(DEBUG4, "TZ \"%s\" scores %d: at %ld \"%s\" versus \"%s\"",
226                                          tzname, i, (long) pgtt,
227                                          pgtm->tm_zone, cbuf);
228                                 return i;
229                         }
230                 }
231         }
232
233         elog(DEBUG4, "TZ \"%s\" gets max score %d", tzname, i);
234         return i;
235 }
236
237
238 /*
239  * Try to identify a timezone name (in our terminology) that best matches the
240  * observed behavior of the system timezone library.  We cannot assume that
241  * the system TZ environment setting (if indeed there is one) matches our
242  * terminology, so we ignore it and just look at what localtime() returns.
243  */
244 static const char *
245 identify_system_timezone(void)
246 {
247         static char resultbuf[TZ_STRLEN_MAX + 1];
248         time_t          tnow;
249         time_t          t;
250         struct tztry tt;
251         struct tm  *tm;
252         int                     bestscore;
253         char            tmptzdir[MAXPGPATH];
254         int                     std_ofs;
255         char            std_zone_name[TZ_STRLEN_MAX + 1],
256                                 dst_zone_name[TZ_STRLEN_MAX + 1];
257         char            cbuf[TZ_STRLEN_MAX + 1];
258
259         /* Initialize OS timezone library */
260         tzset();
261
262         /*
263          * Set up the list of dates to be probed to see how well our timezone
264          * matches the system zone.  We first probe January and July of 2004; this
265          * serves to quickly eliminate the vast majority of the TZ database
266          * entries.  If those dates match, we probe every week from 2004 backwards
267          * to late 1904.  (Weekly resolution is good enough to identify DST
268          * transition rules, since everybody switches on Sundays.)      The further
269          * back the zone matches, the better we score it.  This may seem like a
270          * rather random way of doing things, but experience has shown that
271          * system-supplied timezone definitions are likely to have DST behavior
272          * that is right for the recent past and not so accurate further back.
273          * Scoring in this way allows us to recognize zones that have some
274          * commonality with the zic database, without insisting on exact match.
275          * (Note: we probe Thursdays, not Sundays, to avoid triggering
276          * DST-transition bugs in localtime itself.)
277          */
278         tt.n_test_times = 0;
279         tt.test_times[tt.n_test_times++] = build_time_t(2004, 1, 15);
280         tt.test_times[tt.n_test_times++] = t = build_time_t(2004, 7, 15);
281         while (tt.n_test_times < MAX_TEST_TIMES)
282         {
283                 t -= T_WEEK;
284                 tt.test_times[tt.n_test_times++] = t;
285         }
286
287         /* Search for the best-matching timezone file */
288         strcpy(tmptzdir, pg_TZDIR());
289         bestscore = -1;
290         resultbuf[0] = '\0';
291         scan_available_timezones(tmptzdir, tmptzdir + strlen(tmptzdir) + 1,
292                                                          &tt,
293                                                          &bestscore, resultbuf);
294         if (bestscore > 0)
295                 return resultbuf;
296
297         /*
298          * Couldn't find a match in the database, so next we try constructed zone
299          * names (like "PST8PDT").
300          *
301          * First we need to determine the names of the local standard and daylight
302          * zones.  The idea here is to scan forward from today until we have seen
303          * both zones, if both are in use.
304          */
305         memset(std_zone_name, 0, sizeof(std_zone_name));
306         memset(dst_zone_name, 0, sizeof(dst_zone_name));
307         std_ofs = 0;
308
309         tnow = time(NULL);
310
311         /*
312          * Round back to a GMT midnight so results don't depend on local time of
313          * day
314          */
315         tnow -= (tnow % T_DAY);
316
317         /*
318          * We have to look a little further ahead than one year, in case today is
319          * just past a DST boundary that falls earlier in the year than the next
320          * similar boundary.  Arbitrarily scan up to 14 months.
321          */
322         for (t = tnow; t <= tnow + T_MONTH * 14; t += T_MONTH)
323         {
324                 tm = localtime(&t);
325                 if (!tm)
326                         continue;
327                 if (tm->tm_isdst < 0)
328                         continue;
329                 if (tm->tm_isdst == 0 && std_zone_name[0] == '\0')
330                 {
331                         /* found STD zone */
332                         memset(cbuf, 0, sizeof(cbuf));
333                         strftime(cbuf, sizeof(cbuf) - 1, "%Z", tm); /* zone abbr */
334                         strcpy(std_zone_name, cbuf);
335                         std_ofs = get_timezone_offset(tm);
336                 }
337                 if (tm->tm_isdst > 0 && dst_zone_name[0] == '\0')
338                 {
339                         /* found DST zone */
340                         memset(cbuf, 0, sizeof(cbuf));
341                         strftime(cbuf, sizeof(cbuf) - 1, "%Z", tm); /* zone abbr */
342                         strcpy(dst_zone_name, cbuf);
343                 }
344                 /* Done if found both */
345                 if (std_zone_name[0] && dst_zone_name[0])
346                         break;
347         }
348
349         /* We should have found a STD zone name by now... */
350         if (std_zone_name[0] == '\0')
351         {
352                 ereport(LOG,
353                                 (errmsg("unable to determine system timezone, defaulting to \"%s\"", "GMT"),
354                 errhint("You can specify the correct timezone in postgresql.conf.")));
355                 return NULL;                    /* go to GMT */
356         }
357
358         /* If we found DST then try STD<ofs>DST */
359         if (dst_zone_name[0] != '\0')
360         {
361                 snprintf(resultbuf, sizeof(resultbuf), "%s%d%s",
362                                  std_zone_name, -std_ofs / 3600, dst_zone_name);
363                 if (score_timezone(resultbuf, &tt) > 0)
364                         return resultbuf;
365         }
366
367         /* Try just the STD timezone (works for GMT at least) */
368         strcpy(resultbuf, std_zone_name);
369         if (score_timezone(resultbuf, &tt) > 0)
370                 return resultbuf;
371
372         /* Try STD<ofs> */
373         snprintf(resultbuf, sizeof(resultbuf), "%s%d",
374                          std_zone_name, -std_ofs / 3600);
375         if (score_timezone(resultbuf, &tt) > 0)
376                 return resultbuf;
377
378         /*
379          * Did not find the timezone.  Fallback to use a GMT zone.      Note that the
380          * zic timezone database names the GMT-offset zones in POSIX style: plus
381          * is west of Greenwich.  It's unfortunate that this is opposite of SQL
382          * conventions.  Should we therefore change the names? Probably not...
383          */
384         snprintf(resultbuf, sizeof(resultbuf), "Etc/GMT%s%d",
385                          (-std_ofs > 0) ? "+" : "", -std_ofs / 3600);
386
387         ereport(LOG,
388                  (errmsg("could not recognize system timezone, defaulting to \"%s\"",
389                                  resultbuf),
390            errhint("You can specify the correct timezone in postgresql.conf.")));
391         return resultbuf;
392 }
393
394 /*
395  * Recursively scan the timezone database looking for the best match to
396  * the system timezone behavior.
397  *
398  * tzdir points to a buffer of size MAXPGPATH.  On entry, it holds the
399  * pathname of a directory containing TZ files.  We internally modify it
400  * to hold pathnames of sub-directories and files, but must restore it
401  * to its original contents before exit.
402  *
403  * tzdirsub points to the part of tzdir that represents the subfile name
404  * (ie, tzdir + the original directory name length, plus one for the
405  * first added '/').
406  *
407  * tt tells about the system timezone behavior we need to match.
408  *
409  * *bestscore and *bestzonename on entry hold the best score found so far
410  * and the name of the best zone.  We overwrite them if we find a better
411  * score.  bestzonename must be a buffer of length TZ_STRLEN_MAX + 1.
412  */
413 static void
414 scan_available_timezones(char *tzdir, char *tzdirsub, struct tztry * tt,
415                                                  int *bestscore, char *bestzonename)
416 {
417         int                     tzdir_orig_len = strlen(tzdir);
418         DIR                *dirdesc;
419         struct dirent *direntry;
420
421         dirdesc = AllocateDir(tzdir);
422         if (!dirdesc)
423         {
424                 ereport(LOG,
425                                 (errcode_for_file_access(),
426                                  errmsg("could not open directory \"%s\": %m", tzdir)));
427                 return;
428         }
429
430         while ((direntry = ReadDir(dirdesc, tzdir)) != NULL)
431         {
432                 struct stat statbuf;
433
434                 /* Ignore . and .., plus any other "hidden" files */
435                 if (direntry->d_name[0] == '.')
436                         continue;
437
438                 snprintf(tzdir + tzdir_orig_len, MAXPGPATH - tzdir_orig_len,
439                                  "/%s", direntry->d_name);
440
441                 if (stat(tzdir, &statbuf) != 0)
442                 {
443                         ereport(LOG,
444                                         (errcode_for_file_access(),
445                                          errmsg("could not stat \"%s\": %m", tzdir)));
446                         tzdir[tzdir_orig_len] = '\0';
447                         continue;
448                 }
449
450                 if (S_ISDIR(statbuf.st_mode))
451                 {
452                         /* Recurse into subdirectory */
453                         scan_available_timezones(tzdir, tzdirsub, tt,
454                                                                          bestscore, bestzonename);
455                 }
456                 else
457                 {
458                         /* Load and test this file */
459                         int                     score = score_timezone(tzdirsub, tt);
460
461                         if (score > *bestscore)
462                         {
463                                 *bestscore = score;
464                                 StrNCpy(bestzonename, tzdirsub, TZ_STRLEN_MAX + 1);
465                         }
466                         else if (score == *bestscore)
467                         {
468                                 /* Consider how to break a tie */
469                                 if (strlen(tzdirsub) < strlen(bestzonename) ||
470                                         (strlen(tzdirsub) == strlen(bestzonename) &&
471                                          strcmp(tzdirsub, bestzonename) < 0))
472                                         StrNCpy(bestzonename, tzdirsub, TZ_STRLEN_MAX + 1);
473                         }
474                 }
475
476                 /* Restore tzdir */
477                 tzdir[tzdir_orig_len] = '\0';
478         }
479
480         FreeDir(dirdesc);
481 }
482 #else                                                   /* WIN32 */
483
484 static const struct
485 {
486         const char *stdname;            /* Windows name of standard timezone */
487         const char *dstname;            /* Windows name of daylight timezone */
488         const char *pgtzname;           /* Name of pgsql timezone to map to */
489 }       win32_tzmap[] =
490
491 {
492         /*
493          * This list was built from the contents of the registry at
494          * HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time
495          * Zones on Windows XP Professional SP1
496          *
497          * The zones have been matched to zic timezones by looking at the cities
498          * listed in the win32 display name (in the comment here) in most cases.
499          */
500         {
501                 "Afghanistan Standard Time", "Afghanistan Daylight Time",
502                 "Asia/Kabul"
503         },                                                      /* (GMT+04:30) Kabul */
504         {
505                 "Alaskan Standard Time", "Alaskan Daylight Time",
506                 "US/Alaska"
507         },                                                      /* (GMT-09:00) Alaska */
508         {
509                 "Arab Standard Time", "Arab Daylight Time",
510                 "Asia/Kuwait"
511         },                                                      /* (GMT+03:00) Kuwait, Riyadh */
512         {
513                 "Arabian Standard Time", "Arabian Daylight Time",
514                 "Asia/Muscat"
515         },                                                      /* (GMT+04:00) Abu Dhabi, Muscat */
516         {
517                 "Arabic Standard Time", "Arabic Daylight Time",
518                 "Asia/Baghdad"
519         },                                                      /* (GMT+03:00) Baghdad */
520         {
521                 "Atlantic Standard Time", "Atlantic Daylight Time",
522                 "Canada/Atlantic"
523         },                                                      /* (GMT-04:00) Atlantic Time (Canada) */
524         {
525                 "AUS Central Standard Time", "AUS Central Daylight Time",
526                 "Australia/Darwin"
527         },                                                      /* (GMT+09:30) Darwin */
528         {
529                 "AUS Eastern Standard Time", "AUS Eastern Daylight Time",
530                 "Australia/Canberra"
531         },                                                      /* (GMT+10:00) Canberra, Melbourne, Sydney */
532         {
533                 "Azores Standard Time", "Azores Daylight Time",
534                 "Atlantic/Azores"
535         },                                                      /* (GMT-01:00) Azores */
536         {
537                 "Canada Central Standard Time", "Canada Central Daylight Time",
538                 "Canada/Saskatchewan"
539         },                                                      /* (GMT-06:00) Saskatchewan */
540         {
541                 "Cape Verde Standard Time", "Cape Verde Daylight Time",
542                 "Atlantic/Cape_Verde"
543         },                                                      /* (GMT-01:00) Cape Verde Is. */
544         {
545                 "Caucasus Standard Time", "Caucasus Daylight Time",
546                 "Asia/Baku"
547         },                                                      /* (GMT+04:00) Baku, Tbilisi, Yerevan */
548         {
549                 "Cen. Australia Standard Time", "Cen. Australia Daylight Time",
550                 "Australia/Adelaide"
551         },                                                      /* (GMT+09:30) Adelaide */
552         {
553                 "Central America Standard Time", "Central America Daylight Time",
554                 "CST6CDT"
555         },                                                      /* (GMT-06:00) Central America */
556         {
557                 "Central Asia Standard Time", "Central Asia Daylight Time",
558                 "Asia/Dhaka"
559         },                                                      /* (GMT+06:00) Astana, Dhaka */
560         {
561                 "Central Europe Standard Time", "Central Europe Daylight Time",
562                 "Europe/Belgrade"
563         },                                                      /* (GMT+01:00) Belgrade, Bratislava, Budapest,
564                                                                  * Ljubljana, Prague */
565         {
566                 "Central European Standard Time", "Central European Daylight Time",
567                 "Europe/Sarajevo"
568         },                                                      /* (GMT+01:00) Sarajevo, Skopje, Warsaw,
569                                                                  * Zagreb */
570         {
571                 "Central Pacific Standard Time", "Central Pacific Daylight Time",
572                 "Pacific/Noumea"
573         },                                                      /* (GMT+11:00) Magadan, Solomon Is., New
574                                                                  * Caledonia */
575         {
576                 "Central Standard Time", "Central Daylight Time",
577                 "US/Central"
578         },                                                      /* (GMT-06:00) Central Time (US & Canada) */
579         {
580                 "China Standard Time", "China Daylight Time",
581                 "Asia/Hong_Kong"
582         },                                                      /* (GMT+08:00) Beijing, Chongqing, Hong Kong,
583                                                                  * Urumqi */
584         {
585                 "Dateline Standard Time", "Dateline Daylight Time",
586                 "Etc/GMT+12"
587         },                                                      /* (GMT-12:00) International Date Line West */
588         {
589                 "E. Africa Standard Time", "E. Africa Daylight Time",
590                 "Africa/Nairobi"
591         },                                                      /* (GMT+03:00) Nairobi */
592         {
593                 "E. Australia Standard Time", "E. Australia Daylight Time",
594                 "Australia/Brisbane"
595         },                                                      /* (GMT+10:00) Brisbane */
596         {
597                 "E. Europe Standard Time", "E. Europe Daylight Time",
598                 "Europe/Bucharest"
599         },                                                      /* (GMT+02:00) Bucharest */
600         {
601                 "E. South America Standard Time", "E. South America Daylight Time",
602                 "America/Araguaina"
603         },                                                      /* (GMT-03:00) Brasilia */
604         {
605                 "Eastern Standard Time", "Eastern Daylight Time",
606                 "US/Eastern"
607         },                                                      /* (GMT-05:00) Eastern Time (US & Canada) */
608         {
609                 "Egypt Standard Time", "Egypt Daylight Time",
610                 "Africa/Cairo"
611         },                                                      /* (GMT+02:00) Cairo */
612         {
613                 "Ekaterinburg Standard Time", "Ekaterinburg Daylight Time",
614                 "Asia/Yekaterinburg"
615         },                                                      /* (GMT+05:00) Ekaterinburg */
616         {
617                 "Fiji Standard Time", "Fiji Daylight Time",
618                 "Pacific/Fiji"
619         },                                                      /* (GMT+12:00) Fiji, Kamchatka, Marshall Is. */
620         {
621                 "FLE Standard Time", "FLE Daylight Time",
622                 "Europe/Helsinki"
623         },                                                      /* (GMT+02:00) Helsinki, Kyiv, Riga, Sofia,
624                                                                  * Tallinn, Vilnius */
625         {
626                 "GMT Standard Time", "GMT Daylight Time",
627                 "Europe/Dublin"
628         },                                                      /* (GMT) Greenwich Mean Time : Dublin,
629                                                                  * Edinburgh, Lisbon, London */
630         {
631                 "Greenland Standard Time", "Greenland Daylight Time",
632                 "America/Godthab"
633         },                                                      /* (GMT-03:00) Greenland */
634         {
635                 "Greenwich Standard Time", "Greenwich Daylight Time",
636                 "Africa/Casablanca"
637         },                                                      /* (GMT) Casablanca, Monrovia */
638         {
639                 "GTB Standard Time", "GTB Daylight Time",
640                 "Europe/Athens"
641         },                                                      /* (GMT+02:00) Athens, Istanbul, Minsk */
642         {
643                 "Hawaiian Standard Time", "Hawaiian Daylight Time",
644                 "US/Hawaii"
645         },                                                      /* (GMT-10:00) Hawaii */
646         {
647                 "India Standard Time", "India Daylight Time",
648                 "Asia/Calcutta"
649         },                                                      /* (GMT+05:30) Chennai, Kolkata, Mumbai, New
650                                                                  * Delhi */
651         {
652                 "Iran Standard Time", "Iran Daylight Time",
653                 "Asia/Tehran"
654         },                                                      /* (GMT+03:30) Tehran */
655         {
656                 "Jerusalem Standard Time", "Jerusalem Daylight Time",
657                 "Asia/Jerusalem"
658         },                                                      /* (GMT+02:00) Jerusalem */
659         {
660                 "Korea Standard Time", "Korea Daylight Time",
661                 "Asia/Seoul"
662         },                                                      /* (GMT+09:00) Seoul */
663         {
664                 "Mexico Standard Time", "Mexico Daylight Time",
665                 "America/Mexico_City"
666         },                                                      /* (GMT-06:00) Guadalajara, Mexico City,
667                                                                  * Monterrey */
668         {
669                 "Mexico Standard Time", "Mexico Daylight Time",
670                 "America/La_Paz"
671         },                                                      /* (GMT-07:00) Chihuahua, La Paz, Mazatlan */
672         {
673                 "Mid-Atlantic Standard Time", "Mid-Atlantic Daylight Time",
674                 "Atlantic/South_Georgia"
675         },                                                      /* (GMT-02:00) Mid-Atlantic */
676         {
677                 "Mountain Standard Time", "Mountain Daylight Time",
678                 "US/Mountain"
679         },                                                      /* (GMT-07:00) Mountain Time (US & Canada) */
680         {
681                 "Myanmar Standard Time", "Myanmar Daylight Time",
682                 "Asia/Rangoon"
683         },                                                      /* (GMT+06:30) Rangoon */
684         {
685                 "N. Central Asia Standard Time", "N. Central Asia Daylight Time",
686                 "Asia/Almaty"
687         },                                                      /* (GMT+06:00) Almaty, Novosibirsk */
688         {
689                 "Nepal Standard Time", "Nepal Daylight Time",
690                 "Asia/Katmandu"
691         },                                                      /* (GMT+05:45) Kathmandu */
692         {
693                 "New Zealand Standard Time", "New Zealand Daylight Time",
694                 "Pacific/Auckland"
695         },                                                      /* (GMT+12:00) Auckland, Wellington */
696         {
697                 "Newfoundland Standard Time", "Newfoundland Daylight Time",
698                 "Canada/Newfoundland"
699         },                                                      /* (GMT-03:30) Newfoundland */
700         {
701                 "North Asia East Standard Time", "North Asia East Daylight Time",
702                 "Asia/Irkutsk"
703         },                                                      /* (GMT+08:00) Irkutsk, Ulaan Bataar */
704         {
705                 "North Asia Standard Time", "North Asia Daylight Time",
706                 "Asia/Krasnoyarsk"
707         },                                                      /* (GMT+07:00) Krasnoyarsk */
708         {
709                 "Pacific SA Standard Time", "Pacific SA Daylight Time",
710                 "America/Santiago"
711         },                                                      /* (GMT-04:00) Santiago */
712         {
713                 "Pacific Standard Time", "Pacific Daylight Time",
714                 "US/Pacific"
715         },                                                      /* (GMT-08:00) Pacific Time (US & Canada);
716                                                                  * Tijuana */
717         {
718                 "Romance Standard Time", "Romance Daylight Time",
719                 "Europe/Brussels"
720         },                                                      /* (GMT+01:00) Brussels, Copenhagen, Madrid,
721                                                                  * Paris */
722         {
723                 "Russian Standard Time", "Russian Daylight Time",
724                 "Europe/Moscow"
725         },                                                      /* (GMT+03:00) Moscow, St. Petersburg,
726                                                                  * Volgograd */
727         {
728                 "SA Eastern Standard Time", "SA Eastern Daylight Time",
729                 "America/Buenos_Aires"
730         },                                                      /* (GMT-03:00) Buenos Aires, Georgetown */
731         {
732                 "SA Pacific Standard Time", "SA Pacific Daylight Time",
733                 "America/Bogota"
734         },                                                      /* (GMT-05:00) Bogota, Lima, Quito */
735         {
736                 "SA Western Standard Time", "SA Western Daylight Time",
737                 "America/Caracas"
738         },                                                      /* (GMT-04:00) Caracas, La Paz */
739         {
740                 "Samoa Standard Time", "Samoa Daylight Time",
741                 "Pacific/Midway"
742         },                                                      /* (GMT-11:00) Midway Island, Samoa */
743         {
744                 "SE Asia Standard Time", "SE Asia Daylight Time",
745                 "Asia/Bangkok"
746         },                                                      /* (GMT+07:00) Bangkok, Hanoi, Jakarta */
747         {
748                 "Malay Peninsula Standard Time", "Malay Peninsula Daylight Time",
749                 "Asia/Kuala_Lumpur"
750         },                                                      /* (GMT+08:00) Kuala Lumpur, Singapore */
751         {
752                 "South Africa Standard Time", "South Africa Daylight Time",
753                 "Africa/Harare"
754         },                                                      /* (GMT+02:00) Harare, Pretoria */
755         {
756                 "Sri Lanka Standard Time", "Sri Lanka Daylight Time",
757                 "Asia/Colombo"
758         },                                                      /* (GMT+06:00) Sri Jayawardenepura */
759         {
760                 "Taipei Standard Time", "Taipei Daylight Time",
761                 "Asia/Taipei"
762         },                                                      /* (GMT+08:00) Taipei */
763         {
764                 "Tasmania Standard Time", "Tasmania Daylight Time",
765                 "Australia/Hobart"
766         },                                                      /* (GMT+10:00) Hobart */
767         {
768                 "Tokyo Standard Time", "Tokyo Daylight Time",
769                 "Asia/Tokyo"
770         },                                                      /* (GMT+09:00) Osaka, Sapporo, Tokyo */
771         {
772                 "Tonga Standard Time", "Tonga Daylight Time",
773                 "Pacific/Tongatapu"
774         },                                                      /* (GMT+13:00) Nuku'alofa */
775         {
776                 "US Eastern Standard Time", "US Eastern Daylight Time",
777                 "US/Eastern"
778         },                                                      /* (GMT-05:00) Indiana (East) */
779         {
780                 "US Mountain Standard Time", "US Mountain Daylight Time",
781                 "US/Arizona"
782         },                                                      /* (GMT-07:00) Arizona */
783         {
784                 "Vladivostok Standard Time", "Vladivostok Daylight Time",
785                 "Asia/Vladivostok"
786         },                                                      /* (GMT+10:00) Vladivostok */
787         {
788                 "W. Australia Standard Time", "W. Australia Daylight Time",
789                 "Australia/Perth"
790         },                                                      /* (GMT+08:00) Perth */
791 /*      {"W. Central Africa Standard Time", "W. Central Africa Daylight Time",
792          *       *       *       *      ""}, Could not find a match for this one. Excluded for now. *//* (
793          * G MT+01:00) West Central Africa */
794         {
795                 "W. Europe Standard Time", "W. Europe Daylight Time",
796                 "CET"
797         },                                                      /* (GMT+01:00) Amsterdam, Berlin, Bern, Rome,
798                                                                  * Stockholm, Vienna */
799         {
800                 "West Asia Standard Time", "West Asia Daylight Time",
801                 "Asia/Karachi"
802         },                                                      /* (GMT+05:00) Islamabad, Karachi, Tashkent */
803         {
804                 "West Pacific Standard Time", "West Pacific Daylight Time",
805                 "Pacific/Guam"
806         },                                                      /* (GMT+10:00) Guam, Port Moresby */
807         {
808                 "Yakutsk Standard Time", "Yakutsk Daylight Time",
809                 "Asia/Yakutsk"
810         },                                                      /* (GMT+09:00) Yakutsk */
811         {
812                 NULL, NULL, NULL
813         }
814 };
815
816 static const char *
817 identify_system_timezone(void)
818 {
819         int                     i;
820         char            tzname[128];
821         char            localtzname[256];
822         time_t          t = time(NULL);
823         struct tm  *tm = localtime(&t);
824         HKEY            rootKey;
825         int                     idx;
826
827         if (!tm)
828         {
829                 ereport(WARNING,
830                                 (errmsg_internal("could not determine current date/time: localtime failed")));
831                 return NULL;
832         }
833
834         memset(tzname, 0, sizeof(tzname));
835         strftime(tzname, sizeof(tzname) - 1, "%Z", tm);
836
837         for (i = 0; win32_tzmap[i].stdname != NULL; i++)
838         {
839                 if (strcmp(tzname, win32_tzmap[i].stdname) == 0 ||
840                         strcmp(tzname, win32_tzmap[i].dstname) == 0)
841                 {
842                         elog(DEBUG4, "TZ \"%s\" matches Windows timezone \"%s\"",
843                                  win32_tzmap[i].pgtzname, tzname);
844                         return win32_tzmap[i].pgtzname;
845                 }
846         }
847
848         /*
849          * Localized Windows versions return localized names for the timezone.
850          * Scan the registry to find the English name, and then try matching
851          * against our table again.
852          */
853         memset(localtzname, 0, sizeof(localtzname));
854         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
855                            "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
856                                          0,
857                                          KEY_READ,
858                                          &rootKey) != ERROR_SUCCESS)
859         {
860                 ereport(WARNING,
861                                 (errmsg_internal("could not open registry key to identify Windows timezone: %i", (int) GetLastError())));
862                 return NULL;
863         }
864
865         for (idx = 0;; idx++)
866         {
867                 char            keyname[256];
868                 char            zonename[256];
869                 DWORD           namesize;
870                 FILETIME        lastwrite;
871                 HKEY            key;
872                 LONG            r;
873
874                 memset(keyname, 0, sizeof(keyname));
875                 namesize = sizeof(keyname);
876                 if ((r = RegEnumKeyEx(rootKey,
877                                                           idx,
878                                                           keyname,
879                                                           &namesize,
880                                                           NULL,
881                                                           NULL,
882                                                           NULL,
883                                                           &lastwrite)) != ERROR_SUCCESS)
884                 {
885                         if (r == ERROR_NO_MORE_ITEMS)
886                                 break;
887                         ereport(WARNING,
888                                         (errmsg_internal("could not enumerate registry subkeys to identify Windows timezone: %i", (int) r)));
889                         break;
890                 }
891
892                 if ((r = RegOpenKeyEx(rootKey, keyname, 0, KEY_READ, &key)) != ERROR_SUCCESS)
893                 {
894                         ereport(WARNING,
895                                         (errmsg_internal("could not open registry subkey to identify Windows timezone: %i", (int) r)));
896                         break;
897                 }
898
899                 memset(zonename, 0, sizeof(zonename));
900                 namesize = sizeof(zonename);
901                 if ((r = RegQueryValueEx(key, "Std", NULL, NULL, zonename, &namesize)) != ERROR_SUCCESS)
902                 {
903                         ereport(WARNING,
904                                         (errmsg_internal("could not query value for 'std' to identify Windows timezone: %i", (int) r)));
905                         RegCloseKey(key);
906                         break;
907                 }
908                 if (strcmp(tzname, zonename) == 0)
909                 {
910                         /* Matched zone */
911                         strcpy(localtzname, keyname);
912                         RegCloseKey(key);
913                         break;
914                 }
915                 memset(zonename, 0, sizeof(zonename));
916                 namesize = sizeof(zonename);
917                 if ((r = RegQueryValueEx(key, "Dlt", NULL, NULL, zonename, &namesize)) != ERROR_SUCCESS)
918                 {
919                         ereport(WARNING,
920                                         (errmsg_internal("could not query value for 'dlt' to identify Windows timezone: %i", (int) r)));
921                         RegCloseKey(key);
922                         break;
923                 }
924                 if (strcmp(tzname, zonename) == 0)
925                 {
926                         /* Matched DST zone */
927                         strcpy(localtzname, keyname);
928                         RegCloseKey(key);
929                         break;
930                 }
931
932                 RegCloseKey(key);
933         }
934
935         RegCloseKey(rootKey);
936
937         if (localtzname[0])
938         {
939                 /* Found a localized name, so scan for that one too */
940                 for (i = 0; win32_tzmap[i].stdname != NULL; i++)
941                 {
942                         if (strcmp(localtzname, win32_tzmap[i].stdname) == 0 ||
943                                 strcmp(localtzname, win32_tzmap[i].dstname) == 0)
944                         {
945                                 elog(DEBUG4, "TZ \"%s\" matches localized Windows timezone \"%s\" (\"%s\")",
946                                          win32_tzmap[i].pgtzname, tzname, localtzname);
947                                 return win32_tzmap[i].pgtzname;
948                         }
949                 }
950         }
951
952         ereport(WARNING,
953                         (errmsg("could not find a match for Windows timezone \"%s\"",
954                                         tzname)));
955         return NULL;
956 }
957 #endif   /* WIN32 */
958
959
960
961 /*
962  * We keep loaded timezones in a hashtable so we don't have to
963  * load and parse the TZ definition file every time it is selected.
964  */
965 static HTAB *timezone_cache = NULL;
966
967 static bool
968 init_timezone_hashtable(void)
969 {
970         HASHCTL         hash_ctl;
971
972         MemSet(&hash_ctl, 0, sizeof(hash_ctl));
973
974         hash_ctl.keysize = TZ_STRLEN_MAX + 1;
975         hash_ctl.entrysize = sizeof(pg_tz);
976
977         timezone_cache = hash_create("Timezones",
978                                                                  4,
979                                                                  &hash_ctl,
980                                                                  HASH_ELEM);
981         if (!timezone_cache)
982                 return false;
983
984         return true;
985 }
986
987 /*
988  * Load a timezone from file or from cache.
989  * Does not verify that the timezone is acceptable!
990  */
991 struct pg_tz *
992 pg_tzset(const char *name)
993 {
994         pg_tz      *tzp;
995         pg_tz           tz;
996
997         if (strlen(name) > TZ_STRLEN_MAX)
998                 return NULL;                    /* not going to fit */
999
1000         if (!timezone_cache)
1001                 if (!init_timezone_hashtable())
1002                         return NULL;
1003
1004         tzp = (pg_tz *) hash_search(timezone_cache,
1005                                                                 name,
1006                                                                 HASH_FIND,
1007                                                                 NULL);
1008         if (tzp)
1009         {
1010                 /* Timezone found in cache, nothing more to do */
1011                 return tzp;
1012         }
1013
1014         if (tzload(name, &tz.state) != 0)
1015         {
1016                 if (name[0] == ':' || tzparse(name, &tz.state, FALSE) != 0)
1017                 {
1018                         /* Unknown timezone. Fail our call instead of loading GMT! */
1019                         return NULL;
1020                 }
1021         }
1022
1023         strcpy(tz.TZname, name);
1024
1025         /* Save timezone in the cache */
1026         tzp = hash_search(timezone_cache,
1027                                           name,
1028                                           HASH_ENTER,
1029                                           NULL);
1030
1031         strcpy(tzp->TZname, tz.TZname);
1032         memcpy(&tzp->state, &tz.state, sizeof(tz.state));
1033
1034         return tzp;
1035 }
1036
1037
1038 /*
1039  * Check whether timezone is acceptable.
1040  *
1041  * What we are doing here is checking for leap-second-aware timekeeping.
1042  * We need to reject such TZ settings because they'll wreak havoc with our
1043  * date/time arithmetic.
1044  *
1045  * NB: this must NOT ereport(ERROR).  The caller must get control back so that
1046  * it can restore the old value of TZ if we don't like the new one.
1047  */
1048 bool
1049 tz_acceptable(pg_tz *tz)
1050 {
1051         struct pg_tm *tt;
1052         pg_time_t       time2000;
1053
1054         /*
1055          * To detect leap-second timekeeping, run pg_localtime for what should be
1056          * GMT midnight, 2000-01-01.  Insist that the tm_sec value be zero; any
1057          * other result has to be due to leap seconds.
1058          */
1059         time2000 = (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
1060         tt = pg_localtime(&time2000, tz);
1061         if (!tt || tt->tm_sec != 0)
1062                 return false;
1063
1064         return true;
1065 }
1066
1067
1068 /*
1069  * Set the global timezone. Verify that it's acceptable first.
1070  */
1071 static bool
1072 set_global_timezone(const char *tzname)
1073 {
1074         pg_tz      *tznew;
1075
1076         if (!tzname || !tzname[0])
1077                 return false;
1078
1079         tznew = pg_tzset(tzname);
1080         if (!tznew)
1081                 return false;
1082
1083         if (!tz_acceptable(tznew))
1084                 return false;
1085
1086         global_timezone = tznew;
1087         return true;
1088 }
1089
1090 /*
1091  * Identify a suitable default timezone setting based on the environment,
1092  * and make it active.
1093  *
1094  * We first look to the TZ environment variable.  If not found or not
1095  * recognized by our own code, we see if we can identify the timezone
1096  * from the behavior of the system timezone library.  When all else fails,
1097  * fall back to GMT.
1098  */
1099 static const char *
1100 select_default_timezone(void)
1101 {
1102         const char *def_tz;
1103
1104         def_tz = getenv("TZ");
1105         if (set_global_timezone(def_tz))
1106                 return def_tz;
1107
1108         def_tz = identify_system_timezone();
1109         if (set_global_timezone(def_tz))
1110                 return def_tz;
1111
1112         if (set_global_timezone("GMT"))
1113                 return "GMT";
1114
1115         ereport(FATAL,
1116                         (errmsg("could not select a suitable default timezone"),
1117                          errdetail("It appears that your GMT time zone uses leap seconds. PostgreSQL does not support leap seconds.")));
1118         return NULL;                            /* keep compiler quiet */
1119 }
1120
1121 /*
1122  * Initialize timezone library
1123  *
1124  * This is called after initial loading of postgresql.conf.  If no TimeZone
1125  * setting was found therein, we try to derive one from the environment.
1126  */
1127 void
1128 pg_timezone_initialize(void)
1129 {
1130         /* Do we need to try to figure the timezone? */
1131         if (pg_strcasecmp(GetConfigOption("timezone"), "UNKNOWN") == 0)
1132         {
1133                 const char *def_tz;
1134
1135                 /* Select setting */
1136                 def_tz = select_default_timezone();
1137                 /* Tell GUC about the value. Will redundantly call pg_tzset() */
1138                 SetConfigOption("timezone", def_tz, PGC_POSTMASTER, PGC_S_ARGV);
1139         }
1140 }