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