localtime.c 66 KB

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