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