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