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