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