Added a new module, res_phoneprov, which allows auto-provisioning of phones
[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         tmp->tm_gmtoff = ttisp->tt_gmtoff;
1132 #ifdef TM_ZONE
1133         tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1134 #endif /* defined TM_ZONE */
1135         tmp->tm_usec = timep->tv_usec;
1136         return result;
1137 }
1138
1139 struct ast_tm *ast_localtime(const struct timeval *timep, struct ast_tm *tmp, const char *zone)
1140 {
1141         const struct state *sp = ast_tzset(zone);
1142         memset(tmp, 0, sizeof(*tmp));
1143         return sp ? localsub(timep, 0L, tmp, sp) : NULL;
1144 }
1145
1146 /*
1147 ** This function provides informaton about daylight savings time 
1148 ** for the given timezone.  This includes whether it can determine 
1149 ** if daylight savings is used for this timezone, the UTC times for 
1150 ** when daylight savings transitions, and the offset in seconds from 
1151 ** UTC. 
1152 */
1153
1154 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)
1155 {
1156         int i;  
1157         int transition1 = -1;
1158         int transition2 = -1;
1159         time_t          seconds;
1160         int  bounds_exceeded = 0;
1161         time_t  t = *timep;
1162         const struct state *sp;
1163         
1164         if (NULL == dst_enabled)
1165                 return;
1166         *dst_enabled = 0;
1167
1168         if (NULL == dst_start || NULL == dst_end || NULL == gmt_off)
1169                 return;
1170
1171         *gmt_off = 0; 
1172         
1173         sp = ast_tzset(zone);
1174         if (NULL == sp) 
1175                 return;
1176         
1177         /* If the desired time exceeds the bounds of the defined time transitions  
1178         * then give give up on determining DST info and simply look for gmt offset 
1179         * This requires that I adjust the given time using increments of Gregorian 
1180         * repeats to place the time within the defined time transitions in the 
1181         * timezone structure.  
1182         */
1183         if ((sp->goback && t < sp->ats[0]) ||
1184                         (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
1185                 time_t          tcycles;
1186                 int_fast64_t    icycles;
1187
1188                 if (t < sp->ats[0])
1189                         seconds = sp->ats[0] - t;
1190                 else    seconds = t - sp->ats[sp->timecnt - 1];
1191                 --seconds;
1192                 tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
1193                 ++tcycles;
1194                 icycles = tcycles;
1195                 if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
1196                         return;
1197                 seconds = icycles;
1198                 seconds *= YEARSPERREPEAT;
1199                 seconds *= AVGSECSPERYEAR;
1200                 if (t < sp->ats[0])
1201                         t += seconds;
1202                 else
1203                         t -= seconds;
1204                 
1205                 if (t < sp->ats[0] || t > sp->ats[sp->timecnt - 1])
1206                         return; /* "cannot happen" */
1207
1208                 bounds_exceeded = 1;
1209         }
1210
1211         if (sp->timecnt == 0 || t < sp->ats[0]) {
1212                 /* I have no transition times or I'm before time */
1213                 *dst_enabled = 0;
1214                 /* Find where I can get gmtoff */
1215                 i = 0;
1216                 while (sp->ttis[i].tt_isdst)
1217                         if (++i >= sp->typecnt) {
1218                         i = 0;
1219                         break;
1220                         }
1221                         *gmt_off = sp->ttis[i].tt_gmtoff;
1222                         return;
1223         } 
1224
1225         for (i = 1; i < sp->timecnt; ++i) {
1226                 if (t < sp->ats[i]) {
1227                         transition1 = sp->types[i - 1];
1228                         transition2 = sp->types[i];
1229                         break;
1230                 } 
1231         }
1232         /* if I found transition times that do not bounded the given time and these correspond to 
1233                 or the bounding zones do not reflect a changes in day light savings, then I do not have dst active */
1234         if (i >= sp->timecnt || 0 > transition1 || 0 > transition2 ||
1235                         (sp->ttis[transition1].tt_isdst == sp->ttis[transition2].tt_isdst)) {
1236                 *dst_enabled = 0;
1237                 *gmt_off         = sp->ttis[sp->types[sp->timecnt -1]].tt_gmtoff;
1238         } else {
1239                 /* I have valid daylight savings information. */
1240                 if(sp->ttis[transition2].tt_isdst) 
1241                         *gmt_off = sp->ttis[transition1].tt_gmtoff;
1242                 else 
1243                         *gmt_off = sp->ttis[transition2].tt_gmtoff;
1244
1245                 /* If I adjusted the time earlier, indicate that the dst is invalid */
1246                 if (!bounds_exceeded) {
1247                         *dst_enabled = 1;
1248                         /* Determine which of the bounds is the start of daylight savings and which is the end */
1249                         if(sp->ttis[transition2].tt_isdst) {
1250                                 *dst_start = sp->ats[i];
1251                                 *dst_end = sp->ats[i -1];
1252                         } else {
1253                                 *dst_start = sp->ats[i -1];
1254                                 *dst_end = sp->ats[i];
1255                         }
1256                 }
1257         }       
1258         return;
1259 }
1260
1261 /*
1262 ** gmtsub is to gmtime as localsub is to localtime.
1263 */
1264
1265 static struct ast_tm *gmtsub(const struct timeval *timep, const long offset, struct ast_tm *tmp)
1266 {
1267         struct ast_tm * result;
1268         struct state *sp;
1269
1270         AST_LIST_LOCK(&zonelist);
1271         AST_LIST_TRAVERSE(&zonelist, sp, list) {
1272                 if (!strcmp(sp->name, "UTC"))
1273                         break;
1274         }
1275
1276         if (!sp) {
1277                 if (!(sp = (struct state *) ast_calloc(1, sizeof *sp)))
1278                         return NULL;
1279                 gmtload(sp);
1280                 AST_LIST_INSERT_TAIL(&zonelist, sp, list);
1281         }
1282         AST_LIST_UNLOCK(&zonelist);
1283
1284         result = timesub(timep, offset, sp, tmp);
1285 #ifdef TM_ZONE
1286         /*
1287         ** Could get fancy here and deliver something such as
1288         ** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
1289         ** but this is no time for a treasure hunt.
1290         */
1291         if (offset != 0)
1292                 tmp->TM_ZONE = "    ";
1293         else
1294                 tmp->TM_ZONE = sp->chars;
1295 #endif /* defined TM_ZONE */
1296         return result;
1297 }
1298
1299 /*! \brief
1300 ** Return the number of leap years through the end of the given year
1301 ** where, to make the math easy, the answer for year zero is defined as zero.
1302 */
1303
1304 static int leaps_thru_end_of(const int y)
1305 {
1306         return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
1307                 -(leaps_thru_end_of(-(y + 1)) + 1);
1308 }
1309
1310 static struct ast_tm *timesub(const struct timeval *timep, const long offset, const struct state *sp, struct ast_tm *tmp)
1311 {
1312         const struct lsinfo *   lp;
1313         time_t                  tdays;
1314         int                     idays;  /* unsigned would be so 2003 */
1315         long                    rem;
1316         int                             y;
1317         const int *             ip;
1318         long                    corr;
1319         int                     hit;
1320         int                     i;
1321         long    seconds;
1322
1323
1324         corr = 0;
1325         hit = 0;
1326         i = (sp == NULL) ? 0 : sp->leapcnt;
1327         while (--i >= 0) {
1328                 lp = &sp->lsis[i];
1329                 if (timep->tv_sec >= lp->ls_trans) {
1330                         if (timep->tv_sec == lp->ls_trans) {
1331                                 hit = ((i == 0 && lp->ls_corr > 0) ||
1332                                         lp->ls_corr > sp->lsis[i - 1].ls_corr);
1333                                 if (hit)
1334                                         while (i > 0 &&
1335                                                 sp->lsis[i].ls_trans ==
1336                                                 sp->lsis[i - 1].ls_trans + 1 &&
1337                                                 sp->lsis[i].ls_corr ==
1338                                                 sp->lsis[i - 1].ls_corr + 1) {
1339                                                         ++hit;
1340                                                         --i;
1341                                         }
1342                         }
1343                         corr = lp->ls_corr;
1344                         break;
1345                 }
1346         }
1347         y = EPOCH_YEAR;
1348         tdays = timep->tv_sec / SECSPERDAY;
1349         rem = timep->tv_sec - tdays * SECSPERDAY;
1350         while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
1351                 int             newy;
1352                 time_t  tdelta;
1353                 int     idelta;
1354                 int     leapdays;
1355
1356                 tdelta = tdays / DAYSPERLYEAR;
1357                 idelta = tdelta;
1358                 if (tdelta - idelta >= 1 || idelta - tdelta >= 1)
1359                         return NULL;
1360                 if (idelta == 0)
1361                         idelta = (tdays < 0) ? -1 : 1;
1362                 newy = y;
1363                 if (increment_overflow(&newy, idelta))
1364                         return NULL;
1365                 leapdays = leaps_thru_end_of(newy - 1) -
1366                         leaps_thru_end_of(y - 1);
1367                 tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
1368                 tdays -= leapdays;
1369                 y = newy;
1370         }
1371
1372         seconds = tdays * SECSPERDAY + 0.5;
1373         tdays = seconds / SECSPERDAY;
1374         rem += seconds - tdays * SECSPERDAY;
1375
1376         /*
1377         ** Given the range, we can now fearlessly cast...
1378         */
1379         idays = tdays;
1380         rem += offset - corr;
1381         while (rem < 0) {
1382                 rem += SECSPERDAY;
1383                 --idays;
1384         }
1385         while (rem >= SECSPERDAY) {
1386                 rem -= SECSPERDAY;
1387                 ++idays;
1388         }
1389         while (idays < 0) {
1390                 if (increment_overflow(&y, -1))
1391                         return NULL;
1392                 idays += year_lengths[isleap(y)];
1393         }
1394         while (idays >= year_lengths[isleap(y)]) {
1395                 idays -= year_lengths[isleap(y)];
1396                 if (increment_overflow(&y, 1))
1397                         return NULL;
1398         }
1399         tmp->tm_year = y;
1400         if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
1401                 return NULL;
1402         tmp->tm_yday = idays;
1403         /*
1404         ** The "extra" mods below avoid overflow problems.
1405         */
1406         tmp->tm_wday = EPOCH_WDAY +
1407                 ((y - EPOCH_YEAR) % DAYSPERWEEK) *
1408                 (DAYSPERNYEAR % DAYSPERWEEK) +
1409                 leaps_thru_end_of(y - 1) -
1410                 leaps_thru_end_of(EPOCH_YEAR - 1) +
1411                 idays;
1412         tmp->tm_wday %= DAYSPERWEEK;
1413         if (tmp->tm_wday < 0)
1414                 tmp->tm_wday += DAYSPERWEEK;
1415         tmp->tm_hour = (int) (rem / SECSPERHOUR);
1416         rem %= SECSPERHOUR;
1417         tmp->tm_min = (int) (rem / SECSPERMIN);
1418         /*
1419         ** A positive leap second requires a special
1420         ** representation. This uses "... ??:59:60" et seq.
1421         */
1422         tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1423         ip = mon_lengths[isleap(y)];
1424         for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
1425                 idays -= ip[tmp->tm_mon];
1426         tmp->tm_mday = (int) (idays + 1);
1427         tmp->tm_isdst = 0;
1428 #ifdef TM_GMTOFF
1429         tmp->TM_GMTOFF = offset;
1430 #endif /* defined TM_GMTOFF */
1431         tmp->tm_usec = timep->tv_usec;
1432         return tmp;
1433 }
1434
1435 /*! \note
1436 ** Adapted from code provided by Robert Elz, who writes:
1437 **      The "best" way to do mktime I think is based on an idea of Bob
1438 **      Kridle's (so its said...) from a long time ago.
1439 **      It does a binary search of the time_t space. Since time_t's are
1440 **      just 32 bits, its a max of 32 iterations (even at 64 bits it
1441 **      would still be very reasonable).
1442 */
1443
1444 /*! \brief
1445 ** Simplified normalize logic courtesy Paul Eggert.
1446 */
1447
1448 static int increment_overflow(int *number, int delta)
1449 {
1450         int     number0;
1451
1452         number0 = *number;
1453         *number += delta;
1454         return (*number < number0) != (delta < 0);
1455 }
1456
1457 static int long_increment_overflow(long *number, int delta)
1458 {
1459         long    number0;
1460
1461         number0 = *number;
1462         *number += delta;
1463         return (*number < number0) != (delta < 0);
1464 }
1465
1466 static int normalize_overflow(int *tensptr, int *unitsptr, const int base)
1467 {
1468         int     tensdelta;
1469
1470         tensdelta = (*unitsptr >= 0) ?
1471                 (*unitsptr / base) :
1472                 (-1 - (-1 - *unitsptr) / base);
1473         *unitsptr -= tensdelta * base;
1474         return increment_overflow(tensptr, tensdelta);
1475 }
1476
1477 static int long_normalize_overflow(long *tensptr, int *unitsptr, const int base)
1478 {
1479         int     tensdelta;
1480
1481         tensdelta = (*unitsptr >= 0) ?
1482                 (*unitsptr / base) :
1483                 (-1 - (-1 - *unitsptr) / base);
1484         *unitsptr -= tensdelta * base;
1485         return long_increment_overflow(tensptr, tensdelta);
1486 }
1487
1488 static int tmcomp(const struct ast_tm *atmp, const struct ast_tm *btmp)
1489 {
1490         int     result;
1491
1492         if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1493                 (result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1494                 (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1495                 (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1496                 (result = (atmp->tm_min - btmp->tm_min)) == 0 &&
1497                 (result = (atmp->tm_sec - btmp->tm_sec)) == 0)
1498                         result = atmp->tm_usec - btmp->tm_usec;
1499         return result;
1500 }
1501
1502 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)
1503 {
1504         int                     dir;
1505         int                     i, j;
1506         int                     saved_seconds;
1507         long                    li;
1508         time_t                  lo;
1509         time_t                  hi;
1510         long                            y;
1511         struct timeval                  newt = { 0, 0 };
1512         struct timeval                  t = { 0, 0 };
1513         struct ast_tm                   yourtm, mytm;
1514
1515         *okayp = FALSE;
1516         yourtm = *tmp;
1517         if (do_norm_secs) {
1518                 if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1519                         SECSPERMIN))
1520                                 return WRONG;
1521         }
1522         if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1523                 return WRONG;
1524         if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1525                 return WRONG;
1526         y = yourtm.tm_year;
1527         if (long_normalize_overflow(&y, &yourtm.tm_mon, MONSPERYEAR))
1528                 return WRONG;
1529         /*
1530         ** Turn y into an actual year number for now.
1531         ** It is converted back to an offset from TM_YEAR_BASE later.
1532         */
1533         if (long_increment_overflow(&y, TM_YEAR_BASE))
1534                 return WRONG;
1535         while (yourtm.tm_mday <= 0) {
1536                 if (long_increment_overflow(&y, -1))
1537                         return WRONG;
1538                 li = y + (1 < yourtm.tm_mon);
1539                 yourtm.tm_mday += year_lengths[isleap(li)];
1540         }
1541         while (yourtm.tm_mday > DAYSPERLYEAR) {
1542                 li = y + (1 < yourtm.tm_mon);
1543                 yourtm.tm_mday -= year_lengths[isleap(li)];
1544                 if (long_increment_overflow(&y, 1))
1545                         return WRONG;
1546         }
1547         for ( ; ; ) {
1548                 i = mon_lengths[isleap(y)][yourtm.tm_mon];
1549                 if (yourtm.tm_mday <= i)
1550                         break;
1551                 yourtm.tm_mday -= i;
1552                 if (++yourtm.tm_mon >= MONSPERYEAR) {
1553                         yourtm.tm_mon = 0;
1554                         if (long_increment_overflow(&y, 1))
1555                                 return WRONG;
1556                 }
1557         }
1558         if (long_increment_overflow(&y, -TM_YEAR_BASE))
1559                 return WRONG;
1560         yourtm.tm_year = y;
1561         if (yourtm.tm_year != y)
1562                 return WRONG;
1563         if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
1564                 saved_seconds = 0;
1565         else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
1566                 /*
1567                 ** We can't set tm_sec to 0, because that might push the
1568                 ** time below the minimum representable time.
1569                 ** Set tm_sec to 59 instead.
1570                 ** This assumes that the minimum representable time is
1571                 ** not in the same minute that a leap second was deleted from,
1572                 ** which is a safer assumption than using 58 would be.
1573                 */
1574                 if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1575                         return WRONG;
1576                 saved_seconds = yourtm.tm_sec;
1577                 yourtm.tm_sec = SECSPERMIN - 1;
1578         } else {
1579                 saved_seconds = yourtm.tm_sec;
1580                 yourtm.tm_sec = 0;
1581         }
1582         /*
1583         ** Do a binary search (this works whatever time_t's type is).
1584         */
1585         if (!TYPE_SIGNED(time_t)) {
1586                 lo = 0;
1587                 hi = lo - 1;
1588         } else if (!TYPE_INTEGRAL(time_t)) {
1589                 if (sizeof(time_t) > sizeof(float))
1590                         hi = (time_t) DBL_MAX;
1591                 else    hi = (time_t) FLT_MAX;
1592                 lo = -hi;
1593         } else {
1594                 lo = 1;
1595                 for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
1596                         lo *= 2;
1597                 hi = -(lo + 1);
1598         }
1599         for ( ; ; ) {
1600                 t.tv_sec = lo / 2 + hi / 2;
1601                 if (t.tv_sec < lo)
1602                         t.tv_sec = lo;
1603                 else if (t.tv_sec > hi)
1604                         t.tv_sec = hi;
1605                 if ((*funcp)(&t, offset, &mytm, sp) == NULL) {
1606                         /*
1607                         ** Assume that t is too extreme to be represented in
1608                         ** a struct ast_tm; arrange things so that it is less
1609                         ** extreme on the next pass.
1610                         */
1611                         dir = (t.tv_sec > 0) ? 1 : -1;
1612                 } else  dir = tmcomp(&mytm, &yourtm);
1613                 if (dir != 0) {
1614                         if (t.tv_sec == lo) {
1615                                 ++t.tv_sec;
1616                                 if (t.tv_sec <= lo)
1617                                         return WRONG;
1618                                 ++lo;
1619                         } else if (t.tv_sec == hi) {
1620                                 --t.tv_sec;
1621                                 if (t.tv_sec >= hi)
1622                                         return WRONG;
1623                                 --hi;
1624                         }
1625                         if (lo > hi)
1626                                 return WRONG;
1627                         if (dir > 0)
1628                                 hi = t.tv_sec;
1629                         else    lo = t.tv_sec;
1630                         continue;
1631                 }
1632                 if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1633                         break;
1634                 /*
1635                 ** Right time, wrong type.
1636                 ** Hunt for right time, right type.
1637                 ** It's okay to guess wrong since the guess
1638                 ** gets checked.
1639                 */
1640                 /*
1641                 ** The (void *) casts are the benefit of SunOS 3.3 on Sun 2's.
1642                 */
1643                 for (i = sp->typecnt - 1; i >= 0; --i) {
1644                         if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1645                                 continue;
1646                         for (j = sp->typecnt - 1; j >= 0; --j) {
1647                                 if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1648                                         continue;
1649                                 newt.tv_sec = t.tv_sec + sp->ttis[j].tt_gmtoff -
1650                                         sp->ttis[i].tt_gmtoff;
1651                                 if ((*funcp)(&newt, offset, &mytm, sp) == NULL)
1652                                         continue;
1653                                 if (tmcomp(&mytm, &yourtm) != 0)
1654                                         continue;
1655                                 if (mytm.tm_isdst != yourtm.tm_isdst)
1656                                         continue;
1657                                 /*
1658                                 ** We have a match.
1659                                 */
1660                                 t = newt;
1661                                 goto label;
1662                         }
1663                 }
1664                 return WRONG;
1665         }
1666 label:
1667         newt.tv_sec = t.tv_sec + saved_seconds;
1668         if ((newt.tv_sec < t.tv_sec) != (saved_seconds < 0))
1669                 return WRONG;
1670         t.tv_sec = newt.tv_sec;
1671         if ((*funcp)(&t, offset, tmp, sp))
1672                 *okayp = TRUE;
1673         return t;
1674 }
1675
1676 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)
1677 {
1678         struct timeval  t;
1679
1680         /*! \note
1681         ** First try without normalization of seconds
1682         ** (in case tm_sec contains a value associated with a leap second).
1683         ** If that fails, try with normalization of seconds.
1684         */
1685         t = time2sub(tmp, funcp, offset, okayp, FALSE, sp);
1686         return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE, sp);
1687 }
1688
1689 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)
1690 {
1691         struct timeval                  t;
1692         int                     samei, otheri;
1693         int                     sameind, otherind;
1694         int                     i;
1695         int                     nseen;
1696         int                             seen[TZ_MAX_TYPES];
1697         int                             types[TZ_MAX_TYPES];
1698         int                             okay;
1699
1700         if (tmp->tm_isdst > 1)
1701                 tmp->tm_isdst = 1;
1702         t = time2(tmp, funcp, offset, &okay, sp);
1703 #ifdef PCTS
1704         /*
1705         ** PCTS code courtesy Grant Sullivan.
1706         */
1707         if (okay)
1708                 return t;
1709         if (tmp->tm_isdst < 0)
1710                 tmp->tm_isdst = 0;      /* reset to std and try again */
1711 #endif /* defined PCTS */
1712 #ifndef PCTS
1713         if (okay || tmp->tm_isdst < 0)
1714                 return t;
1715 #endif /* !defined PCTS */
1716         /*
1717         ** We're supposed to assume that somebody took a time of one type
1718         ** and did some math on it that yielded a "struct ast_tm" that's bad.
1719         ** We try to divine the type they started from and adjust to the
1720         ** type they need.
1721         */
1722         if (sp == NULL)
1723                 return WRONG;
1724         for (i = 0; i < sp->typecnt; ++i)
1725                 seen[i] = FALSE;
1726         nseen = 0;
1727         for (i = sp->timecnt - 1; i >= 0; --i)
1728                 if (!seen[sp->types[i]]) {
1729                         seen[sp->types[i]] = TRUE;
1730                         types[nseen++] = sp->types[i];
1731                 }
1732         for (sameind = 0; sameind < nseen; ++sameind) {
1733                 samei = types[sameind];
1734                 if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1735                         continue;
1736                 for (otherind = 0; otherind < nseen; ++otherind) {
1737                         otheri = types[otherind];
1738                         if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1739                                 continue;
1740                         tmp->tm_sec += sp->ttis[otheri].tt_gmtoff -
1741                                         sp->ttis[samei].tt_gmtoff;
1742                         tmp->tm_isdst = !tmp->tm_isdst;
1743                         t = time2(tmp, funcp, offset, &okay, sp);
1744                         if (okay)
1745                                 return t;
1746                         tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff -
1747                                         sp->ttis[samei].tt_gmtoff;
1748                         tmp->tm_isdst = !tmp->tm_isdst;
1749                 }
1750         }
1751         return WRONG;
1752 }
1753
1754 struct timeval ast_mktime(struct ast_tm *tmp, const char *zone)
1755 {
1756         const struct state *sp;
1757         if (!(sp = ast_tzset(zone)))
1758                 return WRONG;
1759         return time1(tmp, localsub, 0L, sp);
1760 }
1761
1762 int ast_strftime(char *buf, size_t len, const char *tmp, const struct ast_tm *tm)
1763 {
1764         size_t fmtlen = strlen(tmp) + 1;
1765         char *format = ast_calloc(1, fmtlen), *fptr = format, *newfmt;
1766         int decimals = -1, i, res;
1767         long fraction;
1768
1769         if (!format)
1770                 return -1;
1771         for (; *tmp; tmp++) {
1772                 if (*tmp == '%') {
1773                         switch (tmp[1]) {
1774                         case '1':
1775                         case '2':
1776                         case '3':
1777                         case '4':
1778                         case '5':
1779                         case '6':
1780                                 if (tmp[2] != 'q')
1781                                         goto defcase;
1782                                 decimals = tmp[1] - '0';
1783                                 tmp++;
1784                                 /* Fall through */
1785                         case 'q': /* Milliseconds */
1786                                 if (decimals == -1)
1787                                         decimals = 3;
1788
1789                                 /* Juggle some memory to fit the item */
1790                                 newfmt = ast_realloc(format, fmtlen + decimals);
1791                                 if (!newfmt) {
1792                                         ast_free(format);
1793                                         return -1;
1794                                 }
1795                                 fptr = fptr - format + newfmt;
1796                                 format = newfmt;
1797                                 fmtlen += decimals;
1798
1799                                 /* Reduce the fraction of time to the accuracy needed */
1800                                 for (i = 6, fraction = tm->tm_usec; i > decimals; i--)
1801                                         fraction /= 10;
1802                                 fptr += sprintf(fptr, "%0*ld", decimals, fraction);
1803
1804                                 /* Reset, in case more than one 'q' specifier exists */
1805                                 decimals = -1;
1806                                 tmp++;
1807                                 break;
1808                         default:
1809                                 goto defcase;
1810                         }
1811                 } else
1812 defcase:        *fptr++ = *tmp;
1813         }
1814         *fptr = '\0';
1815 #undef strftime
1816         res = (int)strftime(buf, len, format, (struct tm *)tm);
1817         ast_free(format);
1818         return res;
1819 }
1820