localtime.c 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587
  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. #ifdef HAVE_NEWLOCALE
  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 = 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. if (inotify_thread != AST_PTHREADT_NULL) {
  700. AST_LIST_LOCK(&zonelist);
  701. #ifdef TEST_FRAMEWORK
  702. test = info;
  703. #endif
  704. pthread_kill(inotify_thread, SIGURG);
  705. ast_cond_wait(&initialization, &(&zonelist)->lock);
  706. #ifdef TEST_FRAMEWORK
  707. test = NULL;
  708. #endif
  709. AST_LIST_UNLOCK(&zonelist);
  710. }
  711. }
  712. /*! \note
  713. ** Section 4.12.3 of X3.159-1989 requires that
  714. ** Except for the strftime function, these functions [asctime,
  715. ** ctime, gmtime, localtime] return values in one of two static
  716. ** objects: a broken-down time structure and an array of char.
  717. ** Thanks to Paul Eggert for noting this.
  718. */
  719. static long detzcode(const char * const codep)
  720. {
  721. long result;
  722. int i;
  723. result = (codep[0] & 0x80) ? ~0L : 0;
  724. for (i = 0; i < 4; ++i)
  725. result = (result << 8) | (codep[i] & 0xff);
  726. return result;
  727. }
  728. static time_t detzcode64(const char * const codep)
  729. {
  730. time_t result;
  731. int i;
  732. result = (codep[0] & 0x80) ? (~(int_fast64_t) 0) : 0;
  733. for (i = 0; i < 8; ++i)
  734. result = result * 256 + (codep[i] & 0xff);
  735. return result;
  736. }
  737. static int differ_by_repeat(const time_t t1, const time_t t0)
  738. {
  739. const long long at1 = t1, at0 = t0;
  740. if (TYPE_INTEGRAL(time_t) &&
  741. TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
  742. return 0;
  743. return at1 - at0 == SECSPERREPEAT;
  744. }
  745. static int tzload(const char *name, struct state * const sp, const int doextend)
  746. {
  747. const char * p;
  748. int i;
  749. int fid;
  750. int stored;
  751. int nread;
  752. union {
  753. struct tzhead tzhead;
  754. char buf[2 * sizeof(struct tzhead) +
  755. 2 * sizeof *sp +
  756. 4 * TZ_MAX_TIMES];
  757. } u;
  758. if (name == NULL && (name = TZDEFAULT) == NULL)
  759. return -1;
  760. {
  761. int doaccess;
  762. /*
  763. ** Section 4.9.1 of the C standard says that
  764. ** "FILENAME_MAX expands to an integral constant expression
  765. ** that is the size needed for an array of char large enough
  766. ** to hold the longest file name string that the implementation
  767. ** guarantees can be opened."
  768. */
  769. char fullname[FILENAME_MAX + 1];
  770. if (name[0] == ':')
  771. ++name;
  772. doaccess = name[0] == '/';
  773. if (!doaccess) {
  774. if ((p = TZDIR) == NULL)
  775. return -1;
  776. if ((strlen(p) + strlen(name) + 1) >= sizeof fullname)
  777. return -1;
  778. (void) strcpy(fullname, p);
  779. (void) strcat(fullname, "/");
  780. (void) strcat(fullname, name);
  781. /*
  782. ** Set doaccess if '.' (as in "../") shows up in name.
  783. */
  784. if (strchr(name, '.') != NULL)
  785. doaccess = TRUE;
  786. name = fullname;
  787. }
  788. if (doaccess && access(name, R_OK) != 0)
  789. return -1;
  790. if ((fid = open(name, OPEN_MODE)) == -1)
  791. return -1;
  792. if (ast_fully_booted) {
  793. /* If we don't wait until Asterisk is fully booted, it's possible
  794. * that the watcher thread gets started in the parent process,
  795. * before daemon(3) is called, and the thread won't propagate to
  796. * the child. Given that bootup only takes a few seconds, it's
  797. * reasonable to only start the watcher later. */
  798. add_notify(sp, name);
  799. }
  800. }
  801. nread = read(fid, u.buf, sizeof u.buf);
  802. /* comp nread < sizeof u.tzhead against unexpected short files */
  803. if (close(fid) < 0 || nread < sizeof u.tzhead)
  804. return -1;
  805. for (stored = 4; stored <= 8; stored *= 2) {
  806. int ttisstdcnt;
  807. int ttisgmtcnt;
  808. ttisstdcnt = (int) detzcode(u.tzhead.tzh_ttisstdcnt);
  809. ttisgmtcnt = (int) detzcode(u.tzhead.tzh_ttisgmtcnt);
  810. sp->leapcnt = (int) detzcode(u.tzhead.tzh_leapcnt);
  811. sp->timecnt = (int) detzcode(u.tzhead.tzh_timecnt);
  812. sp->typecnt = (int) detzcode(u.tzhead.tzh_typecnt);
  813. sp->charcnt = (int) detzcode(u.tzhead.tzh_charcnt);
  814. p = u.tzhead.tzh_charcnt + sizeof u.tzhead.tzh_charcnt;
  815. if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
  816. sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
  817. sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
  818. sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
  819. (ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
  820. (ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
  821. return -1;
  822. if (nread - (p - u.buf) <
  823. sp->timecnt * stored + /* ats */
  824. sp->timecnt + /* types */
  825. sp->typecnt * 6 + /* ttinfos */
  826. sp->charcnt + /* chars */
  827. sp->leapcnt * (stored + 4) + /* lsinfos */
  828. ttisstdcnt + /* ttisstds */
  829. ttisgmtcnt) /* ttisgmts */
  830. return -1;
  831. for (i = 0; i < sp->timecnt; ++i) {
  832. sp->ats[i] = (stored == 4) ?
  833. detzcode(p) : detzcode64(p);
  834. p += stored;
  835. }
  836. for (i = 0; i < sp->timecnt; ++i) {
  837. sp->types[i] = (unsigned char) *p++;
  838. if (sp->types[i] >= sp->typecnt)
  839. return -1;
  840. }
  841. for (i = 0; i < sp->typecnt; ++i) {
  842. struct ttinfo * ttisp;
  843. ttisp = &sp->ttis[i];
  844. ttisp->tt_gmtoff = detzcode(p);
  845. p += 4;
  846. ttisp->tt_isdst = (unsigned char) *p++;
  847. if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
  848. return -1;
  849. ttisp->tt_abbrind = (unsigned char) *p++;
  850. if (ttisp->tt_abbrind < 0 ||
  851. ttisp->tt_abbrind > sp->charcnt)
  852. return -1;
  853. }
  854. for (i = 0; i < sp->charcnt; ++i)
  855. sp->chars[i] = *p++;
  856. sp->chars[i] = '\0'; /* ensure '\0' at end */
  857. for (i = 0; i < sp->leapcnt; ++i) {
  858. struct lsinfo * lsisp;
  859. lsisp = &sp->lsis[i];
  860. lsisp->ls_trans = (stored == 4) ?
  861. detzcode(p) : detzcode64(p);
  862. p += stored;
  863. lsisp->ls_corr = detzcode(p);
  864. p += 4;
  865. }
  866. for (i = 0; i < sp->typecnt; ++i) {
  867. struct ttinfo * ttisp;
  868. ttisp = &sp->ttis[i];
  869. if (ttisstdcnt == 0)
  870. ttisp->tt_ttisstd = FALSE;
  871. else {
  872. ttisp->tt_ttisstd = *p++;
  873. if (ttisp->tt_ttisstd != TRUE &&
  874. ttisp->tt_ttisstd != FALSE)
  875. return -1;
  876. }
  877. }
  878. for (i = 0; i < sp->typecnt; ++i) {
  879. struct ttinfo * ttisp;
  880. ttisp = &sp->ttis[i];
  881. if (ttisgmtcnt == 0)
  882. ttisp->tt_ttisgmt = FALSE;
  883. else {
  884. ttisp->tt_ttisgmt = *p++;
  885. if (ttisp->tt_ttisgmt != TRUE &&
  886. ttisp->tt_ttisgmt != FALSE)
  887. return -1;
  888. }
  889. }
  890. /*
  891. ** Out-of-sort ats should mean we're running on a
  892. ** signed time_t system but using a data file with
  893. ** unsigned values (or vice versa).
  894. */
  895. for (i = 0; i < sp->timecnt - 2; ++i)
  896. if (sp->ats[i] > sp->ats[i + 1]) {
  897. ++i;
  898. if (TYPE_SIGNED(time_t)) {
  899. /*
  900. ** Ignore the end (easy).
  901. */
  902. sp->timecnt = i;
  903. } else {
  904. /*
  905. ** Ignore the beginning (harder).
  906. */
  907. int j;
  908. for (j = 0; j + i < sp->timecnt; ++j) {
  909. sp->ats[j] = sp->ats[j + i];
  910. sp->types[j] = sp->types[j + i];
  911. }
  912. sp->timecnt = j;
  913. }
  914. break;
  915. }
  916. /*
  917. ** If this is an old file, we're done.
  918. */
  919. if (u.tzhead.tzh_version[0] == '\0')
  920. break;
  921. nread -= p - u.buf;
  922. for (i = 0; i < nread; ++i)
  923. u.buf[i] = p[i];
  924. /* next loop iter. will assume at least
  925. sizeof(struct tzhead) bytes */
  926. if (nread < sizeof(u.tzhead)) {
  927. break;
  928. }
  929. /*
  930. ** If this is a narrow integer time_t system, we're done.
  931. */
  932. if (stored >= (int) sizeof(time_t) && TYPE_INTEGRAL(time_t))
  933. break;
  934. }
  935. if (doextend && nread > 2 &&
  936. u.buf[0] == '\n' && u.buf[nread - 1] == '\n' &&
  937. sp->typecnt + 2 <= TZ_MAX_TYPES) {
  938. struct state ts;
  939. int result;
  940. /* for temporary struct state --
  941. * macro flags the the struct as a stack temp.
  942. * to prevent use within add_notify()
  943. */
  944. SP_STACK_INIT(ts);
  945. u.buf[nread - 1] = '\0';
  946. result = tzparse(&u.buf[1], &ts, FALSE);
  947. if (result == 0 && ts.typecnt == 2 &&
  948. sp->charcnt + ts.charcnt <= TZ_MAX_CHARS) {
  949. for (i = 0; i < 2; ++i)
  950. ts.ttis[i].tt_abbrind +=
  951. sp->charcnt;
  952. for (i = 0; i < ts.charcnt; ++i)
  953. sp->chars[sp->charcnt++] =
  954. ts.chars[i];
  955. i = 0;
  956. while (i < ts.timecnt &&
  957. ts.ats[i] <=
  958. sp->ats[sp->timecnt - 1])
  959. ++i;
  960. while (i < ts.timecnt &&
  961. sp->timecnt < TZ_MAX_TIMES) {
  962. sp->ats[sp->timecnt] =
  963. ts.ats[i];
  964. sp->types[sp->timecnt] =
  965. sp->typecnt +
  966. ts.types[i];
  967. ++sp->timecnt;
  968. ++i;
  969. }
  970. sp->ttis[sp->typecnt++] = ts.ttis[0];
  971. sp->ttis[sp->typecnt++] = ts.ttis[1];
  972. }
  973. }
  974. i = 2 * YEARSPERREPEAT;
  975. sp->goback = sp->goahead = sp->timecnt > i;
  976. sp->goback = sp->goback && sp->types[i] == sp->types[0] &&
  977. differ_by_repeat(sp->ats[i], sp->ats[0]);
  978. sp->goahead = sp->goahead &&
  979. sp->types[sp->timecnt - 1] == sp->types[sp->timecnt - 1 - i] &&
  980. differ_by_repeat(sp->ats[sp->timecnt - 1],
  981. sp->ats[sp->timecnt - 1 - i]);
  982. return 0;
  983. }
  984. static const int mon_lengths[2][MONSPERYEAR] = {
  985. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
  986. { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
  987. };
  988. static const int year_lengths[2] = {
  989. DAYSPERNYEAR, DAYSPERLYEAR
  990. };
  991. /*! \brief
  992. ** Given a pointer into a time zone string, scan until a character that is not
  993. ** a valid character in a zone name is found. Return a pointer to that
  994. ** character.
  995. */
  996. static const char * getzname(const char *strp)
  997. {
  998. char c;
  999. while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
  1000. c != '+')
  1001. ++strp;
  1002. return strp;
  1003. }
  1004. /*! \brief
  1005. ** Given a pointer into an extended time zone string, scan until the ending
  1006. ** delimiter of the zone name is located. Return a pointer to the delimiter.
  1007. **
  1008. ** As with getzname above, the legal character set is actually quite
  1009. ** restricted, with other characters producing undefined results.
  1010. ** We don't do any checking here; checking is done later in common-case code.
  1011. */
  1012. static const char * getqzname(const char *strp, const int delim)
  1013. {
  1014. int c;
  1015. while ((c = *strp) != '\0' && c != delim)
  1016. ++strp;
  1017. return strp;
  1018. }
  1019. /*! \brief
  1020. ** Given a pointer into a time zone string, extract a number from that string.
  1021. ** Check that the number is within a specified range; if it is not, return
  1022. ** NULL.
  1023. ** Otherwise, return a pointer to the first character not part of the number.
  1024. */
  1025. static const char *getnum(const char *strp, int *nump, const int min, const int max)
  1026. {
  1027. char c;
  1028. int num;
  1029. if (strp == NULL || !is_digit(c = *strp))
  1030. return NULL;
  1031. num = 0;
  1032. do {
  1033. num = num * 10 + (c - '0');
  1034. if (num > max)
  1035. return NULL; /* illegal value */
  1036. c = *++strp;
  1037. } while (is_digit(c));
  1038. if (num < min)
  1039. return NULL; /* illegal value */
  1040. *nump = num;
  1041. return strp;
  1042. }
  1043. /*! \brief
  1044. ** Given a pointer into a time zone string, extract a number of seconds,
  1045. ** in hh[:mm[:ss]] form, from the string.
  1046. ** If any error occurs, return NULL.
  1047. ** Otherwise, return a pointer to the first character not part of the number
  1048. ** of seconds.
  1049. */
  1050. static const char *getsecs(const char *strp, long * const secsp)
  1051. {
  1052. int num;
  1053. /*
  1054. ** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
  1055. ** "M10.4.6/26", which does not conform to Posix,
  1056. ** but which specifies the equivalent of
  1057. ** ``02:00 on the first Sunday on or after 23 Oct''.
  1058. */
  1059. strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
  1060. if (strp == NULL)
  1061. return NULL;
  1062. *secsp = num * (long) SECSPERHOUR;
  1063. if (*strp == ':') {
  1064. ++strp;
  1065. strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
  1066. if (strp == NULL)
  1067. return NULL;
  1068. *secsp += num * SECSPERMIN;
  1069. if (*strp == ':') {
  1070. ++strp;
  1071. /* `SECSPERMIN' allows for leap seconds. */
  1072. strp = getnum(strp, &num, 0, SECSPERMIN);
  1073. if (strp == NULL)
  1074. return NULL;
  1075. *secsp += num;
  1076. }
  1077. }
  1078. return strp;
  1079. }
  1080. /*! \brief
  1081. ** Given a pointer into a time zone string, extract an offset, in
  1082. ** [+-]hh[:mm[:ss]] form, from the string.
  1083. ** If any error occurs, return NULL.
  1084. ** Otherwise, return a pointer to the first character not part of the time.
  1085. */
  1086. static const char *getoffset(const char *strp, long *offsetp)
  1087. {
  1088. int neg = 0;
  1089. if (*strp == '-') {
  1090. neg = 1;
  1091. ++strp;
  1092. } else if (*strp == '+')
  1093. ++strp;
  1094. strp = getsecs(strp, offsetp);
  1095. if (strp == NULL)
  1096. return NULL; /* illegal time */
  1097. if (neg)
  1098. *offsetp = -*offsetp;
  1099. return strp;
  1100. }
  1101. /*! \brief
  1102. ** Given a pointer into a time zone string, extract a rule in the form
  1103. ** date[/time]. See POSIX section 8 for the format of "date" and "time".
  1104. ** If a valid rule is not found, return NULL.
  1105. ** Otherwise, return a pointer to the first character not part of the rule.
  1106. */
  1107. static const char *getrule(const char *strp, struct rule *rulep)
  1108. {
  1109. if (*strp == 'J') {
  1110. /*
  1111. ** Julian day.
  1112. */
  1113. rulep->r_type = JULIAN_DAY;
  1114. ++strp;
  1115. strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
  1116. } else if (*strp == 'M') {
  1117. /*
  1118. ** Month, week, day.
  1119. */
  1120. rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
  1121. ++strp;
  1122. strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
  1123. if (strp == NULL)
  1124. return NULL;
  1125. if (*strp++ != '.')
  1126. return NULL;
  1127. strp = getnum(strp, &rulep->r_week, 1, 5);
  1128. if (strp == NULL)
  1129. return NULL;
  1130. if (*strp++ != '.')
  1131. return NULL;
  1132. strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
  1133. } else if (is_digit(*strp)) {
  1134. /*
  1135. ** Day of year.
  1136. */
  1137. rulep->r_type = DAY_OF_YEAR;
  1138. strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
  1139. } else return NULL; /* invalid format */
  1140. if (strp == NULL)
  1141. return NULL;
  1142. if (*strp == '/') {
  1143. /*
  1144. ** Time specified.
  1145. */
  1146. ++strp;
  1147. strp = getsecs(strp, &rulep->r_time);
  1148. } else rulep->r_time = 2 * SECSPERHOUR; /* default = 2:00:00 */
  1149. return strp;
  1150. }
  1151. /*! \brief
  1152. ** Given the Epoch-relative time of January 1, 00:00:00 UTC, in a year, the
  1153. ** year, a rule, and the offset from UTC at the time that rule takes effect,
  1154. ** calculate the Epoch-relative time that rule takes effect.
  1155. */
  1156. static time_t transtime(const time_t janfirst, const int year, const struct rule *rulep, const long offset)
  1157. {
  1158. int leapyear;
  1159. time_t value;
  1160. int i;
  1161. int d, m1, yy0, yy1, yy2, dow;
  1162. INITIALIZE(value);
  1163. leapyear = isleap(year);
  1164. switch (rulep->r_type) {
  1165. case JULIAN_DAY:
  1166. /*
  1167. ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
  1168. ** years.
  1169. ** In non-leap years, or if the day number is 59 or less, just
  1170. ** add SECSPERDAY times the day number-1 to the time of
  1171. ** January 1, midnight, to get the day.
  1172. */
  1173. value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
  1174. if (leapyear && rulep->r_day >= 60)
  1175. value += SECSPERDAY;
  1176. break;
  1177. case DAY_OF_YEAR:
  1178. /*
  1179. ** n - day of year.
  1180. ** Just add SECSPERDAY times the day number to the time of
  1181. ** January 1, midnight, to get the day.
  1182. */
  1183. value = janfirst + rulep->r_day * SECSPERDAY;
  1184. break;
  1185. case MONTH_NTH_DAY_OF_WEEK:
  1186. /*
  1187. ** Mm.n.d - nth "dth day" of month m.
  1188. */
  1189. value = janfirst;
  1190. for (i = 0; i < rulep->r_mon - 1; ++i)
  1191. value += mon_lengths[leapyear][i] * SECSPERDAY;
  1192. /*
  1193. ** Use Zeller's Congruence to get day-of-week of first day of
  1194. ** month.
  1195. */
  1196. m1 = (rulep->r_mon + 9) % 12 + 1;
  1197. yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
  1198. yy1 = yy0 / 100;
  1199. yy2 = yy0 % 100;
  1200. dow = ((26 * m1 - 2) / 10 +
  1201. 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
  1202. if (dow < 0)
  1203. dow += DAYSPERWEEK;
  1204. /*
  1205. ** "dow" is the day-of-week of the first day of the month. Get
  1206. ** the day-of-month (zero-origin) of the first "dow" day of the
  1207. ** month.
  1208. */
  1209. d = rulep->r_day - dow;
  1210. if (d < 0)
  1211. d += DAYSPERWEEK;
  1212. for (i = 1; i < rulep->r_week; ++i) {
  1213. if (d + DAYSPERWEEK >=
  1214. mon_lengths[leapyear][rulep->r_mon - 1])
  1215. break;
  1216. d += DAYSPERWEEK;
  1217. }
  1218. /*
  1219. ** "d" is the day-of-month (zero-origin) of the day we want.
  1220. */
  1221. value += d * SECSPERDAY;
  1222. break;
  1223. }
  1224. /*
  1225. ** "value" is the Epoch-relative time of 00:00:00 UTC on the day in
  1226. ** question. To get the Epoch-relative time of the specified local
  1227. ** time on that day, add the transition time and the current offset
  1228. ** from UTC.
  1229. */
  1230. return value + rulep->r_time + offset;
  1231. }
  1232. /*! \note
  1233. ** Given a POSIX section 8-style TZ string, fill in the rule tables as
  1234. ** appropriate.
  1235. */
  1236. static int tzparse(const char *name, struct state *sp, const int lastditch)
  1237. {
  1238. const char * stdname;
  1239. const char * dstname;
  1240. size_t stdlen;
  1241. size_t dstlen;
  1242. long stdoffset;
  1243. long dstoffset;
  1244. time_t * atp;
  1245. unsigned char * typep;
  1246. char * cp;
  1247. int load_result;
  1248. INITIALIZE(dstname);
  1249. stdname = name;
  1250. if (lastditch) {
  1251. stdlen = strlen(name); /* length of standard zone name */
  1252. name += stdlen;
  1253. if (stdlen >= sizeof sp->chars)
  1254. stdlen = (sizeof sp->chars) - 1;
  1255. stdoffset = 0;
  1256. } else {
  1257. if (*name == '<') {
  1258. name++;
  1259. stdname = name;
  1260. name = getqzname(name, '>');
  1261. if (*name != '>')
  1262. return -1;
  1263. stdlen = name - stdname;
  1264. name++;
  1265. } else {
  1266. name = getzname(name);
  1267. stdlen = name - stdname;
  1268. }
  1269. if (*name == '\0')
  1270. return -1;
  1271. name = getoffset(name, &stdoffset);
  1272. if (name == NULL)
  1273. return -1;
  1274. }
  1275. load_result = tzload(TZDEFRULES, sp, FALSE);
  1276. if (load_result != 0)
  1277. sp->leapcnt = 0; /* so, we're off a little */
  1278. if (*name != '\0') {
  1279. if (*name == '<') {
  1280. dstname = ++name;
  1281. name = getqzname(name, '>');
  1282. if (*name != '>')
  1283. return -1;
  1284. dstlen = name - dstname;
  1285. name++;
  1286. } else {
  1287. dstname = name;
  1288. name = getzname(name);
  1289. dstlen = name - dstname; /* length of DST zone name */
  1290. }
  1291. if (*name != '\0' && *name != ',' && *name != ';') {
  1292. name = getoffset(name, &dstoffset);
  1293. if (name == NULL)
  1294. return -1;
  1295. } else dstoffset = stdoffset - SECSPERHOUR;
  1296. if (*name == '\0' && load_result != 0)
  1297. name = TZDEFRULESTRING;
  1298. if (*name == ',' || *name == ';') {
  1299. struct rule start;
  1300. struct rule end;
  1301. int year;
  1302. time_t janfirst;
  1303. time_t starttime;
  1304. time_t endtime;
  1305. ++name;
  1306. if ((name = getrule(name, &start)) == NULL)
  1307. return -1;
  1308. if (*name++ != ',')
  1309. return -1;
  1310. if ((name = getrule(name, &end)) == NULL)
  1311. return -1;
  1312. if (*name != '\0')
  1313. return -1;
  1314. sp->typecnt = 2; /* standard time and DST */
  1315. /*
  1316. ** Two transitions per year, from EPOCH_YEAR forward.
  1317. */
  1318. sp->ttis[0].tt_gmtoff = -dstoffset;
  1319. sp->ttis[0].tt_isdst = 1;
  1320. sp->ttis[0].tt_abbrind = stdlen + 1;
  1321. sp->ttis[1].tt_gmtoff = -stdoffset;
  1322. sp->ttis[1].tt_isdst = 0;
  1323. sp->ttis[1].tt_abbrind = 0;
  1324. atp = sp->ats;
  1325. typep = sp->types;
  1326. janfirst = 0;
  1327. sp->timecnt = 0;
  1328. for (year = EPOCH_YEAR;
  1329. sp->timecnt + 2 <= TZ_MAX_TIMES;
  1330. ++year) {
  1331. time_t newfirst;
  1332. starttime = transtime(janfirst, year, &start,
  1333. stdoffset);
  1334. endtime = transtime(janfirst, year, &end,
  1335. dstoffset);
  1336. if (starttime > endtime) {
  1337. *atp++ = endtime;
  1338. *typep++ = 1; /* DST ends */
  1339. *atp++ = starttime;
  1340. *typep++ = 0; /* DST begins */
  1341. } else {
  1342. *atp++ = starttime;
  1343. *typep++ = 0; /* DST begins */
  1344. *atp++ = endtime;
  1345. *typep++ = 1; /* DST ends */
  1346. }
  1347. sp->timecnt += 2;
  1348. newfirst = janfirst;
  1349. newfirst += year_lengths[isleap(year)] *
  1350. SECSPERDAY;
  1351. if (newfirst <= janfirst)
  1352. break;
  1353. janfirst = newfirst;
  1354. }
  1355. } else {
  1356. long theirstdoffset;
  1357. long theirdstoffset;
  1358. long theiroffset;
  1359. int isdst;
  1360. int i;
  1361. int j;
  1362. if (*name != '\0')
  1363. return -1;
  1364. /*
  1365. ** Initial values of theirstdoffset and theirdstoffset.
  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. theirdstoffset = 0;
  1377. for (i = 0; i < sp->timecnt; ++i) {
  1378. j = sp->types[i];
  1379. if (sp->ttis[j].tt_isdst) {
  1380. theirdstoffset =
  1381. -sp->ttis[j].tt_gmtoff;
  1382. break;
  1383. }
  1384. }
  1385. /*
  1386. ** Initially we're assumed to be in standard time.
  1387. */
  1388. isdst = FALSE;
  1389. theiroffset = theirstdoffset;
  1390. /*
  1391. ** Now juggle transition times and types
  1392. ** tracking offsets as you do.
  1393. */
  1394. for (i = 0; i < sp->timecnt; ++i) {
  1395. j = sp->types[i];
  1396. sp->types[i] = sp->ttis[j].tt_isdst;
  1397. if (sp->ttis[j].tt_ttisgmt) {
  1398. /* No adjustment to transition time */
  1399. } else {
  1400. /*
  1401. ** If summer time is in effect, and the
  1402. ** transition time was not specified as
  1403. ** standard time, add the summer time
  1404. ** offset to the transition time;
  1405. ** otherwise, add the standard time
  1406. ** offset to the transition time.
  1407. */
  1408. /*
  1409. ** Transitions from DST to DDST
  1410. ** will effectively disappear since
  1411. ** POSIX provides for only one DST
  1412. ** offset.
  1413. */
  1414. if (isdst && !sp->ttis[j].tt_ttisstd) {
  1415. sp->ats[i] += dstoffset -
  1416. theirdstoffset;
  1417. } else {
  1418. sp->ats[i] += stdoffset -
  1419. theirstdoffset;
  1420. }
  1421. }
  1422. theiroffset = -sp->ttis[j].tt_gmtoff;
  1423. if (sp->ttis[j].tt_isdst)
  1424. theirdstoffset = theiroffset;
  1425. else theirstdoffset = theiroffset;
  1426. }
  1427. /*
  1428. ** Finally, fill in ttis.
  1429. ** ttisstd and ttisgmt need not be handled.
  1430. */
  1431. sp->ttis[0].tt_gmtoff = -stdoffset;
  1432. sp->ttis[0].tt_isdst = FALSE;
  1433. sp->ttis[0].tt_abbrind = 0;
  1434. sp->ttis[1].tt_gmtoff = -dstoffset;
  1435. sp->ttis[1].tt_isdst = TRUE;
  1436. sp->ttis[1].tt_abbrind = stdlen + 1;
  1437. sp->typecnt = 2;
  1438. }
  1439. } else {
  1440. dstlen = 0;
  1441. sp->typecnt = 1; /* only standard time */
  1442. sp->timecnt = 0;
  1443. sp->ttis[0].tt_gmtoff = -stdoffset;
  1444. sp->ttis[0].tt_isdst = 0;
  1445. sp->ttis[0].tt_abbrind = 0;
  1446. }
  1447. sp->charcnt = stdlen + 1;
  1448. if (dstlen != 0)
  1449. sp->charcnt += dstlen + 1;
  1450. if ((size_t) sp->charcnt > sizeof sp->chars)
  1451. return -1;
  1452. cp = sp->chars;
  1453. (void) strncpy(cp, stdname, stdlen);
  1454. cp += stdlen;
  1455. *cp++ = '\0';
  1456. if (dstlen != 0) {
  1457. (void) strncpy(cp, dstname, dstlen);
  1458. *(cp + dstlen) = '\0';
  1459. }
  1460. return 0;
  1461. }
  1462. static int gmtload(struct state *sp)
  1463. {
  1464. if (tzload(gmt, sp, TRUE) != 0)
  1465. return tzparse(gmt, sp, TRUE);
  1466. else
  1467. return -1;
  1468. }
  1469. void clean_time_zones(void)
  1470. {
  1471. struct state *sp;
  1472. AST_LIST_LOCK(&zonelist);
  1473. while ((sp = AST_LIST_REMOVE_HEAD(&zonelist, list))) {
  1474. sstate_free(sp);
  1475. }
  1476. AST_LIST_UNLOCK(&zonelist);
  1477. }
  1478. static const struct state *ast_tzset(const char *zone)
  1479. {
  1480. struct state *sp;
  1481. if (ast_strlen_zero(zone)) {
  1482. #ifdef SOLARIS
  1483. zone = getenv("TZ");
  1484. if (ast_strlen_zero(zone)) {
  1485. zone = "GMT";
  1486. }
  1487. #else
  1488. zone = "/etc/localtime";
  1489. #endif
  1490. }
  1491. AST_LIST_LOCK(&zonelist);
  1492. AST_LIST_TRAVERSE(&zonelist, sp, list) {
  1493. if (!strcmp(sp->name, zone)) {
  1494. AST_LIST_UNLOCK(&zonelist);
  1495. return sp;
  1496. }
  1497. }
  1498. if (!(sp = sstate_alloc())) {
  1499. AST_LIST_UNLOCK(&zonelist);
  1500. return NULL;
  1501. }
  1502. if (tzload(zone, sp, TRUE) != 0) {
  1503. if (zone[0] == ':' || tzparse(zone, sp, FALSE) != 0)
  1504. (void) gmtload(sp);
  1505. }
  1506. ast_copy_string(sp->name, zone, sizeof(sp->name));
  1507. AST_LIST_INSERT_TAIL(&zonelist, sp, list);
  1508. AST_LIST_UNLOCK(&zonelist);
  1509. return sp;
  1510. }
  1511. /*! \note
  1512. ** The easy way to behave "as if no library function calls" localtime
  1513. ** is to not call it--so we drop its guts into "localsub", which can be
  1514. ** freely called. (And no, the PANS doesn't require the above behavior--
  1515. ** but it *is* desirable.)
  1516. **
  1517. ** The unused offset argument is for the benefit of mktime variants.
  1518. */
  1519. static struct ast_tm *localsub(const struct timeval *timep, const long offset, struct ast_tm *tmp, const struct state *sp)
  1520. {
  1521. const struct ttinfo * ttisp;
  1522. int i;
  1523. struct ast_tm * result;
  1524. struct timeval t;
  1525. memcpy(&t, timep, sizeof(t));
  1526. if (sp == NULL)
  1527. return gmtsub(timep, offset, tmp);
  1528. if ((sp->goback && t.tv_sec < sp->ats[0]) ||
  1529. (sp->goahead && t.tv_sec > sp->ats[sp->timecnt - 1])) {
  1530. struct timeval newt = t;
  1531. time_t seconds;
  1532. time_t tcycles;
  1533. int_fast64_t icycles;
  1534. if (t.tv_sec < sp->ats[0])
  1535. seconds = sp->ats[0] - t.tv_sec;
  1536. else seconds = t.tv_sec - sp->ats[sp->timecnt - 1];
  1537. --seconds;
  1538. tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
  1539. ++tcycles;
  1540. icycles = tcycles;
  1541. if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
  1542. return NULL;
  1543. seconds = icycles;
  1544. seconds *= YEARSPERREPEAT;
  1545. seconds *= AVGSECSPERYEAR;
  1546. if (t.tv_sec < sp->ats[0])
  1547. newt.tv_sec += seconds;
  1548. else newt.tv_sec -= seconds;
  1549. if (newt.tv_sec < sp->ats[0] ||
  1550. newt.tv_sec > sp->ats[sp->timecnt - 1])
  1551. return NULL; /* "cannot happen" */
  1552. result = localsub(&newt, offset, tmp, sp);
  1553. if (result == tmp) {
  1554. time_t newy;
  1555. newy = tmp->tm_year;
  1556. if (t.tv_sec < sp->ats[0])
  1557. newy -= icycles * YEARSPERREPEAT;
  1558. else
  1559. newy += icycles * YEARSPERREPEAT;
  1560. tmp->tm_year = newy;
  1561. if (tmp->tm_year != newy)
  1562. return NULL;
  1563. }
  1564. return result;
  1565. }
  1566. if (sp->timecnt == 0 || t.tv_sec < sp->ats[0]) {
  1567. i = 0;
  1568. while (sp->ttis[i].tt_isdst) {
  1569. if (++i >= sp->typecnt) {
  1570. i = 0;
  1571. break;
  1572. }
  1573. }
  1574. } else {
  1575. int lo = 1;
  1576. int hi = sp->timecnt;
  1577. while (lo < hi) {
  1578. int mid = (lo + hi) >> 1;
  1579. if (t.tv_sec < sp->ats[mid])
  1580. hi = mid;
  1581. else
  1582. lo = mid + 1;
  1583. }
  1584. i = (int) sp->types[lo - 1];
  1585. }
  1586. ttisp = &sp->ttis[i];
  1587. /*
  1588. ** To get (wrong) behavior that's compatible with System V Release 2.0
  1589. ** you'd replace the statement below with
  1590. ** t += ttisp->tt_gmtoff;
  1591. ** timesub(&t, 0L, sp, tmp);
  1592. */
  1593. result = timesub(&t, ttisp->tt_gmtoff, sp, tmp);
  1594. tmp->tm_isdst = ttisp->tt_isdst;
  1595. #ifndef SOLARIS /* Solaris doesn't have this element */
  1596. tmp->tm_gmtoff = ttisp->tt_gmtoff;
  1597. #endif
  1598. #ifdef TM_ZONE
  1599. tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
  1600. #endif /* defined TM_ZONE */
  1601. tmp->tm_usec = timep->tv_usec;
  1602. return result;
  1603. }
  1604. struct ast_tm *ast_localtime(const struct timeval *timep, struct ast_tm *tmp, const char *zone)
  1605. {
  1606. const struct state *sp = ast_tzset(zone);
  1607. memset(tmp, 0, sizeof(*tmp));
  1608. return sp ? localsub(timep, 0L, tmp, sp) : NULL;
  1609. }
  1610. /*
  1611. ** This function provides informaton about daylight savings time
  1612. ** for the given timezone. This includes whether it can determine
  1613. ** if daylight savings is used for this timezone, the UTC times for
  1614. ** when daylight savings transitions, and the offset in seconds from
  1615. ** UTC.
  1616. */
  1617. 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)
  1618. {
  1619. int i;
  1620. int transition1 = -1;
  1621. int transition2 = -1;
  1622. time_t seconds;
  1623. int bounds_exceeded = 0;
  1624. time_t t = *timep;
  1625. const struct state *sp;
  1626. if (NULL == dst_enabled)
  1627. return;
  1628. *dst_enabled = 0;
  1629. if (NULL == dst_start || NULL == dst_end || NULL == gmt_off)
  1630. return;
  1631. *gmt_off = 0;
  1632. sp = ast_tzset(zone);
  1633. if (NULL == sp)
  1634. return;
  1635. /* If the desired time exceeds the bounds of the defined time transitions
  1636. * then give give up on determining DST info and simply look for gmt offset
  1637. * This requires that I adjust the given time using increments of Gregorian
  1638. * repeats to place the time within the defined time transitions in the
  1639. * timezone structure.
  1640. */
  1641. if ((sp->goback && t < sp->ats[0]) ||
  1642. (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
  1643. time_t tcycles;
  1644. int_fast64_t icycles;
  1645. if (t < sp->ats[0])
  1646. seconds = sp->ats[0] - t;
  1647. else seconds = t - sp->ats[sp->timecnt - 1];
  1648. --seconds;
  1649. tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
  1650. ++tcycles;
  1651. icycles = tcycles;
  1652. if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
  1653. return;
  1654. seconds = icycles;
  1655. seconds *= YEARSPERREPEAT;
  1656. seconds *= AVGSECSPERYEAR;
  1657. if (t < sp->ats[0])
  1658. t += seconds;
  1659. else
  1660. t -= seconds;
  1661. if (t < sp->ats[0] || t > sp->ats[sp->timecnt - 1])
  1662. return; /* "cannot happen" */
  1663. bounds_exceeded = 1;
  1664. }
  1665. if (sp->timecnt == 0 || t < sp->ats[0]) {
  1666. /* I have no transition times or I'm before time */
  1667. *dst_enabled = 0;
  1668. /* Find where I can get gmtoff */
  1669. i = 0;
  1670. while (sp->ttis[i].tt_isdst)
  1671. if (++i >= sp->typecnt) {
  1672. i = 0;
  1673. break;
  1674. }
  1675. *gmt_off = sp->ttis[i].tt_gmtoff;
  1676. return;
  1677. }
  1678. for (i = 1; i < sp->timecnt; ++i) {
  1679. if (t < sp->ats[i]) {
  1680. transition1 = sp->types[i - 1];
  1681. transition2 = sp->types[i];
  1682. break;
  1683. }
  1684. }
  1685. /* if I found transition times that do not bounded the given time and these correspond to
  1686. or the bounding zones do not reflect a changes in day light savings, then I do not have dst active */
  1687. if (i >= sp->timecnt || 0 > transition1 || 0 > transition2 ||
  1688. (sp->ttis[transition1].tt_isdst == sp->ttis[transition2].tt_isdst)) {
  1689. *dst_enabled = 0;
  1690. *gmt_off = sp->ttis[sp->types[sp->timecnt -1]].tt_gmtoff;
  1691. } else {
  1692. /* I have valid daylight savings information. */
  1693. if(sp->ttis[transition2].tt_isdst)
  1694. *gmt_off = sp->ttis[transition1].tt_gmtoff;
  1695. else
  1696. *gmt_off = sp->ttis[transition2].tt_gmtoff;
  1697. /* If I adjusted the time earlier, indicate that the dst is invalid */
  1698. if (!bounds_exceeded) {
  1699. *dst_enabled = 1;
  1700. /* Determine which of the bounds is the start of daylight savings and which is the end */
  1701. if(sp->ttis[transition2].tt_isdst) {
  1702. *dst_start = sp->ats[i];
  1703. *dst_end = sp->ats[i -1];
  1704. } else {
  1705. *dst_start = sp->ats[i -1];
  1706. *dst_end = sp->ats[i];
  1707. }
  1708. }
  1709. }
  1710. return;
  1711. }
  1712. /*
  1713. ** gmtsub is to gmtime as localsub is to localtime.
  1714. */
  1715. static struct ast_tm *gmtsub(const struct timeval *timep, const long offset, struct ast_tm *tmp)
  1716. {
  1717. struct ast_tm * result;
  1718. struct state *sp;
  1719. AST_LIST_LOCK(&zonelist);
  1720. AST_LIST_TRAVERSE(&zonelist, sp, list) {
  1721. if (!strcmp(sp->name, "UTC"))
  1722. break;
  1723. }
  1724. if (!sp) {
  1725. if (!(sp = sstate_alloc())) {
  1726. AST_LIST_UNLOCK(&zonelist);
  1727. return NULL;
  1728. }
  1729. gmtload(sp);
  1730. AST_LIST_INSERT_TAIL(&zonelist, sp, list);
  1731. }
  1732. AST_LIST_UNLOCK(&zonelist);
  1733. result = timesub(timep, offset, sp, tmp);
  1734. #ifdef TM_ZONE
  1735. /*
  1736. ** Could get fancy here and deliver something such as
  1737. ** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
  1738. ** but this is no time for a treasure hunt.
  1739. */
  1740. if (offset != 0)
  1741. tmp->TM_ZONE = " ";
  1742. else
  1743. tmp->TM_ZONE = sp->chars;
  1744. #endif /* defined TM_ZONE */
  1745. return result;
  1746. }
  1747. /*! \brief
  1748. ** Return the number of leap years through the end of the given year
  1749. ** where, to make the math easy, the answer for year zero is defined as zero.
  1750. */
  1751. static int leaps_thru_end_of(const int y)
  1752. {
  1753. return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
  1754. -(leaps_thru_end_of(-(y + 1)) + 1);
  1755. }
  1756. static struct ast_tm *timesub(const struct timeval *timep, const long offset, const struct state *sp, struct ast_tm *tmp)
  1757. {
  1758. const struct lsinfo * lp;
  1759. time_t tdays;
  1760. int idays; /* unsigned would be so 2003 */
  1761. long rem;
  1762. int y;
  1763. const int * ip;
  1764. long corr;
  1765. int hit;
  1766. int i;
  1767. long seconds;
  1768. corr = 0;
  1769. hit = 0;
  1770. i = (sp == NULL) ? 0 : sp->leapcnt;
  1771. while (--i >= 0) {
  1772. lp = &sp->lsis[i];
  1773. if (timep->tv_sec >= lp->ls_trans) {
  1774. if (timep->tv_sec == lp->ls_trans) {
  1775. hit = ((i == 0 && lp->ls_corr > 0) ||
  1776. lp->ls_corr > sp->lsis[i - 1].ls_corr);
  1777. if (hit)
  1778. while (i > 0 &&
  1779. sp->lsis[i].ls_trans ==
  1780. sp->lsis[i - 1].ls_trans + 1 &&
  1781. sp->lsis[i].ls_corr ==
  1782. sp->lsis[i - 1].ls_corr + 1) {
  1783. ++hit;
  1784. --i;
  1785. }
  1786. }
  1787. corr = lp->ls_corr;
  1788. break;
  1789. }
  1790. }
  1791. y = EPOCH_YEAR;
  1792. tdays = timep->tv_sec / SECSPERDAY;
  1793. rem = timep->tv_sec - tdays * SECSPERDAY;
  1794. while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
  1795. int newy;
  1796. time_t tdelta;
  1797. int idelta;
  1798. int leapdays;
  1799. tdelta = tdays / DAYSPERLYEAR;
  1800. idelta = tdelta;
  1801. if (tdelta - idelta >= 1 || idelta - tdelta >= 1)
  1802. return NULL;
  1803. if (idelta == 0)
  1804. idelta = (tdays < 0) ? -1 : 1;
  1805. newy = y;
  1806. if (increment_overflow(&newy, idelta))
  1807. return NULL;
  1808. leapdays = leaps_thru_end_of(newy - 1) -
  1809. leaps_thru_end_of(y - 1);
  1810. tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
  1811. tdays -= leapdays;
  1812. y = newy;
  1813. }
  1814. seconds = tdays * SECSPERDAY + 0.5;
  1815. tdays = seconds / SECSPERDAY;
  1816. rem += seconds - tdays * SECSPERDAY;
  1817. /*
  1818. ** Given the range, we can now fearlessly cast...
  1819. */
  1820. idays = tdays;
  1821. rem += offset - corr;
  1822. while (rem < 0) {
  1823. rem += SECSPERDAY;
  1824. --idays;
  1825. }
  1826. while (rem >= SECSPERDAY) {
  1827. rem -= SECSPERDAY;
  1828. ++idays;
  1829. }
  1830. while (idays < 0) {
  1831. if (increment_overflow(&y, -1))
  1832. return NULL;
  1833. idays += year_lengths[isleap(y)];
  1834. }
  1835. while (idays >= year_lengths[isleap(y)]) {
  1836. idays -= year_lengths[isleap(y)];
  1837. if (increment_overflow(&y, 1))
  1838. return NULL;
  1839. }
  1840. tmp->tm_year = y;
  1841. if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
  1842. return NULL;
  1843. tmp->tm_yday = idays;
  1844. /*
  1845. ** The "extra" mods below avoid overflow problems.
  1846. */
  1847. tmp->tm_wday = EPOCH_WDAY +
  1848. ((y - EPOCH_YEAR) % DAYSPERWEEK) *
  1849. (DAYSPERNYEAR % DAYSPERWEEK) +
  1850. leaps_thru_end_of(y - 1) -
  1851. leaps_thru_end_of(EPOCH_YEAR - 1) +
  1852. idays;
  1853. tmp->tm_wday %= DAYSPERWEEK;
  1854. if (tmp->tm_wday < 0)
  1855. tmp->tm_wday += DAYSPERWEEK;
  1856. tmp->tm_hour = (int) (rem / SECSPERHOUR);
  1857. rem %= SECSPERHOUR;
  1858. tmp->tm_min = (int) (rem / SECSPERMIN);
  1859. /*
  1860. ** A positive leap second requires a special
  1861. ** representation. This uses "... ??:59:60" et seq.
  1862. */
  1863. tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
  1864. ip = mon_lengths[isleap(y)];
  1865. for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
  1866. idays -= ip[tmp->tm_mon];
  1867. tmp->tm_mday = (int) (idays + 1);
  1868. tmp->tm_isdst = 0;
  1869. #ifdef TM_GMTOFF
  1870. tmp->TM_GMTOFF = offset;
  1871. #endif /* defined TM_GMTOFF */
  1872. tmp->tm_usec = timep->tv_usec;
  1873. return tmp;
  1874. }
  1875. /*! \note
  1876. ** Adapted from code provided by Robert Elz, who writes:
  1877. ** The "best" way to do mktime I think is based on an idea of Bob
  1878. ** Kridle's (so its said...) from a long time ago.
  1879. ** It does a binary search of the time_t space. Since time_t's are
  1880. ** just 32 bits, its a max of 32 iterations (even at 64 bits it
  1881. ** would still be very reasonable).
  1882. */
  1883. /*! \brief
  1884. ** Simplified normalize logic courtesy Paul Eggert.
  1885. */
  1886. static int increment_overflow(int *number, int delta)
  1887. {
  1888. int number0;
  1889. number0 = *number;
  1890. *number += delta;
  1891. return (*number < number0) != (delta < 0);
  1892. }
  1893. static int long_increment_overflow(long *number, int delta)
  1894. {
  1895. long number0;
  1896. number0 = *number;
  1897. *number += delta;
  1898. return (*number < number0) != (delta < 0);
  1899. }
  1900. static int normalize_overflow(int *tensptr, int *unitsptr, const int base)
  1901. {
  1902. int tensdelta;
  1903. tensdelta = (*unitsptr >= 0) ?
  1904. (*unitsptr / base) :
  1905. (-1 - (-1 - *unitsptr) / base);
  1906. *unitsptr -= tensdelta * base;
  1907. return increment_overflow(tensptr, tensdelta);
  1908. }
  1909. static int long_normalize_overflow(long *tensptr, int *unitsptr, const int base)
  1910. {
  1911. int tensdelta;
  1912. tensdelta = (*unitsptr >= 0) ?
  1913. (*unitsptr / base) :
  1914. (-1 - (-1 - *unitsptr) / base);
  1915. *unitsptr -= tensdelta * base;
  1916. return long_increment_overflow(tensptr, tensdelta);
  1917. }
  1918. static int tmcomp(const struct ast_tm *atmp, const struct ast_tm *btmp)
  1919. {
  1920. int result;
  1921. if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
  1922. (result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
  1923. (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
  1924. (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
  1925. (result = (atmp->tm_min - btmp->tm_min)) == 0 &&
  1926. (result = (atmp->tm_sec - btmp->tm_sec)) == 0)
  1927. result = atmp->tm_usec - btmp->tm_usec;
  1928. return result;
  1929. }
  1930. 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)
  1931. {
  1932. int dir;
  1933. int i, j;
  1934. int saved_seconds;
  1935. long li;
  1936. time_t lo;
  1937. time_t hi;
  1938. long y;
  1939. struct timeval newt = { 0, 0 };
  1940. struct timeval t = { 0, 0 };
  1941. struct ast_tm yourtm, mytm;
  1942. *okayp = FALSE;
  1943. yourtm = *tmp;
  1944. if (do_norm_secs) {
  1945. if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
  1946. SECSPERMIN))
  1947. return WRONG;
  1948. }
  1949. if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
  1950. return WRONG;
  1951. if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
  1952. return WRONG;
  1953. y = yourtm.tm_year;
  1954. if (long_normalize_overflow(&y, &yourtm.tm_mon, MONSPERYEAR))
  1955. return WRONG;
  1956. /*
  1957. ** Turn y into an actual year number for now.
  1958. ** It is converted back to an offset from TM_YEAR_BASE later.
  1959. */
  1960. if (long_increment_overflow(&y, TM_YEAR_BASE))
  1961. return WRONG;
  1962. while (yourtm.tm_mday <= 0) {
  1963. if (long_increment_overflow(&y, -1))
  1964. return WRONG;
  1965. li = y + (1 < yourtm.tm_mon);
  1966. yourtm.tm_mday += year_lengths[isleap(li)];
  1967. }
  1968. while (yourtm.tm_mday > DAYSPERLYEAR) {
  1969. li = y + (1 < yourtm.tm_mon);
  1970. yourtm.tm_mday -= year_lengths[isleap(li)];
  1971. if (long_increment_overflow(&y, 1))
  1972. return WRONG;
  1973. }
  1974. for ( ; ; ) {
  1975. i = mon_lengths[isleap(y)][yourtm.tm_mon];
  1976. if (yourtm.tm_mday <= i)
  1977. break;
  1978. yourtm.tm_mday -= i;
  1979. if (++yourtm.tm_mon >= MONSPERYEAR) {
  1980. yourtm.tm_mon = 0;
  1981. if (long_increment_overflow(&y, 1))
  1982. return WRONG;
  1983. }
  1984. }
  1985. if (long_increment_overflow(&y, -TM_YEAR_BASE))
  1986. return WRONG;
  1987. yourtm.tm_year = y;
  1988. if (yourtm.tm_year != y)
  1989. return WRONG;
  1990. if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
  1991. saved_seconds = 0;
  1992. else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
  1993. /*
  1994. ** We can't set tm_sec to 0, because that might push the
  1995. ** time below the minimum representable time.
  1996. ** Set tm_sec to 59 instead.
  1997. ** This assumes that the minimum representable time is
  1998. ** not in the same minute that a leap second was deleted from,
  1999. ** which is a safer assumption than using 58 would be.
  2000. */
  2001. if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
  2002. return WRONG;
  2003. saved_seconds = yourtm.tm_sec;
  2004. yourtm.tm_sec = SECSPERMIN - 1;
  2005. } else {
  2006. saved_seconds = yourtm.tm_sec;
  2007. yourtm.tm_sec = 0;
  2008. }
  2009. /*
  2010. ** Do a binary search (this works whatever time_t's type is).
  2011. */
  2012. if (!TYPE_SIGNED(time_t)) {
  2013. lo = 0;
  2014. hi = lo - 1;
  2015. } else if (!TYPE_INTEGRAL(time_t)) {
  2016. if (sizeof(time_t) > sizeof(float))
  2017. hi = (time_t) DBL_MAX;
  2018. else hi = (time_t) FLT_MAX;
  2019. lo = -hi;
  2020. } else {
  2021. lo = 1;
  2022. for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
  2023. lo *= 2;
  2024. hi = -(lo + 1);
  2025. }
  2026. for ( ; ; ) {
  2027. t.tv_sec = lo / 2 + hi / 2;
  2028. if (t.tv_sec < lo)
  2029. t.tv_sec = lo;
  2030. else if (t.tv_sec > hi)
  2031. t.tv_sec = hi;
  2032. if ((*funcp)(&t, offset, &mytm, sp) == NULL) {
  2033. /*
  2034. ** Assume that t is too extreme to be represented in
  2035. ** a struct ast_tm; arrange things so that it is less
  2036. ** extreme on the next pass.
  2037. */
  2038. dir = (t.tv_sec > 0) ? 1 : -1;
  2039. } else dir = tmcomp(&mytm, &yourtm);
  2040. if (dir != 0) {
  2041. if (t.tv_sec == lo) {
  2042. ++t.tv_sec;
  2043. if (t.tv_sec <= lo)
  2044. return WRONG;
  2045. ++lo;
  2046. } else if (t.tv_sec == hi) {
  2047. --t.tv_sec;
  2048. if (t.tv_sec >= hi)
  2049. return WRONG;
  2050. --hi;
  2051. }
  2052. if (lo > hi)
  2053. return WRONG;
  2054. if (dir > 0)
  2055. hi = t.tv_sec;
  2056. else lo = t.tv_sec;
  2057. continue;
  2058. }
  2059. if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
  2060. break;
  2061. /*
  2062. ** Right time, wrong type.
  2063. ** Hunt for right time, right type.
  2064. ** It's okay to guess wrong since the guess
  2065. ** gets checked.
  2066. */
  2067. /*
  2068. ** The (void *) casts are the benefit of SunOS 3.3 on Sun 2's.
  2069. */
  2070. for (i = sp->typecnt - 1; i >= 0; --i) {
  2071. if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
  2072. continue;
  2073. for (j = sp->typecnt - 1; j >= 0; --j) {
  2074. if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
  2075. continue;
  2076. newt.tv_sec = t.tv_sec + sp->ttis[j].tt_gmtoff -
  2077. sp->ttis[i].tt_gmtoff;
  2078. if ((*funcp)(&newt, offset, &mytm, sp) == NULL)
  2079. continue;
  2080. if (tmcomp(&mytm, &yourtm) != 0)
  2081. continue;
  2082. if (mytm.tm_isdst != yourtm.tm_isdst)
  2083. continue;
  2084. /*
  2085. ** We have a match.
  2086. */
  2087. t = newt;
  2088. goto label;
  2089. }
  2090. }
  2091. return WRONG;
  2092. }
  2093. label:
  2094. newt.tv_sec = t.tv_sec + saved_seconds;
  2095. if ((newt.tv_sec < t.tv_sec) != (saved_seconds < 0))
  2096. return WRONG;
  2097. t.tv_sec = newt.tv_sec;
  2098. if ((*funcp)(&t, offset, tmp, sp))
  2099. *okayp = TRUE;
  2100. return t;
  2101. }
  2102. 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)
  2103. {
  2104. struct timeval t;
  2105. /*! \note
  2106. ** First try without normalization of seconds
  2107. ** (in case tm_sec contains a value associated with a leap second).
  2108. ** If that fails, try with normalization of seconds.
  2109. */
  2110. t = time2sub(tmp, funcp, offset, okayp, FALSE, sp);
  2111. return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE, sp);
  2112. }
  2113. 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)
  2114. {
  2115. struct timeval t;
  2116. int samei, otheri;
  2117. int sameind, otherind;
  2118. int i;
  2119. int nseen;
  2120. int seen[TZ_MAX_TYPES];
  2121. int types[TZ_MAX_TYPES];
  2122. int okay;
  2123. if (tmp->tm_isdst > 1)
  2124. tmp->tm_isdst = 1;
  2125. t = time2(tmp, funcp, offset, &okay, sp);
  2126. #ifdef PCTS
  2127. /*
  2128. ** PCTS code courtesy Grant Sullivan.
  2129. */
  2130. if (okay)
  2131. return t;
  2132. if (tmp->tm_isdst < 0)
  2133. tmp->tm_isdst = 0; /* reset to std and try again */
  2134. #endif /* defined PCTS */
  2135. #ifndef PCTS
  2136. if (okay || tmp->tm_isdst < 0)
  2137. return t;
  2138. #endif /* !defined PCTS */
  2139. /*
  2140. ** We're supposed to assume that somebody took a time of one type
  2141. ** and did some math on it that yielded a "struct ast_tm" that's bad.
  2142. ** We try to divine the type they started from and adjust to the
  2143. ** type they need.
  2144. */
  2145. if (sp == NULL)
  2146. return WRONG;
  2147. for (i = 0; i < sp->typecnt; ++i)
  2148. seen[i] = FALSE;
  2149. nseen = 0;
  2150. for (i = sp->timecnt - 1; i >= 0; --i)
  2151. if (!seen[sp->types[i]]) {
  2152. seen[sp->types[i]] = TRUE;
  2153. types[nseen++] = sp->types[i];
  2154. }
  2155. for (sameind = 0; sameind < nseen; ++sameind) {
  2156. samei = types[sameind];
  2157. if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
  2158. continue;
  2159. for (otherind = 0; otherind < nseen; ++otherind) {
  2160. otheri = types[otherind];
  2161. if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
  2162. continue;
  2163. tmp->tm_sec += sp->ttis[otheri].tt_gmtoff -
  2164. sp->ttis[samei].tt_gmtoff;
  2165. tmp->tm_isdst = !tmp->tm_isdst;
  2166. t = time2(tmp, funcp, offset, &okay, sp);
  2167. if (okay)
  2168. return t;
  2169. tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff -
  2170. sp->ttis[samei].tt_gmtoff;
  2171. tmp->tm_isdst = !tmp->tm_isdst;
  2172. }
  2173. }
  2174. return WRONG;
  2175. }
  2176. struct timeval ast_mktime(struct ast_tm *tmp, const char *zone)
  2177. {
  2178. const struct state *sp;
  2179. if (!(sp = ast_tzset(zone)))
  2180. return WRONG;
  2181. return time1(tmp, localsub, 0L, sp);
  2182. }
  2183. #ifdef HAVE_NEWLOCALE
  2184. static struct locale_entry *find_by_locale(locale_t locale)
  2185. {
  2186. struct locale_entry *cur;
  2187. AST_LIST_TRAVERSE(&localelist, cur, list) {
  2188. if (locale == cur->locale) {
  2189. return cur;
  2190. }
  2191. }
  2192. return NULL;
  2193. }
  2194. static struct locale_entry *find_by_name(const char *name)
  2195. {
  2196. struct locale_entry *cur;
  2197. AST_LIST_TRAVERSE(&localelist, cur, list) {
  2198. if (strcmp(name, cur->name) == 0) {
  2199. return cur;
  2200. }
  2201. }
  2202. return NULL;
  2203. }
  2204. static const char *store_by_locale(locale_t prevlocale)
  2205. {
  2206. struct locale_entry *cur;
  2207. if (prevlocale == LC_GLOBAL_LOCALE) {
  2208. return NULL;
  2209. } else {
  2210. /* Get a handle for this entry, if any */
  2211. if ((cur = find_by_locale(prevlocale))) {
  2212. return cur->name;
  2213. } else {
  2214. /* Create an entry, so it can be restored later */
  2215. int x;
  2216. cur = NULL;
  2217. AST_LIST_LOCK(&localelist);
  2218. for (x = 0; x < 10000; x++) {
  2219. char name[5];
  2220. snprintf(name, sizeof(name), "%04d", x);
  2221. if (!find_by_name(name)) {
  2222. if ((cur = ast_calloc(1, sizeof(*cur) + strlen(name) + 1))) {
  2223. cur->locale = prevlocale;
  2224. strcpy(cur->name, name); /* SAFE */
  2225. AST_LIST_INSERT_TAIL(&localelist, cur, list);
  2226. }
  2227. break;
  2228. }
  2229. }
  2230. AST_LIST_UNLOCK(&localelist);
  2231. return cur ? cur->name : NULL;
  2232. }
  2233. }
  2234. }
  2235. const char *ast_setlocale(const char *locale)
  2236. {
  2237. struct locale_entry *cur;
  2238. locale_t prevlocale = LC_GLOBAL_LOCALE;
  2239. if (locale == NULL) {
  2240. return store_by_locale(uselocale(LC_GLOBAL_LOCALE));
  2241. }
  2242. AST_LIST_LOCK(&localelist);
  2243. if ((cur = find_by_name(locale))) {
  2244. prevlocale = uselocale(cur->locale);
  2245. }
  2246. if (!cur) {
  2247. if ((cur = ast_calloc(1, sizeof(*cur) + strlen(locale) + 1))) {
  2248. cur->locale = newlocale(LC_ALL_MASK, locale, NULL);
  2249. strcpy(cur->name, locale); /* SAFE */
  2250. AST_LIST_INSERT_TAIL(&localelist, cur, list);
  2251. prevlocale = uselocale(cur->locale);
  2252. }
  2253. }
  2254. AST_LIST_UNLOCK(&localelist);
  2255. return store_by_locale(prevlocale);
  2256. }
  2257. #else
  2258. const char *ast_setlocale(const char *unused)
  2259. {
  2260. return NULL;
  2261. }
  2262. #endif
  2263. int ast_strftime_locale(char *buf, size_t len, const char *tmp, const struct ast_tm *tm, const char *locale)
  2264. {
  2265. size_t fmtlen = strlen(tmp) + 1;
  2266. char *format = ast_calloc(1, fmtlen), *fptr = format, *newfmt;
  2267. int decimals = -1, i, res;
  2268. long fraction;
  2269. const char *prevlocale;
  2270. buf[0] = '\0';/* Ensure the buffer is initialized. */
  2271. if (!format) {
  2272. return -1;
  2273. }
  2274. for (; *tmp; tmp++) {
  2275. if (*tmp == '%') {
  2276. switch (tmp[1]) {
  2277. case '1':
  2278. case '2':
  2279. case '3':
  2280. case '4':
  2281. case '5':
  2282. case '6':
  2283. if (tmp[2] != 'q') {
  2284. goto defcase;
  2285. }
  2286. decimals = tmp[1] - '0';
  2287. tmp++;
  2288. /* Fall through */
  2289. case 'q': /* Milliseconds */
  2290. if (decimals == -1) {
  2291. decimals = 3;
  2292. }
  2293. /* Juggle some memory to fit the item */
  2294. newfmt = ast_realloc(format, fmtlen + decimals);
  2295. if (!newfmt) {
  2296. ast_free(format);
  2297. return -1;
  2298. }
  2299. fptr = fptr - format + newfmt;
  2300. format = newfmt;
  2301. fmtlen += decimals;
  2302. /* Reduce the fraction of time to the accuracy needed */
  2303. for (i = 6, fraction = tm->tm_usec; i > decimals; i--) {
  2304. fraction /= 10;
  2305. }
  2306. fptr += sprintf(fptr, "%0*ld", decimals, fraction);
  2307. /* Reset, in case more than one 'q' specifier exists */
  2308. decimals = -1;
  2309. tmp++;
  2310. break;
  2311. default:
  2312. goto defcase;
  2313. }
  2314. } else {
  2315. defcase: *fptr++ = *tmp;
  2316. }
  2317. }
  2318. *fptr = '\0';
  2319. #undef strftime
  2320. if (locale) {
  2321. prevlocale = ast_setlocale(locale);
  2322. }
  2323. res = (int)strftime(buf, len, format, (struct tm *)tm);
  2324. if (locale) {
  2325. ast_setlocale(prevlocale);
  2326. }
  2327. ast_free(format);
  2328. return res;
  2329. }
  2330. int ast_strftime(char *buf, size_t len, const char *tmp, const struct ast_tm *tm)
  2331. {
  2332. return ast_strftime_locale(buf, len, tmp, tm, NULL);
  2333. }
  2334. char *ast_strptime_locale(const char *s, const char *format, struct ast_tm *tm, const char *locale)
  2335. {
  2336. struct tm tm2 = { 0, };
  2337. char *res;
  2338. const char *prevlocale;
  2339. prevlocale = ast_setlocale(locale);
  2340. res = strptime(s, format, &tm2);
  2341. ast_setlocale(prevlocale);
  2342. /* ast_time and tm are not the same size - tm is a subset of
  2343. * ast_time. Hence, the size of tm needs to be used for the
  2344. * memcpy
  2345. */
  2346. memcpy(tm, &tm2, sizeof(tm2));
  2347. tm->tm_usec = 0;
  2348. /* strptime(3) doesn't set .tm_isdst correctly, so to force ast_mktime(3)
  2349. * to deal with it correctly, we set it to -1. */
  2350. tm->tm_isdst = -1;
  2351. return res;
  2352. }
  2353. char *ast_strptime(const char *s, const char *format, struct ast_tm *tm)
  2354. {
  2355. return ast_strptime_locale(s, format, tm, NULL);
  2356. }