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