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