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