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