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