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