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