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