localtime.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499
  1. /* Convert timestamp from time_t to struct tm. */
  2. /*
  3. ** This file is in the public domain, so clarified as of
  4. ** 1996-06-05 by Arthur David Olson.
  5. */
  6. /*
  7. ** Leap second handling from Bradley White.
  8. ** POSIX-style TZ environment variable handling from Guy Harris.
  9. */
  10. /*LINTLIBRARY*/
  11. #define LOCALTIME_IMPLEMENTATION
  12. #include "private.h"
  13. #include "tzfile.h"
  14. #include <fcntl.h>
  15. #if defined THREAD_SAFE && THREAD_SAFE
  16. # include <pthread.h>
  17. static pthread_mutex_t locallock = PTHREAD_MUTEX_INITIALIZER;
  18. static int lock(void) { return pthread_mutex_lock(&locallock); }
  19. static void unlock(void) { pthread_mutex_unlock(&locallock); }
  20. #else
  21. static int lock(void) { return 0; }
  22. static void unlock(void) { }
  23. #endif
  24. #ifndef TZ_ABBR_CHAR_SET
  25. # define TZ_ABBR_CHAR_SET \
  26. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
  27. #endif /* !defined TZ_ABBR_CHAR_SET */
  28. #ifndef TZ_ABBR_ERR_CHAR
  29. # define TZ_ABBR_ERR_CHAR '_'
  30. #endif /* !defined TZ_ABBR_ERR_CHAR */
  31. /*
  32. ** Support non-POSIX platforms that distinguish between text and binary files.
  33. */
  34. #ifndef O_BINARY
  35. # define O_BINARY 0
  36. #endif
  37. #ifndef WILDABBR
  38. /*
  39. ** Someone might make incorrect use of a time zone abbreviation:
  40. ** 1. They might reference tzname[0] before calling tzset (explicitly
  41. ** or implicitly).
  42. ** 2. They might reference tzname[1] before calling tzset (explicitly
  43. ** or implicitly).
  44. ** 3. They might reference tzname[1] after setting to a time zone
  45. ** in which Daylight Saving Time is never observed.
  46. ** 4. They might reference tzname[0] after setting to a time zone
  47. ** in which Standard Time is never observed.
  48. ** 5. They might reference tm.TM_ZONE after calling offtime.
  49. ** What's best to do in the above cases is open to debate;
  50. ** for now, we just set things up so that in any of the five cases
  51. ** WILDABBR is used. Another possibility: initialize tzname[0] to the
  52. ** string "tzname[0] used before set", and similarly for the other cases.
  53. ** And another: initialize tzname[0] to "ERA", with an explanation in the
  54. ** manual page of what this "time zone abbreviation" means (doing this so
  55. ** that tzname[0] has the "normal" length of three characters).
  56. */
  57. # define WILDABBR " "
  58. #endif /* !defined WILDABBR */
  59. static const char wildabbr[] = WILDABBR;
  60. static char const etc_utc[] = "Etc/UTC";
  61. static char const *utc = etc_utc + sizeof "Etc/" - 1;
  62. /*
  63. ** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
  64. ** Default to US rules as of 2017-05-07.
  65. ** POSIX does not specify the default DST rules;
  66. ** for historical reasons, US rules are a common default.
  67. */
  68. #ifndef TZDEFRULESTRING
  69. # define TZDEFRULESTRING ",M3.2.0,M11.1.0"
  70. #endif
  71. struct ttinfo { /* time type information */
  72. int_fast32_t tt_utoff; /* UT offset in seconds */
  73. bool tt_isdst; /* used to set tm_isdst */
  74. int tt_desigidx; /* abbreviation list index */
  75. bool tt_ttisstd; /* transition is std time */
  76. bool tt_ttisut; /* transition is UT */
  77. };
  78. struct lsinfo { /* leap second information */
  79. time_t ls_trans; /* transition time */
  80. int_fast32_t ls_corr; /* correction to apply */
  81. };
  82. /* This abbreviation means local time is unspecified. */
  83. static char const UNSPEC[] = "-00";
  84. /* How many extra bytes are needed at the end of struct state's chars array.
  85. This needs to be at least 1 for null termination in case the input
  86. data isn't properly terminated, and it also needs to be big enough
  87. for ttunspecified to work without crashing. */
  88. enum { CHARS_EXTRA = max(sizeof UNSPEC, 2) - 1 };
  89. /* Limit to time zone abbreviation length in POSIX-style TZ strings.
  90. This is distinct from TZ_MAX_CHARS, which limits TZif file contents. */
  91. #ifndef TZNAME_MAXIMUM
  92. # define TZNAME_MAXIMUM 255
  93. #endif
  94. struct state {
  95. int leapcnt;
  96. int timecnt;
  97. int typecnt;
  98. int charcnt;
  99. bool goback;
  100. bool goahead;
  101. time_t ats[TZ_MAX_TIMES];
  102. unsigned char types[TZ_MAX_TIMES];
  103. struct ttinfo ttis[TZ_MAX_TYPES];
  104. char chars[max(max(TZ_MAX_CHARS + CHARS_EXTRA, sizeof "UTC"),
  105. 2 * (TZNAME_MAXIMUM + 1))];
  106. struct lsinfo lsis[TZ_MAX_LEAPS];
  107. /* The time type to use for early times or if no transitions.
  108. It is always zero for recent tzdb releases.
  109. It might be nonzero for data from tzdb 2018e or earlier. */
  110. int defaulttype;
  111. };
  112. enum r_type {
  113. JULIAN_DAY, /* Jn = Julian day */
  114. DAY_OF_YEAR, /* n = day of year */
  115. MONTH_NTH_DAY_OF_WEEK /* Mm.n.d = month, week, day of week */
  116. };
  117. struct rule {
  118. enum r_type r_type; /* type of rule */
  119. int r_day; /* day number of rule */
  120. int r_week; /* week number of rule */
  121. int r_mon; /* month number of rule */
  122. int_fast32_t r_time; /* transition time of rule */
  123. };
  124. static struct tm *gmtsub(struct state const *, time_t const *, int_fast32_t,
  125. struct tm *);
  126. static bool increment_overflow(int *, int);
  127. static bool increment_overflow_time(time_t *, int_fast32_t);
  128. static int_fast32_t leapcorr(struct state const *, time_t);
  129. static bool normalize_overflow32(int_fast32_t *, int *, int);
  130. static struct tm *timesub(time_t const *, int_fast32_t, struct state const *,
  131. struct tm *);
  132. static bool typesequiv(struct state const *, int, int);
  133. static bool tzparse(char const *, struct state *, struct state *);
  134. #ifdef ALL_STATE
  135. static struct state * lclptr;
  136. static struct state * gmtptr;
  137. #endif /* defined ALL_STATE */
  138. #ifndef ALL_STATE
  139. static struct state lclmem;
  140. static struct state gmtmem;
  141. static struct state *const lclptr = &lclmem;
  142. static struct state *const gmtptr = &gmtmem;
  143. #endif /* State Farm */
  144. #ifndef TZ_STRLEN_MAX
  145. # define TZ_STRLEN_MAX 255
  146. #endif /* !defined TZ_STRLEN_MAX */
  147. static char lcl_TZname[TZ_STRLEN_MAX + 1];
  148. static int lcl_is_set;
  149. /*
  150. ** Section 4.12.3 of X3.159-1989 requires that
  151. ** Except for the strftime function, these functions [asctime,
  152. ** ctime, gmtime, localtime] return values in one of two static
  153. ** objects: a broken-down time structure and an array of char.
  154. ** Thanks to Paul Eggert for noting this.
  155. **
  156. ** This requirement was removed in C99, so support it only if requested,
  157. ** as support is more likely to lead to bugs in badly written programs.
  158. */
  159. #if SUPPORT_C89
  160. static struct tm tm;
  161. #endif
  162. #if 2 <= HAVE_TZNAME + TZ_TIME_T
  163. char * tzname[2] = {
  164. (char *) wildabbr,
  165. (char *) wildabbr
  166. };
  167. #endif
  168. #if 2 <= USG_COMPAT + TZ_TIME_T
  169. long timezone;
  170. int daylight;
  171. #endif
  172. #if 2 <= ALTZONE + TZ_TIME_T
  173. long altzone;
  174. #endif
  175. /* Initialize *S to a value based on UTOFF, ISDST, and DESIGIDX. */
  176. static void
  177. init_ttinfo(struct ttinfo *s, int_fast32_t utoff, bool isdst, int desigidx)
  178. {
  179. s->tt_utoff = utoff;
  180. s->tt_isdst = isdst;
  181. s->tt_desigidx = desigidx;
  182. s->tt_ttisstd = false;
  183. s->tt_ttisut = false;
  184. }
  185. /* Return true if SP's time type I does not specify local time. */
  186. static bool
  187. ttunspecified(struct state const *sp, int i)
  188. {
  189. char const *abbr = &sp->chars[sp->ttis[i].tt_desigidx];
  190. /* memcmp is likely faster than strcmp, and is safe due to CHARS_EXTRA. */
  191. return memcmp(abbr, UNSPEC, sizeof UNSPEC) == 0;
  192. }
  193. static int_fast32_t
  194. detzcode(const char *const codep)
  195. {
  196. register int_fast32_t result;
  197. register int i;
  198. int_fast32_t one = 1;
  199. int_fast32_t halfmaxval = one << (32 - 2);
  200. int_fast32_t maxval = halfmaxval - 1 + halfmaxval;
  201. int_fast32_t minval = -1 - maxval;
  202. result = codep[0] & 0x7f;
  203. for (i = 1; i < 4; ++i)
  204. result = (result << 8) | (codep[i] & 0xff);
  205. if (codep[0] & 0x80) {
  206. /* Do two's-complement negation even on non-two's-complement machines.
  207. If the result would be minval - 1, return minval. */
  208. result -= !TWOS_COMPLEMENT(int_fast32_t) && result != 0;
  209. result += minval;
  210. }
  211. return result;
  212. }
  213. static int_fast64_t
  214. detzcode64(const char *const codep)
  215. {
  216. register int_fast64_t result;
  217. register int i;
  218. int_fast64_t one = 1;
  219. int_fast64_t halfmaxval = one << (64 - 2);
  220. int_fast64_t maxval = halfmaxval - 1 + halfmaxval;
  221. int_fast64_t minval = -TWOS_COMPLEMENT(int_fast64_t) - maxval;
  222. result = codep[0] & 0x7f;
  223. for (i = 1; i < 8; ++i)
  224. result = (result << 8) | (codep[i] & 0xff);
  225. if (codep[0] & 0x80) {
  226. /* Do two's-complement negation even on non-two's-complement machines.
  227. If the result would be minval - 1, return minval. */
  228. result -= !TWOS_COMPLEMENT(int_fast64_t) && result != 0;
  229. result += minval;
  230. }
  231. return result;
  232. }
  233. static void
  234. update_tzname_etc(struct state const *sp, struct ttinfo const *ttisp)
  235. {
  236. #if HAVE_TZNAME
  237. tzname[ttisp->tt_isdst] = (char *) &sp->chars[ttisp->tt_desigidx];
  238. #endif
  239. #if USG_COMPAT
  240. if (!ttisp->tt_isdst)
  241. timezone = - ttisp->tt_utoff;
  242. #endif
  243. #if ALTZONE
  244. if (ttisp->tt_isdst)
  245. altzone = - ttisp->tt_utoff;
  246. #endif
  247. }
  248. /* If STDDST_MASK indicates that SP's TYPE provides useful info,
  249. update tzname, timezone, and/or altzone and return STDDST_MASK,
  250. diminished by the provided info if it is a specified local time.
  251. Otherwise, return STDDST_MASK. See settzname for STDDST_MASK. */
  252. static int
  253. may_update_tzname_etc(int stddst_mask, struct state *sp, int type)
  254. {
  255. struct ttinfo *ttisp = &sp->ttis[type];
  256. int this_bit = 1 << ttisp->tt_isdst;
  257. if (stddst_mask & this_bit) {
  258. update_tzname_etc(sp, ttisp);
  259. if (!ttunspecified(sp, type))
  260. return stddst_mask & ~this_bit;
  261. }
  262. return stddst_mask;
  263. }
  264. static void
  265. settzname(void)
  266. {
  267. register struct state * const sp = lclptr;
  268. register int i;
  269. /* If STDDST_MASK & 1 we need info about a standard time.
  270. If STDDST_MASK & 2 we need info about a daylight saving time.
  271. When STDDST_MASK becomes zero we can stop looking. */
  272. int stddst_mask = 0;
  273. #if HAVE_TZNAME
  274. tzname[0] = tzname[1] = (char *) (sp ? wildabbr : utc);
  275. stddst_mask = 3;
  276. #endif
  277. #if USG_COMPAT
  278. timezone = 0;
  279. stddst_mask = 3;
  280. #endif
  281. #if ALTZONE
  282. altzone = 0;
  283. stddst_mask |= 2;
  284. #endif
  285. /*
  286. ** And to get the latest time zone abbreviations into tzname. . .
  287. */
  288. if (sp) {
  289. for (i = sp->timecnt - 1; stddst_mask && 0 <= i; i--)
  290. stddst_mask = may_update_tzname_etc(stddst_mask, sp, sp->types[i]);
  291. for (i = sp->typecnt - 1; stddst_mask && 0 <= i; i--)
  292. stddst_mask = may_update_tzname_etc(stddst_mask, sp, i);
  293. }
  294. #if USG_COMPAT
  295. daylight = stddst_mask >> 1 ^ 1;
  296. #endif
  297. }
  298. /* Replace bogus characters in time zone abbreviations.
  299. Return 0 on success, an errno value if a time zone abbreviation is
  300. too long. */
  301. static int
  302. scrub_abbrs(struct state *sp)
  303. {
  304. int i;
  305. /* Reject overlong abbreviations. */
  306. for (i = 0; i < sp->charcnt - (TZNAME_MAXIMUM + 1); ) {
  307. int len = strlen(&sp->chars[i]);
  308. if (TZNAME_MAXIMUM < len)
  309. return EOVERFLOW;
  310. i += len + 1;
  311. }
  312. /* Replace bogus characters. */
  313. for (i = 0; i < sp->charcnt; ++i)
  314. if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
  315. sp->chars[i] = TZ_ABBR_ERR_CHAR;
  316. return 0;
  317. }
  318. /* Input buffer for data read from a compiled tz file. */
  319. union input_buffer {
  320. /* The first part of the buffer, interpreted as a header. */
  321. struct tzhead tzhead;
  322. /* The entire buffer. */
  323. char buf[2 * sizeof(struct tzhead) + 2 * sizeof(struct state)
  324. + 4 * TZ_MAX_TIMES];
  325. };
  326. /* TZDIR with a trailing '/' rather than a trailing '\0'. */
  327. static char const tzdirslash[sizeof TZDIR] = TZDIR "/";
  328. /* Local storage needed for 'tzloadbody'. */
  329. union local_storage {
  330. /* The results of analyzing the file's contents after it is opened. */
  331. struct file_analysis {
  332. /* The input buffer. */
  333. union input_buffer u;
  334. /* A temporary state used for parsing a TZ string in the file. */
  335. struct state st;
  336. } u;
  337. /* The file name to be opened. */
  338. char fullname[max(sizeof(struct file_analysis), sizeof tzdirslash + 1024)];
  339. };
  340. /* Load tz data from the file named NAME into *SP. Read extended
  341. format if DOEXTEND. Use *LSP for temporary storage. Return 0 on
  342. success, an errno value on failure. */
  343. static int
  344. tzloadbody(char const *name, struct state *sp, bool doextend,
  345. union local_storage *lsp)
  346. {
  347. register int i;
  348. register int fid;
  349. register int stored;
  350. register ssize_t nread;
  351. register bool doaccess;
  352. register union input_buffer *up = &lsp->u.u;
  353. register int tzheadsize = sizeof(struct tzhead);
  354. sp->goback = sp->goahead = false;
  355. if (! name) {
  356. name = TZDEFAULT;
  357. if (! name)
  358. return EINVAL;
  359. }
  360. if (name[0] == ':')
  361. ++name;
  362. #ifdef SUPPRESS_TZDIR
  363. /* Do not prepend TZDIR. This is intended for specialized
  364. applications only, due to its security implications. */
  365. doaccess = true;
  366. #else
  367. doaccess = name[0] == '/';
  368. #endif
  369. if (!doaccess) {
  370. char const *dot;
  371. if (sizeof lsp->fullname - sizeof tzdirslash <= strlen(name))
  372. return ENAMETOOLONG;
  373. /* Create a string "TZDIR/NAME". Using sprintf here
  374. would pull in stdio (and would fail if the
  375. resulting string length exceeded INT_MAX!). */
  376. memcpy(lsp->fullname, tzdirslash, sizeof tzdirslash);
  377. strcpy(lsp->fullname + sizeof tzdirslash, name);
  378. /* Set doaccess if NAME contains a ".." file name
  379. component, as such a name could read a file outside
  380. the TZDIR virtual subtree. */
  381. for (dot = name; (dot = strchr(dot, '.')); dot++)
  382. if ((dot == name || dot[-1] == '/') && dot[1] == '.'
  383. && (dot[2] == '/' || !dot[2])) {
  384. doaccess = true;
  385. break;
  386. }
  387. name = lsp->fullname;
  388. }
  389. if (doaccess && access(name, R_OK) != 0)
  390. return errno;
  391. fid = open(name, O_RDONLY | O_BINARY);
  392. if (fid < 0)
  393. return errno;
  394. nread = read(fid, up->buf, sizeof up->buf);
  395. if (nread < tzheadsize) {
  396. int err = nread < 0 ? errno : EINVAL;
  397. close(fid);
  398. return err;
  399. }
  400. if (close(fid) < 0)
  401. return errno;
  402. for (stored = 4; stored <= 8; stored *= 2) {
  403. char version = up->tzhead.tzh_version[0];
  404. bool skip_datablock = stored == 4 && version;
  405. int_fast32_t datablock_size;
  406. int_fast32_t ttisstdcnt = detzcode(up->tzhead.tzh_ttisstdcnt);
  407. int_fast32_t ttisutcnt = detzcode(up->tzhead.tzh_ttisutcnt);
  408. int_fast64_t prevtr = -1;
  409. int_fast32_t prevcorr;
  410. int_fast32_t leapcnt = detzcode(up->tzhead.tzh_leapcnt);
  411. int_fast32_t timecnt = detzcode(up->tzhead.tzh_timecnt);
  412. int_fast32_t typecnt = detzcode(up->tzhead.tzh_typecnt);
  413. int_fast32_t charcnt = detzcode(up->tzhead.tzh_charcnt);
  414. char const *p = up->buf + tzheadsize;
  415. /* Although tzfile(5) currently requires typecnt to be nonzero,
  416. support future formats that may allow zero typecnt
  417. in files that have a TZ string and no transitions. */
  418. if (! (0 <= leapcnt && leapcnt < TZ_MAX_LEAPS
  419. && 0 <= typecnt && typecnt < TZ_MAX_TYPES
  420. && 0 <= timecnt && timecnt < TZ_MAX_TIMES
  421. && 0 <= charcnt && charcnt < TZ_MAX_CHARS
  422. && 0 <= ttisstdcnt && ttisstdcnt < TZ_MAX_TYPES
  423. && 0 <= ttisutcnt && ttisutcnt < TZ_MAX_TYPES))
  424. return EINVAL;
  425. datablock_size
  426. = (timecnt * stored /* ats */
  427. + timecnt /* types */
  428. + typecnt * 6 /* ttinfos */
  429. + charcnt /* chars */
  430. + leapcnt * (stored + 4) /* lsinfos */
  431. + ttisstdcnt /* ttisstds */
  432. + ttisutcnt); /* ttisuts */
  433. if (nread < tzheadsize + datablock_size)
  434. return EINVAL;
  435. if (skip_datablock)
  436. p += datablock_size;
  437. else {
  438. if (! ((ttisstdcnt == typecnt || ttisstdcnt == 0)
  439. && (ttisutcnt == typecnt || ttisutcnt == 0)))
  440. return EINVAL;
  441. sp->leapcnt = leapcnt;
  442. sp->timecnt = timecnt;
  443. sp->typecnt = typecnt;
  444. sp->charcnt = charcnt;
  445. /* Read transitions, discarding those out of time_t range.
  446. But pretend the last transition before TIME_T_MIN
  447. occurred at TIME_T_MIN. */
  448. timecnt = 0;
  449. for (i = 0; i < sp->timecnt; ++i) {
  450. int_fast64_t at
  451. = stored == 4 ? detzcode(p) : detzcode64(p);
  452. sp->types[i] = at <= TIME_T_MAX;
  453. if (sp->types[i]) {
  454. time_t attime
  455. = ((TYPE_SIGNED(time_t) ? at < TIME_T_MIN : at < 0)
  456. ? TIME_T_MIN : at);
  457. if (timecnt && attime <= sp->ats[timecnt - 1]) {
  458. if (attime < sp->ats[timecnt - 1])
  459. return EINVAL;
  460. sp->types[i - 1] = 0;
  461. timecnt--;
  462. }
  463. sp->ats[timecnt++] = attime;
  464. }
  465. p += stored;
  466. }
  467. timecnt = 0;
  468. for (i = 0; i < sp->timecnt; ++i) {
  469. unsigned char typ = *p++;
  470. if (sp->typecnt <= typ)
  471. return EINVAL;
  472. if (sp->types[i])
  473. sp->types[timecnt++] = typ;
  474. }
  475. sp->timecnt = timecnt;
  476. for (i = 0; i < sp->typecnt; ++i) {
  477. register struct ttinfo * ttisp;
  478. unsigned char isdst, desigidx;
  479. ttisp = &sp->ttis[i];
  480. ttisp->tt_utoff = detzcode(p);
  481. p += 4;
  482. isdst = *p++;
  483. if (! (isdst < 2))
  484. return EINVAL;
  485. ttisp->tt_isdst = isdst;
  486. desigidx = *p++;
  487. if (! (desigidx < sp->charcnt))
  488. return EINVAL;
  489. ttisp->tt_desigidx = desigidx;
  490. }
  491. for (i = 0; i < sp->charcnt; ++i)
  492. sp->chars[i] = *p++;
  493. /* Ensure '\0'-terminated, and make it safe to call
  494. ttunspecified later. */
  495. memset(&sp->chars[i], 0, CHARS_EXTRA);
  496. /* Read leap seconds, discarding those out of time_t range. */
  497. leapcnt = 0;
  498. for (i = 0; i < sp->leapcnt; ++i) {
  499. int_fast64_t tr = stored == 4 ? detzcode(p) : detzcode64(p);
  500. int_fast32_t corr = detzcode(p + stored);
  501. p += stored + 4;
  502. /* Leap seconds cannot occur before the Epoch,
  503. or out of order. */
  504. if (tr <= prevtr)
  505. return EINVAL;
  506. /* To avoid other botches in this code, each leap second's
  507. correction must differ from the previous one's by 1
  508. second or less, except that the first correction can be
  509. any value; these requirements are more generous than
  510. RFC 8536, to allow future RFC extensions. */
  511. if (! (i == 0
  512. || (prevcorr < corr
  513. ? corr == prevcorr + 1
  514. : (corr == prevcorr
  515. || corr == prevcorr - 1))))
  516. return EINVAL;
  517. prevtr = tr;
  518. prevcorr = corr;
  519. if (tr <= TIME_T_MAX) {
  520. sp->lsis[leapcnt].ls_trans = tr;
  521. sp->lsis[leapcnt].ls_corr = corr;
  522. leapcnt++;
  523. }
  524. }
  525. sp->leapcnt = leapcnt;
  526. for (i = 0; i < sp->typecnt; ++i) {
  527. register struct ttinfo * ttisp;
  528. ttisp = &sp->ttis[i];
  529. if (ttisstdcnt == 0)
  530. ttisp->tt_ttisstd = false;
  531. else {
  532. if (*p != true && *p != false)
  533. return EINVAL;
  534. ttisp->tt_ttisstd = *p++;
  535. }
  536. }
  537. for (i = 0; i < sp->typecnt; ++i) {
  538. register struct ttinfo * ttisp;
  539. ttisp = &sp->ttis[i];
  540. if (ttisutcnt == 0)
  541. ttisp->tt_ttisut = false;
  542. else {
  543. if (*p != true && *p != false)
  544. return EINVAL;
  545. ttisp->tt_ttisut = *p++;
  546. }
  547. }
  548. }
  549. nread -= p - up->buf;
  550. memmove(up->buf, p, nread);
  551. /* If this is an old file, we're done. */
  552. if (!version)
  553. break;
  554. }
  555. if (doextend && nread > 2 &&
  556. up->buf[0] == '\n' && up->buf[nread - 1] == '\n' &&
  557. sp->typecnt + 2 <= TZ_MAX_TYPES) {
  558. struct state *ts = &lsp->u.st;
  559. up->buf[nread - 1] = '\0';
  560. if (tzparse(&up->buf[1], ts, sp)) {
  561. /* Attempt to reuse existing abbreviations.
  562. Without this, America/Anchorage would be right on
  563. the edge after 2037 when TZ_MAX_CHARS is 50, as
  564. sp->charcnt equals 40 (for LMT AST AWT APT AHST
  565. AHDT YST AKDT AKST) and ts->charcnt equals 10
  566. (for AKST AKDT). Reusing means sp->charcnt can
  567. stay 40 in this example. */
  568. int gotabbr = 0;
  569. int charcnt = sp->charcnt;
  570. for (i = 0; i < ts->typecnt; i++) {
  571. char *tsabbr = ts->chars + ts->ttis[i].tt_desigidx;
  572. int j;
  573. for (j = 0; j < charcnt; j++)
  574. if (strcmp(sp->chars + j, tsabbr) == 0) {
  575. ts->ttis[i].tt_desigidx = j;
  576. gotabbr++;
  577. break;
  578. }
  579. if (! (j < charcnt)) {
  580. int tsabbrlen = strlen(tsabbr);
  581. if (j + tsabbrlen < TZ_MAX_CHARS) {
  582. strcpy(sp->chars + j, tsabbr);
  583. charcnt = j + tsabbrlen + 1;
  584. ts->ttis[i].tt_desigidx = j;
  585. gotabbr++;
  586. }
  587. }
  588. }
  589. if (gotabbr == ts->typecnt) {
  590. sp->charcnt = charcnt;
  591. /* Ignore any trailing, no-op transitions generated
  592. by zic as they don't help here and can run afoul
  593. of bugs in zic 2016j or earlier. */
  594. while (1 < sp->timecnt
  595. && (sp->types[sp->timecnt - 1]
  596. == sp->types[sp->timecnt - 2]))
  597. sp->timecnt--;
  598. for (i = 0;
  599. i < ts->timecnt && sp->timecnt < TZ_MAX_TIMES;
  600. i++) {
  601. time_t t = ts->ats[i];
  602. if (increment_overflow_time(&t, leapcorr(sp, t))
  603. || (0 < sp->timecnt
  604. && t <= sp->ats[sp->timecnt - 1]))
  605. continue;
  606. sp->ats[sp->timecnt] = t;
  607. sp->types[sp->timecnt] = (sp->typecnt
  608. + ts->types[i]);
  609. sp->timecnt++;
  610. }
  611. for (i = 0; i < ts->typecnt; i++)
  612. sp->ttis[sp->typecnt++] = ts->ttis[i];
  613. }
  614. }
  615. }
  616. if (sp->typecnt == 0)
  617. return EINVAL;
  618. if (sp->timecnt > 1) {
  619. if (sp->ats[0] <= TIME_T_MAX - SECSPERREPEAT) {
  620. time_t repeatat = sp->ats[0] + SECSPERREPEAT;
  621. int repeattype = sp->types[0];
  622. for (i = 1; i < sp->timecnt; ++i)
  623. if (sp->ats[i] == repeatat
  624. && typesequiv(sp, sp->types[i], repeattype)) {
  625. sp->goback = true;
  626. break;
  627. }
  628. }
  629. if (TIME_T_MIN + SECSPERREPEAT <= sp->ats[sp->timecnt - 1]) {
  630. time_t repeatat = sp->ats[sp->timecnt - 1] - SECSPERREPEAT;
  631. int repeattype = sp->types[sp->timecnt - 1];
  632. for (i = sp->timecnt - 2; i >= 0; --i)
  633. if (sp->ats[i] == repeatat
  634. && typesequiv(sp, sp->types[i], repeattype)) {
  635. sp->goahead = true;
  636. break;
  637. }
  638. }
  639. }
  640. /* Infer sp->defaulttype from the data. Although this default
  641. type is always zero for data from recent tzdb releases,
  642. things are trickier for data from tzdb 2018e or earlier.
  643. The first set of heuristics work around bugs in 32-bit data
  644. generated by tzdb 2013c or earlier. The workaround is for
  645. zones like Australia/Macquarie where timestamps before the
  646. first transition have a time type that is not the earliest
  647. standard-time type. See:
  648. https://mm.icann.org/pipermail/tz/2013-May/019368.html */
  649. /*
  650. ** If type 0 does not specify local time, or is unused in transitions,
  651. ** it's the type to use for early times.
  652. */
  653. for (i = 0; i < sp->timecnt; ++i)
  654. if (sp->types[i] == 0)
  655. break;
  656. i = i < sp->timecnt && ! ttunspecified(sp, 0) ? -1 : 0;
  657. /*
  658. ** Absent the above,
  659. ** if there are transition times
  660. ** and the first transition is to a daylight time
  661. ** find the standard type less than and closest to
  662. ** the type of the first transition.
  663. */
  664. if (i < 0 && sp->timecnt > 0 && sp->ttis[sp->types[0]].tt_isdst) {
  665. i = sp->types[0];
  666. while (--i >= 0)
  667. if (!sp->ttis[i].tt_isdst)
  668. break;
  669. }
  670. /* The next heuristics are for data generated by tzdb 2018e or
  671. earlier, for zones like EST5EDT where the first transition
  672. is to DST. */
  673. /*
  674. ** If no result yet, find the first standard type.
  675. ** If there is none, punt to type zero.
  676. */
  677. if (i < 0) {
  678. i = 0;
  679. while (sp->ttis[i].tt_isdst)
  680. if (++i >= sp->typecnt) {
  681. i = 0;
  682. break;
  683. }
  684. }
  685. /* A simple 'sp->defaulttype = 0;' would suffice here if we
  686. didn't have to worry about 2018e-or-earlier data. Even
  687. simpler would be to remove the defaulttype member and just
  688. use 0 in its place. */
  689. sp->defaulttype = i;
  690. return 0;
  691. }
  692. /* Load tz data from the file named NAME into *SP. Read extended
  693. format if DOEXTEND. Return 0 on success, an errno value on failure. */
  694. static int
  695. tzload(char const *name, struct state *sp, bool doextend)
  696. {
  697. #ifdef ALL_STATE
  698. union local_storage *lsp = malloc(sizeof *lsp);
  699. if (!lsp) {
  700. return HAVE_MALLOC_ERRNO ? errno : ENOMEM;
  701. } else {
  702. int err = tzloadbody(name, sp, doextend, lsp);
  703. free(lsp);
  704. return err;
  705. }
  706. #else
  707. union local_storage ls;
  708. return tzloadbody(name, sp, doextend, &ls);
  709. #endif
  710. }
  711. static bool
  712. typesequiv(const struct state *sp, int a, int b)
  713. {
  714. register bool result;
  715. if (sp == NULL ||
  716. a < 0 || a >= sp->typecnt ||
  717. b < 0 || b >= sp->typecnt)
  718. result = false;
  719. else {
  720. /* Compare the relevant members of *AP and *BP.
  721. Ignore tt_ttisstd and tt_ttisut, as they are
  722. irrelevant now and counting them could cause
  723. sp->goahead to mistakenly remain false. */
  724. register const struct ttinfo * ap = &sp->ttis[a];
  725. register const struct ttinfo * bp = &sp->ttis[b];
  726. result = (ap->tt_utoff == bp->tt_utoff
  727. && ap->tt_isdst == bp->tt_isdst
  728. && (strcmp(&sp->chars[ap->tt_desigidx],
  729. &sp->chars[bp->tt_desigidx])
  730. == 0));
  731. }
  732. return result;
  733. }
  734. static const int mon_lengths[2][MONSPERYEAR] = {
  735. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
  736. { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
  737. };
  738. static const int year_lengths[2] = {
  739. DAYSPERNYEAR, DAYSPERLYEAR
  740. };
  741. /* Is C an ASCII digit? */
  742. static bool
  743. is_digit(char c)
  744. {
  745. return '0' <= c && c <= '9';
  746. }
  747. /*
  748. ** Given a pointer into a timezone string, scan until a character that is not
  749. ** a valid character in a time zone abbreviation is found.
  750. ** Return a pointer to that character.
  751. */
  752. ATTRIBUTE_REPRODUCIBLE static const char *
  753. getzname(register const char *strp)
  754. {
  755. register char c;
  756. while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
  757. c != '+')
  758. ++strp;
  759. return strp;
  760. }
  761. /*
  762. ** Given a pointer into an extended timezone string, scan until the ending
  763. ** delimiter of the time zone abbreviation is located.
  764. ** Return a pointer to the delimiter.
  765. **
  766. ** As with getzname above, the legal character set is actually quite
  767. ** restricted, with other characters producing undefined results.
  768. ** We don't do any checking here; checking is done later in common-case code.
  769. */
  770. ATTRIBUTE_REPRODUCIBLE static const char *
  771. getqzname(register const char *strp, const int delim)
  772. {
  773. register int c;
  774. while ((c = *strp) != '\0' && c != delim)
  775. ++strp;
  776. return strp;
  777. }
  778. /*
  779. ** Given a pointer into a timezone string, extract a number from that string.
  780. ** Check that the number is within a specified range; if it is not, return
  781. ** NULL.
  782. ** Otherwise, return a pointer to the first character not part of the number.
  783. */
  784. static const char *
  785. getnum(register const char *strp, int *const nump, const int min, const int max)
  786. {
  787. register char c;
  788. register int num;
  789. if (strp == NULL || !is_digit(c = *strp))
  790. return NULL;
  791. num = 0;
  792. do {
  793. num = num * 10 + (c - '0');
  794. if (num > max)
  795. return NULL; /* illegal value */
  796. c = *++strp;
  797. } while (is_digit(c));
  798. if (num < min)
  799. return NULL; /* illegal value */
  800. *nump = num;
  801. return strp;
  802. }
  803. /*
  804. ** Given a pointer into a timezone string, extract a number of seconds,
  805. ** in hh[:mm[:ss]] form, from the string.
  806. ** If any error occurs, return NULL.
  807. ** Otherwise, return a pointer to the first character not part of the number
  808. ** of seconds.
  809. */
  810. static const char *
  811. getsecs(register const char *strp, int_fast32_t *const secsp)
  812. {
  813. int num;
  814. int_fast32_t secsperhour = SECSPERHOUR;
  815. /*
  816. ** 'HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
  817. ** "M10.4.6/26", which does not conform to Posix,
  818. ** but which specifies the equivalent of
  819. ** "02:00 on the first Sunday on or after 23 Oct".
  820. */
  821. strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
  822. if (strp == NULL)
  823. return NULL;
  824. *secsp = num * secsperhour;
  825. if (*strp == ':') {
  826. ++strp;
  827. strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
  828. if (strp == NULL)
  829. return NULL;
  830. *secsp += num * SECSPERMIN;
  831. if (*strp == ':') {
  832. ++strp;
  833. /* 'SECSPERMIN' allows for leap seconds. */
  834. strp = getnum(strp, &num, 0, SECSPERMIN);
  835. if (strp == NULL)
  836. return NULL;
  837. *secsp += num;
  838. }
  839. }
  840. return strp;
  841. }
  842. /*
  843. ** Given a pointer into a timezone string, extract an offset, in
  844. ** [+-]hh[:mm[:ss]] form, from the string.
  845. ** If any error occurs, return NULL.
  846. ** Otherwise, return a pointer to the first character not part of the time.
  847. */
  848. static const char *
  849. getoffset(register const char *strp, int_fast32_t *const offsetp)
  850. {
  851. register bool neg = false;
  852. if (*strp == '-') {
  853. neg = true;
  854. ++strp;
  855. } else if (*strp == '+')
  856. ++strp;
  857. strp = getsecs(strp, offsetp);
  858. if (strp == NULL)
  859. return NULL; /* illegal time */
  860. if (neg)
  861. *offsetp = -*offsetp;
  862. return strp;
  863. }
  864. /*
  865. ** Given a pointer into a timezone string, extract a rule in the form
  866. ** date[/time]. See POSIX section 8 for the format of "date" and "time".
  867. ** If a valid rule is not found, return NULL.
  868. ** Otherwise, return a pointer to the first character not part of the rule.
  869. */
  870. static const char *
  871. getrule(const char *strp, register struct rule *const rulep)
  872. {
  873. if (*strp == 'J') {
  874. /*
  875. ** Julian day.
  876. */
  877. rulep->r_type = JULIAN_DAY;
  878. ++strp;
  879. strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
  880. } else if (*strp == 'M') {
  881. /*
  882. ** Month, week, day.
  883. */
  884. rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
  885. ++strp;
  886. strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
  887. if (strp == NULL)
  888. return NULL;
  889. if (*strp++ != '.')
  890. return NULL;
  891. strp = getnum(strp, &rulep->r_week, 1, 5);
  892. if (strp == NULL)
  893. return NULL;
  894. if (*strp++ != '.')
  895. return NULL;
  896. strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
  897. } else if (is_digit(*strp)) {
  898. /*
  899. ** Day of year.
  900. */
  901. rulep->r_type = DAY_OF_YEAR;
  902. strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
  903. } else return NULL; /* invalid format */
  904. if (strp == NULL)
  905. return NULL;
  906. if (*strp == '/') {
  907. /*
  908. ** Time specified.
  909. */
  910. ++strp;
  911. strp = getoffset(strp, &rulep->r_time);
  912. } else rulep->r_time = 2 * SECSPERHOUR; /* default = 2:00:00 */
  913. return strp;
  914. }
  915. /*
  916. ** Given a year, a rule, and the offset from UT at the time that rule takes
  917. ** effect, calculate the year-relative time that rule takes effect.
  918. */
  919. static int_fast32_t
  920. transtime(const int year, register const struct rule *const rulep,
  921. const int_fast32_t offset)
  922. {
  923. register bool leapyear;
  924. register int_fast32_t value;
  925. register int i;
  926. int d, m1, yy0, yy1, yy2, dow;
  927. leapyear = isleap(year);
  928. switch (rulep->r_type) {
  929. case JULIAN_DAY:
  930. /*
  931. ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
  932. ** years.
  933. ** In non-leap years, or if the day number is 59 or less, just
  934. ** add SECSPERDAY times the day number-1 to the time of
  935. ** January 1, midnight, to get the day.
  936. */
  937. value = (rulep->r_day - 1) * SECSPERDAY;
  938. if (leapyear && rulep->r_day >= 60)
  939. value += SECSPERDAY;
  940. break;
  941. case DAY_OF_YEAR:
  942. /*
  943. ** n - day of year.
  944. ** Just add SECSPERDAY times the day number to the time of
  945. ** January 1, midnight, to get the day.
  946. */
  947. value = rulep->r_day * SECSPERDAY;
  948. break;
  949. case MONTH_NTH_DAY_OF_WEEK:
  950. /*
  951. ** Mm.n.d - nth "dth day" of month m.
  952. */
  953. /*
  954. ** Use Zeller's Congruence to get day-of-week of first day of
  955. ** month.
  956. */
  957. m1 = (rulep->r_mon + 9) % 12 + 1;
  958. yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
  959. yy1 = yy0 / 100;
  960. yy2 = yy0 % 100;
  961. dow = ((26 * m1 - 2) / 10 +
  962. 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
  963. if (dow < 0)
  964. dow += DAYSPERWEEK;
  965. /*
  966. ** "dow" is the day-of-week of the first day of the month. Get
  967. ** the day-of-month (zero-origin) of the first "dow" day of the
  968. ** month.
  969. */
  970. d = rulep->r_day - dow;
  971. if (d < 0)
  972. d += DAYSPERWEEK;
  973. for (i = 1; i < rulep->r_week; ++i) {
  974. if (d + DAYSPERWEEK >=
  975. mon_lengths[leapyear][rulep->r_mon - 1])
  976. break;
  977. d += DAYSPERWEEK;
  978. }
  979. /*
  980. ** "d" is the day-of-month (zero-origin) of the day we want.
  981. */
  982. value = d * SECSPERDAY;
  983. for (i = 0; i < rulep->r_mon - 1; ++i)
  984. value += mon_lengths[leapyear][i] * SECSPERDAY;
  985. break;
  986. default: unreachable();
  987. }
  988. /*
  989. ** "value" is the year-relative time of 00:00:00 UT on the day in
  990. ** question. To get the year-relative time of the specified local
  991. ** time on that day, add the transition time and the current offset
  992. ** from UT.
  993. */
  994. return value + rulep->r_time + offset;
  995. }
  996. /*
  997. ** Given a POSIX section 8-style TZ string, fill in the rule tables as
  998. ** appropriate.
  999. */
  1000. static bool
  1001. tzparse(const char *name, struct state *sp, struct state *basep)
  1002. {
  1003. const char * stdname;
  1004. const char * dstname;
  1005. int_fast32_t stdoffset;
  1006. int_fast32_t dstoffset;
  1007. register char * cp;
  1008. register bool load_ok;
  1009. ptrdiff_t stdlen, dstlen, charcnt;
  1010. time_t atlo = TIME_T_MIN, leaplo = TIME_T_MIN;
  1011. stdname = name;
  1012. if (*name == '<') {
  1013. name++;
  1014. stdname = name;
  1015. name = getqzname(name, '>');
  1016. if (*name != '>')
  1017. return false;
  1018. stdlen = name - stdname;
  1019. name++;
  1020. } else {
  1021. name = getzname(name);
  1022. stdlen = name - stdname;
  1023. }
  1024. if (! (0 < stdlen && stdlen <= TZNAME_MAXIMUM))
  1025. return false;
  1026. name = getoffset(name, &stdoffset);
  1027. if (name == NULL)
  1028. return false;
  1029. charcnt = stdlen + 1;
  1030. if (basep) {
  1031. if (0 < basep->timecnt)
  1032. atlo = basep->ats[basep->timecnt - 1];
  1033. load_ok = false;
  1034. sp->leapcnt = basep->leapcnt;
  1035. memcpy(sp->lsis, basep->lsis, sp->leapcnt * sizeof *sp->lsis);
  1036. } else {
  1037. load_ok = tzload(TZDEFRULES, sp, false) == 0;
  1038. if (!load_ok)
  1039. sp->leapcnt = 0; /* So, we're off a little. */
  1040. }
  1041. if (0 < sp->leapcnt)
  1042. leaplo = sp->lsis[sp->leapcnt - 1].ls_trans;
  1043. if (*name != '\0') {
  1044. if (*name == '<') {
  1045. dstname = ++name;
  1046. name = getqzname(name, '>');
  1047. if (*name != '>')
  1048. return false;
  1049. dstlen = name - dstname;
  1050. name++;
  1051. } else {
  1052. dstname = name;
  1053. name = getzname(name);
  1054. dstlen = name - dstname; /* length of DST abbr. */
  1055. }
  1056. if (! (0 < dstlen && dstlen <= TZNAME_MAXIMUM))
  1057. return false;
  1058. charcnt += dstlen + 1;
  1059. if (*name != '\0' && *name != ',' && *name != ';') {
  1060. name = getoffset(name, &dstoffset);
  1061. if (name == NULL)
  1062. return false;
  1063. } else dstoffset = stdoffset - SECSPERHOUR;
  1064. if (*name == '\0' && !load_ok)
  1065. name = TZDEFRULESTRING;
  1066. if (*name == ',' || *name == ';') {
  1067. struct rule start;
  1068. struct rule end;
  1069. register int year;
  1070. register int timecnt;
  1071. time_t janfirst;
  1072. int_fast32_t janoffset = 0;
  1073. int yearbeg, yearlim;
  1074. ++name;
  1075. if ((name = getrule(name, &start)) == NULL)
  1076. return false;
  1077. if (*name++ != ',')
  1078. return false;
  1079. if ((name = getrule(name, &end)) == NULL)
  1080. return false;
  1081. if (*name != '\0')
  1082. return false;
  1083. sp->typecnt = 2; /* standard time and DST */
  1084. /*
  1085. ** Two transitions per year, from EPOCH_YEAR forward.
  1086. */
  1087. init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
  1088. init_ttinfo(&sp->ttis[1], -dstoffset, true, stdlen + 1);
  1089. sp->defaulttype = 0;
  1090. timecnt = 0;
  1091. janfirst = 0;
  1092. yearbeg = EPOCH_YEAR;
  1093. do {
  1094. int_fast32_t yearsecs
  1095. = year_lengths[isleap(yearbeg - 1)] * SECSPERDAY;
  1096. yearbeg--;
  1097. if (increment_overflow_time(&janfirst, -yearsecs)) {
  1098. janoffset = -yearsecs;
  1099. break;
  1100. }
  1101. } while (atlo < janfirst
  1102. && EPOCH_YEAR - YEARSPERREPEAT / 2 < yearbeg);
  1103. while (true) {
  1104. int_fast32_t yearsecs
  1105. = year_lengths[isleap(yearbeg)] * SECSPERDAY;
  1106. int yearbeg1 = yearbeg;
  1107. time_t janfirst1 = janfirst;
  1108. if (increment_overflow_time(&janfirst1, yearsecs)
  1109. || increment_overflow(&yearbeg1, 1)
  1110. || atlo <= janfirst1)
  1111. break;
  1112. yearbeg = yearbeg1;
  1113. janfirst = janfirst1;
  1114. }
  1115. yearlim = yearbeg;
  1116. if (increment_overflow(&yearlim, YEARSPERREPEAT + 1))
  1117. yearlim = INT_MAX;
  1118. for (year = yearbeg; year < yearlim; year++) {
  1119. int_fast32_t
  1120. starttime = transtime(year, &start, stdoffset),
  1121. endtime = transtime(year, &end, dstoffset);
  1122. int_fast32_t
  1123. yearsecs = (year_lengths[isleap(year)]
  1124. * SECSPERDAY);
  1125. bool reversed = endtime < starttime;
  1126. if (reversed) {
  1127. int_fast32_t swap = starttime;
  1128. starttime = endtime;
  1129. endtime = swap;
  1130. }
  1131. if (reversed
  1132. || (starttime < endtime
  1133. && endtime - starttime < yearsecs)) {
  1134. if (TZ_MAX_TIMES - 2 < timecnt)
  1135. break;
  1136. sp->ats[timecnt] = janfirst;
  1137. if (! increment_overflow_time
  1138. (&sp->ats[timecnt],
  1139. janoffset + starttime)
  1140. && atlo <= sp->ats[timecnt])
  1141. sp->types[timecnt++] = !reversed;
  1142. sp->ats[timecnt] = janfirst;
  1143. if (! increment_overflow_time
  1144. (&sp->ats[timecnt],
  1145. janoffset + endtime)
  1146. && atlo <= sp->ats[timecnt]) {
  1147. sp->types[timecnt++] = reversed;
  1148. }
  1149. }
  1150. if (endtime < leaplo) {
  1151. yearlim = year;
  1152. if (increment_overflow(&yearlim,
  1153. YEARSPERREPEAT + 1))
  1154. yearlim = INT_MAX;
  1155. }
  1156. if (increment_overflow_time
  1157. (&janfirst, janoffset + yearsecs))
  1158. break;
  1159. janoffset = 0;
  1160. }
  1161. sp->timecnt = timecnt;
  1162. if (! timecnt) {
  1163. sp->ttis[0] = sp->ttis[1];
  1164. sp->typecnt = 1; /* Perpetual DST. */
  1165. } else if (YEARSPERREPEAT < year - yearbeg)
  1166. sp->goback = sp->goahead = true;
  1167. } else {
  1168. register int_fast32_t theirstdoffset;
  1169. register int_fast32_t theirdstoffset;
  1170. register int_fast32_t theiroffset;
  1171. register bool isdst;
  1172. register int i;
  1173. register int j;
  1174. if (*name != '\0')
  1175. return false;
  1176. /*
  1177. ** Initial values of theirstdoffset and theirdstoffset.
  1178. */
  1179. theirstdoffset = 0;
  1180. for (i = 0; i < sp->timecnt; ++i) {
  1181. j = sp->types[i];
  1182. if (!sp->ttis[j].tt_isdst) {
  1183. theirstdoffset =
  1184. - sp->ttis[j].tt_utoff;
  1185. break;
  1186. }
  1187. }
  1188. theirdstoffset = 0;
  1189. for (i = 0; i < sp->timecnt; ++i) {
  1190. j = sp->types[i];
  1191. if (sp->ttis[j].tt_isdst) {
  1192. theirdstoffset =
  1193. - sp->ttis[j].tt_utoff;
  1194. break;
  1195. }
  1196. }
  1197. /*
  1198. ** Initially we're assumed to be in standard time.
  1199. */
  1200. isdst = false;
  1201. /*
  1202. ** Now juggle transition times and types
  1203. ** tracking offsets as you do.
  1204. */
  1205. for (i = 0; i < sp->timecnt; ++i) {
  1206. j = sp->types[i];
  1207. sp->types[i] = sp->ttis[j].tt_isdst;
  1208. if (sp->ttis[j].tt_ttisut) {
  1209. /* No adjustment to transition time */
  1210. } else {
  1211. /*
  1212. ** If daylight saving time is in
  1213. ** effect, and the transition time was
  1214. ** not specified as standard time, add
  1215. ** the daylight saving time offset to
  1216. ** the transition time; otherwise, add
  1217. ** the standard time offset to the
  1218. ** transition time.
  1219. */
  1220. /*
  1221. ** Transitions from DST to DDST
  1222. ** will effectively disappear since
  1223. ** POSIX provides for only one DST
  1224. ** offset.
  1225. */
  1226. if (isdst && !sp->ttis[j].tt_ttisstd) {
  1227. sp->ats[i] += dstoffset -
  1228. theirdstoffset;
  1229. } else {
  1230. sp->ats[i] += stdoffset -
  1231. theirstdoffset;
  1232. }
  1233. }
  1234. theiroffset = -sp->ttis[j].tt_utoff;
  1235. if (sp->ttis[j].tt_isdst)
  1236. theirdstoffset = theiroffset;
  1237. else theirstdoffset = theiroffset;
  1238. }
  1239. /*
  1240. ** Finally, fill in ttis.
  1241. */
  1242. init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
  1243. init_ttinfo(&sp->ttis[1], -dstoffset, true, stdlen + 1);
  1244. sp->typecnt = 2;
  1245. sp->defaulttype = 0;
  1246. }
  1247. } else {
  1248. dstlen = 0;
  1249. sp->typecnt = 1; /* only standard time */
  1250. sp->timecnt = 0;
  1251. init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
  1252. sp->defaulttype = 0;
  1253. }
  1254. sp->charcnt = charcnt;
  1255. cp = sp->chars;
  1256. memcpy(cp, stdname, stdlen);
  1257. cp += stdlen;
  1258. *cp++ = '\0';
  1259. if (dstlen != 0) {
  1260. memcpy(cp, dstname, dstlen);
  1261. *(cp + dstlen) = '\0';
  1262. }
  1263. return true;
  1264. }
  1265. static void
  1266. gmtload(struct state *const sp)
  1267. {
  1268. if (tzload(etc_utc, sp, true) != 0)
  1269. tzparse("UTC0", sp, NULL);
  1270. }
  1271. /* Initialize *SP to a value appropriate for the TZ setting NAME.
  1272. Return 0 on success, an errno value on failure. */
  1273. static int
  1274. zoneinit(struct state *sp, char const *name)
  1275. {
  1276. if (name && ! name[0]) {
  1277. /*
  1278. ** User wants it fast rather than right.
  1279. */
  1280. sp->leapcnt = 0; /* so, we're off a little */
  1281. sp->timecnt = 0;
  1282. sp->typecnt = 0;
  1283. sp->charcnt = 0;
  1284. sp->goback = sp->goahead = false;
  1285. init_ttinfo(&sp->ttis[0], 0, false, 0);
  1286. strcpy(sp->chars, utc);
  1287. sp->defaulttype = 0;
  1288. return 0;
  1289. } else {
  1290. int err = tzload(name, sp, true);
  1291. if (err != 0 && name && name[0] != ':' && tzparse(name, sp, NULL))
  1292. err = 0;
  1293. if (err == 0)
  1294. err = scrub_abbrs(sp);
  1295. return err;
  1296. }
  1297. }
  1298. static void
  1299. tzset_unlocked(void)
  1300. {
  1301. char const *name = getenv("TZ");
  1302. struct state *sp = lclptr;
  1303. int lcl = name ? strlen(name) < sizeof lcl_TZname : -1;
  1304. if (lcl < 0
  1305. ? lcl_is_set < 0
  1306. : 0 < lcl_is_set && strcmp(lcl_TZname, name) == 0)
  1307. return;
  1308. #ifdef ALL_STATE
  1309. if (! sp)
  1310. lclptr = sp = malloc(sizeof *lclptr);
  1311. #endif /* defined ALL_STATE */
  1312. if (sp) {
  1313. if (zoneinit(sp, name) != 0)
  1314. zoneinit(sp, "");
  1315. if (0 < lcl)
  1316. strcpy(lcl_TZname, name);
  1317. }
  1318. settzname();
  1319. lcl_is_set = lcl;
  1320. }
  1321. void
  1322. tzset(void)
  1323. {
  1324. if (lock() != 0)
  1325. return;
  1326. tzset_unlocked();
  1327. unlock();
  1328. }
  1329. static void
  1330. gmtcheck(void)
  1331. {
  1332. static bool gmt_is_set;
  1333. if (lock() != 0)
  1334. return;
  1335. if (! gmt_is_set) {
  1336. #ifdef ALL_STATE
  1337. gmtptr = malloc(sizeof *gmtptr);
  1338. #endif
  1339. if (gmtptr)
  1340. gmtload(gmtptr);
  1341. gmt_is_set = true;
  1342. }
  1343. unlock();
  1344. }
  1345. #if NETBSD_INSPIRED
  1346. timezone_t
  1347. tzalloc(char const *name)
  1348. {
  1349. timezone_t sp = malloc(sizeof *sp);
  1350. if (sp) {
  1351. int err = zoneinit(sp, name);
  1352. if (err != 0) {
  1353. free(sp);
  1354. errno = err;
  1355. return NULL;
  1356. }
  1357. } else if (!HAVE_MALLOC_ERRNO)
  1358. errno = ENOMEM;
  1359. return sp;
  1360. }
  1361. void
  1362. tzfree(timezone_t sp)
  1363. {
  1364. free(sp);
  1365. }
  1366. /*
  1367. ** NetBSD 6.1.4 has ctime_rz, but omit it because POSIX says ctime and
  1368. ** ctime_r are obsolescent and have potential security problems that
  1369. ** ctime_rz would share. Callers can instead use localtime_rz + strftime.
  1370. **
  1371. ** NetBSD 6.1.4 has tzgetname, but omit it because it doesn't work
  1372. ** in zones with three or more time zone abbreviations.
  1373. ** Callers can instead use localtime_rz + strftime.
  1374. */
  1375. #endif
  1376. /*
  1377. ** The easy way to behave "as if no library function calls" localtime
  1378. ** is to not call it, so we drop its guts into "localsub", which can be
  1379. ** freely called. (And no, the PANS doesn't require the above behavior,
  1380. ** but it *is* desirable.)
  1381. **
  1382. ** If successful and SETNAME is nonzero,
  1383. ** set the applicable parts of tzname, timezone and altzone;
  1384. ** however, it's OK to omit this step if the timezone is POSIX-compatible,
  1385. ** since in that case tzset should have already done this step correctly.
  1386. ** SETNAME's type is int_fast32_t for compatibility with gmtsub,
  1387. ** but it is actually a boolean and its value should be 0 or 1.
  1388. */
  1389. /*ARGSUSED*/
  1390. static struct tm *
  1391. localsub(struct state const *sp, time_t const *timep, int_fast32_t setname,
  1392. struct tm *const tmp)
  1393. {
  1394. register const struct ttinfo * ttisp;
  1395. register int i;
  1396. register struct tm * result;
  1397. const time_t t = *timep;
  1398. if (sp == NULL) {
  1399. /* Don't bother to set tzname etc.; tzset has already done it. */
  1400. return gmtsub(gmtptr, timep, 0, tmp);
  1401. }
  1402. if ((sp->goback && t < sp->ats[0]) ||
  1403. (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
  1404. time_t newt;
  1405. register time_t seconds;
  1406. register time_t years;
  1407. if (t < sp->ats[0])
  1408. seconds = sp->ats[0] - t;
  1409. else seconds = t - sp->ats[sp->timecnt - 1];
  1410. --seconds;
  1411. /* Beware integer overflow, as SECONDS might
  1412. be close to the maximum time_t. */
  1413. years = seconds / SECSPERREPEAT * YEARSPERREPEAT;
  1414. seconds = years * AVGSECSPERYEAR;
  1415. years += YEARSPERREPEAT;
  1416. if (t < sp->ats[0])
  1417. newt = t + seconds + SECSPERREPEAT;
  1418. else
  1419. newt = t - seconds - SECSPERREPEAT;
  1420. if (newt < sp->ats[0] ||
  1421. newt > sp->ats[sp->timecnt - 1])
  1422. return NULL; /* "cannot happen" */
  1423. result = localsub(sp, &newt, setname, tmp);
  1424. if (result) {
  1425. #if defined ckd_add && defined ckd_sub
  1426. if (t < sp->ats[0]
  1427. ? ckd_sub(&result->tm_year,
  1428. result->tm_year, years)
  1429. : ckd_add(&result->tm_year,
  1430. result->tm_year, years))
  1431. return NULL;
  1432. #else
  1433. register int_fast64_t newy;
  1434. newy = result->tm_year;
  1435. if (t < sp->ats[0])
  1436. newy -= years;
  1437. else newy += years;
  1438. if (! (INT_MIN <= newy && newy <= INT_MAX))
  1439. return NULL;
  1440. result->tm_year = newy;
  1441. #endif
  1442. }
  1443. return result;
  1444. }
  1445. if (sp->timecnt == 0 || t < sp->ats[0]) {
  1446. i = sp->defaulttype;
  1447. } else {
  1448. register int lo = 1;
  1449. register int hi = sp->timecnt;
  1450. while (lo < hi) {
  1451. register int mid = (lo + hi) >> 1;
  1452. if (t < sp->ats[mid])
  1453. hi = mid;
  1454. else lo = mid + 1;
  1455. }
  1456. i = sp->types[lo - 1];
  1457. }
  1458. ttisp = &sp->ttis[i];
  1459. /*
  1460. ** To get (wrong) behavior that's compatible with System V Release 2.0
  1461. ** you'd replace the statement below with
  1462. ** t += ttisp->tt_utoff;
  1463. ** timesub(&t, 0L, sp, tmp);
  1464. */
  1465. result = timesub(&t, ttisp->tt_utoff, sp, tmp);
  1466. if (result) {
  1467. result->tm_isdst = ttisp->tt_isdst;
  1468. #ifdef TM_ZONE
  1469. result->TM_ZONE = (char *) &sp->chars[ttisp->tt_desigidx];
  1470. #endif /* defined TM_ZONE */
  1471. if (setname)
  1472. update_tzname_etc(sp, ttisp);
  1473. }
  1474. return result;
  1475. }
  1476. #if NETBSD_INSPIRED
  1477. struct tm *
  1478. localtime_rz(struct state *restrict sp, time_t const *restrict timep,
  1479. struct tm *restrict tmp)
  1480. {
  1481. return localsub(sp, timep, 0, tmp);
  1482. }
  1483. #endif
  1484. static struct tm *
  1485. localtime_tzset(time_t const *timep, struct tm *tmp, bool setname)
  1486. {
  1487. int err = lock();
  1488. if (err) {
  1489. errno = err;
  1490. return NULL;
  1491. }
  1492. if (setname || !lcl_is_set)
  1493. tzset_unlocked();
  1494. tmp = localsub(lclptr, timep, setname, tmp);
  1495. unlock();
  1496. return tmp;
  1497. }
  1498. struct tm *
  1499. localtime(const time_t *timep)
  1500. {
  1501. #if !SUPPORT_C89
  1502. static struct tm tm;
  1503. #endif
  1504. return localtime_tzset(timep, &tm, true);
  1505. }
  1506. struct tm *
  1507. localtime_r(const time_t *restrict timep, struct tm *restrict tmp)
  1508. {
  1509. return localtime_tzset(timep, tmp, false);
  1510. }
  1511. /*
  1512. ** gmtsub is to gmtime as localsub is to localtime.
  1513. */
  1514. static struct tm *
  1515. gmtsub(ATTRIBUTE_MAYBE_UNUSED struct state const *sp, time_t const *timep,
  1516. int_fast32_t offset, struct tm *tmp)
  1517. {
  1518. register struct tm * result;
  1519. result = timesub(timep, offset, gmtptr, tmp);
  1520. #ifdef TM_ZONE
  1521. /*
  1522. ** Could get fancy here and deliver something such as
  1523. ** "+xx" or "-xx" if offset is non-zero,
  1524. ** but this is no time for a treasure hunt.
  1525. */
  1526. tmp->TM_ZONE = ((char *)
  1527. (offset ? wildabbr : gmtptr ? gmtptr->chars : utc));
  1528. #endif /* defined TM_ZONE */
  1529. return result;
  1530. }
  1531. /*
  1532. * Re-entrant version of gmtime.
  1533. */
  1534. struct tm *
  1535. gmtime_r(time_t const *restrict timep, struct tm *restrict tmp)
  1536. {
  1537. gmtcheck();
  1538. return gmtsub(gmtptr, timep, 0, tmp);
  1539. }
  1540. struct tm *
  1541. gmtime(const time_t *timep)
  1542. {
  1543. #if !SUPPORT_C89
  1544. static struct tm tm;
  1545. #endif
  1546. return gmtime_r(timep, &tm);
  1547. }
  1548. #if STD_INSPIRED
  1549. /* This function is obsolescent and may disappear in future releases.
  1550. Callers can instead use localtime_rz with a fixed-offset zone. */
  1551. struct tm *
  1552. offtime(const time_t *timep, long offset)
  1553. {
  1554. gmtcheck();
  1555. #if !SUPPORT_C89
  1556. static struct tm tm;
  1557. #endif
  1558. return gmtsub(gmtptr, timep, offset, &tm);
  1559. }
  1560. #endif
  1561. /*
  1562. ** Return the number of leap years through the end of the given year
  1563. ** where, to make the math easy, the answer for year zero is defined as zero.
  1564. */
  1565. static time_t
  1566. leaps_thru_end_of_nonneg(time_t y)
  1567. {
  1568. return y / 4 - y / 100 + y / 400;
  1569. }
  1570. static time_t
  1571. leaps_thru_end_of(time_t y)
  1572. {
  1573. return (y < 0
  1574. ? -1 - leaps_thru_end_of_nonneg(-1 - y)
  1575. : leaps_thru_end_of_nonneg(y));
  1576. }
  1577. static struct tm *
  1578. timesub(const time_t *timep, int_fast32_t offset,
  1579. const struct state *sp, struct tm *tmp)
  1580. {
  1581. register const struct lsinfo * lp;
  1582. register time_t tdays;
  1583. register const int * ip;
  1584. register int_fast32_t corr;
  1585. register int i;
  1586. int_fast32_t idays, rem, dayoff, dayrem;
  1587. time_t y;
  1588. /* If less than SECSPERMIN, the number of seconds since the
  1589. most recent positive leap second; otherwise, do not add 1
  1590. to localtime tm_sec because of leap seconds. */
  1591. time_t secs_since_posleap = SECSPERMIN;
  1592. corr = 0;
  1593. i = (sp == NULL) ? 0 : sp->leapcnt;
  1594. while (--i >= 0) {
  1595. lp = &sp->lsis[i];
  1596. if (*timep >= lp->ls_trans) {
  1597. corr = lp->ls_corr;
  1598. if ((i == 0 ? 0 : lp[-1].ls_corr) < corr)
  1599. secs_since_posleap = *timep - lp->ls_trans;
  1600. break;
  1601. }
  1602. }
  1603. /* Calculate the year, avoiding integer overflow even if
  1604. time_t is unsigned. */
  1605. tdays = *timep / SECSPERDAY;
  1606. rem = *timep % SECSPERDAY;
  1607. rem += offset % SECSPERDAY - corr % SECSPERDAY + 3 * SECSPERDAY;
  1608. dayoff = offset / SECSPERDAY - corr / SECSPERDAY + rem / SECSPERDAY - 3;
  1609. rem %= SECSPERDAY;
  1610. /* y = (EPOCH_YEAR
  1611. + floor((tdays + dayoff) / DAYSPERREPEAT) * YEARSPERREPEAT),
  1612. sans overflow. But calculate against 1570 (EPOCH_YEAR -
  1613. YEARSPERREPEAT) instead of against 1970 so that things work
  1614. for localtime values before 1970 when time_t is unsigned. */
  1615. dayrem = tdays % DAYSPERREPEAT;
  1616. dayrem += dayoff % DAYSPERREPEAT;
  1617. y = (EPOCH_YEAR - YEARSPERREPEAT
  1618. + ((1 + dayoff / DAYSPERREPEAT + dayrem / DAYSPERREPEAT
  1619. - ((dayrem % DAYSPERREPEAT) < 0)
  1620. + tdays / DAYSPERREPEAT)
  1621. * YEARSPERREPEAT));
  1622. /* idays = (tdays + dayoff) mod DAYSPERREPEAT, sans overflow. */
  1623. idays = tdays % DAYSPERREPEAT;
  1624. idays += dayoff % DAYSPERREPEAT + 2 * DAYSPERREPEAT;
  1625. idays %= DAYSPERREPEAT;
  1626. /* Increase Y and decrease IDAYS until IDAYS is in range for Y. */
  1627. while (year_lengths[isleap(y)] <= idays) {
  1628. int tdelta = idays / DAYSPERLYEAR;
  1629. int_fast32_t ydelta = tdelta + !tdelta;
  1630. time_t newy = y + ydelta;
  1631. register int leapdays;
  1632. leapdays = leaps_thru_end_of(newy - 1) -
  1633. leaps_thru_end_of(y - 1);
  1634. idays -= ydelta * DAYSPERNYEAR;
  1635. idays -= leapdays;
  1636. y = newy;
  1637. }
  1638. #ifdef ckd_add
  1639. if (ckd_add(&tmp->tm_year, y, -TM_YEAR_BASE)) {
  1640. errno = EOVERFLOW;
  1641. return NULL;
  1642. }
  1643. #else
  1644. if (!TYPE_SIGNED(time_t) && y < TM_YEAR_BASE) {
  1645. int signed_y = y;
  1646. tmp->tm_year = signed_y - TM_YEAR_BASE;
  1647. } else if ((!TYPE_SIGNED(time_t) || INT_MIN + TM_YEAR_BASE <= y)
  1648. && y - TM_YEAR_BASE <= INT_MAX)
  1649. tmp->tm_year = y - TM_YEAR_BASE;
  1650. else {
  1651. errno = EOVERFLOW;
  1652. return NULL;
  1653. }
  1654. #endif
  1655. tmp->tm_yday = idays;
  1656. /*
  1657. ** The "extra" mods below avoid overflow problems.
  1658. */
  1659. tmp->tm_wday = (TM_WDAY_BASE
  1660. + ((tmp->tm_year % DAYSPERWEEK)
  1661. * (DAYSPERNYEAR % DAYSPERWEEK))
  1662. + leaps_thru_end_of(y - 1)
  1663. - leaps_thru_end_of(TM_YEAR_BASE - 1)
  1664. + idays);
  1665. tmp->tm_wday %= DAYSPERWEEK;
  1666. if (tmp->tm_wday < 0)
  1667. tmp->tm_wday += DAYSPERWEEK;
  1668. tmp->tm_hour = rem / SECSPERHOUR;
  1669. rem %= SECSPERHOUR;
  1670. tmp->tm_min = rem / SECSPERMIN;
  1671. tmp->tm_sec = rem % SECSPERMIN;
  1672. /* Use "... ??:??:60" at the end of the localtime minute containing
  1673. the second just before the positive leap second. */
  1674. tmp->tm_sec += secs_since_posleap <= tmp->tm_sec;
  1675. ip = mon_lengths[isleap(y)];
  1676. for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
  1677. idays -= ip[tmp->tm_mon];
  1678. tmp->tm_mday = idays + 1;
  1679. tmp->tm_isdst = 0;
  1680. #ifdef TM_GMTOFF
  1681. tmp->TM_GMTOFF = offset;
  1682. #endif /* defined TM_GMTOFF */
  1683. return tmp;
  1684. }
  1685. /*
  1686. ** Adapted from code provided by Robert Elz, who writes:
  1687. ** The "best" way to do mktime I think is based on an idea of Bob
  1688. ** Kridle's (so its said...) from a long time ago.
  1689. ** It does a binary search of the time_t space. Since time_t's are
  1690. ** just 32 bits, its a max of 32 iterations (even at 64 bits it
  1691. ** would still be very reasonable).
  1692. */
  1693. #ifndef WRONG
  1694. # define WRONG (-1)
  1695. #endif /* !defined WRONG */
  1696. /*
  1697. ** Normalize logic courtesy Paul Eggert.
  1698. */
  1699. static bool
  1700. increment_overflow(int *ip, int j)
  1701. {
  1702. #ifdef ckd_add
  1703. return ckd_add(ip, *ip, j);
  1704. #else
  1705. register int const i = *ip;
  1706. /*
  1707. ** If i >= 0 there can only be overflow if i + j > INT_MAX
  1708. ** or if j > INT_MAX - i; given i >= 0, INT_MAX - i cannot overflow.
  1709. ** If i < 0 there can only be overflow if i + j < INT_MIN
  1710. ** or if j < INT_MIN - i; given i < 0, INT_MIN - i cannot overflow.
  1711. */
  1712. if ((i >= 0) ? (j > INT_MAX - i) : (j < INT_MIN - i))
  1713. return true;
  1714. *ip += j;
  1715. return false;
  1716. #endif
  1717. }
  1718. static bool
  1719. increment_overflow32(int_fast32_t *const lp, int const m)
  1720. {
  1721. #ifdef ckd_add
  1722. return ckd_add(lp, *lp, m);
  1723. #else
  1724. register int_fast32_t const l = *lp;
  1725. if ((l >= 0) ? (m > INT_FAST32_MAX - l) : (m < INT_FAST32_MIN - l))
  1726. return true;
  1727. *lp += m;
  1728. return false;
  1729. #endif
  1730. }
  1731. static bool
  1732. increment_overflow_time(time_t *tp, int_fast32_t j)
  1733. {
  1734. #ifdef ckd_add
  1735. return ckd_add(tp, *tp, j);
  1736. #else
  1737. /*
  1738. ** This is like
  1739. ** 'if (! (TIME_T_MIN <= *tp + j && *tp + j <= TIME_T_MAX)) ...',
  1740. ** except that it does the right thing even if *tp + j would overflow.
  1741. */
  1742. if (! (j < 0
  1743. ? (TYPE_SIGNED(time_t) ? TIME_T_MIN - j <= *tp : -1 - j < *tp)
  1744. : *tp <= TIME_T_MAX - j))
  1745. return true;
  1746. *tp += j;
  1747. return false;
  1748. #endif
  1749. }
  1750. static bool
  1751. normalize_overflow(int *const tensptr, int *const unitsptr, const int base)
  1752. {
  1753. register int tensdelta;
  1754. tensdelta = (*unitsptr >= 0) ?
  1755. (*unitsptr / base) :
  1756. (-1 - (-1 - *unitsptr) / base);
  1757. *unitsptr -= tensdelta * base;
  1758. return increment_overflow(tensptr, tensdelta);
  1759. }
  1760. static bool
  1761. normalize_overflow32(int_fast32_t *tensptr, int *unitsptr, int base)
  1762. {
  1763. register int tensdelta;
  1764. tensdelta = (*unitsptr >= 0) ?
  1765. (*unitsptr / base) :
  1766. (-1 - (-1 - *unitsptr) / base);
  1767. *unitsptr -= tensdelta * base;
  1768. return increment_overflow32(tensptr, tensdelta);
  1769. }
  1770. static int
  1771. tmcomp(register const struct tm *const atmp,
  1772. register const struct tm *const btmp)
  1773. {
  1774. register int result;
  1775. if (atmp->tm_year != btmp->tm_year)
  1776. return atmp->tm_year < btmp->tm_year ? -1 : 1;
  1777. if ((result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
  1778. (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
  1779. (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
  1780. (result = (atmp->tm_min - btmp->tm_min)) == 0)
  1781. result = atmp->tm_sec - btmp->tm_sec;
  1782. return result;
  1783. }
  1784. /* Copy to *DEST from *SRC. Copy only the members needed for mktime,
  1785. as other members might not be initialized. */
  1786. static void
  1787. mktmcpy(struct tm *dest, struct tm const *src)
  1788. {
  1789. dest->tm_sec = src->tm_sec;
  1790. dest->tm_min = src->tm_min;
  1791. dest->tm_hour = src->tm_hour;
  1792. dest->tm_mday = src->tm_mday;
  1793. dest->tm_mon = src->tm_mon;
  1794. dest->tm_year = src->tm_year;
  1795. dest->tm_isdst = src->tm_isdst;
  1796. #if defined TM_GMTOFF && ! UNINIT_TRAP
  1797. dest->TM_GMTOFF = src->TM_GMTOFF;
  1798. #endif
  1799. }
  1800. static time_t
  1801. time2sub(struct tm *const tmp,
  1802. struct tm *(*funcp)(struct state const *, time_t const *,
  1803. int_fast32_t, struct tm *),
  1804. struct state const *sp,
  1805. const int_fast32_t offset,
  1806. bool *okayp,
  1807. bool do_norm_secs)
  1808. {
  1809. register int dir;
  1810. register int i, j;
  1811. register int saved_seconds;
  1812. register int_fast32_t li;
  1813. register time_t lo;
  1814. register time_t hi;
  1815. int_fast32_t y;
  1816. time_t newt;
  1817. time_t t;
  1818. struct tm yourtm, mytm;
  1819. *okayp = false;
  1820. mktmcpy(&yourtm, tmp);
  1821. if (do_norm_secs) {
  1822. if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
  1823. SECSPERMIN))
  1824. return WRONG;
  1825. }
  1826. if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
  1827. return WRONG;
  1828. if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
  1829. return WRONG;
  1830. y = yourtm.tm_year;
  1831. if (normalize_overflow32(&y, &yourtm.tm_mon, MONSPERYEAR))
  1832. return WRONG;
  1833. /*
  1834. ** Turn y into an actual year number for now.
  1835. ** It is converted back to an offset from TM_YEAR_BASE later.
  1836. */
  1837. if (increment_overflow32(&y, TM_YEAR_BASE))
  1838. return WRONG;
  1839. while (yourtm.tm_mday <= 0) {
  1840. if (increment_overflow32(&y, -1))
  1841. return WRONG;
  1842. li = y + (1 < yourtm.tm_mon);
  1843. yourtm.tm_mday += year_lengths[isleap(li)];
  1844. }
  1845. while (yourtm.tm_mday > DAYSPERLYEAR) {
  1846. li = y + (1 < yourtm.tm_mon);
  1847. yourtm.tm_mday -= year_lengths[isleap(li)];
  1848. if (increment_overflow32(&y, 1))
  1849. return WRONG;
  1850. }
  1851. for ( ; ; ) {
  1852. i = mon_lengths[isleap(y)][yourtm.tm_mon];
  1853. if (yourtm.tm_mday <= i)
  1854. break;
  1855. yourtm.tm_mday -= i;
  1856. if (++yourtm.tm_mon >= MONSPERYEAR) {
  1857. yourtm.tm_mon = 0;
  1858. if (increment_overflow32(&y, 1))
  1859. return WRONG;
  1860. }
  1861. }
  1862. #ifdef ckd_add
  1863. if (ckd_add(&yourtm.tm_year, y, -TM_YEAR_BASE))
  1864. return WRONG;
  1865. #else
  1866. if (increment_overflow32(&y, -TM_YEAR_BASE))
  1867. return WRONG;
  1868. if (! (INT_MIN <= y && y <= INT_MAX))
  1869. return WRONG;
  1870. yourtm.tm_year = y;
  1871. #endif
  1872. if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
  1873. saved_seconds = 0;
  1874. else if (yourtm.tm_year < EPOCH_YEAR - TM_YEAR_BASE) {
  1875. /*
  1876. ** We can't set tm_sec to 0, because that might push the
  1877. ** time below the minimum representable time.
  1878. ** Set tm_sec to 59 instead.
  1879. ** This assumes that the minimum representable time is
  1880. ** not in the same minute that a leap second was deleted from,
  1881. ** which is a safer assumption than using 58 would be.
  1882. */
  1883. if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
  1884. return WRONG;
  1885. saved_seconds = yourtm.tm_sec;
  1886. yourtm.tm_sec = SECSPERMIN - 1;
  1887. } else {
  1888. saved_seconds = yourtm.tm_sec;
  1889. yourtm.tm_sec = 0;
  1890. }
  1891. /*
  1892. ** Do a binary search (this works whatever time_t's type is).
  1893. */
  1894. lo = TIME_T_MIN;
  1895. hi = TIME_T_MAX;
  1896. for ( ; ; ) {
  1897. t = lo / 2 + hi / 2;
  1898. if (t < lo)
  1899. t = lo;
  1900. else if (t > hi)
  1901. t = hi;
  1902. if (! funcp(sp, &t, offset, &mytm)) {
  1903. /*
  1904. ** Assume that t is too extreme to be represented in
  1905. ** a struct tm; arrange things so that it is less
  1906. ** extreme on the next pass.
  1907. */
  1908. dir = (t > 0) ? 1 : -1;
  1909. } else dir = tmcomp(&mytm, &yourtm);
  1910. if (dir != 0) {
  1911. if (t == lo) {
  1912. if (t == TIME_T_MAX)
  1913. return WRONG;
  1914. ++t;
  1915. ++lo;
  1916. } else if (t == hi) {
  1917. if (t == TIME_T_MIN)
  1918. return WRONG;
  1919. --t;
  1920. --hi;
  1921. }
  1922. if (lo > hi)
  1923. return WRONG;
  1924. if (dir > 0)
  1925. hi = t;
  1926. else lo = t;
  1927. continue;
  1928. }
  1929. #if defined TM_GMTOFF && ! UNINIT_TRAP
  1930. if (mytm.TM_GMTOFF != yourtm.TM_GMTOFF
  1931. && (yourtm.TM_GMTOFF < 0
  1932. ? (-SECSPERDAY <= yourtm.TM_GMTOFF
  1933. && (mytm.TM_GMTOFF <=
  1934. (min(INT_FAST32_MAX, LONG_MAX)
  1935. + yourtm.TM_GMTOFF)))
  1936. : (yourtm.TM_GMTOFF <= SECSPERDAY
  1937. && ((max(INT_FAST32_MIN, LONG_MIN)
  1938. + yourtm.TM_GMTOFF)
  1939. <= mytm.TM_GMTOFF)))) {
  1940. /* MYTM matches YOURTM except with the wrong UT offset.
  1941. YOURTM.TM_GMTOFF is plausible, so try it instead.
  1942. It's OK if YOURTM.TM_GMTOFF contains uninitialized data,
  1943. since the guess gets checked. */
  1944. time_t altt = t;
  1945. int_fast32_t diff = mytm.TM_GMTOFF - yourtm.TM_GMTOFF;
  1946. if (!increment_overflow_time(&altt, diff)) {
  1947. struct tm alttm;
  1948. if (funcp(sp, &altt, offset, &alttm)
  1949. && alttm.tm_isdst == mytm.tm_isdst
  1950. && alttm.TM_GMTOFF == yourtm.TM_GMTOFF
  1951. && tmcomp(&alttm, &yourtm) == 0) {
  1952. t = altt;
  1953. mytm = alttm;
  1954. }
  1955. }
  1956. }
  1957. #endif
  1958. if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
  1959. break;
  1960. /*
  1961. ** Right time, wrong type.
  1962. ** Hunt for right time, right type.
  1963. ** It's okay to guess wrong since the guess
  1964. ** gets checked.
  1965. */
  1966. if (sp == NULL)
  1967. return WRONG;
  1968. for (i = sp->typecnt - 1; i >= 0; --i) {
  1969. if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
  1970. continue;
  1971. for (j = sp->typecnt - 1; j >= 0; --j) {
  1972. if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
  1973. continue;
  1974. if (ttunspecified(sp, j))
  1975. continue;
  1976. newt = (t + sp->ttis[j].tt_utoff
  1977. - sp->ttis[i].tt_utoff);
  1978. if (! funcp(sp, &newt, offset, &mytm))
  1979. continue;
  1980. if (tmcomp(&mytm, &yourtm) != 0)
  1981. continue;
  1982. if (mytm.tm_isdst != yourtm.tm_isdst)
  1983. continue;
  1984. /*
  1985. ** We have a match.
  1986. */
  1987. t = newt;
  1988. goto label;
  1989. }
  1990. }
  1991. return WRONG;
  1992. }
  1993. label:
  1994. newt = t + saved_seconds;
  1995. if ((newt < t) != (saved_seconds < 0))
  1996. return WRONG;
  1997. t = newt;
  1998. if (funcp(sp, &t, offset, tmp))
  1999. *okayp = true;
  2000. return t;
  2001. }
  2002. static time_t
  2003. time2(struct tm * const tmp,
  2004. struct tm *(*funcp)(struct state const *, time_t const *,
  2005. int_fast32_t, struct tm *),
  2006. struct state const *sp,
  2007. const int_fast32_t offset,
  2008. bool *okayp)
  2009. {
  2010. time_t t;
  2011. /*
  2012. ** First try without normalization of seconds
  2013. ** (in case tm_sec contains a value associated with a leap second).
  2014. ** If that fails, try with normalization of seconds.
  2015. */
  2016. t = time2sub(tmp, funcp, sp, offset, okayp, false);
  2017. return *okayp ? t : time2sub(tmp, funcp, sp, offset, okayp, true);
  2018. }
  2019. static time_t
  2020. time1(struct tm *const tmp,
  2021. struct tm *(*funcp)(struct state const *, time_t const *,
  2022. int_fast32_t, struct tm *),
  2023. struct state const *sp,
  2024. const int_fast32_t offset)
  2025. {
  2026. register time_t t;
  2027. register int samei, otheri;
  2028. register int sameind, otherind;
  2029. register int i;
  2030. register int nseen;
  2031. char seen[TZ_MAX_TYPES];
  2032. unsigned char types[TZ_MAX_TYPES];
  2033. bool okay;
  2034. if (tmp == NULL) {
  2035. errno = EINVAL;
  2036. return WRONG;
  2037. }
  2038. if (tmp->tm_isdst > 1)
  2039. tmp->tm_isdst = 1;
  2040. t = time2(tmp, funcp, sp, offset, &okay);
  2041. if (okay)
  2042. return t;
  2043. if (tmp->tm_isdst < 0)
  2044. #ifdef PCTS
  2045. /*
  2046. ** POSIX Conformance Test Suite code courtesy Grant Sullivan.
  2047. */
  2048. tmp->tm_isdst = 0; /* reset to std and try again */
  2049. #else
  2050. return t;
  2051. #endif /* !defined PCTS */
  2052. /*
  2053. ** We're supposed to assume that somebody took a time of one type
  2054. ** and did some math on it that yielded a "struct tm" that's bad.
  2055. ** We try to divine the type they started from and adjust to the
  2056. ** type they need.
  2057. */
  2058. if (sp == NULL)
  2059. return WRONG;
  2060. for (i = 0; i < sp->typecnt; ++i)
  2061. seen[i] = false;
  2062. nseen = 0;
  2063. for (i = sp->timecnt - 1; i >= 0; --i)
  2064. if (!seen[sp->types[i]] && !ttunspecified(sp, sp->types[i])) {
  2065. seen[sp->types[i]] = true;
  2066. types[nseen++] = sp->types[i];
  2067. }
  2068. for (sameind = 0; sameind < nseen; ++sameind) {
  2069. samei = types[sameind];
  2070. if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
  2071. continue;
  2072. for (otherind = 0; otherind < nseen; ++otherind) {
  2073. otheri = types[otherind];
  2074. if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
  2075. continue;
  2076. tmp->tm_sec += (sp->ttis[otheri].tt_utoff
  2077. - sp->ttis[samei].tt_utoff);
  2078. tmp->tm_isdst = !tmp->tm_isdst;
  2079. t = time2(tmp, funcp, sp, offset, &okay);
  2080. if (okay)
  2081. return t;
  2082. tmp->tm_sec -= (sp->ttis[otheri].tt_utoff
  2083. - sp->ttis[samei].tt_utoff);
  2084. tmp->tm_isdst = !tmp->tm_isdst;
  2085. }
  2086. }
  2087. return WRONG;
  2088. }
  2089. static time_t
  2090. mktime_tzname(struct state *sp, struct tm *tmp, bool setname)
  2091. {
  2092. if (sp)
  2093. return time1(tmp, localsub, sp, setname);
  2094. else {
  2095. gmtcheck();
  2096. return time1(tmp, gmtsub, gmtptr, 0);
  2097. }
  2098. }
  2099. #if NETBSD_INSPIRED
  2100. time_t
  2101. mktime_z(struct state *restrict sp, struct tm *restrict tmp)
  2102. {
  2103. return mktime_tzname(sp, tmp, false);
  2104. }
  2105. #endif
  2106. time_t
  2107. mktime(struct tm *tmp)
  2108. {
  2109. time_t t;
  2110. int err = lock();
  2111. if (err) {
  2112. errno = err;
  2113. return -1;
  2114. }
  2115. tzset_unlocked();
  2116. t = mktime_tzname(lclptr, tmp, true);
  2117. unlock();
  2118. return t;
  2119. }
  2120. #if STD_INSPIRED
  2121. /* This function is obsolescent and may disapper in future releases.
  2122. Callers can instead use mktime. */
  2123. time_t
  2124. timelocal(struct tm *tmp)
  2125. {
  2126. if (tmp != NULL)
  2127. tmp->tm_isdst = -1; /* in case it wasn't initialized */
  2128. return mktime(tmp);
  2129. }
  2130. #else
  2131. static
  2132. #endif
  2133. /* This function is obsolescent and may disapper in future releases.
  2134. Callers can instead use mktime_z with a fixed-offset zone. */
  2135. time_t
  2136. timeoff(struct tm *tmp, long offset)
  2137. {
  2138. if (tmp)
  2139. tmp->tm_isdst = 0;
  2140. gmtcheck();
  2141. return time1(tmp, gmtsub, gmtptr, offset);
  2142. }
  2143. time_t
  2144. timegm(struct tm *tmp)
  2145. {
  2146. time_t t;
  2147. struct tm tmcpy;
  2148. mktmcpy(&tmcpy, tmp);
  2149. tmcpy.tm_wday = -1;
  2150. t = timeoff(&tmcpy, 0);
  2151. if (0 <= tmcpy.tm_wday)
  2152. *tmp = tmcpy;
  2153. return t;
  2154. }
  2155. static int_fast32_t
  2156. leapcorr(struct state const *sp, time_t t)
  2157. {
  2158. register struct lsinfo const * lp;
  2159. register int i;
  2160. i = sp->leapcnt;
  2161. while (--i >= 0) {
  2162. lp = &sp->lsis[i];
  2163. if (t >= lp->ls_trans)
  2164. return lp->ls_corr;
  2165. }
  2166. return 0;
  2167. }
  2168. /*
  2169. ** XXX--is the below the right way to conditionalize??
  2170. */
  2171. #if STD_INSPIRED
  2172. /* NETBSD_INSPIRED_EXTERN functions are exported to callers if
  2173. NETBSD_INSPIRED is defined, and are private otherwise. */
  2174. # if NETBSD_INSPIRED
  2175. # define NETBSD_INSPIRED_EXTERN
  2176. # else
  2177. # define NETBSD_INSPIRED_EXTERN static
  2178. # endif
  2179. /*
  2180. ** IEEE Std 1003.1 (POSIX) says that 536457599
  2181. ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
  2182. ** is not the case if we are accounting for leap seconds.
  2183. ** So, we provide the following conversion routines for use
  2184. ** when exchanging timestamps with POSIX conforming systems.
  2185. */
  2186. NETBSD_INSPIRED_EXTERN time_t
  2187. time2posix_z(struct state *sp, time_t t)
  2188. {
  2189. return t - leapcorr(sp, t);
  2190. }
  2191. time_t
  2192. time2posix(time_t t)
  2193. {
  2194. int err = lock();
  2195. if (err) {
  2196. errno = err;
  2197. return -1;
  2198. }
  2199. if (!lcl_is_set)
  2200. tzset_unlocked();
  2201. if (lclptr)
  2202. t = time2posix_z(lclptr, t);
  2203. unlock();
  2204. return t;
  2205. }
  2206. NETBSD_INSPIRED_EXTERN time_t
  2207. posix2time_z(struct state *sp, time_t t)
  2208. {
  2209. time_t x;
  2210. time_t y;
  2211. /*
  2212. ** For a positive leap second hit, the result
  2213. ** is not unique. For a negative leap second
  2214. ** hit, the corresponding time doesn't exist,
  2215. ** so we return an adjacent second.
  2216. */
  2217. x = t + leapcorr(sp, t);
  2218. y = x - leapcorr(sp, x);
  2219. if (y < t) {
  2220. do {
  2221. x++;
  2222. y = x - leapcorr(sp, x);
  2223. } while (y < t);
  2224. x -= y != t;
  2225. } else if (y > t) {
  2226. do {
  2227. --x;
  2228. y = x - leapcorr(sp, x);
  2229. } while (y > t);
  2230. x += y != t;
  2231. }
  2232. return x;
  2233. }
  2234. time_t
  2235. posix2time(time_t t)
  2236. {
  2237. int err = lock();
  2238. if (err) {
  2239. errno = err;
  2240. return -1;
  2241. }
  2242. if (!lcl_is_set)
  2243. tzset_unlocked();
  2244. if (lclptr)
  2245. t = posix2time_z(lclptr, t);
  2246. unlock();
  2247. return t;
  2248. }
  2249. #endif /* STD_INSPIRED */
  2250. #if TZ_TIME_T
  2251. # if !USG_COMPAT
  2252. # define daylight 0
  2253. # define timezone 0
  2254. # endif
  2255. # if !ALTZONE
  2256. # define altzone 0
  2257. # endif
  2258. /* Convert from the underlying system's time_t to the ersatz time_tz,
  2259. which is called 'time_t' in this file. Typically, this merely
  2260. converts the time's integer width. On some platforms, the system
  2261. time is local time not UT, or uses some epoch other than the POSIX
  2262. epoch.
  2263. Although this code appears to define a function named 'time' that
  2264. returns time_t, the macros in private.h cause this code to actually
  2265. define a function named 'tz_time' that returns tz_time_t. The call
  2266. to sys_time invokes the underlying system's 'time' function. */
  2267. time_t
  2268. time(time_t *p)
  2269. {
  2270. time_t r = sys_time(0);
  2271. if (r != (time_t) -1) {
  2272. int_fast32_t offset = EPOCH_LOCAL ? (daylight ? timezone : altzone) : 0;
  2273. if (increment_overflow32(&offset, -EPOCH_OFFSET)
  2274. || increment_overflow_time(&r, offset)) {
  2275. errno = EOVERFLOW;
  2276. r = -1;
  2277. }
  2278. }
  2279. if (p)
  2280. *p = r;
  2281. return r;
  2282. }
  2283. #endif