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