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