445f93a55f01ca532ad5f35b62375ed3bc91e7bb
[asterisk/asterisk.git] / main / stdtime / localtime.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * Most of this code is in the public domain, so clarified as of
9  * June 5, 1996 by Arthur David Olson (arthur_david_olson@nih.gov).
10  *
11  * All modifications to this code to abstract timezones away from
12  * the environment are by Tilghman Lesher, <tlesher@vcch.com>, with
13  * the copyright assigned to Digium.
14  *
15  * See http://www.asterisk.org for more information about
16  * the Asterisk project. Please do not directly contact
17  * any of the maintainers of this project for assistance;
18  * the project provides a web site, mailing lists and IRC
19  * channels for your use.
20  *
21  * This program is free software, distributed under the terms of
22  * the GNU General Public License Version 2. See the LICENSE file
23  * at the top of the source tree.
24  */
25
26 /*! \file
27  *
28  * Multi-timezone Localtime code
29  *
30  * The original source from this file may be obtained from ftp://elsie.nci.nih.gov/pub/
31  */
32
33 /*
34 ** This file is in the public domain, so clarified as of
35 ** 1996-06-05 by Arthur David Olson.
36 */
37
38 /*
39 ** Leap second handling from Bradley White.
40 ** POSIX-style TZ environment variable handling from Guy Harris.
41 */
42
43 /* #define DEBUG */
44
45 /*LINTLIBRARY*/
46
47
48 #include "asterisk.h"
49
50 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
51
52 #include <sys/stat.h>
53 #include <fcntl.h>
54 #include <float.h>
55
56 #include "private.h"
57 #include "tzfile.h"
58
59 #include "asterisk/lock.h"
60 #include "asterisk/localtime.h"
61 #include "asterisk/strings.h"
62 #include "asterisk/linkedlists.h"
63 #include "asterisk/utils.h"
64
65 #ifndef lint
66 #ifndef NOID
67 static char     __attribute__((unused)) elsieid[] = "@(#)localtime.c    8.5";
68 #endif /* !defined NOID */
69 #endif /* !defined lint */
70
71 #ifndef TZ_ABBR_MAX_LEN
72 #define TZ_ABBR_MAX_LEN 16
73 #endif /* !defined TZ_ABBR_MAX_LEN */
74
75 #ifndef TZ_ABBR_CHAR_SET
76 #define TZ_ABBR_CHAR_SET \
77         "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
78 #endif /* !defined TZ_ABBR_CHAR_SET */
79
80 #ifndef TZ_ABBR_ERR_CHAR
81 #define TZ_ABBR_ERR_CHAR        '_'
82 #endif /* !defined TZ_ABBR_ERR_CHAR */
83
84 /*
85 ** SunOS 4.1.1 headers lack O_BINARY.
86 */
87
88 #ifdef O_BINARY
89 #define OPEN_MODE       (O_RDONLY | O_BINARY)
90 #endif /* defined O_BINARY */
91 #ifndef O_BINARY
92 #define OPEN_MODE       O_RDONLY
93 #endif /* !defined O_BINARY */
94
95 static const char       gmt[] = "GMT";
96 static const struct timeval WRONG = { 0, 0 };
97
98 /*! \note
99  * The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
100  * We default to US rules as of 1999-08-17.
101  * POSIX 1003.1 section 8.1.1 says that the default DST rules are
102  * implementation dependent; for historical reasons, US rules are a
103  * common default.
104  */
105 #ifndef TZDEFRULESTRING
106 #define TZDEFRULESTRING ",M4.1.0,M10.5.0"
107 #endif /* !defined TZDEFDST */
108
109 /*!< \brief time type information */
110 struct ttinfo {                         /* time type information */
111         long            tt_gmtoff;      /* UTC offset in seconds */
112         int             tt_isdst;       /* used to set tm_isdst */
113         int             tt_abbrind;     /* abbreviation list index */
114         int             tt_ttisstd;     /* TRUE if transition is std time */
115         int             tt_ttisgmt;     /* TRUE if transition is UTC */
116 };
117
118 /*! \brief leap second information */
119 struct lsinfo {                         /* leap second information */
120         time_t          ls_trans;       /* transition time */
121         long            ls_corr;        /* correction to apply */
122 };
123
124 #define BIGGEST(a, b)   (((a) > (b)) ? (a) : (b))
125
126 #ifdef TZNAME_MAX
127 #define MY_TZNAME_MAX   TZNAME_MAX
128 #endif /* defined TZNAME_MAX */
129 #ifndef TZNAME_MAX
130 #define MY_TZNAME_MAX   255
131 #endif /* !defined TZNAME_MAX */
132 #ifndef TZ_STRLEN_MAX
133 #define TZ_STRLEN_MAX   255
134 #endif /* !defined TZ_STRLEN_MAX */
135
136 struct state {
137         /*! Name of the file that this references */
138         char    name[TZ_STRLEN_MAX + 1];
139         int             leapcnt;
140         int             timecnt;
141         int             typecnt;
142         int             charcnt;
143         int             goback;
144         int             goahead;
145         time_t          ats[TZ_MAX_TIMES];
146         unsigned char   types[TZ_MAX_TIMES];
147         struct ttinfo   ttis[TZ_MAX_TYPES];
148         char            chars[BIGGEST(BIGGEST(TZ_MAX_CHARS + 1, sizeof gmt),
149                                 (2 * (MY_TZNAME_MAX + 1)))];
150         struct lsinfo   lsis[TZ_MAX_LEAPS];
151         AST_LIST_ENTRY(state) list;
152 };
153
154 struct rule {
155         int             r_type;         /* type of rule--see below */
156         int             r_day;          /* day number of rule */
157         int             r_week;         /* week number of rule */
158         int             r_mon;          /* month number of rule */
159         long            r_time;         /* transition time of rule */
160 };
161
162 #define JULIAN_DAY              0       /* Jn - Julian day */
163 #define DAY_OF_YEAR             1       /* n - day of year */
164 #define MONTH_NTH_DAY_OF_WEEK   2       /* Mm.n.d - month, week, day of week */
165
166 /*
167 ** Prototypes for static functions.
168 */
169
170 static long             detzcode P((const char * codep));
171 static time_t           detzcode64 P((const char * codep));
172 static int              differ_by_repeat P((time_t t1, time_t t0));
173 static const char *     getzname P((const char * strp));
174 static const char *     getqzname P((const char * strp, const int delim));
175 static const char *     getnum P((const char * strp, int * nump, int min,
176                                 int max));
177 static const char *     getsecs P((const char * strp, long * secsp));
178 static const char *     getoffset P((const char * strp, long * offsetp));
179 static const char *     getrule P((const char * strp, struct rule * rulep));
180 static int              gmtload P((struct state * sp));
181 static struct ast_tm *  gmtsub P((const struct timeval * timep, long offset,
182                                 struct ast_tm * tmp));
183 static struct ast_tm *  localsub P((const struct timeval * timep, long offset,
184                                 struct ast_tm * tmp, const struct state *sp));
185 static int              increment_overflow P((int * number, int delta));
186 static int              leaps_thru_end_of P((int y));
187 static int              long_increment_overflow P((long * number, int delta));
188 static int              long_normalize_overflow P((long * tensptr,
189                                 int * unitsptr, const int base));
190 static int              normalize_overflow P((int * tensptr, int * unitsptr,
191                                 const int base));
192 static struct timeval   time1 P((struct ast_tm * tmp,
193                                 struct ast_tm * (*funcp) P((const struct timeval *,
194                                 long, struct ast_tm *, const struct state *sp)),
195                                 long offset, const struct state *sp));
196 static struct timeval   time2 P((struct ast_tm *tmp,
197                                 struct ast_tm * (*funcp) P((const struct timeval *,
198                                 long, struct ast_tm*, const struct state *sp)),
199                                 long offset, int * okayp, const struct state *sp));
200 static struct timeval   time2sub P((struct ast_tm *tmp,
201                                 struct ast_tm * (*funcp) (const struct timeval *,
202                                 long, struct ast_tm*, const struct state *sp),
203                                 long offset, int * okayp, int do_norm_secs, const struct state *sp));
204 static struct ast_tm *  timesub P((const struct timeval * timep, long offset,
205                                 const struct state * sp, struct ast_tm * tmp));
206 static int              tmcomp P((const struct ast_tm * atmp,
207                                 const struct ast_tm * btmp));
208 static time_t           transtime P((time_t janfirst, int year,
209                                 const struct rule * rulep, long offset));
210 static int              tzload P((const char * name, struct state * sp,
211                                 int doextend));
212 static int              tzparse P((const char * name, struct state * sp,
213                                 int lastditch));
214
215 static AST_LIST_HEAD_STATIC(zonelist, state);
216
217 #ifndef TZ_STRLEN_MAX
218 #define TZ_STRLEN_MAX 255
219 #endif /* !defined TZ_STRLEN_MAX */
220
221 /*! \note
222 ** Section 4.12.3 of X3.159-1989 requires that
223 **      Except for the strftime function, these functions [asctime,
224 **      ctime, gmtime, localtime] return values in one of two static
225 **      objects: a broken-down time structure and an array of char.
226 ** Thanks to Paul Eggert for noting this.
227 */
228
229 static long detzcode(const char * const codep)
230 {
231         long    result;
232         int     i;
233
234         result = (codep[0] & 0x80) ? ~0L : 0;
235         for (i = 0; i < 4; ++i)
236                 result = (result << 8) | (codep[i] & 0xff);
237         return result;
238 }
239
240 static time_t detzcode64(const char * const codep)
241 {
242         time_t  result;
243         int     i;
244
245         result = (codep[0] & 0x80) ?  (~(int_fast64_t) 0) : 0;
246         for (i = 0; i < 8; ++i)
247                 result = result * 256 + (codep[i] & 0xff);
248         return result;
249 }
250
251 static int differ_by_repeat(const time_t t1, const time_t t0)
252 {
253         const long long at1 = t1, at0 = t0;
254         if (TYPE_INTEGRAL(time_t) &&
255                 TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
256                         return 0;
257         return at1 - at0 == SECSPERREPEAT;
258 }
259
260 static int tzload(const char *name, struct state * const sp, const int doextend)
261 {
262         const char *            p;
263         int                     i;
264         int                     fid;
265         int                     stored;
266         int                     nread;
267         union {
268                 struct tzhead   tzhead;
269                 char            buf[2 * sizeof(struct tzhead) +
270                                         2 * sizeof *sp +
271                                         4 * TZ_MAX_TIMES];
272         } u;
273
274         if (name == NULL && (name = TZDEFAULT) == NULL)
275                 return -1;
276         {
277                 int     doaccess;
278                 /*
279                 ** Section 4.9.1 of the C standard says that
280                 ** "FILENAME_MAX expands to an integral constant expression
281                 ** that is the size needed for an array of char large enough
282                 ** to hold the longest file name string that the implementation
283                 ** guarantees can be opened."
284                 */
285                 char            fullname[FILENAME_MAX + 1];
286
287                 if (name[0] == ':')
288                         ++name;
289                 doaccess = name[0] == '/';
290                 if (!doaccess) {
291                         if ((p = TZDIR) == NULL)
292                                 return -1;
293                         if ((strlen(p) + strlen(name) + 1) >= sizeof fullname)
294                                 return -1;
295                         (void) strcpy(fullname, p);
296                         (void) strcat(fullname, "/");
297                         (void) strcat(fullname, name);
298                         /*
299                         ** Set doaccess if '.' (as in "../") shows up in name.
300                         */
301                         if (strchr(name, '.') != NULL)
302                                 doaccess = TRUE;
303                         name = fullname;
304                 }
305                 if (doaccess && access(name, R_OK) != 0)
306                         return -1;
307                 if ((fid = open(name, OPEN_MODE)) == -1)
308                         return -1;
309         }
310         nread = read(fid, u.buf, sizeof u.buf);
311         if (close(fid) < 0 || nread <= 0)
312                 return -1;
313         for (stored = 4; stored <= 8; stored *= 2) {
314                 int             ttisstdcnt;
315                 int             ttisgmtcnt;
316
317                 ttisstdcnt = (int) detzcode(u.tzhead.tzh_ttisstdcnt);
318                 ttisgmtcnt = (int) detzcode(u.tzhead.tzh_ttisgmtcnt);
319                 sp->leapcnt = (int) detzcode(u.tzhead.tzh_leapcnt);
320                 sp->timecnt = (int) detzcode(u.tzhead.tzh_timecnt);
321                 sp->typecnt = (int) detzcode(u.tzhead.tzh_typecnt);
322                 sp->charcnt = (int) detzcode(u.tzhead.tzh_charcnt);
323                 p = u.tzhead.tzh_charcnt + sizeof u.tzhead.tzh_charcnt;
324                 if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
325                         sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
326                         sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
327                         sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
328                         (ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
329                         (ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
330                                 return -1;
331                 if (nread - (p - u.buf) <
332                         sp->timecnt * stored +          /* ats */
333                         sp->timecnt +                   /* types */
334                         sp->typecnt * 6 +               /* ttinfos */
335                         sp->charcnt +                   /* chars */
336                         sp->leapcnt * (stored + 4) +    /* lsinfos */
337                         ttisstdcnt +                    /* ttisstds */
338                         ttisgmtcnt)                     /* ttisgmts */
339                                 return -1;
340                 for (i = 0; i < sp->timecnt; ++i) {
341                         sp->ats[i] = (stored == 4) ?
342                                 detzcode(p) : detzcode64(p);
343                         p += stored;
344                 }
345                 for (i = 0; i < sp->timecnt; ++i) {
346                         sp->types[i] = (unsigned char) *p++;
347                         if (sp->types[i] >= sp->typecnt)
348                                 return -1;
349                 }
350                 for (i = 0; i < sp->typecnt; ++i) {
351                         struct ttinfo * ttisp;
352
353                         ttisp = &sp->ttis[i];
354                         ttisp->tt_gmtoff = detzcode(p);
355                         p += 4;
356                         ttisp->tt_isdst = (unsigned char) *p++;
357                         if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
358                                 return -1;
359                         ttisp->tt_abbrind = (unsigned char) *p++;
360                         if (ttisp->tt_abbrind < 0 ||
361                                 ttisp->tt_abbrind > sp->charcnt)
362                                         return -1;
363                 }
364                 for (i = 0; i < sp->charcnt; ++i)
365                         sp->chars[i] = *p++;
366                 sp->chars[i] = '\0';    /* ensure '\0' at end */
367                 for (i = 0; i < sp->leapcnt; ++i) {
368                         struct lsinfo * lsisp;
369
370                         lsisp = &sp->lsis[i];
371                         lsisp->ls_trans = (stored == 4) ?
372                                 detzcode(p) : detzcode64(p);
373                         p += stored;
374                         lsisp->ls_corr = detzcode(p);
375                         p += 4;
376                 }
377                 for (i = 0; i < sp->typecnt; ++i) {
378                         struct ttinfo * ttisp;
379
380                         ttisp = &sp->ttis[i];
381                         if (ttisstdcnt == 0)
382                                 ttisp->tt_ttisstd = FALSE;
383                         else {
384                                 ttisp->tt_ttisstd = *p++;
385                                 if (ttisp->tt_ttisstd != TRUE &&
386                                         ttisp->tt_ttisstd != FALSE)
387                                                 return -1;
388                         }
389                 }
390                 for (i = 0; i < sp->typecnt; ++i) {
391                         struct ttinfo * ttisp;
392
393                         ttisp = &sp->ttis[i];
394                         if (ttisgmtcnt == 0)
395                                 ttisp->tt_ttisgmt = FALSE;
396                         else {
397                                 ttisp->tt_ttisgmt = *p++;
398                                 if (ttisp->tt_ttisgmt != TRUE &&
399                                         ttisp->tt_ttisgmt != FALSE)
400                                                 return -1;
401                         }
402                 }
403                 /*
404                 ** Out-of-sort ats should mean we're running on a
405                 ** signed time_t system but using a data file with
406                 ** unsigned values (or vice versa).
407                 */
408                 for (i = 0; i < sp->timecnt - 2; ++i)
409                         if (sp->ats[i] > sp->ats[i + 1]) {
410                                 ++i;
411                                 if (TYPE_SIGNED(time_t)) {
412                                         /*
413                                         ** Ignore the end (easy).
414                                         */
415                                         sp->timecnt = i;
416                                 } else {
417                                         /*
418                                         ** Ignore the beginning (harder).
419                                         */
420                                         int     j;
421
422                                         for (j = 0; j + i < sp->timecnt; ++j) {
423                                                 sp->ats[j] = sp->ats[j + i];
424                                                 sp->types[j] = sp->types[j + i];
425                                         }
426                                         sp->timecnt = j;
427                                 }
428                                 break;
429                         }
430                 /*
431                 ** If this is an old file, we're done.
432                 */
433                 if (u.tzhead.tzh_version[0] == '\0')
434                         break;
435                 nread -= p - u.buf;
436                 for (i = 0; i < nread; ++i)
437                         u.buf[i] = p[i];
438                 /*
439                 ** If this is a narrow integer time_t system, we're done.
440                 */
441                 if (stored >= (int) sizeof(time_t) && TYPE_INTEGRAL(time_t))
442                         break;
443         }
444         if (doextend && nread > 2 &&
445                 u.buf[0] == '\n' && u.buf[nread - 1] == '\n' &&
446                 sp->typecnt + 2 <= TZ_MAX_TYPES) {
447                         struct state    ts;
448                         int     result;
449
450                         u.buf[nread - 1] = '\0';
451                         result = tzparse(&u.buf[1], &ts, FALSE);
452                         if (result == 0 && ts.typecnt == 2 &&
453                                 sp->charcnt + ts.charcnt <= TZ_MAX_CHARS) {
454                                         for (i = 0; i < 2; ++i)
455                                                 ts.ttis[i].tt_abbrind +=
456                                                         sp->charcnt;
457                                         for (i = 0; i < ts.charcnt; ++i)
458                                                 sp->chars[sp->charcnt++] =
459                                                         ts.chars[i];
460                                         i = 0;
461                                         while (i < ts.timecnt &&
462                                                 ts.ats[i] <=
463                                                 sp->ats[sp->timecnt - 1])
464                                                         ++i;
465                                         while (i < ts.timecnt &&
466                                             sp->timecnt < TZ_MAX_TIMES) {
467                                                 sp->ats[sp->timecnt] =
468                                                         ts.ats[i];
469                                                 sp->types[sp->timecnt] =
470                                                         sp->typecnt +
471                                                         ts.types[i];
472                                                 ++sp->timecnt;
473                                                 ++i;
474                                         }
475                                         sp->ttis[sp->typecnt++] = ts.ttis[0];
476                                         sp->ttis[sp->typecnt++] = ts.ttis[1];
477                         }
478         }
479         i = 2 * YEARSPERREPEAT;
480         sp->goback = sp->goahead = sp->timecnt > i;
481         sp->goback = sp->goback && sp->types[i] == sp->types[0] &&
482                 differ_by_repeat(sp->ats[i], sp->ats[0]);
483         sp->goahead = sp->goahead &&
484                 sp->types[sp->timecnt - 1] == sp->types[sp->timecnt - 1 - i] &&
485                 differ_by_repeat(sp->ats[sp->timecnt - 1],
486                          sp->ats[sp->timecnt - 1 - i]);
487         return 0;
488 }
489
490 static const int        mon_lengths[2][MONSPERYEAR] = {
491         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
492         { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
493 };
494
495 static const int        year_lengths[2] = {
496         DAYSPERNYEAR, DAYSPERLYEAR
497 };
498
499 /*! \brief
500 ** Given a pointer into a time zone string, scan until a character that is not
501 ** a valid character in a zone name is found. Return a pointer to that
502 ** character.
503 */
504
505 static const char * getzname(const char *strp)
506 {
507         char    c;
508
509         while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
510                 c != '+')
511                         ++strp;
512         return strp;
513 }
514
515 /*! \brief
516 ** Given a pointer into an extended time zone string, scan until the ending
517 ** delimiter of the zone name is located. Return a pointer to the delimiter.
518 **
519 ** As with getzname above, the legal character set is actually quite
520 ** restricted, with other characters producing undefined results.
521 ** We don't do any checking here; checking is done later in common-case code.
522 */
523
524 static const char * getqzname(const char *strp, const int delim)
525 {
526         int     c;
527
528         while ((c = *strp) != '\0' && c != delim)
529                 ++strp;
530         return strp;
531 }
532
533 /*! \brief
534 ** Given a pointer into a time zone string, extract a number from that string.
535 ** Check that the number is within a specified range; if it is not, return
536 ** NULL.
537 ** Otherwise, return a pointer to the first character not part of the number.
538 */
539
540 static const char *getnum(const char *strp, int *nump, const int min, const int max)
541 {
542         char    c;
543         int     num;
544
545         if (strp == NULL || !is_digit(c = *strp))
546                 return NULL;
547         num = 0;
548         do {
549                 num = num * 10 + (c - '0');
550                 if (num > max)
551                         return NULL;    /* illegal value */
552                 c = *++strp;
553         } while (is_digit(c));
554         if (num < min)
555                 return NULL;            /* illegal value */
556         *nump = num;
557         return strp;
558 }
559
560 /*! \brief
561 ** Given a pointer into a time zone string, extract a number of seconds,
562 ** in hh[:mm[:ss]] form, from the string.
563 ** If any error occurs, return NULL.
564 ** Otherwise, return a pointer to the first character not part of the number
565 ** of seconds.
566 */
567
568 static const char *getsecs(const char *strp, long * const secsp)
569 {
570         int     num;
571
572         /*
573         ** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
574         ** "M10.4.6/26", which does not conform to Posix,
575         ** but which specifies the equivalent of
576         ** ``02:00 on the first Sunday on or after 23 Oct''.
577         */
578         strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
579         if (strp == NULL)
580                 return NULL;
581         *secsp = num * (long) SECSPERHOUR;
582         if (*strp == ':') {
583                 ++strp;
584                 strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
585                 if (strp == NULL)
586                         return NULL;
587                 *secsp += num * SECSPERMIN;
588                 if (*strp == ':') {
589                         ++strp;
590                         /* `SECSPERMIN' allows for leap seconds. */
591                         strp = getnum(strp, &num, 0, SECSPERMIN);
592                         if (strp == NULL)
593                                 return NULL;
594                         *secsp += num;
595                 }
596         }
597         return strp;
598 }
599
600 /*! \brief
601 ** Given a pointer into a time zone string, extract an offset, in
602 ** [+-]hh[:mm[:ss]] form, from the string.
603 ** If any error occurs, return NULL.
604 ** Otherwise, return a pointer to the first character not part of the time.
605 */
606
607 static const char *getoffset(const char *strp, long *offsetp)
608 {
609         int     neg = 0;
610
611         if (*strp == '-') {
612                 neg = 1;
613                 ++strp;
614         } else if (*strp == '+')
615                 ++strp;
616         strp = getsecs(strp, offsetp);
617         if (strp == NULL)
618                 return NULL;            /* illegal time */
619         if (neg)
620                 *offsetp = -*offsetp;
621         return strp;
622 }
623
624 /*! \brief
625 ** Given a pointer into a time zone string, extract a rule in the form
626 ** date[/time]. See POSIX section 8 for the format of "date" and "time".
627 ** If a valid rule is not found, return NULL.
628 ** Otherwise, return a pointer to the first character not part of the rule.
629 */
630
631 static const char *getrule(const char *strp, struct rule *rulep)
632 {
633         if (*strp == 'J') {
634                 /*
635                 ** Julian day.
636                 */
637                 rulep->r_type = JULIAN_DAY;
638                 ++strp;
639                 strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
640         } else if (*strp == 'M') {
641                 /*
642                 ** Month, week, day.
643                 */
644                 rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
645                 ++strp;
646                 strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
647                 if (strp == NULL)
648                         return NULL;
649                 if (*strp++ != '.')
650                         return NULL;
651                 strp = getnum(strp, &rulep->r_week, 1, 5);
652                 if (strp == NULL)
653                         return NULL;
654                 if (*strp++ != '.')
655                         return NULL;
656                 strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
657         } else if (is_digit(*strp)) {
658                 /*
659                 ** Day of year.
660                 */
661                 rulep->r_type = DAY_OF_YEAR;
662                 strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
663         } else  return NULL;            /* invalid format */
664         if (strp == NULL)
665                 return NULL;
666         if (*strp == '/') {
667                 /*
668                 ** Time specified.
669                 */
670                 ++strp;
671                 strp = getsecs(strp, &rulep->r_time);
672         } else  rulep->r_time = 2 * SECSPERHOUR;        /* default = 2:00:00 */
673         return strp;
674 }
675
676 /*! \brief
677 ** Given the Epoch-relative time of January 1, 00:00:00 UTC, in a year, the
678 ** year, a rule, and the offset from UTC at the time that rule takes effect,
679 ** calculate the Epoch-relative time that rule takes effect.
680 */
681
682 static time_t transtime(const time_t janfirst, const int year, const struct rule *rulep, const long offset)
683 {
684         int     leapyear;
685         time_t  value;
686         int     i;
687         int             d, m1, yy0, yy1, yy2, dow;
688
689         INITIALIZE(value);
690         leapyear = isleap(year);
691         switch (rulep->r_type) {
692
693         case JULIAN_DAY:
694                 /*
695                 ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
696                 ** years.
697                 ** In non-leap years, or if the day number is 59 or less, just
698                 ** add SECSPERDAY times the day number-1 to the time of
699                 ** January 1, midnight, to get the day.
700                 */
701                 value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
702                 if (leapyear && rulep->r_day >= 60)
703                         value += SECSPERDAY;
704                 break;
705
706         case DAY_OF_YEAR:
707                 /*
708                 ** n - day of year.
709                 ** Just add SECSPERDAY times the day number to the time of
710                 ** January 1, midnight, to get the day.
711                 */
712                 value = janfirst + rulep->r_day * SECSPERDAY;
713                 break;
714
715         case MONTH_NTH_DAY_OF_WEEK:
716                 /*
717                 ** Mm.n.d - nth "dth day" of month m.
718                 */
719                 value = janfirst;
720                 for (i = 0; i < rulep->r_mon - 1; ++i)
721                         value += mon_lengths[leapyear][i] * SECSPERDAY;
722
723                 /*
724                 ** Use Zeller's Congruence to get day-of-week of first day of
725                 ** month.
726                 */
727                 m1 = (rulep->r_mon + 9) % 12 + 1;
728                 yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
729                 yy1 = yy0 / 100;
730                 yy2 = yy0 % 100;
731                 dow = ((26 * m1 - 2) / 10 +
732                         1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
733                 if (dow < 0)
734                         dow += DAYSPERWEEK;
735
736                 /*
737                 ** "dow" is the day-of-week of the first day of the month. Get
738                 ** the day-of-month (zero-origin) of the first "dow" day of the
739                 ** month.
740                 */
741                 d = rulep->r_day - dow;
742                 if (d < 0)
743                         d += DAYSPERWEEK;
744                 for (i = 1; i < rulep->r_week; ++i) {
745                         if (d + DAYSPERWEEK >=
746                                 mon_lengths[leapyear][rulep->r_mon - 1])
747                                         break;
748                         d += DAYSPERWEEK;
749                 }
750
751                 /*
752                 ** "d" is the day-of-month (zero-origin) of the day we want.
753                 */
754                 value += d * SECSPERDAY;
755                 break;
756         }
757
758         /*
759         ** "value" is the Epoch-relative time of 00:00:00 UTC on the day in
760         ** question. To get the Epoch-relative time of the specified local
761         ** time on that day, add the transition time and the current offset
762         ** from UTC.
763         */
764         return value + rulep->r_time + offset;
765 }
766
767 /*! \note
768 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
769 ** appropriate.
770 */
771
772 static int tzparse(const char *name, struct state *sp, const int lastditch)
773 {
774         const char *                    stdname;
775         const char *                    dstname;
776         size_t                          stdlen;
777         size_t                          dstlen;
778         long                            stdoffset;
779         long                            dstoffset;
780         time_t *                atp;
781         unsigned char * typep;
782         char *                  cp;
783         int                     load_result;
784
785         INITIALIZE(dstname);
786         stdname = name;
787         if (lastditch) {
788                 stdlen = strlen(name);  /* length of standard zone name */
789                 name += stdlen;
790                 if (stdlen >= sizeof sp->chars)
791                         stdlen = (sizeof sp->chars) - 1;
792                 stdoffset = 0;
793         } else {
794                 if (*name == '<') {
795                         name++;
796                         stdname = name;
797                         name = getqzname(name, '>');
798                         if (*name != '>')
799                                 return -1;
800                         stdlen = name - stdname;
801                         name++;
802                 } else {
803                         name = getzname(name);
804                         stdlen = name - stdname;
805                 }
806                 if (*name == '\0')
807                         return -1;
808                 name = getoffset(name, &stdoffset);
809                 if (name == NULL)
810                         return -1;
811         }
812         load_result = tzload(TZDEFRULES, sp, FALSE);
813         if (load_result != 0)
814                 sp->leapcnt = 0;                /* so, we're off a little */
815         if (*name != '\0') {
816                 if (*name == '<') {
817                         dstname = ++name;
818                         name = getqzname(name, '>');
819                         if (*name != '>')
820                                 return -1;
821                         dstlen = name - dstname;
822                         name++;
823                 } else {
824                         dstname = name;
825                         name = getzname(name);
826                         dstlen = name - dstname; /* length of DST zone name */
827                 }
828                 if (*name != '\0' && *name != ',' && *name != ';') {
829                         name = getoffset(name, &dstoffset);
830                         if (name == NULL)
831                                 return -1;
832                 } else  dstoffset = stdoffset - SECSPERHOUR;
833                 if (*name == '\0' && load_result != 0)
834                         name = TZDEFRULESTRING;
835                 if (*name == ',' || *name == ';') {
836                         struct rule     start;
837                         struct rule     end;
838                         int     year;
839                         time_t  janfirst;
840                         time_t          starttime;
841                         time_t          endtime;
842
843                         ++name;
844                         if ((name = getrule(name, &start)) == NULL)
845                                 return -1;
846                         if (*name++ != ',')
847                                 return -1;
848                         if ((name = getrule(name, &end)) == NULL)
849                                 return -1;
850                         if (*name != '\0')
851                                 return -1;
852                         sp->typecnt = 2;        /* standard time and DST */
853                         /*
854                         ** Two transitions per year, from EPOCH_YEAR forward.
855                         */
856                         sp->ttis[0].tt_gmtoff = -dstoffset;
857                         sp->ttis[0].tt_isdst = 1;
858                         sp->ttis[0].tt_abbrind = stdlen + 1;
859                         sp->ttis[1].tt_gmtoff = -stdoffset;
860                         sp->ttis[1].tt_isdst = 0;
861                         sp->ttis[1].tt_abbrind = 0;
862                         atp = sp->ats;
863                         typep = sp->types;
864                         janfirst = 0;
865                         sp->timecnt = 0;
866                         for (year = EPOCH_YEAR;
867                             sp->timecnt + 2 <= TZ_MAX_TIMES;
868                             ++year) {
869                                 time_t  newfirst;
870
871                                 starttime = transtime(janfirst, year, &start,
872                                         stdoffset);
873                                 endtime = transtime(janfirst, year, &end,
874                                         dstoffset);
875                                 if (starttime > endtime) {
876                                         *atp++ = endtime;
877                                         *typep++ = 1;   /* DST ends */
878                                         *atp++ = starttime;
879                                         *typep++ = 0;   /* DST begins */
880                                 } else {
881                                         *atp++ = starttime;
882                                         *typep++ = 0;   /* DST begins */
883                                         *atp++ = endtime;
884                                         *typep++ = 1;   /* DST ends */
885                                 }
886                                 sp->timecnt += 2;
887                                 newfirst = janfirst;
888                                 newfirst += year_lengths[isleap(year)] *
889                                         SECSPERDAY;
890                                 if (newfirst <= janfirst)
891                                         break;
892                                 janfirst = newfirst;
893                         }
894                 } else {
895                         long    theirstdoffset;
896                         long    theirdstoffset;
897                         long    theiroffset;
898                         int     isdst;
899                         int     i;
900                         int     j;
901
902                         if (*name != '\0')
903                                 return -1;
904                         /*
905                         ** Initial values of theirstdoffset and theirdstoffset.
906                         */
907                         theirstdoffset = 0;
908                         for (i = 0; i < sp->timecnt; ++i) {
909                                 j = sp->types[i];
910                                 if (!sp->ttis[j].tt_isdst) {
911                                         theirstdoffset =
912                                                 -sp->ttis[j].tt_gmtoff;
913                                         break;
914                                 }
915                         }
916                         theirdstoffset = 0;
917                         for (i = 0; i < sp->timecnt; ++i) {
918                                 j = sp->types[i];
919                                 if (sp->ttis[j].tt_isdst) {
920                                         theirdstoffset =
921                                                 -sp->ttis[j].tt_gmtoff;
922                                         break;
923                                 }
924                         }
925                         /*
926                         ** Initially we're assumed to be in standard time.
927                         */
928                         isdst = FALSE;
929                         theiroffset = theirstdoffset;
930                         /*
931                         ** Now juggle transition times and types
932                         ** tracking offsets as you do.
933                         */
934                         for (i = 0; i < sp->timecnt; ++i) {
935                                 j = sp->types[i];
936                                 sp->types[i] = sp->ttis[j].tt_isdst;
937                                 if (sp->ttis[j].tt_ttisgmt) {
938                                         /* No adjustment to transition time */
939                                 } else {
940                                         /*
941                                         ** If summer time is in effect, and the
942                                         ** transition time was not specified as
943                                         ** standard time, add the summer time
944                                         ** offset to the transition time;
945                                         ** otherwise, add the standard time
946                                         ** offset to the transition time.
947                                         */
948                                         /*
949                                         ** Transitions from DST to DDST
950                                         ** will effectively disappear since
951                                         ** POSIX provides for only one DST
952                                         ** offset.
953                                         */
954                                         if (isdst && !sp->ttis[j].tt_ttisstd) {
955                                                 sp->ats[i] += dstoffset -
956                                                         theirdstoffset;
957                                         } else {
958                                                 sp->ats[i] += stdoffset -
959                                                         theirstdoffset;
960                                         }
961                                 }
962                                 theiroffset = -sp->ttis[j].tt_gmtoff;
963                                 if (sp->ttis[j].tt_isdst)
964                                         theirdstoffset = theiroffset;
965                                 else    theirstdoffset = theiroffset;
966                         }
967                         /*
968                         ** Finally, fill in ttis.
969                         ** ttisstd and ttisgmt need not be handled.
970                         */
971                         sp->ttis[0].tt_gmtoff = -stdoffset;
972                         sp->ttis[0].tt_isdst = FALSE;
973                         sp->ttis[0].tt_abbrind = 0;
974                         sp->ttis[1].tt_gmtoff = -dstoffset;
975                         sp->ttis[1].tt_isdst = TRUE;
976                         sp->ttis[1].tt_abbrind = stdlen + 1;
977                         sp->typecnt = 2;
978                 }
979         } else {
980                 dstlen = 0;
981                 sp->typecnt = 1;                /* only standard time */
982                 sp->timecnt = 0;
983                 sp->ttis[0].tt_gmtoff = -stdoffset;
984                 sp->ttis[0].tt_isdst = 0;
985                 sp->ttis[0].tt_abbrind = 0;
986         }
987         sp->charcnt = stdlen + 1;
988         if (dstlen != 0)
989                 sp->charcnt += dstlen + 1;
990         if ((size_t) sp->charcnt > sizeof sp->chars)
991                 return -1;
992         cp = sp->chars;
993         (void) strncpy(cp, stdname, stdlen);
994         cp += stdlen;
995         *cp++ = '\0';
996         if (dstlen != 0) {
997                 (void) strncpy(cp, dstname, dstlen);
998                 *(cp + dstlen) = '\0';
999         }
1000         return 0;
1001 }
1002
1003 static int gmtload(struct state *sp)
1004 {
1005         if (tzload(gmt, sp, TRUE) != 0)
1006                 return tzparse(gmt, sp, TRUE);
1007         else
1008                 return -1;
1009 }
1010
1011 static const struct state *ast_tzset(const char *zone)
1012 {
1013         struct state *sp;
1014
1015         if (ast_strlen_zero(zone))
1016                 zone = "/etc/localtime";
1017
1018         AST_LIST_LOCK(&zonelist);
1019         AST_LIST_TRAVERSE(&zonelist, sp, list) {
1020                 if (!strcmp(sp->name, zone)) {
1021                         AST_LIST_UNLOCK(&zonelist);
1022                         return sp;
1023                 }
1024         }
1025         AST_LIST_UNLOCK(&zonelist);
1026
1027         if (!(sp = ast_calloc(1, sizeof *sp)))
1028                 return NULL;
1029
1030         if (tzload(zone, sp, TRUE) != 0) {
1031                 if (zone[0] == ':' || tzparse(zone, sp, FALSE) != 0)
1032                         (void) gmtload(sp);
1033         }
1034         ast_copy_string(sp->name, zone, sizeof(sp->name));
1035         AST_LIST_LOCK(&zonelist);
1036         AST_LIST_INSERT_TAIL(&zonelist, sp, list);
1037         AST_LIST_UNLOCK(&zonelist);
1038         return sp;
1039 }
1040
1041 /*! \note
1042 ** The easy way to behave "as if no library function calls" localtime
1043 ** is to not call it--so we drop its guts into "localsub", which can be
1044 ** freely called. (And no, the PANS doesn't require the above behavior--
1045 ** but it *is* desirable.)
1046 **
1047 ** The unused offset argument is for the benefit of mktime variants.
1048 */
1049
1050 static struct ast_tm *localsub(const struct timeval *timep, const long offset, struct ast_tm *tmp, const struct state *sp)
1051 {
1052         const struct ttinfo *   ttisp;
1053         int                     i;
1054         struct ast_tm *         result;
1055         struct timeval  t;
1056         memcpy(&t, timep, sizeof(t));
1057
1058         if (sp == NULL)
1059                 return gmtsub(timep, offset, tmp);
1060         if ((sp->goback && t.tv_sec < sp->ats[0]) ||
1061                 (sp->goahead && t.tv_sec > sp->ats[sp->timecnt - 1])) {
1062                         struct timeval  newt = t;
1063                         time_t          seconds;
1064                         time_t          tcycles;
1065                         int_fast64_t    icycles;
1066
1067                         if (t.tv_sec < sp->ats[0])
1068                                 seconds = sp->ats[0] - t.tv_sec;
1069                         else    seconds = t.tv_sec - sp->ats[sp->timecnt - 1];
1070                         --seconds;
1071                         tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
1072                         ++tcycles;
1073                         icycles = tcycles;
1074                         if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
1075                                 return NULL;
1076                         seconds = icycles;
1077                         seconds *= YEARSPERREPEAT;
1078                         seconds *= AVGSECSPERYEAR;
1079                         if (t.tv_sec < sp->ats[0])
1080                                 newt.tv_sec += seconds;
1081                         else    newt.tv_sec -= seconds;
1082                         if (newt.tv_sec < sp->ats[0] ||
1083                                 newt.tv_sec > sp->ats[sp->timecnt - 1])
1084                                         return NULL;    /* "cannot happen" */
1085                         result = localsub(&newt, offset, tmp, sp);
1086                         if (result == tmp) {
1087                                 time_t  newy;
1088
1089                                 newy = tmp->tm_year;
1090                                 if (t.tv_sec < sp->ats[0])
1091                                         newy -= icycles * YEARSPERREPEAT;
1092                                 else
1093                                         newy += icycles * YEARSPERREPEAT;
1094                                 tmp->tm_year = newy;
1095                                 if (tmp->tm_year != newy)
1096                                         return NULL;
1097                         }
1098                         return result;
1099         }
1100         if (sp->timecnt == 0 || t.tv_sec < sp->ats[0]) {
1101                 i = 0;
1102                 while (sp->ttis[i].tt_isdst) {
1103                         if (++i >= sp->typecnt) {
1104                                 i = 0;
1105                                 break;
1106                         }
1107                 }
1108         } else {
1109                 int     lo = 1;
1110                 int     hi = sp->timecnt;
1111
1112                 while (lo < hi) {
1113                         int     mid = (lo + hi) >> 1;
1114
1115                         if (t.tv_sec < sp->ats[mid])
1116                                 hi = mid;
1117                         else
1118                                 lo = mid + 1;
1119                 }
1120                 i = (int) sp->types[lo - 1];
1121         }
1122         ttisp = &sp->ttis[i];
1123         /*
1124         ** To get (wrong) behavior that's compatible with System V Release 2.0
1125         ** you'd replace the statement below with
1126         **      t += ttisp->tt_gmtoff;
1127         **      timesub(&t, 0L, sp, tmp);
1128         */
1129         result = timesub(&t, ttisp->tt_gmtoff, sp, tmp);
1130         tmp->tm_isdst = ttisp->tt_isdst;
1131 #ifndef SOLARIS /* Solaris doesn't have this element */
1132         tmp->tm_gmtoff = ttisp->tt_gmtoff;
1133 #endif
1134 #ifdef TM_ZONE
1135         tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1136 #endif /* defined TM_ZONE */
1137         tmp->tm_usec = timep->tv_usec;
1138         return result;
1139 }
1140
1141 struct ast_tm *ast_localtime(const struct timeval *timep, struct ast_tm *tmp, const char *zone)
1142 {
1143         const struct state *sp = ast_tzset(zone);
1144         memset(tmp, 0, sizeof(*tmp));
1145         return sp ? localsub(timep, 0L, tmp, sp) : NULL;
1146 }
1147
1148 /*
1149 ** This function provides informaton about daylight savings time 
1150 ** for the given timezone.  This includes whether it can determine 
1151 ** if daylight savings is used for this timezone, the UTC times for 
1152 ** when daylight savings transitions, and the offset in seconds from 
1153 ** UTC. 
1154 */
1155
1156 void ast_get_dst_info(const time_t * const timep, int *dst_enabled, time_t *dst_start, time_t *dst_end, int *gmt_off, const char * const zone)
1157 {
1158         int i;  
1159         int transition1 = -1;
1160         int transition2 = -1;
1161         time_t          seconds;
1162         int  bounds_exceeded = 0;
1163         time_t  t = *timep;
1164         const struct state *sp;
1165         
1166         if (NULL == dst_enabled)
1167                 return;
1168         *dst_enabled = 0;
1169
1170         if (NULL == dst_start || NULL == dst_end || NULL == gmt_off)
1171                 return;
1172
1173         *gmt_off = 0; 
1174         
1175         sp = ast_tzset(zone);
1176         if (NULL == sp) 
1177                 return;
1178         
1179         /* If the desired time exceeds the bounds of the defined time transitions  
1180         * then give give up on determining DST info and simply look for gmt offset 
1181         * This requires that I adjust the given time using increments of Gregorian 
1182         * repeats to place the time within the defined time transitions in the 
1183         * timezone structure.  
1184         */
1185         if ((sp->goback && t < sp->ats[0]) ||
1186                         (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
1187                 time_t          tcycles;
1188                 int_fast64_t    icycles;
1189
1190                 if (t < sp->ats[0])
1191                         seconds = sp->ats[0] - t;
1192                 else    seconds = t - sp->ats[sp->timecnt - 1];
1193                 --seconds;
1194                 tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
1195                 ++tcycles;
1196                 icycles = tcycles;
1197                 if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
1198                         return;
1199                 seconds = icycles;
1200                 seconds *= YEARSPERREPEAT;
1201                 seconds *= AVGSECSPERYEAR;
1202                 if (t < sp->ats[0])
1203                         t += seconds;
1204                 else
1205                         t -= seconds;
1206                 
1207                 if (t < sp->ats[0] || t > sp->ats[sp->timecnt - 1])
1208                         return; /* "cannot happen" */
1209
1210                 bounds_exceeded = 1;
1211         }
1212
1213         if (sp->timecnt == 0 || t < sp->ats[0]) {
1214                 /* I have no transition times or I'm before time */
1215                 *dst_enabled = 0;
1216                 /* Find where I can get gmtoff */
1217                 i = 0;
1218                 while (sp->ttis[i].tt_isdst)
1219                         if (++i >= sp->typecnt) {
1220                         i = 0;
1221                         break;
1222                         }
1223                         *gmt_off = sp->ttis[i].tt_gmtoff;
1224                         return;
1225         } 
1226
1227         for (i = 1; i < sp->timecnt; ++i) {
1228                 if (t < sp->ats[i]) {
1229                         transition1 = sp->types[i - 1];
1230                         transition2 = sp->types[i];
1231                         break;
1232                 } 
1233         }
1234         /* if I found transition times that do not bounded the given time and these correspond to 
1235                 or the bounding zones do not reflect a changes in day light savings, then I do not have dst active */
1236         if (i >= sp->timecnt || 0 > transition1 || 0 > transition2 ||
1237                         (sp->ttis[transition1].tt_isdst == sp->ttis[transition2].tt_isdst)) {
1238                 *dst_enabled = 0;
1239                 *gmt_off         = sp->ttis[sp->types[sp->timecnt -1]].tt_gmtoff;
1240         } else {
1241                 /* I have valid daylight savings information. */
1242                 if(sp->ttis[transition2].tt_isdst) 
1243                         *gmt_off = sp->ttis[transition1].tt_gmtoff;
1244                 else 
1245                         *gmt_off = sp->ttis[transition2].tt_gmtoff;
1246
1247                 /* If I adjusted the time earlier, indicate that the dst is invalid */
1248                 if (!bounds_exceeded) {
1249                         *dst_enabled = 1;
1250                         /* Determine which of the bounds is the start of daylight savings and which is the end */
1251                         if(sp->ttis[transition2].tt_isdst) {
1252                                 *dst_start = sp->ats[i];
1253                                 *dst_end = sp->ats[i -1];
1254                         } else {
1255                                 *dst_start = sp->ats[i -1];
1256                                 *dst_end = sp->ats[i];
1257                         }
1258                 }
1259         }       
1260         return;
1261 }
1262
1263 /*
1264 ** gmtsub is to gmtime as localsub is to localtime.
1265 */
1266
1267 static struct ast_tm *gmtsub(const struct timeval *timep, const long offset, struct ast_tm *tmp)
1268 {
1269         struct ast_tm * result;
1270         struct state *sp;
1271
1272         AST_LIST_LOCK(&zonelist);
1273         AST_LIST_TRAVERSE(&zonelist, sp, list) {
1274                 if (!strcmp(sp->name, "UTC"))
1275                         break;
1276         }
1277
1278         if (!sp) {
1279                 if (!(sp = (struct state *) ast_calloc(1, sizeof *sp)))
1280                         return NULL;
1281                 gmtload(sp);
1282                 AST_LIST_INSERT_TAIL(&zonelist, sp, list);
1283         }
1284         AST_LIST_UNLOCK(&zonelist);
1285
1286         result = timesub(timep, offset, sp, tmp);
1287 #ifdef TM_ZONE
1288         /*
1289         ** Could get fancy here and deliver something such as
1290         ** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
1291         ** but this is no time for a treasure hunt.
1292         */
1293         if (offset != 0)
1294                 tmp->TM_ZONE = "    ";
1295         else
1296                 tmp->TM_ZONE = sp->chars;
1297 #endif /* defined TM_ZONE */
1298         return result;
1299 }
1300
1301 /*! \brief
1302 ** Return the number of leap years through the end of the given year
1303 ** where, to make the math easy, the answer for year zero is defined as zero.
1304 */
1305
1306 static int leaps_thru_end_of(const int y)
1307 {
1308         return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
1309                 -(leaps_thru_end_of(-(y + 1)) + 1);
1310 }
1311
1312 static struct ast_tm *timesub(const struct timeval *timep, const long offset, const struct state *sp, struct ast_tm *tmp)
1313 {
1314         const struct lsinfo *   lp;
1315         time_t                  tdays;
1316         int                     idays;  /* unsigned would be so 2003 */
1317         long                    rem;
1318         int                             y;
1319         const int *             ip;
1320         long                    corr;
1321         int                     hit;
1322         int                     i;
1323         long    seconds;
1324
1325
1326         corr = 0;
1327         hit = 0;
1328         i = (sp == NULL) ? 0 : sp->leapcnt;
1329         while (--i >= 0) {
1330                 lp = &sp->lsis[i];
1331                 if (timep->tv_sec >= lp->ls_trans) {
1332                         if (timep->tv_sec == lp->ls_trans) {
1333                                 hit = ((i == 0 && lp->ls_corr > 0) ||
1334                                         lp->ls_corr > sp->lsis[i - 1].ls_corr);
1335                                 if (hit)
1336                                         while (i > 0 &&
1337                                                 sp->lsis[i].ls_trans ==
1338                                                 sp->lsis[i - 1].ls_trans + 1 &&
1339                                                 sp->lsis[i].ls_corr ==
1340                                                 sp->lsis[i - 1].ls_corr + 1) {
1341                                                         ++hit;
1342                                                         --i;
1343                                         }
1344                         }
1345                         corr = lp->ls_corr;
1346                         break;
1347                 }
1348         }
1349         y = EPOCH_YEAR;
1350         tdays = timep->tv_sec / SECSPERDAY;
1351         rem = timep->tv_sec - tdays * SECSPERDAY;
1352         while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
1353                 int             newy;
1354                 time_t  tdelta;
1355                 int     idelta;
1356                 int     leapdays;
1357
1358                 tdelta = tdays / DAYSPERLYEAR;
1359                 idelta = tdelta;
1360                 if (tdelta - idelta >= 1 || idelta - tdelta >= 1)
1361                         return NULL;
1362                 if (idelta == 0)
1363                         idelta = (tdays < 0) ? -1 : 1;
1364                 newy = y;
1365                 if (increment_overflow(&newy, idelta))
1366                         return NULL;
1367                 leapdays = leaps_thru_end_of(newy - 1) -
1368                         leaps_thru_end_of(y - 1);
1369                 tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
1370                 tdays -= leapdays;
1371                 y = newy;
1372         }
1373
1374         seconds = tdays * SECSPERDAY + 0.5;
1375         tdays = seconds / SECSPERDAY;
1376         rem += seconds - tdays * SECSPERDAY;
1377
1378         /*
1379         ** Given the range, we can now fearlessly cast...
1380         */
1381         idays = tdays;
1382         rem += offset - corr;
1383         while (rem < 0) {
1384                 rem += SECSPERDAY;
1385                 --idays;
1386         }
1387         while (rem >= SECSPERDAY) {
1388                 rem -= SECSPERDAY;
1389                 ++idays;
1390         }
1391         while (idays < 0) {
1392                 if (increment_overflow(&y, -1))
1393                         return NULL;
1394                 idays += year_lengths[isleap(y)];
1395         }
1396         while (idays >= year_lengths[isleap(y)]) {
1397                 idays -= year_lengths[isleap(y)];
1398                 if (increment_overflow(&y, 1))
1399                         return NULL;
1400         }
1401         tmp->tm_year = y;
1402         if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
1403                 return NULL;
1404         tmp->tm_yday = idays;
1405         /*
1406         ** The "extra" mods below avoid overflow problems.
1407         */
1408         tmp->tm_wday = EPOCH_WDAY +
1409                 ((y - EPOCH_YEAR) % DAYSPERWEEK) *
1410                 (DAYSPERNYEAR % DAYSPERWEEK) +
1411                 leaps_thru_end_of(y - 1) -
1412                 leaps_thru_end_of(EPOCH_YEAR - 1) +
1413                 idays;
1414         tmp->tm_wday %= DAYSPERWEEK;
1415         if (tmp->tm_wday < 0)
1416                 tmp->tm_wday += DAYSPERWEEK;
1417         tmp->tm_hour = (int) (rem / SECSPERHOUR);
1418         rem %= SECSPERHOUR;
1419         tmp->tm_min = (int) (rem / SECSPERMIN);
1420         /*
1421         ** A positive leap second requires a special
1422         ** representation. This uses "... ??:59:60" et seq.
1423         */
1424         tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1425         ip = mon_lengths[isleap(y)];
1426         for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
1427                 idays -= ip[tmp->tm_mon];
1428         tmp->tm_mday = (int) (idays + 1);
1429         tmp->tm_isdst = 0;
1430 #ifdef TM_GMTOFF
1431         tmp->TM_GMTOFF = offset;
1432 #endif /* defined TM_GMTOFF */
1433         tmp->tm_usec = timep->tv_usec;
1434         return tmp;
1435 }
1436
1437 /*! \note
1438 ** Adapted from code provided by Robert Elz, who writes:
1439 **      The "best" way to do mktime I think is based on an idea of Bob
1440 **      Kridle's (so its said...) from a long time ago.
1441 **      It does a binary search of the time_t space. Since time_t's are
1442 **      just 32 bits, its a max of 32 iterations (even at 64 bits it
1443 **      would still be very reasonable).
1444 */
1445
1446 /*! \brief
1447 ** Simplified normalize logic courtesy Paul Eggert.
1448 */
1449
1450 static int increment_overflow(int *number, int delta)
1451 {
1452         int     number0;
1453
1454         number0 = *number;
1455         *number += delta;
1456         return (*number < number0) != (delta < 0);
1457 }
1458
1459 static int long_increment_overflow(long *number, int delta)
1460 {
1461         long    number0;
1462
1463         number0 = *number;
1464         *number += delta;
1465         return (*number < number0) != (delta < 0);
1466 }
1467
1468 static int normalize_overflow(int *tensptr, int *unitsptr, const int base)
1469 {
1470         int     tensdelta;
1471
1472         tensdelta = (*unitsptr >= 0) ?
1473                 (*unitsptr / base) :
1474                 (-1 - (-1 - *unitsptr) / base);
1475         *unitsptr -= tensdelta * base;
1476         return increment_overflow(tensptr, tensdelta);
1477 }
1478
1479 static int long_normalize_overflow(long *tensptr, int *unitsptr, const int base)
1480 {
1481         int     tensdelta;
1482
1483         tensdelta = (*unitsptr >= 0) ?
1484                 (*unitsptr / base) :
1485                 (-1 - (-1 - *unitsptr) / base);
1486         *unitsptr -= tensdelta * base;
1487         return long_increment_overflow(tensptr, tensdelta);
1488 }
1489
1490 static int tmcomp(const struct ast_tm *atmp, const struct ast_tm *btmp)
1491 {
1492         int     result;
1493
1494         if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1495                 (result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1496                 (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1497                 (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1498                 (result = (atmp->tm_min - btmp->tm_min)) == 0 &&
1499                 (result = (atmp->tm_sec - btmp->tm_sec)) == 0)
1500                         result = atmp->tm_usec - btmp->tm_usec;
1501         return result;
1502 }
1503
1504 static struct timeval time2sub(struct ast_tm *tmp, struct ast_tm * (* const funcp) (const struct timeval *, long, struct ast_tm *, const struct state *), const long offset, int *okayp, const int do_norm_secs, const struct state *sp)
1505 {
1506         int                     dir;
1507         int                     i, j;
1508         int                     saved_seconds;
1509         long                    li;
1510         time_t                  lo;
1511         time_t                  hi;
1512         long                            y;
1513         struct timeval                  newt = { 0, 0 };
1514         struct timeval                  t = { 0, 0 };
1515         struct ast_tm                   yourtm, mytm;
1516
1517         *okayp = FALSE;
1518         yourtm = *tmp;
1519         if (do_norm_secs) {
1520                 if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1521                         SECSPERMIN))
1522                                 return WRONG;
1523         }
1524         if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1525                 return WRONG;
1526         if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1527                 return WRONG;
1528         y = yourtm.tm_year;
1529         if (long_normalize_overflow(&y, &yourtm.tm_mon, MONSPERYEAR))
1530                 return WRONG;
1531         /*
1532         ** Turn y into an actual year number for now.
1533         ** It is converted back to an offset from TM_YEAR_BASE later.
1534         */
1535         if (long_increment_overflow(&y, TM_YEAR_BASE))
1536                 return WRONG;
1537         while (yourtm.tm_mday <= 0) {
1538                 if (long_increment_overflow(&y, -1))
1539                         return WRONG;
1540                 li = y + (1 < yourtm.tm_mon);
1541                 yourtm.tm_mday += year_lengths[isleap(li)];
1542         }
1543         while (yourtm.tm_mday > DAYSPERLYEAR) {
1544                 li = y + (1 < yourtm.tm_mon);
1545                 yourtm.tm_mday -= year_lengths[isleap(li)];
1546                 if (long_increment_overflow(&y, 1))
1547                         return WRONG;
1548         }
1549         for ( ; ; ) {
1550                 i = mon_lengths[isleap(y)][yourtm.tm_mon];
1551                 if (yourtm.tm_mday <= i)
1552                         break;
1553                 yourtm.tm_mday -= i;
1554                 if (++yourtm.tm_mon >= MONSPERYEAR) {
1555                         yourtm.tm_mon = 0;
1556                         if (long_increment_overflow(&y, 1))
1557                                 return WRONG;
1558                 }
1559         }
1560         if (long_increment_overflow(&y, -TM_YEAR_BASE))
1561                 return WRONG;
1562         yourtm.tm_year = y;
1563         if (yourtm.tm_year != y)
1564                 return WRONG;
1565         if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
1566                 saved_seconds = 0;
1567         else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
1568                 /*
1569                 ** We can't set tm_sec to 0, because that might push the
1570                 ** time below the minimum representable time.
1571                 ** Set tm_sec to 59 instead.
1572                 ** This assumes that the minimum representable time is
1573                 ** not in the same minute that a leap second was deleted from,
1574                 ** which is a safer assumption than using 58 would be.
1575                 */
1576                 if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1577                         return WRONG;
1578                 saved_seconds = yourtm.tm_sec;
1579                 yourtm.tm_sec = SECSPERMIN - 1;
1580         } else {
1581                 saved_seconds = yourtm.tm_sec;
1582                 yourtm.tm_sec = 0;
1583         }
1584         /*
1585         ** Do a binary search (this works whatever time_t's type is).
1586         */
1587         if (!TYPE_SIGNED(time_t)) {
1588                 lo = 0;
1589                 hi = lo - 1;
1590         } else if (!TYPE_INTEGRAL(time_t)) {
1591                 if (sizeof(time_t) > sizeof(float))
1592                         hi = (time_t) DBL_MAX;
1593                 else    hi = (time_t) FLT_MAX;
1594                 lo = -hi;
1595         } else {
1596                 lo = 1;
1597                 for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
1598                         lo *= 2;
1599                 hi = -(lo + 1);
1600         }
1601         for ( ; ; ) {
1602                 t.tv_sec = lo / 2 + hi / 2;
1603                 if (t.tv_sec < lo)
1604                         t.tv_sec = lo;
1605                 else if (t.tv_sec > hi)
1606                         t.tv_sec = hi;
1607                 if ((*funcp)(&t, offset, &mytm, sp) == NULL) {
1608                         /*
1609                         ** Assume that t is too extreme to be represented in
1610                         ** a struct ast_tm; arrange things so that it is less
1611                         ** extreme on the next pass.
1612                         */
1613                         dir = (t.tv_sec > 0) ? 1 : -1;
1614                 } else  dir = tmcomp(&mytm, &yourtm);
1615                 if (dir != 0) {
1616                         if (t.tv_sec == lo) {
1617                                 ++t.tv_sec;
1618                                 if (t.tv_sec <= lo)
1619                                         return WRONG;
1620                                 ++lo;
1621                         } else if (t.tv_sec == hi) {
1622                                 --t.tv_sec;
1623                                 if (t.tv_sec >= hi)
1624                                         return WRONG;
1625                                 --hi;
1626                         }
1627                         if (lo > hi)
1628                                 return WRONG;
1629                         if (dir > 0)
1630                                 hi = t.tv_sec;
1631                         else    lo = t.tv_sec;
1632                         continue;
1633                 }
1634                 if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1635                         break;
1636                 /*
1637                 ** Right time, wrong type.
1638                 ** Hunt for right time, right type.
1639                 ** It's okay to guess wrong since the guess
1640                 ** gets checked.
1641                 */
1642                 /*
1643                 ** The (void *) casts are the benefit of SunOS 3.3 on Sun 2's.
1644                 */
1645                 for (i = sp->typecnt - 1; i >= 0; --i) {
1646                         if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1647                                 continue;
1648                         for (j = sp->typecnt - 1; j >= 0; --j) {
1649                                 if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1650                                         continue;
1651                                 newt.tv_sec = t.tv_sec + sp->ttis[j].tt_gmtoff -
1652                                         sp->ttis[i].tt_gmtoff;
1653                                 if ((*funcp)(&newt, offset, &mytm, sp) == NULL)
1654                                         continue;
1655                                 if (tmcomp(&mytm, &yourtm) != 0)
1656                                         continue;
1657                                 if (mytm.tm_isdst != yourtm.tm_isdst)
1658                                         continue;
1659                                 /*
1660                                 ** We have a match.
1661                                 */
1662                                 t = newt;
1663                                 goto label;
1664                         }
1665                 }
1666                 return WRONG;
1667         }
1668 label:
1669         newt.tv_sec = t.tv_sec + saved_seconds;
1670         if ((newt.tv_sec < t.tv_sec) != (saved_seconds < 0))
1671                 return WRONG;
1672         t.tv_sec = newt.tv_sec;
1673         if ((*funcp)(&t, offset, tmp, sp))
1674                 *okayp = TRUE;
1675         return t;
1676 }
1677
1678 static struct timeval time2(struct ast_tm *tmp, struct ast_tm * (* const funcp) (const struct timeval *, long, struct ast_tm*, const struct state *sp), const long offset, int *okayp, const struct state *sp)
1679 {
1680         struct timeval  t;
1681
1682         /*! \note
1683         ** First try without normalization of seconds
1684         ** (in case tm_sec contains a value associated with a leap second).
1685         ** If that fails, try with normalization of seconds.
1686         */
1687         t = time2sub(tmp, funcp, offset, okayp, FALSE, sp);
1688         return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE, sp);
1689 }
1690
1691 static struct timeval time1(struct ast_tm *tmp, struct ast_tm * (* const funcp) (const struct timeval *, long, struct ast_tm *, const struct state *), const long offset, const struct state *sp)
1692 {
1693         struct timeval                  t;
1694         int                     samei, otheri;
1695         int                     sameind, otherind;
1696         int                     i;
1697         int                     nseen;
1698         int                             seen[TZ_MAX_TYPES];
1699         int                             types[TZ_MAX_TYPES];
1700         int                             okay;
1701
1702         if (tmp->tm_isdst > 1)
1703                 tmp->tm_isdst = 1;
1704         t = time2(tmp, funcp, offset, &okay, sp);
1705 #ifdef PCTS
1706         /*
1707         ** PCTS code courtesy Grant Sullivan.
1708         */
1709         if (okay)
1710                 return t;
1711         if (tmp->tm_isdst < 0)
1712                 tmp->tm_isdst = 0;      /* reset to std and try again */
1713 #endif /* defined PCTS */
1714 #ifndef PCTS
1715         if (okay || tmp->tm_isdst < 0)
1716                 return t;
1717 #endif /* !defined PCTS */
1718         /*
1719         ** We're supposed to assume that somebody took a time of one type
1720         ** and did some math on it that yielded a "struct ast_tm" that's bad.
1721         ** We try to divine the type they started from and adjust to the
1722         ** type they need.
1723         */
1724         if (sp == NULL)
1725                 return WRONG;
1726         for (i = 0; i < sp->typecnt; ++i)
1727                 seen[i] = FALSE;
1728         nseen = 0;
1729         for (i = sp->timecnt - 1; i >= 0; --i)
1730                 if (!seen[sp->types[i]]) {
1731                         seen[sp->types[i]] = TRUE;
1732                         types[nseen++] = sp->types[i];
1733                 }
1734         for (sameind = 0; sameind < nseen; ++sameind) {
1735                 samei = types[sameind];
1736                 if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1737                         continue;
1738                 for (otherind = 0; otherind < nseen; ++otherind) {
1739                         otheri = types[otherind];
1740                         if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1741                                 continue;
1742                         tmp->tm_sec += sp->ttis[otheri].tt_gmtoff -
1743                                         sp->ttis[samei].tt_gmtoff;
1744                         tmp->tm_isdst = !tmp->tm_isdst;
1745                         t = time2(tmp, funcp, offset, &okay, sp);
1746                         if (okay)
1747                                 return t;
1748                         tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff -
1749                                         sp->ttis[samei].tt_gmtoff;
1750                         tmp->tm_isdst = !tmp->tm_isdst;
1751                 }
1752         }
1753         return WRONG;
1754 }
1755
1756 struct timeval ast_mktime(struct ast_tm *tmp, const char *zone)
1757 {
1758         const struct state *sp;
1759         if (!(sp = ast_tzset(zone)))
1760                 return WRONG;
1761         return time1(tmp, localsub, 0L, sp);
1762 }
1763
1764 int ast_strftime(char *buf, size_t len, const char *tmp, const struct ast_tm *tm)
1765 {
1766         size_t fmtlen = strlen(tmp) + 1;
1767         char *format = ast_calloc(1, fmtlen), *fptr = format, *newfmt;
1768         int decimals = -1, i, res;
1769         long fraction;
1770
1771         if (!format)
1772                 return -1;
1773         for (; *tmp; tmp++) {
1774                 if (*tmp == '%') {
1775                         switch (tmp[1]) {
1776                         case '1':
1777                         case '2':
1778                         case '3':
1779                         case '4':
1780                         case '5':
1781                         case '6':
1782                                 if (tmp[2] != 'q')
1783                                         goto defcase;
1784                                 decimals = tmp[1] - '0';
1785                                 tmp++;
1786                                 /* Fall through */
1787                         case 'q': /* Milliseconds */
1788                                 if (decimals == -1)
1789                                         decimals = 3;
1790
1791                                 /* Juggle some memory to fit the item */
1792                                 newfmt = ast_realloc(format, fmtlen + decimals);
1793                                 if (!newfmt) {
1794                                         ast_free(format);
1795                                         return -1;
1796                                 }
1797                                 fptr = fptr - format + newfmt;
1798                                 format = newfmt;
1799                                 fmtlen += decimals;
1800
1801                                 /* Reduce the fraction of time to the accuracy needed */
1802                                 for (i = 6, fraction = tm->tm_usec; i > decimals; i--)
1803                                         fraction /= 10;
1804                                 fptr += sprintf(fptr, "%0*ld", decimals, fraction);
1805
1806                                 /* Reset, in case more than one 'q' specifier exists */
1807                                 decimals = -1;
1808                                 tmp++;
1809                                 break;
1810                         default:
1811                                 goto defcase;
1812                         }
1813                 } else
1814 defcase:        *fptr++ = *tmp;
1815         }
1816         *fptr = '\0';
1817 #undef strftime
1818         res = (int)strftime(buf, len, format, (struct tm *)tm);
1819         ast_free(format);
1820         return res;
1821 }
1822