eb19a5c3e3927dde12b03750e14571c67987c438
[kopensolaris-gnu/glibc.git] / time / zic.c
1 #ifndef lint
2 #ifndef NOID
3 static char     elsieid[] = "@(#)zic.c  7.19";
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         if (fromfile[0] == '/')
529                 fromname = fromfile;
530         else {
531                 fromname = ecpyalloc(directory);
532                 fromname = ecatalloc(fromname, "/");
533                 fromname = ecatalloc(fromname, fromfile);
534         }
535         if (tofile[0] == '/')
536                 toname = tofile;
537         else {
538                 toname = ecpyalloc(directory);
539                 toname = ecatalloc(toname, "/");
540                 toname = ecatalloc(toname, tofile);
541         }
542         /*
543         ** We get to be careful here since
544         ** there's a fair chance of root running us.
545         */
546         if (!itsdir(toname))
547                 (void) remove(toname);
548         if (link(fromname, toname) != 0) {
549                 if (mkdirs(toname) != 0)
550                         (void) exit(EXIT_FAILURE);
551                 if (link(fromname, toname) != 0) {
552                         (void) fprintf(stderr, "%s: Can't link from %s to ",
553                                 progname, fromname);
554                         (void) perror(toname);
555                         (void) exit(EXIT_FAILURE);
556                 }
557         }
558         if (fromname != fromfile)
559                 ifree(fromname);
560         if (toname != tofile)
561                 ifree(toname);
562 }
563
564 static void
565 setboundaries()
566 {
567         register time_t bit;
568
569         for (bit = 1; bit > 0; bit <<= 1)
570                 ;
571         if (bit == 0) {         /* time_t is an unsigned type */
572                 tt_signed = FALSE;
573                 min_time = 0;
574                 max_time = ~(time_t) 0;
575                 if (sflag)
576                         max_time >>= 1;
577         } else {
578                 tt_signed = TRUE;
579                 min_time = bit;
580                 max_time = bit;
581                 ++max_time;
582                 max_time = -max_time;
583                 if (sflag)
584                         min_time = 0;
585         }
586         min_year = TM_YEAR_BASE + gmtime(&min_time)->tm_year;
587         max_year = TM_YEAR_BASE + gmtime(&max_time)->tm_year;
588 }
589
590 static int
591 itsdir(name)
592 const char * const      name;
593 {
594         register char * myname;
595         register int    accres;
596
597         myname = ecpyalloc(name);
598         myname = ecatalloc(myname, "/.");
599         accres = access(myname, 0);
600         ifree(myname);
601         return accres == 0;
602 }
603
604 /*
605 ** Associate sets of rules with zones.
606 */
607
608 /*
609 ** Sort by rule name.
610 */
611
612 static int
613 rcomp(cp1, cp2)
614 const genericptr_t      cp1;
615 const genericptr_t      cp2;
616 {
617         return strcmp(((struct rule *) cp1)->r_name,
618                 ((struct rule *) cp2)->r_name);
619 }
620
621 static void
622 associate()
623 {
624         register struct zone *  zp;
625         register struct rule *  rp;
626         register int            base, out;
627         register int            i;
628
629         if (nrules != 0)
630                 (void) qsort((genericptr_t) rules,
631                         (qsort_size_t) nrules,
632                         (qsort_size_t) sizeof *rules, rcomp);
633         for (i = 0; i < nzones; ++i) {
634                 zp = &zones[i];
635                 zp->z_rules = NULL;
636                 zp->z_nrules = 0;
637         }
638         for (base = 0; base < nrules; base = out) {
639                 rp = &rules[base];
640                 for (out = base + 1; out < nrules; ++out)
641                         if (strcmp(rp->r_name, rules[out].r_name) != 0)
642                                 break;
643                 for (i = 0; i < nzones; ++i) {
644                         zp = &zones[i];
645                         if (strcmp(zp->z_rule, rp->r_name) != 0)
646                                 continue;
647                         zp->z_rules = rp;
648                         zp->z_nrules = out - base;
649                 }
650         }
651         for (i = 0; i < nzones; ++i) {
652                 zp = &zones[i];
653                 if (zp->z_nrules == 0) {
654                         /*
655                         ** Maybe we have a local standard time offset.
656                         */
657                         eat(zp->z_filename, zp->z_linenum);
658                         zp->z_stdoff = gethms(zp->z_rule, "unruly zone", TRUE);
659                         /*
660                         ** Note, though, that if there's no rule,
661                         ** a '%s' in the format is a bad thing.
662                         */
663                         if (strchr(zp->z_format, '%') != 0)
664                                 error("%s in ruleless zone");
665                 }
666         }
667         if (errors)
668                 (void) exit(EXIT_FAILURE);
669 }
670
671 static void
672 infile(name)
673 const char *    name;
674 {
675         register FILE *                 fp;
676         register char **                fields;
677         register char *                 cp;
678         register const struct lookup *  lp;
679         register int                    nfields;
680         register int                    wantcont;
681         register int                    num;
682         char                            buf[BUFSIZ];
683
684         if (strcmp(name, "-") == 0) {
685                 name = "standard input";
686                 fp = stdin;
687         } else if ((fp = fopen(name, "r")) == NULL) {
688                 (void) fprintf(stderr, "%s: Can't open ", progname);
689                 (void) perror(name);
690                 (void) exit(EXIT_FAILURE);
691         }
692         wantcont = FALSE;
693         for (num = 1; ; ++num) {
694                 eat(name, num);
695                 if (fgets(buf, (int) sizeof buf, fp) != buf)
696                         break;
697                 cp = strchr(buf, '\n');
698                 if (cp == NULL) {
699                         error("line too long");
700                         (void) exit(EXIT_FAILURE);
701                 }
702                 *cp = '\0';
703                 fields = getfields(buf);
704                 nfields = 0;
705                 while (fields[nfields] != NULL) {
706                         static char     nada[1];
707
708                         if (ciequal(fields[nfields], "-"))
709                                 fields[nfields] = nada;
710                         ++nfields;
711                 }
712                 if (nfields == 0) {
713                         /* nothing to do */
714                 } else if (wantcont) {
715                         wantcont = inzcont(fields, nfields);
716                 } else {
717                         lp = byword(fields[0], line_codes);
718                         if (lp == NULL)
719                                 error("input line of unknown type");
720                         else switch ((int) (lp->l_value)) {
721                                 case LC_RULE:
722                                         inrule(fields, nfields);
723                                         wantcont = FALSE;
724                                         break;
725                                 case LC_ZONE:
726                                         wantcont = inzone(fields, nfields);
727                                         break;
728                                 case LC_LINK:
729                                         inlink(fields, nfields);
730                                         wantcont = FALSE;
731                                         break;
732                                 case LC_LEAP:
733                                         if (name != leapsec)
734                                                 (void) fprintf(stderr,
735 "%s: Leap line in non leap seconds file %s\n",
736                                                         progname, name);
737                                         else    inleap(fields, nfields);
738                                         wantcont = FALSE;
739                                         break;
740                                 default:        /* "cannot happen" */
741                                         (void) fprintf(stderr,
742 "%s: panic: Invalid l_value %d\n",
743                                                 progname, lp->l_value);
744                                         (void) exit(EXIT_FAILURE);
745                         }
746                 }
747                 ifree((char *) fields);
748         }
749         if (ferror(fp)) {
750                 (void) fprintf(stderr, "%s: Error reading ", progname);
751                 (void) perror(filename);
752                 (void) exit(EXIT_FAILURE);
753         }
754         if (fp != stdin && fclose(fp)) {
755                 (void) fprintf(stderr, "%s: Error closing ", progname);
756                 (void) perror(filename);
757                 (void) exit(EXIT_FAILURE);
758         }
759         if (wantcont)
760                 error("expected continuation line not found");
761 }
762
763 /*
764 ** Convert a string of one of the forms
765 **      h       -h      hh:mm   -hh:mm  hh:mm:ss        -hh:mm:ss
766 ** into a number of seconds.
767 ** A null string maps to zero.
768 ** Call error with errstring and return zero on errors.
769 */
770
771 static long
772 gethms(string, errstring, signable)
773 const char *            string;
774 const char * const      errstring;
775 const int               signable;
776 {
777         int     hh, mm, ss, sign;
778
779         if (string == NULL || *string == '\0')
780                 return 0;
781         if (!signable)
782                 sign = 1;
783         else if (*string == '-') {
784                 sign = -1;
785                 ++string;
786         } else  sign = 1;
787         if (sscanf(string, scheck(string, "%d"), &hh) == 1)
788                 mm = ss = 0;
789         else if (sscanf(string, scheck(string, "%d:%d"), &hh, &mm) == 2)
790                 ss = 0;
791         else if (sscanf(string, scheck(string, "%d:%d:%d"),
792                 &hh, &mm, &ss) != 3) {
793                         error(errstring);
794                         return 0;
795         }
796         if (hh < 0 || hh >= HOURSPERDAY ||
797                 mm < 0 || mm >= MINSPERHOUR ||
798                 ss < 0 || ss > SECSPERMIN) {
799                         error(errstring);
800                         return 0;
801         }
802         return eitol(sign) *
803                 (eitol(hh * MINSPERHOUR + mm) *
804                 eitol(SECSPERMIN) + eitol(ss));
805 }
806
807 static void
808 inrule(fields, nfields)
809 register char ** const  fields;
810 const int               nfields;
811 {
812         static struct rule      r;
813
814         if (nfields != RULE_FIELDS) {
815                 error("wrong number of fields on Rule line");
816                 return;
817         }
818         if (*fields[RF_NAME] == '\0') {
819                 error("nameless rule");
820                 return;
821         }
822         r.r_filename = filename;
823         r.r_linenum = linenum;
824         r.r_stdoff = gethms(fields[RF_STDOFF], "invalid saved time", TRUE);
825         rulesub(&r, fields[RF_LOYEAR], fields[RF_HIYEAR], fields[RF_COMMAND],
826                 fields[RF_MONTH], fields[RF_DAY], fields[RF_TOD]);
827         r.r_name = ecpyalloc(fields[RF_NAME]);
828         r.r_abbrvar = ecpyalloc(fields[RF_ABBRVAR]);
829         rules = (struct rule *) erealloc((char *) rules,
830                 (int) ((nrules + 1) * sizeof *rules));
831         rules[nrules++] = r;
832 }
833
834 static int
835 inzone(fields, nfields)
836 register char ** const  fields;
837 const int               nfields;
838 {
839         register int    i;
840         static char *   buf;
841
842         if (nfields < ZONE_MINFIELDS || nfields > ZONE_MAXFIELDS) {
843                 error("wrong number of fields on Zone line");
844                 return FALSE;
845         }
846         if (strcmp(fields[ZF_NAME], TZDEFAULT) == 0 && lcltime != NULL) {
847                 buf = erealloc(buf, 132 + strlen(TZDEFAULT));
848                 (void) sprintf(buf,
849 "\"Zone %s\" line and -l option are mutually exclusive",
850                         TZDEFAULT);
851                 error(buf);
852                 return FALSE;
853         }
854         if (strcmp(fields[ZF_NAME], TZDEFRULES) == 0 && psxrules != NULL) {
855                 buf = erealloc(buf, 132 + strlen(TZDEFRULES));
856                 (void) sprintf(buf,
857 "\"Zone %s\" line and -p option are mutually exclusive",
858                         TZDEFRULES);
859                 error(buf);
860                 return FALSE;
861         }
862         for (i = 0; i < nzones; ++i)
863                 if (zones[i].z_name != NULL &&
864                         strcmp(zones[i].z_name, fields[ZF_NAME]) == 0) {
865                                 buf = erealloc(buf, 132 +
866                                         strlen(fields[ZF_NAME]) +
867                                         strlen(zones[i].z_filename));
868                                 (void) sprintf(buf,
869 "duplicate zone name %s (file \"%s\", line %d)",
870                                         fields[ZF_NAME],
871                                         zones[i].z_filename,
872                                         zones[i].z_linenum);
873                                 error(buf);
874                                 return FALSE;
875                 }
876         return inzsub(fields, nfields, FALSE);
877 }
878
879 static int
880 inzcont(fields, nfields)
881 register char ** const  fields;
882 const int               nfields;
883 {
884         if (nfields < ZONEC_MINFIELDS || nfields > ZONEC_MAXFIELDS) {
885                 error("wrong number of fields on Zone continuation line");
886                 return FALSE;
887         }
888         return inzsub(fields, nfields, TRUE);
889 }
890
891 static int
892 inzsub(fields, nfields, iscont)
893 register char ** const  fields;
894 const int               nfields;
895 const int               iscont;
896 {
897         register char *         cp;
898         static struct zone      z;
899         register int            i_gmtoff, i_rule, i_format;
900         register int            i_untilyear, i_untilmonth;
901         register int            i_untilday, i_untiltime;
902         register int            hasuntil;
903
904         if (iscont) {
905                 i_gmtoff = ZFC_GMTOFF;
906                 i_rule = ZFC_RULE;
907                 i_format = ZFC_FORMAT;
908                 i_untilyear = ZFC_TILYEAR;
909                 i_untilmonth = ZFC_TILMONTH;
910                 i_untilday = ZFC_TILDAY;
911                 i_untiltime = ZFC_TILTIME;
912                 z.z_name = NULL;
913         } else {
914                 i_gmtoff = ZF_GMTOFF;
915                 i_rule = ZF_RULE;
916                 i_format = ZF_FORMAT;
917                 i_untilyear = ZF_TILYEAR;
918                 i_untilmonth = ZF_TILMONTH;
919                 i_untilday = ZF_TILDAY;
920                 i_untiltime = ZF_TILTIME;
921                 z.z_name = ecpyalloc(fields[ZF_NAME]);
922         }
923         z.z_filename = filename;
924         z.z_linenum = linenum;
925         z.z_gmtoff = gethms(fields[i_gmtoff], "invalid GMT offset", TRUE);
926         if ((cp = strchr(fields[i_format], '%')) != 0) {
927                 if (*++cp != 's' || strchr(cp, '%') != 0) {
928                         error("invalid abbreviation format");
929                         return FALSE;
930                 }
931         }
932         z.z_rule = ecpyalloc(fields[i_rule]);
933         z.z_format = ecpyalloc(fields[i_format]);
934         hasuntil = nfields > i_untilyear;
935         if (hasuntil) {
936                 z.z_untilrule.r_filename = filename;
937                 z.z_untilrule.r_linenum = linenum;
938                 rulesub(&z.z_untilrule,
939                         fields[i_untilyear],
940                         "only",
941                         "",
942                         (nfields > i_untilmonth) ?
943                         fields[i_untilmonth] : "Jan",
944                         (nfields > i_untilday) ? fields[i_untilday] : "1",
945                         (nfields > i_untiltime) ? fields[i_untiltime] : "0");
946                 z.z_untiltime = rpytime(&z.z_untilrule,
947                         z.z_untilrule.r_loyear);
948                 if (iscont && nzones > 0 &&
949                         z.z_untiltime > min_time &&
950                         z.z_untiltime < max_time &&
951                         zones[nzones - 1].z_untiltime > min_time &&
952                         zones[nzones - 1].z_untiltime < max_time &&
953                         zones[nzones - 1].z_untiltime >= z.z_untiltime) {
954 error("Zone continuation line end time is not after end time of previous line");
955                                 return FALSE;
956                 }
957         }
958         zones = (struct zone *) erealloc((char *) zones,
959                 (int) ((nzones + 1) * sizeof *zones));
960         zones[nzones++] = z;
961         /*
962         ** If there was an UNTIL field on this line,
963         ** there's more information about the zone on the next line.
964         */
965         return hasuntil;
966 }
967
968 static void
969 inleap(fields, nfields)
970 register char ** const  fields;
971 const int               nfields;
972 {
973         register const char *           cp;
974         register const struct lookup *  lp;
975         register int                    i, j;
976         int                             year, month, day;
977         long                            dayoff, tod;
978         time_t                          t;
979
980         if (nfields != LEAP_FIELDS) {
981                 error("wrong number of fields on Leap line");
982                 return;
983         }
984         dayoff = 0;
985         cp = fields[LP_YEAR];
986         if (sscanf(cp, scheck(cp, "%d"), &year) != 1) {
987                         /*
988                          * Leapin' Lizards!
989                          */
990                         error("invalid leaping year");
991                         return;
992         }
993         j = EPOCH_YEAR;
994         while (j != year) {
995                 if (year > j) {
996                         i = len_years[isleap(j)];
997                         ++j;
998                 } else {
999                         --j;
1000                         i = -len_years[isleap(j)];
1001                 }
1002                 dayoff = oadd(dayoff, eitol(i));
1003         }
1004         if ((lp = byword(fields[LP_MONTH], mon_names)) == NULL) {
1005                 error("invalid month name");
1006                 return;
1007         }
1008         month = lp->l_value;
1009         j = TM_JANUARY;
1010         while (j != month) {
1011                 i = len_months[isleap(year)][j];
1012                 dayoff = oadd(dayoff, eitol(i));
1013                 ++j;
1014         }
1015         cp = fields[LP_DAY];
1016         if (sscanf(cp, scheck(cp, "%d"), &day) != 1 ||
1017                 day <= 0 || day > len_months[isleap(year)][month]) {
1018                         error("invalid day of month");
1019                         return;
1020         }
1021         dayoff = oadd(dayoff, eitol(day - 1));
1022         if (dayoff < 0 && !tt_signed) {
1023                 error("time before zero");
1024                 return;
1025         }
1026         t = (time_t) dayoff * SECSPERDAY;
1027         /*
1028         ** Cheap overflow check.
1029         */
1030         if (t / SECSPERDAY != dayoff) {
1031                 error("time overflow");
1032                 return;
1033         }
1034         tod = gethms(fields[LP_TIME], "invalid time of day", FALSE);
1035         cp = fields[LP_CORR];
1036         {
1037                 register int    positive;
1038                 int             count;
1039
1040                 if (strcmp(cp, "") == 0) { /* infile() turns "-" into "" */
1041                         positive = FALSE;
1042                         count = 1;
1043                 } else if (strcmp(cp, "--") == 0) {
1044                         positive = FALSE;
1045                         count = 2;
1046                 } else if (strcmp(cp, "+") == 0) {
1047                         positive = TRUE;
1048                         count = 1;
1049                 } else if (strcmp(cp, "++") == 0) {
1050                         positive = TRUE;
1051                         count = 2;
1052                 } else {
1053                         error("illegal CORRECTION field on Leap line");
1054                         return;
1055                 }
1056                 if ((lp = byword(fields[LP_ROLL], leap_types)) == NULL) {
1057                         error("illegal Rolling/Stationary field on Leap line");
1058                         return;
1059                 }
1060                 leapadd(tadd(t, tod), positive, lp->l_value, count);
1061         }
1062 }
1063
1064 static void
1065 inlink(fields, nfields)
1066 register char ** const  fields;
1067 const int               nfields;
1068 {
1069         struct link     l;
1070
1071         if (nfields != LINK_FIELDS) {
1072                 error("wrong number of fields on Link line");
1073                 return;
1074         }
1075         if (*fields[LF_FROM] == '\0') {
1076                 error("blank FROM field on Link line");
1077                 return;
1078         }
1079         if (*fields[LF_TO] == '\0') {
1080                 error("blank TO field on Link line");
1081                 return;
1082         }
1083         l.l_filename = filename;
1084         l.l_linenum = linenum;
1085         l.l_from = ecpyalloc(fields[LF_FROM]);
1086         l.l_to = ecpyalloc(fields[LF_TO]);
1087         links = (struct link *) erealloc((char *) links,
1088                 (int) ((nlinks + 1) * sizeof *links));
1089         links[nlinks++] = l;
1090 }
1091
1092 static void
1093 rulesub(rp, loyearp, hiyearp, typep, monthp, dayp, timep)
1094 register struct rule * const    rp;
1095 char * const                    loyearp;
1096 char * const                    hiyearp;
1097 char * const                    typep;
1098 char * const                    monthp;
1099 char * const                    dayp;
1100 char * const                    timep;
1101 {
1102         register struct lookup const *  lp;
1103         register char *                 cp;
1104
1105         if ((lp = byword(monthp, mon_names)) == NULL) {
1106                 error("invalid month name");
1107                 return;
1108         }
1109         rp->r_month = lp->l_value;
1110         rp->r_todisstd = FALSE;
1111         cp = timep;
1112         if (*cp != '\0') {
1113                 cp += strlen(cp) - 1;
1114                 switch (lowerit(*cp)) {
1115                         case 's':
1116                                 rp->r_todisstd = TRUE;
1117                                 *cp = '\0';
1118                                 break;
1119                         case 'w':
1120                                 rp->r_todisstd = FALSE;
1121                                 *cp = '\0';
1122                                 break;
1123                 }
1124         }
1125         rp->r_tod = gethms(timep, "invalid time of day", FALSE);
1126         /*
1127         ** Year work.
1128         */
1129         cp = loyearp;
1130         if ((lp = byword(cp, begin_years)) != NULL) switch ((int) lp->l_value) {
1131                 case YR_MINIMUM:
1132                         rp->r_loyear = min_year;
1133                         break;
1134                 case YR_MAXIMUM:
1135                         rp->r_loyear = max_year;
1136                         break;
1137                 default:        /* "cannot happen" */
1138                         (void) fprintf(stderr,
1139                                 "%s: panic: Invalid l_value %d\n",
1140                                 progname, lp->l_value);
1141                         (void) exit(EXIT_FAILURE);
1142         } else if (sscanf(cp, scheck(cp, "%d"), &rp->r_loyear) != 1) {
1143                 error("invalid starting year");
1144                 return;
1145         }
1146         cp = hiyearp;
1147         if ((lp = byword(cp, end_years)) != NULL) switch ((int) lp->l_value) {
1148                 case YR_MINIMUM:
1149                         rp->r_hiyear = min_year;
1150                         break;
1151                 case YR_MAXIMUM:
1152                         rp->r_hiyear = max_year;
1153                         break;
1154                 case YR_ONLY:
1155                         rp->r_hiyear = rp->r_loyear;
1156                         break;
1157                 default:        /* "cannot happen" */
1158                         (void) fprintf(stderr,
1159                                 "%s: panic: Invalid l_value %d\n",
1160                                 progname, lp->l_value);
1161                         (void) exit(EXIT_FAILURE);
1162         } else if (sscanf(cp, scheck(cp, "%d"), &rp->r_hiyear) != 1) {
1163                 error("invalid ending year");
1164                 return;
1165         }
1166         if (rp->r_loyear > rp->r_hiyear) {
1167                 error("starting year greater than ending year");
1168                 return;
1169         }
1170         if (*typep == '\0')
1171                 rp->r_yrtype = NULL;
1172         else {
1173                 if (rp->r_loyear == rp->r_hiyear) {
1174                         error("typed single year");
1175                         return;
1176                 }
1177                 rp->r_yrtype = ecpyalloc(typep);
1178         }
1179         /*
1180         ** Day work.
1181         ** Accept things such as:
1182         **      1
1183         **      last-Sunday
1184         **      Sun<=20
1185         **      Sun>=7
1186         */
1187         if ((lp = byword(dayp, lasts)) != NULL) {
1188                 rp->r_dycode = DC_DOWLEQ;
1189                 rp->r_wday = lp->l_value;
1190                 rp->r_dayofmonth = len_months[1][rp->r_month];
1191         } else {
1192                 if ((cp = strchr(dayp, '<')) != 0)
1193                         rp->r_dycode = DC_DOWLEQ;
1194                 else if ((cp = strchr(dayp, '>')) != 0)
1195                         rp->r_dycode = DC_DOWGEQ;
1196                 else {
1197                         cp = dayp;
1198                         rp->r_dycode = DC_DOM;
1199                 }
1200                 if (rp->r_dycode != DC_DOM) {
1201                         *cp++ = 0;
1202                         if (*cp++ != '=') {
1203                                 error("invalid day of month");
1204                                 return;
1205                         }
1206                         if ((lp = byword(dayp, wday_names)) == NULL) {
1207                                 error("invalid weekday name");
1208                                 return;
1209                         }
1210                         rp->r_wday = lp->l_value;
1211                 }
1212                 if (sscanf(cp, scheck(cp, "%d"), &rp->r_dayofmonth) != 1 ||
1213                         rp->r_dayofmonth <= 0 ||
1214                         (rp->r_dayofmonth > len_months[1][rp->r_month])) {
1215                                 error("invalid day of month");
1216                                 return;
1217                 }
1218         }
1219 }
1220
1221 static void
1222 convert(val, buf)
1223 const long      val;
1224 char * const    buf;
1225 {
1226         register int    i;
1227         register long   shift;
1228
1229         for (i = 0, shift = 24; i < 4; ++i, shift -= 8)
1230                 buf[i] = val >> shift;
1231 }
1232
1233 static void
1234 puttzcode(val, fp)
1235 const long      val;
1236 FILE * const    fp;
1237 {
1238         char    buf[4];
1239
1240         convert(val, buf);
1241         (void) fwrite((genericptr_t) buf,
1242                 (fwrite_size_t) sizeof buf,
1243                 (fwrite_size_t) 1, fp);
1244 }
1245
1246 static void
1247 writezone(name)
1248 const char * const      name;
1249 {
1250         register FILE *         fp;
1251         register int            i, j;
1252         static char *           fullname;
1253         static struct tzhead    tzh;
1254
1255         fullname = erealloc(fullname,
1256                 strlen(directory) + 1 + strlen(name) + 1);
1257         (void) sprintf(fullname, "%s/%s", directory, name);
1258         if ((fp = fopen(fullname, "wb")) == NULL) {
1259                 if (mkdirs(fullname) != 0)
1260                         (void) exit(EXIT_FAILURE);
1261                 if ((fp = fopen(fullname, "wb")) == NULL) {
1262                         (void) fprintf(stderr, "%s: Can't create ", progname);
1263                         (void) perror(fullname);
1264                         (void) exit(EXIT_FAILURE);
1265                 }
1266         }
1267         convert(eitol(typecnt), tzh.tzh_ttisstdcnt);
1268         convert(eitol(leapcnt), tzh.tzh_leapcnt);
1269         convert(eitol(timecnt), tzh.tzh_timecnt);
1270         convert(eitol(typecnt), tzh.tzh_typecnt);
1271         convert(eitol(charcnt), tzh.tzh_charcnt);
1272         (void) fwrite((genericptr_t) &tzh,
1273                 (fwrite_size_t) sizeof tzh,
1274                 (fwrite_size_t) 1, fp);
1275         for (i = 0; i < timecnt; ++i) {
1276                 j = leapcnt;
1277                 while (--j >= 0)
1278                         if (ats[i] >= trans[j]) {
1279                                 ats[i] = tadd(ats[i], corr[j]);
1280                                 break;
1281                         }
1282                 puttzcode((long) ats[i], fp);
1283         }
1284         if (timecnt > 0)
1285                 (void) fwrite((genericptr_t) types,
1286                         (fwrite_size_t) sizeof types[0],
1287                         (fwrite_size_t) timecnt, fp);
1288         for (i = 0; i < typecnt; ++i) {
1289                 puttzcode((long) gmtoffs[i], fp);
1290                 (void) putc(isdsts[i], fp);
1291                 (void) putc(abbrinds[i], fp);
1292         }
1293         if (charcnt != 0)
1294                 (void) fwrite((genericptr_t) chars,
1295                         (fwrite_size_t) sizeof chars[0],
1296                         (fwrite_size_t) charcnt, fp);
1297         for (i = 0; i < leapcnt; ++i) {
1298                 if (roll[i]) {
1299                         if (timecnt == 0 || trans[i] < ats[0]) {
1300                                 j = 0;
1301                                 while (isdsts[j])
1302                                         if (++j >= typecnt) {
1303                                                 j = 0;
1304                                                 break;
1305                                         }
1306                         } else {
1307                                 j = 1;
1308                                 while (j < timecnt && trans[i] >= ats[j])
1309                                         ++j;
1310                                 j = types[j - 1];
1311                         }
1312                         puttzcode((long) tadd(trans[i], -gmtoffs[j]), fp);
1313                 } else  puttzcode((long) trans[i], fp);
1314                 puttzcode((long) corr[i], fp);
1315         }
1316         for (i = 0; i < typecnt; ++i)
1317                 (void) putc(ttisstds[i], fp);
1318         if (ferror(fp) || fclose(fp)) {
1319                 (void) fprintf(stderr, "%s: Write error on ", progname);
1320                 (void) perror(fullname);
1321                 (void) exit(EXIT_FAILURE);
1322         }
1323 }
1324
1325 static void
1326 outzone(zpfirst, zonecount)
1327 const struct zone * const       zpfirst;
1328 const int                       zonecount;
1329 {
1330         register const struct zone *    zp;
1331         register struct rule *          rp;
1332         register int                    i, j;
1333         register int                    usestart, useuntil;
1334         register time_t                 starttime, untiltime;
1335         register long                   gmtoff;
1336         register long                   stdoff;
1337         register int                    year;
1338         register long                   startoff;
1339         register int                    startisdst;
1340         register int                    startttisstd;
1341         register int                    type;
1342         char                            startbuf[BUFSIZ];
1343
1344         /*
1345         ** Now. . .finally. . .generate some useful data!
1346         */
1347         timecnt = 0;
1348         typecnt = 0;
1349         charcnt = 0;
1350         /*
1351         ** A guess that may well be corrected later.
1352         */
1353         stdoff = 0;
1354         /*
1355         ** Thanks to Earl Chew (earl@dnd.icp.nec.com.au)
1356         ** for noting the need to unconditionally initialize startttisstd.
1357         */
1358         startttisstd = FALSE;
1359 #ifdef lint
1360         starttime = 0;
1361 #endif /* defined lint */
1362         for (i = 0; i < zonecount; ++i) {
1363                 zp = &zpfirst[i];
1364                 usestart = i > 0 && (zp - 1)->z_untiltime > min_time;
1365                 useuntil = i < (zonecount - 1);
1366                 if (useuntil && zp->z_untiltime <= min_time)
1367                         continue;
1368                 gmtoff = zp->z_gmtoff;
1369                 eat(zp->z_filename, zp->z_linenum);
1370                 startisdst = -1;
1371                 if (zp->z_nrules == 0) {
1372                         stdoff = zp->z_stdoff;
1373                         (void) strcpy(startbuf, zp->z_format);
1374                         type = addtype(oadd(zp->z_gmtoff, stdoff),
1375                                 startbuf, stdoff != 0, startttisstd);
1376                         if (usestart)
1377                                 addtt(starttime, type);
1378                         else if (stdoff != 0)
1379                                 addtt(min_time, type);
1380                 } else for (year = min_year; year <= max_year; ++year) {
1381                         if (useuntil && year > zp->z_untilrule.r_hiyear)
1382                                 break;
1383                         /*
1384                         ** Mark which rules to do in the current year.
1385                         ** For those to do, calculate rpytime(rp, year);
1386                         */
1387                         for (j = 0; j < zp->z_nrules; ++j) {
1388                                 rp = &zp->z_rules[j];
1389                                 eats(zp->z_filename, zp->z_linenum,
1390                                         rp->r_filename, rp->r_linenum);
1391                                 rp->r_todo = year >= rp->r_loyear &&
1392                                                 year <= rp->r_hiyear &&
1393                                                 yearistype(year, rp->r_yrtype);
1394                                 if (rp->r_todo)
1395                                         rp->r_temp = rpytime(rp, year);
1396                         }
1397                         for ( ; ; ) {
1398                                 register int    k;
1399                                 register time_t jtime, ktime;
1400                                 register long   offset;
1401                                 char            buf[BUFSIZ];
1402
1403                                 if (useuntil) {
1404                                         /*
1405                                         ** Turn untiltime into GMT
1406                                         ** assuming the current gmtoff and
1407                                         ** stdoff values.
1408                                         */
1409                                         untiltime = tadd(zp->z_untiltime,
1410                                                 -gmtoff);
1411                                         if (!zp->z_untilrule.r_todisstd)
1412                                                 untiltime = tadd(untiltime,
1413                                                         -stdoff);
1414                                 }
1415                                 /*
1416                                 ** Find the rule (of those to do, if any)
1417                                 ** that takes effect earliest in the year.
1418                                 */
1419                                 k = -1;
1420 #ifdef lint
1421                                 ktime = 0;
1422 #endif /* defined lint */
1423                                 for (j = 0; j < zp->z_nrules; ++j) {
1424                                         rp = &zp->z_rules[j];
1425                                         if (!rp->r_todo)
1426                                                 continue;
1427                                         eats(zp->z_filename, zp->z_linenum,
1428                                                 rp->r_filename, rp->r_linenum);
1429                                         offset = gmtoff;
1430                                         if (!rp->r_todisstd)
1431                                                 offset = oadd(offset, stdoff);
1432                                         jtime = rp->r_temp;
1433                                         if (jtime == min_time ||
1434                                                 jtime == max_time)
1435                                                         continue;
1436                                         jtime = tadd(jtime, -offset);
1437                                         if (k < 0 || jtime < ktime) {
1438                                                 k = j;
1439                                                 ktime = jtime;
1440                                         }
1441                                 }
1442                                 if (k < 0)
1443                                         break;  /* go on to next year */
1444                                 rp = &zp->z_rules[k];
1445                                 rp->r_todo = FALSE;
1446                                 if (useuntil && ktime >= untiltime)
1447                                         break;
1448                                 if (usestart) {
1449                                     if (ktime < starttime) {
1450                                         stdoff = rp->r_stdoff;
1451                                         startoff = oadd(zp->z_gmtoff,
1452                                                 rp->r_stdoff);
1453                                         (void) sprintf(startbuf, zp->z_format,
1454                                                 rp->r_abbrvar);
1455                                         startisdst = rp->r_stdoff != 0;
1456                                         continue;
1457                                     }
1458                                     usestart = FALSE;
1459                                     if (ktime != starttime) {
1460                                         if (startisdst < 0 &&
1461                                             zp->z_gmtoff !=
1462                                             (zp - 1)->z_gmtoff) {
1463                                                 type = (timecnt == 0) ? 0 :
1464                                                         types[timecnt - 1];
1465                                                 startoff = oadd(gmtoffs[type],
1466                                                         -(zp - 1)->z_gmtoff);
1467                                                 startisdst = startoff != 0;
1468                                                 startoff = oadd(startoff,
1469                                                         zp->z_gmtoff);
1470                                                 (void) strcpy(startbuf,
1471                                                         &chars[abbrinds[type]]);
1472                                         }
1473                                         if (startisdst >= 0)
1474 addtt(starttime, addtype(startoff, startbuf, startisdst, startttisstd));
1475                                     }
1476                                 }
1477                                 eats(zp->z_filename, zp->z_linenum,
1478                                         rp->r_filename, rp->r_linenum);
1479                                 (void) sprintf(buf, zp->z_format,
1480                                         rp->r_abbrvar);
1481                                 offset = oadd(zp->z_gmtoff, rp->r_stdoff);
1482                                 type = addtype(offset, buf, rp->r_stdoff != 0,
1483                                         rp->r_todisstd);
1484                                 addtt(ktime, type);
1485                                 stdoff = rp->r_stdoff;
1486                         }
1487                 }
1488                 /*
1489                 ** Now we may get to set starttime for the next zone line.
1490                 */
1491                 if (useuntil) {
1492                         starttime = tadd(zp->z_untiltime, -gmtoff);
1493                         startttisstd = zp->z_untilrule.r_todisstd;
1494                         if (!startttisstd)
1495                                 starttime = tadd(starttime, -stdoff);
1496                 }
1497         }
1498         writezone(zpfirst->z_name);
1499 }
1500
1501 static void
1502 addtt(starttime, type)
1503 const time_t    starttime;
1504 const int       type;
1505 {
1506         if (timecnt != 0 && type == types[timecnt - 1])
1507                 return; /* easy enough! */
1508         if (timecnt == 0 && type == 0 && isdsts[0] == 0)
1509                 return; /* handled by default rule */
1510         if (timecnt >= TZ_MAX_TIMES) {
1511                 error("too many transitions?!");
1512                 (void) exit(EXIT_FAILURE);
1513         }
1514         ats[timecnt] = starttime;
1515         types[timecnt] = type;
1516         ++timecnt;
1517 }
1518
1519 static int
1520 addtype(gmtoff, abbr, isdst, ttisstd)
1521 const long              gmtoff;
1522 const char * const      abbr;
1523 const int               isdst;
1524 const int               ttisstd;
1525 {
1526         register int    i, j;
1527
1528         /*
1529         ** See if there's already an entry for this zone type.
1530         ** If so, just return its index.
1531         */
1532         for (i = 0; i < typecnt; ++i) {
1533                 if (gmtoff == gmtoffs[i] && isdst == isdsts[i] &&
1534                         strcmp(abbr, &chars[abbrinds[i]]) == 0 &&
1535                         ttisstd == ttisstds[i])
1536                                 return i;
1537         }
1538         /*
1539         ** There isn't one; add a new one, unless there are already too
1540         ** many.
1541         */
1542         if (typecnt >= TZ_MAX_TYPES) {
1543                 error("too many local time types");
1544                 (void) exit(EXIT_FAILURE);
1545         }
1546         gmtoffs[i] = gmtoff;
1547         isdsts[i] = isdst;
1548         ttisstds[i] = ttisstd;
1549
1550         for (j = 0; j < charcnt; ++j)
1551                 if (strcmp(&chars[j], abbr) == 0)
1552                         break;
1553         if (j == charcnt)
1554                 newabbr(abbr);
1555         abbrinds[i] = j;
1556         ++typecnt;
1557         return i;
1558 }
1559
1560 static void
1561 leapadd(t, positive, rolling, count)
1562 const time_t    t;
1563 const int       positive;
1564 const int       rolling;
1565 int             count;
1566 {
1567         register int    i, j;
1568
1569         if (leapcnt + (positive ? count : 1) > TZ_MAX_LEAPS) {
1570                 error("too many leap seconds");
1571                 (void) exit(EXIT_FAILURE);
1572         }
1573         for (i = 0; i < leapcnt; ++i)
1574                 if (t <= trans[i]) {
1575                         if (t == trans[i]) {
1576                                 error("repeated leap second moment");
1577                                 (void) exit(EXIT_FAILURE);
1578                         }
1579                         break;
1580                 }
1581         do {
1582                 for (j = leapcnt; j > i; --j) {
1583                         trans[j] = trans[j - 1];
1584                         corr[j] = corr[j - 1];
1585                         roll[j] = roll[j - 1];
1586                 }
1587                 trans[i] = t;
1588                 corr[i] = positive ? 1L : eitol(-count);
1589                 roll[i] = rolling;
1590                 ++leapcnt;
1591         } while (positive && --count != 0);
1592 }
1593
1594 static void
1595 adjleap()
1596 {
1597         register int    i;
1598         register long   last = 0;
1599
1600         /*
1601         ** propagate leap seconds forward
1602         */
1603         for (i = 0; i < leapcnt; ++i) {
1604                 trans[i] = tadd(trans[i], last);
1605                 last = corr[i] += last;
1606         }
1607 }
1608
1609 static int
1610 yearistype(year, type)
1611 const int               year;
1612 const char * const      type;
1613 {
1614         static char *   buf;
1615         int             result;
1616
1617         if (type == NULL || *type == '\0')
1618                 return TRUE;
1619         if (strcmp(type, "uspres") == 0)
1620                 return (year % 4) == 0;
1621         if (strcmp(type, "nonpres") == 0)
1622                 return (year % 4) != 0;
1623         buf = erealloc(buf, 132 + strlen(yitcommand) + strlen(type));
1624         (void) sprintf(buf, "%s %d %s", yitcommand, year, type);
1625         result = system(buf);
1626         if (result == 0)
1627                 return TRUE;
1628         if (result == (1 << 8))
1629                 return FALSE;
1630         error("Wild result from command execution");
1631         (void) fprintf(stderr, "%s: command was '%s', result was %d\n",
1632                 progname, buf, result);
1633         for ( ; ; )
1634                 (void) exit(EXIT_FAILURE);
1635 }
1636
1637 static int
1638 lowerit(a)
1639 const int       a;
1640 {
1641         return (isascii(a) && isupper(a)) ? tolower(a) : a;
1642 }
1643
1644 static int
1645 ciequal(ap, bp)         /* case-insensitive equality */
1646 register const char *   ap;
1647 register const char *   bp;
1648 {
1649         while (lowerit(*ap) == lowerit(*bp++))
1650                 if (*ap++ == '\0')
1651                         return TRUE;
1652         return FALSE;
1653 }
1654
1655 static int
1656 itsabbr(abbr, word)
1657 register const char *   abbr;
1658 register const char *   word;
1659 {
1660         if (lowerit(*abbr) != lowerit(*word))
1661                 return FALSE;
1662         ++word;
1663         while (*++abbr != '\0')
1664                 do if (*word == '\0')
1665                         return FALSE;
1666                                 while (lowerit(*word++) != lowerit(*abbr));
1667         return TRUE;
1668 }
1669
1670 static const struct lookup *
1671 byword(word, table)
1672 register const char * const             word;
1673 register const struct lookup * const    table;
1674 {
1675         register const struct lookup *  foundlp;
1676         register const struct lookup *  lp;
1677
1678         if (word == NULL || table == NULL)
1679                 return NULL;
1680         /*
1681         ** Look for exact match.
1682         */
1683         for (lp = table; lp->l_word != NULL; ++lp)
1684                 if (ciequal(word, lp->l_word))
1685                         return lp;
1686         /*
1687         ** Look for inexact match.
1688         */
1689         foundlp = NULL;
1690         for (lp = table; lp->l_word != NULL; ++lp)
1691                 if (itsabbr(word, lp->l_word))
1692                         if (foundlp == NULL)
1693                                 foundlp = lp;
1694                         else    return NULL;    /* multiple inexact matches */
1695         return foundlp;
1696 }
1697
1698 static char **
1699 getfields(cp)
1700 register char * cp;
1701 {
1702         register char *         dp;
1703         register char **        array;
1704         register int            nsubs;
1705
1706         if (cp == NULL)
1707                 return NULL;
1708         array = (char **) emalloc((int) ((strlen(cp) + 1) * sizeof *array));
1709         nsubs = 0;
1710         for ( ; ; ) {
1711                 while (isascii(*cp) && isspace(*cp))
1712                         ++cp;
1713                 if (*cp == '\0' || *cp == '#')
1714                         break;
1715                 array[nsubs++] = dp = cp;
1716                 do {
1717                         if ((*dp = *cp++) != '"')
1718                                 ++dp;
1719                         else while ((*dp = *cp++) != '"')
1720                                 if (*dp != '\0')
1721                                         ++dp;
1722                                 else    error("Odd number of quotation marks");
1723                 } while (*cp != '\0' && *cp != '#' &&
1724                         (!isascii(*cp) || !isspace(*cp)));
1725                 if (isascii(*cp) && isspace(*cp))
1726                         ++cp;
1727                 *dp = '\0';
1728         }
1729         array[nsubs] = NULL;
1730         return array;
1731 }
1732
1733 static long
1734 oadd(t1, t2)
1735 const long      t1;
1736 const long      t2;
1737 {
1738         register long   t;
1739
1740         t = t1 + t2;
1741         if ((t2 > 0 && t <= t1) || (t2 < 0 && t >= t1)) {
1742                 error("time overflow");
1743                 (void) exit(EXIT_FAILURE);
1744         }
1745         return t;
1746 }
1747
1748 static time_t
1749 tadd(t1, t2)
1750 const time_t    t1;
1751 const long      t2;
1752 {
1753         register time_t t;
1754
1755         if (t1 == max_time && t2 > 0)
1756                 return max_time;
1757         if (t1 == min_time && t2 < 0)
1758                 return min_time;
1759         t = t1 + t2;
1760         if ((t2 > 0 && t <= t1) || (t2 < 0 && t >= t1)) {
1761                 error("time overflow");
1762                 (void) exit(EXIT_FAILURE);
1763         }
1764         return t;
1765 }
1766
1767 /*
1768 ** Given a rule, and a year, compute the date - in seconds since January 1,
1769 ** 1970, 00:00 LOCAL time - in that year that the rule refers to.
1770 */
1771
1772 static time_t
1773 rpytime(rp, wantedy)
1774 register const struct rule * const      rp;
1775 register const int                      wantedy;
1776 {
1777         register int    y, m, i;
1778         register long   dayoff;                 /* with a nod to Margaret O. */
1779         register time_t t;
1780
1781         dayoff = 0;
1782         m = TM_JANUARY;
1783         y = EPOCH_YEAR;
1784         while (wantedy != y) {
1785                 if (wantedy > y) {
1786                         i = len_years[isleap(y)];
1787                         ++y;
1788                 } else {
1789                         --y;
1790                         i = -len_years[isleap(y)];
1791                 }
1792                 dayoff = oadd(dayoff, eitol(i));
1793         }
1794         while (m != rp->r_month) {
1795                 i = len_months[isleap(y)][m];
1796                 dayoff = oadd(dayoff, eitol(i));
1797                 ++m;
1798         }
1799         i = rp->r_dayofmonth;
1800         if (m == TM_FEBRUARY && i == 29 && !isleap(y)) {
1801                 if (rp->r_dycode == DC_DOWLEQ)
1802                         --i;
1803                 else {
1804                         error("use of 2/29 in non leap-year");
1805                         (void) exit(EXIT_FAILURE);
1806                 }
1807         }
1808         --i;
1809         dayoff = oadd(dayoff, eitol(i));
1810         if (rp->r_dycode == DC_DOWGEQ || rp->r_dycode == DC_DOWLEQ) {
1811                 register long   wday;
1812
1813 #define LDAYSPERWEEK    ((long) DAYSPERWEEK)
1814                 wday = eitol(EPOCH_WDAY);
1815                 /*
1816                 ** Don't trust mod of negative numbers.
1817                 */
1818                 if (dayoff >= 0)
1819                         wday = (wday + dayoff) % LDAYSPERWEEK;
1820                 else {
1821                         wday -= ((-dayoff) % LDAYSPERWEEK);
1822                         if (wday < 0)
1823                                 wday += LDAYSPERWEEK;
1824                 }
1825                 while (wday != eitol(rp->r_wday))
1826                         if (rp->r_dycode == DC_DOWGEQ) {
1827                                 dayoff = oadd(dayoff, (long) 1);
1828                                 if (++wday >= LDAYSPERWEEK)
1829                                         wday = 0;
1830                                 ++i;
1831                         } else {
1832                                 dayoff = oadd(dayoff, (long) -1);
1833                                 if (--wday < 0)
1834                                         wday = LDAYSPERWEEK - 1;
1835                                 --i;
1836                         }
1837                 if (i < 0 || i >= len_months[isleap(y)][m]) {
1838                         error("no day in month matches rule");
1839                         (void) exit(EXIT_FAILURE);
1840                 }
1841         }
1842         if (dayoff < 0 && !tt_signed)
1843                 return min_time;
1844         t = (time_t) dayoff * SECSPERDAY;
1845         /*
1846         ** Cheap overflow check.
1847         */
1848         if (t / SECSPERDAY != dayoff)
1849                 return (dayoff > 0) ? max_time : min_time;
1850         return tadd(t, rp->r_tod);
1851 }
1852
1853 static void
1854 newabbr(string)
1855 const char * const      string;
1856 {
1857         register int    i;
1858
1859         i = strlen(string) + 1;
1860         if (charcnt + i > TZ_MAX_CHARS) {
1861                 error("too many, or too long, time zone abbreviations");
1862                 (void) exit(EXIT_FAILURE);
1863         }
1864         (void) strcpy(&chars[charcnt], string);
1865         charcnt += eitol(i);
1866 }
1867
1868 static int
1869 mkdirs(name)
1870 char * const    name;
1871 {
1872         register char * cp;
1873
1874         if ((cp = name) == NULL || *cp == '\0')
1875                 return 0;
1876         while ((cp = strchr(cp + 1, '/')) != 0) {
1877                 *cp = '\0';
1878 #ifndef unix
1879                 /*
1880                 ** MS-DOS drive specifier?
1881                 */
1882                 if (strlen(name) == 2 && isascii(name[0]) &&
1883                         isalpha(name[0]) && name[1] == ':') {
1884                                 *cp = '/';
1885                                 continue;
1886                 }
1887 #endif /* !defined unix */
1888                 if (!itsdir(name)) {
1889                         /*
1890                         ** It doesn't seem to exist, so we try to create it.
1891                         */
1892                         if (emkdir(name, 0755) != 0) {
1893                                 (void) fprintf(stderr,
1894                                         "%s: Can't create directory ",
1895                                         progname);
1896                                 (void) perror(name);
1897                                 return -1;
1898                         }
1899                 }
1900                 *cp = '/';
1901         }
1902         return 0;
1903 }
1904
1905 static long
1906 eitol(i)
1907 const int       i;
1908 {
1909         long    l;
1910
1911         l = i;
1912         if ((i < 0 && l >= 0) || (i == 0 && l != 0) || (i > 0 && l <= 0)) {
1913                 (void) fprintf(stderr,
1914                         "%s: %d did not sign extend correctly\n",
1915                         progname, i);
1916                 (void) exit(EXIT_FAILURE);
1917         }
1918         return l;
1919 }
1920
1921 /*
1922 ** UNIX is a registered trademark of AT&T.
1923 */