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