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