Don't use <filename> in docs
[platform/upstream/glib.git] / glib / gtimezone.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16  *
17  * Author: Ryan Lortie <desrt@desrt.ca>
18  */
19
20 /* Prologue {{{1 */
21
22 #include "config.h"
23
24 #include "gtimezone.h"
25
26 #include <string.h>
27 #include <stdlib.h>
28 #include <signal.h>
29
30 #include "gmappedfile.h"
31 #include "gtestutils.h"
32 #include "gfileutils.h"
33 #include "gstrfuncs.h"
34 #include "ghash.h"
35 #include "gthread.h"
36 #include "gbytes.h"
37 #include "gslice.h"
38 #include "gdatetime.h"
39 #include "gdate.h"
40
41 #ifdef G_OS_WIN32
42 #define STRICT
43 #include <windows.h>
44 #endif
45
46 /**
47  * SECTION:timezone
48  * @title: GTimeZone
49  * @short_description: a structure representing a time zone
50  * @see_also: #GDateTime
51  *
52  * #GTimeZone is a structure that represents a time zone, at no
53  * particular point in time.  It is refcounted and immutable.
54  *
55  * A time zone contains a number of intervals.  Each interval has
56  * an abbreviation to describe it, an offet to UTC and a flag indicating
57  * if the daylight savings time is in effect during that interval.  A
58  * time zone always has at least one interval -- interval 0.
59  *
60  * Every UTC time is contained within exactly one interval, but a given
61  * local time may be contained within zero, one or two intervals (due to
62  * incontinuities associated with daylight savings time).
63  *
64  * An interval may refer to a specific period of time (eg: the duration
65  * of daylight savings time during 2010) or it may refer to many periods
66  * of time that share the same properties (eg: all periods of daylight
67  * savings time).  It is also possible (usually for political reasons)
68  * that some properties (like the abbreviation) change between intervals
69  * without other properties changing.
70  *
71  * #GTimeZone is available since GLib 2.26.
72  */
73
74 /**
75  * GTimeZone:
76  *
77  * #GTimeZone is an opaque structure whose members cannot be accessed
78  * directly.
79  *
80  * Since: 2.26
81  **/
82
83 /* IANA zoneinfo file format {{{1 */
84
85 /* unaligned */
86 typedef struct { gchar bytes[8]; } gint64_be;
87 typedef struct { gchar bytes[4]; } gint32_be;
88 typedef struct { gchar bytes[4]; } guint32_be;
89
90 static inline gint64 gint64_from_be (const gint64_be be) {
91   gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
92 }
93
94 static inline gint32 gint32_from_be (const gint32_be be) {
95   gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
96 }
97
98 static inline guint32 guint32_from_be (const guint32_be be) {
99   guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
100 }
101
102 /* The layout of an IANA timezone file header */
103 struct tzhead
104 {
105   gchar      tzh_magic[4];
106   gchar      tzh_version;
107   guchar     tzh_reserved[15];
108
109   guint32_be tzh_ttisgmtcnt;
110   guint32_be tzh_ttisstdcnt;
111   guint32_be tzh_leapcnt;
112   guint32_be tzh_timecnt;
113   guint32_be tzh_typecnt;
114   guint32_be tzh_charcnt;
115 };
116
117 struct ttinfo
118 {
119   gint32_be tt_gmtoff;
120   guint8    tt_isdst;
121   guint8    tt_abbrind;
122 };
123
124 /* A Transition Date structure for TZ Rules, an intermediate structure
125    for parsing MSWindows and Environment-variable time zones. It
126    Generalizes MSWindows's SYSTEMTIME struct.
127  */
128 typedef struct
129 {
130   gint     year;
131   gint     mon;
132   gint     mday;
133   gint     wday;
134   gint     week;
135   gint     hour;
136   gint     min;
137   gint     sec;
138 } TimeZoneDate;
139
140 /* POSIX Timezone abbreviations are typically 3 or 4 characters, but
141    Microsoft uses 32-character names. We'll use one larger to ensure
142    we have room for the terminating \0.
143  */
144 #define NAME_SIZE 33
145
146 /* A MSWindows-style time zone transition rule. Generalizes the
147    MSWindows TIME_ZONE_INFORMATION struct. Also used to compose time
148    zones from tzset-style identifiers.
149  */
150 typedef struct
151 {
152   gint         start_year;
153   gint32       std_offset;
154   gint32       dlt_offset;
155   TimeZoneDate dlt_start;
156   TimeZoneDate dlt_end;
157   gchar std_name[NAME_SIZE];
158   gchar dlt_name[NAME_SIZE];
159 } TimeZoneRule;
160
161 /* GTimeZone's internal representation of a Daylight Savings (Summer)
162    time interval.
163  */
164 typedef struct
165 {
166   gint32     gmt_offset;
167   gboolean   is_dst;
168   gboolean   is_standard;
169   gboolean   is_gmt;
170   gchar     *abbrev;
171 } TransitionInfo;
172
173 /* GTimeZone's representation of a transition time to or from Daylight
174    Savings (Summer) time and Standard time for the zone. */
175 typedef struct
176 {
177   gint64 time;
178   gint   info_index;
179 } Transition;
180
181 /* GTimeZone structure */
182 struct _GTimeZone
183 {
184   gchar   *name;
185   GArray  *t_info;         /* Array of TransitionInfo */
186   GArray  *transitions;    /* Array of Transition */
187   gint     ref_count;
188 };
189
190 G_LOCK_DEFINE_STATIC (time_zones);
191 static GHashTable/*<string?, GTimeZone>*/ *time_zones;
192
193 #define MIN_TZYEAR 1916 /* Daylight Savings started in WWI */
194 #define MAX_TZYEAR 2999 /* And it's not likely ever to go away, but
195                            there's no point in getting carried
196                            away. */
197
198 /**
199  * g_time_zone_unref:
200  * @tz: a #GTimeZone
201  *
202  * Decreases the reference count on @tz.
203  *
204  * Since: 2.26
205  **/
206 void
207 g_time_zone_unref (GTimeZone *tz)
208 {
209   int ref_count;
210
211 again:
212   ref_count = g_atomic_int_get (&tz->ref_count);
213
214   g_assert (ref_count > 0);
215
216   if (ref_count == 1)
217     {
218       if (tz->name != NULL)
219         {
220           G_LOCK(time_zones);
221
222           /* someone else might have grabbed a ref in the meantime */
223           if G_UNLIKELY (g_atomic_int_get (&tz->ref_count) != 1)
224             {
225               G_UNLOCK(time_zones);
226               goto again;
227             }
228
229           g_hash_table_remove (time_zones, tz->name);
230           G_UNLOCK(time_zones);
231         }
232
233       if (tz->t_info != NULL)
234         {
235           gint idx;
236           for (idx = 0; idx < tz->t_info->len; idx++)
237             {
238               TransitionInfo *info = &g_array_index (tz->t_info, TransitionInfo, idx);
239               g_free (info->abbrev);
240             }
241           g_array_free (tz->t_info, TRUE);
242         }
243       if (tz->transitions != NULL)
244         g_array_free (tz->transitions, TRUE);
245       g_free (tz->name);
246
247       g_slice_free (GTimeZone, tz);
248     }
249
250   else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
251                                                           ref_count,
252                                                           ref_count - 1))
253     goto again;
254 }
255
256 /**
257  * g_time_zone_ref:
258  * @tz: a #GTimeZone
259  *
260  * Increases the reference count on @tz.
261  *
262  * Returns: a new reference to @tz.
263  *
264  * Since: 2.26
265  **/
266 GTimeZone *
267 g_time_zone_ref (GTimeZone *tz)
268 {
269   g_assert (tz->ref_count > 0);
270
271   g_atomic_int_inc (&tz->ref_count);
272
273   return tz;
274 }
275
276 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
277 /*
278  * parses strings of the form h or hh[[:]mm[[[:]ss]]] where:
279  *  - h[h] is 0 to 23
280  *  - mm is 00 to 59
281  *  - ss is 00 to 59
282  */
283 static gboolean
284 parse_time (const gchar *time_,
285             gint32      *offset)
286 {
287   if (*time_ < '0' || '9' < *time_)
288     return FALSE;
289
290   *offset = 60 * 60 * (*time_++ - '0');
291
292   if (*time_ == '\0')
293     return TRUE;
294
295   if (*time_ != ':')
296     {
297       if (*time_ < '0' || '9' < *time_)
298         return FALSE;
299
300       *offset *= 10;
301       *offset += 60 * 60 * (*time_++ - '0');
302
303       if (*offset > 23 * 60 * 60)
304         return FALSE;
305
306       if (*time_ == '\0')
307         return TRUE;
308     }
309
310   if (*time_ == ':')
311     time_++;
312
313   if (*time_ < '0' || '5' < *time_)
314     return FALSE;
315
316   *offset += 10 * 60 * (*time_++ - '0');
317
318   if (*time_ < '0' || '9' < *time_)
319     return FALSE;
320
321   *offset += 60 * (*time_++ - '0');
322
323   if (*time_ == '\0')
324     return TRUE;
325
326   if (*time_ == ':')
327     time_++;
328
329   if (*time_ < '0' || '5' < *time_)
330     return FALSE;
331
332   *offset += 10 * (*time_++ - '0');
333
334   if (*time_ < '0' || '9' < *time_)
335     return FALSE;
336
337   *offset += *time_++ - '0';
338
339   return *time_ == '\0';
340 }
341
342 static gboolean
343 parse_constant_offset (const gchar *name,
344                        gint32      *offset)
345 {
346   if (g_strcmp0 (name, "UTC") == 0)
347     {
348       *offset = 0;
349       return TRUE;
350     }
351
352   if (*name >= '0' && '9' >= *name)
353     return parse_time (name, offset);
354
355   switch (*name++)
356     {
357     case 'Z':
358       *offset = 0;
359       return !*name;
360
361     case '+':
362       return parse_time (name, offset);
363
364     case '-':
365       if (parse_time (name, offset))
366         {
367           *offset = -*offset;
368           return TRUE;
369         }
370
371     default:
372       return FALSE;
373     }
374 }
375
376 static void
377 zone_for_constant_offset (GTimeZone *gtz, const gchar *name)
378 {
379   gint32 offset;
380   TransitionInfo info;
381
382   if (name == NULL || !parse_constant_offset (name, &offset))
383     return;
384
385   info.gmt_offset = offset;
386   info.is_dst = FALSE;
387   info.is_standard = TRUE;
388   info.is_gmt = TRUE;
389   info.abbrev =  g_strdup (name);
390
391
392   gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), 1);
393   g_array_append_val (gtz->t_info, info);
394
395   /* Constant offset, no transitions */
396   gtz->transitions = NULL;
397 }
398
399 #ifdef G_OS_UNIX
400 static GBytes*
401 zone_info_unix (const gchar *identifier)
402 {
403   gchar *filename;
404   GMappedFile *file = NULL;
405   GBytes *zoneinfo = NULL;
406
407   /* identifier can be a relative or absolute path name;
408      if relative, it is interpreted starting from /usr/share/zoneinfo
409      while the POSIX standard says it should start with :,
410      glibc allows both syntaxes, so we should too */
411   if (identifier != NULL)
412     {
413       const gchar *tzdir;
414
415       tzdir = getenv ("TZDIR");
416       if (tzdir == NULL)
417         tzdir = "/usr/share/zoneinfo";
418
419       if (*identifier == ':')
420         identifier ++;
421
422       if (g_path_is_absolute (identifier))
423         filename = g_strdup (identifier);
424       else
425         filename = g_build_filename (tzdir, identifier, NULL);
426     }
427   else
428     filename = g_strdup ("/etc/localtime");
429
430   file = g_mapped_file_new (filename, FALSE, NULL);
431   if (file != NULL)
432     {
433       zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
434                                              g_mapped_file_get_length (file),
435                                              (GDestroyNotify)g_mapped_file_unref,
436                                              g_mapped_file_ref (file));
437       g_mapped_file_unref (file);
438     }
439   g_free (filename);
440   return zoneinfo;
441 }
442
443 static void
444 init_zone_from_iana_info (GTimeZone *gtz, GBytes *zoneinfo)
445 {
446   gsize size;
447   guint index;
448   guint32 time_count, type_count, leap_count, isgmt_count;
449   guint32  isstd_count, char_count ;
450   guint8 *tz_transitions, *tz_type_index, *tz_ttinfo;
451   guint8 *tz_leaps, *tz_isgmt, *tz_isstd;
452   guint8 *tz_abbrs;
453   gsize timesize = sizeof (gint32), countsize = sizeof (gint32);
454   const struct tzhead *header = g_bytes_get_data (zoneinfo, &size);
455
456   g_return_if_fail (size >= sizeof (struct tzhead) &&
457                     memcmp (header, "TZif", 4) == 0);
458
459   if (header->tzh_version == '2')
460       {
461         /* Skip ahead to the newer 64-bit data if it's available. */
462         header = (const struct tzhead *)
463           (((const gchar *) (header + 1)) +
464            guint32_from_be(header->tzh_ttisgmtcnt) +
465            guint32_from_be(header->tzh_ttisstdcnt) +
466            8 * guint32_from_be(header->tzh_leapcnt) +
467            5 * guint32_from_be(header->tzh_timecnt) +
468            6 * guint32_from_be(header->tzh_typecnt) +
469            guint32_from_be(header->tzh_charcnt));
470         timesize = sizeof (gint64);
471       }
472   time_count = guint32_from_be(header->tzh_timecnt);
473   type_count = guint32_from_be(header->tzh_typecnt);
474   leap_count = guint32_from_be(header->tzh_leapcnt);
475   isgmt_count = guint32_from_be(header->tzh_ttisgmtcnt);
476   isstd_count = guint32_from_be(header->tzh_ttisstdcnt);
477   char_count = guint32_from_be(header->tzh_charcnt);
478
479   g_assert (type_count == isgmt_count);
480   g_assert (type_count == isstd_count);
481
482   tz_transitions = ((guint8 *) (header) + sizeof (*header));
483   tz_type_index = tz_transitions + timesize * time_count;
484   tz_ttinfo = tz_type_index + time_count;
485   tz_abbrs = tz_ttinfo + sizeof (struct ttinfo) * type_count;
486   tz_leaps = tz_abbrs + char_count;
487   tz_isstd = tz_leaps + (timesize + countsize) * leap_count;
488   tz_isgmt = tz_isstd + isstd_count;
489
490   gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo),
491                                    type_count);
492   gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition),
493                                         time_count);
494
495   for (index = 0; index < type_count; index++)
496     {
497       TransitionInfo t_info;
498       struct ttinfo info = ((struct ttinfo*)tz_ttinfo)[index];
499       t_info.gmt_offset = gint32_from_be (info.tt_gmtoff);
500       t_info.is_dst = info.tt_isdst ? TRUE : FALSE;
501       t_info.is_standard = tz_isstd[index] ? TRUE : FALSE;
502       t_info.is_gmt = tz_isgmt[index] ? TRUE : FALSE;
503       t_info.abbrev = g_strdup ((gchar *) &tz_abbrs[info.tt_abbrind]);
504       g_array_append_val (gtz->t_info, t_info);
505     }
506
507   for (index = 0; index < time_count; index++)
508     {
509       Transition trans;
510       if (header->tzh_version == '2')
511         trans.time = gint64_from_be (((gint64_be*)tz_transitions)[index]);
512       else
513         trans.time = gint32_from_be (((gint32_be*)tz_transitions)[index]);
514       trans.info_index = tz_type_index[index];
515       g_assert (trans.info_index >= 0);
516       g_assert (trans.info_index < gtz->t_info->len);
517       g_array_append_val (gtz->transitions, trans);
518     }
519 }
520
521 #elif defined (G_OS_WIN32)
522
523 static void
524 copy_windows_systemtime (SYSTEMTIME *s_time, TimeZoneDate *tzdate)
525 {
526   tzdate->sec = s_time->wSecond;
527   tzdate->min = s_time->wMinute;
528   tzdate->hour = s_time->wHour;
529   tzdate->mon = s_time->wMonth;
530   tzdate->year = s_time->wYear;
531   tzdate->wday = s_time->wDayOfWeek ? s_time->wDayOfWeek : 7;
532
533   if (s_time->wYear)
534     {
535       tzdate->mday = s_time->wDay;
536       tzdate->wday = 0;
537     }
538   else
539     tzdate->week = s_time->wDay;
540 }
541
542 /* UTC = local time + bias while local time = UTC + offset */
543 static void
544 rule_from_windows_time_zone_info (TimeZoneRule *rule,
545                                   TIME_ZONE_INFORMATION *tzi)
546 {
547   /* Set offset */
548   if (tzi->StandardDate.wMonth)
549     {
550       rule->std_offset = -(tzi->Bias + tzi->StandardBias) * 60;
551       rule->dlt_offset = -(tzi->Bias + tzi->DaylightBias) * 60;
552       copy_windows_systemtime (&(tzi->DaylightDate), &(rule->dlt_start));
553
554       copy_windows_systemtime (&(tzi->StandardDate), &(rule->dlt_end));
555
556     }
557
558   else
559     {
560       rule->std_offset = -tzi->Bias * 60;
561       rule->dlt_start.mon = 0;
562     }
563   strncpy (rule->std_name, (gchar*)tzi->StandardName, NAME_SIZE - 1);
564   strncpy (rule->dlt_name, (gchar*)tzi->DaylightName, NAME_SIZE - 1);
565 }
566
567 static gchar*
568 windows_default_tzname (void)
569 {
570   const gchar *subkey =
571     "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
572   HKEY key;
573   gchar *key_name = NULL;
574   if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
575                      KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
576     {
577       DWORD size = 0;
578       if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
579                             NULL, &size) == ERROR_SUCCESS)
580         {
581           key_name = g_malloc ((gint)size);
582           if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
583                                 (LPBYTE)key_name, &size) != ERROR_SUCCESS)
584             {
585               g_free (key_name);
586               key_name = NULL;
587             }
588         }
589       RegCloseKey (key);
590     }
591   return key_name;
592 }
593
594 typedef   struct
595 {
596   LONG Bias;
597   LONG StandardBias;
598   LONG DaylightBias;
599   SYSTEMTIME StandardDate;
600   SYSTEMTIME DaylightDate;
601 } RegTZI;
602
603 static void
604 system_time_copy (SYSTEMTIME *orig, SYSTEMTIME *target)
605 {
606   g_return_if_fail (orig != NULL);
607   g_return_if_fail (target != NULL);
608
609   target->wYear = orig->wYear;
610   target->wMonth = orig->wMonth;
611   target->wDayOfWeek = orig->wDayOfWeek;
612   target->wDay = orig->wDay;
613   target->wHour = orig->wHour;
614   target->wMinute = orig->wMinute;
615   target->wSecond = orig->wSecond;
616   target->wMilliseconds = orig->wMilliseconds;
617 }
618
619 static void
620 register_tzi_to_tzi (RegTZI *reg, TIME_ZONE_INFORMATION *tzi)
621 {
622   g_return_if_fail (reg != NULL);
623   g_return_if_fail (tzi != NULL);
624   tzi->Bias = reg->Bias;
625   system_time_copy (&(reg->StandardDate), &(tzi->StandardDate));
626   tzi->StandardBias = reg->StandardBias;
627   system_time_copy (&(reg->DaylightDate), &(tzi->DaylightDate));
628   tzi->DaylightBias = reg->DaylightBias;
629 }
630
631 static gint
632 rules_from_windows_time_zone (const gchar *identifier, TimeZoneRule **rules)
633 {
634   HKEY key;
635   gchar *subkey, *subkey_dynamic;
636   gchar *key_name = NULL;
637   const gchar *reg_key =
638     "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
639   TIME_ZONE_INFORMATION tzi;
640   DWORD size;
641   gint rules_num = 0;
642   RegTZI regtzi, regtzi_prev;
643
644   *rules = NULL;
645   key_name = NULL;
646
647   if (!identifier)
648     key_name = windows_default_tzname ();
649   else
650     key_name = g_strdup (identifier);
651
652   if (!key_name)
653     return 0;
654
655   subkey = g_strconcat (reg_key, key_name, NULL);
656   subkey_dynamic = g_strconcat (subkey, "\\Dynamic DST", NULL);
657
658   if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
659                      KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
660       return 0;
661   size = sizeof tzi.StandardName;
662   if (RegQueryValueExA (key, "Std", NULL, NULL,
663                         (LPBYTE)&(tzi.StandardName), &size) != ERROR_SUCCESS)
664     goto failed;
665
666   size = sizeof tzi.DaylightName;
667
668   if (RegQueryValueExA (key, "Dlt", NULL, NULL,
669                         (LPBYTE)&(tzi.DaylightName), &size) != ERROR_SUCCESS)
670     goto failed;
671
672   RegCloseKey (key);
673   if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey_dynamic, 0,
674                      KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
675     {
676       DWORD first, last;
677       int year, i;
678       gchar *s;
679
680       size = sizeof first;
681       if (RegQueryValueExA (key, "FirstEntry", NULL, NULL,
682                             (LPBYTE) &first, &size) != ERROR_SUCCESS)
683         goto failed;
684
685       size = sizeof last;
686       if (RegQueryValueExA (key, "LastEntry", NULL, NULL,
687                             (LPBYTE) &last, &size) != ERROR_SUCCESS)
688         goto failed;
689
690       rules_num = last - first + 2;
691       *rules = g_new0 (TimeZoneRule, rules_num);
692
693       for (year = first, i = 0; year <= last; year++)
694         {
695           s = g_strdup_printf ("%d", year);
696
697           size = sizeof regtzi;
698           if (RegQueryValueExA (key, s, NULL, NULL,
699                             (LPBYTE) &regtzi, &size) != ERROR_SUCCESS)
700             {
701               g_free (*rules);
702               *rules = NULL;
703               break;
704             }
705
706           g_free (s);
707
708           if (year > first && memcmp (&regtzi_prev, &regtzi, sizeof regtzi) == 0)
709               continue;
710           else
711             memcpy (&regtzi_prev, &regtzi, sizeof regtzi);
712
713           register_tzi_to_tzi (&regtzi, &tzi);
714           rule_from_windows_time_zone_info (&(*rules)[i], &tzi);
715           (*rules)[i++].start_year = year;
716         }
717
718       rules_num = i + 1;
719
720 failed:
721       RegCloseKey (key);
722     }
723   else if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
724                           KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
725     {
726       size = sizeof regtzi;
727       if (RegQueryValueExA (key, "TZI", NULL, NULL,
728                             (LPBYTE) &regtzi, &size) == ERROR_SUCCESS)
729         {
730           rules_num = 2;
731           *rules = g_new0 (TimeZoneRule, 2);
732           register_tzi_to_tzi (&regtzi, &tzi);
733           rule_from_windows_time_zone_info (&(*rules)[0], &tzi);
734         }
735
736       RegCloseKey (key);
737     }
738
739   g_free (subkey_dynamic);
740   g_free (subkey);
741   g_free (key_name);
742
743   if (*rules)
744     {
745       (*rules)[0].start_year = MIN_TZYEAR;
746       if ((*rules)[rules_num - 2].start_year < MAX_TZYEAR)
747         (*rules)[rules_num - 1].start_year = MAX_TZYEAR;
748       else
749         (*rules)[rules_num - 1].start_year = (*rules)[rules_num - 2].start_year + 1;
750
751       return rules_num;
752     }
753   else
754     return 0;
755 }
756
757 #endif
758
759 static void
760 find_relative_date (TimeZoneDate *buffer)
761 {
762   gint wday;
763   GDate date;
764   g_date_clear (&date, 1);
765   wday = buffer->wday;
766
767   /* Get last day if last is needed, first day otherwise */
768   if (buffer->mon == 13 || buffer->mon == 14) /* Julian Date */
769     {
770       g_date_set_dmy (&date, 1, 1, buffer->year);
771       if (wday >= 59 && buffer->mon == 13 && g_date_is_leap_year (buffer->year))
772         g_date_add_days (&date, wday);
773       else
774         g_date_add_days (&date, wday - 1);
775       buffer->mon = (int) g_date_get_month (&date);
776       buffer->mday = (int) g_date_get_day (&date);
777       buffer->wday = 0;
778     }
779   else /* M.W.D */
780     {
781       guint days;
782       guint days_in_month = g_date_days_in_month (buffer->mon, buffer->year);
783       GDateWeekday first_wday;
784
785       g_date_set_dmy (&date, 1, buffer->mon, buffer->year);
786       first_wday = g_date_get_weekday (&date);
787
788       if (first_wday > wday)
789         ++(buffer->week);
790       /* week is 1 <= w <= 5, we need 0-based */
791       days = 7 * (buffer->week - 1) + wday - first_wday;
792
793       while (days > days_in_month)
794         days -= 7;
795
796       g_date_add_days (&date, days);
797
798       buffer->mday = g_date_get_day (&date);
799     }
800 }
801
802 /* Offset is previous offset of local time. Returns 0 if month is 0 */
803 static gint64
804 boundary_for_year (TimeZoneDate *boundary,
805                    gint          year,
806                    gint32        offset)
807 {
808   TimeZoneDate buffer;
809   GDate date;
810   const guint64 unix_epoch_start = 719163L;
811   const guint64 seconds_per_day = 86400L;
812
813   if (!boundary->mon)
814     return 0;
815   buffer = *boundary;
816
817   if (boundary->year == 0)
818     {
819       buffer.year = year;
820
821       if (buffer.wday)
822         find_relative_date (&buffer);
823     }
824
825   g_assert (buffer.year == year);
826   g_date_clear (&date, 1);
827   g_date_set_dmy (&date, buffer.mday, buffer.mon, buffer.year);
828   return ((g_date_get_julian (&date) - unix_epoch_start) * seconds_per_day +
829           buffer.hour * 3600 + buffer.min * 60 + buffer.sec - offset);
830 }
831
832 static void
833 fill_transition_info_from_rule (TransitionInfo *info,
834                                 TimeZoneRule   *rule,
835                                 gboolean        is_dst)
836 {
837   gint offset = is_dst ? rule->dlt_offset : rule->std_offset;
838   gchar *name = is_dst ? rule->dlt_name : rule->std_name;
839
840   info->gmt_offset = offset;
841   info->is_dst = is_dst;
842   info->is_standard = FALSE;
843   info->is_gmt = FALSE;
844
845   if (name)
846     info->abbrev = g_strdup (name);
847
848   else
849     info->abbrev = g_strdup_printf ("%+03d%02d",
850                                       (int) offset / 3600,
851                                       (int) abs (offset / 60) % 60);
852 }
853
854 static void
855 init_zone_from_rules (GTimeZone    *gtz,
856                       TimeZoneRule *rules,
857                       gint          rules_num)
858 {
859   guint type_count = 0, trans_count = 0, info_index = 0;
860   guint ri; /* rule index */
861   gboolean skip_first_std_trans = TRUE;
862   gint32 last_offset;
863
864   type_count = 0;
865   trans_count = 0;
866
867   /* Last rule only contains max year */
868   for (ri = 0; ri < rules_num - 1; ri++)
869     {
870       if (rules[ri].dlt_start.mon || rules[ri].dlt_end.mon)
871         {
872           guint rulespan = (rules[ri + 1].start_year - rules[ri].start_year);
873           guint transitions = rules[ri].dlt_start.mon > 0 ? 1 : 0;
874           transitions += rules[ri].dlt_end.mon > 0 ? 1 : 0;
875           type_count += rules[ri].dlt_start.mon > 0 ? 2 : 1;
876           trans_count += transitions * rulespan;
877         }
878       else
879         type_count++;
880     }
881
882   gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), type_count);
883   gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition), trans_count);
884
885   last_offset = rules[0].std_offset;
886
887   for (ri = 0; ri < rules_num - 1; ri++)
888     {
889       if ((rules[ri].std_offset || rules[ri].dlt_offset) &&
890           rules[ri].dlt_start.mon == 0 && rules[ri].dlt_end.mon == 0)
891         {
892           TransitionInfo std_info;
893           /* Standard */
894           fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
895           g_array_append_val (gtz->t_info, std_info);
896
897           if (ri > 0 &&
898               ((rules[ri - 1].dlt_start.mon > 12 &&
899                 rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
900                 rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
901             {
902               /* The previous rule was a southern hemisphere rule that
903                  starts the year with DST, so we need to add a
904                  transition to return to standard time */
905               guint year = rules[ri].start_year;
906               gint64 std_time =  boundary_for_year (&rules[ri].dlt_end,
907                                                     year, last_offset);
908               Transition std_trans = {std_time, info_index};
909               g_array_append_val (gtz->transitions, std_trans);
910
911             }
912           last_offset = rules[ri].std_offset;
913           ++info_index;
914           skip_first_std_trans = TRUE;
915          }
916       else if (rules[ri].std_offset || rules[ri].dlt_offset)
917         {
918           const guint start_year = rules[ri].start_year;
919           const guint end_year = rules[ri + 1].start_year;
920           gboolean dlt_first;
921           guint year;
922           TransitionInfo std_info, dlt_info;
923           if (rules[ri].dlt_start.mon > 12)
924             dlt_first = rules[ri].dlt_start.wday > rules[ri].dlt_end.wday;
925           else
926             dlt_first = rules[ri].dlt_start.mon > rules[ri].dlt_end.mon;
927           /* Standard rules are always even, because before the first
928              transition is always standard time, and 0 is even. */
929           fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
930           fill_transition_info_from_rule (&dlt_info, &(rules[ri]), TRUE);
931
932           g_array_append_val (gtz->t_info, std_info);
933           g_array_append_val (gtz->t_info, dlt_info);
934
935           /* Transition dates. We hope that a year which ends daylight
936              time in a southern-hemisphere country (i.e., one that
937              begins the year in daylight time) will include a rule
938              which has only a dlt_end. */
939           for (year = start_year; year < end_year; year++)
940             {
941               gint32 dlt_offset = (dlt_first ? last_offset :
942                                    rules[ri].dlt_offset);
943               gint32 std_offset = (dlt_first ? rules[ri].std_offset :
944                                    last_offset);
945               /* NB: boundary_for_year returns 0 if mon == 0 */
946               gint64 std_time =  boundary_for_year (&rules[ri].dlt_end,
947                                                     year, dlt_offset);
948               gint64 dlt_time = boundary_for_year (&rules[ri].dlt_start,
949                                                    year, std_offset);
950               Transition std_trans = {std_time, info_index};
951               Transition dlt_trans = {dlt_time, info_index + 1};
952               last_offset = (dlt_first ? rules[ri].dlt_offset :
953                              rules[ri].std_offset);
954               if (dlt_first)
955                 {
956                   if (skip_first_std_trans)
957                     skip_first_std_trans = FALSE;
958                   else if (std_time)
959                     g_array_append_val (gtz->transitions, std_trans);
960                   if (dlt_time)
961                     g_array_append_val (gtz->transitions, dlt_trans);
962                 }
963               else
964                 {
965                   if (dlt_time)
966                     g_array_append_val (gtz->transitions, dlt_trans);
967                   if (std_time)
968                     g_array_append_val (gtz->transitions, std_trans);
969                 }
970             }
971
972           info_index += 2;
973         }
974     }
975   if (ri > 0 &&
976       ((rules[ri - 1].dlt_start.mon > 12 &&
977         rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
978        rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
979     {
980       /* The previous rule was a southern hemisphere rule that
981          starts the year with DST, so we need to add a
982          transition to return to standard time */
983       TransitionInfo info;
984       guint year = rules[ri].start_year;
985       Transition trans;
986       fill_transition_info_from_rule (&info, &(rules[ri - 1]), FALSE);
987       g_array_append_val (gtz->t_info, info);
988       trans.time = boundary_for_year (&rules[ri - 1].dlt_end,
989                                       year, last_offset);
990       trans.info_index = info_index;
991       g_array_append_val (gtz->transitions, trans);
992      }
993 }
994
995 /*
996  * parses date[/time] for parsing TZ environment variable
997  *
998  * date is either Mm.w.d, Jn or N
999  * - m is 1 to 12
1000  * - w is 1 to 5
1001  * - d is 0 to 6
1002  * - n is 1 to 365
1003  * - N is 0 to 365
1004  *
1005  * time is either h or hh[[:]mm[[[:]ss]]]
1006  *  - h[h] is 0 to 23
1007  *  - mm is 00 to 59
1008  *  - ss is 00 to 59
1009  */
1010 static gboolean
1011 parse_mwd_boundary (gchar **pos, TimeZoneDate *boundary)
1012 {
1013   gint month, week, day;
1014
1015   if (**pos == '\0' || **pos < '0' || '9' < **pos)
1016     return FALSE;
1017
1018   month = *(*pos)++ - '0';
1019
1020   if ((month == 1 && **pos >= '0' && '2' >= **pos) ||
1021       (month == 0 && **pos >= '0' && '9' >= **pos))
1022     {
1023       month *= 10;
1024       month += *(*pos)++ - '0';
1025     }
1026
1027   if (*(*pos)++ != '.' || month == 0)
1028     return FALSE;
1029
1030   if (**pos == '\0' || **pos < '1' || '5' < **pos)
1031     return FALSE;
1032
1033   week = *(*pos)++ - '0';
1034
1035   if (*(*pos)++ != '.')
1036     return FALSE;
1037
1038   if (**pos == '\0' || **pos < '0' || '6' < **pos)
1039     return FALSE;
1040
1041   day = *(*pos)++ - '0';
1042
1043   if (!day)
1044     day += 7;
1045
1046   boundary->year = 0;
1047   boundary->mon = month;
1048   boundary->week = week;
1049   boundary->wday = day;
1050   return TRUE;
1051 }
1052
1053 /* Different implementations of tzset interpret the Julian day field
1054    differently. For example, Linux specifies that it should be 1-based
1055    (1 Jan is JD 1) for both Jn and n formats, while zOS and BSD
1056    specify that a Jn JD is 1-based while an n JD is 0-based. Rather
1057    than trying to follow different specs, we will follow GDate's
1058    practice thatIn order to keep it simple, we will follow Linux's
1059    practice. */
1060
1061 static gboolean
1062 parse_julian_boundary (gchar** pos, TimeZoneDate *boundary,
1063                        gboolean ignore_leap)
1064 {
1065   gint day = 0;
1066   GDate date;
1067
1068   while (**pos >= '0' && '9' >= **pos)
1069     {
1070       day *= 10;
1071       day += *(*pos)++ - '0';
1072     }
1073
1074   if (day < 1 || 365 < day)
1075     return FALSE;
1076
1077   g_date_clear (&date, 1);
1078   g_date_set_julian (&date, day);
1079   boundary->year = 0;
1080   boundary->mon = (int) g_date_get_month (&date);
1081   boundary->mday = (int) g_date_get_day (&date);
1082   boundary->wday = 0;
1083
1084   if (!ignore_leap && day >= 59)
1085     boundary->mday++;
1086
1087   return TRUE;
1088 }
1089
1090 static gboolean
1091 parse_tz_boundary (const gchar  *identifier,
1092                    TimeZoneDate *boundary)
1093 {
1094   gchar *pos;
1095
1096   pos = (gchar*)identifier;
1097   /* Month-week-weekday */
1098   if (*pos == 'M')
1099     {
1100       ++pos;
1101       if (!parse_mwd_boundary (&pos, boundary))
1102         return FALSE;
1103     }
1104   /* Julian date which ignores Feb 29 in leap years */
1105   else if (*pos == 'J')
1106     {
1107       ++pos;
1108       if (!parse_julian_boundary (&pos, boundary, FALSE))
1109         return FALSE ;
1110     }
1111   /* Julian date which counts Feb 29 in leap years */
1112   else if (*pos >= '0' && '9' >= *pos)
1113     {
1114       if (!parse_julian_boundary (&pos, boundary, TRUE))
1115         return FALSE;
1116     }
1117   else
1118     return FALSE;
1119
1120   /* Time */
1121
1122   if (*pos == '/')
1123     {
1124       gint32 offset;
1125
1126       if (!parse_time (++pos, &offset))
1127         return FALSE;
1128
1129       boundary->hour = offset / 3600;
1130       boundary->min = (offset / 60) % 60;
1131       boundary->sec = offset % 3600;
1132
1133       return TRUE;
1134     }
1135
1136   else
1137     {
1138       boundary->hour = 2;
1139       boundary->min = 0;
1140       boundary->sec = 0;
1141
1142       return *pos == '\0';
1143     }
1144 }
1145
1146 static gint
1147 create_ruleset_from_rule (TimeZoneRule **rules, TimeZoneRule *rule)
1148 {
1149   *rules = g_new0 (TimeZoneRule, 2);
1150
1151   (*rules)[0].start_year = MIN_TZYEAR;
1152   (*rules)[1].start_year = MAX_TZYEAR;
1153
1154   (*rules)[0].std_offset = -rule->std_offset;
1155   (*rules)[0].dlt_offset = -rule->dlt_offset;
1156   (*rules)[0].dlt_start  = rule->dlt_start;
1157   (*rules)[0].dlt_end = rule->dlt_end;
1158   strcpy ((*rules)[0].std_name, rule->std_name);
1159   strcpy ((*rules)[0].dlt_name, rule->dlt_name);
1160   return 2;
1161 }
1162
1163 static gboolean
1164 parse_offset (gchar **pos, gint32 *target)
1165 {
1166   gchar *buffer;
1167   gchar *target_pos = *pos;
1168   gboolean ret;
1169
1170   while (**pos == '+' || **pos == '-' || **pos == ':' ||
1171          (**pos >= '0' && '9' >= **pos))
1172     ++(*pos);
1173
1174   buffer = g_strndup (target_pos, *pos - target_pos);
1175   ret = parse_constant_offset (buffer, target);
1176   g_free (buffer);
1177
1178   return ret;
1179 }
1180
1181 static gboolean
1182 parse_identifier_boundary (gchar **pos, TimeZoneDate *target)
1183 {
1184   gchar *buffer;
1185   gchar *target_pos = *pos;
1186   gboolean ret;
1187
1188   while (**pos != ',' && **pos != '\0')
1189     ++(*pos);
1190   buffer = g_strndup (target_pos, *pos - target_pos);
1191   ret = parse_tz_boundary (buffer, target);
1192   g_free (buffer);
1193
1194   return ret;
1195 }
1196
1197 static gboolean
1198 set_tz_name (gchar **pos, gchar *buffer, guint size)
1199 {
1200   gchar *name_pos = *pos;
1201   guint len;
1202
1203   /* Name is ASCII alpha (Is this necessarily true?) */
1204   while (g_ascii_isalpha (**pos))
1205     ++(*pos);
1206
1207   /* Name should be three or more alphabetic characters */
1208   if (*pos - name_pos < 3)
1209     return FALSE;
1210
1211   memset (buffer, 0, NAME_SIZE);
1212   /* name_pos isn't 0-terminated, so we have to limit the length expressly */
1213   len = *pos - name_pos > size - 1 ? size - 1 : *pos - name_pos;
1214   strncpy (buffer, name_pos, len);
1215   return TRUE;
1216 }
1217
1218 static gboolean
1219 parse_identifier_boundaries (gchar **pos, TimeZoneRule *tzr)
1220 {
1221   if (*(*pos)++ != ',')
1222     return FALSE;
1223
1224   /* Start date */
1225   if (!parse_identifier_boundary (pos, &(tzr->dlt_start)) || *(*pos)++ != ',')
1226     return FALSE;
1227
1228   /* End date */
1229   if (!parse_identifier_boundary (pos, &(tzr->dlt_end)))
1230     return FALSE;
1231   return TRUE;
1232 }
1233
1234 /*
1235  * Creates an array of TimeZoneRule from a TZ environment variable
1236  * type of identifier.  Should free rules afterwards
1237  */
1238 static gint
1239 rules_from_identifier (const gchar   *identifier,
1240                        TimeZoneRule **rules)
1241 {
1242   gchar *pos;
1243   TimeZoneRule tzr;
1244
1245   if (!identifier)
1246     return 0;
1247
1248   pos = (gchar*)identifier;
1249   memset (&tzr, 0, sizeof (tzr));
1250   /* Standard offset */
1251   if (!(set_tz_name (&pos, tzr.std_name, NAME_SIZE)) ||
1252       !parse_offset (&pos, &(tzr.std_offset)))
1253     return 0;
1254
1255   if (*pos == 0)
1256     return create_ruleset_from_rule (rules, &tzr);
1257
1258   /* Format 2 */
1259   if (!(set_tz_name (&pos, tzr.dlt_name, NAME_SIZE)))
1260     return 0;
1261   parse_offset (&pos, &(tzr.dlt_offset));
1262   if (tzr.dlt_offset == 0) /* No daylight offset given, assume it's 1
1263                               hour earlier that standard */
1264     tzr.dlt_offset = tzr.std_offset - 3600;
1265   if (*pos == '\0')
1266 #ifdef G_OS_WIN32
1267     /* Windows allows us to use the US DST boundaries if they're not given */
1268     {
1269       int i;
1270       guint rules_num = 0;
1271
1272       /* Use US rules, Windows' default is Pacific Standard Time */
1273       if ((rules_num = rules_from_windows_time_zone ("Pacific Standard Time",
1274                                                      rules)))
1275         {
1276           for (i = 0; i < rules_num - 1; i++)
1277             {
1278               (*rules)[i].std_offset = - tzr.std_offset;
1279               (*rules)[i].dlt_offset = - tzr.dlt_offset;
1280               strcpy ((*rules)[i].std_name, tzr.std_name);
1281               strcpy ((*rules)[i].dlt_name, tzr.dlt_name);
1282             }
1283
1284           return rules_num;
1285         }
1286       else
1287         return 0;
1288     }
1289 #else
1290   return 0;
1291 #endif
1292   /* Start and end required (format 2) */
1293   if (!parse_identifier_boundaries (&pos, &tzr))
1294     return 0;
1295
1296   return create_ruleset_from_rule (rules, &tzr);
1297 }
1298
1299 /* Construction {{{1 */
1300 /**
1301  * g_time_zone_new:
1302  * @identifier: (allow-none): a timezone identifier
1303  *
1304  * Creates a #GTimeZone corresponding to @identifier.
1305  *
1306  * @identifier can either be an RFC3339/ISO 8601 time offset or
1307  * something that would pass as a valid value for the `TZ` environment
1308  * variable (including %NULL).
1309  *
1310  * In Windows, @identifier can also be the unlocalized name of a time
1311  * zone for standard time, for example "Pacific Standard Time".
1312  *
1313  * Valid RFC3339 time offsets are <literal>"Z"</literal> (for UTC) or
1314  * <literal>"±hh:mm"</literal>.  ISO 8601 additionally specifies
1315  * <literal>"±hhmm"</literal> and <literal>"±hh"</literal>.  Offsets are
1316  * time values to be added to Coordinated Universal Time (UTC) to get
1317  * the local time.
1318  *
1319  * In UNIX, the `TZ` environment variable typically corresponds
1320  * to the name of a file in the zoneinfo database, or string in
1321  * "std offset [dst [offset],start[/time],end[/time]]" (POSIX) format.
1322  * There  are  no spaces in the specification. The name of standard
1323  * and daylight savings time zone must be three or more alphabetic
1324  * characters. Offsets are time values to be added to local time to
1325  * get Coordinated Universal Time (UTC) and should be
1326  * <literal>"[±]hh[[:]mm[:ss]]"</literal>.  Dates are either
1327  * <literal>"Jn"</literal> (Julian day with n between 1 and 365, leap
1328  * years not counted), <literal>"n"</literal> (zero-based Julian day
1329  * with n between 0 and 365) or <literal>"Mm.w.d"</literal> (day d
1330  * (0 <= d <= 6) of week w (1 <= w <= 5) of month m (1 <= m <= 12), day
1331  * 0 is a Sunday).  Times are in local wall clock time, the default is
1332  * 02:00:00.
1333  *
1334  * In Windows, the "tzn[+|–]hh[:mm[:ss]][dzn]" format is used, but also
1335  * accepts POSIX format.  The Windows format uses US rules for all time
1336  * zones; daylight savings time is 60 minutes behind the standard time
1337  * with date and time of change taken from Pacific Standard Time.
1338  * Offsets are time values to be added to the local time to get
1339  * Coordinated Universal Time (UTC).
1340  *
1341  * g_time_zone_new_local() calls this function with the value of the
1342  * `TZ` environment variable. This function itself is independent of
1343  * the value of `TZ`, but if @identifier is %NULL then `/etc/localtime`
1344  * will be consulted to discover the correct time zone on UNIX and the
1345  * registry will be consulted or GetTimeZoneInformation() will be used
1346  * to get the local time zone on Windows.
1347  *
1348  * If intervals are not available, only time zone rules from `TZ`
1349  * environment variable or other means, then they will be computed
1350  * from year 1900 to 2037.  If the maximum year for the rules is
1351  * available and it is greater than 2037, then it will followed
1352  * instead.
1353  *
1354  * See <ulink
1355  * url='http://tools.ietf.org/html/rfc3339#section-5.6'>RFC3339
1356  * §5.6</ulink> for a precise definition of valid RFC3339 time offsets
1357  * (the <literal>time-offset</literal> expansion) and ISO 8601 for the
1358  * full list of valid time offsets.  See <ulink
1359  * url='http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html'>The
1360  * GNU C Library manual</ulink> for an explanation of the possible
1361  * values of the `TZ` environment variable.  See <ulink
1362  * url='http://msdn.microsoft.com/en-us/library/ms912391%28v=winembedded.11%29.aspx'>
1363  * Microsoft Time Zone Index Values</ulink> for the list of time zones
1364  * on Windows.
1365  *
1366  * You should release the return value by calling g_time_zone_unref()
1367  * when you are done with it.
1368  *
1369  * Returns: the requested timezone
1370  *
1371  * Since: 2.26
1372  **/
1373 GTimeZone *
1374 g_time_zone_new (const gchar *identifier)
1375 {
1376   GTimeZone *tz = NULL;
1377   TimeZoneRule *rules;
1378   gint rules_num;
1379
1380   G_LOCK (time_zones);
1381   if (time_zones == NULL)
1382     time_zones = g_hash_table_new (g_str_hash, g_str_equal);
1383
1384   if (identifier)
1385     {
1386       tz = g_hash_table_lookup (time_zones, identifier);
1387       if (tz)
1388         {
1389           g_atomic_int_inc (&tz->ref_count);
1390           G_UNLOCK (time_zones);
1391           return tz;
1392         }
1393     }
1394
1395   tz = g_slice_new0 (GTimeZone);
1396   tz->name = g_strdup (identifier);
1397   tz->ref_count = 0;
1398
1399   zone_for_constant_offset (tz, identifier);
1400
1401   if (tz->t_info == NULL &&
1402       (rules_num = rules_from_identifier (identifier, &rules)))
1403     {
1404       init_zone_from_rules (tz, rules, rules_num);
1405       g_free (rules);
1406     }
1407
1408   if (tz->t_info == NULL)
1409     {
1410 #ifdef G_OS_UNIX
1411       GBytes *zoneinfo = zone_info_unix (identifier);
1412       if (!zoneinfo)
1413         zone_for_constant_offset (tz, "UTC");
1414       else
1415         {
1416           init_zone_from_iana_info (tz, zoneinfo);
1417           g_bytes_unref (zoneinfo);
1418         }
1419 #elif defined (G_OS_WIN32)
1420       if ((rules_num = rules_from_windows_time_zone (identifier, &rules)))
1421         {
1422           init_zone_from_rules (tz, rules, rules_num);
1423           g_free (rules);
1424         }
1425     }
1426
1427   if (tz->t_info == NULL)
1428     {
1429       if (identifier)
1430         zone_for_constant_offset (tz, "UTC");
1431       else
1432         {
1433           TIME_ZONE_INFORMATION tzi;
1434
1435           if (GetTimeZoneInformation (&tzi) != TIME_ZONE_ID_INVALID)
1436             {
1437               rules = g_new0 (TimeZoneRule, 2);
1438
1439               rule_from_windows_time_zone_info (&rules[0], &tzi);
1440
1441               memset (rules[0].std_name, 0, NAME_SIZE);
1442               memset (rules[0].dlt_name, 0, NAME_SIZE);
1443
1444               rules[0].start_year = MIN_TZYEAR;
1445               rules[1].start_year = MAX_TZYEAR;
1446
1447               init_zone_from_rules (tz, rules, 2);
1448
1449               g_free (rules);
1450             }
1451         }
1452 #endif
1453     }
1454
1455   if (tz->t_info != NULL)
1456     {
1457       if (identifier)
1458         g_hash_table_insert (time_zones, tz->name, tz);
1459     }
1460   g_atomic_int_inc (&tz->ref_count);
1461   G_UNLOCK (time_zones);
1462
1463   return tz;
1464 }
1465
1466 /**
1467  * g_time_zone_new_utc:
1468  *
1469  * Creates a #GTimeZone corresponding to UTC.
1470  *
1471  * This is equivalent to calling g_time_zone_new() with a value like
1472  * "Z", "UTC", "+00", etc.
1473  *
1474  * You should release the return value by calling g_time_zone_unref()
1475  * when you are done with it.
1476  *
1477  * Returns: the universal timezone
1478  *
1479  * Since: 2.26
1480  **/
1481 GTimeZone *
1482 g_time_zone_new_utc (void)
1483 {
1484   return g_time_zone_new ("UTC");
1485 }
1486
1487 /**
1488  * g_time_zone_new_local:
1489  *
1490  * Creates a #GTimeZone corresponding to local time.  The local time
1491  * zone may change between invocations to this function; for example,
1492  * if the system administrator changes it.
1493  *
1494  * This is equivalent to calling g_time_zone_new() with the value of
1495  * the `TZ` environment variable (including the possibility of %NULL).
1496  *
1497  * You should release the return value by calling g_time_zone_unref()
1498  * when you are done with it.
1499  *
1500  * Returns: the local timezone
1501  *
1502  * Since: 2.26
1503  **/
1504 GTimeZone *
1505 g_time_zone_new_local (void)
1506 {
1507   return g_time_zone_new (getenv ("TZ"));
1508 }
1509
1510 #define TRANSITION(n)         g_array_index (tz->transitions, Transition, n)
1511 #define TRANSITION_INFO(n)    g_array_index (tz->t_info, TransitionInfo, n)
1512
1513 /* Internal helpers {{{1 */
1514 /* NB: Interval 0 is before the first transition, so there's no
1515  * transition structure to point to which TransitionInfo to
1516  * use. Rule-based zones are set up so that TI 0 is always standard
1517  * time (which is what's in effect before Daylight time got started
1518  * in the early 20th century), but IANA tzfiles don't follow that
1519  * convention. The tzfile documentation says to use the first
1520  * standard-time (i.e., non-DST) tinfo, so that's what we do.
1521  */
1522 inline static const TransitionInfo*
1523 interval_info (GTimeZone *tz,
1524                guint      interval)
1525 {
1526   guint index;
1527   g_return_val_if_fail (tz->t_info != NULL, NULL);
1528   if (interval && tz->transitions && interval <= tz->transitions->len)
1529     index = (TRANSITION(interval - 1)).info_index;
1530   else
1531     {
1532       for (index = 0; index < tz->t_info->len; index++)
1533         {
1534           TransitionInfo *tzinfo = &(TRANSITION_INFO(index));
1535           if (!tzinfo->is_dst)
1536             return tzinfo;
1537         }
1538       index = 0;
1539     }
1540
1541   return &(TRANSITION_INFO(index));
1542 }
1543
1544 inline static gint64
1545 interval_start (GTimeZone *tz,
1546                 guint      interval)
1547 {
1548   if (!interval || tz->transitions == NULL || tz->transitions->len == 0)
1549     return G_MININT64;
1550   if (interval > tz->transitions->len)
1551     interval = tz->transitions->len;
1552   return (TRANSITION(interval - 1)).time;
1553 }
1554
1555 inline static gint64
1556 interval_end (GTimeZone *tz,
1557               guint      interval)
1558 {
1559   if (tz->transitions && interval < tz->transitions->len)
1560     return (TRANSITION(interval)).time - 1;
1561   return G_MAXINT64;
1562 }
1563
1564 inline static gint32
1565 interval_offset (GTimeZone *tz,
1566                  guint      interval)
1567 {
1568   g_return_val_if_fail (tz->t_info != NULL, 0);
1569   return interval_info (tz, interval)->gmt_offset;
1570 }
1571
1572 inline static gboolean
1573 interval_isdst (GTimeZone *tz,
1574                 guint      interval)
1575 {
1576   g_return_val_if_fail (tz->t_info != NULL, 0);
1577   return interval_info (tz, interval)->is_dst;
1578 }
1579
1580
1581 inline static gboolean
1582 interval_isgmt (GTimeZone *tz,
1583                 guint      interval)
1584 {
1585   g_return_val_if_fail (tz->t_info != NULL, 0);
1586   return interval_info (tz, interval)->is_gmt;
1587 }
1588
1589 inline static gboolean
1590 interval_isstandard (GTimeZone *tz,
1591                 guint      interval)
1592 {
1593   return interval_info (tz, interval)->is_standard;
1594 }
1595
1596 inline static gchar*
1597 interval_abbrev (GTimeZone *tz,
1598                   guint      interval)
1599 {
1600   g_return_val_if_fail (tz->t_info != NULL, 0);
1601   return interval_info (tz, interval)->abbrev;
1602 }
1603
1604 inline static gint64
1605 interval_local_start (GTimeZone *tz,
1606                       guint      interval)
1607 {
1608   if (interval)
1609     return interval_start (tz, interval) + interval_offset (tz, interval);
1610
1611   return G_MININT64;
1612 }
1613
1614 inline static gint64
1615 interval_local_end (GTimeZone *tz,
1616                     guint      interval)
1617 {
1618   if (tz->transitions && interval < tz->transitions->len)
1619     return interval_end (tz, interval) + interval_offset (tz, interval);
1620
1621   return G_MAXINT64;
1622 }
1623
1624 static gboolean
1625 interval_valid (GTimeZone *tz,
1626                 guint      interval)
1627 {
1628   if ( tz->transitions == NULL)
1629     return interval == 0;
1630   return interval <= tz->transitions->len;
1631 }
1632
1633 /* g_time_zone_find_interval() {{{1 */
1634
1635 /**
1636  * g_time_zone_adjust_time:
1637  * @tz: a #GTimeZone
1638  * @type: the #GTimeType of @time_
1639  * @time_: a pointer to a number of seconds since January 1, 1970
1640  *
1641  * Finds an interval within @tz that corresponds to the given @time_,
1642  * possibly adjusting @time_ if required to fit into an interval.
1643  * The meaning of @time_ depends on @type.
1644  *
1645  * This function is similar to g_time_zone_find_interval(), with the
1646  * difference that it always succeeds (by making the adjustments
1647  * described below).
1648  *
1649  * In any of the cases where g_time_zone_find_interval() succeeds then
1650  * this function returns the same value, without modifying @time_.
1651  *
1652  * This function may, however, modify @time_ in order to deal with
1653  * non-existent times.  If the non-existent local @time_ of 02:30 were
1654  * requested on March 14th 2010 in Toronto then this function would
1655  * adjust @time_ to be 03:00 and return the interval containing the
1656  * adjusted time.
1657  *
1658  * Returns: the interval containing @time_, never -1
1659  *
1660  * Since: 2.26
1661  **/
1662 gint
1663 g_time_zone_adjust_time (GTimeZone *tz,
1664                          GTimeType  type,
1665                          gint64    *time_)
1666 {
1667   gint i;
1668   guint intervals;
1669
1670   if (tz->transitions == NULL)
1671     return 0;
1672
1673   intervals = tz->transitions->len;
1674
1675   /* find the interval containing *time UTC
1676    * TODO: this could be binary searched (or better) */
1677   for (i = 0; i <= intervals; i++)
1678     if (*time_ <= interval_end (tz, i))
1679       break;
1680
1681   g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
1682
1683   if (type != G_TIME_TYPE_UNIVERSAL)
1684     {
1685       if (*time_ < interval_local_start (tz, i))
1686         /* if time came before the start of this interval... */
1687         {
1688           i--;
1689
1690           /* if it's not in the previous interval... */
1691           if (*time_ > interval_local_end (tz, i))
1692             {
1693               /* it doesn't exist.  fast-forward it. */
1694               i++;
1695               *time_ = interval_local_start (tz, i);
1696             }
1697         }
1698
1699       else if (*time_ > interval_local_end (tz, i))
1700         /* if time came after the end of this interval... */
1701         {
1702           i++;
1703
1704           /* if it's not in the next interval... */
1705           if (*time_ < interval_local_start (tz, i))
1706             /* it doesn't exist.  fast-forward it. */
1707             *time_ = interval_local_start (tz, i);
1708         }
1709
1710       else if (interval_isdst (tz, i) != type)
1711         /* it's in this interval, but dst flag doesn't match.
1712          * check neighbours for a better fit. */
1713         {
1714           if (i && *time_ <= interval_local_end (tz, i - 1))
1715             i--;
1716
1717           else if (i < intervals &&
1718                    *time_ >= interval_local_start (tz, i + 1))
1719             i++;
1720         }
1721     }
1722
1723   return i;
1724 }
1725
1726 /**
1727  * g_time_zone_find_interval:
1728  * @tz: a #GTimeZone
1729  * @type: the #GTimeType of @time_
1730  * @time_: a number of seconds since January 1, 1970
1731  *
1732  * Finds an the interval within @tz that corresponds to the given @time_.
1733  * The meaning of @time_ depends on @type.
1734  *
1735  * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
1736  * succeed (since universal time is monotonic and continuous).
1737  *
1738  * Otherwise @time_ is treated is local time.  The distinction between
1739  * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
1740  * the case that the given @time_ is ambiguous.  In Toronto, for example,
1741  * 01:30 on November 7th 2010 occurred twice (once inside of daylight
1742  * savings time and the next, an hour later, outside of daylight savings
1743  * time).  In this case, the different value of @type would result in a
1744  * different interval being returned.
1745  *
1746  * It is still possible for this function to fail.  In Toronto, for
1747  * example, 02:00 on March 14th 2010 does not exist (due to the leap
1748  * forward to begin daylight savings time).  -1 is returned in that
1749  * case.
1750  *
1751  * Returns: the interval containing @time_, or -1 in case of failure
1752  *
1753  * Since: 2.26
1754  */
1755 gint
1756 g_time_zone_find_interval (GTimeZone *tz,
1757                            GTimeType  type,
1758                            gint64     time_)
1759 {
1760   gint i;
1761   guint intervals;
1762
1763   if (tz->transitions == NULL)
1764     return 0;
1765   intervals = tz->transitions->len;
1766   for (i = 0; i <= intervals; i++)
1767     if (time_ <= interval_end (tz, i))
1768       break;
1769
1770   if (type == G_TIME_TYPE_UNIVERSAL)
1771     return i;
1772
1773   if (time_ < interval_local_start (tz, i))
1774     {
1775       if (time_ > interval_local_end (tz, --i))
1776         return -1;
1777     }
1778
1779   else if (time_ > interval_local_end (tz, i))
1780     {
1781       if (time_ < interval_local_start (tz, ++i))
1782         return -1;
1783     }
1784
1785   else if (interval_isdst (tz, i) != type)
1786     {
1787       if (i && time_ <= interval_local_end (tz, i - 1))
1788         i--;
1789
1790       else if (i < intervals && time_ >= interval_local_start (tz, i + 1))
1791         i++;
1792     }
1793
1794   return i;
1795 }
1796
1797 /* Public API accessors {{{1 */
1798
1799 /**
1800  * g_time_zone_get_abbreviation:
1801  * @tz: a #GTimeZone
1802  * @interval: an interval within the timezone
1803  *
1804  * Determines the time zone abbreviation to be used during a particular
1805  * @interval of time in the time zone @tz.
1806  *
1807  * For example, in Toronto this is currently "EST" during the winter
1808  * months and "EDT" during the summer months when daylight savings time
1809  * is in effect.
1810  *
1811  * Returns: the time zone abbreviation, which belongs to @tz
1812  *
1813  * Since: 2.26
1814  **/
1815 const gchar *
1816 g_time_zone_get_abbreviation (GTimeZone *tz,
1817                               gint       interval)
1818 {
1819   g_return_val_if_fail (interval_valid (tz, (guint)interval), NULL);
1820
1821   return interval_abbrev (tz, (guint)interval);
1822 }
1823
1824 /**
1825  * g_time_zone_get_offset:
1826  * @tz: a #GTimeZone
1827  * @interval: an interval within the timezone
1828  *
1829  * Determines the offset to UTC in effect during a particular @interval
1830  * of time in the time zone @tz.
1831  *
1832  * The offset is the number of seconds that you add to UTC time to
1833  * arrive at local time for @tz (ie: negative numbers for time zones
1834  * west of GMT, positive numbers for east).
1835  *
1836  * Returns: the number of seconds that should be added to UTC to get the
1837  *          local time in @tz
1838  *
1839  * Since: 2.26
1840  **/
1841 gint32
1842 g_time_zone_get_offset (GTimeZone *tz,
1843                         gint       interval)
1844 {
1845   g_return_val_if_fail (interval_valid (tz, (guint)interval), 0);
1846
1847   return interval_offset (tz, (guint)interval);
1848 }
1849
1850 /**
1851  * g_time_zone_is_dst:
1852  * @tz: a #GTimeZone
1853  * @interval: an interval within the timezone
1854  *
1855  * Determines if daylight savings time is in effect during a particular
1856  * @interval of time in the time zone @tz.
1857  *
1858  * Returns: %TRUE if daylight savings time is in effect
1859  *
1860  * Since: 2.26
1861  **/
1862 gboolean
1863 g_time_zone_is_dst (GTimeZone *tz,
1864                     gint       interval)
1865 {
1866   g_return_val_if_fail (interval_valid (tz, interval), FALSE);
1867
1868   if (tz->transitions == NULL)
1869     return FALSE;
1870
1871   return interval_isdst (tz, (guint)interval);
1872 }
1873
1874 /* Epilogue {{{1 */
1875 /* vim:set foldmethod=marker: */