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