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