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