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