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