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