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