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