Replace FSF snail mail address with URLs.
[platform/upstream/glibc.git] / timezone / zic.c
1 /*
2 ** This file is in the public domain, so clarified as of
3 ** 2006-07-17 by Arthur David Olson.
4 */
5
6 static char     elsieid[] = "@(#)zic.c  8.19";
7
8 #include "private.h"
9 #include "locale.h"
10 #include "tzfile.h"
11
12 #define ZIC_VERSION     '2'
13
14 typedef int_fast64_t    zic_t;
15
16 #ifndef ZIC_MAX_ABBR_LEN_WO_WARN
17 #define ZIC_MAX_ABBR_LEN_WO_WARN        6
18 #endif /* !defined ZIC_MAX_ABBR_LEN_WO_WARN */
19
20 #if HAVE_SYS_STAT_H
21 #include "sys/stat.h"
22 #endif
23 #ifdef S_IRUSR
24 #define MKDIR_UMASK (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
25 #else
26 #define MKDIR_UMASK 0755
27 #endif
28
29 /*
30 ** On some ancient hosts, predicates like `isspace(C)' are defined
31 ** only if isascii(C) || C == EOF. Modern hosts obey the C Standard,
32 ** which says they are defined only if C == ((unsigned char) C) || C == EOF.
33 ** Neither the C Standard nor Posix require that `isascii' exist.
34 ** For portability, we check both ancient and modern requirements.
35 ** If isascii is not defined, the isascii check succeeds trivially.
36 */
37 #include "ctype.h"
38 #ifndef isascii
39 #define isascii(x) 1
40 #endif
41
42 #define OFFSET_STRLEN_MAXIMUM   (7 + INT_STRLEN_MAXIMUM(long))
43 #define RULE_STRLEN_MAXIMUM     8       /* "Mdd.dd.d" */
44
45 #define end(cp) (strchr((cp), '\0'))
46
47 struct rule {
48         const char *    r_filename;
49         int             r_linenum;
50         const char *    r_name;
51
52         int             r_loyear;       /* for example, 1986 */
53         int             r_hiyear;       /* for example, 1986 */
54         const char *    r_yrtype;
55         int             r_lowasnum;
56         int             r_hiwasnum;
57
58         int             r_month;        /* 0..11 */
59
60         int             r_dycode;       /* see below */
61         int             r_dayofmonth;
62         int             r_wday;
63
64         long            r_tod;          /* time from midnight */
65         int             r_todisstd;     /* above is standard time if TRUE */
66                                         /* or wall clock time if FALSE */
67         int             r_todisgmt;     /* above is GMT if TRUE */
68                                         /* or local time if FALSE */
69         long            r_stdoff;       /* offset from standard time */
70         const char *    r_abbrvar;      /* variable part of abbreviation */
71
72         int             r_todo;         /* a rule to do (used in outzone) */
73         zic_t           r_temp;         /* used in outzone */
74 };
75
76 /*
77 **      r_dycode                r_dayofmonth    r_wday
78 */
79
80 #define DC_DOM          0       /* 1..31 */     /* unused */
81 #define DC_DOWGEQ       1       /* 1..31 */     /* 0..6 (Sun..Sat) */
82 #define DC_DOWLEQ       2       /* 1..31 */     /* 0..6 (Sun..Sat) */
83
84 struct zone {
85         const char *    z_filename;
86         int             z_linenum;
87
88         const char *    z_name;
89         long            z_gmtoff;
90         const char *    z_rule;
91         const char *    z_format;
92
93         long            z_stdoff;
94
95         struct rule *   z_rules;
96         int             z_nrules;
97
98         struct rule     z_untilrule;
99         zic_t           z_untiltime;
100 };
101
102 extern int      getopt(int argc, char * const argv[],
103                         const char * options);
104 extern int      link(const char * fromname, const char * toname);
105 extern char *   optarg;
106 extern int      optind;
107
108 static void     addtt(zic_t starttime, int type);
109 static int      addtype(long gmtoff, const char * abbr, int isdst,
110                                 int ttisstd, int ttisgmt);
111 static void     leapadd(zic_t t, int positive, int rolling, int count);
112 static void     adjleap(void);
113 static void     associate(void);
114 static int      ciequal(const char * ap, const char * bp);
115 static void     convert(long val, char * buf);
116 static void     convert64(zic_t val, char * buf);
117 static void     dolink(const char * fromfield, const char * tofield);
118 static void     doabbr(char * abbr, const char * format,
119                         const char * letters, int isdst, int doquotes);
120 static void     eat(const char * name, int num);
121 static void     eats(const char * name, int num,
122                         const char * rname, int rnum);
123 static long     eitol(int i);
124 static void     error(const char * message);
125 static char **  getfields(char * buf);
126 static long     gethms(const char * string, const char * errstrng,
127                         int signable);
128 static void     infile(const char * filename);
129 static void     inleap(char ** fields, int nfields);
130 static void     inlink(char ** fields, int nfields);
131 static void     inrule(char ** fields, int nfields);
132 static int      inzcont(char ** fields, int nfields);
133 static int      inzone(char ** fields, int nfields);
134 static int      inzsub(char ** fields, int nfields, int iscont);
135 static int      is32(zic_t x);
136 static int      itsabbr(const char * abbr, const char * word);
137 static int      itsdir(const char * name);
138 static int      lowerit(int c);
139 static char *   memcheck(char * tocheck);
140 static int      mkdirs(char * filename);
141 static void     newabbr(const char * abbr);
142 static long     oadd(long t1, long t2);
143 static void     outzone(const struct zone * zp, int ntzones);
144 static void     puttzcode(long code, FILE * fp);
145 static void     puttzcode64(zic_t code, FILE * fp);
146 static int      rcomp(const void * leftp, const void * rightp);
147 static zic_t    rpytime(const struct rule * rp, int wantedy);
148 static void     rulesub(struct rule * rp,
149                         const char * loyearp, const char * hiyearp,
150                         const char * typep, const char * monthp,
151                         const char * dayp, const char * timep);
152 static int      stringoffset(char * result, long offset);
153 static int      stringrule(char * result, const struct rule * rp,
154                         long dstoff, long gmtoff);
155 static void     stringzone(char * result,
156                         const struct zone * zp, int ntzones);
157 static void     setboundaries(void);
158 static zic_t    tadd(zic_t t1, long t2);
159 static void     usage(FILE *stream, int status);
160 static void     writezone(const char * name, const char * string);
161 static int      yearistype(int year, const char * type);
162
163 static int              charcnt;
164 static int              errors;
165 static const char *     filename;
166 static int              leapcnt;
167 static int              leapseen;
168 static int              leapminyear;
169 static int              leapmaxyear;
170 static int              linenum;
171 static int              max_abbrvar_len;
172 static int              max_format_len;
173 static zic_t            max_time;
174 static int              max_year;
175 static zic_t            min_time;
176 static int              min_year;
177 static int              noise;
178 static const char *     rfilename;
179 static int              rlinenum;
180 static const char *     progname;
181 static int              timecnt;
182 static int              typecnt;
183
184 /*
185 ** Line codes.
186 */
187
188 #define LC_RULE         0
189 #define LC_ZONE         1
190 #define LC_LINK         2
191 #define LC_LEAP         3
192
193 /*
194 ** Which fields are which on a Zone line.
195 */
196
197 #define ZF_NAME         1
198 #define ZF_GMTOFF       2
199 #define ZF_RULE         3
200 #define ZF_FORMAT       4
201 #define ZF_TILYEAR      5
202 #define ZF_TILMONTH     6
203 #define ZF_TILDAY       7
204 #define ZF_TILTIME      8
205 #define ZONE_MINFIELDS  5
206 #define ZONE_MAXFIELDS  9
207
208 /*
209 ** Which fields are which on a Zone continuation line.
210 */
211
212 #define ZFC_GMTOFF      0
213 #define ZFC_RULE        1
214 #define ZFC_FORMAT      2
215 #define ZFC_TILYEAR     3
216 #define ZFC_TILMONTH    4
217 #define ZFC_TILDAY      5
218 #define ZFC_TILTIME     6
219 #define ZONEC_MINFIELDS 3
220 #define ZONEC_MAXFIELDS 7
221
222 /*
223 ** Which files are which on a Rule line.
224 */
225
226 #define RF_NAME         1
227 #define RF_LOYEAR       2
228 #define RF_HIYEAR       3
229 #define RF_COMMAND      4
230 #define RF_MONTH        5
231 #define RF_DAY          6
232 #define RF_TOD          7
233 #define RF_STDOFF       8
234 #define RF_ABBRVAR      9
235 #define RULE_FIELDS     10
236
237 /*
238 ** Which fields are which on a Link line.
239 */
240
241 #define LF_FROM         1
242 #define LF_TO           2
243 #define LINK_FIELDS     3
244
245 /*
246 ** Which fields are which on a Leap line.
247 */
248
249 #define LP_YEAR         1
250 #define LP_MONTH        2
251 #define LP_DAY          3
252 #define LP_TIME         4
253 #define LP_CORR         5
254 #define LP_ROLL         6
255 #define LEAP_FIELDS     7
256
257 /*
258 ** Year synonyms.
259 */
260
261 #define YR_MINIMUM      0
262 #define YR_MAXIMUM      1
263 #define YR_ONLY         2
264
265 static struct rule *    rules;
266 static int              nrules; /* number of rules */
267
268 static struct zone *    zones;
269 static int              nzones; /* number of zones */
270
271 struct link {
272         const char *    l_filename;
273         int             l_linenum;
274         const char *    l_from;
275         const char *    l_to;
276 };
277
278 static struct link *    links;
279 static int              nlinks;
280
281 struct lookup {
282         const char *    l_word;
283         const int       l_value;
284 };
285
286 static struct lookup const *    byword(const char * string,
287                                         const struct lookup * lp);
288
289 static struct lookup const      line_codes[] = {
290         { "Rule",       LC_RULE },
291         { "Zone",       LC_ZONE },
292         { "Link",       LC_LINK },
293         { "Leap",       LC_LEAP },
294         { NULL,         0}
295 };
296
297 static struct lookup const      mon_names[] = {
298         { "January",    TM_JANUARY },
299         { "February",   TM_FEBRUARY },
300         { "March",      TM_MARCH },
301         { "April",      TM_APRIL },
302         { "May",        TM_MAY },
303         { "June",       TM_JUNE },
304         { "July",       TM_JULY },
305         { "August",     TM_AUGUST },
306         { "September",  TM_SEPTEMBER },
307         { "October",    TM_OCTOBER },
308         { "November",   TM_NOVEMBER },
309         { "December",   TM_DECEMBER },
310         { NULL,         0 }
311 };
312
313 static struct lookup const      wday_names[] = {
314         { "Sunday",     TM_SUNDAY },
315         { "Monday",     TM_MONDAY },
316         { "Tuesday",    TM_TUESDAY },
317         { "Wednesday",  TM_WEDNESDAY },
318         { "Thursday",   TM_THURSDAY },
319         { "Friday",     TM_FRIDAY },
320         { "Saturday",   TM_SATURDAY },
321         { NULL,         0 }
322 };
323
324 static struct lookup const      lasts[] = {
325         { "last-Sunday",        TM_SUNDAY },
326         { "last-Monday",        TM_MONDAY },
327         { "last-Tuesday",       TM_TUESDAY },
328         { "last-Wednesday",     TM_WEDNESDAY },
329         { "last-Thursday",      TM_THURSDAY },
330         { "last-Friday",        TM_FRIDAY },
331         { "last-Saturday",      TM_SATURDAY },
332         { NULL,                 0 }
333 };
334
335 static struct lookup const      begin_years[] = {
336         { "minimum",    YR_MINIMUM },
337         { "maximum",    YR_MAXIMUM },
338         { NULL,         0 }
339 };
340
341 static struct lookup const      end_years[] = {
342         { "minimum",    YR_MINIMUM },
343         { "maximum",    YR_MAXIMUM },
344         { "only",       YR_ONLY },
345         { NULL,         0 }
346 };
347
348 static struct lookup const      leap_types[] = {
349         { "Rolling",    TRUE },
350         { "Stationary", FALSE },
351         { NULL,         0 }
352 };
353
354 static const int        len_months[2][MONSPERYEAR] = {
355         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
356         { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
357 };
358
359 static const int        len_years[2] = {
360         DAYSPERNYEAR, DAYSPERLYEAR
361 };
362
363 static struct attype {
364         zic_t           at;
365         unsigned char   type;
366 }                       attypes[TZ_MAX_TIMES];
367 static long             gmtoffs[TZ_MAX_TYPES];
368 static char             isdsts[TZ_MAX_TYPES];
369 static unsigned char    abbrinds[TZ_MAX_TYPES];
370 static char             ttisstds[TZ_MAX_TYPES];
371 static char             ttisgmts[TZ_MAX_TYPES];
372 static char             chars[TZ_MAX_CHARS];
373 static zic_t            trans[TZ_MAX_LEAPS];
374 static long             corr[TZ_MAX_LEAPS];
375 static char             roll[TZ_MAX_LEAPS];
376
377 /*
378 ** Memory allocation.
379 */
380
381 static char *
382 memcheck(ptr)
383 char * const    ptr;
384 {
385         if (ptr == NULL) {
386                 const char *e = strerror(errno);
387
388                 (void) fprintf(stderr, _("%s: Memory exhausted: %s\n"),
389                         progname, e);
390                 exit(EXIT_FAILURE);
391         }
392         return ptr;
393 }
394
395 #define emalloc(size)           memcheck(imalloc(size))
396 #define erealloc(ptr, size)     memcheck(irealloc((ptr), (size)))
397 #define ecpyalloc(ptr)          memcheck(icpyalloc(ptr))
398 #define ecatalloc(oldp, newp)   memcheck(icatalloc((oldp), (newp)))
399
400 /*
401 ** Error handling.
402 */
403
404 static void
405 eats(name, num, rname, rnum)
406 const char * const      name;
407 const int               num;
408 const char * const      rname;
409 const int               rnum;
410 {
411         filename = name;
412         linenum = num;
413         rfilename = rname;
414         rlinenum = rnum;
415 }
416
417 static void
418 eat(name, num)
419 const char * const      name;
420 const int               num;
421 {
422         eats(name, num, (char *) NULL, -1);
423 }
424
425 static void
426 error(string)
427 const char * const      string;
428 {
429         /*
430         ** Match the format of "cc" to allow sh users to
431         **      zic ... 2>&1 | error -t "*" -v
432         ** on BSD systems.
433         */
434         (void) fprintf(stderr, _("\"%s\", line %d: %s"),
435                 filename, linenum, string);
436         if (rfilename != NULL)
437                 (void) fprintf(stderr, _(" (rule from \"%s\", line %d)"),
438                         rfilename, rlinenum);
439         (void) fprintf(stderr, "\n");
440         ++errors;
441 }
442
443 static void
444 warning(string)
445 const char * const      string;
446 {
447         char *  cp;
448
449         cp = ecpyalloc(_("warning: "));
450         cp = ecatalloc(cp, string);
451         error(cp);
452         ifree(cp);
453         --errors;
454 }
455
456 static void
457 usage(FILE *stream, int status)
458 {
459         (void) fprintf(stream, _("%s: usage is %s \
460 [ --version ] [ --help ] [ -v ] [ -l localtime ] [ -p posixrules ] \\\n\
461 \t[ -d directory ] [ -L leapseconds ] [ -y yearistype ] [ filename ... ]\n\
462 \n\
463 Report bugs to tz@elsie.nci.nih.gov.\n"),
464                        progname, progname);
465         exit(status);
466 }
467
468 static const char *     psxrules;
469 static const char *     lcltime;
470 static const char *     directory;
471 static const char *     leapsec;
472 static const char *     yitcommand;
473
474 int
475 main(argc, argv)
476 int     argc;
477 char *  argv[];
478 {
479         register int    i;
480         register int    j;
481         register int    c;
482
483 #ifdef unix
484         (void) umask(umask(S_IWGRP | S_IWOTH) | (S_IWGRP | S_IWOTH));
485 #endif /* defined unix */
486 #if HAVE_GETTEXT
487         (void) setlocale(LC_ALL, "");
488 #ifdef TZ_DOMAINDIR
489         (void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
490 #endif /* defined TEXTDOMAINDIR */
491         (void) textdomain(TZ_DOMAIN);
492 #endif /* HAVE_GETTEXT */
493         progname = argv[0];
494         if (TYPE_BIT(zic_t) < 64) {
495                 (void) fprintf(stderr, "%s: %s\n", progname,
496                         _("wild compilation-time specification of zic_t"));
497                 exit(EXIT_FAILURE);
498         }
499         for (i = 1; i < argc; ++i)
500                 if (strcmp(argv[i], "--version") == 0) {
501                         (void) printf("%s\n", elsieid);
502                         exit(EXIT_SUCCESS);
503                 } else if (strcmp(argv[i], "--help") == 0) {
504                         usage(stdout, EXIT_SUCCESS);
505                 }
506         while ((c = getopt(argc, argv, "d:l:p:L:vsy:")) != EOF && c != -1)
507                 switch (c) {
508                         default:
509                                 usage(stderr, EXIT_FAILURE);
510                         case 'd':
511                                 if (directory == NULL)
512                                         directory = optarg;
513                                 else {
514                                         (void) fprintf(stderr,
515 _("%s: More than one -d option specified\n"),
516                                                 progname);
517                                         exit(EXIT_FAILURE);
518                                 }
519                                 break;
520                         case 'l':
521                                 if (lcltime == NULL)
522                                         lcltime = optarg;
523                                 else {
524                                         (void) fprintf(stderr,
525 _("%s: More than one -l option specified\n"),
526                                                 progname);
527                                         exit(EXIT_FAILURE);
528                                 }
529                                 break;
530                         case 'p':
531                                 if (psxrules == NULL)
532                                         psxrules = optarg;
533                                 else {
534                                         (void) fprintf(stderr,
535 _("%s: More than one -p option specified\n"),
536                                                 progname);
537                                         exit(EXIT_FAILURE);
538                                 }
539                                 break;
540                         case 'y':
541                                 if (yitcommand == NULL)
542                                         yitcommand = optarg;
543                                 else {
544                                         (void) fprintf(stderr,
545 _("%s: More than one -y option specified\n"),
546                                                 progname);
547                                         exit(EXIT_FAILURE);
548                                 }
549                                 break;
550                         case 'L':
551                                 if (leapsec == NULL)
552                                         leapsec = optarg;
553                                 else {
554                                         (void) fprintf(stderr,
555 _("%s: More than one -L option specified\n"),
556                                                 progname);
557                                         exit(EXIT_FAILURE);
558                                 }
559                                 break;
560                         case 'v':
561                                 noise = TRUE;
562                                 break;
563                         case 's':
564                                 (void) printf("%s: -s ignored\n", progname);
565                                 break;
566                 }
567         if (optind == argc - 1 && strcmp(argv[optind], "=") == 0)
568                 usage(stderr, EXIT_FAILURE);    /* usage message by request */
569         if (directory == NULL)
570                 directory = TZDIR;
571         if (yitcommand == NULL)
572                 yitcommand = "yearistype";
573
574         setboundaries();
575
576         if (optind < argc && leapsec != NULL) {
577                 infile(leapsec);
578                 adjleap();
579         }
580
581         for (i = optind; i < argc; ++i)
582                 infile(argv[i]);
583         if (errors)
584                 exit(EXIT_FAILURE);
585         associate();
586         for (i = 0; i < nzones; i = j) {
587                 /*
588                 ** Find the next non-continuation zone entry.
589                 */
590                 for (j = i + 1; j < nzones && zones[j].z_name == NULL; ++j)
591                         continue;
592                 outzone(&zones[i], j - i);
593         }
594         /*
595         ** Make links.
596         */
597         for (i = 0; i < nlinks; ++i) {
598                 eat(links[i].l_filename, links[i].l_linenum);
599                 dolink(links[i].l_from, links[i].l_to);
600                 if (noise)
601                         for (j = 0; j < nlinks; ++j)
602                                 if (strcmp(links[i].l_to,
603                                         links[j].l_from) == 0)
604                                                 warning(_("link to link"));
605         }
606         if (lcltime != NULL) {
607                 eat("command line", 1);
608                 dolink(lcltime, TZDEFAULT);
609         }
610         if (psxrules != NULL) {
611                 eat("command line", 1);
612                 dolink(psxrules, TZDEFRULES);
613         }
614         return (errors == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
615 }
616
617 static void
618 dolink(fromfield, tofield)
619 const char * const      fromfield;
620 const char * const      tofield;
621 {
622         register char * fromname;
623         register char * toname;
624
625         if (fromfield[0] == '/')
626                 fromname = ecpyalloc(fromfield);
627         else {
628                 fromname = ecpyalloc(directory);
629                 fromname = ecatalloc(fromname, "/");
630                 fromname = ecatalloc(fromname, fromfield);
631         }
632         if (tofield[0] == '/')
633                 toname = ecpyalloc(tofield);
634         else {
635                 toname = ecpyalloc(directory);
636                 toname = ecatalloc(toname, "/");
637                 toname = ecatalloc(toname, tofield);
638         }
639         /*
640         ** We get to be careful here since
641         ** there's a fair chance of root running us.
642         */
643         if (!itsdir(toname))
644                 (void) remove(toname);
645         if (link(fromname, toname) != 0) {
646                 int     result;
647
648                 if (mkdirs(toname) != 0)
649                         exit(EXIT_FAILURE);
650
651                 result = link(fromname, toname);
652 #if HAVE_SYMLINK
653                 if (result != 0 &&
654                         access(fromname, F_OK) == 0 &&
655                         !itsdir(fromname)) {
656                                 const char *s = tofield;
657                                 register char * symlinkcontents = NULL;
658
659                                 while ((s = strchr(s+1, '/')) != NULL)
660                                         symlinkcontents =
661                                                 ecatalloc(symlinkcontents,
662                                                 "../");
663                                 symlinkcontents =
664                                         ecatalloc(symlinkcontents,
665                                         fromname);
666                                 result = symlink(symlinkcontents,
667                                         toname);
668                                 if (result == 0)
669 warning(_("hard link failed, symbolic link used"));
670                                 ifree(symlinkcontents);
671                 }
672 #endif /* HAVE_SYMLINK */
673                 if (result != 0) {
674                         const char *e = strerror(errno);
675
676                         (void) fprintf(stderr,
677                                 _("%s: Can't link from %s to %s: %s\n"),
678                                 progname, fromname, toname, e);
679                         exit(EXIT_FAILURE);
680                 }
681         }
682         ifree(fromname);
683         ifree(toname);
684 }
685
686 #define TIME_T_BITS_IN_FILE     64
687
688 static void
689 setboundaries(void)
690 {
691         register int    i;
692
693         min_time = -1;
694         for (i = 0; i < TIME_T_BITS_IN_FILE - 1; ++i)
695                 min_time *= 2;
696         max_time = -(min_time + 1);
697 }
698
699 static int
700 itsdir(name)
701 const char * const      name;
702 {
703         register char * myname;
704         register int    accres;
705
706         myname = ecpyalloc(name);
707         myname = ecatalloc(myname, "/.");
708         accres = access(myname, F_OK);
709         ifree(myname);
710         return accres == 0;
711 }
712
713 /*
714 ** Associate sets of rules with zones.
715 */
716
717 /*
718 ** Sort by rule name.
719 */
720
721 static int
722 rcomp(cp1, cp2)
723 const void *    cp1;
724 const void *    cp2;
725 {
726         return strcmp(((const struct rule *) cp1)->r_name,
727                 ((const struct rule *) cp2)->r_name);
728 }
729
730 static void
731 associate(void)
732 {
733         register struct zone *  zp;
734         register struct rule *  rp;
735         register int            base, out;
736         register int            i, j;
737
738         if (nrules != 0) {
739                 (void) qsort((void *) rules, (size_t) nrules,
740                         (size_t) sizeof *rules, rcomp);
741                 for (i = 0; i < nrules - 1; ++i) {
742                         if (strcmp(rules[i].r_name,
743                                 rules[i + 1].r_name) != 0)
744                                         continue;
745                         if (strcmp(rules[i].r_filename,
746                                 rules[i + 1].r_filename) == 0)
747                                         continue;
748                         eat(rules[i].r_filename, rules[i].r_linenum);
749                         warning(_("same rule name in multiple files"));
750                         eat(rules[i + 1].r_filename, rules[i + 1].r_linenum);
751                         warning(_("same rule name in multiple files"));
752                         for (j = i + 2; j < nrules; ++j) {
753                                 if (strcmp(rules[i].r_name,
754                                         rules[j].r_name) != 0)
755                                                 break;
756                                 if (strcmp(rules[i].r_filename,
757                                         rules[j].r_filename) == 0)
758                                                 continue;
759                                 if (strcmp(rules[i + 1].r_filename,
760                                         rules[j].r_filename) == 0)
761                                                 continue;
762                                 break;
763                         }
764                         i = j - 1;
765                 }
766         }
767         for (i = 0; i < nzones; ++i) {
768                 zp = &zones[i];
769                 zp->z_rules = NULL;
770                 zp->z_nrules = 0;
771         }
772         for (base = 0; base < nrules; base = out) {
773                 rp = &rules[base];
774                 for (out = base + 1; out < nrules; ++out)
775                         if (strcmp(rp->r_name, rules[out].r_name) != 0)
776                                 break;
777                 for (i = 0; i < nzones; ++i) {
778                         zp = &zones[i];
779                         if (strcmp(zp->z_rule, rp->r_name) != 0)
780                                 continue;
781                         zp->z_rules = rp;
782                         zp->z_nrules = out - base;
783                 }
784         }
785         for (i = 0; i < nzones; ++i) {
786                 zp = &zones[i];
787                 if (zp->z_nrules == 0) {
788                         /*
789                         ** Maybe we have a local standard time offset.
790                         */
791                         eat(zp->z_filename, zp->z_linenum);
792                         zp->z_stdoff = gethms(zp->z_rule, _("unruly zone"),
793                                 TRUE);
794                         /*
795                         ** Note, though, that if there's no rule,
796                         ** a '%s' in the format is a bad thing.
797                         */
798                         if (strchr(zp->z_format, '%') != 0)
799                                 error(_("%s in ruleless zone"));
800                 }
801         }
802         if (errors)
803                 exit(EXIT_FAILURE);
804 }
805
806 static void
807 infile(name)
808 const char *    name;
809 {
810         register FILE *                 fp;
811         register char **                fields;
812         register char *                 cp;
813         register const struct lookup *  lp;
814         register int                    nfields;
815         register int                    wantcont;
816         register int                    num;
817         char                            buf[BUFSIZ];
818
819         if (strcmp(name, "-") == 0) {
820                 name = _("standard input");
821                 fp = stdin;
822         } else if ((fp = fopen(name, "r")) == NULL) {
823                 const char *e = strerror(errno);
824
825                 (void) fprintf(stderr, _("%s: Can't open %s: %s\n"),
826                         progname, name, e);
827                 exit(EXIT_FAILURE);
828         }
829         wantcont = FALSE;
830         for (num = 1; ; ++num) {
831                 eat(name, num);
832                 if (fgets(buf, (int) sizeof buf, fp) != buf)
833                         break;
834                 cp = strchr(buf, '\n');
835                 if (cp == NULL) {
836                         error(_("line too long"));
837                         exit(EXIT_FAILURE);
838                 }
839                 *cp = '\0';
840                 fields = getfields(buf);
841                 nfields = 0;
842                 while (fields[nfields] != NULL) {
843                         static char     nada;
844
845                         if (strcmp(fields[nfields], "-") == 0)
846                                 fields[nfields] = &nada;
847                         ++nfields;
848                 }
849                 if (nfields == 0) {
850                         /* nothing to do */
851                 } else if (wantcont) {
852                         wantcont = inzcont(fields, nfields);
853                 } else {
854                         lp = byword(fields[0], line_codes);
855                         if (lp == NULL)
856                                 error(_("input line of unknown type"));
857                         else switch ((int) (lp->l_value)) {
858                                 case LC_RULE:
859                                         inrule(fields, nfields);
860                                         wantcont = FALSE;
861                                         break;
862                                 case LC_ZONE:
863                                         wantcont = inzone(fields, nfields);
864                                         break;
865                                 case LC_LINK:
866                                         inlink(fields, nfields);
867                                         wantcont = FALSE;
868                                         break;
869                                 case LC_LEAP:
870                                         if (name != leapsec)
871                                                 (void) fprintf(stderr,
872 _("%s: Leap line in non leap seconds file %s\n"),
873                                                         progname, name);
874                                         else    inleap(fields, nfields);
875                                         wantcont = FALSE;
876                                         break;
877                                 default:        /* "cannot happen" */
878                                         (void) fprintf(stderr,
879 _("%s: panic: Invalid l_value %d\n"),
880                                                 progname, lp->l_value);
881                                         exit(EXIT_FAILURE);
882                         }
883                 }
884                 ifree((char *) fields);
885         }
886         if (ferror(fp)) {
887                 (void) fprintf(stderr, _("%s: Error reading %s\n"),
888                         progname, filename);
889                 exit(EXIT_FAILURE);
890         }
891         if (fp != stdin && fclose(fp)) {
892                 const char *e = strerror(errno);
893
894                 (void) fprintf(stderr, _("%s: Error closing %s: %s\n"),
895                         progname, filename, e);
896                 exit(EXIT_FAILURE);
897         }
898         if (wantcont)
899                 error(_("expected continuation line not found"));
900 }
901
902 /*
903 ** Convert a string of one of the forms
904 **      h       -h      hh:mm   -hh:mm  hh:mm:ss        -hh:mm:ss
905 ** into a number of seconds.
906 ** A null string maps to zero.
907 ** Call error with errstring and return zero on errors.
908 */
909
910 static long
911 gethms(string, errstring, signable)
912 const char *            string;
913 const char * const      errstring;
914 const int               signable;
915 {
916         long    hh;
917         int     mm, ss, sign;
918
919         if (string == NULL || *string == '\0')
920                 return 0;
921         if (!signable)
922                 sign = 1;
923         else if (*string == '-') {
924                 sign = -1;
925                 ++string;
926         } else  sign = 1;
927         if (sscanf(string, scheck(string, "%ld"), &hh) == 1)
928                 mm = ss = 0;
929         else if (sscanf(string, scheck(string, "%ld:%d"), &hh, &mm) == 2)
930                 ss = 0;
931         else if (sscanf(string, scheck(string, "%ld:%d:%d"),
932                 &hh, &mm, &ss) != 3) {
933                         error(errstring);
934                         return 0;
935         }
936         if (hh < 0 ||
937                 mm < 0 || mm >= MINSPERHOUR ||
938                 ss < 0 || ss > SECSPERMIN) {
939                         error(errstring);
940                         return 0;
941         }
942         if (LONG_MAX / SECSPERHOUR < hh) {
943                 error(_("time overflow"));
944                 return 0;
945         }
946         if (noise && hh == HOURSPERDAY && mm == 0 && ss == 0)
947                 warning(_("24:00 not handled by pre-1998 versions of zic"));
948         if (noise && (hh > HOURSPERDAY ||
949                 (hh == HOURSPERDAY && (mm != 0 || ss != 0))))
950 warning(_("values over 24 hours not handled by pre-2007 versions of zic"));
951         return oadd(eitol(sign) * hh * eitol(SECSPERHOUR),
952                     eitol(sign) * (eitol(mm) * eitol(SECSPERMIN) + eitol(ss)));
953 }
954
955 static void
956 inrule(fields, nfields)
957 register char ** const  fields;
958 const int               nfields;
959 {
960         static struct rule      r;
961
962         if (nfields != RULE_FIELDS) {
963                 error(_("wrong number of fields on Rule line"));
964                 return;
965         }
966         if (*fields[RF_NAME] == '\0') {
967                 error(_("nameless rule"));
968                 return;
969         }
970         r.r_filename = filename;
971         r.r_linenum = linenum;
972         r.r_stdoff = gethms(fields[RF_STDOFF], _("invalid saved time"), TRUE);
973         rulesub(&r, fields[RF_LOYEAR], fields[RF_HIYEAR], fields[RF_COMMAND],
974                 fields[RF_MONTH], fields[RF_DAY], fields[RF_TOD]);
975         r.r_name = ecpyalloc(fields[RF_NAME]);
976         r.r_abbrvar = ecpyalloc(fields[RF_ABBRVAR]);
977         if (max_abbrvar_len < strlen(r.r_abbrvar))
978                 max_abbrvar_len = strlen(r.r_abbrvar);
979         rules = (struct rule *) (void *) erealloc((char *) rules,
980                 (int) ((nrules + 1) * sizeof *rules));
981         rules[nrules++] = r;
982 }
983
984 static int
985 inzone(fields, nfields)
986 register char ** const  fields;
987 const int               nfields;
988 {
989         register int    i;
990         static char *   buf;
991
992         if (nfields < ZONE_MINFIELDS || nfields > ZONE_MAXFIELDS) {
993                 error(_("wrong number of fields on Zone line"));
994                 return FALSE;
995         }
996         if (strcmp(fields[ZF_NAME], TZDEFAULT) == 0 && lcltime != NULL) {
997                 buf = erealloc(buf, (int) (132 + strlen(TZDEFAULT)));
998                 (void) sprintf(buf,
999 _("\"Zone %s\" line and -l option are mutually exclusive"),
1000                         TZDEFAULT);
1001                 error(buf);
1002                 return FALSE;
1003         }
1004         if (strcmp(fields[ZF_NAME], TZDEFRULES) == 0 && psxrules != NULL) {
1005                 buf = erealloc(buf, (int) (132 + strlen(TZDEFRULES)));
1006                 (void) sprintf(buf,
1007 _("\"Zone %s\" line and -p option are mutually exclusive"),
1008                         TZDEFRULES);
1009                 error(buf);
1010                 return FALSE;
1011         }
1012         for (i = 0; i < nzones; ++i)
1013                 if (zones[i].z_name != NULL &&
1014                         strcmp(zones[i].z_name, fields[ZF_NAME]) == 0) {
1015                                 buf = erealloc(buf, (int) (132 +
1016                                         strlen(fields[ZF_NAME]) +
1017                                         strlen(zones[i].z_filename)));
1018                                 (void) sprintf(buf,
1019 _("duplicate zone name %s (file \"%s\", line %d)"),
1020                                         fields[ZF_NAME],
1021                                         zones[i].z_filename,
1022                                         zones[i].z_linenum);
1023                                 error(buf);
1024                                 return FALSE;
1025                 }
1026         return inzsub(fields, nfields, FALSE);
1027 }
1028
1029 static int
1030 inzcont(fields, nfields)
1031 register char ** const  fields;
1032 const int               nfields;
1033 {
1034         if (nfields < ZONEC_MINFIELDS || nfields > ZONEC_MAXFIELDS) {
1035                 error(_("wrong number of fields on Zone continuation line"));
1036                 return FALSE;
1037         }
1038         return inzsub(fields, nfields, TRUE);
1039 }
1040
1041 static int
1042 inzsub(fields, nfields, iscont)
1043 register char ** const  fields;
1044 const int               nfields;
1045 const int               iscont;
1046 {
1047         register char *         cp;
1048         static struct zone      z;
1049         register int            i_gmtoff, i_rule, i_format;
1050         register int            i_untilyear, i_untilmonth;
1051         register int            i_untilday, i_untiltime;
1052         register int            hasuntil;
1053
1054         if (iscont) {
1055                 i_gmtoff = ZFC_GMTOFF;
1056                 i_rule = ZFC_RULE;
1057                 i_format = ZFC_FORMAT;
1058                 i_untilyear = ZFC_TILYEAR;
1059                 i_untilmonth = ZFC_TILMONTH;
1060                 i_untilday = ZFC_TILDAY;
1061                 i_untiltime = ZFC_TILTIME;
1062                 z.z_name = NULL;
1063         } else {
1064                 i_gmtoff = ZF_GMTOFF;
1065                 i_rule = ZF_RULE;
1066                 i_format = ZF_FORMAT;
1067                 i_untilyear = ZF_TILYEAR;
1068                 i_untilmonth = ZF_TILMONTH;
1069                 i_untilday = ZF_TILDAY;
1070                 i_untiltime = ZF_TILTIME;
1071                 z.z_name = ecpyalloc(fields[ZF_NAME]);
1072         }
1073         z.z_filename = filename;
1074         z.z_linenum = linenum;
1075         z.z_gmtoff = gethms(fields[i_gmtoff], _("invalid UTC offset"), TRUE);
1076         if ((cp = strchr(fields[i_format], '%')) != 0) {
1077                 if (*++cp != 's' || strchr(cp, '%') != 0) {
1078                         error(_("invalid abbreviation format"));
1079                         return FALSE;
1080                 }
1081         }
1082         z.z_rule = ecpyalloc(fields[i_rule]);
1083         z.z_format = ecpyalloc(fields[i_format]);
1084         if (max_format_len < strlen(z.z_format))
1085                 max_format_len = strlen(z.z_format);
1086         hasuntil = nfields > i_untilyear;
1087         if (hasuntil) {
1088                 z.z_untilrule.r_filename = filename;
1089                 z.z_untilrule.r_linenum = linenum;
1090                 rulesub(&z.z_untilrule,
1091                         fields[i_untilyear],
1092                         "only",
1093                         "",
1094                         (nfields > i_untilmonth) ?
1095                         fields[i_untilmonth] : "Jan",
1096                         (nfields > i_untilday) ? fields[i_untilday] : "1",
1097                         (nfields > i_untiltime) ? fields[i_untiltime] : "0");
1098                 z.z_untiltime = rpytime(&z.z_untilrule,
1099                         z.z_untilrule.r_loyear);
1100                 if (iscont && nzones > 0 &&
1101                         z.z_untiltime > min_time &&
1102                         z.z_untiltime < max_time &&
1103                         zones[nzones - 1].z_untiltime > min_time &&
1104                         zones[nzones - 1].z_untiltime < max_time &&
1105                         zones[nzones - 1].z_untiltime >= z.z_untiltime) {
1106                                 error(_(
1107 "Zone continuation line end time is not after end time of previous line"
1108                                         ));
1109                                 return FALSE;
1110                 }
1111         }
1112         zones = (struct zone *) (void *) erealloc((char *) zones,
1113                 (int) ((nzones + 1) * sizeof *zones));
1114         zones[nzones++] = z;
1115         /*
1116         ** If there was an UNTIL field on this line,
1117         ** there's more information about the zone on the next line.
1118         */
1119         return hasuntil;
1120 }
1121
1122 static void
1123 inleap(fields, nfields)
1124 register char ** const  fields;
1125 const int               nfields;
1126 {
1127         register const char *           cp;
1128         register const struct lookup *  lp;
1129         register int                    i, j;
1130         int                             year, month, day;
1131         long                            dayoff, tod;
1132         zic_t                           t;
1133
1134         if (nfields != LEAP_FIELDS) {
1135                 error(_("wrong number of fields on Leap line"));
1136                 return;
1137         }
1138         dayoff = 0;
1139         cp = fields[LP_YEAR];
1140         if (sscanf(cp, scheck(cp, "%d"), &year) != 1) {
1141                 /*
1142                 ** Leapin' Lizards!
1143                 */
1144                 error(_("invalid leaping year"));
1145                 return;
1146         }
1147         if (!leapseen || leapmaxyear < year)
1148                 leapmaxyear = year;
1149         if (!leapseen || leapminyear > year)
1150                 leapminyear = year;
1151         leapseen = TRUE;
1152         j = EPOCH_YEAR;
1153         while (j != year) {
1154                 if (year > j) {
1155                         i = len_years[isleap(j)];
1156                         ++j;
1157                 } else {
1158                         --j;
1159                         i = -len_years[isleap(j)];
1160                 }
1161                 dayoff = oadd(dayoff, eitol(i));
1162         }
1163         if ((lp = byword(fields[LP_MONTH], mon_names)) == NULL) {
1164                 error(_("invalid month name"));
1165                 return;
1166         }
1167         month = lp->l_value;
1168         j = TM_JANUARY;
1169         while (j != month) {
1170                 i = len_months[isleap(year)][j];
1171                 dayoff = oadd(dayoff, eitol(i));
1172                 ++j;
1173         }
1174         cp = fields[LP_DAY];
1175         if (sscanf(cp, scheck(cp, "%d"), &day) != 1 ||
1176                 day <= 0 || day > len_months[isleap(year)][month]) {
1177                         error(_("invalid day of month"));
1178                         return;
1179         }
1180         dayoff = oadd(dayoff, eitol(day - 1));
1181         if (dayoff < 0 && !TYPE_SIGNED(zic_t)) {
1182                 error(_("time before zero"));
1183                 return;
1184         }
1185         if (dayoff < min_time / SECSPERDAY) {
1186                 error(_("time too small"));
1187                 return;
1188         }
1189         if (dayoff > max_time / SECSPERDAY) {
1190                 error(_("time too large"));
1191                 return;
1192         }
1193         t = (zic_t) dayoff * SECSPERDAY;
1194         tod = gethms(fields[LP_TIME], _("invalid time of day"), FALSE);
1195         cp = fields[LP_CORR];
1196         {
1197                 register int    positive;
1198                 int             count;
1199
1200                 if (strcmp(cp, "") == 0) { /* infile() turns "-" into "" */
1201                         positive = FALSE;
1202                         count = 1;
1203                 } else if (strcmp(cp, "--") == 0) {
1204                         positive = FALSE;
1205                         count = 2;
1206                 } else if (strcmp(cp, "+") == 0) {
1207                         positive = TRUE;
1208                         count = 1;
1209                 } else if (strcmp(cp, "++") == 0) {
1210                         positive = TRUE;
1211                         count = 2;
1212                 } else {
1213                         error(_("illegal CORRECTION field on Leap line"));
1214                         return;
1215                 }
1216                 if ((lp = byword(fields[LP_ROLL], leap_types)) == NULL) {
1217                         error(_(
1218                                 "illegal Rolling/Stationary field on Leap line"
1219                                 ));
1220                         return;
1221                 }
1222                 leapadd(tadd(t, tod), positive, lp->l_value, count);
1223         }
1224 }
1225
1226 static void
1227 inlink(fields, nfields)
1228 register char ** const  fields;
1229 const int               nfields;
1230 {
1231         struct link     l;
1232
1233         if (nfields != LINK_FIELDS) {
1234                 error(_("wrong number of fields on Link line"));
1235                 return;
1236         }
1237         if (*fields[LF_FROM] == '\0') {
1238                 error(_("blank FROM field on Link line"));
1239                 return;
1240         }
1241         if (*fields[LF_TO] == '\0') {
1242                 error(_("blank TO field on Link line"));
1243                 return;
1244         }
1245         l.l_filename = filename;
1246         l.l_linenum = linenum;
1247         l.l_from = ecpyalloc(fields[LF_FROM]);
1248         l.l_to = ecpyalloc(fields[LF_TO]);
1249         links = (struct link *) (void *) erealloc((char *) links,
1250                 (int) ((nlinks + 1) * sizeof *links));
1251         links[nlinks++] = l;
1252 }
1253
1254 static void
1255 rulesub(rp, loyearp, hiyearp, typep, monthp, dayp, timep)
1256 register struct rule * const    rp;
1257 const char * const              loyearp;
1258 const char * const              hiyearp;
1259 const char * const              typep;
1260 const char * const              monthp;
1261 const char * const              dayp;
1262 const char * const              timep;
1263 {
1264         register const struct lookup *  lp;
1265         register const char *           cp;
1266         register char *                 dp;
1267         register char *                 ep;
1268
1269         if ((lp = byword(monthp, mon_names)) == NULL) {
1270                 error(_("invalid month name"));
1271                 return;
1272         }
1273         rp->r_month = lp->l_value;
1274         rp->r_todisstd = FALSE;
1275         rp->r_todisgmt = FALSE;
1276         dp = ecpyalloc(timep);
1277         if (*dp != '\0') {
1278                 ep = dp + strlen(dp) - 1;
1279                 switch (lowerit(*ep)) {
1280                         case 's':       /* Standard */
1281                                 rp->r_todisstd = TRUE;
1282                                 rp->r_todisgmt = FALSE;
1283                                 *ep = '\0';
1284                                 break;
1285                         case 'w':       /* Wall */
1286                                 rp->r_todisstd = FALSE;
1287                                 rp->r_todisgmt = FALSE;
1288                                 *ep = '\0';
1289                                 break;
1290                         case 'g':       /* Greenwich */
1291                         case 'u':       /* Universal */
1292                         case 'z':       /* Zulu */
1293                                 rp->r_todisstd = TRUE;
1294                                 rp->r_todisgmt = TRUE;
1295                                 *ep = '\0';
1296                                 break;
1297                 }
1298         }
1299         rp->r_tod = gethms(dp, _("invalid time of day"), FALSE);
1300         ifree(dp);
1301         /*
1302         ** Year work.
1303         */
1304         cp = loyearp;
1305         lp = byword(cp, begin_years);
1306         rp->r_lowasnum = lp == NULL;
1307         if (!rp->r_lowasnum) switch ((int) lp->l_value) {
1308                 case YR_MINIMUM:
1309                         rp->r_loyear = INT_MIN;
1310                         break;
1311                 case YR_MAXIMUM:
1312                         rp->r_loyear = INT_MAX;
1313                         break;
1314                 default:        /* "cannot happen" */
1315                         (void) fprintf(stderr,
1316                                 _("%s: panic: Invalid l_value %d\n"),
1317                                 progname, lp->l_value);
1318                         exit(EXIT_FAILURE);
1319         } else if (sscanf(cp, scheck(cp, "%d"), &rp->r_loyear) != 1) {
1320                 error(_("invalid starting year"));
1321                 return;
1322         }
1323         cp = hiyearp;
1324         lp = byword(cp, end_years);
1325         rp->r_hiwasnum = lp == NULL;
1326         if (!rp->r_hiwasnum) switch ((int) lp->l_value) {
1327                 case YR_MINIMUM:
1328                         rp->r_hiyear = INT_MIN;
1329                         break;
1330                 case YR_MAXIMUM:
1331                         rp->r_hiyear = INT_MAX;
1332                         break;
1333                 case YR_ONLY:
1334                         rp->r_hiyear = rp->r_loyear;
1335                         break;
1336                 default:        /* "cannot happen" */
1337                         (void) fprintf(stderr,
1338                                 _("%s: panic: Invalid l_value %d\n"),
1339                                 progname, lp->l_value);
1340                         exit(EXIT_FAILURE);
1341         } else if (sscanf(cp, scheck(cp, "%d"), &rp->r_hiyear) != 1) {
1342                 error(_("invalid ending year"));
1343                 return;
1344         }
1345         if (rp->r_loyear > rp->r_hiyear) {
1346                 error(_("starting year greater than ending year"));
1347                 return;
1348         }
1349         if (*typep == '\0')
1350                 rp->r_yrtype = NULL;
1351         else {
1352                 if (rp->r_loyear == rp->r_hiyear) {
1353                         error(_("typed single year"));
1354                         return;
1355                 }
1356                 rp->r_yrtype = ecpyalloc(typep);
1357         }
1358         /*
1359         ** Day work.
1360         ** Accept things such as:
1361         **      1
1362         **      last-Sunday
1363         **      Sun<=20
1364         **      Sun>=7
1365         */
1366         dp = ecpyalloc(dayp);
1367         if ((lp = byword(dp, lasts)) != NULL) {
1368                 rp->r_dycode = DC_DOWLEQ;
1369                 rp->r_wday = lp->l_value;
1370                 rp->r_dayofmonth = len_months[1][rp->r_month];
1371         } else {
1372                 if ((ep = strchr(dp, '<')) != 0)
1373                         rp->r_dycode = DC_DOWLEQ;
1374                 else if ((ep = strchr(dp, '>')) != 0)
1375                         rp->r_dycode = DC_DOWGEQ;
1376                 else {
1377                         ep = dp;
1378                         rp->r_dycode = DC_DOM;
1379                 }
1380                 if (rp->r_dycode != DC_DOM) {
1381                         *ep++ = 0;
1382                         if (*ep++ != '=') {
1383                                 error(_("invalid day of month"));
1384                                 ifree(dp);
1385                                 return;
1386                         }
1387                         if ((lp = byword(dp, wday_names)) == NULL) {
1388                                 error(_("invalid weekday name"));
1389                                 ifree(dp);
1390                                 return;
1391                         }
1392                         rp->r_wday = lp->l_value;
1393                 }
1394                 if (sscanf(ep, scheck(ep, "%d"), &rp->r_dayofmonth) != 1 ||
1395                         rp->r_dayofmonth <= 0 ||
1396                         (rp->r_dayofmonth > len_months[1][rp->r_month])) {
1397                                 error(_("invalid day of month"));
1398                                 ifree(dp);
1399                                 return;
1400                 }
1401         }
1402         ifree(dp);
1403 }
1404
1405 static void
1406 convert(val, buf)
1407 const long      val;
1408 char * const    buf;
1409 {
1410         register int    i;
1411         register int    shift;
1412
1413         for (i = 0, shift = 24; i < 4; ++i, shift -= 8)
1414                 buf[i] = val >> shift;
1415 }
1416
1417 static void
1418 convert64(val, buf)
1419 const zic_t     val;
1420 char * const    buf;
1421 {
1422         register int    i;
1423         register int    shift;
1424
1425         for (i = 0, shift = 56; i < 8; ++i, shift -= 8)
1426                 buf[i] = val >> shift;
1427 }
1428
1429 static void
1430 puttzcode(val, fp)
1431 const long      val;
1432 FILE * const    fp;
1433 {
1434         char    buf[4];
1435
1436         convert(val, buf);
1437         (void) fwrite((void *) buf, (size_t) sizeof buf, (size_t) 1, fp);
1438 }
1439
1440 static void
1441 puttzcode64(val, fp)
1442 const zic_t     val;
1443 FILE * const    fp;
1444 {
1445         char    buf[8];
1446
1447         convert64(val, buf);
1448         (void) fwrite((void *) buf, (size_t) sizeof buf, (size_t) 1, fp);
1449 }
1450
1451 static int
1452 atcomp(avp, bvp)
1453 const void *    avp;
1454 const void *    bvp;
1455 {
1456         const zic_t     a = ((const struct attype *) avp)->at;
1457         const zic_t     b = ((const struct attype *) bvp)->at;
1458
1459         return (a < b) ? -1 : (a > b);
1460 }
1461
1462 static int
1463 is32(x)
1464 const zic_t     x;
1465 {
1466         return INT32_MIN <= x && x <= INT32_MAX;
1467 }
1468
1469 static void
1470 writezone(name, string)
1471 const char * const      name;
1472 const char * const      string;
1473 {
1474         register FILE *                 fp;
1475         register int                    i, j;
1476         register int                    leapcnt32, leapi32;
1477         register int                    timecnt32, timei32;
1478         register int                    pass;
1479         static char *                   fullname;
1480         static const struct tzhead      tzh0;
1481         static struct tzhead            tzh;
1482         zic_t                           ats[TZ_MAX_TIMES];
1483         unsigned char                   types[TZ_MAX_TIMES];
1484
1485         /*
1486         ** Sort.
1487         */
1488         if (timecnt > 1)
1489                 (void) qsort((void *) attypes, (size_t) timecnt,
1490                         (size_t) sizeof *attypes, atcomp);
1491         /*
1492         ** Optimize.
1493         */
1494         {
1495                 int     fromi;
1496                 int     toi;
1497
1498                 toi = 0;
1499                 fromi = 0;
1500                 while (fromi < timecnt && attypes[fromi].at < min_time)
1501                         ++fromi;
1502                 if (isdsts[0] == 0)
1503                         while (fromi < timecnt && attypes[fromi].type == 0)
1504                                 ++fromi;        /* handled by default rule */
1505                 for ( ; fromi < timecnt; ++fromi) {
1506                         if (toi != 0 && ((attypes[fromi].at +
1507                                 gmtoffs[attypes[toi - 1].type]) <=
1508                                 (attypes[toi - 1].at + gmtoffs[toi == 1 ? 0
1509                                 : attypes[toi - 2].type]))) {
1510                                         attypes[toi - 1].type =
1511                                                 attypes[fromi].type;
1512                                         continue;
1513                         }
1514                         if (toi == 0 ||
1515                                 attypes[toi - 1].type != attypes[fromi].type)
1516                                         attypes[toi++] = attypes[fromi];
1517                 }
1518                 timecnt = toi;
1519         }
1520         /*
1521         ** Transfer.
1522         */
1523         for (i = 0; i < timecnt; ++i) {
1524                 ats[i] = attypes[i].at;
1525                 types[i] = attypes[i].type;
1526         }
1527         /*
1528         ** Correct for leap seconds.
1529         */
1530         for (i = 0; i < timecnt; ++i) {
1531                 j = leapcnt;
1532                 while (--j >= 0)
1533                         if (ats[i] > trans[j] - corr[j]) {
1534                                 ats[i] = tadd(ats[i], corr[j]);
1535                                 break;
1536                         }
1537         }
1538         /*
1539         ** Figure out 32-bit-limited starts and counts.
1540         */
1541         timecnt32 = timecnt;
1542         timei32 = 0;
1543         leapcnt32 = leapcnt;
1544         leapi32 = 0;
1545         while (timecnt32 > 0 && !is32(ats[timecnt32 - 1]))
1546                 --timecnt32;
1547         while (timecnt32 > 0 && !is32(ats[timei32])) {
1548                 --timecnt32;
1549                 ++timei32;
1550         }
1551         while (leapcnt32 > 0 && !is32(trans[leapcnt32 - 1]))
1552                 --leapcnt32;
1553         while (leapcnt32 > 0 && !is32(trans[leapi32])) {
1554                 --leapcnt32;
1555                 ++leapi32;
1556         }
1557         fullname = erealloc(fullname,
1558                 (int) (strlen(directory) + 1 + strlen(name) + 1));
1559         (void) sprintf(fullname, "%s/%s", directory, name);
1560         /*
1561         ** Remove old file, if any, to snap links.
1562         */
1563         if (!itsdir(fullname) && remove(fullname) != 0 && errno != ENOENT) {
1564                 const char *e = strerror(errno);
1565
1566                 (void) fprintf(stderr, _("%s: Can't remove %s: %s\n"),
1567                         progname, fullname, e);
1568                 exit(EXIT_FAILURE);
1569         }
1570         if ((fp = fopen(fullname, "wb")) == NULL) {
1571                 if (mkdirs(fullname) != 0)
1572                         exit(EXIT_FAILURE);
1573                 if ((fp = fopen(fullname, "wb")) == NULL) {
1574                         const char *e = strerror(errno);
1575
1576                         (void) fprintf(stderr, _("%s: Can't create %s: %s\n"),
1577                                 progname, fullname, e);
1578                         exit(EXIT_FAILURE);
1579                 }
1580         }
1581         for (pass = 1; pass <= 2; ++pass) {
1582                 register int    thistimei, thistimecnt;
1583                 register int    thisleapi, thisleapcnt;
1584                 register int    thistimelim, thisleaplim;
1585                 int             writetype[TZ_MAX_TIMES];
1586                 int             typemap[TZ_MAX_TYPES];
1587                 register int    thistypecnt;
1588                 char            thischars[TZ_MAX_CHARS];
1589                 char            thischarcnt;
1590                 int             indmap[TZ_MAX_CHARS];
1591
1592                 if (pass == 1) {
1593                         thistimei = timei32;
1594                         thistimecnt = timecnt32;
1595                         thisleapi = leapi32;
1596                         thisleapcnt = leapcnt32;
1597                 } else {
1598                         thistimei = 0;
1599                         thistimecnt = timecnt;
1600                         thisleapi = 0;
1601                         thisleapcnt = leapcnt;
1602                 }
1603                 thistimelim = thistimei + thistimecnt;
1604                 thisleaplim = thisleapi + thisleapcnt;
1605                 for (i = 0; i < typecnt; ++i)
1606                         writetype[i] = thistimecnt == timecnt;
1607                 if (thistimecnt == 0) {
1608                         /*
1609                         ** No transition times fall in the current
1610                         ** (32- or 64-bit) window.
1611                         */
1612                         if (typecnt != 0)
1613                                 writetype[typecnt - 1] = TRUE;
1614                 } else {
1615                         for (i = thistimei - 1; i < thistimelim; ++i)
1616                                 if (i >= 0)
1617                                         writetype[types[i]] = TRUE;
1618                         /*
1619                         ** For America/Godthab and Antarctica/Palmer
1620                         */
1621                         if (thistimei == 0)
1622                                 writetype[0] = TRUE;
1623                 }
1624                 thistypecnt = 0;
1625                 for (i = 0; i < typecnt; ++i)
1626                         typemap[i] = writetype[i] ?  thistypecnt++ : -1;
1627                 for (i = 0; i < sizeof indmap / sizeof indmap[0]; ++i)
1628                         indmap[i] = -1;
1629                 thischarcnt = 0;
1630                 for (i = 0; i < typecnt; ++i) {
1631                         register char * thisabbr;
1632
1633                         if (!writetype[i])
1634                                 continue;
1635                         if (indmap[abbrinds[i]] >= 0)
1636                                 continue;
1637                         thisabbr = &chars[abbrinds[i]];
1638                         for (j = 0; j < thischarcnt; ++j)
1639                                 if (strcmp(&thischars[j], thisabbr) == 0)
1640                                         break;
1641                         if (j == thischarcnt) {
1642                                 (void) strcpy(&thischars[(int) thischarcnt],
1643                                         thisabbr);
1644                                 thischarcnt += strlen(thisabbr) + 1;
1645                         }
1646                         indmap[abbrinds[i]] = j;
1647                 }
1648 #define DO(field)       (void) fwrite((void *) tzh.field, \
1649                                 (size_t) sizeof tzh.field, (size_t) 1, fp)
1650                 tzh = tzh0;
1651                 (void) strncpy(tzh.tzh_magic, TZ_MAGIC, sizeof tzh.tzh_magic);
1652                 tzh.tzh_version[0] = ZIC_VERSION;
1653                 convert(eitol(thistypecnt), tzh.tzh_ttisgmtcnt);
1654                 convert(eitol(thistypecnt), tzh.tzh_ttisstdcnt);
1655                 convert(eitol(thisleapcnt), tzh.tzh_leapcnt);
1656                 convert(eitol(thistimecnt), tzh.tzh_timecnt);
1657                 convert(eitol(thistypecnt), tzh.tzh_typecnt);
1658                 convert(eitol(thischarcnt), tzh.tzh_charcnt);
1659                 DO(tzh_magic);
1660                 DO(tzh_version);
1661                 DO(tzh_reserved);
1662                 DO(tzh_ttisgmtcnt);
1663                 DO(tzh_ttisstdcnt);
1664                 DO(tzh_leapcnt);
1665                 DO(tzh_timecnt);
1666                 DO(tzh_typecnt);
1667                 DO(tzh_charcnt);
1668 #undef DO
1669                 for (i = thistimei; i < thistimelim; ++i)
1670                         if (pass == 1)
1671                                 puttzcode((long) ats[i], fp);
1672                         else    puttzcode64(ats[i], fp);
1673                 for (i = thistimei; i < thistimelim; ++i) {
1674                         unsigned char   uc;
1675
1676                         uc = typemap[types[i]];
1677                         (void) fwrite((void *) &uc,
1678                                 (size_t) sizeof uc,
1679                                 (size_t) 1,
1680                                 fp);
1681                 }
1682                 for (i = 0; i < typecnt; ++i)
1683                         if (writetype[i]) {
1684                                 puttzcode(gmtoffs[i], fp);
1685                                 (void) putc(isdsts[i], fp);
1686                                 (void) putc((unsigned char) indmap[abbrinds[i]], fp);
1687                         }
1688                 if (thischarcnt != 0)
1689                         (void) fwrite((void *) thischars,
1690                                 (size_t) sizeof thischars[0],
1691                                 (size_t) thischarcnt, fp);
1692                 for (i = thisleapi; i < thisleaplim; ++i) {
1693                         register zic_t  todo;
1694
1695                         if (roll[i]) {
1696                                 if (timecnt == 0 || trans[i] < ats[0]) {
1697                                         j = 0;
1698                                         while (isdsts[j])
1699                                                 if (++j >= typecnt) {
1700                                                         j = 0;
1701                                                         break;
1702                                                 }
1703                                 } else {
1704                                         j = 1;
1705                                         while (j < timecnt &&
1706                                                 trans[i] >= ats[j])
1707                                                         ++j;
1708                                         j = types[j - 1];
1709                                 }
1710                                 todo = tadd(trans[i], -gmtoffs[j]);
1711                         } else  todo = trans[i];
1712                         if (pass == 1)
1713                                 puttzcode((long) todo, fp);
1714                         else    puttzcode64(todo, fp);
1715                         puttzcode(corr[i], fp);
1716                 }
1717                 for (i = 0; i < typecnt; ++i)
1718                         if (writetype[i])
1719                                 (void) putc(ttisstds[i], fp);
1720                 for (i = 0; i < typecnt; ++i)
1721                         if (writetype[i])
1722                                 (void) putc(ttisgmts[i], fp);
1723         }
1724         (void) fprintf(fp, "\n%s\n", string);
1725         if (ferror(fp) || fclose(fp)) {
1726                 (void) fprintf(stderr, _("%s: Error writing %s\n"),
1727                         progname, fullname);
1728                 exit(EXIT_FAILURE);
1729         }
1730 }
1731
1732 static void
1733 doabbr(abbr, format, letters, isdst, doquotes)
1734 char * const            abbr;
1735 const char * const      format;
1736 const char * const      letters;
1737 const int               isdst;
1738 const int               doquotes;
1739 {
1740         register char * cp;
1741         register char * slashp;
1742         register int    len;
1743
1744         slashp = strchr(format, '/');
1745         if (slashp == NULL) {
1746                 if (letters == NULL)
1747                         (void) strcpy(abbr, format);
1748                 else    (void) sprintf(abbr, format, letters);
1749         } else if (isdst) {
1750                 (void) strcpy(abbr, slashp + 1);
1751         } else {
1752                 if (slashp > format)
1753                         (void) strncpy(abbr, format,
1754                                 (unsigned) (slashp - format));
1755                 abbr[slashp - format] = '\0';
1756         }
1757         if (!doquotes)
1758                 return;
1759         for (cp = abbr; *cp != '\0'; ++cp)
1760                 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", *cp) == NULL &&
1761                         strchr("abcdefghijklmnopqrstuvwxyz", *cp) == NULL)
1762                                 break;
1763         len = strlen(abbr);
1764         if (len > 0 && *cp == '\0')
1765                 return;
1766         abbr[len + 2] = '\0';
1767         abbr[len + 1] = '>';
1768         for ( ; len > 0; --len)
1769                 abbr[len] = abbr[len - 1];
1770         abbr[0] = '<';
1771 }
1772
1773 static void
1774 updateminmax(x)
1775 const int       x;
1776 {
1777         if (min_year > x)
1778                 min_year = x;
1779         if (max_year < x)
1780                 max_year = x;
1781 }
1782
1783 static int
1784 stringoffset(result, offset)
1785 char *  result;
1786 long    offset;
1787 {
1788         register int    hours;
1789         register int    minutes;
1790         register int    seconds;
1791
1792         result[0] = '\0';
1793         if (offset < 0) {
1794                 (void) strcpy(result, "-");
1795                 offset = -offset;
1796         }
1797         seconds = offset % SECSPERMIN;
1798         offset /= SECSPERMIN;
1799         minutes = offset % MINSPERHOUR;
1800         offset /= MINSPERHOUR;
1801         hours = offset;
1802         if (hours >= HOURSPERDAY) {
1803                 result[0] = '\0';
1804                 return -1;
1805         }
1806         (void) sprintf(end(result), "%d", hours);
1807         if (minutes != 0 || seconds != 0) {
1808                 (void) sprintf(end(result), ":%02d", minutes);
1809                 if (seconds != 0)
1810                         (void) sprintf(end(result), ":%02d", seconds);
1811         }
1812         return 0;
1813 }
1814
1815 static int
1816 stringrule(result, rp, dstoff, gmtoff)
1817 char *                          result;
1818 const struct rule * const       rp;
1819 const long                      dstoff;
1820 const long                      gmtoff;
1821 {
1822         register long   tod;
1823
1824         result = end(result);
1825         if (rp->r_dycode == DC_DOM) {
1826                 register int    month, total;
1827
1828                 if (rp->r_dayofmonth == 29 && rp->r_month == TM_FEBRUARY)
1829                         return -1;
1830                 total = 0;
1831                 for (month = 0; month < rp->r_month; ++month)
1832                         total += len_months[0][month];
1833                 (void) sprintf(result, "J%d", total + rp->r_dayofmonth);
1834         } else {
1835                 register int    week;
1836
1837                 if (rp->r_dycode == DC_DOWGEQ) {
1838                         week = 1 + rp->r_dayofmonth / DAYSPERWEEK;
1839                         if ((week - 1) * DAYSPERWEEK + 1 != rp->r_dayofmonth)
1840                                 return -1;
1841                 } else if (rp->r_dycode == DC_DOWLEQ) {
1842                         if (rp->r_dayofmonth == len_months[1][rp->r_month])
1843                                 week = 5;
1844                         else {
1845                                 week = 1 + rp->r_dayofmonth / DAYSPERWEEK;
1846                                 if (week * DAYSPERWEEK - 1 != rp->r_dayofmonth)
1847                                         return -1;
1848                         }
1849                 } else  return -1;      /* "cannot happen" */
1850                 (void) sprintf(result, "M%d.%d.%d",
1851                         rp->r_month + 1, week, rp->r_wday);
1852         }
1853         tod = rp->r_tod;
1854         if (rp->r_todisgmt)
1855                 tod += gmtoff;
1856         if (rp->r_todisstd && rp->r_stdoff == 0)
1857                 tod += dstoff;
1858         if (tod < 0) {
1859                 result[0] = '\0';
1860                 return -1;
1861         }
1862         if (tod != 2 * SECSPERMIN * MINSPERHOUR) {
1863                 (void) strcat(result, "/");
1864                 if (stringoffset(end(result), tod) != 0)
1865                         return -1;
1866         }
1867         return 0;
1868 }
1869
1870 static void
1871 stringzone(result, zpfirst, zonecount)
1872 char *                          result;
1873 const struct zone * const       zpfirst;
1874 const int                       zonecount;
1875 {
1876         register const struct zone *    zp;
1877         register struct rule *          rp;
1878         register struct rule *          stdrp;
1879         register struct rule *          dstrp;
1880         register int                    i;
1881         register const char *           abbrvar;
1882
1883         result[0] = '\0';
1884         zp = zpfirst + zonecount - 1;
1885         stdrp = dstrp = NULL;
1886         for (i = 0; i < zp->z_nrules; ++i) {
1887                 rp = &zp->z_rules[i];
1888                 if (rp->r_hiwasnum || rp->r_hiyear != INT_MAX)
1889                         continue;
1890                 if (rp->r_yrtype != NULL)
1891                         continue;
1892                 if (rp->r_stdoff == 0) {
1893                         if (stdrp == NULL)
1894                                 stdrp = rp;
1895                         else    return;
1896                 } else {
1897                         if (dstrp == NULL)
1898                                 dstrp = rp;
1899                         else    return;
1900                 }
1901         }
1902         if (stdrp == NULL && dstrp == NULL) {
1903                 /*
1904                 ** There are no rules running through "max".
1905                 ** Let's find the latest rule.
1906                 */
1907                 for (i = 0; i < zp->z_nrules; ++i) {
1908                         rp = &zp->z_rules[i];
1909                         if (stdrp == NULL || rp->r_hiyear > stdrp->r_hiyear ||
1910                                 (rp->r_hiyear == stdrp->r_hiyear &&
1911                                 rp->r_month > stdrp->r_month))
1912                                         stdrp = rp;
1913                 }
1914                 if (stdrp != NULL && stdrp->r_stdoff != 0)
1915                         return; /* We end up in DST (a POSIX no-no). */
1916                 /*
1917                 ** Horrid special case: if year is 2037,
1918                 ** presume this is a zone handled on a year-by-year basis;
1919                 ** do not try to apply a rule to the zone.
1920                 */
1921                 if (stdrp != NULL && stdrp->r_hiyear == 2037)
1922                         return;
1923         }
1924         if (stdrp == NULL && zp->z_nrules != 0)
1925                 return;
1926         abbrvar = (stdrp == NULL) ? "" : stdrp->r_abbrvar;
1927         doabbr(result, zp->z_format, abbrvar, FALSE, TRUE);
1928         if (stringoffset(end(result), -zp->z_gmtoff) != 0) {
1929                 result[0] = '\0';
1930                 return;
1931         }
1932         if (dstrp == NULL)
1933                 return;
1934         doabbr(end(result), zp->z_format, dstrp->r_abbrvar, TRUE, TRUE);
1935         if (dstrp->r_stdoff != SECSPERMIN * MINSPERHOUR)
1936                 if (stringoffset(end(result),
1937                         -(zp->z_gmtoff + dstrp->r_stdoff)) != 0) {
1938                                 result[0] = '\0';
1939                                 return;
1940                 }
1941         (void) strcat(result, ",");
1942         if (stringrule(result, dstrp, dstrp->r_stdoff, zp->z_gmtoff) != 0) {
1943                 result[0] = '\0';
1944                 return;
1945         }
1946         (void) strcat(result, ",");
1947         if (stringrule(result, stdrp, dstrp->r_stdoff, zp->z_gmtoff) != 0) {
1948                 result[0] = '\0';
1949                 return;
1950         }
1951 }
1952
1953 static void
1954 outzone(zpfirst, zonecount)
1955 const struct zone * const       zpfirst;
1956 const int                       zonecount;
1957 {
1958         register const struct zone *    zp;
1959         register struct rule *          rp;
1960         register int                    i, j;
1961         register int                    usestart, useuntil;
1962         register zic_t                  starttime, untiltime;
1963         register long                   gmtoff;
1964         register long                   stdoff;
1965         register int                    year;
1966         register long                   startoff;
1967         register int                    startttisstd;
1968         register int                    startttisgmt;
1969         register int                    type;
1970         register char *                 startbuf;
1971         register char *                 ab;
1972         register char *                 envvar;
1973         register int                    max_abbr_len;
1974         register int                    max_envvar_len;
1975
1976         max_abbr_len = 2 + max_format_len + max_abbrvar_len;
1977         max_envvar_len = 2 * max_abbr_len + 5 * 9;
1978         startbuf = emalloc(max_abbr_len + 1);
1979         ab = emalloc(max_abbr_len + 1);
1980         envvar = emalloc(max_envvar_len + 1);
1981         INITIALIZE(untiltime);
1982         INITIALIZE(starttime);
1983         /*
1984         ** Now. . .finally. . .generate some useful data!
1985         */
1986         timecnt = 0;
1987         typecnt = 0;
1988         charcnt = 0;
1989         /*
1990         ** Thanks to Earl Chew
1991         ** for noting the need to unconditionally initialize startttisstd.
1992         */
1993         startttisstd = FALSE;
1994         startttisgmt = FALSE;
1995         min_year = max_year = EPOCH_YEAR;
1996         if (leapseen) {
1997                 updateminmax(leapminyear);
1998                 updateminmax(leapmaxyear + (leapmaxyear < INT_MAX));
1999         }
2000         for (i = 0; i < zonecount; ++i) {
2001                 zp = &zpfirst[i];
2002                 if (i < zonecount - 1)
2003                         updateminmax(zp->z_untilrule.r_loyear);
2004                 for (j = 0; j < zp->z_nrules; ++j) {
2005                         rp = &zp->z_rules[j];
2006                         if (rp->r_lowasnum)
2007                                 updateminmax(rp->r_loyear);
2008                         if (rp->r_hiwasnum)
2009                                 updateminmax(rp->r_hiyear);
2010                 }
2011         }
2012         /*
2013         ** Generate lots of data if a rule can't cover all future times.
2014         */
2015         stringzone(envvar, zpfirst, zonecount);
2016         if (noise && envvar[0] == '\0') {
2017                 register char * wp;
2018
2019 wp = ecpyalloc(_("no POSIX environment variable for zone"));
2020                 wp = ecatalloc(wp, " ");
2021                 wp = ecatalloc(wp, zpfirst->z_name);
2022                 warning(wp);
2023                 ifree(wp);
2024         }
2025         if (envvar[0] == '\0') {
2026                 if (min_year >= INT_MIN + YEARSPERREPEAT)
2027                         min_year -= YEARSPERREPEAT;
2028                 else    min_year = INT_MIN;
2029                 if (max_year <= INT_MAX - YEARSPERREPEAT)
2030                         max_year += YEARSPERREPEAT;
2031                 else    max_year = INT_MAX;
2032         }
2033         /*
2034         ** For the benefit of older systems,
2035         ** generate data from 1900 through 2037.
2036         */
2037         if (min_year > 1900)
2038                 min_year = 1900;
2039         if (max_year < 2037)
2040                 max_year = 2037;
2041         for (i = 0; i < zonecount; ++i) {
2042                 /*
2043                 ** A guess that may well be corrected later.
2044                 */
2045                 stdoff = 0;
2046                 zp = &zpfirst[i];
2047                 usestart = i > 0 && (zp - 1)->z_untiltime > min_time;
2048                 useuntil = i < (zonecount - 1);
2049                 if (useuntil && zp->z_untiltime <= min_time)
2050                         continue;
2051                 gmtoff = zp->z_gmtoff;
2052                 eat(zp->z_filename, zp->z_linenum);
2053                 *startbuf = '\0';
2054                 startoff = zp->z_gmtoff;
2055                 if (zp->z_nrules == 0) {
2056                         stdoff = zp->z_stdoff;
2057                         doabbr(startbuf, zp->z_format,
2058                                 (char *) NULL, stdoff != 0, FALSE);
2059                         type = addtype(oadd(zp->z_gmtoff, stdoff),
2060                                 startbuf, stdoff != 0, startttisstd,
2061                                 startttisgmt);
2062                         if (usestart) {
2063                                 addtt(starttime, type);
2064                                 usestart = FALSE;
2065                         } else if (stdoff != 0)
2066                                 addtt(min_time, type);
2067                 } else for (year = min_year; year <= max_year; ++year) {
2068                         if (useuntil && year > zp->z_untilrule.r_hiyear)
2069                                 break;
2070                         /*
2071                         ** Mark which rules to do in the current year.
2072                         ** For those to do, calculate rpytime(rp, year);
2073                         */
2074                         for (j = 0; j < zp->z_nrules; ++j) {
2075                                 rp = &zp->z_rules[j];
2076                                 eats(zp->z_filename, zp->z_linenum,
2077                                         rp->r_filename, rp->r_linenum);
2078                                 rp->r_todo = year >= rp->r_loyear &&
2079                                                 year <= rp->r_hiyear &&
2080                                                 yearistype(year, rp->r_yrtype);
2081                                 if (rp->r_todo)
2082                                         rp->r_temp = rpytime(rp, year);
2083                         }
2084                         for ( ; ; ) {
2085                                 register int    k;
2086                                 register zic_t  jtime, ktime;
2087                                 register long   offset;
2088
2089                                 INITIALIZE(ktime);
2090                                 if (useuntil) {
2091                                         /*
2092                                         ** Turn untiltime into UTC
2093                                         ** assuming the current gmtoff and
2094                                         ** stdoff values.
2095                                         */
2096                                         untiltime = zp->z_untiltime;
2097                                         if (!zp->z_untilrule.r_todisgmt)
2098                                                 untiltime = tadd(untiltime,
2099                                                         -gmtoff);
2100                                         if (!zp->z_untilrule.r_todisstd)
2101                                                 untiltime = tadd(untiltime,
2102                                                         -stdoff);
2103                                 }
2104                                 /*
2105                                 ** Find the rule (of those to do, if any)
2106                                 ** that takes effect earliest in the year.
2107                                 */
2108                                 k = -1;
2109                                 for (j = 0; j < zp->z_nrules; ++j) {
2110                                         rp = &zp->z_rules[j];
2111                                         if (!rp->r_todo)
2112                                                 continue;
2113                                         eats(zp->z_filename, zp->z_linenum,
2114                                                 rp->r_filename, rp->r_linenum);
2115                                         offset = rp->r_todisgmt ? 0 : gmtoff;
2116                                         if (!rp->r_todisstd)
2117                                                 offset = oadd(offset, stdoff);
2118                                         jtime = rp->r_temp;
2119                                         if (jtime == min_time ||
2120                                                 jtime == max_time)
2121                                                         continue;
2122                                         jtime = tadd(jtime, -offset);
2123                                         if (k < 0 || jtime < ktime) {
2124                                                 k = j;
2125                                                 ktime = jtime;
2126                                         }
2127                                 }
2128                                 if (k < 0)
2129                                         break;  /* go on to next year */
2130                                 rp = &zp->z_rules[k];
2131                                 rp->r_todo = FALSE;
2132                                 if (useuntil && ktime >= untiltime)
2133                                         break;
2134                                 stdoff = rp->r_stdoff;
2135                                 if (usestart && ktime == starttime)
2136                                         usestart = FALSE;
2137                                 if (usestart) {
2138                                         if (ktime < starttime) {
2139                                                 startoff = oadd(zp->z_gmtoff,
2140                                                         stdoff);
2141                                                 doabbr(startbuf, zp->z_format,
2142                                                         rp->r_abbrvar,
2143                                                         rp->r_stdoff != 0,
2144                                                         FALSE);
2145                                                 continue;
2146                                         }
2147                                         if (*startbuf == '\0' &&
2148                                                 startoff == oadd(zp->z_gmtoff,
2149                                                 stdoff)) {
2150                                                         doabbr(startbuf,
2151                                                                 zp->z_format,
2152                                                                 rp->r_abbrvar,
2153                                                                 rp->r_stdoff !=
2154                                                                 0,
2155                                                                 FALSE);
2156                                         }
2157                                 }
2158                                 eats(zp->z_filename, zp->z_linenum,
2159                                         rp->r_filename, rp->r_linenum);
2160                                 doabbr(ab, zp->z_format, rp->r_abbrvar,
2161                                         rp->r_stdoff != 0, FALSE);
2162                                 offset = oadd(zp->z_gmtoff, rp->r_stdoff);
2163                                 type = addtype(offset, ab, rp->r_stdoff != 0,
2164                                         rp->r_todisstd, rp->r_todisgmt);
2165                                 addtt(ktime, type);
2166                         }
2167                 }
2168                 if (usestart) {
2169                         if (*startbuf == '\0' &&
2170                                 zp->z_format != NULL &&
2171                                 strchr(zp->z_format, '%') == NULL &&
2172                                 strchr(zp->z_format, '/') == NULL)
2173                                         (void) strcpy(startbuf, zp->z_format);
2174                         eat(zp->z_filename, zp->z_linenum);
2175                         if (*startbuf == '\0')
2176 error(_("can't determine time zone abbreviation to use just after until time"));
2177                         else    addtt(starttime,
2178                                         addtype(startoff, startbuf,
2179                                                 startoff != zp->z_gmtoff,
2180                                                 startttisstd,
2181                                                 startttisgmt));
2182                 }
2183                 /*
2184                 ** Now we may get to set starttime for the next zone line.
2185                 */
2186                 if (useuntil) {
2187                         startttisstd = zp->z_untilrule.r_todisstd;
2188                         startttisgmt = zp->z_untilrule.r_todisgmt;
2189                         starttime = zp->z_untiltime;
2190                         if (!startttisstd)
2191                                 starttime = tadd(starttime, -stdoff);
2192                         if (!startttisgmt)
2193                                 starttime = tadd(starttime, -gmtoff);
2194                 }
2195         }
2196         writezone(zpfirst->z_name, envvar);
2197         ifree(startbuf);
2198         ifree(ab);
2199         ifree(envvar);
2200 }
2201
2202 static void
2203 addtt(starttime, type)
2204 const zic_t     starttime;
2205 int             type;
2206 {
2207         if (starttime <= min_time ||
2208                 (timecnt == 1 && attypes[0].at < min_time)) {
2209                 gmtoffs[0] = gmtoffs[type];
2210                 isdsts[0] = isdsts[type];
2211                 ttisstds[0] = ttisstds[type];
2212                 ttisgmts[0] = ttisgmts[type];
2213                 if (abbrinds[type] != 0)
2214                         (void) strcpy(chars, &chars[abbrinds[type]]);
2215                 abbrinds[0] = 0;
2216                 charcnt = strlen(chars) + 1;
2217                 typecnt = 1;
2218                 timecnt = 0;
2219                 type = 0;
2220         }
2221         if (timecnt >= TZ_MAX_TIMES) {
2222                 error(_("too many transitions?!"));
2223                 exit(EXIT_FAILURE);
2224         }
2225         attypes[timecnt].at = starttime;
2226         attypes[timecnt].type = type;
2227         ++timecnt;
2228 }
2229
2230 static int
2231 addtype(gmtoff, abbr, isdst, ttisstd, ttisgmt)
2232 const long              gmtoff;
2233 const char * const      abbr;
2234 const int               isdst;
2235 const int               ttisstd;
2236 const int               ttisgmt;
2237 {
2238         register int    i, j;
2239
2240         if (isdst != TRUE && isdst != FALSE) {
2241                 error(_("internal error - addtype called with bad isdst"));
2242                 exit(EXIT_FAILURE);
2243         }
2244         if (ttisstd != TRUE && ttisstd != FALSE) {
2245                 error(_("internal error - addtype called with bad ttisstd"));
2246                 exit(EXIT_FAILURE);
2247         }
2248         if (ttisgmt != TRUE && ttisgmt != FALSE) {
2249                 error(_("internal error - addtype called with bad ttisgmt"));
2250                 exit(EXIT_FAILURE);
2251         }
2252         /*
2253         ** See if there's already an entry for this zone type.
2254         ** If so, just return its index.
2255         */
2256         for (i = 0; i < typecnt; ++i) {
2257                 if (gmtoff == gmtoffs[i] && isdst == isdsts[i] &&
2258                         strcmp(abbr, &chars[abbrinds[i]]) == 0 &&
2259                         ttisstd == ttisstds[i] &&
2260                         ttisgmt == ttisgmts[i])
2261                                 return i;
2262         }
2263         /*
2264         ** There isn't one; add a new one, unless there are already too
2265         ** many.
2266         */
2267         if (typecnt >= TZ_MAX_TYPES) {
2268                 error(_("too many local time types"));
2269                 exit(EXIT_FAILURE);
2270         }
2271         if (! (-1L - 2147483647L <= gmtoff && gmtoff <= 2147483647L)) {
2272                 error(_("UTC offset out of range"));
2273                 exit(EXIT_FAILURE);
2274         }
2275         gmtoffs[i] = gmtoff;
2276         isdsts[i] = isdst;
2277         ttisstds[i] = ttisstd;
2278         ttisgmts[i] = ttisgmt;
2279
2280         for (j = 0; j < charcnt; ++j)
2281                 if (strcmp(&chars[j], abbr) == 0)
2282                         break;
2283         if (j == charcnt)
2284                 newabbr(abbr);
2285         abbrinds[i] = j;
2286         ++typecnt;
2287         return i;
2288 }
2289
2290 static void
2291 leapadd(t, positive, rolling, count)
2292 const zic_t     t;
2293 const int       positive;
2294 const int       rolling;
2295 int             count;
2296 {
2297         register int    i, j;
2298
2299         if (leapcnt + (positive ? count : 1) > TZ_MAX_LEAPS) {
2300                 error(_("too many leap seconds"));
2301                 exit(EXIT_FAILURE);
2302         }
2303         for (i = 0; i < leapcnt; ++i)
2304                 if (t <= trans[i]) {
2305                         if (t == trans[i]) {
2306                                 error(_("repeated leap second moment"));
2307                                 exit(EXIT_FAILURE);
2308                         }
2309                         break;
2310                 }
2311         do {
2312                 for (j = leapcnt; j > i; --j) {
2313                         trans[j] = trans[j - 1];
2314                         corr[j] = corr[j - 1];
2315                         roll[j] = roll[j - 1];
2316                 }
2317                 trans[i] = t;
2318                 corr[i] = positive ? 1L : eitol(-count);
2319                 roll[i] = rolling;
2320                 ++leapcnt;
2321         } while (positive && --count != 0);
2322 }
2323
2324 static void
2325 adjleap(void)
2326 {
2327         register int    i;
2328         register long   last = 0;
2329
2330         /*
2331         ** propagate leap seconds forward
2332         */
2333         for (i = 0; i < leapcnt; ++i) {
2334                 trans[i] = tadd(trans[i], last);
2335                 last = corr[i] += last;
2336         }
2337 }
2338
2339 static int
2340 yearistype(year, type)
2341 const int               year;
2342 const char * const      type;
2343 {
2344         static char *   buf;
2345         int             result;
2346
2347         if (type == NULL || *type == '\0')
2348                 return TRUE;
2349         buf = erealloc(buf, (int) (132 + strlen(yitcommand) + strlen(type)));
2350         (void) sprintf(buf, "%s %d %s", yitcommand, year, type);
2351         result = system(buf);
2352         if (WIFEXITED(result)) switch (WEXITSTATUS(result)) {
2353                 case 0:
2354                         return TRUE;
2355                 case 1:
2356                         return FALSE;
2357         }
2358         error(_("Wild result from command execution"));
2359         (void) fprintf(stderr, _("%s: command was '%s', result was %d\n"),
2360                 progname, buf, result);
2361         for ( ; ; )
2362                 exit(EXIT_FAILURE);
2363 }
2364
2365 static int
2366 lowerit(a)
2367 int     a;
2368 {
2369         a = (unsigned char) a;
2370         return (isascii(a) && isupper(a)) ? tolower(a) : a;
2371 }
2372
2373 static int
2374 ciequal(ap, bp)         /* case-insensitive equality */
2375 register const char *   ap;
2376 register const char *   bp;
2377 {
2378         while (lowerit(*ap) == lowerit(*bp++))
2379                 if (*ap++ == '\0')
2380                         return TRUE;
2381         return FALSE;
2382 }
2383
2384 static int
2385 itsabbr(abbr, word)
2386 register const char *   abbr;
2387 register const char *   word;
2388 {
2389         if (lowerit(*abbr) != lowerit(*word))
2390                 return FALSE;
2391         ++word;
2392         while (*++abbr != '\0')
2393                 do {
2394                         if (*word == '\0')
2395                                 return FALSE;
2396                 } while (lowerit(*word++) != lowerit(*abbr));
2397         return TRUE;
2398 }
2399
2400 static const struct lookup *
2401 byword(word, table)
2402 register const char * const             word;
2403 register const struct lookup * const    table;
2404 {
2405         register const struct lookup *  foundlp;
2406         register const struct lookup *  lp;
2407
2408         if (word == NULL || table == NULL)
2409                 return NULL;
2410         /*
2411         ** Look for exact match.
2412         */
2413         for (lp = table; lp->l_word != NULL; ++lp)
2414                 if (ciequal(word, lp->l_word))
2415                         return lp;
2416         /*
2417         ** Look for inexact match.
2418         */
2419         foundlp = NULL;
2420         for (lp = table; lp->l_word != NULL; ++lp)
2421                 if (itsabbr(word, lp->l_word)) {
2422                         if (foundlp == NULL)
2423                                 foundlp = lp;
2424                         else    return NULL;    /* multiple inexact matches */
2425                 }
2426         return foundlp;
2427 }
2428
2429 static char **
2430 getfields(cp)
2431 register char * cp;
2432 {
2433         register char *         dp;
2434         register char **        array;
2435         register int            nsubs;
2436
2437         if (cp == NULL)
2438                 return NULL;
2439         array = (char **) (void *)
2440                 emalloc((int) ((strlen(cp) + 1) * sizeof *array));
2441         nsubs = 0;
2442         for ( ; ; ) {
2443                 while (isascii((unsigned char) *cp) &&
2444                         isspace((unsigned char) *cp))
2445                                 ++cp;
2446                 if (*cp == '\0' || *cp == '#')
2447                         break;
2448                 array[nsubs++] = dp = cp;
2449                 do {
2450                         if ((*dp = *cp++) != '"')
2451                                 ++dp;
2452                         else while ((*dp = *cp++) != '"')
2453                                 if (*dp != '\0')
2454                                         ++dp;
2455                                 else {
2456                                         error(_(
2457                                                 "Odd number of quotation marks"
2458                                                 ));
2459                                         exit(1);
2460                                 }
2461                 } while (*cp != '\0' && *cp != '#' &&
2462                         (!isascii(*cp) || !isspace((unsigned char) *cp)));
2463                 if (isascii(*cp) && isspace((unsigned char) *cp))
2464                         ++cp;
2465                 *dp = '\0';
2466         }
2467         array[nsubs] = NULL;
2468         return array;
2469 }
2470
2471 static long
2472 oadd(t1, t2)
2473 const long      t1;
2474 const long      t2;
2475 {
2476         register long   t;
2477
2478         t = t1 + t2;
2479         if ((t2 > 0 && t <= t1) || (t2 < 0 && t >= t1)) {
2480                 error(_("time overflow"));
2481                 exit(EXIT_FAILURE);
2482         }
2483         return t;
2484 }
2485
2486 static zic_t
2487 tadd(t1, t2)
2488 const zic_t     t1;
2489 const long      t2;
2490 {
2491         register zic_t  t;
2492
2493         if (t1 == max_time && t2 > 0)
2494                 return max_time;
2495         if (t1 == min_time && t2 < 0)
2496                 return min_time;
2497         t = t1 + t2;
2498         if ((t2 > 0 && t <= t1) || (t2 < 0 && t >= t1)) {
2499                 error(_("time overflow"));
2500                 exit(EXIT_FAILURE);
2501         }
2502         return t;
2503 }
2504
2505 /*
2506 ** Given a rule, and a year, compute the date - in seconds since January 1,
2507 ** 1970, 00:00 LOCAL time - in that year that the rule refers to.
2508 */
2509
2510 static zic_t
2511 rpytime(rp, wantedy)
2512 register const struct rule * const      rp;
2513 register const int                      wantedy;
2514 {
2515         register int    y, m, i;
2516         register long   dayoff;                 /* with a nod to Margaret O. */
2517         register zic_t  t;
2518
2519         if (wantedy == INT_MIN)
2520                 return min_time;
2521         if (wantedy == INT_MAX)
2522                 return max_time;
2523         dayoff = 0;
2524         m = TM_JANUARY;
2525         y = EPOCH_YEAR;
2526         while (wantedy != y) {
2527                 if (wantedy > y) {
2528                         i = len_years[isleap(y)];
2529                         ++y;
2530                 } else {
2531                         --y;
2532                         i = -len_years[isleap(y)];
2533                 }
2534                 dayoff = oadd(dayoff, eitol(i));
2535         }
2536         while (m != rp->r_month) {
2537                 i = len_months[isleap(y)][m];
2538                 dayoff = oadd(dayoff, eitol(i));
2539                 ++m;
2540         }
2541         i = rp->r_dayofmonth;
2542         if (m == TM_FEBRUARY && i == 29 && !isleap(y)) {
2543                 if (rp->r_dycode == DC_DOWLEQ)
2544                         --i;
2545                 else {
2546                         error(_("use of 2/29 in non leap-year"));
2547                         exit(EXIT_FAILURE);
2548                 }
2549         }
2550         --i;
2551         dayoff = oadd(dayoff, eitol(i));
2552         if (rp->r_dycode == DC_DOWGEQ || rp->r_dycode == DC_DOWLEQ) {
2553                 register long   wday;
2554
2555 #define LDAYSPERWEEK    ((long) DAYSPERWEEK)
2556                 wday = eitol(EPOCH_WDAY);
2557                 /*
2558                 ** Don't trust mod of negative numbers.
2559                 */
2560                 if (dayoff >= 0)
2561                         wday = (wday + dayoff) % LDAYSPERWEEK;
2562                 else {
2563                         wday -= ((-dayoff) % LDAYSPERWEEK);
2564                         if (wday < 0)
2565                                 wday += LDAYSPERWEEK;
2566                 }
2567                 while (wday != eitol(rp->r_wday))
2568                         if (rp->r_dycode == DC_DOWGEQ) {
2569                                 dayoff = oadd(dayoff, (long) 1);
2570                                 if (++wday >= LDAYSPERWEEK)
2571                                         wday = 0;
2572                                 ++i;
2573                         } else {
2574                                 dayoff = oadd(dayoff, (long) -1);
2575                                 if (--wday < 0)
2576                                         wday = LDAYSPERWEEK - 1;
2577                                 --i;
2578                         }
2579                 if (i < 0 || i >= len_months[isleap(y)][m]) {
2580                         if (noise)
2581                                 warning(_("rule goes past start/end of month--\
2582 will not work with pre-2004 versions of zic"));
2583                 }
2584         }
2585         if (dayoff < min_time / SECSPERDAY)
2586                 return min_time;
2587         if (dayoff > max_time / SECSPERDAY)
2588                 return max_time;
2589         t = (zic_t) dayoff * SECSPERDAY;
2590         return tadd(t, rp->r_tod);
2591 }
2592
2593 static void
2594 newabbr(string)
2595 const char * const      string;
2596 {
2597         register int    i;
2598
2599         if (strcmp(string, GRANDPARENTED) != 0) {
2600                 register const char *   cp;
2601                 register char *         wp;
2602
2603                 /*
2604                 ** Want one to ZIC_MAX_ABBR_LEN_WO_WARN alphabetics
2605                 ** optionally followed by a + or - and a number from 1 to 14.
2606                 */
2607                 cp = string;
2608                 wp = NULL;
2609                 while (isascii((unsigned char) *cp) &&
2610                         isalpha((unsigned char) *cp))
2611                                 ++cp;
2612                 if (cp - string == 0)
2613 wp = _("time zone abbreviation lacks alphabetic at start");
2614                 if (noise && cp - string > 3)
2615 wp = _("time zone abbreviation has more than 3 alphabetics");
2616                 if (cp - string > ZIC_MAX_ABBR_LEN_WO_WARN)
2617 wp = _("time zone abbreviation has too many alphabetics");
2618                 if (wp == NULL && (*cp == '+' || *cp == '-')) {
2619                         ++cp;
2620                         if (isascii((unsigned char) *cp) &&
2621                                 isdigit((unsigned char) *cp))
2622                                         if (*cp++ == '1' &&
2623                                                 *cp >= '0' && *cp <= '4')
2624                                                         ++cp;
2625                 }
2626                 if (*cp != '\0')
2627 wp = _("time zone abbreviation differs from POSIX standard");
2628                 if (wp != NULL) {
2629                         wp = ecpyalloc(wp);
2630                         wp = ecatalloc(wp, " (");
2631                         wp = ecatalloc(wp, string);
2632                         wp = ecatalloc(wp, ")");
2633                         warning(wp);
2634                         ifree(wp);
2635                 }
2636         }
2637         i = strlen(string) + 1;
2638         if (charcnt + i > TZ_MAX_CHARS) {
2639                 error(_("too many, or too long, time zone abbreviations"));
2640                 exit(EXIT_FAILURE);
2641         }
2642         (void) strcpy(&chars[charcnt], string);
2643         charcnt += eitol(i);
2644 }
2645
2646 static int
2647 mkdirs(argname)
2648 char *          argname;
2649 {
2650         register char * name;
2651         register char * cp;
2652
2653         if (argname == NULL || *argname == '\0')
2654                 return 0;
2655         cp = name = ecpyalloc(argname);
2656         while ((cp = strchr(cp + 1, '/')) != 0) {
2657                 *cp = '\0';
2658 #ifndef unix
2659                 /*
2660                 ** DOS drive specifier?
2661                 */
2662                 if (isalpha((unsigned char) name[0]) &&
2663                         name[1] == ':' && name[2] == '\0') {
2664                                 *cp = '/';
2665                                 continue;
2666                 }
2667 #endif /* !defined unix */
2668                 if (!itsdir(name)) {
2669                         /*
2670                         ** It doesn't seem to exist, so we try to create it.
2671                         ** Creation may fail because of the directory being
2672                         ** created by some other multiprocessor, so we get
2673                         ** to do extra checking.
2674                         */
2675                         if (mkdir(name, MKDIR_UMASK) != 0) {
2676                                 const char *e = strerror(errno);
2677
2678                                 if (errno != EEXIST || !itsdir(name)) {
2679                                         (void) fprintf(stderr,
2680 _("%s: Can't create directory %s: %s\n"),
2681                                                 progname, name, e);
2682                                         ifree(name);
2683                                         return -1;
2684                                 }
2685                         }
2686                 }
2687                 *cp = '/';
2688         }
2689         ifree(name);
2690         return 0;
2691 }
2692
2693 static long
2694 eitol(i)
2695 const int       i;
2696 {
2697         long    l;
2698
2699         l = i;
2700         if ((i < 0 && l >= 0) || (i == 0 && l != 0) || (i > 0 && l <= 0)) {
2701                 (void) fprintf(stderr,
2702                         _("%s: %d did not sign extend correctly\n"),
2703                         progname, i);
2704                 exit(EXIT_FAILURE);
2705         }
2706         return l;
2707 }
2708
2709 /*
2710 ** UNIX was a registered trademark of The Open Group in 2003.
2711 */