Merge remote branch 'gvdb/master'
[platform/upstream/glib.git] / glib / gtimezone.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 /* Prologue {{{1 */
23
24 #include "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 "gbuffer.h"
37
38 /**
39  * SECTION:timezone
40  * @title: GTimeZone
41  * @short_description: A structure representing a time zone
42  * @see_also: #GDateTime
43  *
44  * #GTimeZone is a structure that represents a time zone, at no
45  * particular point in time.  It is refcounted and immutable.
46  *
47  * A time zone contains a number of intervals.  Each interval has
48  * an abbreviation to describe it, an offet to UTC and a flag indicating
49  * if the daylight savings time is in effect during that interval.  A
50  * time zone always has at least one interval -- interval 0.
51  *
52  * Every UTC time is contained within exactly one interval, but a given
53  * local time may be contained within zero, one or two intervals (due to
54  * incontinuities associated with daylight savings time).
55  *
56  * An interval may refer to a specific period of time (eg: the duration
57  * of daylight savings time during 2010) or it may refer to many periods
58  * of time that share the same properties (eg: all periods of daylight
59  * savings time).  It is also possible (usually for political reasons)
60  * that some properties (like the abbreviation) change between intervals
61  * without other properties changing.
62  *
63  * #GTimeZone is available since GLib 2.26.
64  */
65
66 /**
67  * GTimeZone:
68  *
69  * #GDateTime is an opaque structure whose members cannot be accessed
70  * directly.
71  *
72  * Since: 2.26
73  **/
74
75 /* zoneinfo file format {{{1 */
76
77 /* unaligned */
78 typedef struct { gchar bytes[8]; } gint64_be;
79 typedef struct { gchar bytes[4]; } gint32_be;
80 typedef struct { gchar bytes[4]; } guint32_be;
81
82 static inline gint64 gint64_from_be (const gint64_be be) {
83   gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
84 }
85
86 static inline gint32 gint32_from_be (const gint32_be be) {
87   gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
88 }
89
90 static inline guint32 guint32_from_be (const guint32_be be) {
91   guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
92 }
93
94 struct tzhead
95 {
96   gchar      tzh_magic[4];
97   gchar      tzh_version;
98   guchar     tzh_reserved[15];
99
100   guint32_be tzh_ttisgmtcnt;
101   guint32_be tzh_ttisstdcnt;
102   guint32_be tzh_leapcnt;
103   guint32_be tzh_timecnt;
104   guint32_be tzh_typecnt;
105   guint32_be tzh_charcnt;
106 };
107
108 struct ttinfo
109 {
110   gint32_be tt_gmtoff;
111   guint8    tt_isdst;
112   guint8    tt_abbrind;
113 };
114
115 /* GTimeZone structure and lifecycle {{{1 */
116 struct _GTimeZone
117 {
118   gchar   *name;
119
120   GBuffer *zoneinfo;
121
122   const struct tzhead *header;
123   const struct ttinfo *infos;
124   const gint64_be     *trans;
125   const guint8        *indices;
126   const gchar         *abbrs;
127   gint                 timecnt;
128
129   gint     ref_count;
130 };
131
132 G_LOCK_DEFINE_STATIC (time_zones);
133 static GHashTable/*<string?, GTimeZone>*/ *time_zones;
134
135 static guint
136 g_str_hash0 (gconstpointer data)
137 {
138   return data ? g_str_hash (data) : 0;
139 }
140
141 static gboolean
142 g_str_equal0 (gconstpointer a,
143               gconstpointer b)
144 {
145   if (a == b)
146     return TRUE;
147
148   if (!a || !b)
149     return FALSE;
150
151   return g_str_equal (a, b);
152 }
153
154 /**
155  * g_time_zone_unref:
156  * @tz: a #GTimeZone
157  *
158  * Decreases the reference count on @tz.
159  *
160  * Since: 2.26
161  **/
162 void
163 g_time_zone_unref (GTimeZone *tz)
164 {
165   g_assert (tz->ref_count > 0);
166
167   if (g_atomic_int_dec_and_test (&tz->ref_count))
168     {
169       G_LOCK(time_zones);
170       g_hash_table_remove (time_zones, tz->name);
171       G_UNLOCK(time_zones);
172
173       if (tz->zoneinfo)
174         g_buffer_unref (tz->zoneinfo);
175
176       g_free (tz->name);
177
178       g_slice_free (GTimeZone, tz);
179     }
180 }
181
182 /**
183  * g_time_zone_ref:
184  * @tz: a #GTimeZone
185  *
186  * Increases the reference count on @tz.
187  *
188  * Returns: a new reference to @tz.
189  *
190  * Since: 2.26
191  **/
192 GTimeZone *
193 g_time_zone_ref (GTimeZone *tz)
194 {
195   g_assert (tz->ref_count > 0);
196
197   g_atomic_int_inc (&tz->ref_count);
198
199   return tz;
200 }
201
202 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
203 /*
204  * parses strings of the form 'hh' 'hhmm' or 'hh:mm' where:
205  *  - hh is 00 to 23
206  *  - mm is 00 to 59
207  */
208 static gboolean
209 parse_time (const gchar *time,
210             gint32      *offset)
211 {
212   if (*time < '0' || '2' < *time)
213     return FALSE;
214
215   *offset = 10 * 60 * 60 * (*time++ - '0');
216
217   if (*time < '0' || '9' < *time)
218     return FALSE;
219
220   *offset += 60 * 60 * (*time++ - '0');
221
222   if (*offset > 23 * 60 * 60)
223     return FALSE;
224
225   if (*time == '\0')
226     return TRUE;
227
228   if (*time == ':')
229     time++;
230
231   if (*time < '0' || '5' < *time)
232     return FALSE;
233
234   *offset += 10 * 60 * (*time++ - '0');
235
236   if (*time < '0' || '9' < *time)
237     return FALSE;
238
239   *offset += 60 * (*time++ - '0');
240
241   return *time == '\0';
242 }
243
244 static gboolean
245 parse_constant_offset (const gchar *name,
246                        gint32      *offset)
247 {
248   switch (*name++)
249     {
250     case 'Z':
251       *offset = 0;
252       return !*name;
253
254     case '+':
255       return parse_time (name, offset);
256
257     case '-':
258       if (parse_time (name, offset))
259         {
260           *offset = -*offset;
261           return TRUE;
262         }
263
264     default:
265       return FALSE;
266     }
267 }
268
269 static GBuffer *
270 zone_for_constant_offset (const gchar *name)
271 {
272   const gchar fake_zoneinfo_headers[] =
273     "TZif" "2..." "...." "...." "...."
274     "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0"
275     "TZif" "2..." "...." "...." "...."
276     "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\1" "\0\0\0\7";
277   struct {
278     struct tzhead headers[2];
279     struct ttinfo info;
280     gchar abbr[8];
281   } *fake;
282   gint32 offset;
283
284   if (name == NULL || !parse_constant_offset (name, &offset))
285     return NULL;
286
287   offset = GINT32_TO_BE (offset);
288
289   fake = g_malloc (sizeof *fake);
290   memcpy (fake, fake_zoneinfo_headers, sizeof fake_zoneinfo_headers);
291   memcpy (&fake->info.tt_gmtoff, &offset, sizeof offset);
292   fake->info.tt_isdst = FALSE;
293   fake->info.tt_abbrind = 0;
294   strcpy (fake->abbr, name);
295
296   return g_buffer_new_take_data (fake, sizeof *fake);
297 }
298
299 /* Construction {{{1 */
300 /**
301  * g_time_zone_new:
302  * @identifier: (allow-none): a timezone identifier
303  *
304  * Creates a #GTimeZone corresponding to @identifier.
305  *
306  * @identifier can either be an RFC3339/ISO 8601 time offset or
307  * something that would pass as a valid value for the
308  * <varname>TZ</varname> environment variable (including %NULL).
309  *
310  * Valid RFC3339 time offsets are <literal>"Z"</literal> (for UTC) or
311  * <literal>"±hh:mm"</literal>.  ISO 8601 additionally specifies
312  * <literal>"±hhmm"</literal> and <literal>"±hh"</literal>.
313  *
314  * The <varname>TZ</varname> environment variable typically corresponds
315  * to the name of a file in the zoneinfo database, but there are many
316  * other possibilities.  Note that those other possibilities are not
317  * currently implemented, but are planned.
318  *
319  * g_time_zone_new_local() calls this function with the value of the
320  * <varname>TZ</varname> environment variable.  This function itself is
321  * independent of the value of <varname>TZ</varname>, but if @identifier
322  * is %NULL then <filename>/etc/localtime</filename> will be consulted
323  * to discover the correct timezone.
324  *
325  * See <ulink
326  * url='http://tools.ietf.org/html/rfc3339#section-5.6'>RFC3339
327  * §5.6</ulink> for a precise definition of valid RFC3339 time offsets
328  * (the <varname>time-offset</varname> expansion) and ISO 8601 for the
329  * full list of valid time offsets.  See <ulink
330  * url='http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html'>The
331  * GNU C Library manual</ulink> for an explanation of the possible
332  * values of the <varname>TZ</varname> environment variable.
333  *
334  * You should release the return value by calling g_time_zone_unref()
335  * when you are done with it.
336  *
337  * Returns: the requested timezone
338  *
339  * Since: 2.26
340  **/
341 GTimeZone *
342 g_time_zone_new (const gchar *identifier)
343 {
344   GTimeZone *tz;
345
346   G_LOCK (time_zones);
347   if (time_zones == NULL)
348     time_zones = g_hash_table_new (g_str_hash0,
349                                    g_str_equal0);
350
351   tz = g_hash_table_lookup (time_zones, identifier);
352   if (tz == NULL)
353     {
354       tz = g_slice_new0 (GTimeZone);
355       tz->name = g_strdup (identifier);
356       tz->ref_count = 0;
357
358       tz->zoneinfo = zone_for_constant_offset (identifier);
359
360       if (tz->zoneinfo == NULL)
361         {
362           gchar *filename;
363
364           if (identifier != NULL)
365             {
366               const gchar *tzdir;
367
368               tzdir = getenv ("TZDIR");
369               if (tzdir == NULL)
370                 tzdir = "/usr/share/zoneinfo";
371
372               filename = g_build_filename (tzdir, identifier, NULL);
373             }
374           else
375             filename = g_strdup ("/etc/localtime");
376
377           tz->zoneinfo = (GBuffer *) g_mapped_file_new (filename, FALSE, NULL);
378           g_free (filename);
379         }
380
381       if (tz->zoneinfo != NULL)
382         {
383           const struct tzhead *header = tz->zoneinfo->data;
384           gsize size = tz->zoneinfo->size;
385
386           /* we only bother to support version 2 */
387           if (size < sizeof (struct tzhead) || memcmp (header, "TZif2", 5))
388             {
389               g_buffer_unref (tz->zoneinfo);
390               tz->zoneinfo = NULL;
391             }
392           else
393             {
394               gint typecnt;
395
396               /* we trust the file completely. */
397               tz->header = (const struct tzhead *)
398                 (((const gchar *) (header + 1)) +
399                   guint32_from_be(header->tzh_ttisgmtcnt) +
400                   guint32_from_be(header->tzh_ttisstdcnt) +
401                   8 * guint32_from_be(header->tzh_leapcnt) +
402                   5 * guint32_from_be(header->tzh_timecnt) +
403                   6 * guint32_from_be(header->tzh_typecnt) +
404                   guint32_from_be(header->tzh_charcnt));
405
406               typecnt     = guint32_from_be (tz->header->tzh_typecnt);
407               tz->timecnt = guint32_from_be (tz->header->tzh_timecnt);
408               tz->trans   = (gconstpointer) (tz->header + 1);
409               tz->indices = (gconstpointer) (tz->trans + tz->timecnt);
410               tz->infos   = (gconstpointer) (tz->indices + tz->timecnt);
411               tz->abbrs   = (gconstpointer) (tz->infos + typecnt);
412             }
413         }
414
415       g_hash_table_insert (time_zones, tz->name, tz);
416     }
417   g_atomic_int_inc (&tz->ref_count);
418   G_UNLOCK (time_zones);
419
420   return tz;
421 }
422
423 /**
424  * g_time_zone_new_utc:
425  *
426  * Creates a #GTimeZone corresponding to UTC.
427  *
428  * This is equivalent to calling g_time_zone_new() with a value like
429  * "Z", "UTC", "+00", etc.
430  *
431  * You should release the return value by calling g_time_zone_unref()
432  * when you are done with it.
433  *
434  * Returns: the universal timezone
435  *
436  * Since: 2.26
437  **/
438 GTimeZone *
439 g_time_zone_new_utc (void)
440 {
441   return g_time_zone_new ("UTC");
442 }
443
444 /**
445  * g_time_zone_new_local:
446  *
447  * Creates a #GTimeZone corresponding to local time.
448  *
449  * This is equivalent to calling g_time_zone_new() with the value of the
450  * <varname>TZ</varname> environment variable (including the possibility
451  * of %NULL).  Changes made to <varname>TZ</varname> after the first
452  * call to this function may or may not be noticed by future calls.
453  *
454  * You should release the return value by calling g_time_zone_unref()
455  * when you are done with it.
456  *
457  * Returns: the local timezone
458  *
459  * Since: 2.26
460  **/
461 GTimeZone *
462 g_time_zone_new_local (void)
463 {
464   return g_time_zone_new (getenv ("TZ"));
465 }
466
467 /* Internal helpers {{{1 */
468 inline static const struct ttinfo *
469 interval_info (GTimeZone *tz,
470                gint       interval)
471 {
472   if (interval)
473     return tz->infos + tz->indices[interval - 1];
474
475   return tz->infos;
476 }
477
478 inline static gint64
479 interval_start (GTimeZone *tz,
480                 gint       interval)
481 {
482   if (interval)
483     return gint64_from_be (tz->trans[interval - 1]);
484
485   return G_MININT64;
486 }
487
488 inline static gint64
489 interval_end (GTimeZone *tz,
490               gint       interval)
491 {
492   if (interval < tz->timecnt)
493     return gint64_from_be (tz->trans[interval]) - 1;
494
495   return G_MAXINT64;
496 }
497
498 inline static gint32
499 interval_offset (GTimeZone *tz,
500                  gint       interval)
501 {
502   return gint32_from_be (interval_info (tz, interval)->tt_gmtoff);
503 }
504
505 inline static gboolean
506 interval_isdst (GTimeZone *tz,
507                 gint       interval)
508 {
509   return interval_info (tz, interval)->tt_isdst;
510 }
511
512 inline static guint8
513 interval_abbrind (GTimeZone *tz,
514                   gint       interval)
515 {
516   return interval_info (tz, interval)->tt_abbrind;
517 }
518
519 inline static gint64
520 interval_local_start (GTimeZone *tz,
521                       gint       interval)
522 {
523   if (interval)
524     return interval_start (tz, interval) + interval_offset (tz, interval);
525
526   return G_MININT64;
527 }
528
529 inline static gint64
530 interval_local_end (GTimeZone *tz,
531                     gint       interval)
532 {
533   if (interval < tz->timecnt)
534     return interval_end (tz, interval) + interval_offset (tz, interval);
535
536   return G_MAXINT64;
537 }
538
539 static gboolean
540 interval_valid (GTimeZone *tz,
541                 gint       interval)
542 {
543   return interval <= tz->timecnt;
544 }
545
546 /* g_time_zone_find_interval() {{{1 */
547
548 /**
549  * g_time_zone_adjust_time:
550  * @tz: a #GTimeZone
551  * @type: the #GTimeType of @time
552  * @time: a pointer to a number of seconds since January 1, 1970
553  *
554  * Finds an interval within @tz that corresponds to the given @time,
555  * possibly adjusting @time if required to fit into an interval.
556  * The meaning of @time depends on @type.
557  *
558  * This function is similar to g_time_zone_find_interval(), with the
559  * difference that it always succeeds (by making the adjustments
560  * described below).
561  *
562  * In any of the cases where g_time_zone_find_interval() succeeds then
563  * this function returns the same value, without modifying @time.
564  *
565  * This function may, however, modify @time in order to deal with
566  * non-existent times.  If the non-existent local @time of 02:30 were
567  * requested on March 13th 2010 in Toronto then this function would
568  * adjust @time to be 03:00 and return the interval containing the
569  * adjusted time.
570  *
571  * Returns: the interval containing @time, never -1
572  *
573  * Since: 2.26
574  **/
575 gint
576 g_time_zone_adjust_time (GTimeZone *tz,
577                          GTimeType  type,
578                          gint64    *time)
579 {
580   gint i;
581
582   if (tz->zoneinfo == NULL)
583     return 0;
584
585   /* find the interval containing *time UTC
586    * TODO: this could be binary searched (or better) */
587   for (i = 0; i < tz->timecnt; i++)
588     if (*time <= interval_end (tz, i))
589       break;
590
591   g_assert (interval_start (tz, i) <= *time && *time <= interval_end (tz, i));
592
593   if (type != G_TIME_TYPE_UNIVERSAL)
594     {
595       if (*time < interval_local_start (tz, i))
596         /* if time came before the start of this interval... */
597         {
598           i--;
599
600           /* if it's not in the previous interval... */
601           if (*time > interval_local_end (tz, i))
602             {
603               /* it doesn't exist.  fast-forward it. */
604               i++;
605               *time = interval_local_start (tz, i);
606             }
607         }
608
609       else if (*time > interval_local_end (tz, i))
610         /* if time came after the end of this interval... */
611         {
612           i++;
613
614           /* if it's not in the next interval... */
615           if (*time < interval_local_start (tz, i))
616             /* it doesn't exist.  fast-forward it. */
617             *time = interval_local_start (tz, i);
618         }
619
620       else if (interval_isdst (tz, i) != type)
621         /* it's in this interval, but dst flag doesn't match.
622          * check neighbours for a better fit. */
623         {
624           if (i && *time <= interval_local_end (tz, i - 1))
625             i--;
626
627           else if (i < tz->timecnt &&
628                    *time >= interval_local_start (tz, i + 1))
629             i++;
630         }
631     }
632
633   return i;
634 }
635
636 /**
637  * g_time_zone_find_interval:
638  * @tz: a #GTimeZone
639  * @type: the #GTimeType of @time
640  * @time: a number of seconds since January 1, 1970
641  *
642  * Finds an the interval within @tz that corresponds to the given @time.
643  * The meaning of @time depends on @type.
644  *
645  * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
646  * succeed (since universal time is monotonic and continuous).
647  *
648  * Otherwise @time is treated is local time.  The distinction between
649  * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
650  * the case that the given @time is ambiguous.  In Toronto, for example,
651  * 01:30 on November 7th 2010 occured twice (once inside of daylight
652  * savings time and the next, an hour later, outside of daylight savings
653  * time).  In this case, the different value of @type would result in a
654  * different interval being returned.
655  *
656  * It is still possible for this function to fail.  In Toronto, for
657  * example, 02:00 on March 14th 2010 does not exist (due to the leap
658  * forward to begin daylight savings time).  -1 is returned in that
659  * case.
660  *
661  * Returns: the interval containing @time, or -1 in case of failure
662  *
663  * Since: 2.26
664  */
665 gint
666 g_time_zone_find_interval (GTimeZone *tz,
667                            GTimeType  type,
668                            gint64     time)
669 {
670   gint i;
671
672   if (tz->zoneinfo == NULL)
673     return 0;
674
675   for (i = 0; i < tz->timecnt; i++)
676     if (time <= interval_end (tz, i))
677       break;
678
679   if (type == G_TIME_TYPE_UNIVERSAL)
680     return i;
681
682   if (time < interval_local_start (tz, i))
683     {
684       if (time > interval_local_end (tz, --i))
685         return -1;
686     }
687
688   else if (time > interval_local_end (tz, i))
689     {
690       if (time < interval_local_start (tz, ++i))
691         return -1;
692     }
693
694   else if (interval_isdst (tz, i) != type)
695     {
696       if (i && time <= interval_local_end (tz, i - 1))
697         i--;
698
699       else if (i < tz->timecnt && time >= interval_local_start (tz, i + 1))
700         i++;
701     }
702
703   return i;
704 }
705
706 /* Public API accessors {{{1 */
707
708 /**
709  * g_time_zone_get_abbreviation:
710  * @tz: a #GTimeZone
711  * @interval: an interval within the timezone
712  *
713  * Determines the time zone abbreviation to be used during a particular
714  * @interval of time in the time zone @tz.
715  *
716  * For example, in Toronto this is currently "EST" during the winter
717  * months and "EDT" during the summer months when daylight savings time
718  * is in effect.
719  *
720  * Returns: the time zone abbreviation, which belongs to @tz
721  *
722  * Since: 2.26
723  **/
724 const gchar *
725 g_time_zone_get_abbreviation (GTimeZone *tz,
726                               gint       interval)
727 {
728   g_return_val_if_fail (interval_valid (tz, interval), NULL);
729
730   if (tz->header == NULL)
731     return "UTC";
732
733   return tz->abbrs + interval_abbrind (tz, interval);
734 }
735
736 /**
737  * g_time_zone_get_offset:
738  * @tz: a #GTimeZone
739  * @interval: an interval within the timezone
740  *
741  * Determines the offset to UTC in effect during a particular @interval
742  * of time in the time zone @tz.
743  *
744  * The offset is the number of seconds that you add to UTC time to
745  * arrive at local time for @tz (ie: negative numbers for time zones
746  * west of GMT, positive numbers for east).
747  *
748  * Returns: the number of seconds that should be added to UTC to get the
749  *          local time in @tz
750  *
751  * Since: 2.26
752  **/
753 gint32
754 g_time_zone_get_offset (GTimeZone *tz,
755                         gint       interval)
756 {
757   g_return_val_if_fail (interval_valid (tz, interval), 0);
758
759   if (tz->header == NULL)
760     return 0;
761
762   return interval_offset (tz, interval);
763 }
764
765 /**
766  * g_time_zone_is_dst:
767  * @tz: a #GTimeZone
768  * @interval: an interval within the timezone
769  *
770  * Determines if daylight savings time is in effect during a particular
771  * @interval of time in the time zone @tz.
772  *
773  * Returns: %TRUE if daylight savings time is in effect
774  *
775  * Since: 2.26
776  **/
777 gboolean
778 g_time_zone_is_dst (GTimeZone *tz,
779                     gint       interval)
780 {
781   g_return_val_if_fail (interval_valid (tz, interval), FALSE);
782
783   if (tz->header == NULL)
784     return FALSE;
785
786   return interval_isdst (tz, interval);
787 }
788
789 /* Epilogue {{{1 */
790 /* vim:set foldmethod=marker: */