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