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