Coverage Report

Created: 2025-07-17 06:56

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