xref: /minix3/lib/libc/time/zdump.c (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1 /*	$NetBSD: zdump.c,v 1.42 2015/08/13 11:21:18 christos Exp $	*/
2 /*
3 ** This file is in the public domain, so clarified as of
4 ** 2009-05-17 by Arthur David Olson.
5 */
6 
7 #include <sys/cdefs.h>
8 #ifndef lint
9 __RCSID("$NetBSD: zdump.c,v 1.42 2015/08/13 11:21:18 christos Exp $");
10 #endif /* !defined lint */
11 
12 /*
13 ** This code has been made independent of the rest of the time
14 ** conversion package to increase confidence in the verification it provides.
15 ** You can use this code to help in verifying other implementations.
16 **
17 ** To do this, compile with -DUSE_LTZ=0 and link without the tz library.
18 */
19 
20 #ifndef NETBSD_INSPIRED
21 # define NETBSD_INSPIRED 1
22 #endif
23 #ifndef USE_LTZ
24 # define USE_LTZ 1
25 #endif
26 
27 #if USE_LTZ
28 #include "private.h"
29 #endif
30 
31 /* Enable tm_gmtoff and tm_zone on GNUish systems.  */
32 #define _GNU_SOURCE 1
33 /* Enable strtoimax on Solaris 10.  */
34 #define __EXTENSIONS__ 1
35 
36 #include "stdio.h"	/* for stdout, stderr */
37 #include "string.h"	/* for strcpy */
38 #include "sys/types.h"	/* for time_t */
39 #include "time.h"	/* for struct tm */
40 #include "stdlib.h"	/* for exit, malloc, atoi */
41 #include "limits.h"	/* for CHAR_BIT, LLONG_MAX */
42 #include <errno.h>
43 #include <err.h>
44 
45 /*
46 ** Substitutes for pre-C99 compilers.
47 ** Much of this section of code is stolen from private.h.
48 */
49 
50 #ifndef HAVE_STDINT_H
51 # define HAVE_STDINT_H \
52     (199901 <= __STDC_VERSION__ \
53      || 2 < __GLIBC__ + (1 <= __GLIBC_MINOR__)	\
54      || __CYGWIN__)
55 #endif
56 #if HAVE_STDINT_H
57 # include "stdint.h"
58 #endif
59 #ifndef HAVE_INTTYPES_H
60 # define HAVE_INTTYPES_H HAVE_STDINT_H
61 #endif
62 #if HAVE_INTTYPES_H
63 # include <inttypes.h>
64 #endif
65 
66 #ifndef INT_FAST32_MAX
67 # if INT_MAX >> 31 == 0
68 typedef long int_fast32_t;
69 # else
70 typedef int int_fast32_t;
71 # endif
72 #endif
73 
74 /* Pre-C99 GCC compilers define __LONG_LONG_MAX__ instead of LLONG_MAX.  */
75 #if !defined LLONG_MAX && defined __LONG_LONG_MAX__
76 # define LLONG_MAX __LONG_LONG_MAX__
77 #endif
78 
79 #ifndef INTMAX_MAX
80 # ifdef LLONG_MAX
81 typedef long long intmax_t;
82 #  define strtoimax strtoll
83 #  define INTMAX_MAX LLONG_MAX
84 # else
85 typedef long intmax_t;
86 #  define strtoimax strtol
87 #  define INTMAX_MAX LONG_MAX
88 # endif
89 #endif
90 
91 #ifndef PRIdMAX
92 # if INTMAX_MAX == LLONG_MAX
93 #  define PRIdMAX "lld"
94 # else
95 #  define PRIdMAX "ld"
96 # endif
97 #endif
98 
99 /* Infer TM_ZONE on systems where this information is known, but suppress
100    guessing if NO_TM_ZONE is defined.  Similarly for TM_GMTOFF.  */
101 #if (defined __GLIBC__ \
102      || defined __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__ \
103      || (defined __APPLE__ && defined __MACH__))
104 # if !defined TM_GMTOFF && !defined NO_TM_GMTOFF
105 #  define TM_GMTOFF tm_gmtoff
106 # endif
107 # if !defined TM_ZONE && !defined NO_TM_ZONE
108 #  define TM_ZONE tm_zone
109 # endif
110 #endif
111 
112 #ifndef HAVE_LOCALTIME_R
113 # define HAVE_LOCALTIME_R 1
114 #endif
115 
116 #ifndef HAVE_LOCALTIME_RZ
117 # ifdef TM_ZONE
118 #  define HAVE_LOCALTIME_RZ (NETBSD_INSPIRED && USE_LTZ)
119 # else
120 #  define HAVE_LOCALTIME_RZ 0
121 # endif
122 #endif
123 
124 #ifndef HAVE_TZSET
125 # define HAVE_TZSET 1
126 #endif
127 
128 #ifndef ZDUMP_LO_YEAR
129 #define ZDUMP_LO_YEAR	(-500)
130 #endif /* !defined ZDUMP_LO_YEAR */
131 
132 #ifndef ZDUMP_HI_YEAR
133 #define ZDUMP_HI_YEAR	2500
134 #endif /* !defined ZDUMP_HI_YEAR */
135 
136 #ifndef MAX_STRING_LENGTH
137 #define MAX_STRING_LENGTH	1024
138 #endif /* !defined MAX_STRING_LENGTH */
139 
140 #if __STDC_VERSION__ < 199901
141 # define true 1
142 # define false 0
143 # define bool int
144 #else
145 # include <stdbool.h>
146 #endif
147 
148 #ifndef EXIT_SUCCESS
149 #define EXIT_SUCCESS	0
150 #endif /* !defined EXIT_SUCCESS */
151 
152 #ifndef EXIT_FAILURE
153 #define EXIT_FAILURE	1
154 #endif /* !defined EXIT_FAILURE */
155 
156 #ifndef SECSPERMIN
157 #define SECSPERMIN	60
158 #endif /* !defined SECSPERMIN */
159 
160 #ifndef MINSPERHOUR
161 #define MINSPERHOUR	60
162 #endif /* !defined MINSPERHOUR */
163 
164 #ifndef SECSPERHOUR
165 #define SECSPERHOUR	(SECSPERMIN * MINSPERHOUR)
166 #endif /* !defined SECSPERHOUR */
167 
168 #ifndef HOURSPERDAY
169 #define HOURSPERDAY	24
170 #endif /* !defined HOURSPERDAY */
171 
172 #ifndef EPOCH_YEAR
173 #define EPOCH_YEAR	1970
174 #endif /* !defined EPOCH_YEAR */
175 
176 #ifndef TM_YEAR_BASE
177 #define TM_YEAR_BASE	1900
178 #endif /* !defined TM_YEAR_BASE */
179 
180 #ifndef DAYSPERNYEAR
181 #define DAYSPERNYEAR	365
182 #endif /* !defined DAYSPERNYEAR */
183 
184 #ifndef isleap
185 #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
186 #endif /* !defined isleap */
187 
188 #ifndef isleap_sum
189 /*
190 ** See tzfile.h for details on isleap_sum.
191 */
192 #define isleap_sum(a, b)	isleap((a) % 400 + (b) % 400)
193 #endif /* !defined isleap_sum */
194 
195 #define SECSPERDAY	((int_fast32_t) SECSPERHOUR * HOURSPERDAY)
196 #define SECSPERNYEAR	(SECSPERDAY * DAYSPERNYEAR)
197 #define SECSPERLYEAR	(SECSPERNYEAR + SECSPERDAY)
198 #define SECSPER400YEARS	(SECSPERNYEAR * (intmax_t) (300 + 3)	\
199 			 + SECSPERLYEAR * (intmax_t) (100 - 3))
200 
201 /*
202 ** True if SECSPER400YEARS is known to be representable as an
203 ** intmax_t.  It's OK that SECSPER400YEARS_FITS can in theory be false
204 ** even if SECSPER400YEARS is representable, because when that happens
205 ** the code merely runs a bit more slowly, and this slowness doesn't
206 ** occur on any practical platform.
207 */
208 enum { SECSPER400YEARS_FITS = SECSPERLYEAR <= INTMAX_MAX / 400 };
209 
210 #ifndef HAVE_GETTEXT
211 #define HAVE_GETTEXT 0
212 #endif
213 #if HAVE_GETTEXT
214 #include "locale.h"	/* for setlocale */
215 #include "libintl.h"
216 #endif /* HAVE_GETTEXT */
217 
218 #ifndef ATTRIBUTE_PURE
219 #if 2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__)
220 # define ATTRIBUTE_PURE __attribute__ ((ATTRIBUTE_PURE__))
221 #else
222 # define ATTRIBUTE_PURE /* empty */
223 #endif
224 #endif
225 
226 #ifndef INITIALIZE
227 #if defined(__GNUC__) || defined(__lint__)
228 #define INITIALIZE(x)	((x) = 0)
229 #else /* !defined GNUC || lint */
230 #define INITIALIZE(x)
231 #endif /* !defined GNUC || lint */
232 #endif /* !defined INITIALIZE */
233 
234 /*
235 ** For the benefit of GNU folk...
236 ** '_(MSGID)' uses the current locale's message library string for MSGID.
237 ** The default is to use gettext if available, and use MSGID otherwise.
238 */
239 
240 #ifndef _
241 #if HAVE_GETTEXT
242 #define _(msgid) gettext(msgid)
243 #else /* !HAVE_GETTEXT */
244 #define _(msgid) msgid
245 #endif /* !HAVE_GETTEXT */
246 #endif /* !defined _ */
247 
248 #if !defined TZ_DOMAIN && defined HAVE_GETTEXT
249 # define TZ_DOMAIN "tz"
250 #endif
251 
252 #if ! HAVE_LOCALTIME_RZ
253 # undef  timezone_t
254 # define timezone_t char **
255 #endif
256 
257 extern char **	environ;
258 extern int	getopt(int argc, char * const argv[],
259 			const char * options);
260 extern char *	optarg;
261 extern int	optind;
262 
263 /* The minimum and maximum finite time values.  */
264 enum { atime_shift = CHAR_BIT * sizeof (time_t) - 2 };
265 static time_t	absolute_min_time =
266   ((time_t) -1 < 0
267     ? (- ((time_t) ~ (time_t) 0 < 0)
268        - (((time_t) 1 << atime_shift) - 1 + ((time_t) 1 << atime_shift)))
269     : 0);
270 static time_t	absolute_max_time =
271   ((time_t) -1 < 0
272     ? (((time_t) 1 << atime_shift) - 1 + ((time_t) 1 << atime_shift))
273    : -1);
274 static size_t	longest;
275 static char *	progname;
276 static bool	warned;
277 static bool	errout;
278 
279 static char const *abbr(struct tm const *);
280 static intmax_t	delta(struct tm *, struct tm *) ATTRIBUTE_PURE;
281 static void dumptime(struct tm const *);
282 static time_t hunt(timezone_t, char *, time_t, time_t);
283 static void show(timezone_t, char *, time_t, bool);
284 static const char *tformat(void);
285 static time_t yeartot(intmax_t) ATTRIBUTE_PURE;
286 
287 /* Unlike <ctype.h>'s isdigit, this also works if c < 0 | c > UCHAR_MAX. */
288 #define is_digit(c) ((unsigned)(c) - '0' <= 9)
289 
290 /* Is A an alphabetic character in the C locale?  */
291 static bool
is_alpha(char a)292 is_alpha(char a)
293 {
294 	switch (a) {
295 	  default:
296 		return false;
297 	  case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
298 	  case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
299 	  case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
300 	  case 'V': case 'W': case 'X': case 'Y': case 'Z':
301 	  case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
302 	  case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
303 	  case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
304 	  case 'v': case 'w': case 'x': case 'y': case 'z':
305 	  	return true;
306 	}
307 }
308 
309 /* Return A + B, exiting if the result would overflow.  */
310 static size_t
sumsize(size_t a,size_t b)311 sumsize(size_t a, size_t b)
312 {
313 	size_t sum = a + b;
314 	if (sum < a)
315 		errx(EXIT_FAILURE, "size overflow");
316 	return sum;
317 }
318 
319 #if ! HAVE_TZSET
320 # undef tzset
321 # define tzset zdump_tzset
tzset(void)322 static void tzset(void) { }
323 #endif
324 
325 /* Assume gmtime_r works if localtime_r does.
326    A replacement localtime_r is defined below if needed.  */
327 #if ! HAVE_LOCALTIME_R
328 
329 # undef gmtime_r
330 # define gmtime_r zdump_gmtime_r
331 
332 static struct tm *
gmtime_r(time_t * tp,struct tm * tmp)333 gmtime_r(time_t *tp, struct tm *tmp)
334 {
335 	struct tm *r = gmtime(tp);
336 	if (r) {
337 		*tmp = *r;
338 		r = tmp;
339 	}
340 	return r;
341 }
342 
343 #endif
344 
345 /* Platforms with TM_ZONE don't need tzname, so they can use the
346    faster localtime_rz or localtime_r if available.  */
347 
348 #if defined TM_ZONE && HAVE_LOCALTIME_RZ
349 # define USE_LOCALTIME_RZ true
350 #else
351 # define USE_LOCALTIME_RZ false
352 #endif
353 
354 #if ! USE_LOCALTIME_RZ
355 
356 # if !defined TM_ZONE || ! HAVE_LOCALTIME_R || ! HAVE_TZSET
357 #  undef localtime_r
358 #  define localtime_r zdump_localtime_r
359 static struct tm *
localtime_r(time_t * tp,struct tm * tmp)360 localtime_r(time_t *tp, struct tm *tmp)
361 {
362 	struct tm *r = localtime(tp);
363 	if (r) {
364 		*tmp = *r;
365 		r = tmp;
366 	}
367 	return r;
368 }
369 # endif
370 
371 # undef localtime_rz
372 # define localtime_rz zdump_localtime_rz
373 static struct tm *
localtime_rz(timezone_t rz,time_t * tp,struct tm * tmp)374 localtime_rz(timezone_t rz, time_t *tp, struct tm *tmp)
375 {
376 	return localtime_r(tp, tmp);
377 }
378 
379 # ifdef TYPECHECK
380 #  undef mktime_z
381 #  define mktime_z zdump_mktime_z
382 static time_t
mktime_z(timezone_t tz,struct tm * tmp)383 mktime_z(timezone_t tz, struct tm *tmp)
384 {
385 	return mktime(tmp);
386 }
387 # endif
388 
389 # undef tzalloc
390 # undef tzfree
391 # define tzalloc zdump_tzalloc
392 # define tzfree zdump_tzfree
393 
394 static timezone_t
tzalloc(char const * val)395 tzalloc(char const *val)
396 {
397 	static char **fakeenv;
398 	char **env = fakeenv;
399 	char *env0;
400 	if (! env) {
401 		char **e = environ;
402 		int to;
403 
404 		while (*e++)
405 			continue;
406 		env = malloc(sumsize(sizeof *environ,
407 		    (e - environ) * sizeof *environ));
408 		if (! env) {
409 			err(EXIT_FAILURE, "malloc");
410 		}
411 		to = 1;
412 		for (e = environ; (env[to] = *e); e++)
413 			to += strncmp(*e, "TZ=", 3) != 0;
414 	}
415 	env0 = malloc(sumsize(sizeof "TZ=", strlen(val)));
416 	if (! env0) {
417 		err(EXIT_FAILURE, "malloc");
418 	}
419 	env[0] = strcat(strcpy(env0, "TZ="), val);
420 	environ = fakeenv = env;
421 	tzset();
422 	return env;
423 }
424 
425 static void
tzfree(timezone_t env)426 tzfree(timezone_t env)
427 {
428 	environ = env + 1;
429 	free(env[0]);
430 }
431 #endif /* ! USE_LOCALTIME_RZ */
432 
433 /* A UTC time zone, and its initializer.  */
434 static timezone_t gmtz;
435 static void
gmtzinit(void)436 gmtzinit(void)
437 {
438 	if (USE_LOCALTIME_RZ) {
439 		static char const utc[] = "UTC0";
440 		gmtz = tzalloc(utc);
441 		if (!gmtz) {
442 		      err(EXIT_FAILURE, "Cannot create %s", utc);
443 		}
444 	}
445 }
446 
447 /* Convert *TP to UTC, storing the broken-down time into *TMP.
448    Return TMP if successful, NULL otherwise.  This is like gmtime_r(TP, TMP),
449    except typically faster if USE_LOCALTIME_RZ.  */
450 static struct tm *
my_gmtime_r(time_t * tp,struct tm * tmp)451 my_gmtime_r(time_t *tp, struct tm *tmp)
452 {
453 	return USE_LOCALTIME_RZ ?
454 	    localtime_rz(gmtz, tp, tmp) : gmtime_r(tp, tmp);
455 }
456 
457 #ifndef TYPECHECK
458 #define my_localtime_rz	localtime_rz
459 #else /* !defined TYPECHECK */
460 static struct tm *
my_localtime_rz(timezone_t tz,const time_t * tp,struct tm * tmp)461 my_localtime_rz(timezone_t tz, const time_t *tp, struct tm *tmp)
462 {
463 	tmp = localtime_rz(tz, tp, tmp);
464 	if (tmp) {
465 		struct tm	tm;
466 		time_t	t;
467 
468 		tm = *tmp;
469 		t = mktime_z(tz, &tm);
470 		if (t != *tp) {
471 			(void) fflush(stdout);
472 			(void) fprintf(stderr, "\n%s: ", progname);
473 			(void) fprintf(stderr, tformat(), *tp);
474 			(void) fprintf(stderr, " ->");
475 			(void) fprintf(stderr, " year=%d", tmp->tm_year);
476 			(void) fprintf(stderr, " mon=%d", tmp->tm_mon);
477 			(void) fprintf(stderr, " mday=%d", tmp->tm_mday);
478 			(void) fprintf(stderr, " hour=%d", tmp->tm_hour);
479 			(void) fprintf(stderr, " min=%d", tmp->tm_min);
480 			(void) fprintf(stderr, " sec=%d", tmp->tm_sec);
481 			(void) fprintf(stderr, " isdst=%d", tmp->tm_isdst);
482 			(void) fprintf(stderr, " -> ");
483 			(void) fprintf(stderr, tformat(), t);
484 			(void) fprintf(stderr, "\n");
485 			errout = true;
486 		}
487 	}
488 	return tmp;
489 }
490 #endif /* !defined TYPECHECK */
491 
492 static void
abbrok(const char * const abbrp,const char * const zone)493 abbrok(const char *const abbrp, const char *const zone)
494 {
495 	const char *cp;
496 	const char *wp;
497 
498 	if (warned)
499 		return;
500 	cp = abbrp;
501 	while (is_alpha(*cp) || is_digit(*cp) || *cp == '-' || *cp == '+')
502 		++cp;
503 	if (cp - abbrp < 3)
504 		wp = _("has fewer than 3 characters");
505 	else if (cp - abbrp > 6)
506 		wp = _("has more than 6 characters");
507 	else if (*cp)
508 		wp = _("has characters other than ASCII alphanumerics, '-' or '+'");
509 	else
510 		return;
511 	(void) fflush(stdout);
512 	(void) fprintf(stderr,
513 		_("%s: warning: zone \"%s\" abbreviation \"%s\" %s\n"),
514 		progname, zone, abbrp, wp);
515 	warned = errout = true;
516 }
517 
518 /* Return a time zone abbreviation.  If the abbreviation needs to be
519    saved, use *BUF (of size *BUFALLOC) to save it, and return the
520    abbreviation in the possibly-reallocated *BUF.  Otherwise, just
521    return the abbreviation.  Get the abbreviation from TMP.
522    Exit on memory allocation failure.  */
523 static char const *
saveabbr(char ** buf,size_t * bufalloc,struct tm const * tmp)524 saveabbr(char **buf, size_t *bufalloc, struct tm const *tmp)
525 {
526 	char const *ab = abbr(tmp);
527 	if (HAVE_LOCALTIME_RZ)
528 		return ab;
529 	else {
530 		size_t ablen = strlen(ab);
531 		if (*bufalloc <= ablen) {
532 			free(*buf);
533 
534 			/* Make the new buffer at least twice as long as the
535 			   old, to avoid O(N**2) behavior on repeated calls.  */
536 			*bufalloc = sumsize(*bufalloc, ablen + 1);
537 			*buf = malloc(*bufalloc);
538 			if (! *buf) {
539 				err(EXIT_FAILURE, "malloc");
540 			}
541 		}
542 		return strcpy(*buf, ab);
543 	}
544 }
545 
546 static void
close_file(FILE * stream)547 close_file(FILE *stream)
548 {
549 	char const *e = (ferror(stream) ? _("I/O error")
550 	    : fclose(stream) != 0 ? strerror(errno) : NULL);
551 	if (e) {
552 		errx(EXIT_FAILURE, "%s", e);
553 	}
554 }
555 
556 __dead static void
usage(FILE * const stream,const int status)557 usage(FILE *const stream, const int status)
558 {
559 	(void) fprintf(stream,
560 _("%s: usage: %s [--version] [--help] [-{vV}] [-{ct} [lo,]hi] zonename ...\n"
561   "\n"
562   "Report bugs to %s.\n"),
563 		       progname, progname, REPORT_BUGS_TO);
564 	if (status == EXIT_SUCCESS)
565 		close_file(stream);
566 	exit(status);
567 }
568 
569 int
main(int argc,char * argv[])570 main(int argc, char *argv[])
571 {
572 	/* These are static so that they're initially zero.  */
573 	static char *		abbrev;
574 	static size_t		abbrevsize;
575 	static struct tm	newtm;
576 
577 	int		i;
578 	bool		vflag;
579 	bool		Vflag;
580 	char *		cutarg;
581 	char *		cuttimes;
582 	time_t		cutlotime;
583 	time_t		cuthitime;
584 	time_t		now;
585 	time_t		t;
586 	time_t		newt;
587 	struct tm	tm;
588 	struct tm *	tmp;
589 	struct tm *	newtmp;
590 
591 	cutlotime = absolute_min_time;
592 	cuthitime = absolute_max_time;
593 #if HAVE_GETTEXT
594 	(void) setlocale(LC_ALL, "");
595 #ifdef TZ_DOMAINDIR
596 	(void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
597 #endif /* defined TEXTDOMAINDIR */
598 	(void) textdomain(TZ_DOMAIN);
599 #endif /* HAVE_GETTEXT */
600 	progname = argv[0];
601 	for (i = 1; i < argc; ++i)
602 		if (strcmp(argv[i], "--version") == 0) {
603 			(void) printf("zdump %s%s\n", PKGVERSION, TZVERSION);
604 			return EXIT_SUCCESS;
605 		} else if (strcmp(argv[i], "--help") == 0) {
606 			usage(stdout, EXIT_SUCCESS);
607 		}
608 	vflag = Vflag = false;
609 	cutarg = cuttimes = NULL;
610 	for (;;)
611 	  switch (getopt(argc, argv, "c:t:vV")) {
612 	  case 'c': cutarg = optarg; break;
613 	  case 't': cuttimes = optarg; break;
614 	  case 'v': vflag = true; break;
615 	  case 'V': Vflag = true; break;
616 	  case -1:
617 	    if (! (optind == argc - 1 && strcmp(argv[optind], "=") == 0))
618 	      goto arg_processing_done;
619 	    /* Fall through.  */
620 	  default:
621 	    usage(stderr, EXIT_FAILURE);
622 	  }
623  arg_processing_done:;
624 
625 	if (vflag | Vflag) {
626 		intmax_t	lo;
627 		intmax_t	hi;
628 		char *loend, *hiend;
629 		intmax_t cutloyear = ZDUMP_LO_YEAR;
630 		intmax_t cuthiyear = ZDUMP_HI_YEAR;
631 		if (cutarg != NULL) {
632 			lo = strtoimax(cutarg, &loend, 10);
633 			if (cutarg != loend && !*loend) {
634 				hi = lo;
635 				cuthiyear = hi;
636 			} else if (cutarg != loend && *loend == ','
637 				   && (hi = strtoimax(loend + 1, &hiend, 10),
638 				       loend + 1 != hiend && !*hiend)) {
639 				cutloyear = lo;
640 				cuthiyear = hi;
641 			} else {
642 				fprintf(stderr, _("%s: wild -c argument %s\n"),
643 					progname, cutarg);
644 				return EXIT_FAILURE;
645 			}
646 		}
647 		if (cutarg != NULL || cuttimes == NULL) {
648 			cutlotime = yeartot(cutloyear);
649 			cuthitime = yeartot(cuthiyear);
650 		}
651 		if (cuttimes != NULL) {
652 			lo = strtoimax(cuttimes, &loend, 10);
653 			if (cuttimes != loend && !*loend) {
654 				hi = lo;
655 				if (hi < cuthitime) {
656 					if (hi < absolute_min_time)
657 						hi = absolute_min_time;
658 					cuthitime = hi;
659 				}
660 			} else if (cuttimes != loend && *loend == ','
661 				   && (hi = strtoimax(loend + 1, &hiend, 10),
662 				       loend + 1 != hiend && !*hiend)) {
663 				if (cutlotime < lo) {
664 					if (absolute_max_time < lo)
665 						lo = absolute_max_time;
666 					cutlotime = lo;
667 				}
668 				if (hi < cuthitime) {
669 					if (hi < absolute_min_time)
670 						hi = absolute_min_time;
671 					cuthitime = hi;
672 				}
673 			} else {
674 				(void) fprintf(stderr,
675 					_("%s: wild -t argument %s\n"),
676 					progname, cuttimes);
677 				return EXIT_FAILURE;
678 			}
679 		}
680 	}
681 	gmtzinit();
682 	now = time(NULL);
683 	longest = 0;
684 	for (i = optind; i < argc; i++) {
685 		size_t arglen = strlen(argv[i]);
686 		if (longest < arglen)
687 			longest = arglen < INT_MAX ? arglen : INT_MAX;
688 	}
689 
690 	for (i = optind; i < argc; ++i) {
691 		timezone_t tz = tzalloc(argv[i]);
692 		char const *ab;
693 		if (!tz) {
694 			errx(EXIT_FAILURE, "%s", argv[i]);
695 		}
696 		if (! (vflag | Vflag)) {
697 			show(tz, argv[i], now, false);
698 			tzfree(tz);
699 			continue;
700 		}
701 		warned = false;
702 		t = absolute_min_time;
703 		if (!Vflag) {
704 			show(tz, argv[i], t, true);
705 			t += SECSPERDAY;
706 			show(tz, argv[i], t, true);
707 		}
708 		if (t < cutlotime)
709 			t = cutlotime;
710 		tmp = my_localtime_rz(tz, &t, &tm);
711 		if (tmp)
712 			ab = saveabbr(&abbrev, &abbrevsize, &tm);
713 		else
714 			ab = NULL;
715 		while (t < cuthitime) {
716 			newt = ((t < absolute_max_time - SECSPERDAY / 2
717 				&& t + SECSPERDAY / 2 < cuthitime)
718 				? t + SECSPERDAY / 2
719 				: cuthitime);
720 			newtmp = localtime_rz(tz, &newt, &newtm);
721 			if ((tmp == NULL || newtmp == NULL) ? (tmp != newtmp) :
722 			    (delta(&newtm, &tm) != (newt - t) ||
723 			    newtm.tm_isdst != tm.tm_isdst ||
724 			    strcmp(abbr(&newtm), ab) != 0)) {
725 				newt = hunt(tz, argv[i], t, newt);
726 				newtmp = localtime_rz(tz, &newt, &newtm);
727 				if (newtmp)
728 					  ab = saveabbr(&abbrev, &abbrevsize,
729 							&newtm);
730 			}
731 			t = newt;
732 			tm = newtm;
733 			tmp = newtmp;
734 		}
735 		if (!Vflag) {
736 			t = absolute_max_time;
737 			t -= SECSPERDAY;
738 			show(tz, argv[i], t, true);
739 			t += SECSPERDAY;
740 			show(tz, argv[i], t, true);
741 		}
742 		tzfree(tz);
743 	}
744 	close_file(stdout);
745 	if (errout && (ferror(stderr) || fclose(stderr) != 0))
746 		return EXIT_FAILURE;
747 	return EXIT_SUCCESS;
748 }
749 
750 static time_t
yeartot(intmax_t y)751 yeartot(intmax_t y)
752 {
753 	intmax_t	myy, seconds, years;
754 	time_t		t;
755 
756 	myy = EPOCH_YEAR;
757 	t = 0;
758 	while (myy < y) {
759 		if (SECSPER400YEARS_FITS && 400 <= y - myy) {
760 			intmax_t diff400 = (y - myy) / 400;
761 			if (INTMAX_MAX / SECSPER400YEARS < diff400)
762 				return absolute_max_time;
763 			seconds = diff400 * SECSPER400YEARS;
764 			years = diff400 * 400;
765                 } else {
766 			seconds = isleap(myy) ? SECSPERLYEAR : SECSPERNYEAR;
767 			years = 1;
768 		}
769 		myy += years;
770 		if (t > absolute_max_time - seconds)
771 			return absolute_max_time;
772 		t += seconds;
773 	}
774 	while (y < myy) {
775 		if (SECSPER400YEARS_FITS && y + 400 <= myy && myy < 0) {
776 			intmax_t diff400 = (myy - y) / 400;
777 			if (INTMAX_MAX / SECSPER400YEARS < diff400)
778 				return absolute_min_time;
779 			seconds = diff400 * SECSPER400YEARS;
780 			years = diff400 * 400;
781 		} else {
782 			seconds = isleap(myy - 1) ? SECSPERLYEAR : SECSPERNYEAR;
783 			years = 1;
784 		}
785 		myy -= years;
786 		if (t < absolute_min_time + seconds)
787 			return absolute_min_time;
788 		t -= seconds;
789 	}
790 	return t;
791 }
792 
793 static time_t
hunt(timezone_t tz,char * name,time_t lot,time_t hit)794 hunt(timezone_t tz, char *name, time_t lot, time_t hit)
795 {
796 	static char *		loab;
797 	static size_t		loabsize;
798 	char const *		ab;
799 	time_t			t;
800 	struct tm		lotm;
801 	struct tm *	lotmp;
802 	struct tm		tm;
803 	struct tm *	tmp;
804 
805 	lotmp = my_localtime_rz(tz, &lot, &lotm);
806 	if (lotmp)
807 		ab = saveabbr(&loab, &loabsize, &lotm);
808 	else
809 		ab = NULL;
810 	for ( ; ; ) {
811 		time_t diff = hit - lot;
812 		if (diff < 2)
813 			break;
814 		t = lot;
815 		t += diff / 2;
816 		if (t <= lot)
817 			++t;
818 		else if (t >= hit)
819 			--t;
820 		tmp = my_localtime_rz(tz, &t, &tm);
821 		if ((lotmp == NULL || tmp == NULL) ? (lotmp == tmp) :
822 			(delta(&tm, &lotm) == (t - lot) &&
823 			tm.tm_isdst == lotm.tm_isdst &&
824 			strcmp(abbr(&tm), ab) == 0)) {
825 				lot = t;
826 				lotm = tm;
827 				lotmp = tmp;
828 		} else	hit = t;
829 	}
830 	show(tz, name, lot, true);
831 	show(tz, name, hit, true);
832 	return hit;
833 }
834 
835 /*
836 ** Thanks to Paul Eggert for logic used in delta.
837 */
838 
839 static intmax_t
delta(struct tm * newp,struct tm * oldp)840 delta(struct tm *newp, struct tm *oldp)
841 {
842 	intmax_t	result;
843 	int		tmy;
844 
845 	if (newp->tm_year < oldp->tm_year)
846 		return -delta(oldp, newp);
847 	result = 0;
848 	for (tmy = oldp->tm_year; tmy < newp->tm_year; ++tmy)
849 		result += DAYSPERNYEAR + isleap_sum(tmy, TM_YEAR_BASE);
850 	result += newp->tm_yday - oldp->tm_yday;
851 	result *= HOURSPERDAY;
852 	result += newp->tm_hour - oldp->tm_hour;
853 	result *= MINSPERHOUR;
854 	result += newp->tm_min - oldp->tm_min;
855 	result *= SECSPERMIN;
856 	result += newp->tm_sec - oldp->tm_sec;
857 	return result;
858 }
859 
860 #ifndef TM_GMTOFF
861 /* Return A->tm_yday, adjusted to compare it fairly to B->tm_yday.
862    Assume A and B differ by at most one year.  */
863 static int
adjusted_yday(struct tm const * a,struct tm const * b)864 adjusted_yday(struct tm const *a, struct tm const *b)
865 {
866 	int yday = a->tm_yday;
867 	if (b->tm_year < a->tm_year)
868 		yday += 365 + isleap_sum(b->tm_year, TM_YEAR_BASE);
869 	return yday;
870 }
871 #endif
872 
873 /* If A is the broken-down local time and B the broken-down UTC for
874    the same instant, return A's UTC offset in seconds, where positive
875    offsets are east of Greenwich.  On failure, return LONG_MIN.  */
876 static long
gmtoff(struct tm const * a,struct tm const * b)877 gmtoff(struct tm const *a, struct tm const *b)
878 {
879 #ifdef TM_GMTOFF
880 	return a->TM_GMTOFF;
881 #else
882 	if (! b)
883 		return LONG_MIN;
884 	else {
885 		int ayday = adjusted_yday(a, b);
886 		int byday = adjusted_yday(b, a);
887 		int days = ayday - byday;
888 		long hours = a->tm_hour - b->tm_hour + 24 * days;
889 		long minutes = a->tm_min - b->tm_min + 60 * hours;
890 		long seconds = a->tm_sec - b->tm_sec + 60 * minutes;
891 		return seconds;
892 	}
893 #endif
894 }
895 
896 static void
show(timezone_t tz,char * zone,time_t t,bool v)897 show(timezone_t tz, char *zone, time_t t, bool v)
898 {
899 	struct tm *	tmp;
900 	struct tm *	gmtmp;
901 	struct tm tm, gmtm;
902 
903 	(void) printf("%-*s  ", (int) longest, zone);
904 	if (v) {
905 		gmtmp = my_gmtime_r(&t, &gmtm);
906 		if (gmtmp == NULL) {
907 			printf(tformat(), t);
908 		} else {
909 			dumptime(gmtmp);
910 			(void) printf(" UT");
911 		}
912 		(void) printf(" = ");
913 	}
914 	tmp = my_localtime_rz(tz, &t, &tm);
915 	dumptime(tmp);
916 	if (tmp != NULL) {
917 		if (*abbr(tmp) != '\0')
918 			(void) printf(" %s", abbr(tmp));
919 		if (v) {
920 			long off = gmtoff(tmp, gmtmp);
921 			(void) printf(" isdst=%d", tmp->tm_isdst);
922 			if (off != LONG_MIN)
923 				(void) printf(" gmtoff=%ld", off);
924 		}
925 	}
926 	(void) printf("\n");
927 	if (tmp != NULL && *abbr(tmp) != '\0')
928 		abbrok(abbr(tmp), zone);
929 }
930 
931 static const char *
abbr(struct tm const * tmp)932 abbr(struct tm const *tmp)
933 {
934 #ifdef TM_ZONE
935 	return tmp->TM_ZONE;
936 #else
937 	return (0 <= tmp->tm_isdst && tzname[0 < tmp->tm_isdst]
938 		? tzname[0 < tmp->tm_isdst]
939 		: "");
940 #endif
941 }
942 
943 /*
944 ** The code below can fail on certain theoretical systems;
945 ** it works on all known real-world systems as of 2004-12-30.
946 */
947 
948 static const char *
tformat(void)949 tformat(void)
950 {
951 	if (0 > (time_t) -1) {		/* signed */
952 		if (sizeof (time_t) == sizeof (intmax_t))
953 			return "%"PRIdMAX;
954 		if (sizeof (time_t) > sizeof (long))
955 			return "%lld";
956 		if (sizeof (time_t) > sizeof (int))
957 			return "%ld";
958 		return "%d";
959 	}
960 #ifdef PRIuMAX
961 	if (sizeof (time_t) == sizeof (uintmax_t))
962 		return "%"PRIuMAX;
963 #endif
964 	if (sizeof (time_t) > sizeof (unsigned long))
965 		return "%llu";
966 	if (sizeof (time_t) > sizeof (unsigned int))
967 		return "%lu";
968 	return "%u";
969 }
970 
971 static void
dumptime(const struct tm * timeptr)972 dumptime(const struct tm *timeptr)
973 {
974 	static const char	wday_name[][3] = {
975 		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
976 	};
977 	static const char	mon_name[][3] = {
978 		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
979 		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
980 	};
981 	const char *	wn;
982 	const char *	mn;
983 	int		lead;
984 	int		trail;
985 
986 	if (timeptr == NULL) {
987 		printf("NULL");
988 		return;
989 	}
990 	/*
991 	** The packaged localtime_rz and gmtime_r never put out-of-range
992 	** values in tm_wday or tm_mon, but since this code might be compiled
993 	** with other (perhaps experimental) versions, paranoia is in order.
994 	*/
995 	if (timeptr->tm_wday < 0 || timeptr->tm_wday >=
996 		(int) (sizeof wday_name / sizeof wday_name[0]))
997 			wn = "???";
998 	else		wn = wday_name[timeptr->tm_wday];
999 	if (timeptr->tm_mon < 0 || timeptr->tm_mon >=
1000 		(int) (sizeof mon_name / sizeof mon_name[0]))
1001 			mn = "???";
1002 	else		mn = mon_name[timeptr->tm_mon];
1003 	printf("%.3s %.3s%3d %.2d:%.2d:%.2d ",
1004 		wn, mn,
1005 		timeptr->tm_mday, timeptr->tm_hour,
1006 		timeptr->tm_min, timeptr->tm_sec);
1007 #define DIVISOR	10
1008 	trail = timeptr->tm_year % DIVISOR + TM_YEAR_BASE % DIVISOR;
1009 	lead = timeptr->tm_year / DIVISOR + TM_YEAR_BASE / DIVISOR +
1010 		trail / DIVISOR;
1011 	trail %= DIVISOR;
1012 	if (trail < 0 && lead > 0) {
1013 		trail += DIVISOR;
1014 		--lead;
1015 	} else if (lead < 0 && trail > 0) {
1016 		trail -= DIVISOR;
1017 		++lead;
1018 	}
1019 	if (lead == 0)
1020 		printf("%d", trail);
1021 	else	printf("%d%d", lead, ((trail < 0) ? -trail : trail));
1022 }
1023