add files fom from zcode2012e.tar.gz
[platform/upstream/tzdata.git] / zic.c
1 /*
2 ** This file is in the public domain, so clarified as of
3 ** 2006-07-17 by Arthur David Olson.
4 */
5
6 #include "version.h"
7 #include "private.h"
8 #include "locale.h"
9 #include "tzfile.h"
10
11 #define ZIC_VERSION     '2'
12
13 typedef int_fast64_t    zic_t;
14
15 #ifndef ZIC_MAX_ABBR_LEN_WO_WARN
16 #define ZIC_MAX_ABBR_LEN_WO_WARN        6
17 #endif /* !defined ZIC_MAX_ABBR_LEN_WO_WARN */
18
19 #if HAVE_SYS_STAT_H
20 #include "sys/stat.h"
21 #endif
22 #ifdef S_IRUSR
23 #define MKDIR_UMASK (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
24 #else
25 #define MKDIR_UMASK 0755
26 #endif
27
28 /*
29 ** On some ancient hosts, predicates like `isspace(C)' are defined
30 ** only if isascii(C) || C == EOF. Modern hosts obey the C Standard,
31 ** which says they are defined only if C == ((unsigned char) C) || C == EOF.
32 ** Neither the C Standard nor Posix require that `isascii' exist.
33 ** For portability, we check both ancient and modern requirements.
34 ** If isascii is not defined, the isascii check succeeds trivially.
35 */
36 #include "ctype.h"
37 #ifndef isascii
38 #define isascii(x) 1
39 #endif
40
41 #define OFFSET_STRLEN_MAXIMUM   (7 + INT_STRLEN_MAXIMUM(long))
42 #define RULE_STRLEN_MAXIMUM     8       /* "Mdd.dd.d" */
43
44 #define end(cp) (strchr((cp), '\0'))
45
46 struct rule {
47         const char *    r_filename;
48         int             r_linenum;
49         const char *    r_name;
50
51         int             r_loyear;       /* for example, 1986 */
52         int             r_hiyear;       /* for example, 1986 */
53         const char *    r_yrtype;
54         int             r_lowasnum;
55         int             r_hiwasnum;
56
57         int             r_month;        /* 0..11 */
58
59         int             r_dycode;       /* see below */
60         int             r_dayofmonth;
61         int             r_wday;
62
63         long            r_tod;          /* time from midnight */
64         int             r_todisstd;     /* above is standard time if TRUE */
65                                         /* or wall clock time if FALSE */
66         int             r_todisgmt;     /* above is GMT if TRUE */
67                                         /* or local time if FALSE */
68         long            r_stdoff;       /* offset from standard time */
69         const char *    r_abbrvar;      /* variable part of abbreviation */
70
71         int             r_todo;         /* a rule to do (used in outzone) */
72         zic_t           r_temp;         /* used in outzone */
73 };
74
75 /*
76 **      r_dycode                r_dayofmonth    r_wday
77 */
78
79 #define DC_DOM          0       /* 1..31 */     /* unused */
80 #define DC_DOWGEQ       1       /* 1..31 */     /* 0..6 (Sun..Sat) */
81 #define DC_DOWLEQ       2       /* 1..31 */     /* 0..6 (Sun..Sat) */
82
83 struct zone {
84         const char *    z_filename;
85         int             z_linenum;
86
87         const char *    z_name;
88         long            z_gmtoff;
89         const char *    z_rule;
90         const char *    z_format;
91
92         long            z_stdoff;
93
94         struct rule *   z_rules;
95         int             z_nrules;
96
97         struct rule     z_untilrule;
98         zic_t           z_untiltime;
99 };
100
101 extern int      getopt(int argc, char * const argv[],
102                         const char * options);
103 extern int      link(const char * fromname, const char * toname);
104 extern char *   optarg;
105 extern int      optind;
106
107 static void     addtt(zic_t starttime, int type);
108 static int      addtype(long gmtoff, const char * abbr, int isdst,
109                                 int ttisstd, int ttisgmt);
110 static void     leapadd(zic_t t, int positive, int rolling, int count);
111 static void     adjleap(void);
112 static void     associate(void);
113 static int      ciequal(const char * ap, const char * bp);
114 static void     convert(long val, char * buf);
115 static void     convert64(zic_t val, char * buf);
116 static void     dolink(const char * fromfield, const char * tofield);
117 static void     doabbr(char * abbr, const char * format,
118                         const char * letters, int isdst, int doquotes);
119 static void     eat(const char * name, int num);
120 static void     eats(const char * name, int num,
121                         const char * rname, int rnum);
122 static long     eitol(int i);
123 static void     error(const char * message);
124 static char **  getfields(char * buf);
125 static long     gethms(const char * string, const char * errstrng,
126                         int signable);
127 static void     infile(const char * filename);
128 static void     inleap(char ** fields, int nfields);
129 static void     inlink(char ** fields, int nfields);
130 static void     inrule(char ** fields, int nfields);
131 static int      inzcont(char ** fields, int nfields);
132 static int      inzone(char ** fields, int nfields);
133 static int      inzsub(char ** fields, int nfields, int iscont);
134 static int      is32(zic_t x);
135 static int      itsabbr(const char * abbr, const char * word);
136 static int      itsdir(const char * name);
137 static int      lowerit(int c);
138 static char *   memcheck(char * tocheck);
139 static int      mkdirs(char * filename);
140 static void     newabbr(const char * abbr);
141 static long     oadd(long t1, long t2);
142 static void     outzone(const struct zone * zp, int ntzones);
143 static void     puttzcode(long code, FILE * fp);
144 static void     puttzcode64(zic_t code, FILE * fp);
145 static int      rcomp(const void * leftp, const void * rightp);
146 static zic_t    rpytime(const struct rule * rp, int wantedy);
147 static void     rulesub(struct rule * rp,
148                         const char * loyearp, const char * hiyearp,
149                         const char * typep, const char * monthp,
150                         const char * dayp, const char * timep);
151 static int      stringoffset(char * result, long offset);
152 static int      stringrule(char * result, const struct rule * rp,
153                         long dstoff, long gmtoff);
154 static void     stringzone(char * result,
155                         const struct zone * zp, int ntzones);
156 static void     setboundaries(void);
157 static zic_t    tadd(zic_t t1, long t2);
158 static void     usage(FILE *stream, int status);
159 static void     writezone(const char * name, const char * string);
160 static int      yearistype(int year, const char * type);
161
162 static int              charcnt;
163 static int              errors;
164 static const char *     filename;
165 static int              leapcnt;
166 static int              leapseen;
167 static int              leapminyear;
168 static int              leapmaxyear;
169 static int              linenum;
170 static int              max_abbrvar_len;
171 static int              max_format_len;
172 static zic_t            max_time;
173 static int              max_year;
174 static zic_t            min_time;
175 static int              min_year;
176 static int              noise;
177 static const char *     rfilename;
178 static int              rlinenum;
179 static const char *     progname;
180 static int              timecnt;
181 static int              typecnt;
182
183 /*
184 ** Line codes.
185 */
186
187 #define LC_RULE         0
188 #define LC_ZONE         1
189 #define LC_LINK         2
190 #define LC_LEAP         3
191
192 /*
193 ** Which fields are which on a Zone line.
194 */
195
196 #define ZF_NAME         1
197 #define ZF_GMTOFF       2
198 #define ZF_RULE         3
199 #define ZF_FORMAT       4
200 #define ZF_TILYEAR      5
201 #define ZF_TILMONTH     6
202 #define ZF_TILDAY       7
203 #define ZF_TILTIME      8
204 #define ZONE_MINFIELDS  5
205 #define ZONE_MAXFIELDS  9
206
207 /*
208 ** Which fields are which on a Zone continuation line.
209 */
210
211 #define ZFC_GMTOFF      0
212 #define ZFC_RULE        1
213 #define ZFC_FORMAT      2
214 #define ZFC_TILYEAR     3
215 #define ZFC_TILMONTH    4
216 #define ZFC_TILDAY      5
217 #define ZFC_TILTIME     6
218 #define ZONEC_MINFIELDS 3
219 #define ZONEC_MAXFIELDS 7
220
221 /*
222 ** Which files are which on a Rule line.
223 */
224
225 #define RF_NAME         1
226 #define RF_LOYEAR       2
227 #define RF_HIYEAR       3
228 #define RF_COMMAND      4
229 #define RF_MONTH        5
230 #define RF_DAY          6
231 #define RF_TOD          7
232 #define RF_STDOFF       8
233 #define RF_ABBRVAR      9
234 #define RULE_FIELDS     10
235
236 /*
237 ** Which fields are which on a Link line.
238 */
239
240 #define LF_FROM         1
241 #define LF_TO           2
242 #define LINK_FIELDS     3
243
244 /*
245 ** Which fields are which on a Leap line.
246 */
247
248 #define LP_YEAR         1
249 #define LP_MONTH        2
250 #define LP_DAY          3
251 #define LP_TIME         4
252 #define LP_CORR         5
253 #define LP_ROLL         6
254 #define LEAP_FIELDS     7
255
256 /*
257 ** Year synonyms.
258 */
259
260 #define YR_MINIMUM      0
261 #define YR_MAXIMUM      1
262 #define YR_ONLY         2
263
264 static struct rule *    rules;
265 static int              nrules; /* number of rules */
266
267 static struct zone *    zones;
268 static int              nzones; /* number of zones */
269
270 struct link {
271         const char *    l_filename;
272         int             l_linenum;
273         const char *    l_from;
274         const char *    l_to;
275 };
276
277 static struct link *    links;
278 static int              nlinks;
279
280 struct lookup {
281         const char *    l_word;
282         const int       l_value;
283 };
284
285 static struct lookup const *    byword(const char * string,
286                                         const struct lookup * lp);
287
288 static struct lookup const      line_codes[] = {
289         { "Rule",       LC_RULE },
290         { "Zone",       LC_ZONE },
291         { "Link",       LC_LINK },
292         { "Leap",       LC_LEAP },
293         { NULL,         0}
294 };
295
296 static struct lookup const      mon_names[] = {
297         { "January",    TM_JANUARY },
298         { "February",   TM_FEBRUARY },
299         { "March",      TM_MARCH },
300         { "April",      TM_APRIL },
301         { "May",        TM_MAY },
302         { "June",       TM_JUNE },
303         { "July",       TM_JULY },
304         { "August",     TM_AUGUST },
305         { "September",  TM_SEPTEMBER },
306         { "October",    TM_OCTOBER },
307         { "November",   TM_NOVEMBER },
308         { "December",   TM_DECEMBER },
309         { NULL,         0 }
310 };
311
312 static struct lookup const      wday_names[] = {
313         { "Sunday",     TM_SUNDAY },
314         { "Monday",     TM_MONDAY },
315         { "Tuesday",    TM_TUESDAY },
316         { "Wednesday",  TM_WEDNESDAY },
317         { "Thursday",   TM_THURSDAY },
318         { "Friday",     TM_FRIDAY },
319         { "Saturday",   TM_SATURDAY },
320         { NULL,         0 }
321 };
322
323 static struct lookup const      lasts[] = {
324         { "last-Sunday",        TM_SUNDAY },
325         { "last-Monday",        TM_MONDAY },
326         { "last-Tuesday",       TM_TUESDAY },
327         { "last-Wednesday",     TM_WEDNESDAY },
328         { "last-Thursday",      TM_THURSDAY },
329         { "last-Friday",        TM_FRIDAY },
330         { "last-Saturday",      TM_SATURDAY },
331         { NULL,                 0 }
332 };
333
334 static struct lookup const      begin_years[] = {
335         { "minimum",    YR_MINIMUM },
336         { "maximum",    YR_MAXIMUM },
337         { NULL,         0 }
338 };
339
340 static struct lookup const      end_years[] = {
341         { "minimum",    YR_MINIMUM },
342         { "maximum",    YR_MAXIMUM },
343         { "only",       YR_ONLY },
344         { NULL,         0 }
345 };
346
347 static struct lookup const      leap_types[] = {
348         { "Rolling",    TRUE },
349         { "Stationary", FALSE },
350         { NULL,         0 }
351 };
352
353 static const int        len_months[2][MONSPERYEAR] = {
354         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
355         { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
356 };
357
358 static const int        len_years[2] = {
359         DAYSPERNYEAR, DAYSPERLYEAR
360 };
361
362 static struct attype {
363         zic_t           at;
364         unsigned char   type;
365 }                       attypes[TZ_MAX_TIMES];
366 static long             gmtoffs[TZ_MAX_TYPES];
367 static char             isdsts[TZ_MAX_TYPES];
368 static unsigned char    abbrinds[TZ_MAX_TYPES];
369 static char             ttisstds[TZ_MAX_TYPES];
370 static char             ttisgmts[TZ_MAX_TYPES];
371 static char             chars[TZ_MAX_CHARS];
372 static zic_t            trans[TZ_MAX_LEAPS];
373 static long             corr[TZ_MAX_LEAPS];
374 static char             roll[TZ_MAX_LEAPS];
375
376 /*
377 ** Memory allocation.
378 */
379
380 static char *
381 memcheck(ptr)
382 char * const    ptr;
383 {
384         if (ptr == NULL) {
385                 const char *e = strerror(errno);
386
387                 (void) fprintf(stderr, _("%s: Memory exhausted: %s\n"),
388                         progname, e);
389                 exit(EXIT_FAILURE);
390         }
391         return ptr;
392 }
393
394 #define emalloc(size)           memcheck(imalloc(size))
395 #define erealloc(ptr, size)     memcheck(irealloc((ptr), (size)))
396 #define ecpyalloc(ptr)          memcheck(icpyalloc(ptr))
397 #define ecatalloc(oldp, newp)   memcheck(icatalloc((oldp), (newp)))
398
399 /*
400 ** Error handling.
401 */
402
403 static void
404 eats(name, num, rname, rnum)
405 const char * const      name;
406 const int               num;
407 const char * const      rname;
408 const int               rnum;
409 {
410         filename = name;
411         linenum = num;
412         rfilename = rname;
413         rlinenum = rnum;
414 }
415
416 static void
417 eat(name, num)
418 const char * const      name;
419 const int               num;
420 {
421         eats(name, num, (char *) NULL, -1);
422 }
423
424 static void
425 error(string)
426 const char * const      string;
427 {
428         /*
429         ** Match the format of "cc" to allow sh users to
430         **      zic ... 2>&1 | error -t "*" -v
431         ** on BSD systems.
432         */
433         (void) fprintf(stderr, _("\"%s\", line %d: %s"),
434                 filename, linenum, string);
435         if (rfilename != NULL)
436                 (void) fprintf(stderr, _(" (rule from \"%s\", line %d)"),
437                         rfilename, rlinenum);
438         (void) fprintf(stderr, "\n");
439         ++errors;
440 }
441
442 static void
443 warning(string)
444 const char * const      string;
445 {
446         char *  cp;
447
448         cp = ecpyalloc(_("warning: "));
449         cp = ecatalloc(cp, string);
450         error(cp);
451         ifree(cp);
452         --errors;
453 }
454
455 static void
456 usage(FILE *stream, int status)
457 {
458         (void) fprintf(stream, _("%s: usage is %s \
459 [ --version ] [ --help ] [ -v ] [ -l localtime ] [ -p posixrules ] \\\n\
460 \t[ -d directory ] [ -L leapseconds ] [ -y yearistype ] [ filename ... ]\n\
461 \n\
462 Report bugs to tz@elsie.nci.nih.gov.\n"),
463                        progname, progname);
464         exit(status);
465 }
466
467 static const char *     psxrules;
468 static const char *     lcltime;
469 static const char *     directory;
470 static const char *     leapsec;
471 static const char *     yitcommand;
472
473 int
474 main(argc, argv)
475 int     argc;
476 char *  argv[];
477 {
478         register int    i;
479         register int    j;
480         register int    c;
481
482 #ifdef unix
483         (void) umask(umask(S_IWGRP | S_IWOTH) | (S_IWGRP | S_IWOTH));
484 #endif /* defined unix */
485 #if HAVE_GETTEXT
486         (void) setlocale(LC_ALL, "");
487 #ifdef TZ_DOMAINDIR
488         (void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
489 #endif /* defined TEXTDOMAINDIR */
490         (void) textdomain(TZ_DOMAIN);
491 #endif /* HAVE_GETTEXT */
492         progname = argv[0];
493         if (TYPE_BIT(zic_t) < 64) {
494                 (void) fprintf(stderr, "%s: %s\n", progname,
495                         _("wild compilation-time specification of zic_t"));
496                 exit(EXIT_FAILURE);
497         }
498         for (i = 1; i < argc; ++i)
499                 if (strcmp(argv[i], "--version") == 0) {
500                         (void) printf("%s\n", TZVERSION);
501                         exit(EXIT_SUCCESS);
502                 } else if (strcmp(argv[i], "--help") == 0) {
503                         usage(stdout, EXIT_SUCCESS);
504                 }
505         while ((c = getopt(argc, argv, "d:l:p:L:vsy:")) != EOF && c != -1)
506                 switch (c) {
507                         default:
508                                 usage(stderr, EXIT_FAILURE);
509                         case 'd':
510                                 if (directory == NULL)
511                                         directory = optarg;
512                                 else {
513                                         (void) fprintf(stderr,
514 _("%s: More than one -d option specified\n"),
515                                                 progname);
516                                         exit(EXIT_FAILURE);
517                                 }
518                                 break;
519                         case 'l':
520                                 if (lcltime == NULL)
521                                         lcltime = optarg;
522                                 else {
523                                         (void) fprintf(stderr,
524 _("%s: More than one -l option specified\n"),
525                                                 progname);
526                                         exit(EXIT_FAILURE);
527                                 }
528                                 break;
529                         case 'p':
530                                 if (psxrules == NULL)
531                                         psxrules = optarg;
532                                 else {
533                                         (void) fprintf(stderr,
534 _("%s: More than one -p option specified\n"),
535                                                 progname);
536                                         exit(EXIT_FAILURE);
537                                 }
538                                 break;
539                         case 'y':
540                                 if (yitcommand == NULL)
541                                         yitcommand = optarg;
542                                 else {
543                                         (void) fprintf(stderr,
544 _("%s: More than one -y option specified\n"),
545                                                 progname);
546                                         exit(EXIT_FAILURE);
547                                 }
548                                 break;
549                         case 'L':
550                                 if (leapsec == NULL)
551                                         leapsec = optarg;
552                                 else {
553                                         (void) fprintf(stderr,
554 _("%s: More than one -L option specified\n"),
555                                                 progname);
556                                         exit(EXIT_FAILURE);
557                                 }
558                                 break;
559                         case 'v':
560                                 noise = TRUE;
561                                 break;
562                         case 's':
563                                 (void) printf("%s: -s ignored\n", progname);
564                                 break;
565                 }
566         if (optind == argc - 1 && strcmp(argv[optind], "=") == 0)
567                 usage(stderr, EXIT_FAILURE);    /* usage message by request */
568         if (directory == NULL)
569                 directory = TZDIR;
570         if (yitcommand == NULL)
571                 yitcommand = "yearistype";
572
573         setboundaries();
574
575         if (optind < argc && leapsec != NULL) {
576                 infile(leapsec);
577                 adjleap();
578         }
579
580         for (i = optind; i < argc; ++i)
581                 infile(argv[i]);
582         if (errors)
583                 exit(EXIT_FAILURE);
584         associate();
585         for (i = 0; i < nzones; i = j) {
586                 /*
587                 ** Find the next non-continuation zone entry.
588                 */
589                 for (j = i + 1; j < nzones && zones[j].z_name == NULL; ++j)
590                         continue;
591                 outzone(&zones[i], j - i);
592         }
593         /*
594         ** Make links.
595         */
596         for (i = 0; i < nlinks; ++i) {
597                 eat(links[i].l_filename, links[i].l_linenum);
598                 dolink(links[i].l_from, links[i].l_to);
599                 if (noise)
600                         for (j = 0; j < nlinks; ++j)
601                                 if (strcmp(links[i].l_to,
602                                         links[j].l_from) == 0)
603                                                 warning(_("link to link"));
604         }
605         if (lcltime != NULL) {
606                 eat("command line", 1);
607                 dolink(lcltime, TZDEFAULT);
608         }
609         if (psxrules != NULL) {
610                 eat("command line", 1);
611                 dolink(psxrules, TZDEFRULES);
612         }
613         return (errors == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
614 }
615
616 static void
617 dolink(fromfield, tofield)
618 const char * const      fromfield;
619 const char * const      tofield;
620 {
621         register char * fromname;
622         register char * toname;
623
624         if (fromfield[0] == '/')
625                 fromname = ecpyalloc(fromfield);
626         else {
627                 fromname = ecpyalloc(directory);
628                 fromname = ecatalloc(fromname, "/");
629                 fromname = ecatalloc(fromname, fromfield);
630         }
631         if (tofield[0] == '/')
632                 toname = ecpyalloc(tofield);
633         else {
634                 toname = ecpyalloc(directory);
635                 toname = ecatalloc(toname, "/");
636                 toname = ecatalloc(toname, tofield);
637         }
638         /*
639         ** We get to be careful here since
640         ** there's a fair chance of root running us.
641         */
642         if (!itsdir(toname))
643                 (void) remove(toname);
644         if (link(fromname, toname) != 0) {
645                 int     result;
646
647                 if (mkdirs(toname) != 0)
648                         exit(EXIT_FAILURE);
649
650                 result = link(fromname, toname);
651 #if HAVE_SYMLINK
652                 if (result != 0 &&
653                         access(fromname, F_OK) == 0 &&
654                         !itsdir(fromname)) {
655                                 const char *s = tofield;
656                                 register char * symlinkcontents = NULL;
657
658                                 while ((s = strchr(s+1, '/')) != NULL)
659                                         symlinkcontents =
660                                                 ecatalloc(symlinkcontents,
661                                                 "../");
662                                 symlinkcontents =
663                                         ecatalloc(symlinkcontents,
664                                         fromname);
665                                 result = symlink(symlinkcontents,
666                                         toname);
667                                 if (result == 0)
668 warning(_("hard link failed, symbolic link used"));
669                                 ifree(symlinkcontents);
670                 }
671 #endif /* HAVE_SYMLINK */
672                 if (result != 0) {
673                         const char *e = strerror(errno);
674
675                         (void) fprintf(stderr,
676                                 _("%s: Can't link from %s to %s: %s\n"),
677                                 progname, fromname, toname, e);
678                         exit(EXIT_FAILURE);
679                 }
680         }
681         ifree(fromname);
682         ifree(toname);
683 }
684
685 #define TIME_T_BITS_IN_FILE     64
686
687 static void
688 setboundaries(void)
689 {
690         register int    i;
691
692         min_time = -1;
693         for (i = 0; i < TIME_T_BITS_IN_FILE - 1; ++i)
694                 min_time *= 2;
695         max_time = -(min_time + 1);
696 }
697
698 static int
699 itsdir(name)
700 const char * const      name;
701 {
702         register char * myname;
703         register int    accres;
704
705         myname = ecpyalloc(name);
706         myname = ecatalloc(myname, "/.");
707         accres = access(myname, F_OK);
708         ifree(myname);
709         return accres == 0;
710 }
711
712 /*
713 ** Associate sets of rules with zones.
714 */
715
716 /*
717 ** Sort by rule name.
718 */
719
720 static int
721 rcomp(cp1, cp2)
722 const void *    cp1;
723 const void *    cp2;
724 {
725         return strcmp(((const struct rule *) cp1)->r_name,
726                 ((const struct rule *) cp2)->r_name);
727 }
728
729 static void
730 associate(void)
731 {
732         register struct zone *  zp;
733         register struct rule *  rp;
734         register int            base, out;
735         register int            i, j;
736
737         if (nrules != 0) {
738                 (void) qsort((void *) rules, (size_t) nrules,
739                         (size_t) sizeof *rules, rcomp);
740                 for (i = 0; i < nrules - 1; ++i) {
741                         if (strcmp(rules[i].r_name,
742                                 rules[i + 1].r_name) != 0)
743                                         continue;
744                         if (strcmp(rules[i].r_filename,
745                                 rules[i + 1].r_filename) == 0)
746                                         continue;
747                         eat(rules[i].r_filename, rules[i].r_linenum);
748                         warning(_("same rule name in multiple files"));
749                         eat(rules[i + 1].r_filename, rules[i + 1].r_linenum);
750                         warning(_("same rule name in multiple files"));
751                         for (j = i + 2; j < nrules; ++j) {
752                                 if (strcmp(rules[i].r_name,
753                                         rules[j].r_name) != 0)
754                                                 break;
755                                 if (strcmp(rules[i].r_filename,
756                                         rules[j].r_filename) == 0)
757                                                 continue;
758                                 if (strcmp(rules[i + 1].r_filename,
759                                         rules[j].r_filename) == 0)
760                                                 continue;
761                                 break;
762                         }
763                         i = j - 1;
764                 }
765         }
766         for (i = 0; i < nzones; ++i) {
767                 zp = &zones[i];
768                 zp->z_rules = NULL;
769                 zp->z_nrules = 0;
770         }
771         for (base = 0; base < nrules; base = out) {
772                 rp = &rules[base];
773                 for (out = base + 1; out < nrules; ++out)
774                         if (strcmp(rp->r_name, rules[out].r_name) != 0)
775                                 break;
776                 for (i = 0; i < nzones; ++i) {
777                         zp = &zones[i];
778                         if (strcmp(zp->z_rule, rp->r_name) != 0)
779                                 continue;
780                         zp->z_rules = rp;
781                         zp->z_nrules = out - base;
782                 }
783         }
784         for (i = 0; i < nzones; ++i) {
785                 zp = &zones[i];
786                 if (zp->z_nrules == 0) {
787                         /*
788                         ** Maybe we have a local standard time offset.
789                         */
790                         eat(zp->z_filename, zp->z_linenum);
791                         zp->z_stdoff = gethms(zp->z_rule, _("unruly zone"),
792                                 TRUE);
793                         /*
794                         ** Note, though, that if there's no rule,
795                         ** a '%s' in the format is a bad thing.
796                         */
797                         if (strchr(zp->z_format, '%') != 0)
798                                 error(_("%s in ruleless zone"));
799                 }
800         }
801         if (errors)
802                 exit(EXIT_FAILURE);
803 }
804
805 static void
806 infile(name)
807 const char *    name;
808 {
809         register FILE *                 fp;
810         register char **                fields;
811         register char *                 cp;
812         register const struct lookup *  lp;
813         register int                    nfields;
814         register int                    wantcont;
815         register int                    num;
816         char                            buf[BUFSIZ];
817
818         if (strcmp(name, "-") == 0) {
819                 name = _("standard input");
820                 fp = stdin;
821         } else if ((fp = fopen(name, "r")) == NULL) {
822                 const char *e = strerror(errno);
823
824                 (void) fprintf(stderr, _("%s: Can't open %s: %s\n"),
825                         progname, name, e);
826                 exit(EXIT_FAILURE);
827         }
828         wantcont = FALSE;
829         for (num = 1; ; ++num) {
830                 eat(name, num);
831                 if (fgets(buf, (int) sizeof buf, fp) != buf)
832                         break;
833                 cp = strchr(buf, '\n');
834                 if (cp == NULL) {
835                         error(_("line too long"));
836                         exit(EXIT_FAILURE);
837                 }
838                 *cp = '\0';
839                 fields = getfields(buf);
840                 nfields = 0;
841                 while (fields[nfields] != NULL) {
842                         static char     nada;
843
844                         if (strcmp(fields[nfields], "-") == 0)
845                                 fields[nfields] = &nada;
846                         ++nfields;
847                 }
848                 if (nfields == 0) {
849                         /* nothing to do */
850                 } else if (wantcont) {
851                         wantcont = inzcont(fields, nfields);
852                 } else {
853                         lp = byword(fields[0], line_codes);
854                         if (lp == NULL)
855                                 error(_("input line of unknown type"));
856                         else switch ((int) (lp->l_value)) {
857                                 case LC_RULE:
858                                         inrule(fields, nfields);
859                                         wantcont = FALSE;
860                                         break;
861                                 case LC_ZONE:
862                                         wantcont = inzone(fields, nfields);
863                                         break;
864                                 case LC_LINK:
865                                         inlink(fields, nfields);
866                                         wantcont = FALSE;
867                                         break;
868                                 case LC_LEAP:
869                                         if (name != leapsec)
870                                                 (void) fprintf(stderr,
871 _("%s: Leap line in non leap seconds file %s\n"),
872                                                         progname, name);
873                                         else    inleap(fields, nfields);
874                                         wantcont = FALSE;
875                                         break;
876                                 default:        /* "cannot happen" */
877                                         (void) fprintf(stderr,
878 _("%s: panic: Invalid l_value %d\n"),
879                                                 progname, lp->l_value);
880                                         exit(EXIT_FAILURE);
881                         }
882                 }
883                 ifree((char *) fields);
884         }
885         if (ferror(fp)) {
886                 (void) fprintf(stderr, _("%s: Error reading %s\n"),
887                         progname, filename);
888                 exit(EXIT_FAILURE);
889         }
890         if (fp != stdin && fclose(fp)) {
891                 const char *e = strerror(errno);
892
893                 (void) fprintf(stderr, _("%s: Error closing %s: %s\n"),
894                         progname, filename, e);
895                 exit(EXIT_FAILURE);
896         }
897         if (wantcont)
898                 error(_("expected continuation line not found"));
899 }
900
901 /*
902 ** Convert a string of one of the forms
903 **      h       -h      hh:mm   -hh:mm  hh:mm:ss        -hh:mm:ss
904 ** into a number of seconds.
905 ** A null string maps to zero.
906 ** Call error with errstring and return zero on errors.
907 */
908
909 static long
910 gethms(string, errstring, signable)
911 const char *            string;
912 const char * const      errstring;
913 const int               signable;
914 {
915         long    hh;
916         int     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, "%ld"), &hh) == 1)
927                 mm = ss = 0;
928         else if (sscanf(string, scheck(string, "%ld:%d"), &hh, &mm) == 2)
929                 ss = 0;
930         else if (sscanf(string, scheck(string, "%ld:%d:%d"),
931                 &hh, &mm, &ss) != 3) {
932                         error(errstring);
933                         return 0;
934         }
935         if (hh < 0 ||
936                 mm < 0 || mm >= MINSPERHOUR ||
937                 ss < 0 || ss > SECSPERMIN) {
938                         error(errstring);
939                         return 0;
940         }
941         if (LONG_MAX / SECSPERHOUR < hh) {
942                 error(_("time overflow"));
943                 return 0;
944         }
945         if (noise && hh == HOURSPERDAY && mm == 0 && ss == 0)
946                 warning(_("24:00 not handled by pre-1998 versions of zic"));
947         if (noise && (hh > HOURSPERDAY ||
948                 (hh == HOURSPERDAY && (mm != 0 || ss != 0))))
949 warning(_("values over 24 hours not handled by pre-2007 versions of zic"));
950         return oadd(eitol(sign) * hh * eitol(SECSPERHOUR),
951                     eitol(sign) * (eitol(mm) * eitol(SECSPERMIN) + eitol(ss)));
952 }
953
954 static void
955 inrule(fields, nfields)
956 register char ** const  fields;
957 const int               nfields;
958 {
959         static struct rule      r;
960
961         if (nfields != RULE_FIELDS) {
962                 error(_("wrong number of fields on Rule line"));
963                 return;
964         }
965         if (*fields[RF_NAME] == '\0') {
966                 error(_("nameless rule"));
967                 return;
968         }
969         r.r_filename = filename;
970         r.r_linenum = linenum;
971         r.r_stdoff = gethms(fields[RF_STDOFF], _("invalid saved time"), TRUE);
972         rulesub(&r, fields[RF_LOYEAR], fields[RF_HIYEAR], fields[RF_COMMAND],
973                 fields[RF_MONTH], fields[RF_DAY], fields[RF_TOD]);
974         r.r_name = ecpyalloc(fields[RF_NAME]);
975         r.r_abbrvar = ecpyalloc(fields[RF_ABBRVAR]);
976         if (max_abbrvar_len < strlen(r.r_abbrvar))
977                 max_abbrvar_len = strlen(r.r_abbrvar);
978         rules = (struct rule *) (void *) erealloc((char *) rules,
979                 (int) ((nrules + 1) * sizeof *rules));
980         rules[nrules++] = r;
981 }
982
983 static int
984 inzone(fields, nfields)
985 register char ** const  fields;
986 const int               nfields;
987 {
988         register int    i;
989         static char *   buf;
990
991         if (nfields < ZONE_MINFIELDS || nfields > ZONE_MAXFIELDS) {
992                 error(_("wrong number of fields on Zone line"));
993                 return FALSE;
994         }
995         if (strcmp(fields[ZF_NAME], TZDEFAULT) == 0 && lcltime != NULL) {
996                 buf = erealloc(buf, (int) (132 + strlen(TZDEFAULT)));
997                 (void) sprintf(buf,
998 _("\"Zone %s\" line and -l option are mutually exclusive"),
999                         TZDEFAULT);
1000                 error(buf);
1001                 return FALSE;
1002         }
1003         if (strcmp(fields[ZF_NAME], TZDEFRULES) == 0 && psxrules != NULL) {
1004                 buf = erealloc(buf, (int) (132 + strlen(TZDEFRULES)));
1005                 (void) sprintf(buf,
1006 _("\"Zone %s\" line and -p option are mutually exclusive"),
1007                         TZDEFRULES);
1008                 error(buf);
1009                 return FALSE;
1010         }
1011         for (i = 0; i < nzones; ++i)
1012                 if (zones[i].z_name != NULL &&
1013                         strcmp(zones[i].z_name, fields[ZF_NAME]) == 0) {
1014                                 buf = erealloc(buf, (int) (132 +
1015                                         strlen(fields[ZF_NAME]) +
1016                                         strlen(zones[i].z_filename)));
1017                                 (void) sprintf(buf,
1018 _("duplicate zone name %s (file \"%s\", line %d)"),
1019                                         fields[ZF_NAME],
1020                                         zones[i].z_filename,
1021                                         zones[i].z_linenum);
1022                                 error(buf);
1023                                 return FALSE;
1024                 }
1025         return inzsub(fields, nfields, FALSE);
1026 }
1027
1028 static int
1029 inzcont(fields, nfields)
1030 register char ** const  fields;
1031 const int               nfields;
1032 {
1033         if (nfields < ZONEC_MINFIELDS || nfields > ZONEC_MAXFIELDS) {
1034                 error(_("wrong number of fields on Zone continuation line"));
1035                 return FALSE;
1036         }
1037         return inzsub(fields, nfields, TRUE);
1038 }
1039
1040 static int
1041 inzsub(fields, nfields, iscont)
1042 register char ** const  fields;
1043 const int               nfields;
1044 const int               iscont;
1045 {
1046         register char *         cp;
1047         static struct zone      z;
1048         register int            i_gmtoff, i_rule, i_format;
1049         register int            i_untilyear, i_untilmonth;
1050         register int            i_untilday, i_untiltime;
1051         register int            hasuntil;
1052
1053         if (iscont) {
1054                 i_gmtoff = ZFC_GMTOFF;
1055                 i_rule = ZFC_RULE;
1056                 i_format = ZFC_FORMAT;
1057                 i_untilyear = ZFC_TILYEAR;
1058                 i_untilmonth = ZFC_TILMONTH;
1059                 i_untilday = ZFC_TILDAY;
1060                 i_untiltime = ZFC_TILTIME;
1061                 z.z_name = NULL;
1062         } else {
1063                 i_gmtoff = ZF_GMTOFF;
1064                 i_rule = ZF_RULE;
1065                 i_format = ZF_FORMAT;
1066                 i_untilyear = ZF_TILYEAR;
1067                 i_untilmonth = ZF_TILMONTH;
1068                 i_untilday = ZF_TILDAY;
1069                 i_untiltime = ZF_TILTIME;
1070                 z.z_name = ecpyalloc(fields[ZF_NAME]);
1071         }
1072         z.z_filename = filename;
1073         z.z_linenum = linenum;
1074         z.z_gmtoff = gethms(fields[i_gmtoff], _("invalid UTC offset"), TRUE);
1075         if ((cp = strchr(fields[i_format], '%')) != 0) {
1076                 if (*++cp != 's' || strchr(cp, '%') != 0) {
1077                         error(_("invalid abbreviation format"));
1078                         return FALSE;
1079                 }
1080         }
1081         z.z_rule = ecpyalloc(fields[i_rule]);
1082         z.z_format = ecpyalloc(fields[i_format]);
1083         if (max_format_len < strlen(z.z_format))
1084                 max_format_len = strlen(z.z_format);
1085         hasuntil = nfields > i_untilyear;
1086         if (hasuntil) {
1087                 z.z_untilrule.r_filename = filename;
1088                 z.z_untilrule.r_linenum = linenum;
1089                 rulesub(&z.z_untilrule,
1090                         fields[i_untilyear],
1091                         "only",
1092                         "",
1093                         (nfields > i_untilmonth) ?
1094                         fields[i_untilmonth] : "Jan",
1095                         (nfields > i_untilday) ? fields[i_untilday] : "1",
1096                         (nfields > i_untiltime) ? fields[i_untiltime] : "0");
1097                 z.z_untiltime = rpytime(&z.z_untilrule,
1098                         z.z_untilrule.r_loyear);
1099                 if (iscont && nzones > 0 &&
1100                         z.z_untiltime > min_time &&
1101                         z.z_untiltime < max_time &&
1102                         zones[nzones - 1].z_untiltime > min_time &&
1103                         zones[nzones - 1].z_untiltime < max_time &&
1104                         zones[nzones - 1].z_untiltime >= z.z_untiltime) {
1105                                 error(_(
1106 "Zone continuation line end time is not after end time of previous line"
1107                                         ));
1108                                 return FALSE;
1109                 }
1110         }
1111         zones = (struct zone *) (void *) erealloc((char *) zones,
1112                 (int) ((nzones + 1) * sizeof *zones));
1113         zones[nzones++] = z;
1114         /*
1115         ** If there was an UNTIL field on this line,
1116         ** there's more information about the zone on the next line.
1117         */
1118         return hasuntil;
1119 }
1120
1121 static void
1122 inleap(fields, nfields)
1123 register char ** const  fields;
1124 const int               nfields;
1125 {
1126         register const char *           cp;
1127         register const struct lookup *  lp;
1128         register int                    i, j;
1129         int                             year, month, day;
1130         long                            dayoff, tod;
1131         zic_t                           t;
1132
1133         if (nfields != LEAP_FIELDS) {
1134                 error(_("wrong number of fields on Leap line"));
1135                 return;
1136         }
1137         dayoff = 0;
1138         cp = fields[LP_YEAR];
1139         if (sscanf(cp, scheck(cp, "%d"), &year) != 1) {
1140                 /*
1141                 ** Leapin' Lizards!
1142                 */
1143                 error(_("invalid leaping year"));
1144                 return;
1145         }
1146         if (!leapseen || leapmaxyear < year)
1147                 leapmaxyear = year;
1148         if (!leapseen || leapminyear > year)
1149                 leapminyear = year;
1150         leapseen = TRUE;
1151         j = EPOCH_YEAR;
1152         while (j != year) {
1153                 if (year > j) {
1154                         i = len_years[isleap(j)];
1155                         ++j;
1156                 } else {
1157                         --j;
1158                         i = -len_years[isleap(j)];
1159                 }
1160                 dayoff = oadd(dayoff, eitol(i));
1161         }
1162         if ((lp = byword(fields[LP_MONTH], mon_names)) == NULL) {
1163                 error(_("invalid month name"));
1164                 return;
1165         }
1166         month = lp->l_value;
1167         j = TM_JANUARY;
1168         while (j != month) {
1169                 i = len_months[isleap(year)][j];
1170                 dayoff = oadd(dayoff, eitol(i));
1171                 ++j;
1172         }
1173         cp = fields[LP_DAY];
1174         if (sscanf(cp, scheck(cp, "%d"), &day) != 1 ||
1175                 day <= 0 || day > len_months[isleap(year)][month]) {
1176                         error(_("invalid day of month"));
1177                         return;
1178         }
1179         dayoff = oadd(dayoff, eitol(day - 1));
1180         if (dayoff < 0 && !TYPE_SIGNED(zic_t)) {
1181                 error(_("time before zero"));
1182                 return;
1183         }
1184         if (dayoff < min_time / SECSPERDAY) {
1185                 error(_("time too small"));
1186                 return;
1187         }
1188         if (dayoff > max_time / SECSPERDAY) {
1189                 error(_("time too large"));
1190                 return;
1191         }
1192         t = (zic_t) dayoff * SECSPERDAY;
1193         tod = gethms(fields[LP_TIME], _("invalid time of day"), FALSE);
1194         cp = fields[LP_CORR];
1195         {
1196                 register int    positive;
1197                 int             count;
1198
1199                 if (strcmp(cp, "") == 0) { /* infile() turns "-" into "" */
1200                         positive = FALSE;
1201                         count = 1;
1202                 } else if (strcmp(cp, "--") == 0) {
1203                         positive = FALSE;
1204                         count = 2;
1205                 } else if (strcmp(cp, "+") == 0) {
1206                         positive = TRUE;
1207                         count = 1;
1208                 } else if (strcmp(cp, "++") == 0) {
1209                         positive = TRUE;
1210                         count = 2;
1211                 } else {
1212                         error(_("illegal CORRECTION field on Leap line"));
1213                         return;
1214                 }
1215                 if ((lp = byword(fields[LP_ROLL], leap_types)) == NULL) {
1216                         error(_(
1217                                 "illegal Rolling/Stationary field on Leap line"
1218                                 ));
1219                         return;
1220                 }
1221                 leapadd(tadd(t, tod), positive, lp->l_value, count);
1222         }
1223 }
1224
1225 static void
1226 inlink(fields, nfields)
1227 register char ** const  fields;
1228 const int               nfields;
1229 {
1230         struct link     l;
1231
1232         if (nfields != LINK_FIELDS) {
1233                 error(_("wrong number of fields on Link line"));
1234                 return;
1235         }
1236         if (*fields[LF_FROM] == '\0') {
1237                 error(_("blank FROM field on Link line"));
1238                 return;
1239         }
1240         if (*fields[LF_TO] == '\0') {
1241                 error(_("blank TO field on Link line"));
1242                 return;
1243         }
1244         l.l_filename = filename;
1245         l.l_linenum = linenum;
1246         l.l_from = ecpyalloc(fields[LF_FROM]);
1247         l.l_to = ecpyalloc(fields[LF_TO]);
1248         links = (struct link *) (void *) erealloc((char *) links,
1249                 (int) ((nlinks + 1) * sizeof *links));
1250         links[nlinks++] = l;
1251 }
1252
1253 static void
1254 rulesub(rp, loyearp, hiyearp, typep, monthp, dayp, timep)
1255 register struct rule * const    rp;
1256 const char * const              loyearp;
1257 const char * const              hiyearp;
1258 const char * const              typep;
1259 const char * const              monthp;
1260 const char * const              dayp;
1261 const char * const              timep;
1262 {
1263         register const struct lookup *  lp;
1264         register const char *           cp;
1265         register char *                 dp;
1266         register char *                 ep;
1267
1268         if ((lp = byword(monthp, mon_names)) == NULL) {
1269                 error(_("invalid month name"));
1270                 return;
1271         }
1272         rp->r_month = lp->l_value;
1273         rp->r_todisstd = FALSE;
1274         rp->r_todisgmt = FALSE;
1275         dp = ecpyalloc(timep);
1276         if (*dp != '\0') {
1277                 ep = dp + strlen(dp) - 1;
1278                 switch (lowerit(*ep)) {
1279                         case 's':       /* Standard */
1280                                 rp->r_todisstd = TRUE;
1281                                 rp->r_todisgmt = FALSE;
1282                                 *ep = '\0';
1283                                 break;
1284                         case 'w':       /* Wall */
1285                                 rp->r_todisstd = FALSE;
1286                                 rp->r_todisgmt = FALSE;
1287                                 *ep = '\0';
1288                                 break;
1289                         case 'g':       /* Greenwich */
1290                         case 'u':       /* Universal */
1291                         case 'z':       /* Zulu */
1292                                 rp->r_todisstd = TRUE;
1293                                 rp->r_todisgmt = TRUE;
1294                                 *ep = '\0';
1295                                 break;
1296                 }
1297         }
1298         rp->r_tod = gethms(dp, _("invalid time of day"), FALSE);
1299         ifree(dp);
1300         /*
1301         ** Year work.
1302         */
1303         cp = loyearp;
1304         lp = byword(cp, begin_years);
1305         rp->r_lowasnum = lp == NULL;
1306         if (!rp->r_lowasnum) switch ((int) lp->l_value) {
1307                 case YR_MINIMUM:
1308                         rp->r_loyear = INT_MIN;
1309                         break;
1310                 case YR_MAXIMUM:
1311                         rp->r_loyear = INT_MAX;
1312                         break;
1313                 default:        /* "cannot happen" */
1314                         (void) fprintf(stderr,
1315                                 _("%s: panic: Invalid l_value %d\n"),
1316                                 progname, lp->l_value);
1317                         exit(EXIT_FAILURE);
1318         } else if (sscanf(cp, scheck(cp, "%d"), &rp->r_loyear) != 1) {
1319                 error(_("invalid starting year"));
1320                 return;
1321         }
1322         cp = hiyearp;
1323         lp = byword(cp, end_years);
1324         rp->r_hiwasnum = lp == NULL;
1325         if (!rp->r_hiwasnum) switch ((int) lp->l_value) {
1326                 case YR_MINIMUM:
1327                         rp->r_hiyear = INT_MIN;
1328                         break;
1329                 case YR_MAXIMUM:
1330                         rp->r_hiyear = INT_MAX;
1331                         break;
1332                 case YR_ONLY:
1333                         rp->r_hiyear = rp->r_loyear;
1334                         break;
1335                 default:        /* "cannot happen" */
1336                         (void) fprintf(stderr,
1337                                 _("%s: panic: Invalid l_value %d\n"),
1338                                 progname, lp->l_value);
1339                         exit(EXIT_FAILURE);
1340         } else if (sscanf(cp, scheck(cp, "%d"), &rp->r_hiyear) != 1) {
1341                 error(_("invalid ending year"));
1342                 return;
1343         }
1344         if (rp->r_loyear > rp->r_hiyear) {
1345                 error(_("starting year greater than ending year"));
1346                 return;
1347         }
1348         if (*typep == '\0')
1349                 rp->r_yrtype = NULL;
1350         else {
1351                 if (rp->r_loyear == rp->r_hiyear) {
1352                         error(_("typed single year"));
1353                         return;
1354                 }
1355                 rp->r_yrtype = ecpyalloc(typep);
1356         }
1357         /*
1358         ** Day work.
1359         ** Accept things such as:
1360         **      1
1361         **      last-Sunday
1362         **      Sun<=20
1363         **      Sun>=7
1364         */
1365         dp = ecpyalloc(dayp);
1366         if ((lp = byword(dp, lasts)) != NULL) {
1367                 rp->r_dycode = DC_DOWLEQ;
1368                 rp->r_wday = lp->l_value;
1369                 rp->r_dayofmonth = len_months[1][rp->r_month];
1370         } else {
1371                 if ((ep = strchr(dp, '<')) != 0)
1372                         rp->r_dycode = DC_DOWLEQ;
1373                 else if ((ep = strchr(dp, '>')) != 0)
1374                         rp->r_dycode = DC_DOWGEQ;
1375                 else {
1376                         ep = dp;
1377                         rp->r_dycode = DC_DOM;
1378                 }
1379                 if (rp->r_dycode != DC_DOM) {
1380                         *ep++ = 0;
1381                         if (*ep++ != '=') {
1382                                 error(_("invalid day of month"));
1383                                 ifree(dp);
1384                                 return;
1385                         }
1386                         if ((lp = byword(dp, wday_names)) == NULL) {
1387                                 error(_("invalid weekday name"));
1388                                 ifree(dp);
1389                                 return;
1390                         }
1391                         rp->r_wday = lp->l_value;
1392                 }
1393                 if (sscanf(ep, scheck(ep, "%d"), &rp->r_dayofmonth) != 1 ||
1394                         rp->r_dayofmonth <= 0 ||
1395                         (rp->r_dayofmonth > len_months[1][rp->r_month])) {
1396                                 error(_("invalid day of month"));
1397                                 ifree(dp);
1398                                 return;
1399                 }
1400         }
1401         ifree(dp);
1402 }
1403
1404 static void
1405 convert(val, buf)
1406 const long      val;
1407 char * const    buf;
1408 {
1409         register int    i;
1410         register int    shift;
1411
1412         for (i = 0, shift = 24; i < 4; ++i, shift -= 8)
1413                 buf[i] = val >> shift;
1414 }
1415
1416 static void
1417 convert64(val, buf)
1418 const zic_t     val;
1419 char * const    buf;
1420 {
1421         register int    i;
1422         register int    shift;
1423
1424         for (i = 0, shift = 56; i < 8; ++i, shift -= 8)
1425                 buf[i] = val >> shift;
1426 }
1427
1428 static void
1429 puttzcode(val, fp)
1430 const long      val;
1431 FILE * const    fp;
1432 {
1433         char    buf[4];
1434
1435         convert(val, buf);
1436         (void) fwrite((void *) buf, (size_t) sizeof buf, (size_t) 1, fp);
1437 }
1438
1439 static void
1440 puttzcode64(val, fp)
1441 const zic_t     val;
1442 FILE * const    fp;
1443 {
1444         char    buf[8];
1445
1446         convert64(val, buf);
1447         (void) fwrite((void *) buf, (size_t) sizeof buf, (size_t) 1, fp);
1448 }
1449
1450 static int
1451 atcomp(avp, bvp)
1452 const void *    avp;
1453 const void *    bvp;
1454 {
1455         const zic_t     a = ((const struct attype *) avp)->at;
1456         const zic_t     b = ((const struct attype *) bvp)->at;
1457
1458         return (a < b) ? -1 : (a > b);
1459 }
1460
1461 static int
1462 is32(x)
1463 const zic_t     x;
1464 {
1465         return INT32_MIN <= x && x <= INT32_MAX;
1466 }
1467
1468 static void
1469 writezone(name, string)
1470 const char * const      name;
1471 const char * const      string;
1472 {
1473         register FILE *                 fp;
1474         register int                    i, j;
1475         register int                    leapcnt32, leapi32;
1476         register int                    timecnt32, timei32;
1477         register int                    pass;
1478         static char *                   fullname;
1479         static const struct tzhead      tzh0;
1480         static struct tzhead            tzh;
1481         zic_t                           ats[TZ_MAX_TIMES];
1482         unsigned char                   types[TZ_MAX_TIMES];
1483
1484         /*
1485         ** Sort.
1486         */
1487         if (timecnt > 1)
1488                 (void) qsort((void *) attypes, (size_t) timecnt,
1489                         (size_t) sizeof *attypes, atcomp);
1490         /*
1491         ** Optimize.
1492         */
1493         {
1494                 int     fromi;
1495                 int     toi;
1496
1497                 toi = 0;
1498                 fromi = 0;
1499                 while (fromi < timecnt && attypes[fromi].at < min_time)
1500                         ++fromi;
1501                 if (isdsts[0] == 0)
1502                         while (fromi < timecnt && attypes[fromi].type == 0)
1503                                 ++fromi;        /* handled by default rule */
1504                 for ( ; fromi < timecnt; ++fromi) {
1505                         if (toi != 0 && ((attypes[fromi].at +
1506                                 gmtoffs[attypes[toi - 1].type]) <=
1507                                 (attypes[toi - 1].at + gmtoffs[toi == 1 ? 0
1508                                 : attypes[toi - 2].type]))) {
1509                                         attypes[toi - 1].type =
1510                                                 attypes[fromi].type;
1511                                         continue;
1512                         }
1513                         if (toi == 0 ||
1514                                 attypes[toi - 1].type != attypes[fromi].type)
1515                                         attypes[toi++] = attypes[fromi];
1516                 }
1517                 timecnt = toi;
1518         }
1519         /*
1520         ** Transfer.
1521         */
1522         for (i = 0; i < timecnt; ++i) {
1523                 ats[i] = attypes[i].at;
1524                 types[i] = attypes[i].type;
1525         }
1526         /*
1527         ** Correct for leap seconds.
1528         */
1529         for (i = 0; i < timecnt; ++i) {
1530                 j = leapcnt;
1531                 while (--j >= 0)
1532                         if (ats[i] > trans[j] - corr[j]) {
1533                                 ats[i] = tadd(ats[i], corr[j]);
1534                                 break;
1535                         }
1536         }
1537         /*
1538         ** Figure out 32-bit-limited starts and counts.
1539         */
1540         timecnt32 = timecnt;
1541         timei32 = 0;
1542         leapcnt32 = leapcnt;
1543         leapi32 = 0;
1544         while (timecnt32 > 0 && !is32(ats[timecnt32 - 1]))
1545                 --timecnt32;
1546         while (timecnt32 > 0 && !is32(ats[timei32])) {
1547                 --timecnt32;
1548                 ++timei32;
1549         }
1550         while (leapcnt32 > 0 && !is32(trans[leapcnt32 - 1]))
1551                 --leapcnt32;
1552         while (leapcnt32 > 0 && !is32(trans[leapi32])) {
1553                 --leapcnt32;
1554                 ++leapi32;
1555         }
1556         fullname = erealloc(fullname,
1557                 (int) (strlen(directory) + 1 + strlen(name) + 1));
1558         (void) sprintf(fullname, "%s/%s", directory, name);
1559         /*
1560         ** Remove old file, if any, to snap links.
1561         */
1562         if (!itsdir(fullname) && remove(fullname) != 0 && errno != ENOENT) {
1563                 const char *e = strerror(errno);
1564
1565                 (void) fprintf(stderr, _("%s: Can't remove %s: %s\n"),
1566                         progname, fullname, e);
1567                 exit(EXIT_FAILURE);
1568         }
1569         if ((fp = fopen(fullname, "wb")) == NULL) {
1570                 if (mkdirs(fullname) != 0)
1571                         exit(EXIT_FAILURE);
1572                 if ((fp = fopen(fullname, "wb")) == NULL) {
1573                         const char *e = strerror(errno);
1574
1575                         (void) fprintf(stderr, _("%s: Can't create %s: %s\n"),
1576                                 progname, fullname, e);
1577                         exit(EXIT_FAILURE);
1578                 }
1579         }
1580         for (pass = 1; pass <= 2; ++pass) {
1581                 register int    thistimei, thistimecnt;
1582                 register int    thisleapi, thisleapcnt;
1583                 register int    thistimelim, thisleaplim;
1584                 int             writetype[TZ_MAX_TIMES];
1585                 int             typemap[TZ_MAX_TYPES];
1586                 register int    thistypecnt;
1587                 char            thischars[TZ_MAX_CHARS];
1588                 char            thischarcnt;
1589                 int             indmap[TZ_MAX_CHARS];
1590
1591                 if (pass == 1) {
1592                         thistimei = timei32;
1593                         thistimecnt = timecnt32;
1594                         thisleapi = leapi32;
1595                         thisleapcnt = leapcnt32;
1596                 } else {
1597                         thistimei = 0;
1598                         thistimecnt = timecnt;
1599                         thisleapi = 0;
1600                         thisleapcnt = leapcnt;
1601                 }
1602                 thistimelim = thistimei + thistimecnt;
1603                 thisleaplim = thisleapi + thisleapcnt;
1604                 for (i = 0; i < typecnt; ++i)
1605                         writetype[i] = thistimecnt == timecnt;
1606                 if (thistimecnt == 0) {
1607                         /*
1608                         ** No transition times fall in the current
1609                         ** (32- or 64-bit) window.
1610                         */
1611                         if (typecnt != 0)
1612                                 writetype[typecnt - 1] = TRUE;
1613                 } else {
1614                         for (i = thistimei - 1; i < thistimelim; ++i)
1615                                 if (i >= 0)
1616                                         writetype[types[i]] = TRUE;
1617                         /*
1618                         ** For America/Godthab and Antarctica/Palmer
1619                         */
1620                         if (thistimei == 0)
1621                                 writetype[0] = TRUE;
1622                 }
1623 #ifndef LEAVE_SOME_PRE_2011_SYSTEMS_IN_THE_LURCH
1624                 /*
1625                 ** For some pre-2011 systems: if the last-to-be-written
1626                 ** standard (or daylight) type has an offset different from the
1627                 ** most recently used offset,
1628                 ** append an (unused) copy of the most recently used type
1629                 ** (to help get global "altzone" and "timezone" variables
1630                 ** set correctly).
1631                 */
1632                 {
1633                         register int    mrudst, mrustd, hidst, histd, type;
1634
1635                         hidst = histd = mrudst = mrustd = -1;
1636                         for (i = thistimei; i < thistimelim; ++i)
1637                                 if (isdsts[types[i]])
1638                                         mrudst = types[i];
1639                                 else    mrustd = types[i];
1640                         for (i = 0; i < typecnt; ++i)
1641                                 if (writetype[i]) {
1642                                         if (isdsts[i])
1643                                                 hidst = i;
1644                                         else    histd = i;
1645                                 }
1646                         if (hidst >= 0 && mrudst >= 0 && hidst != mrudst &&
1647                                 gmtoffs[hidst] != gmtoffs[mrudst]) {
1648                                         isdsts[mrudst] = -1;
1649                                         type = addtype(gmtoffs[mrudst],
1650                                                 &chars[abbrinds[mrudst]],
1651                                                 TRUE,
1652                                                 ttisstds[mrudst],
1653                                                 ttisgmts[mrudst]);
1654                                         isdsts[mrudst] = TRUE;
1655                                         writetype[type] = TRUE;
1656                         }
1657                         if (histd >= 0 && mrustd >= 0 && histd != mrustd &&
1658                                 gmtoffs[histd] != gmtoffs[mrustd]) {
1659                                         isdsts[mrustd] = -1;
1660                                         type = addtype(gmtoffs[mrustd],
1661                                                 &chars[abbrinds[mrustd]],
1662                                                 FALSE,
1663                                                 ttisstds[mrustd],
1664                                                 ttisgmts[mrustd]);
1665                                         isdsts[mrustd] = FALSE;
1666                                         writetype[type] = TRUE;
1667                         }
1668                 }
1669 #endif /* !defined LEAVE_SOME_PRE_2011_SYSTEMS_IN_THE_LURCH */
1670                 thistypecnt = 0;
1671                 for (i = 0; i < typecnt; ++i)
1672                         typemap[i] = writetype[i] ?  thistypecnt++ : -1;
1673                 for (i = 0; i < sizeof indmap / sizeof indmap[0]; ++i)
1674                         indmap[i] = -1;
1675                 thischarcnt = 0;
1676                 for (i = 0; i < typecnt; ++i) {
1677                         register char * thisabbr;
1678
1679                         if (!writetype[i])
1680                                 continue;
1681                         if (indmap[abbrinds[i]] >= 0)
1682                                 continue;
1683                         thisabbr = &chars[abbrinds[i]];
1684                         for (j = 0; j < thischarcnt; ++j)
1685                                 if (strcmp(&thischars[j], thisabbr) == 0)
1686                                         break;
1687                         if (j == thischarcnt) {
1688                                 (void) strcpy(&thischars[(int) thischarcnt],
1689                                         thisabbr);
1690                                 thischarcnt += strlen(thisabbr) + 1;
1691                         }
1692                         indmap[abbrinds[i]] = j;
1693                 }
1694 #define DO(field)       (void) fwrite((void *) tzh.field, \
1695                                 (size_t) sizeof tzh.field, (size_t) 1, fp)
1696                 tzh = tzh0;
1697                 (void) strncpy(tzh.tzh_magic, TZ_MAGIC, sizeof tzh.tzh_magic);
1698                 tzh.tzh_version[0] = ZIC_VERSION;
1699                 convert(eitol(thistypecnt), tzh.tzh_ttisgmtcnt);
1700                 convert(eitol(thistypecnt), tzh.tzh_ttisstdcnt);
1701                 convert(eitol(thisleapcnt), tzh.tzh_leapcnt);
1702                 convert(eitol(thistimecnt), tzh.tzh_timecnt);
1703                 convert(eitol(thistypecnt), tzh.tzh_typecnt);
1704                 convert(eitol(thischarcnt), tzh.tzh_charcnt);
1705                 DO(tzh_magic);
1706                 DO(tzh_version);
1707                 DO(tzh_reserved);
1708                 DO(tzh_ttisgmtcnt);
1709                 DO(tzh_ttisstdcnt);
1710                 DO(tzh_leapcnt);
1711                 DO(tzh_timecnt);
1712                 DO(tzh_typecnt);
1713                 DO(tzh_charcnt);
1714 #undef DO
1715                 for (i = thistimei; i < thistimelim; ++i)
1716                         if (pass == 1)
1717                                 puttzcode((long) ats[i], fp);
1718                         else    puttzcode64(ats[i], fp);
1719                 for (i = thistimei; i < thistimelim; ++i) {
1720                         unsigned char   uc;
1721
1722                         uc = typemap[types[i]];
1723                         (void) fwrite((void *) &uc,
1724                                 (size_t) sizeof uc,
1725                                 (size_t) 1,
1726                                 fp);
1727                 }
1728                 for (i = 0; i < typecnt; ++i)
1729                         if (writetype[i]) {
1730                                 puttzcode(gmtoffs[i], fp);
1731                                 (void) putc(isdsts[i], fp);
1732                                 (void) putc((unsigned char) indmap[abbrinds[i]], fp);
1733                         }
1734                 if (thischarcnt != 0)
1735                         (void) fwrite((void *) thischars,
1736                                 (size_t) sizeof thischars[0],
1737                                 (size_t) thischarcnt, fp);
1738                 for (i = thisleapi; i < thisleaplim; ++i) {
1739                         register zic_t  todo;
1740
1741                         if (roll[i]) {
1742                                 if (timecnt == 0 || trans[i] < ats[0]) {
1743                                         j = 0;
1744                                         while (isdsts[j])
1745                                                 if (++j >= typecnt) {
1746                                                         j = 0;
1747                                                         break;
1748                                                 }
1749                                 } else {
1750                                         j = 1;
1751                                         while (j < timecnt &&
1752                                                 trans[i] >= ats[j])
1753                                                         ++j;
1754                                         j = types[j - 1];
1755                                 }
1756                                 todo = tadd(trans[i], -gmtoffs[j]);
1757                         } else  todo = trans[i];
1758                         if (pass == 1)
1759                                 puttzcode((long) todo, fp);
1760                         else    puttzcode64(todo, fp);
1761                         puttzcode(corr[i], fp);
1762                 }
1763                 for (i = 0; i < typecnt; ++i)
1764                         if (writetype[i])
1765                                 (void) putc(ttisstds[i], fp);
1766                 for (i = 0; i < typecnt; ++i)
1767                         if (writetype[i])
1768                                 (void) putc(ttisgmts[i], fp);
1769         }
1770         (void) fprintf(fp, "\n%s\n", string);
1771         if (ferror(fp) || fclose(fp)) {
1772                 (void) fprintf(stderr, _("%s: Error writing %s\n"),
1773                         progname, fullname);
1774                 exit(EXIT_FAILURE);
1775         }
1776 }
1777
1778 static void
1779 doabbr(abbr, format, letters, isdst, doquotes)
1780 char * const            abbr;
1781 const char * const      format;
1782 const char * const      letters;
1783 const int               isdst;
1784 const int               doquotes;
1785 {
1786         register char * cp;
1787         register char * slashp;
1788         register int    len;
1789
1790         slashp = strchr(format, '/');
1791         if (slashp == NULL) {
1792                 if (letters == NULL)
1793                         (void) strcpy(abbr, format);
1794                 else    (void) sprintf(abbr, format, letters);
1795         } else if (isdst) {
1796                 (void) strcpy(abbr, slashp + 1);
1797         } else {
1798                 if (slashp > format)
1799                         (void) strncpy(abbr, format,
1800                                 (unsigned) (slashp - format));
1801                 abbr[slashp - format] = '\0';
1802         }
1803         if (!doquotes)
1804                 return;
1805         for (cp = abbr; *cp != '\0'; ++cp)
1806                 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", *cp) == NULL &&
1807                         strchr("abcdefghijklmnopqrstuvwxyz", *cp) == NULL)
1808                                 break;
1809         len = strlen(abbr);
1810         if (len > 0 && *cp == '\0')
1811                 return;
1812         abbr[len + 2] = '\0';
1813         abbr[len + 1] = '>';
1814         for ( ; len > 0; --len)
1815                 abbr[len] = abbr[len - 1];
1816         abbr[0] = '<';
1817 }
1818
1819 static void
1820 updateminmax(x)
1821 const int       x;
1822 {
1823         if (min_year > x)
1824                 min_year = x;
1825         if (max_year < x)
1826                 max_year = x;
1827 }
1828
1829 static int
1830 stringoffset(result, offset)
1831 char *  result;
1832 long    offset;
1833 {
1834         register int    hours;
1835         register int    minutes;
1836         register int    seconds;
1837
1838         result[0] = '\0';
1839         if (offset < 0) {
1840                 (void) strcpy(result, "-");
1841                 offset = -offset;
1842         }
1843         seconds = offset % SECSPERMIN;
1844         offset /= SECSPERMIN;
1845         minutes = offset % MINSPERHOUR;
1846         offset /= MINSPERHOUR;
1847         hours = offset;
1848         if (hours >= HOURSPERDAY) {
1849                 result[0] = '\0';
1850                 return -1;
1851         }
1852         (void) sprintf(end(result), "%d", hours);
1853         if (minutes != 0 || seconds != 0) {
1854                 (void) sprintf(end(result), ":%02d", minutes);
1855                 if (seconds != 0)
1856                         (void) sprintf(end(result), ":%02d", seconds);
1857         }
1858         return 0;
1859 }
1860
1861 static int
1862 stringrule(result, rp, dstoff, gmtoff)
1863 char *                          result;
1864 const struct rule * const       rp;
1865 const long                      dstoff;
1866 const long                      gmtoff;
1867 {
1868         register long   tod;
1869
1870         result = end(result);
1871         if (rp->r_dycode == DC_DOM) {
1872                 register int    month, total;
1873
1874                 if (rp->r_dayofmonth == 29 && rp->r_month == TM_FEBRUARY)
1875                         return -1;
1876                 total = 0;
1877                 for (month = 0; month < rp->r_month; ++month)
1878                         total += len_months[0][month];
1879                 (void) sprintf(result, "J%d", total + rp->r_dayofmonth);
1880         } else {
1881                 register int    week;
1882
1883                 if (rp->r_dycode == DC_DOWGEQ) {
1884                         if ((rp->r_dayofmonth % DAYSPERWEEK) != 1)
1885                                 return -1;
1886                         week = 1 + rp->r_dayofmonth / DAYSPERWEEK;
1887                 } else if (rp->r_dycode == DC_DOWLEQ) {
1888                         if (rp->r_dayofmonth == len_months[1][rp->r_month])
1889                                 week = 5;
1890                         else {
1891                                 if ((rp->r_dayofmonth % DAYSPERWEEK) != 0)
1892                                         return -1;
1893                                 week = rp->r_dayofmonth / DAYSPERWEEK;
1894                         }
1895                 } else  return -1;      /* "cannot happen" */
1896                 (void) sprintf(result, "M%d.%d.%d",
1897                         rp->r_month + 1, week, rp->r_wday);
1898         }
1899         tod = rp->r_tod;
1900         if (rp->r_todisgmt)
1901                 tod += gmtoff;
1902         if (rp->r_todisstd && rp->r_stdoff == 0)
1903                 tod += dstoff;
1904         if (tod < 0) {
1905                 result[0] = '\0';
1906                 return -1;
1907         }
1908         if (tod != 2 * SECSPERMIN * MINSPERHOUR) {
1909                 (void) strcat(result, "/");
1910                 if (stringoffset(end(result), tod) != 0)
1911                         return -1;
1912         }
1913         return 0;
1914 }
1915
1916 static void
1917 stringzone(result, zpfirst, zonecount)
1918 char *                          result;
1919 const struct zone * const       zpfirst;
1920 const int                       zonecount;
1921 {
1922         register const struct zone *    zp;
1923         register struct rule *          rp;
1924         register struct rule *          stdrp;
1925         register struct rule *          dstrp;
1926         register int                    i;
1927         register const char *           abbrvar;
1928
1929         result[0] = '\0';
1930         zp = zpfirst + zonecount - 1;
1931         stdrp = dstrp = NULL;
1932         for (i = 0; i < zp->z_nrules; ++i) {
1933                 rp = &zp->z_rules[i];
1934                 if (rp->r_hiwasnum || rp->r_hiyear != INT_MAX)
1935                         continue;
1936                 if (rp->r_yrtype != NULL)
1937                         continue;
1938                 if (rp->r_stdoff == 0) {
1939                         if (stdrp == NULL)
1940                                 stdrp = rp;
1941                         else    return;
1942                 } else {
1943                         if (dstrp == NULL)
1944                                 dstrp = rp;
1945                         else    return;
1946                 }
1947         }
1948         if (stdrp == NULL && dstrp == NULL) {
1949                 /*
1950                 ** There are no rules running through "max".
1951                 ** Let's find the latest rule.
1952                 */
1953                 for (i = 0; i < zp->z_nrules; ++i) {
1954                         rp = &zp->z_rules[i];
1955                         if (stdrp == NULL || rp->r_hiyear > stdrp->r_hiyear ||
1956                                 (rp->r_hiyear == stdrp->r_hiyear &&
1957                                 rp->r_month > stdrp->r_month))
1958                                         stdrp = rp;
1959                 }
1960                 if (stdrp != NULL && stdrp->r_stdoff != 0)
1961                         return; /* We end up in DST (a POSIX no-no). */
1962                 /*
1963                 ** Horrid special case: if year is 2037,
1964                 ** presume this is a zone handled on a year-by-year basis;
1965                 ** do not try to apply a rule to the zone.
1966                 */
1967                 if (stdrp != NULL && stdrp->r_hiyear == 2037)
1968                         return;
1969         }
1970         if (stdrp == NULL && (zp->z_nrules != 0 || zp->z_stdoff != 0))
1971                 return;
1972         abbrvar = (stdrp == NULL) ? "" : stdrp->r_abbrvar;
1973         doabbr(result, zp->z_format, abbrvar, FALSE, TRUE);
1974         if (stringoffset(end(result), -zp->z_gmtoff) != 0) {
1975                 result[0] = '\0';
1976                 return;
1977         }
1978         if (dstrp == NULL)
1979                 return;
1980         doabbr(end(result), zp->z_format, dstrp->r_abbrvar, TRUE, TRUE);
1981         if (dstrp->r_stdoff != SECSPERMIN * MINSPERHOUR)
1982                 if (stringoffset(end(result),
1983                         -(zp->z_gmtoff + dstrp->r_stdoff)) != 0) {
1984                                 result[0] = '\0';
1985                                 return;
1986                 }
1987         (void) strcat(result, ",");
1988         if (stringrule(result, dstrp, dstrp->r_stdoff, zp->z_gmtoff) != 0) {
1989                 result[0] = '\0';
1990                 return;
1991         }
1992         (void) strcat(result, ",");
1993         if (stringrule(result, stdrp, dstrp->r_stdoff, zp->z_gmtoff) != 0) {
1994                 result[0] = '\0';
1995                 return;
1996         }
1997 }
1998
1999 static void
2000 outzone(zpfirst, zonecount)
2001 const struct zone * const       zpfirst;
2002 const int                       zonecount;
2003 {
2004         register const struct zone *    zp;
2005         register struct rule *          rp;
2006         register int                    i, j;
2007         register int                    usestart, useuntil;
2008         register zic_t                  starttime, untiltime;
2009         register long                   gmtoff;
2010         register long                   stdoff;
2011         register int                    year;
2012         register long                   startoff;
2013         register int                    startttisstd;
2014         register int                    startttisgmt;
2015         register int                    type;
2016         register char *                 startbuf;
2017         register char *                 ab;
2018         register char *                 envvar;
2019         register int                    max_abbr_len;
2020         register int                    max_envvar_len;
2021         register int                    prodstic; /* all rules are min to max */
2022
2023         max_abbr_len = 2 + max_format_len + max_abbrvar_len;
2024         max_envvar_len = 2 * max_abbr_len + 5 * 9;
2025         startbuf = emalloc(max_abbr_len + 1);
2026         ab = emalloc(max_abbr_len + 1);
2027         envvar = emalloc(max_envvar_len + 1);
2028         INITIALIZE(untiltime);
2029         INITIALIZE(starttime);
2030         /*
2031         ** Now. . .finally. . .generate some useful data!
2032         */
2033         timecnt = 0;
2034         typecnt = 0;
2035         charcnt = 0;
2036         prodstic = zonecount == 1;
2037         /*
2038         ** Thanks to Earl Chew
2039         ** for noting the need to unconditionally initialize startttisstd.
2040         */
2041         startttisstd = FALSE;
2042         startttisgmt = FALSE;
2043         min_year = max_year = EPOCH_YEAR;
2044         if (leapseen) {
2045                 updateminmax(leapminyear);
2046                 updateminmax(leapmaxyear + (leapmaxyear < INT_MAX));
2047         }
2048         for (i = 0; i < zonecount; ++i) {
2049                 zp = &zpfirst[i];
2050                 if (i < zonecount - 1)
2051                         updateminmax(zp->z_untilrule.r_loyear);
2052                 for (j = 0; j < zp->z_nrules; ++j) {
2053                         rp = &zp->z_rules[j];
2054                         if (rp->r_lowasnum)
2055                                 updateminmax(rp->r_loyear);
2056                         if (rp->r_hiwasnum)
2057                                 updateminmax(rp->r_hiyear);
2058                         if (rp->r_lowasnum || rp->r_hiwasnum)
2059                                 prodstic = FALSE;
2060                 }
2061         }
2062         /*
2063         ** Generate lots of data if a rule can't cover all future times.
2064         */
2065         stringzone(envvar, zpfirst, zonecount);
2066         if (noise && envvar[0] == '\0') {
2067                 register char * wp;
2068
2069 wp = ecpyalloc(_("no POSIX environment variable for zone"));
2070                 wp = ecatalloc(wp, " ");
2071                 wp = ecatalloc(wp, zpfirst->z_name);
2072                 warning(wp);
2073                 ifree(wp);
2074         }
2075         if (envvar[0] == '\0') {
2076                 if (min_year >= INT_MIN + YEARSPERREPEAT)
2077                         min_year -= YEARSPERREPEAT;
2078                 else    min_year = INT_MIN;
2079                 if (max_year <= INT_MAX - YEARSPERREPEAT)
2080                         max_year += YEARSPERREPEAT;
2081                 else    max_year = INT_MAX;
2082                 /*
2083                 ** Regardless of any of the above,
2084                 ** for a "proDSTic" zone which specifies that its rules
2085                 ** always have and always will be in effect,
2086                 ** we only need one cycle to define the zone.
2087                 */
2088                 if (prodstic) {
2089                         min_year = 1900;
2090                         max_year = min_year + YEARSPERREPEAT;
2091                 }
2092         }
2093         /*
2094         ** For the benefit of older systems,
2095         ** generate data from 1900 through 2037.
2096         */
2097         if (min_year > 1900)
2098                 min_year = 1900;
2099         if (max_year < 2037)
2100                 max_year = 2037;
2101         for (i = 0; i < zonecount; ++i) {
2102                 /*
2103                 ** A guess that may well be corrected later.
2104                 */
2105                 stdoff = 0;
2106                 zp = &zpfirst[i];
2107                 usestart = i > 0 && (zp - 1)->z_untiltime > min_time;
2108                 useuntil = i < (zonecount - 1);
2109                 if (useuntil && zp->z_untiltime <= min_time)
2110                         continue;
2111                 gmtoff = zp->z_gmtoff;
2112                 eat(zp->z_filename, zp->z_linenum);
2113                 *startbuf = '\0';
2114                 startoff = zp->z_gmtoff;
2115                 if (zp->z_nrules == 0) {
2116                         stdoff = zp->z_stdoff;
2117                         doabbr(startbuf, zp->z_format,
2118                                 (char *) NULL, stdoff != 0, FALSE);
2119                         type = addtype(oadd(zp->z_gmtoff, stdoff),
2120                                 startbuf, stdoff != 0, startttisstd,
2121                                 startttisgmt);
2122                         if (usestart) {
2123                                 addtt(starttime, type);
2124                                 usestart = FALSE;
2125                         } else if (stdoff != 0)
2126                                 addtt(min_time, type);
2127                 } else for (year = min_year; year <= max_year; ++year) {
2128                         if (useuntil && year > zp->z_untilrule.r_hiyear)
2129                                 break;
2130                         /*
2131                         ** Mark which rules to do in the current year.
2132                         ** For those to do, calculate rpytime(rp, year);
2133                         */
2134                         for (j = 0; j < zp->z_nrules; ++j) {
2135                                 rp = &zp->z_rules[j];
2136                                 eats(zp->z_filename, zp->z_linenum,
2137                                         rp->r_filename, rp->r_linenum);
2138                                 rp->r_todo = year >= rp->r_loyear &&
2139                                                 year <= rp->r_hiyear &&
2140                                                 yearistype(year, rp->r_yrtype);
2141                                 if (rp->r_todo)
2142                                         rp->r_temp = rpytime(rp, year);
2143                         }
2144                         for ( ; ; ) {
2145                                 register int    k;
2146                                 register zic_t  jtime, ktime;
2147                                 register long   offset;
2148
2149                                 INITIALIZE(ktime);
2150                                 if (useuntil) {
2151                                         /*
2152                                         ** Turn untiltime into UTC
2153                                         ** assuming the current gmtoff and
2154                                         ** stdoff values.
2155                                         */
2156                                         untiltime = zp->z_untiltime;
2157                                         if (!zp->z_untilrule.r_todisgmt)
2158                                                 untiltime = tadd(untiltime,
2159                                                         -gmtoff);
2160                                         if (!zp->z_untilrule.r_todisstd)
2161                                                 untiltime = tadd(untiltime,
2162                                                         -stdoff);
2163                                 }
2164                                 /*
2165                                 ** Find the rule (of those to do, if any)
2166                                 ** that takes effect earliest in the year.
2167                                 */
2168                                 k = -1;
2169                                 for (j = 0; j < zp->z_nrules; ++j) {
2170                                         rp = &zp->z_rules[j];
2171                                         if (!rp->r_todo)
2172                                                 continue;
2173                                         eats(zp->z_filename, zp->z_linenum,
2174                                                 rp->r_filename, rp->r_linenum);
2175                                         offset = rp->r_todisgmt ? 0 : gmtoff;
2176                                         if (!rp->r_todisstd)
2177                                                 offset = oadd(offset, stdoff);
2178                                         jtime = rp->r_temp;
2179                                         if (jtime == min_time ||
2180                                                 jtime == max_time)
2181                                                         continue;
2182                                         jtime = tadd(jtime, -offset);
2183                                         if (k < 0 || jtime < ktime) {
2184                                                 k = j;
2185                                                 ktime = jtime;
2186                                         }
2187                                 }
2188                                 if (k < 0)
2189                                         break;  /* go on to next year */
2190                                 rp = &zp->z_rules[k];
2191                                 rp->r_todo = FALSE;
2192                                 if (useuntil && ktime >= untiltime)
2193                                         break;
2194                                 stdoff = rp->r_stdoff;
2195                                 if (usestart && ktime == starttime)
2196                                         usestart = FALSE;
2197                                 if (usestart) {
2198                                         if (ktime < starttime) {
2199                                                 startoff = oadd(zp->z_gmtoff,
2200                                                         stdoff);
2201                                                 doabbr(startbuf, zp->z_format,
2202                                                         rp->r_abbrvar,
2203                                                         rp->r_stdoff != 0,
2204                                                         FALSE);
2205                                                 continue;
2206                                         }
2207                                         if (*startbuf == '\0' &&
2208                                                 startoff == oadd(zp->z_gmtoff,
2209                                                 stdoff)) {
2210                                                         doabbr(startbuf,
2211                                                                 zp->z_format,
2212                                                                 rp->r_abbrvar,
2213                                                                 rp->r_stdoff !=
2214                                                                 0,
2215                                                                 FALSE);
2216                                         }
2217                                 }
2218                                 eats(zp->z_filename, zp->z_linenum,
2219                                         rp->r_filename, rp->r_linenum);
2220                                 doabbr(ab, zp->z_format, rp->r_abbrvar,
2221                                         rp->r_stdoff != 0, FALSE);
2222                                 offset = oadd(zp->z_gmtoff, rp->r_stdoff);
2223                                 type = addtype(offset, ab, rp->r_stdoff != 0,
2224                                         rp->r_todisstd, rp->r_todisgmt);
2225                                 addtt(ktime, type);
2226                         }
2227                 }
2228                 if (usestart) {
2229                         if (*startbuf == '\0' &&
2230                                 zp->z_format != NULL &&
2231                                 strchr(zp->z_format, '%') == NULL &&
2232                                 strchr(zp->z_format, '/') == NULL)
2233                                         (void) strcpy(startbuf, zp->z_format);
2234                         eat(zp->z_filename, zp->z_linenum);
2235                         if (*startbuf == '\0')
2236 error(_("can't determine time zone abbreviation to use just after until time"));
2237                         else    addtt(starttime,
2238                                         addtype(startoff, startbuf,
2239                                                 startoff != zp->z_gmtoff,
2240                                                 startttisstd,
2241                                                 startttisgmt));
2242                 }
2243                 /*
2244                 ** Now we may get to set starttime for the next zone line.
2245                 */
2246                 if (useuntil) {
2247                         startttisstd = zp->z_untilrule.r_todisstd;
2248                         startttisgmt = zp->z_untilrule.r_todisgmt;
2249                         starttime = zp->z_untiltime;
2250                         if (!startttisstd)
2251                                 starttime = tadd(starttime, -stdoff);
2252                         if (!startttisgmt)
2253                                 starttime = tadd(starttime, -gmtoff);
2254                 }
2255         }
2256         writezone(zpfirst->z_name, envvar);
2257         ifree(startbuf);
2258         ifree(ab);
2259         ifree(envvar);
2260 }
2261
2262 static void
2263 addtt(starttime, type)
2264 const zic_t     starttime;
2265 int             type;
2266 {
2267         if (starttime <= min_time ||
2268                 (timecnt == 1 && attypes[0].at < min_time)) {
2269                 gmtoffs[0] = gmtoffs[type];
2270                 isdsts[0] = isdsts[type];
2271                 ttisstds[0] = ttisstds[type];
2272                 ttisgmts[0] = ttisgmts[type];
2273                 if (abbrinds[type] != 0)
2274                         (void) strcpy(chars, &chars[abbrinds[type]]);
2275                 abbrinds[0] = 0;
2276                 charcnt = strlen(chars) + 1;
2277                 typecnt = 1;
2278                 timecnt = 0;
2279                 type = 0;
2280         }
2281         if (timecnt >= TZ_MAX_TIMES) {
2282                 error(_("too many transitions?!"));
2283                 exit(EXIT_FAILURE);
2284         }
2285         attypes[timecnt].at = starttime;
2286         attypes[timecnt].type = type;
2287         ++timecnt;
2288 }
2289
2290 static int
2291 addtype(gmtoff, abbr, isdst, ttisstd, ttisgmt)
2292 const long              gmtoff;
2293 const char * const      abbr;
2294 const int               isdst;
2295 const int               ttisstd;
2296 const int               ttisgmt;
2297 {
2298         register int    i, j;
2299
2300         if (isdst != TRUE && isdst != FALSE) {
2301                 error(_("internal error - addtype called with bad isdst"));
2302                 exit(EXIT_FAILURE);
2303         }
2304         if (ttisstd != TRUE && ttisstd != FALSE) {
2305                 error(_("internal error - addtype called with bad ttisstd"));
2306                 exit(EXIT_FAILURE);
2307         }
2308         if (ttisgmt != TRUE && ttisgmt != FALSE) {
2309                 error(_("internal error - addtype called with bad ttisgmt"));
2310                 exit(EXIT_FAILURE);
2311         }
2312         /*
2313         ** See if there's already an entry for this zone type.
2314         ** If so, just return its index.
2315         */
2316         for (i = 0; i < typecnt; ++i) {
2317                 if (gmtoff == gmtoffs[i] && isdst == isdsts[i] &&
2318                         strcmp(abbr, &chars[abbrinds[i]]) == 0 &&
2319                         ttisstd == ttisstds[i] &&
2320                         ttisgmt == ttisgmts[i])
2321                                 return i;
2322         }
2323         /*
2324         ** There isn't one; add a new one, unless there are already too
2325         ** many.
2326         */
2327         if (typecnt >= TZ_MAX_TYPES) {
2328                 error(_("too many local time types"));
2329                 exit(EXIT_FAILURE);
2330         }
2331         if (! (-1L - 2147483647L <= gmtoff && gmtoff <= 2147483647L)) {
2332                 error(_("UTC offset out of range"));
2333                 exit(EXIT_FAILURE);
2334         }
2335         gmtoffs[i] = gmtoff;
2336         isdsts[i] = isdst;
2337         ttisstds[i] = ttisstd;
2338         ttisgmts[i] = ttisgmt;
2339
2340         for (j = 0; j < charcnt; ++j)
2341                 if (strcmp(&chars[j], abbr) == 0)
2342                         break;
2343         if (j == charcnt)
2344                 newabbr(abbr);
2345         abbrinds[i] = j;
2346         ++typecnt;
2347         return i;
2348 }
2349
2350 static void
2351 leapadd(t, positive, rolling, count)
2352 const zic_t     t;
2353 const int       positive;
2354 const int       rolling;
2355 int             count;
2356 {
2357         register int    i, j;
2358
2359         if (leapcnt + (positive ? count : 1) > TZ_MAX_LEAPS) {
2360                 error(_("too many leap seconds"));
2361                 exit(EXIT_FAILURE);
2362         }
2363         for (i = 0; i < leapcnt; ++i)
2364                 if (t <= trans[i]) {
2365                         if (t == trans[i]) {
2366                                 error(_("repeated leap second moment"));
2367                                 exit(EXIT_FAILURE);
2368                         }
2369                         break;
2370                 }
2371         do {
2372                 for (j = leapcnt; j > i; --j) {
2373                         trans[j] = trans[j - 1];
2374                         corr[j] = corr[j - 1];
2375                         roll[j] = roll[j - 1];
2376                 }
2377                 trans[i] = t;
2378                 corr[i] = positive ? 1L : eitol(-count);
2379                 roll[i] = rolling;
2380                 ++leapcnt;
2381         } while (positive && --count != 0);
2382 }
2383
2384 static void
2385 adjleap(void)
2386 {
2387         register int    i;
2388         register long   last = 0;
2389
2390         /*
2391         ** propagate leap seconds forward
2392         */
2393         for (i = 0; i < leapcnt; ++i) {
2394                 trans[i] = tadd(trans[i], last);
2395                 last = corr[i] += last;
2396         }
2397 }
2398
2399 static int
2400 yearistype(year, type)
2401 const int               year;
2402 const char * const      type;
2403 {
2404         static char *   buf;
2405         int             result;
2406
2407         if (type == NULL || *type == '\0')
2408                 return TRUE;
2409         buf = erealloc(buf, (int) (132 + strlen(yitcommand) + strlen(type)));
2410         (void) sprintf(buf, "%s %d %s", yitcommand, year, type);
2411         result = system(buf);
2412         if (WIFEXITED(result)) switch (WEXITSTATUS(result)) {
2413                 case 0:
2414                         return TRUE;
2415                 case 1:
2416                         return FALSE;
2417         }
2418         error(_("Wild result from command execution"));
2419         (void) fprintf(stderr, _("%s: command was '%s', result was %d\n"),
2420                 progname, buf, result);
2421         for ( ; ; )
2422                 exit(EXIT_FAILURE);
2423 }
2424
2425 static int
2426 lowerit(a)
2427 int     a;
2428 {
2429         a = (unsigned char) a;
2430         return (isascii(a) && isupper(a)) ? tolower(a) : a;
2431 }
2432
2433 static int
2434 ciequal(ap, bp)         /* case-insensitive equality */
2435 register const char *   ap;
2436 register const char *   bp;
2437 {
2438         while (lowerit(*ap) == lowerit(*bp++))
2439                 if (*ap++ == '\0')
2440                         return TRUE;
2441         return FALSE;
2442 }
2443
2444 static int
2445 itsabbr(abbr, word)
2446 register const char *   abbr;
2447 register const char *   word;
2448 {
2449         if (lowerit(*abbr) != lowerit(*word))
2450                 return FALSE;
2451         ++word;
2452         while (*++abbr != '\0')
2453                 do {
2454                         if (*word == '\0')
2455                                 return FALSE;
2456                 } while (lowerit(*word++) != lowerit(*abbr));
2457         return TRUE;
2458 }
2459
2460 static const struct lookup *
2461 byword(word, table)
2462 register const char * const             word;
2463 register const struct lookup * const    table;
2464 {
2465         register const struct lookup *  foundlp;
2466         register const struct lookup *  lp;
2467
2468         if (word == NULL || table == NULL)
2469                 return NULL;
2470         /*
2471         ** Look for exact match.
2472         */
2473         for (lp = table; lp->l_word != NULL; ++lp)
2474                 if (ciequal(word, lp->l_word))
2475                         return lp;
2476         /*
2477         ** Look for inexact match.
2478         */
2479         foundlp = NULL;
2480         for (lp = table; lp->l_word != NULL; ++lp)
2481                 if (itsabbr(word, lp->l_word)) {
2482                         if (foundlp == NULL)
2483                                 foundlp = lp;
2484                         else    return NULL;    /* multiple inexact matches */
2485                 }
2486         return foundlp;
2487 }
2488
2489 static char **
2490 getfields(cp)
2491 register char * cp;
2492 {
2493         register char *         dp;
2494         register char **        array;
2495         register int            nsubs;
2496
2497         if (cp == NULL)
2498                 return NULL;
2499         array = (char **) (void *)
2500                 emalloc((int) ((strlen(cp) + 1) * sizeof *array));
2501         nsubs = 0;
2502         for ( ; ; ) {
2503                 while (isascii((unsigned char) *cp) &&
2504                         isspace((unsigned char) *cp))
2505                                 ++cp;
2506                 if (*cp == '\0' || *cp == '#')
2507                         break;
2508                 array[nsubs++] = dp = cp;
2509                 do {
2510                         if ((*dp = *cp++) != '"')
2511                                 ++dp;
2512                         else while ((*dp = *cp++) != '"')
2513                                 if (*dp != '\0')
2514                                         ++dp;
2515                                 else {
2516                                         error(_(
2517                                                 "Odd number of quotation marks"
2518                                                 ));
2519                                         exit(1);
2520                                 }
2521                 } while (*cp != '\0' && *cp != '#' &&
2522                         (!isascii(*cp) || !isspace((unsigned char) *cp)));
2523                 if (isascii(*cp) && isspace((unsigned char) *cp))
2524                         ++cp;
2525                 *dp = '\0';
2526         }
2527         array[nsubs] = NULL;
2528         return array;
2529 }
2530
2531 static long
2532 oadd(t1, t2)
2533 const long      t1;
2534 const long      t2;
2535 {
2536         register long   t;
2537
2538         t = t1 + t2;
2539         if ((t2 > 0 && t <= t1) || (t2 < 0 && t >= t1)) {
2540                 error(_("time overflow"));
2541                 exit(EXIT_FAILURE);
2542         }
2543         return t;
2544 }
2545
2546 static zic_t
2547 tadd(t1, t2)
2548 const zic_t     t1;
2549 const long      t2;
2550 {
2551         register zic_t  t;
2552
2553         if (t1 == max_time && t2 > 0)
2554                 return max_time;
2555         if (t1 == min_time && t2 < 0)
2556                 return min_time;
2557         t = t1 + t2;
2558         if ((t2 > 0 && t <= t1) || (t2 < 0 && t >= t1)) {
2559                 error(_("time overflow"));
2560                 exit(EXIT_FAILURE);
2561         }
2562         return t;
2563 }
2564
2565 /*
2566 ** Given a rule, and a year, compute the date - in seconds since January 1,
2567 ** 1970, 00:00 LOCAL time - in that year that the rule refers to.
2568 */
2569
2570 static zic_t
2571 rpytime(rp, wantedy)
2572 register const struct rule * const      rp;
2573 register const int                      wantedy;
2574 {
2575         register int    y, m, i;
2576         register long   dayoff;                 /* with a nod to Margaret O. */
2577         register zic_t  t;
2578
2579         if (wantedy == INT_MIN)
2580                 return min_time;
2581         if (wantedy == INT_MAX)
2582                 return max_time;
2583         dayoff = 0;
2584         m = TM_JANUARY;
2585         y = EPOCH_YEAR;
2586         while (wantedy != y) {
2587                 if (wantedy > y) {
2588                         i = len_years[isleap(y)];
2589                         ++y;
2590                 } else {
2591                         --y;
2592                         i = -len_years[isleap(y)];
2593                 }
2594                 dayoff = oadd(dayoff, eitol(i));
2595         }
2596         while (m != rp->r_month) {
2597                 i = len_months[isleap(y)][m];
2598                 dayoff = oadd(dayoff, eitol(i));
2599                 ++m;
2600         }
2601         i = rp->r_dayofmonth;
2602         if (m == TM_FEBRUARY && i == 29 && !isleap(y)) {
2603                 if (rp->r_dycode == DC_DOWLEQ)
2604                         --i;
2605                 else {
2606                         error(_("use of 2/29 in non leap-year"));
2607                         exit(EXIT_FAILURE);
2608                 }
2609         }
2610         --i;
2611         dayoff = oadd(dayoff, eitol(i));
2612         if (rp->r_dycode == DC_DOWGEQ || rp->r_dycode == DC_DOWLEQ) {
2613                 register long   wday;
2614
2615 #define LDAYSPERWEEK    ((long) DAYSPERWEEK)
2616                 wday = eitol(EPOCH_WDAY);
2617                 /*
2618                 ** Don't trust mod of negative numbers.
2619                 */
2620                 if (dayoff >= 0)
2621                         wday = (wday + dayoff) % LDAYSPERWEEK;
2622                 else {
2623                         wday -= ((-dayoff) % LDAYSPERWEEK);
2624                         if (wday < 0)
2625                                 wday += LDAYSPERWEEK;
2626                 }
2627                 while (wday != eitol(rp->r_wday))
2628                         if (rp->r_dycode == DC_DOWGEQ) {
2629                                 dayoff = oadd(dayoff, (long) 1);
2630                                 if (++wday >= LDAYSPERWEEK)
2631                                         wday = 0;
2632                                 ++i;
2633                         } else {
2634                                 dayoff = oadd(dayoff, (long) -1);
2635                                 if (--wday < 0)
2636                                         wday = LDAYSPERWEEK - 1;
2637                                 --i;
2638                         }
2639                 if (i < 0 || i >= len_months[isleap(y)][m]) {
2640                         if (noise)
2641                                 warning(_("rule goes past start/end of month--\
2642 will not work with pre-2004 versions of zic"));
2643                 }
2644         }
2645         if (dayoff < min_time / SECSPERDAY)
2646                 return min_time;
2647         if (dayoff > max_time / SECSPERDAY)
2648                 return max_time;
2649         t = (zic_t) dayoff * SECSPERDAY;
2650         return tadd(t, rp->r_tod);
2651 }
2652
2653 static void
2654 newabbr(string)
2655 const char * const      string;
2656 {
2657         register int    i;
2658
2659         if (strcmp(string, GRANDPARENTED) != 0) {
2660                 register const char *   cp;
2661                 register char *         wp;
2662
2663                 /*
2664                 ** Want one to ZIC_MAX_ABBR_LEN_WO_WARN alphabetics
2665                 ** optionally followed by a + or - and a number from 1 to 14.
2666                 */
2667                 cp = string;
2668                 wp = NULL;
2669                 while (isascii((unsigned char) *cp) &&
2670                         isalpha((unsigned char) *cp))
2671                                 ++cp;
2672                 if (cp - string == 0)
2673 wp = _("time zone abbreviation lacks alphabetic at start");
2674                 if (noise && cp - string > 3)
2675 wp = _("time zone abbreviation has more than 3 alphabetics");
2676                 if (cp - string > ZIC_MAX_ABBR_LEN_WO_WARN)
2677 wp = _("time zone abbreviation has too many alphabetics");
2678                 if (wp == NULL && (*cp == '+' || *cp == '-')) {
2679                         ++cp;
2680                         if (isascii((unsigned char) *cp) &&
2681                                 isdigit((unsigned char) *cp))
2682                                         if (*cp++ == '1' &&
2683                                                 *cp >= '0' && *cp <= '4')
2684                                                         ++cp;
2685                 }
2686                 if (*cp != '\0')
2687 wp = _("time zone abbreviation differs from POSIX standard");
2688                 if (wp != NULL) {
2689                         wp = ecpyalloc(wp);
2690                         wp = ecatalloc(wp, " (");
2691                         wp = ecatalloc(wp, string);
2692                         wp = ecatalloc(wp, ")");
2693                         warning(wp);
2694                         ifree(wp);
2695                 }
2696         }
2697         i = strlen(string) + 1;
2698         if (charcnt + i > TZ_MAX_CHARS) {
2699                 error(_("too many, or too long, time zone abbreviations"));
2700                 exit(EXIT_FAILURE);
2701         }
2702         (void) strcpy(&chars[charcnt], string);
2703         charcnt += eitol(i);
2704 }
2705
2706 static int
2707 mkdirs(argname)
2708 char *          argname;
2709 {
2710         register char * name;
2711         register char * cp;
2712
2713         if (argname == NULL || *argname == '\0')
2714                 return 0;
2715         cp = name = ecpyalloc(argname);
2716         while ((cp = strchr(cp + 1, '/')) != 0) {
2717                 *cp = '\0';
2718 #ifndef unix
2719                 /*
2720                 ** DOS drive specifier?
2721                 */
2722                 if (isalpha((unsigned char) name[0]) &&
2723                         name[1] == ':' && name[2] == '\0') {
2724                                 *cp = '/';
2725                                 continue;
2726                 }
2727 #endif /* !defined unix */
2728                 if (!itsdir(name)) {
2729                         /*
2730                         ** It doesn't seem to exist, so we try to create it.
2731                         ** Creation may fail because of the directory being
2732                         ** created by some other multiprocessor, so we get
2733                         ** to do extra checking.
2734                         */
2735                         if (mkdir(name, MKDIR_UMASK) != 0) {
2736                                 const char *e = strerror(errno);
2737
2738                                 if (errno != EEXIST || !itsdir(name)) {
2739                                         (void) fprintf(stderr,
2740 _("%s: Can't create directory %s: %s\n"),
2741                                                 progname, name, e);
2742                                         ifree(name);
2743                                         return -1;
2744                                 }
2745                         }
2746                 }
2747                 *cp = '/';
2748         }
2749         ifree(name);
2750         return 0;
2751 }
2752
2753 static long
2754 eitol(i)
2755 const int       i;
2756 {
2757         long    l;
2758
2759         l = i;
2760         if ((i < 0 && l >= 0) || (i == 0 && l != 0) || (i > 0 && l <= 0)) {
2761                 (void) fprintf(stderr,
2762                         _("%s: %d did not sign extend correctly\n"),
2763                         progname, i);
2764                 exit(EXIT_FAILURE);
2765         }
2766         return l;
2767 }
2768
2769 /*
2770 ** UNIX was a registered trademark of The Open Group in 2003.
2771 */