Replace all casts of NULL to something with NULL.
[dragonfly.git] / lib / libc / stdtime / localtime.c
CommitLineData
984263bc
MD
1/*
2** This file is in the public domain, so clarified as of
0e2a9149 3** 1996-06-05 by Arthur David Olson.
984263bc 4**
0e2a9149 5** @(#)localtime.c 8.9
984263bc 6** $FreeBSD: src/lib/libc/stdtime/localtime.c,v 1.25.2.2 2002/08/13 16:08:07 bmilekic Exp $
0e2a9149 7** $DragonFly: src/lib/libc/stdtime/localtime.c,v 1.7 2008/10/19 20:15:58 swildner Exp $
984263bc
MD
8*/
9
1de703da 10/*
0e2a9149
SW
11** Leap second handling from Bradley White.
12** POSIX-style TZ environment variable handling from Guy Harris.
984263bc
MD
13*/
14
15/*LINTLIBRARY*/
16
17ea2221 17#include "namespace.h"
984263bc
MD
18#include <sys/types.h>
19#include <sys/stat.h>
17ea2221
MD
20
21#include <fcntl.h>
0e2a9149 22#include <float.h> /* for FLT_MAX and DBL_MAX */
8e3e2a8f 23#include <time.h>
17ea2221 24#include <pthread.h>
984263bc 25#include "private.h"
17ea2221
MD
26#include <un-namespace.h>
27
984263bc 28#include "tzfile.h"
17ea2221
MD
29
30#include "libc_private.h"
31
32#define _MUTEX_LOCK(x) if (__isthreaded) _pthread_mutex_lock(x)
33#define _MUTEX_UNLOCK(x) if (__isthreaded) _pthread_mutex_unlock(x)
984263bc 34
390e5ad7
PA
35#define _RWLOCK_RDLOCK(x) \
36 do { \
37 if (__isthreaded) _pthread_rwlock_rdlock(x); \
38 } while (0)
39
40#define _RWLOCK_WRLOCK(x) \
41 do { \
42 if (__isthreaded) _pthread_rwlock_wrlock(x); \
43 } while (0)
44
45#define _RWLOCK_UNLOCK(x) \
46 do { \
47 if (__isthreaded) _pthread_rwlock_unlock(x); \
48 } while (0)
49
0e2a9149
SW
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
984263bc
MD
63/*
64** Someone might make incorrect use of a time zone abbreviation:
65** 1. They might reference tzname[0] before calling tzset (explicitly
66** or implicitly).
67** 2. They might reference tzname[1] before calling tzset (explicitly
68** or implicitly).
69** 3. They might reference tzname[1] after setting to a time zone
70** in which Daylight Saving Time is never observed.
71** 4. They might reference tzname[0] after setting to a time zone
72** in which Standard Time is never observed.
73** 5. They might reference tm.TM_ZONE after calling offtime.
74** What's best to do in the above cases is open to debate;
75** for now, we just set things up so that in any of the five cases
0e2a9149 76** WILDABBR is used. Another possibility: initialize tzname[0] to the
984263bc 77** string "tzname[0] used before set", and similarly for the other cases.
0e2a9149 78** And another: initialize tzname[0] to "ERA", with an explanation in the
984263bc
MD
79** manual page of what this "time zone abbreviation" means (doing this so
80** that tzname[0] has the "normal" length of three characters).
81*/
82#define WILDABBR " "
984263bc 83
0e2a9149 84static char wildabbr[] = WILDABBR;
984263bc 85
949d11f2 86static const char gmt[] = "UTC";
984263bc 87
0e2a9149
SW
88/*
89** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
90** We default to US rules as of 1999-08-17.
91** POSIX 1003.1 section 8.1.1 says that the default DST rules are
92** implementation dependent; for historical reasons, US rules are a
93** common default.
94*/
95#ifndef TZDEFRULESTRING
96#define TZDEFRULESTRING ",M4.1.0,M10.5.0"
97#endif /* !defined TZDEFDST */
98
984263bc 99struct ttinfo { /* time type information */
0e2a9149 100 long tt_gmtoff; /* UTC offset in seconds */
984263bc
MD
101 int tt_isdst; /* used to set tm_isdst */
102 int tt_abbrind; /* abbreviation list index */
103 int tt_ttisstd; /* TRUE if transition is std time */
0e2a9149 104 int tt_ttisgmt; /* TRUE if transition is UTC */
984263bc
MD
105};
106
107struct lsinfo { /* leap second information */
108 time_t ls_trans; /* transition time */
109 long ls_corr; /* correction to apply */
110};
111
112#define BIGGEST(a, b) (((a) > (b)) ? (a) : (b))
113
114#ifdef TZNAME_MAX
115#define MY_TZNAME_MAX TZNAME_MAX
116#endif /* defined TZNAME_MAX */
117#ifndef TZNAME_MAX
118#define MY_TZNAME_MAX 255
119#endif /* !defined TZNAME_MAX */
120
121struct state {
122 int leapcnt;
123 int timecnt;
124 int typecnt;
125 int charcnt;
0e2a9149
SW
126 int goback;
127 int goahead;
984263bc
MD
128 time_t ats[TZ_MAX_TIMES];
129 unsigned char types[TZ_MAX_TIMES];
130 struct ttinfo ttis[TZ_MAX_TYPES];
131 char chars[BIGGEST(BIGGEST(TZ_MAX_CHARS + 1, sizeof gmt),
132 (2 * (MY_TZNAME_MAX + 1)))];
133 struct lsinfo lsis[TZ_MAX_LEAPS];
134};
135
136struct rule {
137 int r_type; /* type of rule--see below */
138 int r_day; /* day number of rule */
139 int r_week; /* week number of rule */
140 int r_mon; /* month number of rule */
141 long r_time; /* transition time of rule */
142};
143
144#define JULIAN_DAY 0 /* Jn - Julian day */
145#define DAY_OF_YEAR 1 /* n - day of year */
146#define MONTH_NTH_DAY_OF_WEEK 2 /* Mm.n.d - month, week, day of week */
147
148/*
149** Prototypes for static functions.
150*/
151
1fccf464 152static long detzcode(const char * codep);
0e2a9149
SW
153static time_t detzcode64(const char * codep);
154static int differ_by_repeat(time_t t1, time_t t0);
1fccf464 155static const char * getzname(const char * strp);
0e2a9149
SW
156static const char * getqzname(const char * strp, const int delim);
157static const char * getnum(const char * strp, int * nump, int min,
158 int max);
1fccf464
SW
159static const char * getsecs(const char * strp, long * secsp);
160static const char * getoffset(const char * strp, long * offsetp);
161static const char * getrule(const char * strp, struct rule * rulep);
162static void gmtload(struct state * sp);
0e2a9149 163static struct tm * gmtsub(const time_t * timep, long offset,
1fccf464 164 struct tm * tmp);
0e2a9149 165static struct tm * localsub(const time_t * timep, long offset,
1fccf464
SW
166 struct tm * tmp);
167static int increment_overflow(int * number, int delta);
0e2a9149
SW
168static int leaps_thru_end_of(int y);
169static int long_increment_overflow(long * number, int delta);
170static int long_normalize_overflow(long * tensptr,
171 int * unitsptr, int base);
1fccf464
SW
172static int normalize_overflow(int * tensptr, int * unitsptr,
173 int base);
174static void settzname(void);
175static time_t time1(struct tm * tmp,
0e2a9149
SW
176 struct tm * (*funcp)(const time_t *,
177 long, struct tm *),
1fccf464
SW
178 long offset);
179static time_t time2(struct tm *tmp,
0e2a9149
SW
180 struct tm * (*funcp)(const time_t *,
181 long, struct tm*),
1fccf464 182 long offset, int * okayp);
0e2a9149
SW
183static time_t time2sub(struct tm *tmp,
184 struct tm * (*funcp)(const time_t *,
185 long, struct tm*),
186 long offset, int * okayp, int do_norm_secs);
187static struct tm * timesub(const time_t * timep, long offset,
1fccf464
SW
188 const struct state * sp, struct tm * tmp);
189static int tmcomp(const struct tm * atmp,
190 const struct tm * btmp);
191static time_t transtime(time_t janfirst, int year,
192 const struct rule * rulep, long offset);
0e2a9149
SW
193static int typesequiv(const struct state * sp, int a, int b);
194static int tzload(const char * name, struct state * sp,
195 int doextend);
1fccf464
SW
196static int tzparse(const char * name, struct state * sp,
197 int lastditch);
984263bc 198
984263bc
MD
199static struct state lclmem;
200static struct state gmtmem;
201#define lclptr (&lclmem)
202#define gmtptr (&gmtmem)
984263bc
MD
203
204#ifndef TZ_STRLEN_MAX
205#define TZ_STRLEN_MAX 255
206#endif /* !defined TZ_STRLEN_MAX */
207
208static char lcl_TZname[TZ_STRLEN_MAX + 1];
209static int lcl_is_set;
210static int gmt_is_set;
390e5ad7 211static pthread_rwlock_t lcl_rwlock = PTHREAD_RWLOCK_INITIALIZER;
17ea2221 212static pthread_mutex_t gmt_mutex = PTHREAD_MUTEX_INITIALIZER;
984263bc
MD
213
214char * tzname[2] = {
215 wildabbr,
216 wildabbr
217};
218
219/*
220** Section 4.12.3 of X3.159-1989 requires that
221** Except for the strftime function, these functions [asctime,
222** ctime, gmtime, localtime] return values in one of two static
223** objects: a broken-down time structure and an array of char.
0e2a9149 224** Thanks to Paul Eggert for noting this.
984263bc
MD
225*/
226
227static struct tm tm;
228
7d013f97
PA
229time_t timezone = 0;
230int daylight = 0;
231
984263bc 232static long
1fccf464 233detzcode(const char * const codep)
984263bc 234{
660c873b
DR
235 long result;
236 int i;
984263bc 237
0e2a9149 238 result = (codep[0] & 0x80) ? ~0L : 0;
984263bc
MD
239 for (i = 0; i < 4; ++i)
240 result = (result << 8) | (codep[i] & 0xff);
241 return result;
242}
243
0e2a9149
SW
244static time_t
245detzcode64(const char * const codep)
246{
247 time_t result;
248 int i;
249
250 result = (codep[0] & 0x80) ? (~(int_fast64_t) 0) : 0;
251 for (i = 0; i < 8; ++i)
252 result = result * 256 + (codep[i] & 0xff);
253 return result;
254}
255
984263bc 256static void
1fccf464 257settzname(void)
984263bc 258{
0e2a9149 259 struct state * const sp = lclptr;
660c873b 260 int i;
984263bc
MD
261
262 tzname[0] = wildabbr;
263 tzname[1] = wildabbr;
7d013f97
PA
264 daylight = 0;
265 timezone = 0;
a14127aa 266
984263bc 267 for (i = 0; i < sp->typecnt; ++i) {
660c873b 268 const struct ttinfo * const ttisp = &sp->ttis[i];
984263bc
MD
269
270 tzname[ttisp->tt_isdst] =
271 &sp->chars[ttisp->tt_abbrind];
7d013f97
PA
272 if (ttisp->tt_isdst)
273 daylight = 1;
274 if (i == 0 || !ttisp->tt_isdst)
275 timezone = -(ttisp->tt_gmtoff);
984263bc
MD
276 }
277 /*
278 ** And to get the latest zone names into tzname. . .
279 */
280 for (i = 0; i < sp->timecnt; ++i) {
660c873b 281 const struct ttinfo * const ttisp =
984263bc
MD
282 &sp->ttis[
283 sp->types[i]];
284
285 tzname[ttisp->tt_isdst] =
286 &sp->chars[ttisp->tt_abbrind];
287 }
0e2a9149
SW
288 /*
289 ** Finally, scrub the abbreviations.
290 ** First, replace bogus characters.
291 */
292 for (i = 0; i < sp->charcnt; ++i)
293 if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
294 sp->chars[i] = TZ_ABBR_ERR_CHAR;
295 /*
296 ** Second, truncate long abbreviations.
297 */
298 for (i = 0; i < sp->typecnt; ++i) {
299 const struct ttinfo * const ttisp = &sp->ttis[i];
300 char * cp = &sp->chars[ttisp->tt_abbrind];
301
302 if (strlen(cp) > TZ_ABBR_MAX_LEN &&
303 strcmp(cp, GRANDPARENTED) != 0)
304 *(cp + TZ_ABBR_MAX_LEN) = '\0';
305 }
306}
307
308static int
309differ_by_repeat(const time_t t1, const time_t t0)
310{
311 if (TYPE_INTEGRAL(time_t) &&
312 TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
313 return 0;
314 return t1 - t0 == SECSPERREPEAT;
984263bc
MD
315}
316
317static int
0e2a9149 318tzload(const char *name, struct state * const sp, const int doextend)
984263bc 319{
0e2a9149
SW
320 const char * p;
321 int i;
322 int fid;
323 int stored;
324 int nread;
325 union {
326 struct tzhead tzhead;
327 char buf[2 * sizeof(struct tzhead) +
328 2 * sizeof *sp +
329 4 * TZ_MAX_TIMES];
330 } u;
984263bc
MD
331
332 /* XXX The following is from OpenBSD, and I'm not sure it is correct */
333 if (name != NULL && issetugid() != 0)
334 if ((name[0] == ':' && name[1] == '/') ||
335 name[0] == '/' || strchr(name, '.'))
336 name = NULL;
337 if (name == NULL && (name = TZDEFAULT) == NULL)
338 return -1;
339 {
660c873b 340 int doaccess;
984263bc
MD
341 struct stat stab;
342 /*
343 ** Section 4.9.1 of the C standard says that
344 ** "FILENAME_MAX expands to an integral constant expression
345 ** that is the size needed for an array of char large enough
346 ** to hold the longest file name string that the implementation
347 ** guarantees can be opened."
348 */
349 char fullname[FILENAME_MAX + 1];
350
351 if (name[0] == ':')
352 ++name;
353 doaccess = name[0] == '/';
354 if (!doaccess) {
355 if ((p = TZDIR) == NULL)
356 return -1;
357 if ((strlen(p) + 1 + strlen(name) + 1) >= sizeof fullname)
358 return -1;
1fccf464
SW
359 strcpy(fullname, p);
360 strcat(fullname, "/");
361 strcat(fullname, name);
984263bc
MD
362 /*
363 ** Set doaccess if '.' (as in "../") shows up in name.
364 */
365 if (strchr(name, '.') != NULL)
366 doaccess = TRUE;
367 name = fullname;
368 }
369 if (doaccess && access(name, R_OK) != 0)
0e2a9149 370 return -1;
a14127aa 371 if ((fid = _open(name, O_RDONLY)) == -1)
984263bc 372 return -1;
17ea2221 373 if ((_fstat(fid, &stab) < 0) || !S_ISREG(stab.st_mode)) {
984263bc
MD
374 _close(fid);
375 return -1;
376 }
377 }
0e2a9149
SW
378 nread = read(fid, u.buf, sizeof u.buf);
379 if (close(fid) < 0 || nread <= 0)
380 return -1;
381 for (stored = 4; stored <= 8; stored *= 2) {
984263bc
MD
382 int ttisstdcnt;
383 int ttisgmtcnt;
384
0e2a9149
SW
385 ttisstdcnt = (int) detzcode(u.tzhead.tzh_ttisstdcnt);
386 ttisgmtcnt = (int) detzcode(u.tzhead.tzh_ttisgmtcnt);
387 sp->leapcnt = (int) detzcode(u.tzhead.tzh_leapcnt);
388 sp->timecnt = (int) detzcode(u.tzhead.tzh_timecnt);
389 sp->typecnt = (int) detzcode(u.tzhead.tzh_typecnt);
390 sp->charcnt = (int) detzcode(u.tzhead.tzh_charcnt);
391 p = u.tzhead.tzh_charcnt + sizeof u.tzhead.tzh_charcnt;
984263bc
MD
392 if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
393 sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
394 sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
395 sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
396 (ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
397 (ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
398 return -1;
0e2a9149
SW
399 if (nread - (p - u.buf) <
400 sp->timecnt * stored + /* ats */
984263bc 401 sp->timecnt + /* types */
0e2a9149 402 sp->typecnt * 6 + /* ttinfos */
984263bc 403 sp->charcnt + /* chars */
0e2a9149 404 sp->leapcnt * (stored + 4) + /* lsinfos */
984263bc
MD
405 ttisstdcnt + /* ttisstds */
406 ttisgmtcnt) /* ttisgmts */
407 return -1;
408 for (i = 0; i < sp->timecnt; ++i) {
0e2a9149
SW
409 sp->ats[i] = (stored == 4) ?
410 detzcode(p) : detzcode64(p);
411 p += stored;
984263bc
MD
412 }
413 for (i = 0; i < sp->timecnt; ++i) {
414 sp->types[i] = (unsigned char) *p++;
415 if (sp->types[i] >= sp->typecnt)
416 return -1;
417 }
418 for (i = 0; i < sp->typecnt; ++i) {
660c873b 419 struct ttinfo * ttisp;
984263bc
MD
420
421 ttisp = &sp->ttis[i];
422 ttisp->tt_gmtoff = detzcode(p);
423 p += 4;
424 ttisp->tt_isdst = (unsigned char) *p++;
425 if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
426 return -1;
427 ttisp->tt_abbrind = (unsigned char) *p++;
428 if (ttisp->tt_abbrind < 0 ||
429 ttisp->tt_abbrind > sp->charcnt)
430 return -1;
431 }
432 for (i = 0; i < sp->charcnt; ++i)
433 sp->chars[i] = *p++;
434 sp->chars[i] = '\0'; /* ensure '\0' at end */
435 for (i = 0; i < sp->leapcnt; ++i) {
660c873b 436 struct lsinfo * lsisp;
984263bc
MD
437
438 lsisp = &sp->lsis[i];
0e2a9149
SW
439 lsisp->ls_trans = (stored == 4) ?
440 detzcode(p) : detzcode64(p);
441 p += stored;
984263bc
MD
442 lsisp->ls_corr = detzcode(p);
443 p += 4;
444 }
445 for (i = 0; i < sp->typecnt; ++i) {
660c873b 446 struct ttinfo * ttisp;
984263bc
MD
447
448 ttisp = &sp->ttis[i];
449 if (ttisstdcnt == 0)
450 ttisp->tt_ttisstd = FALSE;
451 else {
452 ttisp->tt_ttisstd = *p++;
453 if (ttisp->tt_ttisstd != TRUE &&
454 ttisp->tt_ttisstd != FALSE)
455 return -1;
456 }
457 }
458 for (i = 0; i < sp->typecnt; ++i) {
660c873b 459 struct ttinfo * ttisp;
984263bc
MD
460
461 ttisp = &sp->ttis[i];
462 if (ttisgmtcnt == 0)
463 ttisp->tt_ttisgmt = FALSE;
464 else {
465 ttisp->tt_ttisgmt = *p++;
466 if (ttisp->tt_ttisgmt != TRUE &&
467 ttisp->tt_ttisgmt != FALSE)
468 return -1;
469 }
470 }
0e2a9149
SW
471 /*
472 ** Out-of-sort ats should mean we're running on a
473 ** signed time_t system but using a data file with
474 ** unsigned values (or vice versa).
475 */
476 for (i = 0; i < sp->timecnt - 2; ++i)
477 if (sp->ats[i] > sp->ats[i + 1]) {
478 ++i;
479 if (TYPE_SIGNED(time_t)) {
480 /*
481 ** Ignore the end (easy).
482 */
483 sp->timecnt = i;
484 } else {
485 /*
486 ** Ignore the beginning (harder).
487 */
488 int j;
489
490 for (j = 0; j + i < sp->timecnt; ++j) {
491 sp->ats[j] = sp->ats[j + i];
492 sp->types[j] = sp->types[j + i];
493 }
494 sp->timecnt = j;
495 }
496 break;
497 }
498 /*
499 ** If this is an old file, we're done.
500 */
501 if (u.tzhead.tzh_version[0] == '\0')
502 break;
503 nread -= p - u.buf;
504 for (i = 0; i < nread; ++i)
505 u.buf[i] = p[i];
506 /*
507 ** If this is a narrow integer time_t system, we're done.
508 */
509 if (stored >= (int) sizeof(time_t) && TYPE_INTEGRAL(time_t))
510 break;
511 }
512 if (doextend && nread > 2 &&
513 u.buf[0] == '\n' && u.buf[nread - 1] == '\n' &&
514 sp->typecnt + 2 <= TZ_MAX_TYPES) {
515 struct state ts;
516 int result;
517
518 u.buf[nread - 1] = '\0';
519 result = tzparse(&u.buf[1], &ts, FALSE);
520 if (result == 0 && ts.typecnt == 2 &&
521 sp->charcnt + ts.charcnt <= TZ_MAX_CHARS) {
522 for (i = 0; i < 2; ++i)
523 ts.ttis[i].tt_abbrind +=
524 sp->charcnt;
525 for (i = 0; i < ts.charcnt; ++i)
526 sp->chars[sp->charcnt++] =
527 ts.chars[i];
528 i = 0;
529 while (i < ts.timecnt &&
530 ts.ats[i] <=
531 sp->ats[sp->timecnt - 1])
532 ++i;
533 while (i < ts.timecnt &&
534 sp->timecnt < TZ_MAX_TIMES) {
535 sp->ats[sp->timecnt] =
536 ts.ats[i];
537 sp->types[sp->timecnt] =
538 sp->typecnt +
539 ts.types[i];
540 ++sp->timecnt;
541 ++i;
542 }
543 sp->ttis[sp->typecnt++] = ts.ttis[0];
544 sp->ttis[sp->typecnt++] = ts.ttis[1];
545 }
546 }
547 sp->goback = sp->goahead = FALSE;
548 if (sp->timecnt > 1) {
549 for (i = 1; i < sp->timecnt; ++i)
550 if (typesequiv(sp, sp->types[i], sp->types[0]) &&
551 differ_by_repeat(sp->ats[i], sp->ats[0])) {
552 sp->goback = TRUE;
553 break;
554 }
555 for (i = sp->timecnt - 2; i >= 0; --i)
556 if (typesequiv(sp, sp->types[sp->timecnt - 1],
557 sp->types[i]) &&
558 differ_by_repeat(sp->ats[sp->timecnt - 1],
559 sp->ats[i])) {
560 sp->goahead = TRUE;
561 break;
562 }
984263bc
MD
563 }
564 return 0;
565}
566
0e2a9149
SW
567static int
568typesequiv(const struct state * const sp, const int a, const int b)
569{
570 int result;
571
572 if (sp == NULL ||
573 a < 0 || a >= sp->typecnt ||
574 b < 0 || b >= sp->typecnt)
575 result = FALSE;
576 else {
577 const struct ttinfo * ap = &sp->ttis[a];
578 const struct ttinfo * bp = &sp->ttis[b];
579 result = ap->tt_gmtoff == bp->tt_gmtoff &&
580 ap->tt_isdst == bp->tt_isdst &&
581 ap->tt_ttisstd == bp->tt_ttisstd &&
582 ap->tt_ttisgmt == bp->tt_ttisgmt &&
583 strcmp(&sp->chars[ap->tt_abbrind],
584 &sp->chars[bp->tt_abbrind]) == 0;
585 }
586 return result;
587}
588
984263bc
MD
589static const int mon_lengths[2][MONSPERYEAR] = {
590 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
591 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
592};
593
594static const int year_lengths[2] = {
595 DAYSPERNYEAR, DAYSPERLYEAR
596};
597
598/*
599** Given a pointer into a time zone string, scan until a character that is not
0e2a9149 600** a valid character in a zone name is found. Return a pointer to that
984263bc
MD
601** character.
602*/
603
604static const char *
1fccf464 605getzname(const char *strp)
984263bc 606{
660c873b 607 char c;
984263bc
MD
608
609 while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
610 c != '+')
611 ++strp;
612 return strp;
613}
614
0e2a9149
SW
615/*
616** Given a pointer into an extended time zone string, scan until the ending
617** delimiter of the zone name is located. Return a pointer to the delimiter.
618**
619** As with getzname above, the legal character set is actually quite
620** restricted, with other characters producing undefined results.
621** We don't do any checking here; checking is done later in common-case code.
622*/
623
624static const char *
625getqzname(const char *strp, const int delim)
626{
627 int c;
628
629 while ((c = *strp) != '\0' && c != delim)
630 ++strp;
631 return strp;
632}
633
984263bc
MD
634/*
635** Given a pointer into a time zone string, extract a number from that string.
636** Check that the number is within a specified range; if it is not, return
637** NULL.
638** Otherwise, return a pointer to the first character not part of the number.
639*/
640
641static const char *
1fccf464 642getnum(const char *strp, int * const nump, const int min, const int max)
984263bc 643{
660c873b
DR
644 char c;
645 int num;
984263bc
MD
646
647 if (strp == NULL || !is_digit(c = *strp))
648 return NULL;
649 num = 0;
650 do {
651 num = num * 10 + (c - '0');
652 if (num > max)
653 return NULL; /* illegal value */
654 c = *++strp;
655 } while (is_digit(c));
656 if (num < min)
657 return NULL; /* illegal value */
658 *nump = num;
659 return strp;
660}
661
662/*
663** Given a pointer into a time zone string, extract a number of seconds,
664** in hh[:mm[:ss]] form, from the string.
665** If any error occurs, return NULL.
666** Otherwise, return a pointer to the first character not part of the number
667** of seconds.
668*/
669
670static const char *
1fccf464 671getsecs(const char *strp, long * const secsp)
984263bc
MD
672{
673 int num;
674
675 /*
676 ** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
677 ** "M10.4.6/26", which does not conform to Posix,
678 ** but which specifies the equivalent of
679 ** ``02:00 on the first Sunday on or after 23 Oct''.
680 */
681 strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
682 if (strp == NULL)
683 return NULL;
684 *secsp = num * (long) SECSPERHOUR;
685 if (*strp == ':') {
686 ++strp;
687 strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
688 if (strp == NULL)
689 return NULL;
690 *secsp += num * SECSPERMIN;
691 if (*strp == ':') {
692 ++strp;
0e2a9149 693 /* `SECSPERMIN' allows for leap seconds. */
984263bc
MD
694 strp = getnum(strp, &num, 0, SECSPERMIN);
695 if (strp == NULL)
696 return NULL;
697 *secsp += num;
698 }
699 }
700 return strp;
701}
702
703/*
704** Given a pointer into a time zone string, extract an offset, in
705** [+-]hh[:mm[:ss]] form, from the string.
706** If any error occurs, return NULL.
707** Otherwise, return a pointer to the first character not part of the time.
708*/
709
710static const char *
1fccf464 711getoffset(const char *strp, long * const offsetp)
984263bc 712{
660c873b 713 int neg = 0;
984263bc
MD
714
715 if (*strp == '-') {
716 neg = 1;
717 ++strp;
718 } else if (*strp == '+')
719 ++strp;
720 strp = getsecs(strp, offsetp);
721 if (strp == NULL)
722 return NULL; /* illegal time */
723 if (neg)
724 *offsetp = -*offsetp;
725 return strp;
726}
727
728/*
729** Given a pointer into a time zone string, extract a rule in the form
0e2a9149 730** date[/time]. See POSIX section 8 for the format of "date" and "time".
984263bc
MD
731** If a valid rule is not found, return NULL.
732** Otherwise, return a pointer to the first character not part of the rule.
733*/
734
735static const char *
1fccf464 736getrule(const char *strp, struct rule * const rulep)
984263bc
MD
737{
738 if (*strp == 'J') {
739 /*
740 ** Julian day.
741 */
742 rulep->r_type = JULIAN_DAY;
743 ++strp;
744 strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
745 } else if (*strp == 'M') {
746 /*
747 ** Month, week, day.
748 */
749 rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
750 ++strp;
751 strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
752 if (strp == NULL)
753 return NULL;
754 if (*strp++ != '.')
755 return NULL;
756 strp = getnum(strp, &rulep->r_week, 1, 5);
757 if (strp == NULL)
758 return NULL;
759 if (*strp++ != '.')
760 return NULL;
761 strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
762 } else if (is_digit(*strp)) {
763 /*
764 ** Day of year.
765 */
766 rulep->r_type = DAY_OF_YEAR;
767 strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
768 } else return NULL; /* invalid format */
769 if (strp == NULL)
770 return NULL;
771 if (*strp == '/') {
772 /*
773 ** Time specified.
774 */
775 ++strp;
776 strp = getsecs(strp, &rulep->r_time);
777 } else rulep->r_time = 2 * SECSPERHOUR; /* default = 2:00:00 */
778 return strp;
779}
780
781/*
0e2a9149
SW
782** Given the Epoch-relative time of January 1, 00:00:00 UTC, in a year, the
783** year, a rule, and the offset from UTC at the time that rule takes effect,
984263bc
MD
784** calculate the Epoch-relative time that rule takes effect.
785*/
786
787static time_t
1fccf464
SW
788transtime(const time_t janfirst, const int year,
789 const struct rule * const rulep, const long offset)
984263bc 790{
660c873b
DR
791 int leapyear;
792 time_t value;
793 int i;
984263bc
MD
794 int d, m1, yy0, yy1, yy2, dow;
795
796 INITIALIZE(value);
797 leapyear = isleap(year);
798 switch (rulep->r_type) {
799
800 case JULIAN_DAY:
801 /*
802 ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
803 ** years.
804 ** In non-leap years, or if the day number is 59 or less, just
805 ** add SECSPERDAY times the day number-1 to the time of
806 ** January 1, midnight, to get the day.
807 */
808 value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
809 if (leapyear && rulep->r_day >= 60)
810 value += SECSPERDAY;
811 break;
812
813 case DAY_OF_YEAR:
814 /*
815 ** n - day of year.
816 ** Just add SECSPERDAY times the day number to the time of
817 ** January 1, midnight, to get the day.
818 */
819 value = janfirst + rulep->r_day * SECSPERDAY;
820 break;
821
822 case MONTH_NTH_DAY_OF_WEEK:
823 /*
824 ** Mm.n.d - nth "dth day" of month m.
825 */
826 value = janfirst;
827 for (i = 0; i < rulep->r_mon - 1; ++i)
828 value += mon_lengths[leapyear][i] * SECSPERDAY;
829
830 /*
831 ** Use Zeller's Congruence to get day-of-week of first day of
832 ** month.
833 */
834 m1 = (rulep->r_mon + 9) % 12 + 1;
835 yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
836 yy1 = yy0 / 100;
837 yy2 = yy0 % 100;
838 dow = ((26 * m1 - 2) / 10 +
839 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
840 if (dow < 0)
841 dow += DAYSPERWEEK;
842
843 /*
0e2a9149 844 ** "dow" is the day-of-week of the first day of the month. Get
984263bc
MD
845 ** the day-of-month (zero-origin) of the first "dow" day of the
846 ** month.
847 */
848 d = rulep->r_day - dow;
849 if (d < 0)
850 d += DAYSPERWEEK;
851 for (i = 1; i < rulep->r_week; ++i) {
852 if (d + DAYSPERWEEK >=
853 mon_lengths[leapyear][rulep->r_mon - 1])
854 break;
855 d += DAYSPERWEEK;
856 }
857
858 /*
859 ** "d" is the day-of-month (zero-origin) of the day we want.
860 */
861 value += d * SECSPERDAY;
862 break;
863 }
864
865 /*
0e2a9149
SW
866 ** "value" is the Epoch-relative time of 00:00:00 UTC on the day in
867 ** question. To get the Epoch-relative time of the specified local
984263bc 868 ** time on that day, add the transition time and the current offset
0e2a9149 869 ** from UTC.
984263bc
MD
870 */
871 return value + rulep->r_time + offset;
872}
873
874/*
875** Given a POSIX section 8-style TZ string, fill in the rule tables as
876** appropriate.
877*/
878
879static int
1fccf464 880tzparse(const char *name, struct state * const sp, const int lastditch)
984263bc
MD
881{
882 const char * stdname;
883 const char * dstname;
884 size_t stdlen;
885 size_t dstlen;
886 long stdoffset;
887 long dstoffset;
660c873b
DR
888 time_t * atp;
889 unsigned char * typep;
890 char * cp;
891 int load_result;
984263bc
MD
892
893 INITIALIZE(dstname);
894 stdname = name;
895 if (lastditch) {
896 stdlen = strlen(name); /* length of standard zone name */
897 name += stdlen;
898 if (stdlen >= sizeof sp->chars)
899 stdlen = (sizeof sp->chars) - 1;
900 stdoffset = 0;
901 } else {
0e2a9149
SW
902 if (*name == '<') {
903 name++;
904 stdname = name;
905 name = getqzname(name, '>');
906 if (*name != '>')
907 return (-1);
908 stdlen = name - stdname;
909 name++;
910 } else {
911 name = getzname(name);
912 stdlen = name - stdname;
984263bc 913 }
0e2a9149
SW
914 if (*name == '\0')
915 return -1;
916 name = getoffset(name, &stdoffset);
917 if (name == NULL)
918 return -1;
984263bc 919 }
0e2a9149 920 load_result = tzload(TZDEFRULES, sp, FALSE);
984263bc
MD
921 if (load_result != 0)
922 sp->leapcnt = 0; /* so, we're off a little */
923 if (*name != '\0') {
0e2a9149
SW
924 if (*name == '<') {
925 dstname = ++name;
926 name = getqzname(name, '>');
927 if (*name != '>')
928 return -1;
929 dstlen = name - dstname;
930 name++;
931 } else {
932 dstname = name;
933 name = getzname(name);
934 dstlen = name - dstname; /* length of DST zone name */
935 }
984263bc
MD
936 if (*name != '\0' && *name != ',' && *name != ';') {
937 name = getoffset(name, &dstoffset);
938 if (name == NULL)
939 return -1;
940 } else dstoffset = stdoffset - SECSPERHOUR;
0e2a9149
SW
941 if (*name == '\0' && load_result != 0)
942 name = TZDEFRULESTRING;
984263bc
MD
943 if (*name == ',' || *name == ';') {
944 struct rule start;
945 struct rule end;
660c873b
DR
946 int year;
947 time_t janfirst;
984263bc
MD
948 time_t starttime;
949 time_t endtime;
950
951 ++name;
952 if ((name = getrule(name, &start)) == NULL)
953 return -1;
954 if (*name++ != ',')
955 return -1;
956 if ((name = getrule(name, &end)) == NULL)
957 return -1;
958 if (*name != '\0')
959 return -1;
960 sp->typecnt = 2; /* standard time and DST */
961 /*
0e2a9149 962 ** Two transitions per year, from EPOCH_YEAR forward.
984263bc 963 */
984263bc
MD
964 sp->ttis[0].tt_gmtoff = -dstoffset;
965 sp->ttis[0].tt_isdst = 1;
966 sp->ttis[0].tt_abbrind = stdlen + 1;
967 sp->ttis[1].tt_gmtoff = -stdoffset;
968 sp->ttis[1].tt_isdst = 0;
969 sp->ttis[1].tt_abbrind = 0;
970 atp = sp->ats;
971 typep = sp->types;
972 janfirst = 0;
0e2a9149
SW
973 sp->timecnt = 0;
974 for (year = EPOCH_YEAR;
975 sp->timecnt + 2 <= TZ_MAX_TIMES;
976 ++year) {
977 time_t newfirst;
978
984263bc
MD
979 starttime = transtime(janfirst, year, &start,
980 stdoffset);
981 endtime = transtime(janfirst, year, &end,
982 dstoffset);
983 if (starttime > endtime) {
984 *atp++ = endtime;
985 *typep++ = 1; /* DST ends */
986 *atp++ = starttime;
987 *typep++ = 0; /* DST begins */
988 } else {
989 *atp++ = starttime;
990 *typep++ = 0; /* DST begins */
991 *atp++ = endtime;
992 *typep++ = 1; /* DST ends */
993 }
0e2a9149
SW
994 sp->timecnt += 2;
995 newfirst = janfirst;
996 newfirst += year_lengths[isleap(year)] *
984263bc 997 SECSPERDAY;
0e2a9149
SW
998 if (newfirst <= janfirst)
999 break;
1000 janfirst = newfirst;
984263bc
MD
1001 }
1002 } else {
660c873b
DR
1003 long theirstdoffset;
1004 long theirdstoffset;
1005 long theiroffset;
1006 int isdst;
1007 int i;
1008 int j;
984263bc
MD
1009
1010 if (*name != '\0')
1011 return -1;
984263bc
MD
1012 /*
1013 ** Initial values of theirstdoffset and theirdstoffset.
1014 */
1015 theirstdoffset = 0;
1016 for (i = 0; i < sp->timecnt; ++i) {
1017 j = sp->types[i];
1018 if (!sp->ttis[j].tt_isdst) {
1019 theirstdoffset =
1020 -sp->ttis[j].tt_gmtoff;
1021 break;
1022 }
1023 }
1024 theirdstoffset = 0;
1025 for (i = 0; i < sp->timecnt; ++i) {
1026 j = sp->types[i];
1027 if (sp->ttis[j].tt_isdst) {
1028 theirdstoffset =
1029 -sp->ttis[j].tt_gmtoff;
1030 break;
1031 }
1032 }
1033 /*
1034 ** Initially we're assumed to be in standard time.
1035 */
1036 isdst = FALSE;
1037 theiroffset = theirstdoffset;
1038 /*
1039 ** Now juggle transition times and types
1040 ** tracking offsets as you do.
1041 */
1042 for (i = 0; i < sp->timecnt; ++i) {
1043 j = sp->types[i];
1044 sp->types[i] = sp->ttis[j].tt_isdst;
1045 if (sp->ttis[j].tt_ttisgmt) {
1046 /* No adjustment to transition time */
1047 } else {
1048 /*
1049 ** If summer time is in effect, and the
1050 ** transition time was not specified as
1051 ** standard time, add the summer time
1052 ** offset to the transition time;
1053 ** otherwise, add the standard time
1054 ** offset to the transition time.
1055 */
1056 /*
1057 ** Transitions from DST to DDST
1058 ** will effectively disappear since
1059 ** POSIX provides for only one DST
1060 ** offset.
1061 */
1062 if (isdst && !sp->ttis[j].tt_ttisstd) {
1063 sp->ats[i] += dstoffset -
1064 theirdstoffset;
1065 } else {
1066 sp->ats[i] += stdoffset -
1067 theirstdoffset;
1068 }
1069 }
1070 theiroffset = -sp->ttis[j].tt_gmtoff;
1071 if (sp->ttis[j].tt_isdst)
1072 theirdstoffset = theiroffset;
1073 else theirstdoffset = theiroffset;
1074 }
1075 /*
1076 ** Finally, fill in ttis.
1077 ** ttisstd and ttisgmt need not be handled.
1078 */
1079 sp->ttis[0].tt_gmtoff = -stdoffset;
1080 sp->ttis[0].tt_isdst = FALSE;
1081 sp->ttis[0].tt_abbrind = 0;
1082 sp->ttis[1].tt_gmtoff = -dstoffset;
1083 sp->ttis[1].tt_isdst = TRUE;
1084 sp->ttis[1].tt_abbrind = stdlen + 1;
0e2a9149 1085 sp->typecnt = 2;
984263bc
MD
1086 }
1087 } else {
1088 dstlen = 0;
1089 sp->typecnt = 1; /* only standard time */
1090 sp->timecnt = 0;
1091 sp->ttis[0].tt_gmtoff = -stdoffset;
1092 sp->ttis[0].tt_isdst = 0;
1093 sp->ttis[0].tt_abbrind = 0;
1094 }
1095 sp->charcnt = stdlen + 1;
1096 if (dstlen != 0)
1097 sp->charcnt += dstlen + 1;
0e2a9149 1098 if ((size_t) sp->charcnt > sizeof sp->chars)
984263bc
MD
1099 return -1;
1100 cp = sp->chars;
1fccf464 1101 strncpy(cp, stdname, stdlen);
984263bc
MD
1102 cp += stdlen;
1103 *cp++ = '\0';
1104 if (dstlen != 0) {
1fccf464 1105 strncpy(cp, dstname, dstlen);
984263bc
MD
1106 *(cp + dstlen) = '\0';
1107 }
1108 return 0;
1109}
1110
1111static void
1fccf464 1112gmtload(struct state * const sp)
984263bc 1113{
0e2a9149 1114 if (tzload(gmt, sp, TRUE) != 0)
1fccf464 1115 tzparse(gmt, sp, TRUE);
984263bc
MD
1116}
1117
17ea2221 1118static void
390e5ad7 1119tzsetwall_basic(int rdlocked)
984263bc 1120{
390e5ad7
PA
1121 if (!rdlocked)
1122 _RWLOCK_RDLOCK(&lcl_rwlock);
1123 if (lcl_is_set < 0) {
1124 if (!rdlocked)
1125 _RWLOCK_UNLOCK(&lcl_rwlock);
984263bc 1126 return;
390e5ad7
PA
1127 }
1128 _RWLOCK_UNLOCK(&lcl_rwlock);
1129
1130 _RWLOCK_WRLOCK(&lcl_rwlock);
984263bc
MD
1131 lcl_is_set = -1;
1132
2038fb68 1133 if (tzload(NULL, lclptr, TRUE) != 0)
984263bc
MD
1134 gmtload(lclptr);
1135 settzname();
390e5ad7
PA
1136 _RWLOCK_UNLOCK(&lcl_rwlock);
1137
1138 if (rdlocked)
1139 _RWLOCK_RDLOCK(&lcl_rwlock);
984263bc
MD
1140}
1141
984263bc 1142void
1fccf464 1143tzsetwall(void)
984263bc 1144{
390e5ad7 1145 tzsetwall_basic(0);
984263bc 1146}
984263bc 1147
984263bc 1148static void
390e5ad7 1149tzset_basic(int rdlocked)
984263bc 1150{
660c873b 1151 const char * name;
984263bc
MD
1152
1153 name = getenv("TZ");
1154 if (name == NULL) {
390e5ad7 1155 tzsetwall_basic(rdlocked);
984263bc
MD
1156 return;
1157 }
1158
390e5ad7
PA
1159 if (!rdlocked)
1160 _RWLOCK_RDLOCK(&lcl_rwlock);
1161 if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0) {
1162 if (!rdlocked)
1163 _RWLOCK_UNLOCK(&lcl_rwlock);
984263bc 1164 return;
390e5ad7
PA
1165 }
1166 _RWLOCK_UNLOCK(&lcl_rwlock);
1167
1168 _RWLOCK_WRLOCK(&lcl_rwlock);
0e2a9149 1169 lcl_is_set = strlen(name) < sizeof lcl_TZname;
984263bc 1170 if (lcl_is_set)
1fccf464 1171 strcpy(lcl_TZname, name);
984263bc 1172
984263bc
MD
1173 if (*name == '\0') {
1174 /*
1175 ** User wants it fast rather than right.
1176 */
1177 lclptr->leapcnt = 0; /* so, we're off a little */
1178 lclptr->timecnt = 0;
0e2a9149
SW
1179 lclptr->typecnt = 0;
1180 lclptr->ttis[0].tt_isdst = 0;
984263bc
MD
1181 lclptr->ttis[0].tt_gmtoff = 0;
1182 lclptr->ttis[0].tt_abbrind = 0;
1fccf464 1183 strcpy(lclptr->chars, gmt);
0e2a9149 1184 } else if (tzload(name, lclptr, TRUE) != 0)
984263bc 1185 if (name[0] == ':' || tzparse(name, lclptr, FALSE) != 0)
1fccf464 1186 gmtload(lclptr);
984263bc 1187 settzname();
390e5ad7
PA
1188 _RWLOCK_UNLOCK(&lcl_rwlock);
1189
1190 if (rdlocked)
1191 _RWLOCK_RDLOCK(&lcl_rwlock);
984263bc
MD
1192}
1193
984263bc 1194void
17ea2221 1195tzset(void)
984263bc 1196{
390e5ad7 1197 tzset_basic(0);
984263bc 1198}
984263bc
MD
1199
1200/*
1201** The easy way to behave "as if no library function calls" localtime
1202** is to not call it--so we drop its guts into "localsub", which can be
0e2a9149 1203** freely called. (And no, the PANS doesn't require the above behavior--
984263bc
MD
1204** but it *is* desirable.)
1205**
1206** The unused offset argument is for the benefit of mktime variants.
1207*/
1208
1209/*ARGSUSED*/
0e2a9149 1210static struct tm *
1fccf464
SW
1211localsub(const time_t * const timep, const long offset __unused,
1212 struct tm * const tmp)
984263bc 1213{
660c873b
DR
1214 struct state * sp;
1215 const struct ttinfo * ttisp;
1216 int i;
0e2a9149
SW
1217 struct tm * result;
1218 const time_t t = *timep;
984263bc
MD
1219
1220 sp = lclptr;
a14127aa 1221
0e2a9149
SW
1222 if ((sp->goback && t < sp->ats[0]) ||
1223 (sp->goahead && t > sp->ats[sp->timecnt - 1])) {
1224 time_t newt = t;
1225 time_t seconds;
1226 time_t tcycles;
1227 int_fast64_t icycles;
1228
1229 if (t < sp->ats[0])
1230 seconds = sp->ats[0] - t;
1231 else seconds = t - sp->ats[sp->timecnt - 1];
1232 --seconds;
1233 tcycles = seconds / YEARSPERREPEAT / AVGSECSPERYEAR;
1234 ++tcycles;
1235 icycles = tcycles;
1236 if (tcycles - icycles >= 1 || icycles - tcycles >= 1)
1237 return NULL;
1238 seconds = icycles;
1239 seconds *= YEARSPERREPEAT;
1240 seconds *= AVGSECSPERYEAR;
1241 if (t < sp->ats[0])
1242 newt += seconds;
1243 else newt -= seconds;
1244 if (newt < sp->ats[0] ||
1245 newt > sp->ats[sp->timecnt - 1])
1246 return NULL; /* "cannot happen" */
1247 result = localsub(&newt, offset, tmp);
1248 if (result == tmp) {
1249 time_t newy;
1250
1251 newy = tmp->tm_year;
1252 if (t < sp->ats[0])
1253 newy -= icycles * YEARSPERREPEAT;
1254 else newy += icycles * YEARSPERREPEAT;
1255 tmp->tm_year = newy;
1256 if (tmp->tm_year != newy)
1257 return NULL;
1258 }
1259 return result;
1260 }
984263bc
MD
1261 if (sp->timecnt == 0 || t < sp->ats[0]) {
1262 i = 0;
1263 while (sp->ttis[i].tt_isdst)
1264 if (++i >= sp->typecnt) {
1265 i = 0;
1266 break;
1267 }
1268 } else {
0e2a9149
SW
1269 int lo = 1;
1270 int hi = sp->timecnt;
1271
1272 while (lo < hi) {
1273 int mid = (lo + hi) >> 1;
1274
1275 if (t < sp->ats[mid])
1276 hi = mid;
1277 else lo = mid + 1;
1278 }
1279 i = (int) sp->types[lo - 1];
984263bc
MD
1280 }
1281 ttisp = &sp->ttis[i];
1282 /*
1283 ** To get (wrong) behavior that's compatible with System V Release 2.0
1284 ** you'd replace the statement below with
1285 ** t += ttisp->tt_gmtoff;
1286 ** timesub(&t, 0L, sp, tmp);
1287 */
0e2a9149 1288 result = timesub(&t, ttisp->tt_gmtoff, sp, tmp);
984263bc
MD
1289 tmp->tm_isdst = ttisp->tt_isdst;
1290 tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
1291#ifdef TM_ZONE
1292 tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1293#endif /* defined TM_ZONE */
0e2a9149 1294 return result;
984263bc
MD
1295}
1296
1297struct tm *
1fccf464 1298localtime_r(const time_t * const timep, struct tm *p_tm)
984263bc 1299{
390e5ad7
PA
1300 _RWLOCK_RDLOCK(&lcl_rwlock);
1301 tzset_basic(1);
984263bc 1302 localsub(timep, 0L, p_tm);
390e5ad7 1303 _RWLOCK_UNLOCK(&lcl_rwlock);
984263bc
MD
1304 return(p_tm);
1305}
1306
1307struct tm *
1fccf464 1308localtime(const time_t * const timep)
984263bc 1309{
17ea2221 1310 static pthread_mutex_t localtime_mutex = PTHREAD_MUTEX_INITIALIZER;
984263bc
MD
1311 static pthread_key_t localtime_key = -1;
1312 struct tm *p_tm;
1313
17ea2221 1314 if (__isthreaded != 0) {
17ea2221 1315 if (localtime_key < 0) {
390e5ad7
PA
1316 _pthread_mutex_lock(&localtime_mutex);
1317 if (localtime_key < 0) {
1318 if (_pthread_key_create(&localtime_key, free) < 0) {
1319 _pthread_mutex_unlock(&localtime_mutex);
1320 return(NULL);
1321 }
17ea2221 1322 }
390e5ad7 1323 _pthread_mutex_unlock(&localtime_mutex);
984263bc 1324 }
17ea2221
MD
1325 p_tm = _pthread_getspecific(localtime_key);
1326 if (p_tm == NULL) {
1327 if ((p_tm = (struct tm *)malloc(sizeof(struct tm)))
1328 == NULL)
1329 return(NULL);
1330 _pthread_setspecific(localtime_key, p_tm);
1331 }
390e5ad7
PA
1332 _RWLOCK_RDLOCK(&lcl_rwlock);
1333 tzset_basic(1);
17ea2221 1334 localsub(timep, 0L, p_tm);
390e5ad7 1335 _RWLOCK_UNLOCK(&lcl_rwlock);
17ea2221
MD
1336 return(p_tm);
1337 } else {
390e5ad7 1338 tzset_basic(0);
17ea2221
MD
1339 localsub(timep, 0L, &tm);
1340 return(&tm);
984263bc 1341 }
984263bc
MD
1342}
1343
1344/*
1345** gmtsub is to gmtime as localsub is to localtime.
1346*/
1347
0e2a9149 1348static struct tm *
1fccf464 1349gmtsub(const time_t * const timep, const long offset, struct tm * const tmp)
984263bc 1350{
0e2a9149
SW
1351 struct tm * result;
1352
984263bc 1353 if (!gmt_is_set) {
390e5ad7
PA
1354 _MUTEX_LOCK(&gmt_mutex);
1355 if (!gmt_is_set) {
1356 gmtload(gmtptr);
1357 gmt_is_set = TRUE;
1358 }
1359 _MUTEX_UNLOCK(&gmt_mutex);
984263bc 1360 }
0e2a9149 1361 result = timesub(timep, offset, gmtptr, tmp);
984263bc
MD
1362#ifdef TM_ZONE
1363 /*
1364 ** Could get fancy here and deliver something such as
0e2a9149 1365 ** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
984263bc
MD
1366 ** but this is no time for a treasure hunt.
1367 */
1368 if (offset != 0)
1369 tmp->TM_ZONE = wildabbr;
a14127aa 1370 else
984263bc 1371 tmp->TM_ZONE = gmtptr->chars;
984263bc 1372#endif /* defined TM_ZONE */
0e2a9149 1373 return result;
984263bc
MD
1374}
1375
1376struct tm *
1fccf464 1377gmtime(const time_t * const timep)
984263bc 1378{
17ea2221 1379 static pthread_mutex_t gmtime_mutex = PTHREAD_MUTEX_INITIALIZER;
984263bc
MD
1380 static pthread_key_t gmtime_key = -1;
1381 struct tm *p_tm;
1382
17ea2221 1383 if (__isthreaded != 0) {
17ea2221 1384 if (gmtime_key < 0) {
390e5ad7
PA
1385 _pthread_mutex_lock(&gmtime_mutex);
1386 if (gmtime_key < 0) {
1387 if (_pthread_key_create(&gmtime_key, free) < 0) {
1388 _pthread_mutex_unlock(&gmtime_mutex);
1389 return(NULL);
1390 }
0e2a9149 1391 }
390e5ad7 1392 _pthread_mutex_unlock(&gmtime_mutex);
984263bc 1393 }
17ea2221
MD
1394 /*
1395 * Changed to follow POSIX.1 threads standard, which
1396 * is what BSD currently has.
1397 */
1398 if ((p_tm = _pthread_getspecific(gmtime_key)) == NULL) {
1399 if ((p_tm = (struct tm *)malloc(sizeof(struct tm)))
1400 == NULL) {
1401 return(NULL);
1402 }
1403 _pthread_setspecific(gmtime_key, p_tm);
984263bc 1404 }
0e2a9149
SW
1405 return gmtsub(timep, 0L, p_tm);
1406 } else {
1407 return gmtsub(timep, 0L, &tm);
984263bc 1408 }
984263bc
MD
1409}
1410
1411struct tm *
0e2a9149 1412gmtime_r(const time_t * timep, struct tm * tmp)
984263bc 1413{
0e2a9149 1414 return gmtsub(timep, 0L, tmp);
984263bc
MD
1415}
1416
984263bc 1417struct tm *
1fccf464 1418offtime(const time_t * const timep, const long offset)
984263bc 1419{
0e2a9149 1420 return gmtsub(timep, offset, &tm);
984263bc
MD
1421}
1422
0e2a9149
SW
1423/*
1424** Return the number of leap years through the end of the given year
1425** where, to make the math easy, the answer for year zero is defined as zero.
1426*/
1427
1428static int
1429leaps_thru_end_of(const int y)
1430{
1431 return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
1432 -(leaps_thru_end_of(-(y + 1)) + 1);
1433}
1434
1435static struct tm *
1fccf464
SW
1436timesub(const time_t * const timep, const long offset,
1437 const struct state * const sp, struct tm * const tmp)
984263bc 1438{
660c873b 1439 const struct lsinfo * lp;
0e2a9149
SW
1440 time_t tdays;
1441 int idays; /* unsigned would be so 2003 */
660c873b
DR
1442 long rem;
1443 int y;
1444 int yleap;
1445 const int * ip;
1446 long corr;
1447 int hit;
1448 int i;
984263bc
MD
1449
1450 corr = 0;
1451 hit = 0;
984263bc 1452 i = sp->leapcnt;
a14127aa 1453
984263bc
MD
1454 while (--i >= 0) {
1455 lp = &sp->lsis[i];
1456 if (*timep >= lp->ls_trans) {
1457 if (*timep == lp->ls_trans) {
1458 hit = ((i == 0 && lp->ls_corr > 0) ||
1459 lp->ls_corr > sp->lsis[i - 1].ls_corr);
1460 if (hit)
1461 while (i > 0 &&
1462 sp->lsis[i].ls_trans ==
1463 sp->lsis[i - 1].ls_trans + 1 &&
1464 sp->lsis[i].ls_corr ==
1465 sp->lsis[i - 1].ls_corr + 1) {
1466 ++hit;
1467 --i;
1468 }
1469 }
1470 corr = lp->ls_corr;
1471 break;
1472 }
1473 }
0e2a9149
SW
1474 y = EPOCH_YEAR;
1475 tdays = *timep / SECSPERDAY;
1476 rem = *timep - tdays * SECSPERDAY;
1477 while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
1478 int newy;
1479 time_t tdelta;
1480 int idelta;
1481 int leapdays;
1482
1483 tdelta = tdays / DAYSPERLYEAR;
1484 idelta = tdelta;
1485 if (tdelta - idelta >= 1 || idelta - tdelta >= 1)
1486 return NULL;
1487 if (idelta == 0)
1488 idelta = (tdays < 0) ? -1 : 1;
1489 newy = y;
1490 if (increment_overflow(&newy, idelta))
1491 return NULL;
1492 leapdays = leaps_thru_end_of(newy - 1) -
1493 leaps_thru_end_of(y - 1);
1494 tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
1495 tdays -= leapdays;
1496 y = newy;
984263bc 1497 }
0e2a9149
SW
1498 {
1499 long seconds;
1500
1501 seconds = tdays * SECSPERDAY + 0.5;
1502 tdays = seconds / SECSPERDAY;
1503 rem += seconds - tdays * SECSPERDAY;
1504 }
1505 /*
1506 ** Given the range, we can now fearlessly cast...
1507 */
1508 idays = tdays;
1509 rem += offset - corr;
984263bc
MD
1510 while (rem < 0) {
1511 rem += SECSPERDAY;
0e2a9149 1512 --idays;
984263bc
MD
1513 }
1514 while (rem >= SECSPERDAY) {
1515 rem -= SECSPERDAY;
0e2a9149 1516 ++idays;
984263bc 1517 }
0e2a9149
SW
1518 while (idays < 0) {
1519 if (increment_overflow(&y, -1))
1520 return NULL;
1521 idays += year_lengths[isleap(y)];
1522 }
1523 while (idays >= year_lengths[isleap(y)]) {
1524 idays -= year_lengths[isleap(y)];
1525 if (increment_overflow(&y, 1))
1526 return NULL;
1527 }
1528 tmp->tm_year = y;
1529 if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
1530 return NULL;
1531 tmp->tm_yday = idays;
1532 /*
1533 ** The "extra" mods below avoid overflow problems.
1534 */
1535 tmp->tm_wday = EPOCH_WDAY +
1536 ((y - EPOCH_YEAR) % DAYSPERWEEK) *
1537 (DAYSPERNYEAR % DAYSPERWEEK) +
1538 leaps_thru_end_of(y - 1) -
1539 leaps_thru_end_of(EPOCH_YEAR - 1) +
1540 idays;
1541 tmp->tm_wday %= DAYSPERWEEK;
1542 if (tmp->tm_wday < 0)
1543 tmp->tm_wday += DAYSPERWEEK;
984263bc 1544 tmp->tm_hour = (int) (rem / SECSPERHOUR);
0e2a9149 1545 rem %= SECSPERHOUR;
984263bc
MD
1546 tmp->tm_min = (int) (rem / SECSPERMIN);
1547 /*
1548 ** A positive leap second requires a special
0e2a9149 1549 ** representation. This uses "... ??:59:60" et seq.
984263bc
MD
1550 */
1551 tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
0e2a9149
SW
1552 ip = mon_lengths[isleap(y)];
1553 for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
1554 idays -= ip[tmp->tm_mon];
1555 tmp->tm_mday = (int) (idays + 1);
984263bc
MD
1556 tmp->tm_isdst = 0;
1557#ifdef TM_GMTOFF
1558 tmp->TM_GMTOFF = offset;
1559#endif /* defined TM_GMTOFF */
0e2a9149 1560 return tmp;
984263bc
MD
1561}
1562
1563char *
1fccf464 1564ctime(const time_t * const timep)
984263bc
MD
1565{
1566/*
1567** Section 4.12.3.2 of X3.159-1989 requires that
0e2a9149
SW
1568** The ctime function converts the calendar time pointed to by timer
1569** to local time in the form of a string. It is equivalent to
984263bc
MD
1570** asctime(localtime(timer))
1571*/
1572 return asctime(localtime(timep));
1573}
1574
1575char *
1fccf464 1576ctime_r(const time_t * const timep, char *buf)
984263bc 1577{
0e2a9149
SW
1578 struct tm mytm;
1579 return asctime_r(localtime_r(timep, &mytm), buf);
984263bc
MD
1580}
1581
1582/*
1583** Adapted from code provided by Robert Elz, who writes:
1584** The "best" way to do mktime I think is based on an idea of Bob
1585** Kridle's (so its said...) from a long time ago.
0e2a9149 1586** It does a binary search of the time_t space. Since time_t's are
984263bc
MD
1587** just 32 bits, its a max of 32 iterations (even at 64 bits it
1588** would still be very reasonable).
1589*/
1590
1591#ifndef WRONG
1592#define WRONG (-1)
1593#endif /* !defined WRONG */
1594
1595/*
0e2a9149 1596** Simplified normalize logic courtesy Paul Eggert.
984263bc
MD
1597*/
1598
1599static int
1fccf464 1600increment_overflow(int *number, int delta)
984263bc
MD
1601{
1602 int number0;
1603
1604 number0 = *number;
1605 *number += delta;
1606 return (*number < number0) != (delta < 0);
1607}
1608
0e2a9149
SW
1609static int
1610long_increment_overflow(long *number, int delta)
1611{
1612 long number0;
1613
1614 number0 = *number;
1615 *number += delta;
1616 return (*number < number0) != (delta < 0);
1617}
1618
984263bc 1619static int
1fccf464 1620normalize_overflow(int * const tensptr, int * const unitsptr, const int base)
984263bc 1621{
660c873b 1622 int tensdelta;
984263bc
MD
1623
1624 tensdelta = (*unitsptr >= 0) ?
1625 (*unitsptr / base) :
1626 (-1 - (-1 - *unitsptr) / base);
1627 *unitsptr -= tensdelta * base;
1628 return increment_overflow(tensptr, tensdelta);
1629}
1630
0e2a9149
SW
1631static int
1632long_normalize_overflow(long * const tensptr, int * const unitsptr,
1633 const int base)
1634{
1635 int tensdelta;
1636
1637 tensdelta = (*unitsptr >= 0) ?
1638 (*unitsptr / base) :
1639 (-1 - (-1 - *unitsptr) / base);
1640 *unitsptr -= tensdelta * base;
1641 return long_increment_overflow(tensptr, tensdelta);
1642}
1643
984263bc 1644static int
1fccf464 1645tmcomp(const struct tm * const atmp, const struct tm * const btmp)
984263bc 1646{
660c873b 1647 int result;
984263bc
MD
1648
1649 if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1650 (result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1651 (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1652 (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1653 (result = (atmp->tm_min - btmp->tm_min)) == 0)
1654 result = atmp->tm_sec - btmp->tm_sec;
1655 return result;
1656}
1657
1658static time_t
0e2a9149
SW
1659time2sub(struct tm * const tmp,
1660 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1661 const long offset, int * const okayp, const int do_norm_secs)
984263bc 1662{
660c873b
DR
1663 const struct state * sp;
1664 int dir;
0e2a9149 1665 int i, j;
660c873b 1666 int saved_seconds;
0e2a9149
SW
1667 long li;
1668 time_t lo;
1669 time_t hi;
1670 long y;
1671 time_t newt;
1672 time_t t;
1673 struct tm yourtm, mytm;
984263bc
MD
1674
1675 *okayp = FALSE;
1676 yourtm = *tmp;
0e2a9149
SW
1677 if (do_norm_secs) {
1678 if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1679 SECSPERMIN))
1680 return WRONG;
1681 }
984263bc
MD
1682 if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1683 return WRONG;
1684 if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1685 return WRONG;
0e2a9149
SW
1686 y = yourtm.tm_year;
1687 if (long_normalize_overflow(&y, &yourtm.tm_mon, MONSPERYEAR))
984263bc
MD
1688 return WRONG;
1689 /*
0e2a9149 1690 ** Turn y into an actual year number for now.
984263bc
MD
1691 ** It is converted back to an offset from TM_YEAR_BASE later.
1692 */
0e2a9149 1693 if (long_increment_overflow(&y, TM_YEAR_BASE))
984263bc
MD
1694 return WRONG;
1695 while (yourtm.tm_mday <= 0) {
0e2a9149 1696 if (long_increment_overflow(&y, -1))
984263bc 1697 return WRONG;
0e2a9149
SW
1698 li = y + (1 < yourtm.tm_mon);
1699 yourtm.tm_mday += year_lengths[isleap(li)];
984263bc
MD
1700 }
1701 while (yourtm.tm_mday > DAYSPERLYEAR) {
0e2a9149
SW
1702 li = y + (1 < yourtm.tm_mon);
1703 yourtm.tm_mday -= year_lengths[isleap(li)];
1704 if (long_increment_overflow(&y, 1))
984263bc
MD
1705 return WRONG;
1706 }
1707 for ( ; ; ) {
0e2a9149 1708 i = mon_lengths[isleap(y)][yourtm.tm_mon];
984263bc
MD
1709 if (yourtm.tm_mday <= i)
1710 break;
1711 yourtm.tm_mday -= i;
1712 if (++yourtm.tm_mon >= MONSPERYEAR) {
1713 yourtm.tm_mon = 0;
0e2a9149 1714 if (long_increment_overflow(&y, 1))
984263bc
MD
1715 return WRONG;
1716 }
1717 }
0e2a9149
SW
1718 if (long_increment_overflow(&y, -TM_YEAR_BASE))
1719 return WRONG;
1720 yourtm.tm_year = y;
1721 if (yourtm.tm_year != y)
984263bc 1722 return WRONG;
0e2a9149
SW
1723 if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
1724 saved_seconds = 0;
1725 else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
984263bc
MD
1726 /*
1727 ** We can't set tm_sec to 0, because that might push the
1728 ** time below the minimum representable time.
1729 ** Set tm_sec to 59 instead.
1730 ** This assumes that the minimum representable time is
1731 ** not in the same minute that a leap second was deleted from,
1732 ** which is a safer assumption than using 58 would be.
1733 */
1734 if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1735 return WRONG;
1736 saved_seconds = yourtm.tm_sec;
1737 yourtm.tm_sec = SECSPERMIN - 1;
1738 } else {
1739 saved_seconds = yourtm.tm_sec;
1740 yourtm.tm_sec = 0;
1741 }
1742 /*
0e2a9149 1743 ** Do a binary search (this works whatever time_t's type is).
984263bc 1744 */
0e2a9149
SW
1745 if (!TYPE_SIGNED(time_t)) {
1746 lo = 0;
1747 hi = lo - 1;
1748 } else if (!TYPE_INTEGRAL(time_t)) {
1749 if (sizeof(time_t) > sizeof(float))
1750 hi = (time_t) DBL_MAX;
1751 else hi = (time_t) FLT_MAX;
1752 lo = -hi;
1753 } else {
1754 lo = 1;
1755 for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
1756 lo *= 2;
1757 hi = -(lo + 1);
1758 }
984263bc 1759 for ( ; ; ) {
0e2a9149
SW
1760 t = lo / 2 + hi / 2;
1761 if (t < lo)
1762 t = lo;
1763 else if (t > hi)
1764 t = hi;
1765 if ((*funcp)(&t, offset, &mytm) == NULL) {
1766 /*
1767 ** Assume that t is too extreme to be represented in
1768 ** a struct tm; arrange things so that it is less
1769 ** extreme on the next pass.
1770 */
1771 dir = (t > 0) ? 1 : -1;
1772 } else dir = tmcomp(&mytm, &yourtm);
984263bc 1773 if (dir != 0) {
0e2a9149
SW
1774 if (t == lo) {
1775 ++t;
1776 if (t <= lo)
1777 return WRONG;
1778 ++lo;
1779 } else if (t == hi) {
1780 --t;
1781 if (t >= hi)
1782 return WRONG;
1783 --hi;
1784 }
1785 if (lo > hi)
984263bc 1786 return WRONG;
0e2a9149
SW
1787 if (dir > 0)
1788 hi = t;
1789 else lo = t;
984263bc
MD
1790 continue;
1791 }
1792 if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1793 break;
1794 /*
1795 ** Right time, wrong type.
1796 ** Hunt for right time, right type.
1797 ** It's okay to guess wrong since the guess
1798 ** gets checked.
1799 */
984263bc 1800 sp = (const struct state *)
0e2a9149 1801 ((funcp == localsub) ? lclptr : gmtptr);
a14127aa 1802
984263bc
MD
1803 for (i = sp->typecnt - 1; i >= 0; --i) {
1804 if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1805 continue;
1806 for (j = sp->typecnt - 1; j >= 0; --j) {
1807 if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1808 continue;
1809 newt = t + sp->ttis[j].tt_gmtoff -
1810 sp->ttis[i].tt_gmtoff;
0e2a9149
SW
1811 if ((*funcp)(&newt, offset, &mytm) == NULL)
1812 continue;
984263bc
MD
1813 if (tmcomp(&mytm, &yourtm) != 0)
1814 continue;
1815 if (mytm.tm_isdst != yourtm.tm_isdst)
1816 continue;
1817 /*
1818 ** We have a match.
1819 */
1820 t = newt;
1821 goto label;
1822 }
1823 }
1824 return WRONG;
1825 }
1826label:
1827 newt = t + saved_seconds;
1828 if ((newt < t) != (saved_seconds < 0))
1829 return WRONG;
1830 t = newt;
0e2a9149
SW
1831 if ((*funcp)(&t, offset, tmp))
1832 *okayp = TRUE;
984263bc
MD
1833 return t;
1834}
1835
0e2a9149
SW
1836static time_t
1837time2(struct tm * const tmp,
1838 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1839 const long offset, int * const okayp)
1840{
1841 time_t t;
1842
1843 /*
1844 ** First try without normalization of seconds
1845 ** (in case tm_sec contains a value associated with a leap second).
1846 ** If that fails, try with normalization of seconds.
1847 */
1848 t = time2sub(tmp, funcp, offset, okayp, FALSE);
1849 return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE);
1850}
1851
984263bc 1852static time_t
1fccf464 1853time1(struct tm * const tmp,
0e2a9149 1854 struct tm * (* const funcp)(const time_t *, long, struct tm *),
1fccf464 1855 const long offset)
984263bc 1856{
660c873b
DR
1857 time_t t;
1858 const struct state * sp;
1859 int samei, otheri;
0e2a9149
SW
1860 int sameind, otherind;
1861 int i;
1862 int nseen;
1863 int seen[TZ_MAX_TYPES];
1864 int types[TZ_MAX_TYPES];
1865 int okay;
984263bc
MD
1866
1867 if (tmp->tm_isdst > 1)
1868 tmp->tm_isdst = 1;
1869 t = time2(tmp, funcp, offset, &okay);
a14127aa 1870
984263bc 1871 /*
0e2a9149 1872 ** PCTS code courtesy Grant Sullivan.
984263bc
MD
1873 */
1874 if (okay)
1875 return t;
1876 if (tmp->tm_isdst < 0)
1877 tmp->tm_isdst = 0; /* reset to std and try again */
a14127aa 1878
984263bc
MD
1879 /*
1880 ** We're supposed to assume that somebody took a time of one type
1881 ** and did some math on it that yielded a "struct tm" that's bad.
1882 ** We try to divine the type they started from and adjust to the
1883 ** type they need.
1884 */
0e2a9149 1885 sp = (const struct state *) ((funcp == localsub) ? lclptr : gmtptr);
a14127aa 1886
0e2a9149
SW
1887 for (i = 0; i < sp->typecnt; ++i)
1888 seen[i] = FALSE;
1889 nseen = 0;
1890 for (i = sp->timecnt - 1; i >= 0; --i)
1891 if (!seen[sp->types[i]]) {
1892 seen[sp->types[i]] = TRUE;
1893 types[nseen++] = sp->types[i];
1894 }
1895 for (sameind = 0; sameind < nseen; ++sameind) {
1896 samei = types[sameind];
984263bc
MD
1897 if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1898 continue;
0e2a9149
SW
1899 for (otherind = 0; otherind < nseen; ++otherind) {
1900 otheri = types[otherind];
984263bc
MD
1901 if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1902 continue;
1903 tmp->tm_sec += sp->ttis[otheri].tt_gmtoff -
1904 sp->ttis[samei].tt_gmtoff;
1905 tmp->tm_isdst = !tmp->tm_isdst;
1906 t = time2(tmp, funcp, offset, &okay);
1907 if (okay)
1908 return t;
1909 tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff -
1910 sp->ttis[samei].tt_gmtoff;
1911 tmp->tm_isdst = !tmp->tm_isdst;
1912 }
1913 }
1914 return WRONG;
1915}
1916
1917time_t
1fccf464 1918mktime(struct tm * const tmp)
984263bc
MD
1919{
1920 time_t mktime_return_value;
390e5ad7
PA
1921 _RWLOCK_RDLOCK(&lcl_rwlock);
1922 tzset_basic(1);
984263bc 1923 mktime_return_value = time1(tmp, localsub, 0L);
390e5ad7 1924 _RWLOCK_UNLOCK(&lcl_rwlock);
984263bc
MD
1925 return(mktime_return_value);
1926}
1927
984263bc 1928time_t
1fccf464 1929timelocal(struct tm * const tmp)
984263bc
MD
1930{
1931 tmp->tm_isdst = -1; /* in case it wasn't initialized */
1932 return mktime(tmp);
1933}
1934
1935time_t
1fccf464 1936timegm(struct tm * const tmp)
984263bc
MD
1937{
1938 tmp->tm_isdst = 0;
1939 return time1(tmp, gmtsub, 0L);
1940}
1941
1942time_t
1fccf464 1943timeoff(struct tm * const tmp, const long offset)
984263bc
MD
1944{
1945 tmp->tm_isdst = 0;
1946 return time1(tmp, gmtsub, offset);
1947}
1948
984263bc
MD
1949#ifdef CMUCS
1950
1951/*
1952** The following is supplied for compatibility with
1953** previous versions of the CMUCS runtime library.
1954*/
1955
1956long
1fccf464 1957gtime(struct tm * const tmp)
984263bc
MD
1958{
1959 const time_t t = mktime(tmp);
1960
1961 if (t == WRONG)
1962 return -1;
1963 return t;
1964}
1965
1966#endif /* defined CMUCS */
1967
1968/*
1969** XXX--is the below the right way to conditionalize??
1970*/
1971
984263bc
MD
1972/*
1973** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
0e2a9149 1974** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
984263bc
MD
1975** is not the case if we are accounting for leap seconds.
1976** So, we provide the following conversion routines for use
1977** when exchanging timestamps with POSIX conforming systems.
1978*/
1979
1980static long
1fccf464 1981leapcorr(time_t *timep)
984263bc 1982{
660c873b
DR
1983 struct state * sp;
1984 struct lsinfo * lp;
1985 int i;
984263bc
MD
1986
1987 sp = lclptr;
1988 i = sp->leapcnt;
1989 while (--i >= 0) {
1990 lp = &sp->lsis[i];
1991 if (*timep >= lp->ls_trans)
1992 return lp->ls_corr;
1993 }
1994 return 0;
1995}
1996
1997time_t
1fccf464 1998time2posix(time_t t)
984263bc
MD
1999{
2000 tzset();
2001 return t - leapcorr(&t);
2002}
2003
2004time_t
1fccf464 2005posix2time(time_t t)
984263bc
MD
2006{
2007 time_t x;
2008 time_t y;
2009
2010 tzset();
2011 /*
2012 ** For a positive leap second hit, the result
0e2a9149 2013 ** is not unique. For a negative leap second
984263bc
MD
2014 ** hit, the corresponding time doesn't exist,
2015 ** so we return an adjacent second.
2016 */
2017 x = t + leapcorr(&t);
2018 y = x - leapcorr(&x);
2019 if (y < t) {
2020 do {
2021 x++;
2022 y = x - leapcorr(&x);
2023 } while (y < t);
2024 if (t != y)
2025 return x - 1;
2026 } else if (y > t) {
2027 do {
2028 --x;
2029 y = x - leapcorr(&x);
2030 } while (y > t);
2031 if (t != y)
2032 return x + 1;
2033 }
2034 return x;
2035}