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