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