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