Home | History | Annotate | Line # | Download | only in time
zic.c revision 1.82
      1  1.82  christos /*	$NetBSD: zic.c,v 1.82 2022/08/16 10:56:21 christos Exp $	*/
      2  1.25   mlelstv /*
      3  1.25   mlelstv ** This file is in the public domain, so clarified as of
      4  1.25   mlelstv ** 2006-07-17 by Arthur David Olson.
      5  1.25   mlelstv */
      6  1.75  christos /* Compile .zi time zone data into TZif binary files.  */
      7   1.2       jtc 
      8  1.26   tsutsui #if HAVE_NBTOOL_CONFIG_H
      9  1.26   tsutsui #include "nbtool_config.h"
     10  1.26   tsutsui #endif
     11  1.26   tsutsui 
     12   1.9  christos #include <sys/cdefs.h>
     13   1.1       jtc #ifndef lint
     14  1.82  christos __RCSID("$NetBSD: zic.c,v 1.82 2022/08/16 10:56:21 christos Exp $");
     15   1.1       jtc #endif /* !defined lint */
     16   1.1       jtc 
     17  1.79  christos /* Use the system 'time' function, instead of any private replacement.
     18  1.79  christos    This avoids creating an unnecessary dependency on localtime.c.  */
     19  1.79  christos #undef EPOCH_LOCAL
     20  1.79  christos #undef EPOCH_OFFSET
     21  1.79  christos #undef RESERVE_STD_EXT_IDS
     22  1.79  christos #undef time_tz
     23  1.79  christos 
     24   1.1       jtc #include "private.h"
     25   1.1       jtc #include "tzfile.h"
     26  1.19    kleink 
     27  1.68  christos #include <fcntl.h>
     28  1.68  christos #include <locale.h>
     29  1.79  christos #include <signal.h>
     30  1.43  christos #include <stdarg.h>
     31  1.65  christos #include <stddef.h>
     32  1.69  christos #include <stdio.h>
     33  1.43  christos #include <unistd.h>
     34  1.63  christos #include <util.h>
     35  1.43  christos 
     36  1.41  christos typedef int_fast64_t	zic_t;
     37  1.41  christos #define ZIC_MIN INT_FAST64_MIN
     38  1.41  christos #define ZIC_MAX INT_FAST64_MAX
     39  1.41  christos #define SCNdZIC SCNdFAST64
     40  1.25   mlelstv 
     41  1.25   mlelstv #ifndef ZIC_MAX_ABBR_LEN_WO_WARN
     42  1.82  christos # define ZIC_MAX_ABBR_LEN_WO_WARN 6
     43  1.25   mlelstv #endif /* !defined ZIC_MAX_ABBR_LEN_WO_WARN */
     44  1.25   mlelstv 
     45  1.57  christos #ifdef HAVE_DIRECT_H
     46  1.57  christos # include <direct.h>
     47  1.57  christos # include <io.h>
     48  1.57  christos # undef mkdir
     49  1.57  christos # define mkdir(name, mode) _mkdir(name)
     50  1.57  christos #endif
     51  1.57  christos 
     52  1.19    kleink #if HAVE_SYS_STAT_H
     53  1.82  christos # include <sys/stat.h>
     54  1.19    kleink #endif
     55  1.19    kleink #ifdef S_IRUSR
     56  1.82  christos # define MKDIR_UMASK (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
     57  1.19    kleink #else
     58  1.82  christos # define MKDIR_UMASK 0755
     59  1.19    kleink #endif
     60  1.69  christos 
     61  1.65  christos /* The maximum ptrdiff_t value, for pre-C99 platforms.  */
     62  1.65  christos #ifndef PTRDIFF_MAX
     63  1.65  christos static ptrdiff_t const PTRDIFF_MAX = MAXVAL(ptrdiff_t, TYPE_BIT(ptrdiff_t));
     64  1.65  christos #endif
     65  1.65  christos 
     66  1.72  christos /* The minimum alignment of a type, for pre-C11 platforms.  */
     67  1.72  christos #if __STDC_VERSION__ < 201112
     68  1.72  christos # define _Alignof(type) offsetof(struct { char a; type b; }, b)
     69  1.72  christos #endif
     70  1.72  christos 
     71  1.82  christos /* The maximum length of a text line, including the trailing newline.  */
     72  1.82  christos #ifndef _POSIX2_LINE_MAX
     73  1.82  christos # define _POSIX2_LINE_MAX 2048
     74  1.82  christos #endif
     75  1.82  christos 
     76  1.69  christos /* The type for line numbers.  Use PRIdMAX to format them; formerly
     77  1.69  christos    there was also "#define PRIdLINENO PRIdMAX" and formats used
     78  1.69  christos    PRIdLINENO, but xgettext cannot grok that.  */
     79  1.65  christos typedef intmax_t lineno;
     80  1.65  christos 
     81   1.1       jtc struct rule {
     82   1.1       jtc 	const char *	r_filename;
     83  1.65  christos 	lineno		r_linenum;
     84   1.1       jtc 	const char *	r_name;
     85   1.1       jtc 
     86  1.41  christos 	zic_t		r_loyear;	/* for example, 1986 */
     87  1.41  christos 	zic_t		r_hiyear;	/* for example, 1986 */
     88  1.51  christos 	bool		r_lowasnum;
     89  1.51  christos 	bool		r_hiwasnum;
     90   1.1       jtc 
     91   1.1       jtc 	int		r_month;	/* 0..11 */
     92   1.1       jtc 
     93   1.1       jtc 	int		r_dycode;	/* see below */
     94   1.1       jtc 	int		r_dayofmonth;
     95   1.1       jtc 	int		r_wday;
     96   1.1       jtc 
     97  1.38  christos 	zic_t		r_tod;		/* time from midnight */
     98  1.75  christos 	bool		r_todisstd;	/* is r_tod standard time? */
     99  1.75  christos 	bool		r_todisut;	/* is r_tod UT? */
    100  1.71  christos 	bool		r_isdst;	/* is this daylight saving time? */
    101  1.75  christos 	zic_t		r_save;		/* offset from standard time */
    102   1.1       jtc 	const char *	r_abbrvar;	/* variable part of abbreviation */
    103   1.1       jtc 
    104  1.65  christos 	bool		r_todo;		/* a rule to do (used in outzone) */
    105  1.25   mlelstv 	zic_t		r_temp;		/* used in outzone */
    106   1.1       jtc };
    107   1.1       jtc 
    108   1.1       jtc /*
    109  1.82  christos ** r_dycode	r_dayofmonth	r_wday
    110   1.1       jtc */
    111  1.82  christos enum {
    112  1.82  christos   DC_DOM,	/* 1..31 */	/* unused */
    113  1.82  christos   DC_DOWGEQ,	/* 1..31 */	/* 0..6 (Sun..Sat) */
    114  1.82  christos   DC_DOWLEQ	/* 1..31 */	/* 0..6 (Sun..Sat) */
    115  1.82  christos };
    116   1.1       jtc 
    117   1.1       jtc struct zone {
    118   1.1       jtc 	const char *	z_filename;
    119  1.65  christos 	lineno		z_linenum;
    120   1.1       jtc 
    121   1.1       jtc 	const char *	z_name;
    122  1.75  christos 	zic_t		z_stdoff;
    123  1.71  christos 	char *		z_rule;
    124   1.1       jtc 	const char *	z_format;
    125  1.55  christos 	char		z_format_specifier;
    126   1.1       jtc 
    127  1.71  christos 	bool		z_isdst;
    128  1.75  christos 	zic_t		z_save;
    129   1.1       jtc 
    130   1.1       jtc 	struct rule *	z_rules;
    131  1.65  christos 	ptrdiff_t	z_nrules;
    132   1.1       jtc 
    133   1.1       jtc 	struct rule	z_untilrule;
    134  1.25   mlelstv 	zic_t		z_untiltime;
    135   1.1       jtc };
    136   1.1       jtc 
    137  1.57  christos #if !HAVE_POSIX_DECLS
    138  1.25   mlelstv extern int	getopt(int argc, char * const argv[],
    139  1.25   mlelstv 			const char * options);
    140  1.77  christos extern int	link(const char * target, const char * linkname);
    141   1.1       jtc extern char *	optarg;
    142   1.1       jtc extern int	optind;
    143  1.57  christos #endif
    144   1.1       jtc 
    145  1.44  christos #if ! HAVE_LINK
    146  1.77  christos # define link(target, linkname) (errno = ENOTSUP, -1)
    147  1.44  christos #endif
    148  1.44  christos #if ! HAVE_SYMLINK
    149  1.68  christos # define readlink(file, buf, size) (errno = ENOTSUP, -1)
    150  1.77  christos # define symlink(target, linkname) (errno = ENOTSUP, -1)
    151  1.63  christos # define S_ISLNK(m) 0
    152  1.44  christos #endif
    153  1.68  christos #ifndef AT_SYMLINK_FOLLOW
    154  1.77  christos # define linkat(targetdir, target, linknamedir, linkname, flag) \
    155  1.77  christos     (itssymlink(target) ? (errno = ENOTSUP, -1) : link(target, linkname))
    156  1.68  christos #endif
    157  1.44  christos 
    158  1.25   mlelstv static void	addtt(zic_t starttime, int type);
    159  1.57  christos static int	addtype(zic_t, char const *, bool, bool, bool);
    160  1.76  christos static void	leapadd(zic_t, int, int);
    161  1.25   mlelstv static void	adjleap(void);
    162  1.25   mlelstv static void	associate(void);
    163  1.63  christos static void	dolink(const char *, const char *, bool);
    164  1.82  christos static int	getfields(char *, char **, int);
    165  1.74  christos static zic_t	gethms(const char * string, const char * errstring);
    166  1.75  christos static zic_t	getsave(char *, bool *);
    167  1.76  christos static void	inexpires(char **, int);
    168  1.25   mlelstv static void	infile(const char * filename);
    169  1.25   mlelstv static void	inleap(char ** fields, int nfields);
    170  1.25   mlelstv static void	inlink(char ** fields, int nfields);
    171  1.25   mlelstv static void	inrule(char ** fields, int nfields);
    172  1.51  christos static bool	inzcont(char ** fields, int nfields);
    173  1.51  christos static bool	inzone(char ** fields, int nfields);
    174  1.74  christos static bool	inzsub(char **, int, bool);
    175  1.74  christos static bool	itssymlink(char const *);
    176  1.51  christos static bool	is_alpha(char a);
    177  1.47  christos static char	lowerit(char);
    178  1.63  christos static void	mkdirs(char const *, bool);
    179  1.25   mlelstv static void	newabbr(const char * abbr);
    180  1.38  christos static zic_t	oadd(zic_t t1, zic_t t2);
    181  1.65  christos static void	outzone(const struct zone * zp, ptrdiff_t ntzones);
    182  1.41  christos static zic_t	rpytime(const struct rule * rp, zic_t wantedy);
    183  1.79  christos static bool	rulesub(struct rule * rp,
    184   1.1       jtc 			const char * loyearp, const char * hiyearp,
    185   1.1       jtc 			const char * typep, const char * monthp,
    186  1.25   mlelstv 			const char * dayp, const char * timep);
    187  1.38  christos static zic_t	tadd(zic_t t1, zic_t t2);
    188   1.5       jtc 
    189  1.55  christos /* Bound on length of what %z can expand to.  */
    190  1.55  christos enum { PERCENT_Z_LEN_BOUND = sizeof "+995959" - 1 };
    191  1.55  christos 
    192  1.59  christos /* If true, work around a bug in Qt 5.6.1 and earlier, which mishandles
    193  1.74  christos    TZif files whose POSIX-TZ-style strings contain '<'; see
    194  1.59  christos    QTBUG-53071 <https://bugreports.qt.io/browse/QTBUG-53071>.  This
    195  1.59  christos    workaround will no longer be needed when Qt 5.6.1 and earlier are
    196  1.59  christos    obsolete, say in the year 2021.  */
    197  1.72  christos #ifndef WORK_AROUND_QTBUG_53071
    198  1.74  christos enum { WORK_AROUND_QTBUG_53071 = true };
    199  1.72  christos #endif
    200  1.59  christos 
    201   1.1       jtc static int		charcnt;
    202  1.51  christos static bool		errors;
    203  1.51  christos static bool		warnings;
    204   1.1       jtc static const char *	filename;
    205   1.1       jtc static int		leapcnt;
    206  1.51  christos static bool		leapseen;
    207  1.41  christos static zic_t		leapminyear;
    208  1.41  christos static zic_t		leapmaxyear;
    209  1.65  christos static lineno		linenum;
    210  1.55  christos static size_t		max_abbrvar_len = PERCENT_Z_LEN_BOUND;
    211  1.36  christos static size_t		max_format_len;
    212  1.41  christos static zic_t		max_year;
    213  1.41  christos static zic_t		min_year;
    214  1.51  christos static bool		noise;
    215   1.1       jtc static const char *	rfilename;
    216  1.65  christos static lineno		rlinenum;
    217   1.1       jtc static const char *	progname;
    218  1.65  christos static ptrdiff_t	timecnt;
    219  1.65  christos static ptrdiff_t	timecnt_alloc;
    220   1.1       jtc static int		typecnt;
    221  1.79  christos static int		unspecifiedtype;
    222   1.1       jtc 
    223   1.1       jtc /*
    224   1.1       jtc ** Line codes.
    225   1.1       jtc */
    226   1.1       jtc 
    227  1.82  christos enum {
    228  1.82  christos   LC_RULE,
    229  1.82  christos   LC_ZONE,
    230  1.82  christos   LC_LINK,
    231  1.82  christos   LC_LEAP,
    232  1.82  christos   LC_EXPIRES
    233  1.82  christos };
    234   1.1       jtc 
    235   1.1       jtc /*
    236   1.1       jtc ** Which fields are which on a Zone line.
    237   1.1       jtc */
    238   1.1       jtc 
    239  1.82  christos enum {
    240  1.82  christos   ZF_NAME = 1,
    241  1.82  christos   ZF_STDOFF,
    242  1.82  christos   ZF_RULE,
    243  1.82  christos   ZF_FORMAT,
    244  1.82  christos   ZF_TILYEAR,
    245  1.82  christos   ZF_TILMONTH,
    246  1.82  christos   ZF_TILDAY,
    247  1.82  christos   ZF_TILTIME,
    248  1.82  christos   ZONE_MAXFIELDS,
    249  1.82  christos   ZONE_MINFIELDS = ZF_TILYEAR
    250  1.82  christos };
    251   1.1       jtc 
    252   1.1       jtc /*
    253   1.1       jtc ** Which fields are which on a Zone continuation line.
    254   1.1       jtc */
    255   1.1       jtc 
    256  1.82  christos enum {
    257  1.82  christos   ZFC_STDOFF,
    258  1.82  christos   ZFC_RULE,
    259  1.82  christos   ZFC_FORMAT,
    260  1.82  christos   ZFC_TILYEAR,
    261  1.82  christos   ZFC_TILMONTH,
    262  1.82  christos   ZFC_TILDAY,
    263  1.82  christos   ZFC_TILTIME,
    264  1.82  christos   ZONEC_MAXFIELDS,
    265  1.82  christos   ZONEC_MINFIELDS = ZFC_TILYEAR
    266  1.82  christos };
    267   1.1       jtc 
    268   1.1       jtc /*
    269   1.1       jtc ** Which files are which on a Rule line.
    270   1.1       jtc */
    271   1.1       jtc 
    272  1.82  christos enum {
    273  1.82  christos   RF_NAME = 1,
    274  1.82  christos   RF_LOYEAR,
    275  1.82  christos   RF_HIYEAR,
    276  1.82  christos   RF_COMMAND,
    277  1.82  christos   RF_MONTH,
    278  1.82  christos   RF_DAY,
    279  1.82  christos   RF_TOD,
    280  1.82  christos   RF_SAVE,
    281  1.82  christos   RF_ABBRVAR,
    282  1.82  christos   RULE_FIELDS
    283  1.82  christos };
    284   1.1       jtc 
    285   1.1       jtc /*
    286   1.1       jtc ** Which fields are which on a Link line.
    287   1.1       jtc */
    288   1.1       jtc 
    289  1.82  christos enum {
    290  1.82  christos   LF_TARGET = 1,
    291  1.82  christos   LF_LINKNAME,
    292  1.82  christos   LINK_FIELDS
    293  1.82  christos };
    294   1.1       jtc 
    295   1.1       jtc /*
    296   1.1       jtc ** Which fields are which on a Leap line.
    297   1.1       jtc */
    298   1.1       jtc 
    299  1.82  christos enum {
    300  1.82  christos   LP_YEAR = 1,
    301  1.82  christos   LP_MONTH,
    302  1.82  christos   LP_DAY,
    303  1.82  christos   LP_TIME,
    304  1.82  christos   LP_CORR,
    305  1.82  christos   LP_ROLL,
    306  1.82  christos   LEAP_FIELDS,
    307   1.1       jtc 
    308  1.82  christos   /* Expires lines are like Leap lines, except without CORR and ROLL fields.  */
    309  1.82  christos   EXPIRES_FIELDS = LP_TIME + 1
    310  1.82  christos };
    311  1.82  christos 
    312  1.82  christos /* The maximum number of fields on any of the above lines.
    313  1.82  christos    (The "+"s pacify gcc -Wenum-compare.)  */
    314  1.82  christos enum {
    315  1.82  christos   MAX_FIELDS = max(max(+RULE_FIELDS, +LINK_FIELDS),
    316  1.82  christos 		   max(+LEAP_FIELDS, +EXPIRES_FIELDS))
    317  1.82  christos };
    318  1.76  christos 
    319   1.1       jtc /*
    320   1.1       jtc ** Year synonyms.
    321   1.1       jtc */
    322   1.1       jtc 
    323  1.82  christos enum {
    324  1.82  christos   YR_MINIMUM,
    325  1.82  christos   YR_MAXIMUM,
    326  1.82  christos   YR_ONLY
    327  1.82  christos };
    328   1.1       jtc 
    329   1.1       jtc static struct rule *	rules;
    330  1.65  christos static ptrdiff_t	nrules;	/* number of rules */
    331  1.65  christos static ptrdiff_t	nrules_alloc;
    332   1.1       jtc 
    333   1.1       jtc static struct zone *	zones;
    334  1.65  christos static ptrdiff_t	nzones;	/* number of zones */
    335  1.65  christos static ptrdiff_t	nzones_alloc;
    336   1.1       jtc 
    337   1.1       jtc struct link {
    338   1.1       jtc 	const char *	l_filename;
    339  1.65  christos 	lineno		l_linenum;
    340  1.77  christos 	const char *	l_target;
    341  1.77  christos 	const char *	l_linkname;
    342   1.1       jtc };
    343   1.1       jtc 
    344   1.1       jtc static struct link *	links;
    345  1.65  christos static ptrdiff_t	nlinks;
    346  1.65  christos static ptrdiff_t	nlinks_alloc;
    347   1.1       jtc 
    348   1.1       jtc struct lookup {
    349   1.1       jtc 	const char *	l_word;
    350   1.1       jtc 	const int	l_value;
    351   1.1       jtc };
    352   1.1       jtc 
    353  1.25   mlelstv static struct lookup const *	byword(const char * string,
    354  1.25   mlelstv 					const struct lookup * lp);
    355   1.1       jtc 
    356  1.69  christos static struct lookup const zi_line_codes[] = {
    357   1.1       jtc 	{ "Rule",	LC_RULE },
    358   1.1       jtc 	{ "Zone",	LC_ZONE },
    359   1.1       jtc 	{ "Link",	LC_LINK },
    360  1.69  christos 	{ NULL,		0 }
    361  1.69  christos };
    362  1.69  christos static struct lookup const leap_line_codes[] = {
    363   1.1       jtc 	{ "Leap",	LC_LEAP },
    364  1.76  christos 	{ "Expires",	LC_EXPIRES },
    365   1.1       jtc 	{ NULL,		0}
    366   1.1       jtc };
    367   1.1       jtc 
    368   1.1       jtc static struct lookup const	mon_names[] = {
    369   1.1       jtc 	{ "January",	TM_JANUARY },
    370   1.1       jtc 	{ "February",	TM_FEBRUARY },
    371   1.1       jtc 	{ "March",	TM_MARCH },
    372   1.1       jtc 	{ "April",	TM_APRIL },
    373   1.1       jtc 	{ "May",	TM_MAY },
    374   1.1       jtc 	{ "June",	TM_JUNE },
    375   1.1       jtc 	{ "July",	TM_JULY },
    376   1.1       jtc 	{ "August",	TM_AUGUST },
    377   1.1       jtc 	{ "September",	TM_SEPTEMBER },
    378   1.1       jtc 	{ "October",	TM_OCTOBER },
    379   1.1       jtc 	{ "November",	TM_NOVEMBER },
    380   1.1       jtc 	{ "December",	TM_DECEMBER },
    381   1.1       jtc 	{ NULL,		0 }
    382   1.1       jtc };
    383   1.1       jtc 
    384   1.1       jtc static struct lookup const	wday_names[] = {
    385   1.1       jtc 	{ "Sunday",	TM_SUNDAY },
    386   1.1       jtc 	{ "Monday",	TM_MONDAY },
    387   1.1       jtc 	{ "Tuesday",	TM_TUESDAY },
    388   1.1       jtc 	{ "Wednesday",	TM_WEDNESDAY },
    389   1.1       jtc 	{ "Thursday",	TM_THURSDAY },
    390   1.1       jtc 	{ "Friday",	TM_FRIDAY },
    391   1.1       jtc 	{ "Saturday",	TM_SATURDAY },
    392   1.1       jtc 	{ NULL,		0 }
    393   1.1       jtc };
    394   1.1       jtc 
    395   1.1       jtc static struct lookup const	lasts[] = {
    396   1.1       jtc 	{ "last-Sunday",	TM_SUNDAY },
    397   1.1       jtc 	{ "last-Monday",	TM_MONDAY },
    398   1.1       jtc 	{ "last-Tuesday",	TM_TUESDAY },
    399   1.1       jtc 	{ "last-Wednesday",	TM_WEDNESDAY },
    400   1.1       jtc 	{ "last-Thursday",	TM_THURSDAY },
    401   1.1       jtc 	{ "last-Friday",	TM_FRIDAY },
    402   1.1       jtc 	{ "last-Saturday",	TM_SATURDAY },
    403   1.1       jtc 	{ NULL,			0 }
    404   1.1       jtc };
    405   1.1       jtc 
    406   1.1       jtc static struct lookup const	begin_years[] = {
    407   1.1       jtc 	{ "minimum",	YR_MINIMUM },
    408   1.1       jtc 	{ "maximum",	YR_MAXIMUM },
    409   1.1       jtc 	{ NULL,		0 }
    410   1.1       jtc };
    411   1.1       jtc 
    412   1.1       jtc static struct lookup const	end_years[] = {
    413   1.1       jtc 	{ "minimum",	YR_MINIMUM },
    414   1.1       jtc 	{ "maximum",	YR_MAXIMUM },
    415   1.1       jtc 	{ "only",	YR_ONLY },
    416   1.1       jtc 	{ NULL,		0 }
    417   1.1       jtc };
    418   1.1       jtc 
    419   1.1       jtc static struct lookup const	leap_types[] = {
    420  1.51  christos 	{ "Rolling",	true },
    421  1.51  christos 	{ "Stationary",	false },
    422   1.1       jtc 	{ NULL,		0 }
    423   1.1       jtc };
    424   1.1       jtc 
    425   1.1       jtc static const int	len_months[2][MONSPERYEAR] = {
    426   1.1       jtc 	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
    427   1.1       jtc 	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
    428   1.1       jtc };
    429   1.1       jtc 
    430   1.1       jtc static const int	len_years[2] = {
    431   1.1       jtc 	DAYSPERNYEAR, DAYSPERLYEAR
    432   1.1       jtc };
    433   1.1       jtc 
    434   1.5       jtc static struct attype {
    435  1.25   mlelstv 	zic_t		at;
    436  1.63  christos 	bool		dontmerge;
    437   1.5       jtc 	unsigned char	type;
    438  1.45  christos } *			attypes;
    439  1.75  christos static zic_t		utoffs[TZ_MAX_TYPES];
    440   1.1       jtc static char		isdsts[TZ_MAX_TYPES];
    441  1.75  christos static unsigned char	desigidx[TZ_MAX_TYPES];
    442  1.51  christos static bool		ttisstds[TZ_MAX_TYPES];
    443  1.75  christos static bool		ttisuts[TZ_MAX_TYPES];
    444   1.1       jtc static char		chars[TZ_MAX_CHARS];
    445  1.25   mlelstv static zic_t		trans[TZ_MAX_LEAPS];
    446  1.38  christos static zic_t		corr[TZ_MAX_LEAPS];
    447   1.1       jtc static char		roll[TZ_MAX_LEAPS];
    448   1.1       jtc 
    449   1.1       jtc /*
    450   1.1       jtc ** Memory allocation.
    451   1.1       jtc */
    452   1.1       jtc 
    453  1.45  christos static _Noreturn void
    454  1.45  christos memory_exhausted(const char *msg)
    455  1.45  christos {
    456  1.45  christos 	fprintf(stderr, _("%s: Memory exhausted: %s\n"), progname, msg);
    457  1.45  christos 	exit(EXIT_FAILURE);
    458  1.45  christos }
    459  1.45  christos 
    460  1.45  christos static ATTRIBUTE_PURE size_t
    461  1.45  christos size_product(size_t nitems, size_t itemsize)
    462  1.45  christos {
    463  1.45  christos 	if (SIZE_MAX / itemsize < nitems)
    464  1.51  christos 		memory_exhausted(_("size overflow"));
    465  1.45  christos 	return nitems * itemsize;
    466  1.45  christos }
    467  1.45  christos 
    468  1.72  christos static ATTRIBUTE_PURE size_t
    469  1.72  christos align_to(size_t size, size_t alignment)
    470  1.72  christos {
    471  1.72  christos   size_t aligned_size = size + alignment - 1;
    472  1.72  christos   aligned_size -= aligned_size % alignment;
    473  1.72  christos   if (aligned_size < size)
    474  1.72  christos     memory_exhausted(_("alignment overflow"));
    475  1.72  christos   return aligned_size;
    476  1.72  christos }
    477  1.72  christos 
    478  1.53  christos #if !HAVE_STRDUP
    479  1.53  christos static char *
    480  1.53  christos strdup(char const *str)
    481  1.53  christos {
    482  1.53  christos 	char *result = malloc(strlen(str) + 1);
    483  1.53  christos 	return result ? strcpy(result, str) : result;
    484  1.53  christos }
    485  1.53  christos #endif
    486  1.53  christos 
    487  1.69  christos static void *
    488  1.53  christos memcheck(void *ptr)
    489   1.1       jtc {
    490  1.45  christos 	if (ptr == NULL)
    491  1.79  christos 	  memory_exhausted(strerror(HAVE_MALLOC_ERRNO ? errno : ENOMEM));
    492   1.1       jtc 	return ptr;
    493   1.1       jtc }
    494   1.1       jtc 
    495  1.71  christos static void * ATTRIBUTE_MALLOC
    496  1.53  christos zic_malloc(size_t size)
    497  1.53  christos {
    498  1.53  christos 	return memcheck(malloc(size));
    499  1.53  christos }
    500  1.53  christos 
    501  1.53  christos static void *
    502  1.53  christos zic_realloc(void *ptr, size_t size)
    503  1.53  christos {
    504  1.53  christos 	return memcheck(realloc(ptr, size));
    505  1.53  christos }
    506  1.53  christos 
    507  1.71  christos static char * ATTRIBUTE_MALLOC
    508  1.53  christos ecpyalloc(char const *str)
    509  1.53  christos {
    510  1.53  christos 	return memcheck(strdup(str));
    511  1.53  christos }
    512   1.1       jtc 
    513  1.45  christos static void *
    514  1.65  christos growalloc(void *ptr, size_t itemsize, ptrdiff_t nitems, ptrdiff_t *nitems_alloc)
    515  1.45  christos {
    516  1.45  christos 	if (nitems < *nitems_alloc)
    517  1.45  christos 		return ptr;
    518  1.45  christos 	else {
    519  1.65  christos 		ptrdiff_t nitems_max = PTRDIFF_MAX - WORK_AROUND_QTBUG_53071;
    520  1.82  christos 		ptrdiff_t amax = min((size_t)nitems_max, SIZE_MAX);
    521  1.45  christos 		if ((amax - 1) / 3 * 2 < *nitems_alloc)
    522  1.65  christos 			memory_exhausted(_("integer overflow"));
    523  1.65  christos 		*nitems_alloc += (*nitems_alloc >> 1) + 1;
    524  1.53  christos 		return zic_realloc(ptr, size_product(*nitems_alloc, itemsize));
    525  1.45  christos 	}
    526  1.45  christos }
    527  1.45  christos 
    528   1.1       jtc /*
    529   1.1       jtc ** Error handling.
    530   1.1       jtc */
    531   1.1       jtc 
    532   1.1       jtc static void
    533  1.65  christos eats(char const *name, lineno num, char const *rname, lineno rnum)
    534   1.1       jtc {
    535   1.1       jtc 	filename = name;
    536   1.1       jtc 	linenum = num;
    537   1.1       jtc 	rfilename = rname;
    538   1.1       jtc 	rlinenum = rnum;
    539   1.1       jtc }
    540   1.1       jtc 
    541   1.1       jtc static void
    542  1.65  christos eat(char const *name, lineno num)
    543   1.1       jtc {
    544  1.31  christos 	eats(name, num, NULL, -1);
    545   1.1       jtc }
    546   1.1       jtc 
    547  1.43  christos static void ATTRIBUTE_FORMAT((printf, 1, 0))
    548  1.43  christos verror(const char *const string, va_list args)
    549   1.1       jtc {
    550   1.1       jtc 	/*
    551   1.1       jtc 	** Match the format of "cc" to allow sh users to
    552   1.1       jtc 	**	zic ... 2>&1 | error -t "*" -v
    553   1.1       jtc 	** on BSD systems.
    554   1.1       jtc 	*/
    555  1.54  christos 	if (filename)
    556  1.69  christos 	  fprintf(stderr, _("\"%s\", line %"PRIdMAX": "), filename, linenum);
    557  1.43  christos 	vfprintf(stderr, string, args);
    558   1.1       jtc 	if (rfilename != NULL)
    559  1.69  christos 		fprintf(stderr, _(" (rule from \"%s\", line %"PRIdMAX")"),
    560   1.1       jtc 			rfilename, rlinenum);
    561  1.51  christos 	fprintf(stderr, "\n");
    562   1.1       jtc }
    563   1.1       jtc 
    564  1.43  christos static void ATTRIBUTE_FORMAT((printf, 1, 2))
    565  1.43  christos error(const char *const string, ...)
    566   1.5       jtc {
    567  1.43  christos 	va_list args;
    568  1.43  christos 	va_start(args, string);
    569  1.43  christos 	verror(string, args);
    570  1.43  christos 	va_end(args);
    571  1.51  christos 	errors = true;
    572  1.43  christos }
    573  1.43  christos 
    574  1.43  christos static void ATTRIBUTE_FORMAT((printf, 1, 2))
    575  1.43  christos warning(const char *const string, ...)
    576  1.43  christos {
    577  1.43  christos 	va_list args;
    578  1.43  christos 	fprintf(stderr, _("warning: "));
    579  1.43  christos 	va_start(args, string);
    580  1.43  christos 	verror(string, args);
    581  1.43  christos 	va_end(args);
    582  1.51  christos 	warnings = true;
    583  1.51  christos }
    584  1.51  christos 
    585  1.79  christos /* Close STREAM.  If it had an I/O error, report it against DIR/NAME,
    586  1.79  christos    remove TEMPNAME if nonnull, and then exit.  */
    587  1.51  christos static void
    588  1.79  christos close_file(FILE *stream, char const *dir, char const *name,
    589  1.79  christos 	   char const *tempname)
    590  1.51  christos {
    591  1.51  christos   char const *e = (ferror(stream) ? _("I/O error")
    592  1.51  christos 		   : fclose(stream) != 0 ? strerror(errno) : NULL);
    593  1.51  christos   if (e) {
    594  1.63  christos     fprintf(stderr, "%s: %s%s%s%s%s\n", progname,
    595  1.63  christos 	    dir ? dir : "", dir ? "/" : "",
    596  1.63  christos 	    name ? name : "", name ? ": " : "",
    597  1.63  christos 	    e);
    598  1.79  christos     if (tempname)
    599  1.79  christos       remove(tempname);
    600  1.51  christos     exit(EXIT_FAILURE);
    601  1.51  christos   }
    602   1.5       jtc }
    603   1.5       jtc 
    604  1.41  christos static _Noreturn void
    605  1.25   mlelstv usage(FILE *stream, int status)
    606   1.1       jtc {
    607  1.51  christos   fprintf(stream,
    608  1.51  christos 	  _("%s: usage is %s [ --version ] [ --help ] [ -v ] \\\n"
    609  1.75  christos 	    "\t[ -b {slim|fat} ] [ -d directory ] [ -l localtime ]"
    610  1.75  christos 	    " [ -L leapseconds ] \\\n"
    611  1.82  christos 	    "\t[ -p posixrules ] [ -r '[@lo][/@hi]' ] [ -R '@hi' ] \\\n"
    612  1.82  christos 	    "\t[ -t localtime-link ] \\\n"
    613  1.74  christos 	    "\t[ filename ... ]\n\n"
    614  1.51  christos 	    "Report bugs to %s.\n"),
    615  1.51  christos 	  progname, progname, REPORT_BUGS_TO);
    616  1.51  christos   if (status == EXIT_SUCCESS)
    617  1.79  christos     close_file(stream, NULL, NULL, NULL);
    618  1.51  christos   exit(status);
    619   1.1       jtc }
    620   1.1       jtc 
    621  1.63  christos /* Change the working directory to DIR, possibly creating DIR and its
    622  1.63  christos    ancestors.  After this is done, all files are accessed with names
    623  1.63  christos    relative to DIR.  */
    624  1.63  christos static void
    625  1.79  christos change_directory(char const *dir)
    626  1.63  christos {
    627  1.63  christos   if (chdir(dir) != 0) {
    628  1.63  christos     int chdir_errno = errno;
    629  1.63  christos     if (chdir_errno == ENOENT) {
    630  1.63  christos       mkdirs(dir, false);
    631  1.63  christos       chdir_errno = chdir(dir) == 0 ? 0 : errno;
    632  1.63  christos     }
    633  1.63  christos     if (chdir_errno != 0) {
    634  1.63  christos       fprintf(stderr, _("%s: Can't chdir to %s: %s\n"),
    635  1.63  christos 	      progname, dir, strerror(chdir_errno));
    636  1.63  christos       exit(EXIT_FAILURE);
    637  1.63  christos     }
    638  1.63  christos   }
    639  1.63  christos }
    640  1.63  christos 
    641  1.79  christos /* Simple signal handling: just set a flag that is checked
    642  1.79  christos    periodically outside critical sections.  To set up the handler,
    643  1.79  christos    prefer sigaction if available to close a signal race.  */
    644  1.79  christos 
    645  1.79  christos static sig_atomic_t got_signal;
    646  1.79  christos 
    647  1.79  christos static void
    648  1.79  christos signal_handler(int sig)
    649  1.79  christos {
    650  1.79  christos #ifndef SA_SIGINFO
    651  1.79  christos   signal(sig, signal_handler);
    652  1.79  christos #endif
    653  1.79  christos   got_signal = sig;
    654  1.79  christos }
    655  1.79  christos 
    656  1.79  christos /* Arrange for SIGINT etc. to be caught by the handler.  */
    657  1.79  christos static void
    658  1.79  christos catch_signals(void)
    659  1.79  christos {
    660  1.79  christos   static int const signals[] = {
    661  1.79  christos #ifdef SIGHUP
    662  1.79  christos     SIGHUP,
    663  1.79  christos #endif
    664  1.79  christos     SIGINT,
    665  1.79  christos #ifdef SIGPIPE
    666  1.79  christos     SIGPIPE,
    667  1.79  christos #endif
    668  1.79  christos     SIGTERM
    669  1.79  christos   };
    670  1.79  christos   size_t i;
    671  1.79  christos   for (i = 0; i < sizeof signals / sizeof signals[0]; i++) {
    672  1.79  christos #ifdef SA_SIGINFO
    673  1.79  christos     struct sigaction act0, act;
    674  1.79  christos     act.sa_handler = signal_handler;
    675  1.79  christos     sigemptyset(&act.sa_mask);
    676  1.79  christos     act.sa_flags = 0;
    677  1.79  christos     if (sigaction(signals[i], &act, &act0) == 0
    678  1.79  christos 	&& ! (act0.sa_flags & SA_SIGINFO) && act0.sa_handler == SIG_IGN) {
    679  1.79  christos       sigaction(signals[i], &act0, NULL);
    680  1.79  christos       got_signal = 0;
    681  1.79  christos     }
    682  1.79  christos #else
    683  1.79  christos     if (signal(signals[i], signal_handler) == SIG_IGN) {
    684  1.79  christos       signal(signals[i], SIG_IGN);
    685  1.79  christos       got_signal = 0;
    686  1.79  christos     }
    687  1.79  christos #endif
    688  1.79  christos   }
    689  1.79  christos }
    690  1.79  christos 
    691  1.79  christos /* If a signal has arrived, terminate zic with appropriate status.  */
    692  1.79  christos static void
    693  1.79  christos check_for_signal(void)
    694  1.79  christos {
    695  1.79  christos   int sig = got_signal;
    696  1.79  christos   if (sig) {
    697  1.79  christos     signal(sig, SIG_DFL);
    698  1.79  christos     raise(sig);
    699  1.79  christos     abort(); /* A bug in 'raise'.  */
    700  1.79  christos   }
    701  1.79  christos }
    702  1.79  christos 
    703  1.82  christos enum { TIME_T_BITS_IN_FILE = 64 };
    704  1.74  christos 
    705  1.74  christos /* The minimum and maximum values representable in a TZif file.  */
    706  1.74  christos static zic_t const min_time = MINVAL(zic_t, TIME_T_BITS_IN_FILE);
    707  1.74  christos static zic_t const max_time = MAXVAL(zic_t, TIME_T_BITS_IN_FILE);
    708  1.74  christos 
    709  1.74  christos /* The minimum, and one less than the maximum, values specified by
    710  1.74  christos    the -r option.  These default to MIN_TIME and MAX_TIME.  */
    711  1.74  christos static zic_t lo_time = MINVAL(zic_t, TIME_T_BITS_IN_FILE);
    712  1.74  christos static zic_t hi_time = MAXVAL(zic_t, TIME_T_BITS_IN_FILE);
    713  1.74  christos 
    714  1.82  christos /* The time specified by the -R option, defaulting to MIN_TIME.  */
    715  1.82  christos static zic_t redundant_time = MINVAL(zic_t, TIME_T_BITS_IN_FILE);
    716  1.82  christos 
    717  1.76  christos /* The time specified by an Expires line, or negative if no such line.  */
    718  1.76  christos static zic_t leapexpires = -1;
    719  1.76  christos 
    720  1.74  christos /* Set the time range of the output to TIMERANGE.
    721  1.74  christos    Return true if successful.  */
    722  1.74  christos static bool
    723  1.74  christos timerange_option(char *timerange)
    724  1.74  christos {
    725  1.74  christos   intmax_t lo = min_time, hi = max_time;
    726  1.74  christos   char *lo_end = timerange, *hi_end;
    727  1.74  christos   if (*timerange == '@') {
    728  1.74  christos     errno = 0;
    729  1.79  christos     lo = strtoimax(timerange + 1, &lo_end, 10);
    730  1.74  christos     if (lo_end == timerange + 1 || (lo == INTMAX_MAX && errno == ERANGE))
    731  1.74  christos       return false;
    732  1.74  christos   }
    733  1.74  christos   hi_end = lo_end;
    734  1.74  christos   if (lo_end[0] == '/' && lo_end[1] == '@') {
    735  1.74  christos     errno = 0;
    736  1.79  christos     hi = strtoimax(lo_end + 2, &hi_end, 10);
    737  1.74  christos     if (hi_end == lo_end + 2 || hi == INTMAX_MIN)
    738  1.74  christos       return false;
    739  1.74  christos     hi -= ! (hi == INTMAX_MAX && errno == ERANGE);
    740  1.74  christos   }
    741  1.74  christos   if (*hi_end || hi < lo || max_time < lo || hi < min_time)
    742  1.74  christos     return false;
    743  1.82  christos   lo_time = max(lo, min_time);
    744  1.82  christos   hi_time = min(hi, max_time);
    745  1.74  christos   return true;
    746  1.74  christos }
    747  1.74  christos 
    748  1.82  christos /* Generate redundant time stamps up to OPT.  Return true if successful.  */
    749  1.82  christos static bool
    750  1.82  christos redundant_time_option(char *opt)
    751  1.82  christos {
    752  1.82  christos   if (*opt == '@') {
    753  1.82  christos     intmax_t redundant;
    754  1.82  christos     char *opt_end;
    755  1.82  christos     redundant = strtoimax(opt + 1, &opt_end, 10);
    756  1.82  christos     if (opt_end != opt + 1 && !*opt_end) {
    757  1.82  christos       redundant_time = max(redundant_time, redundant);
    758  1.82  christos       return true;
    759  1.82  christos     }
    760  1.82  christos   }
    761  1.82  christos   return false;
    762  1.82  christos }
    763  1.82  christos 
    764   1.1       jtc static const char *	psxrules;
    765   1.1       jtc static const char *	lcltime;
    766   1.1       jtc static const char *	directory;
    767   1.1       jtc static const char *	leapsec;
    768  1.70  christos static const char *	tzdefault;
    769   1.1       jtc 
    770  1.75  christos /* -1 if the TZif output file should be slim, 0 if default, 1 if the
    771  1.78  christos    output should be fat for backward compatibility.  ZIC_BLOAT_DEFAULT
    772  1.78  christos    determines the default.  */
    773  1.75  christos static int bloat;
    774  1.75  christos 
    775  1.75  christos static bool
    776  1.75  christos want_bloat(void)
    777  1.75  christos {
    778  1.75  christos   return 0 <= bloat;
    779  1.75  christos }
    780  1.75  christos 
    781  1.75  christos #ifndef ZIC_BLOAT_DEFAULT
    782  1.77  christos # define ZIC_BLOAT_DEFAULT "slim"
    783  1.75  christos #endif
    784  1.75  christos 
    785   1.1       jtc int
    786  1.57  christos main(int argc, char **argv)
    787  1.31  christos {
    788  1.65  christos 	int	c, k;
    789  1.65  christos 	ptrdiff_t	i, j;
    790  1.74  christos 	bool timerange_given = false;
    791   1.1       jtc 
    792  1.41  christos #ifdef S_IWGRP
    793  1.57  christos 	umask(umask(S_IWGRP | S_IWOTH) | (S_IWGRP | S_IWOTH));
    794  1.41  christos #endif
    795  1.57  christos #if HAVE_GETTEXT
    796  1.57  christos 	setlocale(LC_MESSAGES, "");
    797  1.82  christos # ifdef TZ_DOMAINDIR
    798  1.57  christos 	bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
    799  1.82  christos # endif /* defined TEXTDOMAINDIR */
    800  1.57  christos 	textdomain(TZ_DOMAIN);
    801  1.25   mlelstv #endif /* HAVE_GETTEXT */
    802   1.1       jtc 	progname = argv[0];
    803  1.25   mlelstv 	if (TYPE_BIT(zic_t) < 64) {
    804  1.57  christos 		fprintf(stderr, "%s: %s\n", progname,
    805  1.25   mlelstv 			_("wild compilation-time specification of zic_t"));
    806  1.51  christos 		return EXIT_FAILURE;
    807  1.25   mlelstv 	}
    808  1.65  christos 	for (k = 1; k < argc; k++)
    809  1.65  christos 		if (strcmp(argv[k], "--version") == 0) {
    810  1.57  christos 			printf("zic %s%s\n", PKGVERSION, TZVERSION);
    811  1.79  christos 			close_file(stdout, NULL, NULL, NULL);
    812  1.51  christos 			return EXIT_SUCCESS;
    813  1.65  christos 		} else if (strcmp(argv[k], "--help") == 0) {
    814  1.25   mlelstv 			usage(stdout, EXIT_SUCCESS);
    815  1.20    kleink 		}
    816  1.82  christos 	while ((c = getopt(argc, argv, "b:d:l:L:p:r:R:st:vy:")) != EOF
    817  1.82  christos 	       && c != -1)
    818   1.1       jtc 		switch (c) {
    819   1.1       jtc 			default:
    820  1.25   mlelstv 				usage(stderr, EXIT_FAILURE);
    821  1.75  christos 			case 'b':
    822  1.75  christos 				if (strcmp(optarg, "slim") == 0) {
    823  1.75  christos 				  if (0 < bloat)
    824  1.75  christos 				    error(_("incompatible -b options"));
    825  1.75  christos 				  bloat = -1;
    826  1.75  christos 				} else if (strcmp(optarg, "fat") == 0) {
    827  1.75  christos 				  if (bloat < 0)
    828  1.75  christos 				    error(_("incompatible -b options"));
    829  1.75  christos 				  bloat = 1;
    830  1.75  christos 				} else
    831  1.75  christos 				  error(_("invalid option: -b '%s'"), optarg);
    832  1.75  christos 				break;
    833   1.1       jtc 			case 'd':
    834   1.1       jtc 				if (directory == NULL)
    835   1.1       jtc 					directory = optarg;
    836   1.1       jtc 				else {
    837  1.51  christos 					fprintf(stderr,
    838   1.5       jtc _("%s: More than one -d option specified\n"),
    839   1.1       jtc 						progname);
    840  1.51  christos 					return EXIT_FAILURE;
    841   1.1       jtc 				}
    842   1.1       jtc 				break;
    843   1.1       jtc 			case 'l':
    844   1.1       jtc 				if (lcltime == NULL)
    845   1.1       jtc 					lcltime = optarg;
    846   1.1       jtc 				else {
    847  1.51  christos 					fprintf(stderr,
    848   1.5       jtc _("%s: More than one -l option specified\n"),
    849   1.1       jtc 						progname);
    850  1.51  christos 					return EXIT_FAILURE;
    851   1.1       jtc 				}
    852   1.1       jtc 				break;
    853   1.1       jtc 			case 'p':
    854   1.1       jtc 				if (psxrules == NULL)
    855   1.1       jtc 					psxrules = optarg;
    856   1.1       jtc 				else {
    857  1.51  christos 					fprintf(stderr,
    858   1.5       jtc _("%s: More than one -p option specified\n"),
    859   1.1       jtc 						progname);
    860  1.51  christos 					return EXIT_FAILURE;
    861   1.1       jtc 				}
    862   1.1       jtc 				break;
    863  1.70  christos 			case 't':
    864  1.70  christos 				if (tzdefault != NULL) {
    865  1.70  christos 				  fprintf(stderr,
    866  1.70  christos 					  _("%s: More than one -t option"
    867  1.70  christos 					    " specified\n"),
    868  1.70  christos 					  progname);
    869  1.70  christos 				  return EXIT_FAILURE;
    870  1.70  christos 				}
    871  1.70  christos 				tzdefault = optarg;
    872  1.70  christos 				break;
    873   1.1       jtc 			case 'y':
    874  1.77  christos 				warning(_("-y ignored"));
    875   1.1       jtc 				break;
    876   1.1       jtc 			case 'L':
    877   1.1       jtc 				if (leapsec == NULL)
    878   1.1       jtc 					leapsec = optarg;
    879   1.1       jtc 				else {
    880  1.51  christos 					fprintf(stderr,
    881   1.5       jtc _("%s: More than one -L option specified\n"),
    882   1.1       jtc 						progname);
    883  1.51  christos 					return EXIT_FAILURE;
    884   1.1       jtc 				}
    885   1.1       jtc 				break;
    886   1.1       jtc 			case 'v':
    887  1.51  christos 				noise = true;
    888   1.1       jtc 				break;
    889  1.74  christos 			case 'r':
    890  1.74  christos 				if (timerange_given) {
    891  1.74  christos 				  fprintf(stderr,
    892  1.74  christos _("%s: More than one -r option specified\n"),
    893  1.74  christos 					  progname);
    894  1.74  christos 				  return EXIT_FAILURE;
    895  1.74  christos 				}
    896  1.74  christos 				if (! timerange_option(optarg)) {
    897  1.74  christos 				  fprintf(stderr,
    898  1.74  christos _("%s: invalid time range: %s\n"),
    899  1.74  christos 					  progname, optarg);
    900  1.74  christos 				  return EXIT_FAILURE;
    901  1.74  christos 				}
    902  1.74  christos 				timerange_given = true;
    903  1.74  christos 				break;
    904  1.82  christos 			case 'R':
    905  1.82  christos 				if (! redundant_time_option(optarg)) {
    906  1.82  christos 				  fprintf(stderr, _("%s: invalid time: %s\n"),
    907  1.82  christos 					  progname, optarg);
    908  1.82  christos 				  return EXIT_FAILURE;
    909  1.82  christos 				}
    910  1.82  christos 				break;
    911   1.1       jtc 			case 's':
    912  1.54  christos 				warning(_("-s ignored"));
    913   1.1       jtc 				break;
    914   1.1       jtc 		}
    915   1.1       jtc 	if (optind == argc - 1 && strcmp(argv[optind], "=") == 0)
    916  1.25   mlelstv 		usage(stderr, EXIT_FAILURE);	/* usage message by request */
    917  1.82  christos 	if (hi_time + (hi_time < ZIC_MAX) < redundant_time) {
    918  1.82  christos 	  fprintf(stderr, _("%s: -R time exceeds -r cutoff\n"), progname);
    919  1.82  christos 	  return EXIT_FAILURE;
    920  1.82  christos 	}
    921  1.78  christos 	if (bloat == 0) {
    922  1.78  christos 	  static char const bloat_default[] = ZIC_BLOAT_DEFAULT;
    923  1.78  christos 	  if (strcmp(bloat_default, "slim") == 0)
    924  1.78  christos 	    bloat = -1;
    925  1.78  christos 	  else if (strcmp(bloat_default, "fat") == 0)
    926  1.78  christos 	    bloat = 1;
    927  1.78  christos 	  else
    928  1.78  christos 	    abort(); /* Configuration error.  */
    929  1.78  christos 	}
    930   1.1       jtc 	if (directory == NULL)
    931   1.1       jtc 		directory = TZDIR;
    932  1.70  christos 	if (tzdefault == NULL)
    933  1.70  christos 		tzdefault = TZDEFAULT;
    934   1.1       jtc 
    935   1.1       jtc 	if (optind < argc && leapsec != NULL) {
    936   1.1       jtc 		infile(leapsec);
    937   1.1       jtc 		adjleap();
    938   1.1       jtc 	}
    939   1.1       jtc 
    940  1.65  christos 	for (k = optind; k < argc; k++)
    941  1.65  christos 		infile(argv[k]);
    942   1.1       jtc 	if (errors)
    943  1.51  christos 		return EXIT_FAILURE;
    944   1.1       jtc 	associate();
    945  1.63  christos 	change_directory(directory);
    946  1.79  christos 	catch_signals();
    947   1.1       jtc 	for (i = 0; i < nzones; i = j) {
    948   1.1       jtc 		/*
    949   1.1       jtc 		** Find the next non-continuation zone entry.
    950   1.1       jtc 		*/
    951   1.1       jtc 		for (j = i + 1; j < nzones && zones[j].z_name == NULL; ++j)
    952   1.1       jtc 			continue;
    953   1.1       jtc 		outzone(&zones[i], j - i);
    954   1.1       jtc 	}
    955   1.1       jtc 	/*
    956   1.1       jtc 	** Make links.
    957   1.1       jtc 	*/
    958  1.15    kleink 	for (i = 0; i < nlinks; ++i) {
    959  1.15    kleink 		eat(links[i].l_filename, links[i].l_linenum);
    960  1.77  christos 		dolink(links[i].l_target, links[i].l_linkname, false);
    961  1.25   mlelstv 		if (noise)
    962  1.25   mlelstv 			for (j = 0; j < nlinks; ++j)
    963  1.77  christos 				if (strcmp(links[i].l_linkname,
    964  1.77  christos 					links[j].l_target) == 0)
    965  1.25   mlelstv 						warning(_("link to link"));
    966  1.15    kleink 	}
    967  1.15    kleink 	if (lcltime != NULL) {
    968  1.51  christos 		eat(_("command line"), 1);
    969  1.70  christos 		dolink(lcltime, tzdefault, true);
    970  1.15    kleink 	}
    971  1.15    kleink 	if (psxrules != NULL) {
    972  1.51  christos 		eat(_("command line"), 1);
    973  1.63  christos 		dolink(psxrules, TZDEFRULES, true);
    974  1.15    kleink 	}
    975  1.51  christos 	if (warnings && (ferror(stderr) || fclose(stderr) != 0))
    976  1.51  christos 	  return EXIT_FAILURE;
    977  1.51  christos 	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
    978   1.1       jtc }
    979   1.1       jtc 
    980  1.54  christos static bool
    981  1.47  christos componentcheck(char const *name, char const *component,
    982  1.47  christos 	       char const *component_end)
    983  1.47  christos {
    984  1.47  christos 	enum { component_len_max = 14 };
    985  1.65  christos 	ptrdiff_t component_len = component_end - component;
    986  1.53  christos 	if (component_len == 0) {
    987  1.54  christos 	  if (!*name)
    988  1.79  christos 	    error(_("empty file name"));
    989  1.54  christos 	  else
    990  1.79  christos 	    error(_(component == name
    991  1.54  christos 		     ? "file name '%s' begins with '/'"
    992  1.54  christos 		     : *component_end
    993  1.54  christos 		     ? "file name '%s' contains '//'"
    994  1.54  christos 		     : "file name '%s' ends with '/'"),
    995  1.54  christos 		   name);
    996  1.54  christos 	  return false;
    997  1.53  christos 	}
    998  1.47  christos 	if (0 < component_len && component_len <= 2
    999  1.47  christos 	    && component[0] == '.' && component_end[-1] == '.') {
   1000  1.65  christos 	  int len = component_len;
   1001  1.54  christos 	  error(_("file name '%s' contains '%.*s' component"),
   1002  1.65  christos 		name, len, component);
   1003  1.54  christos 	  return false;
   1004  1.54  christos 	}
   1005  1.54  christos 	if (noise) {
   1006  1.54  christos 	  if (0 < component_len && component[0] == '-')
   1007  1.54  christos 	    warning(_("file name '%s' component contains leading '-'"),
   1008  1.54  christos 		    name);
   1009  1.54  christos 	  if (component_len_max < component_len)
   1010  1.54  christos 	    warning(_("file name '%s' contains overlength component"
   1011  1.54  christos 		      " '%.*s...'"),
   1012  1.54  christos 		    name, component_len_max, component);
   1013  1.47  christos 	}
   1014  1.54  christos 	return true;
   1015  1.47  christos }
   1016  1.47  christos 
   1017  1.54  christos static bool
   1018  1.47  christos namecheck(const char *name)
   1019  1.47  christos {
   1020  1.47  christos 	char const *cp;
   1021  1.47  christos 
   1022  1.47  christos 	/* Benign characters in a portable file name.  */
   1023  1.47  christos 	static char const benign[] =
   1024  1.47  christos 	  "-/_"
   1025  1.47  christos 	  "abcdefghijklmnopqrstuvwxyz"
   1026  1.47  christos 	  "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   1027  1.47  christos 
   1028  1.47  christos 	/* Non-control chars in the POSIX portable character set,
   1029  1.47  christos 	   excluding the benign characters.  */
   1030  1.47  christos 	static char const printable_and_not_benign[] =
   1031  1.47  christos 	  " !\"#$%&'()*+,.0123456789:;<=>?@[\\]^`{|}~";
   1032  1.47  christos 
   1033  1.47  christos 	char const *component = name;
   1034  1.47  christos 	for (cp = name; *cp; cp++) {
   1035  1.47  christos 		unsigned char c = *cp;
   1036  1.47  christos 		if (noise && !strchr(benign, c)) {
   1037  1.47  christos 			warning((strchr(printable_and_not_benign, c)
   1038  1.47  christos 				 ? _("file name '%s' contains byte '%c'")
   1039  1.47  christos 				 : _("file name '%s' contains byte '\\%o'")),
   1040  1.47  christos 				name, c);
   1041  1.47  christos 		}
   1042  1.47  christos 		if (c == '/') {
   1043  1.54  christos 			if (!componentcheck(name, component, cp))
   1044  1.54  christos 			  return false;
   1045  1.47  christos 			component = cp + 1;
   1046  1.47  christos 		}
   1047  1.47  christos 	}
   1048  1.54  christos 	return componentcheck(name, component, cp);
   1049  1.47  christos }
   1050  1.47  christos 
   1051  1.79  christos /* Generate a randomish name in the same directory as *NAME.  If
   1052  1.79  christos    *NAMEALLOC, put the name into *NAMEALLOC which is assumed to be
   1053  1.79  christos    that returned by a previous call and is thus already almost set up
   1054  1.79  christos    and equal to *NAME; otherwise, allocate a new name and put its
   1055  1.79  christos    address into both *NAMEALLOC and *NAME.  */
   1056  1.79  christos static void
   1057  1.79  christos random_dirent(char const **name, char **namealloc)
   1058  1.79  christos {
   1059  1.79  christos   char const *src = *name;
   1060  1.79  christos   char *dst = *namealloc;
   1061  1.79  christos   static char const prefix[] = ".zic";
   1062  1.81  christos   static char const alphabet[] =
   1063  1.81  christos     "abcdefghijklmnopqrstuvwxyz"
   1064  1.81  christos     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   1065  1.81  christos     "0123456789";
   1066  1.79  christos   enum { prefixlen = sizeof prefix - 1, alphabetlen = sizeof alphabet - 1 };
   1067  1.79  christos   int suffixlen = 6;
   1068  1.79  christos   char const *lastslash = strrchr(src, '/');
   1069  1.79  christos   ptrdiff_t dirlen = lastslash ? lastslash + 1 - src : 0;
   1070  1.79  christos   static unsigned short initialized;
   1071  1.79  christos   int i;
   1072  1.79  christos 
   1073  1.79  christos   if (!dst) {
   1074  1.79  christos     dst = emalloc(dirlen + prefixlen + suffixlen + 1);
   1075  1.79  christos     memcpy(dst, src, dirlen);
   1076  1.79  christos     memcpy(dst + dirlen, prefix, prefixlen);
   1077  1.79  christos     dst[dirlen + prefixlen + suffixlen] = '\0';
   1078  1.79  christos     *name = *namealloc = dst;
   1079  1.79  christos   }
   1080  1.79  christos 
   1081  1.79  christos   /* This randomization is not the best, but is portable to C89.  */
   1082  1.79  christos   if (!initialized++) {
   1083  1.79  christos     unsigned now = time(NULL);
   1084  1.79  christos     srand(rand() ^ now);
   1085  1.79  christos   }
   1086  1.79  christos   for (i = 0; i < suffixlen; i++)
   1087  1.79  christos     dst[dirlen + prefixlen + i] = alphabet[rand() % alphabetlen];
   1088  1.79  christos }
   1089  1.79  christos 
   1090  1.79  christos /* Prepare to write to the file *OUTNAME, using *TEMPNAME to store the
   1091  1.79  christos    name of the temporary file that will eventually be renamed to
   1092  1.79  christos    *OUTNAME.  Assign the temporary file's name to both *OUTNAME and
   1093  1.79  christos    *TEMPNAME.  If *TEMPNAME is null, allocate the name of any such
   1094  1.79  christos    temporary file; otherwise, reuse *TEMPNAME's storage, which is
   1095  1.79  christos    already set up and only needs its trailing suffix updated.  */
   1096  1.79  christos static FILE *
   1097  1.79  christos open_outfile(char const **outname, char **tempname)
   1098  1.79  christos {
   1099  1.79  christos #if __STDC_VERSION__ < 201112
   1100  1.79  christos   static char const fopen_mode[] = "wb";
   1101  1.79  christos #else
   1102  1.79  christos   static char const fopen_mode[] = "wbx";
   1103  1.79  christos #endif
   1104  1.79  christos 
   1105  1.79  christos   FILE *fp;
   1106  1.79  christos   bool dirs_made = false;
   1107  1.79  christos   if (!*tempname)
   1108  1.79  christos     random_dirent(outname, tempname);
   1109  1.79  christos 
   1110  1.79  christos   while (! (fp = fopen(*outname, fopen_mode))) {
   1111  1.79  christos     int fopen_errno = errno;
   1112  1.79  christos     if (fopen_errno == ENOENT && !dirs_made) {
   1113  1.79  christos       mkdirs(*outname, true);
   1114  1.79  christos       dirs_made = true;
   1115  1.79  christos     } else if (fopen_errno == EEXIST)
   1116  1.79  christos       random_dirent(outname, tempname);
   1117  1.79  christos     else {
   1118  1.79  christos       fprintf(stderr, _("%s: Can't create %s/%s: %s\n"),
   1119  1.79  christos 	      progname, directory, *outname, strerror(fopen_errno));
   1120  1.79  christos       exit(EXIT_FAILURE);
   1121  1.79  christos     }
   1122  1.79  christos   }
   1123  1.79  christos 
   1124  1.79  christos   return fp;
   1125  1.79  christos }
   1126  1.79  christos 
   1127  1.79  christos /* If TEMPNAME, the result is in the temporary file TEMPNAME even
   1128  1.79  christos    though the user wanted it in NAME, so rename TEMPNAME to NAME.
   1129  1.79  christos    Report an error and exit if there is trouble.  Also, free TEMPNAME.  */
   1130  1.79  christos static void
   1131  1.79  christos rename_dest(char *tempname, char const *name)
   1132  1.79  christos {
   1133  1.79  christos   if (tempname) {
   1134  1.79  christos     if (rename(tempname, name) != 0) {
   1135  1.79  christos       int rename_errno = errno;
   1136  1.79  christos       remove(tempname);
   1137  1.79  christos       fprintf(stderr, _("%s: rename to %s/%s: %s\n"),
   1138  1.79  christos 	      progname, directory, name, strerror(rename_errno));
   1139  1.79  christos       exit(EXIT_FAILURE);
   1140  1.79  christos     }
   1141  1.79  christos     free(tempname);
   1142  1.79  christos   }
   1143  1.79  christos }
   1144  1.79  christos 
   1145  1.64       kre /* Create symlink contents suitable for symlinking FROM to TO, as a
   1146  1.64       kre    freshly allocated string.  FROM should be a relative file name, and
   1147  1.64       kre    is relative to the global variable DIRECTORY.  TO can be either
   1148  1.64       kre    relative or absolute.  */
   1149  1.64       kre static char *
   1150  1.77  christos relname(char const *target, char const *linkname)
   1151  1.64       kre {
   1152  1.64       kre   size_t i, taillen, dotdotetcsize;
   1153  1.64       kre   size_t dir_len = 0, dotdots = 0, linksize = SIZE_MAX;
   1154  1.77  christos   char const *f = target;
   1155  1.64       kre   char *result = NULL;
   1156  1.77  christos   if (*linkname == '/') {
   1157  1.64       kre     /* Make F absolute too.  */
   1158  1.64       kre     size_t len = strlen(directory);
   1159  1.64       kre     bool needslash = len && directory[len - 1] != '/';
   1160  1.77  christos     linksize = len + needslash + strlen(target) + 1;
   1161  1.64       kre     f = result = emalloc(linksize);
   1162  1.64       kre     strcpy(result, directory);
   1163  1.64       kre     result[len] = '/';
   1164  1.77  christos     strcpy(result + len + needslash, target);
   1165  1.64       kre   }
   1166  1.77  christos   for (i = 0; f[i] && f[i] == linkname[i]; i++)
   1167  1.64       kre     if (f[i] == '/')
   1168  1.64       kre       dir_len = i + 1;
   1169  1.77  christos   for (; linkname[i]; i++)
   1170  1.77  christos     dotdots += linkname[i] == '/' && linkname[i - 1] != '/';
   1171  1.68  christos   taillen = strlen(f + dir_len);
   1172  1.64       kre   dotdotetcsize = 3 * dotdots + taillen + 1;
   1173  1.64       kre   if (dotdotetcsize <= linksize) {
   1174  1.64       kre     if (!result)
   1175  1.64       kre       result = emalloc(dotdotetcsize);
   1176  1.64       kre     for (i = 0; i < dotdots; i++)
   1177  1.64       kre       memcpy(result + 3 * i, "../", 3);
   1178  1.64       kre     memmove(result + 3 * dotdots, f + dir_len, taillen + 1);
   1179  1.64       kre   }
   1180  1.64       kre   return result;
   1181  1.64       kre }
   1182  1.64       kre 
   1183  1.47  christos static void
   1184  1.77  christos dolink(char const *target, char const *linkname, bool staysymlink)
   1185   1.1       jtc {
   1186  1.77  christos 	bool linkdirs_made = false;
   1187  1.63  christos 	int link_errno;
   1188  1.79  christos 	char *tempname = NULL;
   1189  1.79  christos 	char const *outname = linkname;
   1190  1.79  christos 
   1191  1.79  christos 	check_for_signal();
   1192   1.1       jtc 
   1193  1.79  christos 	if (strcmp(target, "-") == 0) {
   1194  1.79  christos 	  if (remove(linkname) == 0 || errno == ENOENT || errno == ENOTDIR)
   1195  1.79  christos 	    return;
   1196  1.79  christos 	  else {
   1197  1.79  christos 	    char const *e = strerror(errno);
   1198  1.79  christos 	    fprintf(stderr, _("%s: Can't remove %s/%s: %s\n"),
   1199  1.79  christos 		    progname, directory, linkname, e);
   1200  1.79  christos 	    exit(EXIT_FAILURE);
   1201  1.79  christos 	  }
   1202  1.47  christos 	}
   1203  1.79  christos 
   1204  1.79  christos 	while (true) {
   1205  1.79  christos 	  if (linkat(AT_FDCWD, target, AT_FDCWD, outname, AT_SYMLINK_FOLLOW)
   1206  1.79  christos 	      == 0) {
   1207  1.79  christos 	    link_errno = 0;
   1208  1.79  christos 	    break;
   1209  1.79  christos 	  }
   1210  1.79  christos 	  link_errno = errno;
   1211  1.79  christos 	  if (link_errno == EXDEV || link_errno == ENOTSUP)
   1212  1.79  christos 	    break;
   1213  1.79  christos 
   1214  1.79  christos 	  if (link_errno == EEXIST) {
   1215  1.79  christos 	    staysymlink &= !tempname;
   1216  1.79  christos 	    random_dirent(&outname, &tempname);
   1217  1.79  christos 	    if (staysymlink && itssymlink(linkname))
   1218  1.79  christos 	      break;
   1219  1.79  christos 	  } else if (link_errno == ENOENT && !linkdirs_made) {
   1220  1.79  christos 	    mkdirs(linkname, true);
   1221  1.79  christos 	    linkdirs_made = true;
   1222  1.79  christos 	  } else {
   1223  1.79  christos 	    fprintf(stderr, _("%s: Can't link %s/%s to %s/%s: %s\n"),
   1224  1.79  christos 		    progname, directory, target, directory, outname,
   1225  1.79  christos 		    strerror(link_errno));
   1226  1.79  christos 	    exit(EXIT_FAILURE);
   1227  1.79  christos 	  }
   1228  1.63  christos 	}
   1229  1.63  christos 	if (link_errno != 0) {
   1230  1.77  christos 	  bool absolute = *target == '/';
   1231  1.77  christos 	  char *linkalloc = absolute ? NULL : relname(target, linkname);
   1232  1.77  christos 	  char const *contents = absolute ? target : linkalloc;
   1233  1.79  christos 	  int symlink_errno;
   1234  1.79  christos 
   1235  1.79  christos 	  while (true) {
   1236  1.79  christos 	    if (symlink(contents, outname) == 0) {
   1237  1.79  christos 	      symlink_errno = 0;
   1238  1.79  christos 	      break;
   1239  1.79  christos 	    }
   1240  1.79  christos 	    symlink_errno = errno;
   1241  1.79  christos 	    if (symlink_errno == EEXIST)
   1242  1.79  christos 	      random_dirent(&outname, &tempname);
   1243  1.79  christos 	    else if (symlink_errno == ENOENT && !linkdirs_made) {
   1244  1.79  christos 	      mkdirs(linkname, true);
   1245  1.79  christos 	      linkdirs_made = true;
   1246  1.79  christos 	    } else
   1247  1.79  christos 	      break;
   1248  1.63  christos 	  }
   1249  1.64       kre 	  free(linkalloc);
   1250  1.63  christos 	  if (symlink_errno == 0) {
   1251  1.79  christos 	    if (link_errno != ENOTSUP && link_errno != EEXIST)
   1252  1.63  christos 	      warning(_("symbolic link used because hard link failed: %s"),
   1253  1.63  christos 		      strerror(link_errno));
   1254  1.63  christos 	  } else {
   1255  1.63  christos 	    FILE *fp, *tp;
   1256  1.63  christos 	    int c;
   1257  1.77  christos 	    fp = fopen(target, "rb");
   1258  1.63  christos 	    if (!fp) {
   1259  1.63  christos 	      char const *e = strerror(errno);
   1260  1.63  christos 	      fprintf(stderr, _("%s: Can't read %s/%s: %s\n"),
   1261  1.77  christos 		      progname, directory, target, e);
   1262  1.63  christos 	      exit(EXIT_FAILURE);
   1263  1.63  christos 	    }
   1264  1.79  christos 	    tp = open_outfile(&outname, &tempname);
   1265  1.63  christos 	    while ((c = getc(fp)) != EOF)
   1266  1.63  christos 	      putc(c, tp);
   1267  1.79  christos 	    close_file(tp, directory, linkname, tempname);
   1268  1.79  christos 	    close_file(fp, directory, target, NULL);
   1269  1.63  christos 	    if (link_errno != ENOTSUP)
   1270  1.63  christos 	      warning(_("copy used because hard link failed: %s"),
   1271  1.63  christos 		      strerror(link_errno));
   1272  1.63  christos 	    else if (symlink_errno != ENOTSUP)
   1273  1.63  christos 	      warning(_("copy used because symbolic link failed: %s"),
   1274  1.63  christos 		      strerror(symlink_errno));
   1275  1.57  christos 	  }
   1276   1.1       jtc 	}
   1277  1.79  christos 	rename_dest(tempname, linkname);
   1278  1.68  christos }
   1279  1.68  christos 
   1280  1.68  christos /* Return true if NAME is a symbolic link.  */
   1281  1.68  christos static bool
   1282  1.68  christos itssymlink(char const *name)
   1283  1.68  christos {
   1284  1.68  christos   char c;
   1285  1.68  christos   return 0 <= readlink(name, &c, 1);
   1286   1.1       jtc }
   1287   1.1       jtc 
   1288   1.1       jtc /*
   1289   1.1       jtc ** Associate sets of rules with zones.
   1290   1.1       jtc */
   1291   1.1       jtc 
   1292   1.1       jtc /*
   1293   1.1       jtc ** Sort by rule name.
   1294   1.1       jtc */
   1295   1.1       jtc 
   1296   1.1       jtc static int
   1297  1.31  christos rcomp(const void *cp1, const void *cp2)
   1298   1.1       jtc {
   1299  1.79  christos   struct rule const *r1 = cp1, *r2 = cp2;
   1300  1.79  christos   return strcmp(r1->r_name, r2->r_name);
   1301   1.1       jtc }
   1302   1.1       jtc 
   1303   1.1       jtc static void
   1304  1.25   mlelstv associate(void)
   1305   1.1       jtc {
   1306  1.31  christos 	struct zone *	zp;
   1307  1.31  christos 	struct rule *	rp;
   1308  1.75  christos 	ptrdiff_t	i, j, base, out;
   1309   1.1       jtc 
   1310   1.5       jtc 	if (nrules != 0) {
   1311  1.57  christos 		qsort(rules, (size_t)nrules, sizeof *rules, rcomp);
   1312   1.5       jtc 		for (i = 0; i < nrules - 1; ++i) {
   1313   1.5       jtc 			if (strcmp(rules[i].r_name,
   1314   1.5       jtc 				rules[i + 1].r_name) != 0)
   1315   1.5       jtc 					continue;
   1316   1.5       jtc 			if (strcmp(rules[i].r_filename,
   1317   1.5       jtc 				rules[i + 1].r_filename) == 0)
   1318   1.5       jtc 					continue;
   1319   1.5       jtc 			eat(rules[i].r_filename, rules[i].r_linenum);
   1320   1.5       jtc 			warning(_("same rule name in multiple files"));
   1321   1.5       jtc 			eat(rules[i + 1].r_filename, rules[i + 1].r_linenum);
   1322   1.5       jtc 			warning(_("same rule name in multiple files"));
   1323   1.5       jtc 			for (j = i + 2; j < nrules; ++j) {
   1324   1.5       jtc 				if (strcmp(rules[i].r_name,
   1325   1.5       jtc 					rules[j].r_name) != 0)
   1326   1.5       jtc 						break;
   1327   1.5       jtc 				if (strcmp(rules[i].r_filename,
   1328   1.5       jtc 					rules[j].r_filename) == 0)
   1329   1.5       jtc 						continue;
   1330   1.5       jtc 				if (strcmp(rules[i + 1].r_filename,
   1331   1.5       jtc 					rules[j].r_filename) == 0)
   1332   1.5       jtc 						continue;
   1333   1.5       jtc 				break;
   1334   1.5       jtc 			}
   1335   1.5       jtc 			i = j - 1;
   1336   1.5       jtc 		}
   1337   1.5       jtc 	}
   1338   1.1       jtc 	for (i = 0; i < nzones; ++i) {
   1339   1.1       jtc 		zp = &zones[i];
   1340   1.1       jtc 		zp->z_rules = NULL;
   1341   1.1       jtc 		zp->z_nrules = 0;
   1342   1.1       jtc 	}
   1343   1.1       jtc 	for (base = 0; base < nrules; base = out) {
   1344   1.1       jtc 		rp = &rules[base];
   1345   1.1       jtc 		for (out = base + 1; out < nrules; ++out)
   1346   1.1       jtc 			if (strcmp(rp->r_name, rules[out].r_name) != 0)
   1347   1.1       jtc 				break;
   1348   1.1       jtc 		for (i = 0; i < nzones; ++i) {
   1349   1.1       jtc 			zp = &zones[i];
   1350   1.1       jtc 			if (strcmp(zp->z_rule, rp->r_name) != 0)
   1351   1.1       jtc 				continue;
   1352   1.1       jtc 			zp->z_rules = rp;
   1353   1.1       jtc 			zp->z_nrules = out - base;
   1354   1.1       jtc 		}
   1355   1.1       jtc 	}
   1356   1.1       jtc 	for (i = 0; i < nzones; ++i) {
   1357   1.1       jtc 		zp = &zones[i];
   1358   1.1       jtc 		if (zp->z_nrules == 0) {
   1359   1.1       jtc 			/*
   1360   1.1       jtc 			** Maybe we have a local standard time offset.
   1361   1.1       jtc 			*/
   1362   1.1       jtc 			eat(zp->z_filename, zp->z_linenum);
   1363  1.75  christos 			zp->z_save = getsave(zp->z_rule, &zp->z_isdst);
   1364   1.1       jtc 			/*
   1365   1.1       jtc 			** Note, though, that if there's no rule,
   1366   1.1       jtc 			** a '%s' in the format is a bad thing.
   1367   1.1       jtc 			*/
   1368  1.55  christos 			if (zp->z_format_specifier == 's')
   1369  1.43  christos 				error("%s", _("%s in ruleless zone"));
   1370   1.1       jtc 		}
   1371   1.1       jtc 	}
   1372   1.1       jtc 	if (errors)
   1373  1.25   mlelstv 		exit(EXIT_FAILURE);
   1374   1.1       jtc }
   1375   1.1       jtc 
   1376  1.82  christos /* Read a text line from FP into BUF, which is of size BUFSIZE.
   1377  1.82  christos    Terminate it with a NUL byte instead of a newline.
   1378  1.82  christos    Return the line's length, not counting the NUL byte.
   1379  1.82  christos    On EOF, return a negative number.
   1380  1.82  christos    On error, report the error and exit.  */
   1381  1.82  christos static ptrdiff_t
   1382  1.82  christos inputline(FILE *fp, char *buf, ptrdiff_t bufsize)
   1383  1.82  christos {
   1384  1.82  christos   ptrdiff_t linelen = 0, ch;
   1385  1.82  christos   while ((ch = getc(fp)) != '\n') {
   1386  1.82  christos     if (ch < 0) {
   1387  1.82  christos       if (ferror(fp)) {
   1388  1.82  christos 	error(_("input error"));
   1389  1.82  christos 	exit(EXIT_FAILURE);
   1390  1.82  christos       }
   1391  1.82  christos       if (linelen == 0)
   1392  1.82  christos 	return -1;
   1393  1.82  christos       error(_("unterminated line"));
   1394  1.82  christos       exit(EXIT_FAILURE);
   1395  1.82  christos     }
   1396  1.82  christos     if (!ch) {
   1397  1.82  christos       error(_("NUL input byte"));
   1398  1.82  christos       exit(EXIT_FAILURE);
   1399  1.82  christos     }
   1400  1.82  christos     buf[linelen++] = ch;
   1401  1.82  christos     if (linelen == bufsize) {
   1402  1.82  christos       error(_("line too long"));
   1403  1.82  christos       exit(EXIT_FAILURE);
   1404  1.82  christos     }
   1405  1.82  christos   }
   1406  1.82  christos   buf[linelen] = '\0';
   1407  1.82  christos   return linelen;
   1408  1.82  christos }
   1409  1.82  christos 
   1410   1.1       jtc static void
   1411  1.31  christos infile(const char *name)
   1412   1.1       jtc {
   1413  1.31  christos 	FILE *			fp;
   1414  1.31  christos 	const struct lookup *	lp;
   1415  1.51  christos 	bool			wantcont;
   1416  1.65  christos 	lineno			num;
   1417   1.1       jtc 
   1418   1.1       jtc 	if (strcmp(name, "-") == 0) {
   1419   1.5       jtc 		name = _("standard input");
   1420   1.1       jtc 		fp = stdin;
   1421   1.1       jtc 	} else if ((fp = fopen(name, "r")) == NULL) {
   1422   1.5       jtc 		const char *e = strerror(errno);
   1423   1.7       jtc 
   1424  1.51  christos 		fprintf(stderr, _("%s: Can't open %s: %s\n"),
   1425   1.5       jtc 			progname, name, e);
   1426  1.25   mlelstv 		exit(EXIT_FAILURE);
   1427   1.1       jtc 	}
   1428  1.51  christos 	wantcont = false;
   1429   1.1       jtc 	for (num = 1; ; ++num) {
   1430  1.82  christos 		ptrdiff_t linelen;
   1431  1.82  christos 		char buf[_POSIX2_LINE_MAX];
   1432  1.82  christos 		int nfields;
   1433  1.82  christos 		char *fields[MAX_FIELDS];
   1434   1.1       jtc 		eat(name, num);
   1435  1.82  christos 		linelen = inputline(fp, buf, sizeof buf);
   1436  1.82  christos 		if (linelen < 0)
   1437  1.82  christos 		  break;
   1438  1.82  christos 		nfields = getfields(buf, fields,
   1439  1.82  christos 				    sizeof fields / sizeof *fields);
   1440   1.1       jtc 		if (nfields == 0) {
   1441  1.79  christos 			/* nothing to do */
   1442   1.1       jtc 		} else if (wantcont) {
   1443   1.1       jtc 			wantcont = inzcont(fields, nfields);
   1444   1.1       jtc 		} else {
   1445  1.69  christos 			struct lookup const *line_codes
   1446  1.69  christos 			  = name == leapsec ? leap_line_codes : zi_line_codes;
   1447   1.1       jtc 			lp = byword(fields[0], line_codes);
   1448   1.1       jtc 			if (lp == NULL)
   1449   1.5       jtc 				error(_("input line of unknown type"));
   1450  1.65  christos 			else switch (lp->l_value) {
   1451   1.1       jtc 				case LC_RULE:
   1452   1.1       jtc 					inrule(fields, nfields);
   1453  1.51  christos 					wantcont = false;
   1454   1.1       jtc 					break;
   1455   1.1       jtc 				case LC_ZONE:
   1456   1.1       jtc 					wantcont = inzone(fields, nfields);
   1457   1.1       jtc 					break;
   1458   1.1       jtc 				case LC_LINK:
   1459   1.1       jtc 					inlink(fields, nfields);
   1460  1.51  christos 					wantcont = false;
   1461   1.1       jtc 					break;
   1462   1.1       jtc 				case LC_LEAP:
   1463  1.69  christos 					inleap(fields, nfields);
   1464  1.51  christos 					wantcont = false;
   1465   1.1       jtc 					break;
   1466  1.76  christos 				case LC_EXPIRES:
   1467  1.76  christos 					inexpires(fields, nfields);
   1468  1.76  christos 					wantcont = false;
   1469  1.76  christos 					break;
   1470  1.79  christos 				default: UNREACHABLE();
   1471   1.1       jtc 			}
   1472   1.1       jtc 		}
   1473   1.1       jtc 	}
   1474  1.79  christos 	close_file(fp, NULL, filename, NULL);
   1475   1.1       jtc 	if (wantcont)
   1476   1.5       jtc 		error(_("expected continuation line not found"));
   1477   1.1       jtc }
   1478   1.1       jtc 
   1479   1.1       jtc /*
   1480   1.1       jtc ** Convert a string of one of the forms
   1481   1.1       jtc **	h	-h	hh:mm	-hh:mm	hh:mm:ss	-hh:mm:ss
   1482   1.1       jtc ** into a number of seconds.
   1483   1.1       jtc ** A null string maps to zero.
   1484   1.1       jtc ** Call error with errstring and return zero on errors.
   1485   1.1       jtc */
   1486   1.1       jtc 
   1487  1.38  christos static zic_t
   1488  1.74  christos gethms(char const *string, char const *errstring)
   1489   1.1       jtc {
   1490  1.38  christos 	zic_t	hh;
   1491  1.71  christos 	int sign, mm = 0, ss = 0;
   1492  1.71  christos 	char hhx, mmx, ssx, xr = '0', xs;
   1493  1.71  christos 	int tenths = 0;
   1494  1.71  christos 	bool ok = true;
   1495   1.1       jtc 
   1496   1.1       jtc 	if (string == NULL || *string == '\0')
   1497   1.1       jtc 		return 0;
   1498  1.74  christos 	if (*string == '-') {
   1499   1.1       jtc 		sign = -1;
   1500   1.1       jtc 		++string;
   1501   1.1       jtc 	} else	sign = 1;
   1502  1.71  christos 	switch (sscanf(string,
   1503  1.71  christos 		       "%"SCNdZIC"%c%d%c%d%c%1d%*[0]%c%*[0123456789]%c",
   1504  1.71  christos 		       &hh, &hhx, &mm, &mmx, &ss, &ssx, &tenths, &xr, &xs)) {
   1505  1.71  christos 	  default: ok = false; break;
   1506  1.71  christos 	  case 8:
   1507  1.71  christos 	    ok = '0' <= xr && xr <= '9';
   1508  1.71  christos 	    /* fallthrough */
   1509  1.71  christos 	  case 7:
   1510  1.71  christos 	    ok &= ssx == '.';
   1511  1.71  christos 	    if (ok && noise)
   1512  1.71  christos 	      warning(_("fractional seconds rejected by"
   1513  1.71  christos 			" pre-2018 versions of zic"));
   1514  1.71  christos 	    /* fallthrough */
   1515  1.71  christos 	  case 5: ok &= mmx == ':'; /* fallthrough */
   1516  1.71  christos 	  case 3: ok &= hhx == ':'; /* fallthrough */
   1517  1.71  christos 	  case 1: break;
   1518  1.71  christos 	}
   1519  1.71  christos 	if (!ok) {
   1520  1.43  christos 			error("%s", errstring);
   1521   1.1       jtc 			return 0;
   1522   1.1       jtc 	}
   1523  1.25   mlelstv 	if (hh < 0 ||
   1524   1.1       jtc 		mm < 0 || mm >= MINSPERHOUR ||
   1525  1.25   mlelstv 		ss < 0 || ss > SECSPERMIN) {
   1526  1.43  christos 			error("%s", errstring);
   1527   1.1       jtc 			return 0;
   1528   1.1       jtc 	}
   1529  1.41  christos 	if (ZIC_MAX / SECSPERHOUR < hh) {
   1530  1.25   mlelstv 		error(_("time overflow"));
   1531  1.25   mlelstv 		return 0;
   1532  1.25   mlelstv 	}
   1533  1.71  christos 	ss += 5 + ((ss ^ 1) & (xr == '0')) <= tenths; /* Round to even.  */
   1534  1.25   mlelstv 	if (noise && (hh > HOURSPERDAY ||
   1535  1.25   mlelstv 		(hh == HOURSPERDAY && (mm != 0 || ss != 0))))
   1536  1.25   mlelstv warning(_("values over 24 hours not handled by pre-2007 versions of zic"));
   1537  1.41  christos 	return oadd(sign * hh * SECSPERHOUR,
   1538  1.41  christos 		    sign * (mm * SECSPERMIN + ss));
   1539   1.1       jtc }
   1540   1.1       jtc 
   1541  1.71  christos static zic_t
   1542  1.75  christos getsave(char *field, bool *isdst)
   1543  1.71  christos {
   1544  1.71  christos   int dst = -1;
   1545  1.75  christos   zic_t save;
   1546  1.71  christos   size_t fieldlen = strlen(field);
   1547  1.71  christos   if (fieldlen != 0) {
   1548  1.71  christos     char *ep = field + fieldlen - 1;
   1549  1.71  christos     switch (*ep) {
   1550  1.71  christos       case 'd': dst = 1; *ep = '\0'; break;
   1551  1.71  christos       case 's': dst = 0; *ep = '\0'; break;
   1552  1.71  christos     }
   1553  1.71  christos   }
   1554  1.75  christos   save = gethms(field, _("invalid saved time"));
   1555  1.75  christos   *isdst = dst < 0 ? save != 0 : dst;
   1556  1.75  christos   return save;
   1557  1.71  christos }
   1558  1.71  christos 
   1559   1.1       jtc static void
   1560  1.55  christos inrule(char **fields, int nfields)
   1561   1.1       jtc {
   1562  1.79  christos 	struct rule r;
   1563   1.1       jtc 
   1564   1.1       jtc 	if (nfields != RULE_FIELDS) {
   1565   1.5       jtc 		error(_("wrong number of fields on Rule line"));
   1566   1.1       jtc 		return;
   1567   1.1       jtc 	}
   1568  1.74  christos 	switch (*fields[RF_NAME]) {
   1569  1.74  christos 	  case '\0':
   1570  1.74  christos 	  case ' ': case '\f': case '\n': case '\r': case '\t': case '\v':
   1571  1.74  christos 	  case '+': case '-':
   1572  1.74  christos 	  case '0': case '1': case '2': case '3': case '4':
   1573  1.74  christos 	  case '5': case '6': case '7': case '8': case '9':
   1574  1.74  christos 		error(_("Invalid rule name \"%s\""), fields[RF_NAME]);
   1575   1.1       jtc 		return;
   1576   1.1       jtc 	}
   1577   1.1       jtc 	r.r_filename = filename;
   1578   1.1       jtc 	r.r_linenum = linenum;
   1579  1.75  christos 	r.r_save = getsave(fields[RF_SAVE], &r.r_isdst);
   1580  1.79  christos 	if (!rulesub(&r, fields[RF_LOYEAR], fields[RF_HIYEAR],
   1581  1.79  christos 		     fields[RF_COMMAND], fields[RF_MONTH], fields[RF_DAY],
   1582  1.79  christos 		     fields[RF_TOD]))
   1583  1.79  christos 	  return;
   1584   1.1       jtc 	r.r_name = ecpyalloc(fields[RF_NAME]);
   1585   1.1       jtc 	r.r_abbrvar = ecpyalloc(fields[RF_ABBRVAR]);
   1586  1.25   mlelstv 	if (max_abbrvar_len < strlen(r.r_abbrvar))
   1587  1.25   mlelstv 		max_abbrvar_len = strlen(r.r_abbrvar);
   1588  1.45  christos 	rules = growalloc(rules, sizeof *rules, nrules, &nrules_alloc);
   1589   1.1       jtc 	rules[nrules++] = r;
   1590   1.1       jtc }
   1591   1.1       jtc 
   1592  1.51  christos static bool
   1593  1.55  christos inzone(char **fields, int nfields)
   1594   1.1       jtc {
   1595  1.65  christos 	ptrdiff_t	i;
   1596   1.1       jtc 
   1597   1.1       jtc 	if (nfields < ZONE_MINFIELDS || nfields > ZONE_MAXFIELDS) {
   1598   1.5       jtc 		error(_("wrong number of fields on Zone line"));
   1599  1.51  christos 		return false;
   1600   1.1       jtc 	}
   1601  1.70  christos 	if (lcltime != NULL && strcmp(fields[ZF_NAME], tzdefault) == 0) {
   1602  1.43  christos 		error(
   1603   1.5       jtc _("\"Zone %s\" line and -l option are mutually exclusive"),
   1604  1.70  christos 			tzdefault);
   1605  1.51  christos 		return false;
   1606   1.1       jtc 	}
   1607   1.1       jtc 	if (strcmp(fields[ZF_NAME], TZDEFRULES) == 0 && psxrules != NULL) {
   1608  1.43  christos 		error(
   1609   1.5       jtc _("\"Zone %s\" line and -p option are mutually exclusive"),
   1610   1.1       jtc 			TZDEFRULES);
   1611  1.51  christos 		return false;
   1612   1.1       jtc 	}
   1613   1.1       jtc 	for (i = 0; i < nzones; ++i)
   1614   1.1       jtc 		if (zones[i].z_name != NULL &&
   1615  1.65  christos 		    strcmp(zones[i].z_name, fields[ZF_NAME]) == 0) {
   1616  1.65  christos 			error(_("duplicate zone name %s"
   1617  1.69  christos 				" (file \"%s\", line %"PRIdMAX")"),
   1618  1.65  christos 				fields[ZF_NAME],
   1619  1.65  christos 				zones[i].z_filename,
   1620  1.65  christos 				zones[i].z_linenum);
   1621  1.65  christos 			return false;
   1622   1.1       jtc 		}
   1623  1.51  christos 	return inzsub(fields, nfields, false);
   1624   1.1       jtc }
   1625   1.1       jtc 
   1626  1.51  christos static bool
   1627  1.55  christos inzcont(char **fields, int nfields)
   1628   1.1       jtc {
   1629   1.1       jtc 	if (nfields < ZONEC_MINFIELDS || nfields > ZONEC_MAXFIELDS) {
   1630   1.5       jtc 		error(_("wrong number of fields on Zone continuation line"));
   1631  1.51  christos 		return false;
   1632   1.1       jtc 	}
   1633  1.51  christos 	return inzsub(fields, nfields, true);
   1634   1.1       jtc }
   1635   1.1       jtc 
   1636  1.51  christos static bool
   1637  1.74  christos inzsub(char **fields, int nfields, bool iscont)
   1638   1.1       jtc {
   1639  1.31  christos 	char *		cp;
   1640  1.55  christos 	char *		cp1;
   1641  1.79  christos 	struct zone	z;
   1642  1.79  christos 	size_t format_len;
   1643  1.75  christos 	int		i_stdoff, i_rule, i_format;
   1644  1.31  christos 	int		i_untilyear, i_untilmonth;
   1645  1.31  christos 	int		i_untilday, i_untiltime;
   1646  1.51  christos 	bool		hasuntil;
   1647   1.1       jtc 
   1648   1.1       jtc 	if (iscont) {
   1649  1.75  christos 		i_stdoff = ZFC_STDOFF;
   1650   1.1       jtc 		i_rule = ZFC_RULE;
   1651   1.1       jtc 		i_format = ZFC_FORMAT;
   1652   1.1       jtc 		i_untilyear = ZFC_TILYEAR;
   1653   1.1       jtc 		i_untilmonth = ZFC_TILMONTH;
   1654   1.1       jtc 		i_untilday = ZFC_TILDAY;
   1655   1.1       jtc 		i_untiltime = ZFC_TILTIME;
   1656  1.54  christos 	} else if (!namecheck(fields[ZF_NAME]))
   1657  1.54  christos 		return false;
   1658  1.54  christos 	else {
   1659  1.75  christos 		i_stdoff = ZF_STDOFF;
   1660   1.1       jtc 		i_rule = ZF_RULE;
   1661   1.1       jtc 		i_format = ZF_FORMAT;
   1662   1.1       jtc 		i_untilyear = ZF_TILYEAR;
   1663   1.1       jtc 		i_untilmonth = ZF_TILMONTH;
   1664   1.1       jtc 		i_untilday = ZF_TILDAY;
   1665   1.1       jtc 		i_untiltime = ZF_TILTIME;
   1666   1.1       jtc 	}
   1667   1.1       jtc 	z.z_filename = filename;
   1668   1.1       jtc 	z.z_linenum = linenum;
   1669  1.75  christos 	z.z_stdoff = gethms(fields[i_stdoff], _("invalid UT offset"));
   1670   1.1       jtc 	if ((cp = strchr(fields[i_format], '%')) != 0) {
   1671  1.55  christos 		if ((*++cp != 's' && *cp != 'z') || strchr(cp, '%')
   1672  1.55  christos 		    || strchr(fields[i_format], '/')) {
   1673   1.5       jtc 			error(_("invalid abbreviation format"));
   1674  1.51  christos 			return false;
   1675   1.1       jtc 		}
   1676   1.1       jtc 	}
   1677  1.55  christos 	z.z_format_specifier = cp ? *cp : '\0';
   1678  1.79  christos 	format_len = strlen(fields[i_format]);
   1679  1.79  christos 	if (max_format_len < format_len)
   1680  1.79  christos 	  max_format_len = format_len;
   1681   1.1       jtc 	hasuntil = nfields > i_untilyear;
   1682   1.1       jtc 	if (hasuntil) {
   1683   1.1       jtc 		z.z_untilrule.r_filename = filename;
   1684   1.1       jtc 		z.z_untilrule.r_linenum = linenum;
   1685  1.79  christos 		if (!rulesub(
   1686  1.79  christos 			&z.z_untilrule,
   1687   1.1       jtc 			fields[i_untilyear],
   1688   1.1       jtc 			"only",
   1689   1.1       jtc 			"",
   1690   1.1       jtc 			(nfields > i_untilmonth) ?
   1691   1.1       jtc 			fields[i_untilmonth] : "Jan",
   1692   1.1       jtc 			(nfields > i_untilday) ? fields[i_untilday] : "1",
   1693  1.79  christos 			(nfields > i_untiltime) ? fields[i_untiltime] : "0"))
   1694  1.79  christos 		  return false;
   1695   1.1       jtc 		z.z_untiltime = rpytime(&z.z_untilrule,
   1696   1.1       jtc 			z.z_untilrule.r_loyear);
   1697   1.1       jtc 		if (iscont && nzones > 0 &&
   1698   1.1       jtc 			z.z_untiltime > min_time &&
   1699   1.1       jtc 			z.z_untiltime < max_time &&
   1700   1.1       jtc 			zones[nzones - 1].z_untiltime > min_time &&
   1701   1.1       jtc 			zones[nzones - 1].z_untiltime < max_time &&
   1702   1.1       jtc 			zones[nzones - 1].z_untiltime >= z.z_untiltime) {
   1703  1.25   mlelstv 				error(_(
   1704  1.25   mlelstv "Zone continuation line end time is not after end time of previous line"
   1705  1.25   mlelstv 					));
   1706  1.51  christos 				return false;
   1707   1.1       jtc 		}
   1708   1.1       jtc 	}
   1709  1.79  christos 	z.z_name = iscont ? NULL : ecpyalloc(fields[ZF_NAME]);
   1710  1.79  christos 	z.z_rule = ecpyalloc(fields[i_rule]);
   1711  1.79  christos 	z.z_format = cp1 = ecpyalloc(fields[i_format]);
   1712  1.79  christos 	if (z.z_format_specifier == 'z') {
   1713  1.79  christos 	  cp1[cp - fields[i_format]] = 's';
   1714  1.79  christos 	  if (noise)
   1715  1.79  christos 	    warning(_("format '%s' not handled by pre-2015 versions of zic"),
   1716  1.79  christos 		    fields[i_format]);
   1717  1.79  christos 	}
   1718  1.45  christos 	zones = growalloc(zones, sizeof *zones, nzones, &nzones_alloc);
   1719   1.1       jtc 	zones[nzones++] = z;
   1720   1.1       jtc 	/*
   1721   1.1       jtc 	** If there was an UNTIL field on this line,
   1722   1.1       jtc 	** there's more information about the zone on the next line.
   1723   1.1       jtc 	*/
   1724   1.1       jtc 	return hasuntil;
   1725   1.1       jtc }
   1726   1.1       jtc 
   1727  1.76  christos static zic_t
   1728  1.76  christos getleapdatetime(char **fields, int nfields, bool expire_line)
   1729  1.31  christos {
   1730  1.31  christos 	const char *		cp;
   1731  1.31  christos 	const struct lookup *	lp;
   1732  1.65  christos 	zic_t			i, j;
   1733  1.41  christos 	zic_t			year;
   1734  1.41  christos 	int			month, day;
   1735  1.41  christos 	zic_t			dayoff, tod;
   1736  1.41  christos 	zic_t			t;
   1737  1.53  christos 	char			xs;
   1738   1.1       jtc 
   1739   1.1       jtc 	dayoff = 0;
   1740   1.1       jtc 	cp = fields[LP_YEAR];
   1741  1.53  christos 	if (sscanf(cp, "%"SCNdZIC"%c", &year, &xs) != 1) {
   1742  1.25   mlelstv 		/*
   1743  1.25   mlelstv 		** Leapin' Lizards!
   1744  1.25   mlelstv 		*/
   1745  1.25   mlelstv 		error(_("invalid leaping year"));
   1746  1.76  christos 		return -1;
   1747   1.1       jtc 	}
   1748  1.76  christos 	if (!expire_line) {
   1749  1.76  christos 	    if (!leapseen || leapmaxyear < year)
   1750  1.25   mlelstv 		leapmaxyear = year;
   1751  1.76  christos 	    if (!leapseen || leapminyear > year)
   1752  1.25   mlelstv 		leapminyear = year;
   1753  1.76  christos 	    leapseen = true;
   1754  1.76  christos 	}
   1755   1.1       jtc 	j = EPOCH_YEAR;
   1756   1.1       jtc 	while (j != year) {
   1757   1.1       jtc 		if (year > j) {
   1758   1.1       jtc 			i = len_years[isleap(j)];
   1759   1.1       jtc 			++j;
   1760   1.1       jtc 		} else {
   1761   1.1       jtc 			--j;
   1762   1.1       jtc 			i = -len_years[isleap(j)];
   1763   1.1       jtc 		}
   1764  1.41  christos 		dayoff = oadd(dayoff, i);
   1765   1.1       jtc 	}
   1766   1.1       jtc 	if ((lp = byword(fields[LP_MONTH], mon_names)) == NULL) {
   1767   1.5       jtc 		error(_("invalid month name"));
   1768  1.76  christos 		return -1;
   1769   1.1       jtc 	}
   1770   1.1       jtc 	month = lp->l_value;
   1771   1.1       jtc 	j = TM_JANUARY;
   1772   1.1       jtc 	while (j != month) {
   1773   1.1       jtc 		i = len_months[isleap(year)][j];
   1774  1.41  christos 		dayoff = oadd(dayoff, i);
   1775   1.1       jtc 		++j;
   1776   1.1       jtc 	}
   1777   1.1       jtc 	cp = fields[LP_DAY];
   1778  1.53  christos 	if (sscanf(cp, "%d%c", &day, &xs) != 1 ||
   1779   1.1       jtc 		day <= 0 || day > len_months[isleap(year)][month]) {
   1780   1.5       jtc 			error(_("invalid day of month"));
   1781  1.76  christos 			return -1;
   1782   1.1       jtc 	}
   1783  1.41  christos 	dayoff = oadd(dayoff, day - 1);
   1784  1.34    martin 	if (dayoff < min_time / SECSPERDAY) {
   1785  1.20    kleink 		error(_("time too small"));
   1786  1.76  christos 		return -1;
   1787  1.20    kleink 	}
   1788  1.34    martin 	if (dayoff > max_time / SECSPERDAY) {
   1789  1.20    kleink 		error(_("time too large"));
   1790  1.76  christos 		return -1;
   1791   1.1       jtc 	}
   1792  1.46  christos 	t = dayoff * SECSPERDAY;
   1793  1.74  christos 	tod = gethms(fields[LP_TIME], _("invalid time of day"));
   1794  1.76  christos 	t = tadd(t, tod);
   1795  1.76  christos 	if (t < 0)
   1796  1.76  christos 	  error(_("leap second precedes Epoch"));
   1797  1.76  christos 	return t;
   1798  1.76  christos }
   1799  1.76  christos 
   1800  1.76  christos static void
   1801  1.76  christos inleap(char **fields, int nfields)
   1802  1.76  christos {
   1803  1.76  christos   if (nfields != LEAP_FIELDS)
   1804  1.76  christos     error(_("wrong number of fields on Leap line"));
   1805  1.76  christos   else {
   1806  1.76  christos     zic_t t = getleapdatetime(fields, nfields, false);
   1807  1.76  christos     if (0 <= t) {
   1808  1.76  christos       struct lookup const *lp = byword(fields[LP_ROLL], leap_types);
   1809  1.76  christos       if (!lp)
   1810  1.76  christos 	error(_("invalid Rolling/Stationary field on Leap line"));
   1811  1.76  christos       else {
   1812  1.76  christos 	int correction = 0;
   1813  1.76  christos 	if (!fields[LP_CORR][0]) /* infile() turns "-" into "".  */
   1814  1.76  christos 	  correction = -1;
   1815  1.76  christos 	else if (strcmp(fields[LP_CORR], "+") == 0)
   1816  1.76  christos 	  correction = 1;
   1817  1.76  christos 	else
   1818  1.76  christos 	  error(_("invalid CORRECTION field on Leap line"));
   1819  1.76  christos 	if (correction)
   1820  1.76  christos 	  leapadd(t, correction, lp->l_value);
   1821  1.76  christos       }
   1822  1.76  christos     }
   1823  1.76  christos   }
   1824  1.76  christos }
   1825   1.1       jtc 
   1826  1.76  christos static void
   1827  1.76  christos inexpires(char **fields, int nfields)
   1828  1.76  christos {
   1829  1.76  christos   if (nfields != EXPIRES_FIELDS)
   1830  1.76  christos     error(_("wrong number of fields on Expires line"));
   1831  1.76  christos   else if (0 <= leapexpires)
   1832  1.76  christos     error(_("multiple Expires lines"));
   1833  1.76  christos   else
   1834  1.76  christos     leapexpires = getleapdatetime(fields, nfields, true);
   1835   1.1       jtc }
   1836   1.1       jtc 
   1837   1.1       jtc static void
   1838  1.57  christos inlink(char **fields, int nfields)
   1839   1.1       jtc {
   1840   1.1       jtc 	struct link	l;
   1841   1.1       jtc 
   1842   1.1       jtc 	if (nfields != LINK_FIELDS) {
   1843   1.5       jtc 		error(_("wrong number of fields on Link line"));
   1844   1.1       jtc 		return;
   1845   1.1       jtc 	}
   1846  1.77  christos 	if (*fields[LF_TARGET] == '\0') {
   1847  1.77  christos 		error(_("blank TARGET field on Link line"));
   1848   1.1       jtc 		return;
   1849   1.1       jtc 	}
   1850  1.77  christos 	if (! namecheck(fields[LF_LINKNAME]))
   1851  1.54  christos 	  return;
   1852   1.1       jtc 	l.l_filename = filename;
   1853   1.1       jtc 	l.l_linenum = linenum;
   1854  1.77  christos 	l.l_target = ecpyalloc(fields[LF_TARGET]);
   1855  1.77  christos 	l.l_linkname = ecpyalloc(fields[LF_LINKNAME]);
   1856  1.45  christos 	links = growalloc(links, sizeof *links, nlinks, &nlinks_alloc);
   1857   1.1       jtc 	links[nlinks++] = l;
   1858   1.1       jtc }
   1859   1.1       jtc 
   1860  1.79  christos static bool
   1861  1.55  christos rulesub(struct rule *rp, const char *loyearp, const char *hiyearp,
   1862  1.55  christos     const char *typep, const char *monthp, const char *dayp,
   1863  1.55  christos     const char *timep)
   1864  1.31  christos {
   1865  1.31  christos 	const struct lookup *	lp;
   1866  1.31  christos 	const char *		cp;
   1867  1.31  christos 	char *			dp;
   1868  1.31  christos 	char *			ep;
   1869  1.53  christos 	char			xs;
   1870   1.1       jtc 
   1871   1.1       jtc 	if ((lp = byword(monthp, mon_names)) == NULL) {
   1872   1.5       jtc 		error(_("invalid month name"));
   1873  1.79  christos 		return false;
   1874   1.1       jtc 	}
   1875   1.1       jtc 	rp->r_month = lp->l_value;
   1876  1.51  christos 	rp->r_todisstd = false;
   1877  1.75  christos 	rp->r_todisut = false;
   1878   1.1       jtc 	dp = ecpyalloc(timep);
   1879   1.1       jtc 	if (*dp != '\0') {
   1880   1.1       jtc 		ep = dp + strlen(dp) - 1;
   1881   1.1       jtc 		switch (lowerit(*ep)) {
   1882   1.1       jtc 			case 's':	/* Standard */
   1883  1.51  christos 				rp->r_todisstd = true;
   1884  1.75  christos 				rp->r_todisut = false;
   1885   1.1       jtc 				*ep = '\0';
   1886   1.1       jtc 				break;
   1887   1.1       jtc 			case 'w':	/* Wall */
   1888  1.51  christos 				rp->r_todisstd = false;
   1889  1.75  christos 				rp->r_todisut = false;
   1890   1.1       jtc 				*ep = '\0';
   1891   1.7       jtc 				break;
   1892   1.1       jtc 			case 'g':	/* Greenwich */
   1893   1.1       jtc 			case 'u':	/* Universal */
   1894   1.1       jtc 			case 'z':	/* Zulu */
   1895  1.51  christos 				rp->r_todisstd = true;
   1896  1.75  christos 				rp->r_todisut = true;
   1897   1.1       jtc 				*ep = '\0';
   1898   1.1       jtc 				break;
   1899   1.1       jtc 		}
   1900   1.1       jtc 	}
   1901  1.74  christos 	rp->r_tod = gethms(dp, _("invalid time of day"));
   1902  1.31  christos 	free(dp);
   1903   1.1       jtc 	/*
   1904   1.1       jtc 	** Year work.
   1905   1.1       jtc 	*/
   1906   1.1       jtc 	cp = loyearp;
   1907   1.1       jtc 	lp = byword(cp, begin_years);
   1908  1.25   mlelstv 	rp->r_lowasnum = lp == NULL;
   1909  1.65  christos 	if (!rp->r_lowasnum) switch (lp->l_value) {
   1910   1.1       jtc 		case YR_MINIMUM:
   1911  1.41  christos 			rp->r_loyear = ZIC_MIN;
   1912   1.1       jtc 			break;
   1913   1.1       jtc 		case YR_MAXIMUM:
   1914  1.41  christos 			rp->r_loyear = ZIC_MAX;
   1915   1.1       jtc 			break;
   1916  1.79  christos 		default: UNREACHABLE();
   1917  1.53  christos 	} else if (sscanf(cp, "%"SCNdZIC"%c", &rp->r_loyear, &xs) != 1) {
   1918   1.5       jtc 		error(_("invalid starting year"));
   1919  1.79  christos 		return false;
   1920  1.11       jtc 	}
   1921   1.1       jtc 	cp = hiyearp;
   1922  1.25   mlelstv 	lp = byword(cp, end_years);
   1923  1.25   mlelstv 	rp->r_hiwasnum = lp == NULL;
   1924  1.65  christos 	if (!rp->r_hiwasnum) switch (lp->l_value) {
   1925   1.1       jtc 		case YR_MINIMUM:
   1926  1.41  christos 			rp->r_hiyear = ZIC_MIN;
   1927   1.1       jtc 			break;
   1928   1.1       jtc 		case YR_MAXIMUM:
   1929  1.41  christos 			rp->r_hiyear = ZIC_MAX;
   1930   1.1       jtc 			break;
   1931   1.1       jtc 		case YR_ONLY:
   1932   1.1       jtc 			rp->r_hiyear = rp->r_loyear;
   1933   1.1       jtc 			break;
   1934  1.79  christos 		default: UNREACHABLE();
   1935  1.53  christos 	} else if (sscanf(cp, "%"SCNdZIC"%c", &rp->r_hiyear, &xs) != 1) {
   1936   1.5       jtc 		error(_("invalid ending year"));
   1937  1.79  christos 		return false;
   1938  1.11       jtc 	}
   1939   1.1       jtc 	if (rp->r_loyear > rp->r_hiyear) {
   1940   1.5       jtc 		error(_("starting year greater than ending year"));
   1941  1.79  christos 		return false;
   1942   1.1       jtc 	}
   1943  1.77  christos 	if (*typep != '\0') {
   1944  1.77  christos 		error(_("year type \"%s\" is unsupported; use \"-\" instead"),
   1945  1.69  christos 			typep);
   1946  1.79  christos 		return false;
   1947   1.1       jtc 	}
   1948   1.1       jtc 	/*
   1949   1.1       jtc 	** Day work.
   1950   1.1       jtc 	** Accept things such as:
   1951   1.1       jtc 	**	1
   1952  1.69  christos 	**	lastSunday
   1953  1.69  christos 	**	last-Sunday (undocumented; warn about this)
   1954   1.1       jtc 	**	Sun<=20
   1955   1.1       jtc 	**	Sun>=7
   1956   1.1       jtc 	*/
   1957   1.1       jtc 	dp = ecpyalloc(dayp);
   1958   1.1       jtc 	if ((lp = byword(dp, lasts)) != NULL) {
   1959   1.1       jtc 		rp->r_dycode = DC_DOWLEQ;
   1960   1.1       jtc 		rp->r_wday = lp->l_value;
   1961   1.1       jtc 		rp->r_dayofmonth = len_months[1][rp->r_month];
   1962   1.1       jtc 	} else {
   1963   1.1       jtc 		if ((ep = strchr(dp, '<')) != 0)
   1964   1.1       jtc 			rp->r_dycode = DC_DOWLEQ;
   1965   1.1       jtc 		else if ((ep = strchr(dp, '>')) != 0)
   1966   1.1       jtc 			rp->r_dycode = DC_DOWGEQ;
   1967   1.1       jtc 		else {
   1968   1.1       jtc 			ep = dp;
   1969   1.1       jtc 			rp->r_dycode = DC_DOM;
   1970   1.1       jtc 		}
   1971   1.1       jtc 		if (rp->r_dycode != DC_DOM) {
   1972   1.1       jtc 			*ep++ = 0;
   1973   1.1       jtc 			if (*ep++ != '=') {
   1974   1.5       jtc 				error(_("invalid day of month"));
   1975  1.31  christos 				free(dp);
   1976  1.79  christos 				return false;
   1977   1.1       jtc 			}
   1978   1.1       jtc 			if ((lp = byword(dp, wday_names)) == NULL) {
   1979   1.5       jtc 				error(_("invalid weekday name"));
   1980  1.31  christos 				free(dp);
   1981  1.79  christos 				return false;
   1982   1.1       jtc 			}
   1983   1.1       jtc 			rp->r_wday = lp->l_value;
   1984   1.1       jtc 		}
   1985  1.53  christos 		if (sscanf(ep, "%d%c", &rp->r_dayofmonth, &xs) != 1 ||
   1986   1.1       jtc 			rp->r_dayofmonth <= 0 ||
   1987   1.1       jtc 			(rp->r_dayofmonth > len_months[1][rp->r_month])) {
   1988   1.5       jtc 				error(_("invalid day of month"));
   1989  1.31  christos 				free(dp);
   1990  1.79  christos 				return false;
   1991   1.1       jtc 		}
   1992   1.1       jtc 	}
   1993  1.31  christos 	free(dp);
   1994  1.79  christos 	return true;
   1995   1.1       jtc }
   1996   1.1       jtc 
   1997   1.1       jtc static void
   1998  1.79  christos convert(uint_fast32_t val, char *buf)
   1999   1.1       jtc {
   2000  1.31  christos 	int	i;
   2001  1.31  christos 	int	shift;
   2002  1.31  christos 	unsigned char *const b = (unsigned char *) buf;
   2003   1.1       jtc 
   2004   1.1       jtc 	for (i = 0, shift = 24; i < 4; ++i, shift -= 8)
   2005  1.79  christos 		b[i] = (val >> shift) & 0xff;
   2006   1.1       jtc }
   2007   1.1       jtc 
   2008   1.1       jtc static void
   2009  1.79  christos convert64(uint_fast64_t val, char *buf)
   2010  1.25   mlelstv {
   2011  1.31  christos 	int	i;
   2012  1.31  christos 	int	shift;
   2013  1.31  christos 	unsigned char *const b = (unsigned char *) buf;
   2014  1.25   mlelstv 
   2015  1.25   mlelstv 	for (i = 0, shift = 56; i < 8; ++i, shift -= 8)
   2016  1.79  christos 		b[i] = (val >> shift) & 0xff;
   2017  1.25   mlelstv }
   2018  1.25   mlelstv 
   2019  1.25   mlelstv static void
   2020  1.74  christos puttzcode(const int_fast32_t val, FILE *const fp)
   2021   1.1       jtc {
   2022   1.1       jtc 	char	buf[4];
   2023   1.1       jtc 
   2024   1.1       jtc 	convert(val, buf);
   2025  1.57  christos 	fwrite(buf, sizeof buf, (size_t) 1, fp);
   2026   1.1       jtc }
   2027   1.1       jtc 
   2028  1.25   mlelstv static void
   2029  1.74  christos puttzcodepass(zic_t val, FILE *fp, int pass)
   2030  1.25   mlelstv {
   2031  1.74  christos   if (pass == 1)
   2032  1.74  christos     puttzcode(val, fp);
   2033  1.74  christos   else {
   2034  1.25   mlelstv 	char	buf[8];
   2035  1.25   mlelstv 
   2036  1.25   mlelstv 	convert64(val, buf);
   2037  1.57  christos 	fwrite(buf, sizeof buf, (size_t) 1, fp);
   2038  1.74  christos     }
   2039  1.25   mlelstv }
   2040  1.25   mlelstv 
   2041   1.5       jtc static int
   2042  1.31  christos atcomp(const void *avp, const void *bvp)
   2043   1.5       jtc {
   2044  1.79  christos   struct attype const *ap = avp, *bp = bvp;
   2045  1.79  christos   zic_t a = ap->at, b = bp->at;
   2046  1.79  christos   return a < b ? -1 : a > b;
   2047  1.25   mlelstv }
   2048  1.25   mlelstv 
   2049  1.74  christos struct timerange {
   2050  1.74  christos   int defaulttype;
   2051  1.74  christos   ptrdiff_t base, count;
   2052  1.74  christos   int leapbase, leapcount;
   2053  1.82  christos   bool leapexpiry;
   2054  1.74  christos };
   2055  1.74  christos 
   2056  1.74  christos static struct timerange
   2057  1.82  christos limitrange(struct timerange r, zic_t lo, zic_t hi,
   2058  1.74  christos 	   zic_t const *ats, unsigned char const *types)
   2059  1.74  christos {
   2060  1.79  christos   /* Omit ordinary transitions < LO.  */
   2061  1.74  christos   while (0 < r.count && ats[r.base] < lo) {
   2062  1.74  christos     r.defaulttype = types[r.base];
   2063  1.74  christos     r.count--;
   2064  1.74  christos     r.base++;
   2065  1.74  christos   }
   2066  1.79  christos 
   2067  1.79  christos   /* Omit as many initial leap seconds as possible, such that the
   2068  1.79  christos      first leap second in the truncated list is <= LO, and is a
   2069  1.79  christos      positive leap second if and only if it has a positive correction.
   2070  1.79  christos      This supports common TZif readers that assume that the first leap
   2071  1.79  christos      second is positive if and only if its correction is positive.  */
   2072  1.79  christos   while (1 < r.leapcount && trans[r.leapbase + 1] <= lo) {
   2073  1.74  christos     r.leapcount--;
   2074  1.74  christos     r.leapbase++;
   2075  1.74  christos   }
   2076  1.79  christos   while (0 < r.leapbase
   2077  1.79  christos 	 && ((corr[r.leapbase - 1] < corr[r.leapbase])
   2078  1.79  christos 	     != (0 < corr[r.leapbase]))) {
   2079  1.79  christos     r.leapcount++;
   2080  1.79  christos     r.leapbase--;
   2081  1.79  christos   }
   2082  1.79  christos 
   2083  1.74  christos 
   2084  1.79  christos   /* Omit ordinary and leap second transitions greater than HI + 1.  */
   2085  1.79  christos   if (hi < max_time) {
   2086  1.74  christos     while (0 < r.count && hi + 1 < ats[r.base + r.count - 1])
   2087  1.74  christos       r.count--;
   2088  1.74  christos     while (0 < r.leapcount && hi + 1 < trans[r.leapbase + r.leapcount - 1])
   2089  1.74  christos       r.leapcount--;
   2090  1.74  christos   }
   2091  1.74  christos 
   2092  1.79  christos   /* Determine whether to append an expiration to the leap second table.  */
   2093  1.79  christos   r.leapexpiry = 0 <= leapexpires && leapexpires - 1 <= hi;
   2094  1.79  christos 
   2095  1.74  christos   return r;
   2096  1.74  christos }
   2097  1.74  christos 
   2098  1.74  christos static void
   2099  1.74  christos writezone(const char *const name, const char *const string, char version,
   2100  1.74  christos 	int defaulttype)
   2101  1.31  christos {
   2102  1.31  christos 	FILE *			fp;
   2103  1.65  christos 	ptrdiff_t		i, j;
   2104  1.31  christos 	int			pass;
   2105  1.59  christos 	zic_t one = 1;
   2106  1.59  christos 	zic_t y2038_boundary = one << 31;
   2107  1.65  christos 	ptrdiff_t nats = timecnt + WORK_AROUND_QTBUG_53071;
   2108  1.79  christos 	char *tempname = NULL;
   2109  1.79  christos 	char const *outname = name;
   2110  1.72  christos 
   2111  1.72  christos 	/* Allocate the ATS and TYPES arrays via a single malloc,
   2112  1.72  christos 	   as this is a bit faster.  */
   2113  1.72  christos 	zic_t *ats = zic_malloc(align_to(size_product(nats, sizeof *ats + 1),
   2114  1.72  christos 				_Alignof(zic_t)));
   2115  1.59  christos 	void *typesptr = ats + nats;
   2116  1.45  christos 	unsigned char *types = typesptr;
   2117  1.82  christos 	struct timerange rangeall = {0}, range32, range64;
   2118   1.5       jtc 
   2119   1.5       jtc 	/*
   2120   1.5       jtc 	** Sort.
   2121   1.5       jtc 	*/
   2122   1.5       jtc 	if (timecnt > 1)
   2123  1.57  christos 		qsort(attypes, (size_t) timecnt, sizeof *attypes, atcomp);
   2124   1.5       jtc 	/*
   2125   1.5       jtc 	** Optimize.
   2126   1.5       jtc 	*/
   2127   1.5       jtc 	{
   2128  1.65  christos 		ptrdiff_t fromi, toi;
   2129   1.1       jtc 
   2130   1.5       jtc 		toi = 0;
   2131   1.5       jtc 		fromi = 0;
   2132   1.5       jtc 		for ( ; fromi < timecnt; ++fromi) {
   2133  1.75  christos 			if (toi != 0
   2134  1.75  christos 			    && ((attypes[fromi].at
   2135  1.75  christos 				 + utoffs[attypes[toi - 1].type])
   2136  1.75  christos 				<= (attypes[toi - 1].at
   2137  1.75  christos 				    + utoffs[toi == 1 ? 0
   2138  1.75  christos 					     : attypes[toi - 2].type]))) {
   2139  1.25   mlelstv 					attypes[toi - 1].type =
   2140  1.25   mlelstv 						attypes[fromi].type;
   2141  1.25   mlelstv 					continue;
   2142   1.5       jtc 			}
   2143  1.63  christos 			if (toi == 0
   2144  1.63  christos 			    || attypes[fromi].dontmerge
   2145  1.75  christos 			    || (utoffs[attypes[toi - 1].type]
   2146  1.75  christos 				!= utoffs[attypes[fromi].type])
   2147  1.75  christos 			    || (isdsts[attypes[toi - 1].type]
   2148  1.75  christos 				!= isdsts[attypes[fromi].type])
   2149  1.75  christos 			    || (desigidx[attypes[toi - 1].type]
   2150  1.75  christos 				!= desigidx[attypes[fromi].type]))
   2151   1.5       jtc 					attypes[toi++] = attypes[fromi];
   2152   1.5       jtc 		}
   2153   1.5       jtc 		timecnt = toi;
   2154   1.5       jtc 	}
   2155  1.65  christos 
   2156  1.65  christos 	if (noise && timecnt > 1200) {
   2157  1.65  christos 	  if (timecnt > TZ_MAX_TIMES)
   2158  1.65  christos 		warning(_("reference clients mishandle"
   2159  1.65  christos 			  " more than %d transition times"),
   2160  1.65  christos 			TZ_MAX_TIMES);
   2161  1.65  christos 	  else
   2162  1.45  christos 		warning(_("pre-2014 clients may mishandle"
   2163  1.45  christos 			  " more than 1200 transition times"));
   2164  1.65  christos 	}
   2165   1.5       jtc 	/*
   2166   1.5       jtc 	** Transfer.
   2167   1.5       jtc 	*/
   2168   1.5       jtc 	for (i = 0; i < timecnt; ++i) {
   2169   1.5       jtc 		ats[i] = attypes[i].at;
   2170   1.5       jtc 		types[i] = attypes[i].type;
   2171   1.5       jtc 	}
   2172  1.59  christos 
   2173  1.25   mlelstv 	/*
   2174  1.25   mlelstv 	** Correct for leap seconds.
   2175  1.25   mlelstv 	*/
   2176  1.25   mlelstv 	for (i = 0; i < timecnt; ++i) {
   2177  1.25   mlelstv 		j = leapcnt;
   2178  1.25   mlelstv 		while (--j >= 0)
   2179  1.25   mlelstv 			if (ats[i] > trans[j] - corr[j]) {
   2180  1.25   mlelstv 				ats[i] = tadd(ats[i], corr[j]);
   2181  1.25   mlelstv 				break;
   2182  1.25   mlelstv 			}
   2183  1.25   mlelstv 	}
   2184  1.72  christos 
   2185  1.72  christos 	/* Work around QTBUG-53071 for timestamps less than y2038_boundary - 1,
   2186  1.72  christos 	   by inserting a no-op transition at time y2038_boundary - 1.
   2187  1.72  christos 	   This works only for timestamps before the boundary, which
   2188  1.72  christos 	   should be good enough in practice as QTBUG-53071 should be
   2189  1.72  christos 	   long-dead by 2038.  Do this after correcting for leap
   2190  1.72  christos 	   seconds, as the idea is to insert a transition just before
   2191  1.72  christos 	   32-bit time_t rolls around, and this occurs at a slightly
   2192  1.72  christos 	   different moment if transitions are leap-second corrected.  */
   2193  1.75  christos 	if (WORK_AROUND_QTBUG_53071 && timecnt != 0 && want_bloat()
   2194  1.72  christos 	    && ats[timecnt - 1] < y2038_boundary - 1 && strchr(string, '<')) {
   2195  1.72  christos 	  ats[timecnt] = y2038_boundary - 1;
   2196  1.72  christos 	  types[timecnt] = types[timecnt - 1];
   2197  1.72  christos 	  timecnt++;
   2198  1.72  christos 	}
   2199  1.72  christos 
   2200  1.74  christos 	rangeall.defaulttype = defaulttype;
   2201  1.74  christos 	rangeall.count = timecnt;
   2202  1.74  christos 	rangeall.leapcount = leapcnt;
   2203  1.82  christos 	range64 = limitrange(rangeall, lo_time,
   2204  1.82  christos 			     max(hi_time,
   2205  1.82  christos 				 redundant_time - (ZIC_MIN < redundant_time)),
   2206  1.82  christos 			     ats, types);
   2207  1.82  christos 	range32 = limitrange(range64, INT32_MIN, INT32_MAX, ats, types);
   2208  1.79  christos 
   2209  1.79  christos 	/* TZif version 4 is needed if a no-op transition is appended to
   2210  1.79  christos 	   indicate the expiration of the leap second table, or if the first
   2211  1.79  christos 	   leap second transition is not to a +1 or -1 correction.  */
   2212  1.79  christos 	for (pass = 1; pass <= 2; pass++) {
   2213  1.79  christos 	  struct timerange const *r = pass == 1 ? &range32 : &range64;
   2214  1.79  christos 	  if (pass == 1 && !want_bloat())
   2215  1.79  christos 	    continue;
   2216  1.79  christos 	  if (r->leapexpiry) {
   2217  1.79  christos 	    if (noise)
   2218  1.79  christos 	      warning(_("%s: pre-2021b clients may mishandle"
   2219  1.79  christos 			" leap second expiry"),
   2220  1.79  christos 		      name);
   2221  1.79  christos 	    version = '4';
   2222  1.79  christos 	  }
   2223  1.79  christos 	  if (0 < r->leapcount
   2224  1.79  christos 	      && corr[r->leapbase] != 1 && corr[r->leapbase] != -1) {
   2225  1.79  christos 	    if (noise)
   2226  1.79  christos 	      warning(_("%s: pre-2021b clients may mishandle"
   2227  1.79  christos 			" leap second table truncation"),
   2228  1.79  christos 		      name);
   2229  1.79  christos 	    version = '4';
   2230  1.79  christos 	  }
   2231  1.79  christos 	  if (version == '4')
   2232  1.79  christos 	    break;
   2233  1.79  christos  	}
   2234  1.74  christos 
   2235  1.79  christos 	fp = open_outfile(&outname, &tempname);
   2236   1.7       jtc 
   2237  1.25   mlelstv 	for (pass = 1; pass <= 2; ++pass) {
   2238  1.65  christos 		ptrdiff_t	thistimei, thistimecnt, thistimelim;
   2239  1.65  christos 		int	thisleapi, thisleapcnt, thisleaplim;
   2240  1.79  christos 		struct tzhead tzh;
   2241  1.82  christos 		int pretranstype = -1, thisdefaulttype;
   2242  1.82  christos 		bool locut, hicut, thisleapexpiry;
   2243  1.82  christos 		zic_t lo, thismin, thismax;
   2244  1.74  christos 		int old0;
   2245  1.74  christos 		char		omittype[TZ_MAX_TYPES];
   2246  1.25   mlelstv 		int		typemap[TZ_MAX_TYPES];
   2247  1.75  christos 		int		thistypecnt, stdcnt, utcnt;
   2248  1.25   mlelstv 		char		thischars[TZ_MAX_CHARS];
   2249  1.65  christos 		int		thischarcnt;
   2250  1.65  christos 		bool		toomanytimes;
   2251  1.51  christos 		int		indmap[TZ_MAX_CHARS];
   2252  1.25   mlelstv 
   2253  1.25   mlelstv 		if (pass == 1) {
   2254  1.82  christos 			thisdefaulttype = range32.defaulttype;
   2255  1.74  christos 			thistimei = range32.base;
   2256  1.74  christos 			thistimecnt = range32.count;
   2257  1.65  christos 			toomanytimes = thistimecnt >> 31 >> 1 != 0;
   2258  1.74  christos 			thisleapi = range32.leapbase;
   2259  1.74  christos 			thisleapcnt = range32.leapcount;
   2260  1.79  christos 			thisleapexpiry = range32.leapexpiry;
   2261  1.82  christos 			thismin = INT32_MIN;
   2262  1.82  christos 			thismax = INT32_MAX;
   2263  1.25   mlelstv 		} else {
   2264  1.74  christos 			thisdefaulttype = range64.defaulttype;
   2265  1.74  christos 			thistimei = range64.base;
   2266  1.74  christos 			thistimecnt = range64.count;
   2267  1.65  christos 			toomanytimes = thistimecnt >> 31 >> 31 >> 2 != 0;
   2268  1.74  christos 			thisleapi = range64.leapbase;
   2269  1.74  christos 			thisleapcnt = range64.leapcount;
   2270  1.79  christos 			thisleapexpiry = range64.leapexpiry;
   2271  1.82  christos 			thismin = min_time;
   2272  1.82  christos 			thismax = max_time;
   2273  1.25   mlelstv 		}
   2274  1.65  christos 		if (toomanytimes)
   2275  1.65  christos 		  error(_("too many transition times"));
   2276  1.74  christos 
   2277  1.82  christos 		locut = thismin < lo_time && lo_time <= thismax;
   2278  1.82  christos 		hicut = thismin <= hi_time && hi_time < thismax;
   2279  1.25   mlelstv 		thistimelim = thistimei + thistimecnt;
   2280  1.74  christos 		memset(omittype, true, typecnt);
   2281  1.82  christos 
   2282  1.82  christos 		/* Determine whether to output a transition before the first
   2283  1.82  christos 		   transition in range.  This is needed when the output is
   2284  1.82  christos 		   truncated at the start, and is also useful when catering to
   2285  1.82  christos 		   buggy 32-bit clients that do not use time type 0 for
   2286  1.82  christos 		   timestamps before the first transition.  */
   2287  1.82  christos 		if ((locut || (pass == 1 && thistimei))
   2288  1.82  christos 		    && ! (thistimecnt && ats[thistimei] == lo_time)) {
   2289  1.82  christos 		  pretranstype = thisdefaulttype;
   2290  1.82  christos 		  omittype[pretranstype] = false;
   2291  1.82  christos 		}
   2292  1.82  christos 
   2293  1.82  christos 		/* Arguably the default time type in the 32-bit data
   2294  1.82  christos 		   should be range32.defaulttype, which is suited for
   2295  1.82  christos 		   timestamps just before INT32_MIN.  However, zic
   2296  1.82  christos 		   traditionally used the time type of the indefinite
   2297  1.82  christos 		   past instead.  Internet RFC 8532 says readers should
   2298  1.82  christos 		   ignore 32-bit data, so this discrepancy matters only
   2299  1.82  christos 		   to obsolete readers where the traditional type might
   2300  1.82  christos 		   be more appropriate even if it's "wrong".  So, use
   2301  1.82  christos 		   the historical zic value, unless -r specifies a low
   2302  1.82  christos 		   cutoff that excludes some 32-bit timestamps.  */
   2303  1.82  christos 		if (pass == 1 && lo_time <= thismin)
   2304  1.82  christos 		  thisdefaulttype = range64.defaulttype;
   2305  1.82  christos 
   2306  1.82  christos 		if (locut)
   2307  1.82  christos 		  thisdefaulttype = unspecifiedtype;
   2308  1.74  christos 		omittype[thisdefaulttype] = false;
   2309  1.82  christos 		for (i = thistimei; i < thistimelim; i++)
   2310  1.74  christos 		  omittype[types[i]] = false;
   2311  1.79  christos 		if (hicut)
   2312  1.79  christos 		  omittype[unspecifiedtype] = false;
   2313  1.74  christos 
   2314  1.74  christos 		/* Reorder types to make THISDEFAULTTYPE type 0.
   2315  1.74  christos 		   Use TYPEMAP to swap OLD0 and THISDEFAULTTYPE so that
   2316  1.74  christos 		   THISDEFAULTTYPE appears as type 0 in the output instead
   2317  1.74  christos 		   of OLD0.  TYPEMAP also omits unused types.  */
   2318  1.74  christos 		old0 = strlen(omittype);
   2319  1.74  christos 
   2320  1.29  christos #ifndef LEAVE_SOME_PRE_2011_SYSTEMS_IN_THE_LURCH
   2321  1.29  christos 		/*
   2322  1.29  christos 		** For some pre-2011 systems: if the last-to-be-written
   2323  1.29  christos 		** standard (or daylight) type has an offset different from the
   2324  1.29  christos 		** most recently used offset,
   2325  1.29  christos 		** append an (unused) copy of the most recently used type
   2326  1.29  christos 		** (to help get global "altzone" and "timezone" variables
   2327  1.29  christos 		** set correctly).
   2328  1.29  christos 		*/
   2329  1.75  christos 		if (want_bloat()) {
   2330  1.31  christos 			int	mrudst, mrustd, hidst, histd, type;
   2331  1.29  christos 
   2332  1.29  christos 			hidst = histd = mrudst = mrustd = -1;
   2333  1.82  christos 			if (0 <= pretranstype) {
   2334  1.82  christos 			  if (isdsts[pretranstype])
   2335  1.82  christos 			    mrudst = pretranstype;
   2336  1.82  christos 			  else
   2337  1.82  christos 			    mrustd = pretranstype;
   2338  1.82  christos 			}
   2339  1.82  christos 			for (i = thistimei; i < thistimelim; i++)
   2340  1.29  christos 				if (isdsts[types[i]])
   2341  1.29  christos 					mrudst = types[i];
   2342  1.29  christos 				else	mrustd = types[i];
   2343  1.75  christos 			for (i = old0; i < typecnt; i++) {
   2344  1.75  christos 			  int h = (i == old0 ? thisdefaulttype
   2345  1.75  christos 				   : i == thisdefaulttype ? old0 : i);
   2346  1.75  christos 			  if (!omittype[h]) {
   2347  1.75  christos 			    if (isdsts[h])
   2348  1.75  christos 			      hidst = i;
   2349  1.75  christos 			    else
   2350  1.75  christos 			      histd = i;
   2351  1.75  christos 			  }
   2352  1.75  christos 			}
   2353  1.29  christos 			if (hidst >= 0 && mrudst >= 0 && hidst != mrudst &&
   2354  1.75  christos 				utoffs[hidst] != utoffs[mrudst]) {
   2355  1.29  christos 					isdsts[mrudst] = -1;
   2356  1.75  christos 					type = addtype(utoffs[mrudst],
   2357  1.75  christos 						&chars[desigidx[mrudst]],
   2358  1.51  christos 						true,
   2359  1.29  christos 						ttisstds[mrudst],
   2360  1.75  christos 						ttisuts[mrudst]);
   2361  1.51  christos 					isdsts[mrudst] = 1;
   2362  1.74  christos 					omittype[type] = false;
   2363  1.29  christos 			}
   2364  1.29  christos 			if (histd >= 0 && mrustd >= 0 && histd != mrustd &&
   2365  1.75  christos 				utoffs[histd] != utoffs[mrustd]) {
   2366  1.29  christos 					isdsts[mrustd] = -1;
   2367  1.75  christos 					type = addtype(utoffs[mrustd],
   2368  1.75  christos 						&chars[desigidx[mrustd]],
   2369  1.51  christos 						false,
   2370  1.29  christos 						ttisstds[mrustd],
   2371  1.75  christos 						ttisuts[mrustd]);
   2372  1.51  christos 					isdsts[mrustd] = 0;
   2373  1.75  christos 					omittype[type] = false;
   2374  1.29  christos 			}
   2375  1.29  christos 		}
   2376  1.29  christos #endif /* !defined LEAVE_SOME_PRE_2011_SYSTEMS_IN_THE_LURCH */
   2377  1.74  christos  		thistypecnt = 0;
   2378  1.74  christos 		for (i = old0; i < typecnt; i++)
   2379  1.74  christos 		  if (!omittype[i])
   2380  1.74  christos 		    typemap[i == old0 ? thisdefaulttype
   2381  1.74  christos 			    : i == thisdefaulttype ? old0 : i]
   2382  1.74  christos 		      = thistypecnt++;
   2383  1.74  christos 
   2384  1.36  christos 		for (i = 0; i < (int)(sizeof indmap / sizeof indmap[0]); ++i)
   2385  1.25   mlelstv 			indmap[i] = -1;
   2386  1.75  christos 		thischarcnt = stdcnt = utcnt = 0;
   2387  1.74  christos 		for (i = old0; i < typecnt; i++) {
   2388  1.31  christos 			char *	thisabbr;
   2389  1.25   mlelstv 
   2390  1.74  christos 			if (omittype[i])
   2391  1.25   mlelstv 				continue;
   2392  1.75  christos 			if (ttisstds[i])
   2393  1.75  christos 			  stdcnt = thistypecnt;
   2394  1.75  christos 			if (ttisuts[i])
   2395  1.75  christos 			  utcnt = thistypecnt;
   2396  1.75  christos 			if (indmap[desigidx[i]] >= 0)
   2397  1.25   mlelstv 				continue;
   2398  1.75  christos 			thisabbr = &chars[desigidx[i]];
   2399  1.25   mlelstv 			for (j = 0; j < thischarcnt; ++j)
   2400  1.25   mlelstv 				if (strcmp(&thischars[j], thisabbr) == 0)
   2401  1.25   mlelstv 					break;
   2402  1.25   mlelstv 			if (j == thischarcnt) {
   2403  1.65  christos 				strcpy(&thischars[thischarcnt], thisabbr);
   2404  1.25   mlelstv 				thischarcnt += strlen(thisabbr) + 1;
   2405  1.25   mlelstv 			}
   2406  1.75  christos 			indmap[desigidx[i]] = j;
   2407  1.75  christos 		}
   2408  1.75  christos 		if (pass == 1 && !want_bloat()) {
   2409  1.82  christos 		  hicut = thisleapexpiry = false;
   2410  1.82  christos 		  pretranstype = -1;
   2411  1.79  christos 		  thistimecnt = thisleapcnt = 0;
   2412  1.75  christos 		  thistypecnt = thischarcnt = 1;
   2413  1.25   mlelstv 		}
   2414  1.57  christos #define DO(field)	fwrite(tzh.field, sizeof tzh.field, (size_t) 1, fp)
   2415  1.80  christos 		memset(&tzh, 0, sizeof(tzh));
   2416  1.70  christos 		memcpy(tzh.tzh_magic, TZ_MAGIC, sizeof tzh.tzh_magic);
   2417  1.43  christos 		tzh.tzh_version[0] = version;
   2418  1.75  christos 		convert(utcnt, tzh.tzh_ttisutcnt);
   2419  1.75  christos 		convert(stdcnt, tzh.tzh_ttisstdcnt);
   2420  1.79  christos 		convert(thisleapcnt + thisleapexpiry, tzh.tzh_leapcnt);
   2421  1.82  christos 		convert((0 <= pretranstype) + thistimecnt + hicut,
   2422  1.82  christos 			tzh.tzh_timecnt);
   2423  1.41  christos 		convert(thistypecnt, tzh.tzh_typecnt);
   2424  1.41  christos 		convert(thischarcnt, tzh.tzh_charcnt);
   2425  1.25   mlelstv 		DO(tzh_magic);
   2426  1.25   mlelstv 		DO(tzh_version);
   2427  1.25   mlelstv 		DO(tzh_reserved);
   2428  1.75  christos 		DO(tzh_ttisutcnt);
   2429  1.25   mlelstv 		DO(tzh_ttisstdcnt);
   2430  1.25   mlelstv 		DO(tzh_leapcnt);
   2431  1.25   mlelstv 		DO(tzh_timecnt);
   2432  1.25   mlelstv 		DO(tzh_typecnt);
   2433  1.25   mlelstv 		DO(tzh_charcnt);
   2434   1.1       jtc #undef DO
   2435  1.75  christos 		if (pass == 1 && !want_bloat()) {
   2436  1.75  christos 		  /* Output a minimal data block with just one time type.  */
   2437  1.75  christos 		  puttzcode(0, fp);	/* utoff */
   2438  1.75  christos 		  putc(0, fp);		/* dst */
   2439  1.75  christos 		  putc(0, fp);		/* index of abbreviation */
   2440  1.75  christos 		  putc(0, fp);		/* empty-string abbreviation */
   2441  1.75  christos 		  continue;
   2442  1.75  christos 		}
   2443  1.75  christos 
   2444  1.74  christos 		/* Output a LO_TIME transition if needed; see limitrange.
   2445  1.74  christos 		   But do not go below the minimum representable value
   2446  1.74  christos 		   for this pass.  */
   2447  1.74  christos 		lo = pass == 1 && lo_time < INT32_MIN ? INT32_MIN : lo_time;
   2448  1.74  christos 
   2449  1.82  christos 		if (0 <= pretranstype)
   2450  1.74  christos 		  puttzcodepass(lo, fp, pass);
   2451  1.74  christos 		for (i = thistimei; i < thistimelim; ++i) {
   2452  1.79  christos 		  puttzcodepass(ats[i], fp, pass);
   2453  1.74  christos 		}
   2454  1.74  christos 		if (hicut)
   2455  1.74  christos 		  puttzcodepass(hi_time + 1, fp, pass);
   2456  1.82  christos 		if (0 <= pretranstype)
   2457  1.82  christos 		  putc(typemap[pretranstype], fp);
   2458  1.82  christos 		for (i = thistimei; i < thistimelim; i++)
   2459  1.79  christos 		  putc(typemap[types[i]], fp);
   2460  1.74  christos 		if (hicut)
   2461  1.79  christos 		  putc(typemap[unspecifiedtype], fp);
   2462  1.25   mlelstv 
   2463  1.75  christos 		for (i = old0; i < typecnt; i++) {
   2464  1.75  christos 		  int h = (i == old0 ? thisdefaulttype
   2465  1.75  christos 			   : i == thisdefaulttype ? old0 : i);
   2466  1.75  christos 		  if (!omittype[h]) {
   2467  1.75  christos 		    puttzcode(utoffs[h], fp);
   2468  1.75  christos 		    putc(isdsts[h], fp);
   2469  1.75  christos 		    putc(indmap[desigidx[h]], fp);
   2470  1.75  christos 		  }
   2471  1.75  christos 		}
   2472  1.25   mlelstv 		if (thischarcnt != 0)
   2473  1.57  christos 			fwrite(thischars, sizeof thischars[0],
   2474  1.25   mlelstv 				(size_t) thischarcnt, fp);
   2475  1.79  christos 		thisleaplim = thisleapi + thisleapcnt;
   2476  1.25   mlelstv 		for (i = thisleapi; i < thisleaplim; ++i) {
   2477  1.31  christos 			zic_t	todo;
   2478  1.25   mlelstv 
   2479  1.25   mlelstv 			if (roll[i]) {
   2480  1.25   mlelstv 				if (timecnt == 0 || trans[i] < ats[0]) {
   2481  1.25   mlelstv 					j = 0;
   2482  1.25   mlelstv 					while (isdsts[j])
   2483  1.25   mlelstv 						if (++j >= typecnt) {
   2484  1.25   mlelstv 							j = 0;
   2485  1.25   mlelstv 							break;
   2486  1.25   mlelstv 						}
   2487  1.25   mlelstv 				} else {
   2488  1.25   mlelstv 					j = 1;
   2489  1.25   mlelstv 					while (j < timecnt &&
   2490  1.25   mlelstv 						trans[i] >= ats[j])
   2491  1.25   mlelstv 							++j;
   2492  1.25   mlelstv 					j = types[j - 1];
   2493  1.25   mlelstv 				}
   2494  1.75  christos 				todo = tadd(trans[i], -utoffs[j]);
   2495  1.25   mlelstv 			} else	todo = trans[i];
   2496  1.74  christos 			puttzcodepass(todo, fp, pass);
   2497  1.25   mlelstv 			puttzcode(corr[i], fp);
   2498  1.25   mlelstv 		}
   2499  1.79  christos 		if (thisleapexpiry) {
   2500  1.79  christos 		  /* Append a no-op leap correction indicating when the leap
   2501  1.79  christos 		     second table expires.  Although this does not conform to
   2502  1.79  christos 		     Internet RFC 8536, most clients seem to accept this and
   2503  1.79  christos 		     the plan is to amend the RFC to allow this in version 4
   2504  1.79  christos 		     TZif files.  */
   2505  1.79  christos 		  puttzcodepass(leapexpires, fp, pass);
   2506  1.79  christos 		  puttzcode(thisleaplim ? corr[thisleaplim - 1] : 0, fp);
   2507  1.79  christos 		}
   2508  1.75  christos 		if (stdcnt != 0)
   2509  1.75  christos 		  for (i = old0; i < typecnt; i++)
   2510  1.74  christos 			if (!omittype[i])
   2511  1.57  christos 				putc(ttisstds[i], fp);
   2512  1.75  christos 		if (utcnt != 0)
   2513  1.75  christos 		  for (i = old0; i < typecnt; i++)
   2514  1.74  christos 			if (!omittype[i])
   2515  1.75  christos 				putc(ttisuts[i], fp);
   2516   1.1       jtc 	}
   2517  1.57  christos 	fprintf(fp, "\n%s\n", string);
   2518  1.79  christos 	close_file(fp, directory, name, tempname);
   2519  1.79  christos 	rename_dest(tempname, name);
   2520  1.45  christos 	free(ats);
   2521   1.1       jtc }
   2522   1.1       jtc 
   2523  1.55  christos static char const *
   2524  1.55  christos abbroffset(char *buf, zic_t offset)
   2525  1.55  christos {
   2526  1.55  christos 	char sign = '+';
   2527  1.55  christos 	int seconds, minutes;
   2528  1.55  christos 
   2529  1.55  christos 	if (offset < 0) {
   2530  1.55  christos 		offset = -offset;
   2531  1.55  christos 		sign = '-';
   2532  1.55  christos 	}
   2533  1.55  christos 
   2534  1.55  christos 	seconds = offset % SECSPERMIN;
   2535  1.55  christos 	offset /= SECSPERMIN;
   2536  1.55  christos 	minutes = offset % MINSPERHOUR;
   2537  1.55  christos 	offset /= MINSPERHOUR;
   2538  1.55  christos 	if (100 <= offset) {
   2539  1.70  christos 		error(_("%%z UT offset magnitude exceeds 99:59:59"));
   2540  1.55  christos 		return "%z";
   2541  1.55  christos 	} else {
   2542  1.55  christos 		char *p = buf;
   2543  1.55  christos 		*p++ = sign;
   2544  1.55  christos 		*p++ = '0' + offset / 10;
   2545  1.55  christos 		*p++ = '0' + offset % 10;
   2546  1.55  christos 		if (minutes | seconds) {
   2547  1.55  christos 			*p++ = '0' + minutes / 10;
   2548  1.55  christos 			*p++ = '0' + minutes % 10;
   2549  1.55  christos 			if (seconds) {
   2550  1.55  christos 				*p++ = '0' + seconds / 10;
   2551  1.55  christos 				*p++ = '0' + seconds % 10;
   2552  1.55  christos 			}
   2553  1.55  christos 		}
   2554  1.55  christos 		*p = '\0';
   2555  1.55  christos 		return buf;
   2556  1.55  christos 	}
   2557  1.55  christos }
   2558  1.55  christos 
   2559  1.82  christos static char const disable_percent_s[] = "";
   2560  1.82  christos 
   2561  1.53  christos static size_t
   2562  1.79  christos doabbr(char *abbr, size_t abbrlen, struct zone const *zp, const char *letters,
   2563  1.75  christos     bool isdst, zic_t save, bool doquotes)
   2564  1.31  christos {
   2565  1.31  christos 	char *	cp;
   2566  1.31  christos 	char *	slashp;
   2567  1.53  christos 	size_t	len;
   2568  1.55  christos 	char const *format = zp->z_format;
   2569  1.25   mlelstv 
   2570  1.25   mlelstv 	slashp = strchr(format, '/');
   2571  1.25   mlelstv 	if (slashp == NULL) {
   2572  1.55  christos 		char letterbuf[PERCENT_Z_LEN_BOUND + 1];
   2573  1.55  christos 		if (zp->z_format_specifier == 'z')
   2574  1.75  christos 			letters = abbroffset(letterbuf, zp->z_stdoff + save);
   2575  1.55  christos 		else if (!letters)
   2576  1.55  christos 			letters = "%s";
   2577  1.82  christos 		else if (letters == disable_percent_s)
   2578  1.82  christos 			return 0;
   2579  1.57  christos 		snprintf(abbr, abbrlen, format, letters);
   2580  1.71  christos 	} else if (isdst) {
   2581  1.57  christos 		strlcpy(abbr, slashp + 1, abbrlen);
   2582  1.25   mlelstv 	} else {
   2583  1.57  christos 		memcpy(abbr, format, slashp - format);
   2584  1.25   mlelstv 		abbr[slashp - format] = '\0';
   2585  1.25   mlelstv 	}
   2586  1.53  christos 	len = strlen(abbr);
   2587  1.25   mlelstv 	if (!doquotes)
   2588  1.53  christos 		return len;
   2589  1.47  christos 	for (cp = abbr; is_alpha(*cp); cp++)
   2590  1.47  christos 		continue;
   2591  1.25   mlelstv 	if (len > 0 && *cp == '\0')
   2592  1.53  christos 		return len;
   2593  1.25   mlelstv 	abbr[len + 2] = '\0';
   2594  1.25   mlelstv 	abbr[len + 1] = '>';
   2595  1.53  christos 	memmove(abbr + 1, abbr, len);
   2596  1.25   mlelstv 	abbr[0] = '<';
   2597  1.53  christos 	return len + 2;
   2598  1.25   mlelstv }
   2599  1.25   mlelstv 
   2600  1.25   mlelstv static void
   2601  1.41  christos updateminmax(const zic_t x)
   2602  1.25   mlelstv {
   2603  1.25   mlelstv 	if (min_year > x)
   2604  1.25   mlelstv 		min_year = x;
   2605  1.25   mlelstv 	if (max_year < x)
   2606  1.25   mlelstv 		max_year = x;
   2607  1.25   mlelstv }
   2608  1.25   mlelstv 
   2609  1.53  christos static int
   2610  1.79  christos stringoffset(char *result, int resultlen, zic_t offset)
   2611  1.31  christos {
   2612  1.31  christos 	int	hours;
   2613  1.31  christos 	int	minutes;
   2614  1.31  christos 	int	seconds;
   2615  1.53  christos 	bool negative = offset < 0;
   2616  1.53  christos 	int len = negative;
   2617  1.25   mlelstv 
   2618  1.53  christos 	if (negative) {
   2619  1.25   mlelstv 		offset = -offset;
   2620  1.53  christos 		result[0] = '-';
   2621  1.25   mlelstv 	}
   2622  1.25   mlelstv 	seconds = offset % SECSPERMIN;
   2623  1.25   mlelstv 	offset /= SECSPERMIN;
   2624  1.25   mlelstv 	minutes = offset % MINSPERHOUR;
   2625  1.25   mlelstv 	offset /= MINSPERHOUR;
   2626  1.25   mlelstv 	hours = offset;
   2627  1.43  christos 	if (hours >= HOURSPERDAY * DAYSPERWEEK) {
   2628  1.25   mlelstv 		result[0] = '\0';
   2629  1.53  christos 		return 0;
   2630  1.25   mlelstv 	}
   2631  1.79  christos 	len += snprintf(result + len, resultlen - len, "%d", hours);
   2632  1.25   mlelstv 	if (minutes != 0 || seconds != 0) {
   2633  1.79  christos 		len += snprintf(result + len, resultlen - len,
   2634  1.79  christos 		    ":%02d", minutes);
   2635  1.25   mlelstv 		if (seconds != 0)
   2636  1.79  christos 			len += snprintf(result + len, resultlen - len,
   2637  1.79  christos 			    ":%02d", seconds);
   2638  1.25   mlelstv 	}
   2639  1.53  christos 	return len;
   2640  1.25   mlelstv }
   2641  1.25   mlelstv 
   2642  1.25   mlelstv static int
   2643  1.79  christos stringrule(char *result, int resultlen, struct rule *const rp, zic_t save, const zic_t stdoff)
   2644  1.25   mlelstv {
   2645  1.43  christos 	zic_t	tod = rp->r_tod;
   2646  1.79  christos 	int	compat = 0, len = 0;
   2647  1.25   mlelstv 
   2648  1.25   mlelstv 	if (rp->r_dycode == DC_DOM) {
   2649  1.31  christos 		int	month, total;
   2650  1.25   mlelstv 
   2651  1.25   mlelstv 		if (rp->r_dayofmonth == 29 && rp->r_month == TM_FEBRUARY)
   2652  1.25   mlelstv 			return -1;
   2653  1.25   mlelstv 		total = 0;
   2654  1.25   mlelstv 		for (month = 0; month < rp->r_month; ++month)
   2655  1.25   mlelstv 			total += len_months[0][month];
   2656  1.43  christos 		/* Omit the "J" in Jan and Feb, as that's shorter.  */
   2657  1.43  christos 		if (rp->r_month <= 1)
   2658  1.79  christos 		  len += snprintf(result + len, resultlen - len, "%d", total + rp->r_dayofmonth - 1);
   2659  1.43  christos 		else
   2660  1.79  christos 		  len += snprintf(result + len, resultlen - len, "J%d", total + rp->r_dayofmonth);
   2661  1.25   mlelstv 	} else {
   2662  1.31  christos 		int	week;
   2663  1.43  christos 		int	wday = rp->r_wday;
   2664  1.43  christos 		int	wdayoff;
   2665  1.25   mlelstv 
   2666  1.25   mlelstv 		if (rp->r_dycode == DC_DOWGEQ) {
   2667  1.43  christos 			wdayoff = (rp->r_dayofmonth - 1) % DAYSPERWEEK;
   2668  1.43  christos 			if (wdayoff)
   2669  1.43  christos 				compat = 2013;
   2670  1.43  christos 			wday -= wdayoff;
   2671  1.43  christos 			tod += wdayoff * SECSPERDAY;
   2672  1.43  christos 			week = 1 + (rp->r_dayofmonth - 1) / DAYSPERWEEK;
   2673  1.25   mlelstv 		} else if (rp->r_dycode == DC_DOWLEQ) {
   2674  1.25   mlelstv 			if (rp->r_dayofmonth == len_months[1][rp->r_month])
   2675  1.25   mlelstv 				week = 5;
   2676  1.25   mlelstv 			else {
   2677  1.43  christos 				wdayoff = rp->r_dayofmonth % DAYSPERWEEK;
   2678  1.43  christos 				if (wdayoff)
   2679  1.43  christos 					compat = 2013;
   2680  1.43  christos 				wday -= wdayoff;
   2681  1.43  christos 				tod += wdayoff * SECSPERDAY;
   2682  1.29  christos 				week = rp->r_dayofmonth / DAYSPERWEEK;
   2683  1.25   mlelstv 			}
   2684  1.25   mlelstv 		} else	return -1;	/* "cannot happen" */
   2685  1.43  christos 		if (wday < 0)
   2686  1.43  christos 			wday += DAYSPERWEEK;
   2687  1.79  christos 		len += snprintf(result + len, resultlen - len, "M%d.%d.%d",
   2688  1.53  christos 				  rp->r_month + 1, week, wday);
   2689  1.25   mlelstv 	}
   2690  1.75  christos 	if (rp->r_todisut)
   2691  1.75  christos 	  tod += stdoff;
   2692  1.71  christos 	if (rp->r_todisstd && !rp->r_isdst)
   2693  1.75  christos 	  tod += save;
   2694  1.25   mlelstv 	if (tod != 2 * SECSPERMIN * MINSPERHOUR) {
   2695  1.79  christos 		if (len + 1 < resultlen)
   2696  1.79  christos 		    result[len++] = '/';
   2697  1.79  christos 		if (! stringoffset(result + len, resultlen - len, tod))
   2698  1.25   mlelstv 			return -1;
   2699  1.43  christos 		if (tod < 0) {
   2700  1.43  christos 			if (compat < 2013)
   2701  1.43  christos 				compat = 2013;
   2702  1.43  christos 		} else if (SECSPERDAY <= tod) {
   2703  1.43  christos 			if (compat < 1994)
   2704  1.43  christos 				compat = 1994;
   2705  1.43  christos 		}
   2706  1.25   mlelstv 	}
   2707  1.43  christos 	return compat;
   2708  1.43  christos }
   2709  1.43  christos 
   2710  1.43  christos static int
   2711  1.43  christos rule_cmp(struct rule const *a, struct rule const *b)
   2712  1.43  christos {
   2713  1.43  christos 	if (!a)
   2714  1.43  christos 		return -!!b;
   2715  1.43  christos 	if (!b)
   2716  1.43  christos 		return 1;
   2717  1.43  christos 	if (a->r_hiyear != b->r_hiyear)
   2718  1.43  christos 		return a->r_hiyear < b->r_hiyear ? -1 : 1;
   2719  1.79  christos 	if (a->r_hiyear == ZIC_MAX)
   2720  1.79  christos 		return 0;
   2721  1.43  christos 	if (a->r_month - b->r_month != 0)
   2722  1.43  christos 		return a->r_month - b->r_month;
   2723  1.43  christos 	return a->r_dayofmonth - b->r_dayofmonth;
   2724  1.25   mlelstv }
   2725  1.25   mlelstv 
   2726  1.43  christos static int
   2727  1.75  christos stringzone(char *result, int resultlen, const struct zone *const zpfirst,
   2728  1.31  christos     const int zonecount)
   2729  1.31  christos {
   2730  1.31  christos 	const struct zone *	zp;
   2731  1.31  christos 	struct rule *		rp;
   2732  1.31  christos 	struct rule *		stdrp;
   2733  1.31  christos 	struct rule *		dstrp;
   2734  1.65  christos 	ptrdiff_t	i;
   2735  1.43  christos 	int			compat = 0;
   2736  1.43  christos 	int			c;
   2737  1.53  christos 	size_t			len;
   2738  1.53  christos 	int			offsetlen;
   2739  1.43  christos 	struct rule		stdr, dstr;
   2740  1.79  christos 	int dstcmp;
   2741  1.79  christos 	struct rule *lastrp[2] = { NULL, NULL };
   2742  1.79  christos 	struct zone zstr[2];
   2743  1.79  christos 	struct zone const *stdzp;
   2744  1.79  christos 	struct zone const *dstzp;
   2745  1.25   mlelstv 
   2746  1.25   mlelstv 	result[0] = '\0';
   2747  1.74  christos 
   2748  1.74  christos 	/* Internet RFC 8536 section 5.1 says to use an empty TZ string if
   2749  1.74  christos 	   future timestamps are truncated.  */
   2750  1.74  christos 	if (hi_time < max_time)
   2751  1.74  christos 	  return -1;
   2752  1.74  christos 
   2753  1.25   mlelstv 	zp = zpfirst + zonecount - 1;
   2754  1.25   mlelstv 	for (i = 0; i < zp->z_nrules; ++i) {
   2755  1.79  christos 		struct rule **last;
   2756  1.79  christos 		int cmp;
   2757  1.25   mlelstv 		rp = &zp->z_rules[i];
   2758  1.79  christos 		last = &lastrp[rp->r_isdst];
   2759  1.79  christos 		cmp = rule_cmp(*last, rp);
   2760  1.79  christos 		if (cmp < 0)
   2761  1.79  christos 		  *last = rp;
   2762  1.79  christos 		else if (cmp == 0)
   2763  1.79  christos 		  return -1;
   2764  1.79  christos 	}
   2765  1.79  christos 	stdrp = lastrp[false];
   2766  1.79  christos 	dstrp = lastrp[true];
   2767  1.79  christos 	dstcmp = zp->z_nrules ? rule_cmp(dstrp, stdrp) : zp->z_isdst ? 1 : -1;
   2768  1.79  christos 	stdzp = dstzp = zp;
   2769  1.79  christos 
   2770  1.79  christos 	if (dstcmp < 0) {
   2771  1.79  christos 	  /* Standard time all year.  */
   2772  1.79  christos 	  dstrp = NULL;
   2773  1.79  christos 	} else if (0 < dstcmp) {
   2774  1.79  christos 	  /* DST all year.  Use an abbreviation like
   2775  1.79  christos 	     "XXX3EDT4,0/0,J365/23" for EDT (-04) all year.  */
   2776  1.79  christos 	  zic_t save = dstrp ? dstrp->r_save : zp->z_save;
   2777  1.79  christos 	  if (0 <= save)
   2778  1.79  christos 	    {
   2779  1.79  christos 	      /* Positive DST, the typical case for all-year DST.
   2780  1.79  christos 		 Fake a timezone with negative DST.  */
   2781  1.79  christos 	      stdzp = &zstr[0];
   2782  1.79  christos 	      dstzp = &zstr[1];
   2783  1.79  christos 	      zstr[0].z_stdoff = zp->z_stdoff + 2 * save;
   2784  1.79  christos 	      zstr[0].z_format = "XXX";  /* Any 3 letters will do.  */
   2785  1.79  christos 	      zstr[0].z_format_specifier = 0;
   2786  1.79  christos 	      zstr[1].z_stdoff = zstr[0].z_stdoff;
   2787  1.79  christos 	      zstr[1].z_format = zp->z_format;
   2788  1.79  christos 	      zstr[1].z_format_specifier = zp->z_format_specifier;
   2789  1.79  christos 	    }
   2790  1.79  christos 	  dstr.r_month = TM_JANUARY;
   2791  1.79  christos 	  dstr.r_dycode = DC_DOM;
   2792  1.79  christos 	  dstr.r_dayofmonth = 1;
   2793  1.79  christos 	  dstr.r_tod = 0;
   2794  1.79  christos 	  dstr.r_todisstd = dstr.r_todisut = false;
   2795  1.79  christos 	  dstr.r_isdst = true;
   2796  1.79  christos 	  dstr.r_save = save < 0 ? save : -save;
   2797  1.79  christos 	  dstr.r_abbrvar = dstrp ? dstrp->r_abbrvar : NULL;
   2798  1.79  christos 	  stdr.r_month = TM_DECEMBER;
   2799  1.79  christos 	  stdr.r_dycode = DC_DOM;
   2800  1.79  christos 	  stdr.r_dayofmonth = 31;
   2801  1.79  christos 	  stdr.r_tod = SECSPERDAY + dstr.r_save;
   2802  1.79  christos 	  stdr.r_todisstd = stdr.r_todisut = false;
   2803  1.79  christos 	  stdr.r_isdst = false;
   2804  1.79  christos 	  stdr.r_save = 0;
   2805  1.79  christos 	  stdr.r_abbrvar = save < 0 && stdrp ? stdrp->r_abbrvar : NULL;
   2806  1.79  christos 	  dstrp = &dstr;
   2807  1.79  christos 	  stdrp = &stdr;
   2808  1.79  christos 	}
   2809  1.79  christos 	len = doabbr(result, resultlen, stdzp, stdrp ? stdrp->r_abbrvar : NULL,
   2810  1.79  christos 		     false, 0, true);
   2811  1.79  christos 	offsetlen = stringoffset(result + len, resultlen - len,
   2812  1.79  christos 	    -stdzp->z_stdoff);
   2813  1.53  christos 	if (! offsetlen) {
   2814  1.25   mlelstv 		result[0] = '\0';
   2815  1.43  christos 		return -1;
   2816  1.25   mlelstv 	}
   2817  1.53  christos 	len += offsetlen;
   2818  1.25   mlelstv 	if (dstrp == NULL)
   2819  1.43  christos 		return compat;
   2820  1.79  christos 	len += doabbr(result + len, resultlen - len, dstzp, dstrp->r_abbrvar,
   2821  1.75  christos 		      dstrp->r_isdst, dstrp->r_save, true);
   2822  1.75  christos 	if (dstrp->r_save != SECSPERMIN * MINSPERHOUR) {
   2823  1.79  christos 		offsetlen = stringoffset(result + len, resultlen - len,
   2824  1.79  christos 				   - (dstzp->z_stdoff + dstrp->r_save));
   2825  1.53  christos 		if (! offsetlen) {
   2826  1.51  christos 			result[0] = '\0';
   2827  1.51  christos 			return -1;
   2828  1.25   mlelstv 		}
   2829  1.53  christos 		len += offsetlen;
   2830  1.53  christos 	}
   2831  1.53  christos 	result[len++] = ',';
   2832  1.79  christos 	c = stringrule(result + len, resultlen - len, dstrp, dstrp->r_save, stdzp->z_stdoff);
   2833  1.43  christos 	if (c < 0) {
   2834  1.25   mlelstv 		result[0] = '\0';
   2835  1.43  christos 		return -1;
   2836  1.25   mlelstv 	}
   2837  1.43  christos 	if (compat < c)
   2838  1.43  christos 		compat = c;
   2839  1.53  christos 	len += strlen(result + len);
   2840  1.53  christos 	result[len++] = ',';
   2841  1.79  christos 	c = stringrule(result + len, resultlen - len, stdrp, dstrp->r_save, stdzp->z_stdoff);
   2842  1.43  christos 	if (c < 0) {
   2843  1.25   mlelstv 		result[0] = '\0';
   2844  1.43  christos 		return -1;
   2845   1.1       jtc 	}
   2846  1.43  christos 	if (compat < c)
   2847  1.43  christos 		compat = c;
   2848  1.43  christos 	return compat;
   2849   1.1       jtc }
   2850   1.1       jtc 
   2851   1.1       jtc static void
   2852  1.65  christos outzone(const struct zone *zpfirst, ptrdiff_t zonecount)
   2853  1.31  christos {
   2854  1.65  christos 	ptrdiff_t		i, j;
   2855  1.31  christos 	zic_t			starttime, untiltime;
   2856  1.51  christos 	bool			startttisstd;
   2857  1.75  christos 	bool			startttisut;
   2858  1.31  christos 	char *			startbuf;
   2859  1.31  christos 	char *			ab;
   2860  1.31  christos 	char *			envvar;
   2861  1.36  christos 	size_t			max_abbr_len;
   2862  1.36  christos 	size_t			max_envvar_len;
   2863  1.51  christos 	bool			prodstic; /* all rules are min to max */
   2864  1.43  christos 	int			compat;
   2865  1.51  christos 	bool			do_extend;
   2866  1.75  christos 	char			version;
   2867  1.65  christos 	ptrdiff_t lastatmax = -1;
   2868  1.68  christos 	zic_t max_year0;
   2869  1.74  christos 	int defaulttype = -1;
   2870  1.25   mlelstv 
   2871  1.79  christos 	check_for_signal();
   2872  1.79  christos 
   2873  1.25   mlelstv 	max_abbr_len = 2 + max_format_len + max_abbrvar_len;
   2874  1.25   mlelstv 	max_envvar_len = 2 * max_abbr_len + 5 * 9;
   2875  1.53  christos 	startbuf = zic_malloc(max_abbr_len + 1);
   2876  1.53  christos 	ab = zic_malloc(max_abbr_len + 1);
   2877  1.53  christos 	envvar = zic_malloc(max_envvar_len + 1);
   2878   1.1       jtc 	INITIALIZE(untiltime);
   2879   1.1       jtc 	INITIALIZE(starttime);
   2880   1.1       jtc 	/*
   2881   1.1       jtc 	** Now. . .finally. . .generate some useful data!
   2882   1.1       jtc 	*/
   2883   1.1       jtc 	timecnt = 0;
   2884   1.1       jtc 	typecnt = 0;
   2885   1.1       jtc 	charcnt = 0;
   2886  1.29  christos 	prodstic = zonecount == 1;
   2887   1.1       jtc 	/*
   2888  1.25   mlelstv 	** Thanks to Earl Chew
   2889   1.1       jtc 	** for noting the need to unconditionally initialize startttisstd.
   2890   1.1       jtc 	*/
   2891  1.51  christos 	startttisstd = false;
   2892  1.75  christos 	startttisut = false;
   2893  1.25   mlelstv 	min_year = max_year = EPOCH_YEAR;
   2894  1.25   mlelstv 	if (leapseen) {
   2895  1.25   mlelstv 		updateminmax(leapminyear);
   2896  1.41  christos 		updateminmax(leapmaxyear + (leapmaxyear < ZIC_MAX));
   2897  1.25   mlelstv 	}
   2898  1.25   mlelstv 	for (i = 0; i < zonecount; ++i) {
   2899  1.82  christos 		struct zone const *zp = &zpfirst[i];
   2900  1.25   mlelstv 		if (i < zonecount - 1)
   2901  1.25   mlelstv 			updateminmax(zp->z_untilrule.r_loyear);
   2902  1.25   mlelstv 		for (j = 0; j < zp->z_nrules; ++j) {
   2903  1.82  christos 			struct rule *rp = &zp->z_rules[j];
   2904  1.25   mlelstv 			if (rp->r_lowasnum)
   2905  1.25   mlelstv 				updateminmax(rp->r_loyear);
   2906  1.25   mlelstv 			if (rp->r_hiwasnum)
   2907  1.25   mlelstv 				updateminmax(rp->r_hiyear);
   2908  1.41  christos 			if (rp->r_lowasnum || rp->r_hiwasnum)
   2909  1.51  christos 				prodstic = false;
   2910  1.25   mlelstv 		}
   2911  1.25   mlelstv 	}
   2912  1.25   mlelstv 	/*
   2913  1.25   mlelstv 	** Generate lots of data if a rule can't cover all future times.
   2914  1.25   mlelstv 	*/
   2915  1.43  christos 	compat = stringzone(envvar, max_envvar_len + 1, zpfirst, zonecount);
   2916  1.79  christos 	version = compat < 2013 ? '2' : '3';
   2917  1.75  christos 	do_extend = compat < 0;
   2918  1.44  christos 	if (noise) {
   2919  1.44  christos 		if (!*envvar)
   2920  1.43  christos 			warning("%s %s",
   2921  1.43  christos 				_("no POSIX environment variable for zone"),
   2922  1.43  christos 				zpfirst->z_name);
   2923  1.75  christos 		else if (compat != 0) {
   2924  1.43  christos 			/* Circa-COMPAT clients, and earlier clients, might
   2925  1.43  christos 			   not work for this zone when given dates before
   2926  1.43  christos 			   1970 or after 2038.  */
   2927  1.43  christos 			warning(_("%s: pre-%d clients may mishandle"
   2928  1.43  christos 				  " distant timestamps"),
   2929  1.43  christos 				zpfirst->z_name, compat);
   2930  1.43  christos 		}
   2931  1.43  christos 	}
   2932  1.43  christos 	if (do_extend) {
   2933  1.43  christos 		/*
   2934  1.43  christos 		** Search through a couple of extra years past the obvious
   2935  1.43  christos 		** 400, to avoid edge cases.  For example, suppose a non-POSIX
   2936  1.43  christos 		** rule applies from 2012 onwards and has transitions in March
   2937  1.43  christos 		** and September, plus some one-off transitions in November
   2938  1.43  christos 		** 2013.  If zic looked only at the last 400 years, it would
   2939  1.43  christos 		** set max_year=2413, with the intent that the 400 years 2014
   2940  1.43  christos 		** through 2413 will be repeated.  The last transition listed
   2941  1.43  christos 		** in the tzfile would be in 2413-09, less than 400 years
   2942  1.43  christos 		** after the last one-off transition in 2013-11.  Two years
   2943  1.43  christos 		** might be overkill, but with the kind of edge cases
   2944  1.43  christos 		** available we're not sure that one year would suffice.
   2945  1.43  christos 		*/
   2946  1.43  christos 		enum { years_of_observations = YEARSPERREPEAT + 2 };
   2947  1.43  christos 
   2948  1.43  christos 		if (min_year >= ZIC_MIN + years_of_observations)
   2949  1.43  christos 			min_year -= years_of_observations;
   2950  1.41  christos 		else	min_year = ZIC_MIN;
   2951  1.43  christos 		if (max_year <= ZIC_MAX - years_of_observations)
   2952  1.43  christos 			max_year += years_of_observations;
   2953  1.41  christos 		else	max_year = ZIC_MAX;
   2954  1.29  christos 		/*
   2955  1.29  christos 		** Regardless of any of the above,
   2956  1.29  christos 		** for a "proDSTic" zone which specifies that its rules
   2957  1.29  christos 		** always have and always will be in effect,
   2958  1.29  christos 		** we only need one cycle to define the zone.
   2959  1.29  christos 		*/
   2960  1.29  christos 		if (prodstic) {
   2961  1.29  christos 			min_year = 1900;
   2962  1.43  christos 			max_year = min_year + years_of_observations;
   2963  1.29  christos 		}
   2964  1.25   mlelstv 	}
   2965  1.82  christos 	max_year = max(max_year, (redundant_time / (SECSPERDAY * DAYSPERNYEAR)
   2966  1.82  christos 				  + EPOCH_YEAR + 1));
   2967  1.75  christos 	max_year0 = max_year;
   2968  1.75  christos 	if (want_bloat()) {
   2969  1.75  christos 	  /* For the benefit of older systems,
   2970  1.75  christos 	     generate data from 1900 through 2038.  */
   2971  1.75  christos 	  if (min_year > 1900)
   2972  1.25   mlelstv 		min_year = 1900;
   2973  1.75  christos 	  if (max_year < 2038)
   2974  1.68  christos 		max_year = 2038;
   2975  1.75  christos 	}
   2976  1.75  christos 
   2977  1.79  christos 	if (min_time < lo_time || hi_time < max_time)
   2978  1.79  christos 	  unspecifiedtype = addtype(0, "-00", false, false, false);
   2979  1.79  christos 
   2980   1.1       jtc 	for (i = 0; i < zonecount; ++i) {
   2981  1.75  christos 		struct rule *prevrp = NULL;
   2982  1.19    kleink 		/*
   2983  1.19    kleink 		** A guess that may well be corrected later.
   2984  1.19    kleink 		*/
   2985  1.82  christos 		zic_t save = 0;
   2986  1.82  christos 		struct zone const *zp = &zpfirst[i];
   2987  1.82  christos 		bool usestart = i > 0 && (zp - 1)->z_untiltime > min_time;
   2988  1.82  christos 		bool useuntil = i < (zonecount - 1);
   2989  1.82  christos 		zic_t stdoff = zp->z_stdoff;
   2990  1.82  christos 		zic_t startoff = stdoff;
   2991  1.82  christos 		zic_t prevktime;
   2992  1.82  christos 		INITIALIZE(prevktime);
   2993  1.74  christos 		if (useuntil && zp->z_untiltime <= min_time)
   2994   1.1       jtc 			continue;
   2995   1.1       jtc 		eat(zp->z_filename, zp->z_linenum);
   2996   1.5       jtc 		*startbuf = '\0';
   2997   1.1       jtc 		if (zp->z_nrules == 0) {
   2998  1.82  christos 			int type;
   2999  1.75  christos 			save = zp->z_save;
   3000  1.75  christos 			doabbr(startbuf, max_abbr_len + 1,
   3001  1.75  christos 			    zp, NULL, zp->z_isdst, save, false);
   3002  1.75  christos 			type = addtype(oadd(zp->z_stdoff, save),
   3003  1.74  christos 				startbuf, zp->z_isdst, startttisstd,
   3004  1.75  christos 				startttisut);
   3005   1.5       jtc 			if (usestart) {
   3006   1.1       jtc 				addtt(starttime, type);
   3007  1.51  christos 				usestart = false;
   3008  1.74  christos 			} else
   3009  1.74  christos 				defaulttype = type;
   3010  1.82  christos 		} else {
   3011  1.82  christos 		  zic_t year;
   3012  1.82  christos 		  for (year = min_year; year <= max_year; ++year) {
   3013   1.1       jtc 			if (useuntil && year > zp->z_untilrule.r_hiyear)
   3014   1.1       jtc 				break;
   3015   1.1       jtc 			/*
   3016   1.1       jtc 			** Mark which rules to do in the current year.
   3017   1.1       jtc 			** For those to do, calculate rpytime(rp, year);
   3018  1.77  christos 			** The former TYPE field was also considered here.
   3019   1.1       jtc 			*/
   3020   1.1       jtc 			for (j = 0; j < zp->z_nrules; ++j) {
   3021  1.82  christos 				zic_t one = 1;
   3022  1.82  christos 				zic_t y2038_boundary = one << 31;
   3023  1.82  christos 				struct rule *rp = &zp->z_rules[j];
   3024   1.1       jtc 				eats(zp->z_filename, zp->z_linenum,
   3025   1.1       jtc 					rp->r_filename, rp->r_linenum);
   3026   1.1       jtc 				rp->r_todo = year >= rp->r_loyear &&
   3027  1.77  christos 						year <= rp->r_hiyear;
   3028  1.68  christos 				if (rp->r_todo) {
   3029   1.1       jtc 					rp->r_temp = rpytime(rp, year);
   3030  1.68  christos 					rp->r_todo
   3031  1.68  christos 					  = (rp->r_temp < y2038_boundary
   3032  1.68  christos 					     || year <= max_year0);
   3033  1.68  christos 				}
   3034   1.1       jtc 			}
   3035   1.1       jtc 			for ( ; ; ) {
   3036  1.65  christos 				ptrdiff_t	k;
   3037  1.31  christos 				zic_t	jtime, ktime;
   3038  1.38  christos 				zic_t	offset;
   3039  1.82  christos 				struct rule *rp;
   3040  1.82  christos 				int type;
   3041   1.1       jtc 
   3042   1.1       jtc 				INITIALIZE(ktime);
   3043   1.1       jtc 				if (useuntil) {
   3044   1.1       jtc 					/*
   3045  1.43  christos 					** Turn untiltime into UT
   3046  1.75  christos 					** assuming the current stdoff and
   3047  1.75  christos 					** save values.
   3048   1.1       jtc 					*/
   3049   1.1       jtc 					untiltime = zp->z_untiltime;
   3050  1.75  christos 					if (!zp->z_untilrule.r_todisut)
   3051   1.1       jtc 						untiltime = tadd(untiltime,
   3052  1.75  christos 								 -stdoff);
   3053   1.1       jtc 					if (!zp->z_untilrule.r_todisstd)
   3054   1.1       jtc 						untiltime = tadd(untiltime,
   3055  1.75  christos 								 -save);
   3056  1.49  christos 				}
   3057   1.1       jtc 				/*
   3058   1.1       jtc 				** Find the rule (of those to do, if any)
   3059   1.1       jtc 				** that takes effect earliest in the year.
   3060   1.1       jtc 				*/
   3061   1.1       jtc 				k = -1;
   3062   1.1       jtc 				for (j = 0; j < zp->z_nrules; ++j) {
   3063  1.82  christos 					struct rule *r = &zp->z_rules[j];
   3064  1.82  christos 					if (!r->r_todo)
   3065   1.1       jtc 						continue;
   3066   1.1       jtc 					eats(zp->z_filename, zp->z_linenum,
   3067  1.82  christos 						r->r_filename, r->r_linenum);
   3068  1.82  christos 					offset = r->r_todisut ? 0 : stdoff;
   3069  1.82  christos 					if (!r->r_todisstd)
   3070  1.75  christos 						offset = oadd(offset, save);
   3071  1.82  christos 					jtime = r->r_temp;
   3072   1.1       jtc 					if (jtime == min_time ||
   3073   1.1       jtc 						jtime == max_time)
   3074   1.1       jtc 							continue;
   3075   1.1       jtc 					jtime = tadd(jtime, -offset);
   3076   1.1       jtc 					if (k < 0 || jtime < ktime) {
   3077   1.1       jtc 						k = j;
   3078   1.1       jtc 						ktime = jtime;
   3079  1.55  christos 					} else if (jtime == ktime) {
   3080  1.55  christos 					  char const *dup_rules_msg =
   3081  1.55  christos 					    _("two rules for same instant");
   3082  1.55  christos 					  eats(zp->z_filename, zp->z_linenum,
   3083  1.82  christos 					       r->r_filename, r->r_linenum);
   3084  1.55  christos 					  warning("%s", dup_rules_msg);
   3085  1.82  christos 					  r = &zp->z_rules[k];
   3086  1.55  christos 					  eats(zp->z_filename, zp->z_linenum,
   3087  1.82  christos 					       r->r_filename, r->r_linenum);
   3088  1.55  christos 					  error("%s", dup_rules_msg);
   3089   1.1       jtc 					}
   3090   1.1       jtc 				}
   3091   1.1       jtc 				if (k < 0)
   3092   1.1       jtc 					break;	/* go on to next year */
   3093   1.1       jtc 				rp = &zp->z_rules[k];
   3094  1.51  christos 				rp->r_todo = false;
   3095  1.82  christos 				if (useuntil && ktime >= untiltime) {
   3096  1.82  christos 					if (!*startbuf
   3097  1.82  christos 					    && (oadd(zp->z_stdoff, rp->r_save)
   3098  1.82  christos 						== startoff))
   3099  1.82  christos 					  doabbr(startbuf, max_abbr_len + 1,
   3100  1.82  christos 						 zp, rp->r_abbrvar,
   3101  1.82  christos 						 rp->r_isdst, rp->r_save,
   3102  1.82  christos 						 false);
   3103   1.1       jtc 					break;
   3104  1.82  christos 				}
   3105  1.75  christos 				save = rp->r_save;
   3106   1.5       jtc 				if (usestart && ktime == starttime)
   3107  1.51  christos 					usestart = false;
   3108   1.1       jtc 				if (usestart) {
   3109   1.5       jtc 					if (ktime < starttime) {
   3110  1.75  christos 						startoff = oadd(zp->z_stdoff,
   3111  1.75  christos 								save);
   3112  1.25   mlelstv 						doabbr(startbuf,
   3113  1.25   mlelstv 							max_abbr_len + 1,
   3114  1.55  christos 							zp,
   3115   1.5       jtc 							rp->r_abbrvar,
   3116  1.71  christos 							rp->r_isdst,
   3117  1.75  christos 							rp->r_save,
   3118  1.51  christos 							false);
   3119   1.5       jtc 						continue;
   3120   1.5       jtc 					}
   3121  1.75  christos 					if (*startbuf == '\0'
   3122  1.75  christos 					    && startoff == oadd(zp->z_stdoff,
   3123  1.75  christos 								save)) {
   3124  1.25   mlelstv 							doabbr(startbuf,
   3125  1.25   mlelstv 								max_abbr_len + 1,
   3126  1.55  christos 								zp,
   3127  1.25   mlelstv 								rp->r_abbrvar,
   3128  1.71  christos 								rp->r_isdst,
   3129  1.75  christos 								rp->r_save,
   3130  1.51  christos 								false);
   3131   1.1       jtc 					}
   3132   1.1       jtc 				}
   3133   1.1       jtc 				eats(zp->z_filename, zp->z_linenum,
   3134   1.1       jtc 					rp->r_filename, rp->r_linenum);
   3135  1.55  christos 				doabbr(ab, max_abbr_len + 1, zp, rp->r_abbrvar,
   3136  1.75  christos 				       rp->r_isdst, rp->r_save, false);
   3137  1.75  christos 				offset = oadd(zp->z_stdoff, rp->r_save);
   3138  1.75  christos 				if (!want_bloat() && !useuntil && !do_extend
   3139  1.79  christos 				    && prevrp && lo_time <= prevktime
   3140  1.82  christos 				    && redundant_time <= ktime
   3141  1.75  christos 				    && rp->r_hiyear == ZIC_MAX
   3142  1.75  christos 				    && prevrp->r_hiyear == ZIC_MAX)
   3143  1.75  christos 				  break;
   3144  1.71  christos 				type = addtype(offset, ab, rp->r_isdst,
   3145  1.75  christos 					rp->r_todisstd, rp->r_todisut);
   3146  1.74  christos 				if (defaulttype < 0 && !rp->r_isdst)
   3147  1.74  christos 				  defaulttype = type;
   3148  1.63  christos 				if (rp->r_hiyear == ZIC_MAX
   3149  1.63  christos 				    && ! (0 <= lastatmax
   3150  1.63  christos 					  && ktime < attypes[lastatmax].at))
   3151  1.63  christos 				  lastatmax = timecnt;
   3152   1.1       jtc 				addtt(ktime, type);
   3153  1.75  christos 				prevrp = rp;
   3154  1.79  christos 				prevktime = ktime;
   3155   1.1       jtc 			}
   3156  1.82  christos 		  }
   3157   1.1       jtc 		}
   3158   1.5       jtc 		if (usestart) {
   3159  1.82  christos 			bool isdst = startoff != zp->z_stdoff;
   3160  1.82  christos 			if (*startbuf == '\0' && zp->z_format)
   3161  1.82  christos 			  doabbr(startbuf, max_abbr_len + 1,
   3162  1.82  christos 				 zp, disable_percent_s,
   3163  1.82  christos 				 isdst, save, false);
   3164   1.5       jtc 			eat(zp->z_filename, zp->z_linenum);
   3165   1.5       jtc 			if (*startbuf == '\0')
   3166   1.7       jtc error(_("can't determine time zone abbreviation to use just after until time"));
   3167  1.74  christos 			else {
   3168  1.82  christos 			  int type = addtype(startoff, startbuf, isdst,
   3169  1.82  christos 					     startttisstd, startttisut);
   3170  1.74  christos 			  if (defaulttype < 0 && !isdst)
   3171  1.74  christos 			    defaulttype = type;
   3172  1.74  christos 			  addtt(starttime, type);
   3173  1.74  christos 			}
   3174   1.5       jtc 		}
   3175   1.1       jtc 		/*
   3176   1.1       jtc 		** Now we may get to set starttime for the next zone line.
   3177   1.1       jtc 		*/
   3178   1.1       jtc 		if (useuntil) {
   3179   1.1       jtc 			startttisstd = zp->z_untilrule.r_todisstd;
   3180  1.75  christos 			startttisut = zp->z_untilrule.r_todisut;
   3181   1.5       jtc 			starttime = zp->z_untiltime;
   3182   1.1       jtc 			if (!startttisstd)
   3183  1.75  christos 			  starttime = tadd(starttime, -save);
   3184  1.75  christos 			if (!startttisut)
   3185  1.75  christos 			  starttime = tadd(starttime, -stdoff);
   3186   1.1       jtc 		}
   3187   1.1       jtc 	}
   3188  1.74  christos 	if (defaulttype < 0)
   3189  1.74  christos 	  defaulttype = 0;
   3190  1.63  christos 	if (0 <= lastatmax)
   3191  1.63  christos 	  attypes[lastatmax].dontmerge = true;
   3192  1.43  christos 	if (do_extend) {
   3193  1.43  christos 		/*
   3194  1.43  christos 		** If we're extending the explicitly listed observations
   3195  1.43  christos 		** for 400 years because we can't fill the POSIX-TZ field,
   3196  1.43  christos 		** check whether we actually ended up explicitly listing
   3197  1.43  christos 		** observations through that period.  If there aren't any
   3198  1.43  christos 		** near the end of the 400-year period, add a redundant
   3199  1.43  christos 		** one at the end of the final year, to make it clear
   3200  1.43  christos 		** that we are claiming to have definite knowledge of
   3201  1.43  christos 		** the lack of transitions up to that point.
   3202  1.43  christos 		*/
   3203  1.43  christos 		struct rule xr;
   3204  1.43  christos 		struct attype *lastat;
   3205  1.58  dholland 		memset(&xr, 0, sizeof(xr));
   3206  1.43  christos 		xr.r_month = TM_JANUARY;
   3207  1.43  christos 		xr.r_dycode = DC_DOM;
   3208  1.43  christos 		xr.r_dayofmonth = 1;
   3209  1.43  christos 		xr.r_tod = 0;
   3210  1.74  christos 		for (lastat = attypes, i = 1; i < timecnt; i++)
   3211  1.43  christos 			if (attypes[i].at > lastat->at)
   3212  1.43  christos 				lastat = &attypes[i];
   3213  1.74  christos 		if (!lastat || lastat->at < rpytime(&xr, max_year - 1)) {
   3214  1.74  christos 			addtt(rpytime(&xr, max_year + 1),
   3215  1.74  christos 			      lastat ? lastat->type : defaulttype);
   3216  1.63  christos 			attypes[timecnt - 1].dontmerge = true;
   3217  1.43  christos 		}
   3218  1.43  christos 	}
   3219  1.74  christos 	writezone(zpfirst->z_name, envvar, version, defaulttype);
   3220  1.31  christos 	free(startbuf);
   3221  1.31  christos 	free(ab);
   3222  1.31  christos 	free(envvar);
   3223   1.1       jtc }
   3224   1.1       jtc 
   3225   1.1       jtc static void
   3226  1.55  christos addtt(zic_t starttime, int type)
   3227   1.1       jtc {
   3228  1.45  christos 	attypes = growalloc(attypes, sizeof *attypes, timecnt, &timecnt_alloc);
   3229   1.5       jtc 	attypes[timecnt].at = starttime;
   3230  1.63  christos 	attypes[timecnt].dontmerge = false;
   3231   1.5       jtc 	attypes[timecnt].type = type;
   3232   1.1       jtc 	++timecnt;
   3233   1.1       jtc }
   3234   1.1       jtc 
   3235   1.1       jtc static int
   3236  1.75  christos addtype(zic_t utoff, char const *abbr, bool isdst, bool ttisstd, bool ttisut)
   3237   1.1       jtc {
   3238  1.31  christos 	int	i, j;
   3239   1.1       jtc 
   3240  1.75  christos 	if (! (-1L - 2147483647L <= utoff && utoff <= 2147483647L)) {
   3241  1.75  christos 		error(_("UT offset out of range"));
   3242  1.75  christos 		exit(EXIT_FAILURE);
   3243  1.75  christos 	}
   3244  1.75  christos 	if (!want_bloat())
   3245  1.75  christos 	  ttisstd = ttisut = false;
   3246  1.75  christos 
   3247  1.75  christos 	for (j = 0; j < charcnt; ++j)
   3248  1.75  christos 		if (strcmp(&chars[j], abbr) == 0)
   3249  1.75  christos 			break;
   3250  1.75  christos 	if (j == charcnt)
   3251  1.75  christos 		newabbr(abbr);
   3252  1.75  christos 	else {
   3253  1.75  christos 	  /* If there's already an entry, return its index.  */
   3254  1.75  christos 	  for (i = 0; i < typecnt; i++)
   3255  1.75  christos 	    if (utoff == utoffs[i] && isdst == isdsts[i] && j == desigidx[i]
   3256  1.75  christos 		&& ttisstd == ttisstds[i] && ttisut == ttisuts[i])
   3257  1.75  christos 	      return i;
   3258   1.1       jtc 	}
   3259   1.1       jtc 	/*
   3260   1.1       jtc 	** There isn't one; add a new one, unless there are already too
   3261   1.1       jtc 	** many.
   3262   1.1       jtc 	*/
   3263   1.1       jtc 	if (typecnt >= TZ_MAX_TYPES) {
   3264   1.5       jtc 		error(_("too many local time types"));
   3265  1.25   mlelstv 		exit(EXIT_FAILURE);
   3266  1.25   mlelstv 	}
   3267  1.75  christos 	i = typecnt++;
   3268  1.75  christos 	utoffs[i] = utoff;
   3269   1.1       jtc 	isdsts[i] = isdst;
   3270   1.1       jtc 	ttisstds[i] = ttisstd;
   3271  1.75  christos 	ttisuts[i] = ttisut;
   3272  1.75  christos 	desigidx[i] = j;
   3273   1.1       jtc 	return i;
   3274   1.1       jtc }
   3275   1.1       jtc 
   3276   1.1       jtc static void
   3277  1.76  christos leapadd(zic_t t, int correction, int rolling)
   3278   1.1       jtc {
   3279  1.76  christos 	int	i;
   3280   1.1       jtc 
   3281  1.76  christos 	if (TZ_MAX_LEAPS <= leapcnt) {
   3282   1.5       jtc 		error(_("too many leap seconds"));
   3283  1.25   mlelstv 		exit(EXIT_FAILURE);
   3284   1.1       jtc 	}
   3285  1.79  christos 	if (rolling && (lo_time != min_time || hi_time != max_time)) {
   3286  1.79  christos 	  error(_("Rolling leap seconds not supported with -r"));
   3287  1.79  christos 	  exit(EXIT_FAILURE);
   3288  1.79  christos 	}
   3289   1.1       jtc 	for (i = 0; i < leapcnt; ++i)
   3290  1.69  christos 		if (t <= trans[i])
   3291   1.1       jtc 			break;
   3292  1.76  christos 	memmove(&trans[i + 1], &trans[i], (leapcnt - i) * sizeof *trans);
   3293  1.76  christos 	memmove(&corr[i + 1], &corr[i], (leapcnt - i) * sizeof *corr);
   3294  1.76  christos 	memmove(&roll[i + 1], &roll[i], (leapcnt - i) * sizeof *roll);
   3295  1.76  christos 	trans[i] = t;
   3296  1.76  christos 	corr[i] = correction;
   3297  1.76  christos 	roll[i] = rolling;
   3298  1.76  christos 	++leapcnt;
   3299   1.1       jtc }
   3300   1.1       jtc 
   3301   1.1       jtc static void
   3302  1.25   mlelstv adjleap(void)
   3303   1.1       jtc {
   3304  1.31  christos 	int	i;
   3305  1.38  christos 	zic_t	last = 0;
   3306  1.69  christos 	zic_t	prevtrans = 0;
   3307   1.1       jtc 
   3308   1.1       jtc 	/*
   3309   1.1       jtc 	** propagate leap seconds forward
   3310   1.1       jtc 	*/
   3311   1.1       jtc 	for (i = 0; i < leapcnt; ++i) {
   3312  1.69  christos 		if (trans[i] - prevtrans < 28 * SECSPERDAY) {
   3313  1.69  christos 			error(_("Leap seconds too close together"));
   3314  1.69  christos 			exit(EXIT_FAILURE);
   3315  1.69  christos 		}
   3316  1.69  christos 		prevtrans = trans[i];
   3317   1.1       jtc 		trans[i] = tadd(trans[i], last);
   3318   1.1       jtc 		last = corr[i] += last;
   3319   1.1       jtc 	}
   3320  1.76  christos 
   3321  1.76  christos 	if (0 <= leapexpires) {
   3322  1.76  christos 	  leapexpires = oadd(leapexpires, last);
   3323  1.76  christos 	  if (! (leapcnt == 0 || (trans[leapcnt - 1] < leapexpires))) {
   3324  1.76  christos 	    error(_("last Leap time does not precede Expires time"));
   3325  1.76  christos 	    exit(EXIT_FAILURE);
   3326  1.76  christos 	  }
   3327  1.76  christos 	}
   3328   1.1       jtc }
   3329   1.1       jtc 
   3330  1.47  christos /* Is A a space character in the C locale?  */
   3331  1.51  christos static bool
   3332  1.47  christos is_space(char a)
   3333   1.1       jtc {
   3334  1.47  christos 	switch (a) {
   3335  1.47  christos 	  default:
   3336  1.51  christos 		return false;
   3337  1.47  christos 	  case ' ': case '\f': case '\n': case '\r': case '\t': case '\v':
   3338  1.51  christos 	  	return true;
   3339  1.47  christos 	}
   3340  1.47  christos }
   3341  1.47  christos 
   3342  1.47  christos /* Is A an alphabetic character in the C locale?  */
   3343  1.51  christos static bool
   3344  1.47  christos is_alpha(char a)
   3345  1.47  christos {
   3346  1.47  christos 	switch (a) {
   3347  1.47  christos 	  default:
   3348  1.74  christos 		return false;
   3349  1.47  christos 	  case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
   3350  1.47  christos 	  case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
   3351  1.47  christos 	  case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
   3352  1.47  christos 	  case 'V': case 'W': case 'X': case 'Y': case 'Z':
   3353  1.47  christos 	  case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
   3354  1.47  christos 	  case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
   3355  1.47  christos 	  case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
   3356  1.47  christos 	  case 'v': case 'w': case 'x': case 'y': case 'z':
   3357  1.51  christos 		return true;
   3358  1.47  christos 	}
   3359  1.47  christos }
   3360  1.47  christos 
   3361  1.47  christos /* If A is an uppercase character in the C locale, return its lowercase
   3362  1.47  christos    counterpart.  Otherwise, return A.  */
   3363  1.47  christos static char
   3364  1.47  christos lowerit(char a)
   3365  1.47  christos {
   3366  1.47  christos 	switch (a) {
   3367  1.47  christos 	  default: return a;
   3368  1.47  christos 	  case 'A': return 'a'; case 'B': return 'b'; case 'C': return 'c';
   3369  1.47  christos 	  case 'D': return 'd'; case 'E': return 'e'; case 'F': return 'f';
   3370  1.47  christos 	  case 'G': return 'g'; case 'H': return 'h'; case 'I': return 'i';
   3371  1.47  christos 	  case 'J': return 'j'; case 'K': return 'k'; case 'L': return 'l';
   3372  1.47  christos 	  case 'M': return 'm'; case 'N': return 'n'; case 'O': return 'o';
   3373  1.47  christos 	  case 'P': return 'p'; case 'Q': return 'q'; case 'R': return 'r';
   3374  1.47  christos 	  case 'S': return 's'; case 'T': return 't'; case 'U': return 'u';
   3375  1.47  christos 	  case 'V': return 'v'; case 'W': return 'w'; case 'X': return 'x';
   3376  1.47  christos 	  case 'Y': return 'y'; case 'Z': return 'z';
   3377  1.47  christos 	}
   3378   1.1       jtc }
   3379   1.1       jtc 
   3380  1.31  christos /* case-insensitive equality */
   3381  1.73  christos static ATTRIBUTE_PURE bool
   3382  1.31  christos ciequal(const char *ap, const char *bp)
   3383   1.1       jtc {
   3384   1.1       jtc 	while (lowerit(*ap) == lowerit(*bp++))
   3385   1.1       jtc 		if (*ap++ == '\0')
   3386  1.51  christos 			return true;
   3387  1.51  christos 	return false;
   3388   1.1       jtc }
   3389   1.1       jtc 
   3390  1.73  christos static ATTRIBUTE_PURE bool
   3391  1.31  christos itsabbr(const char *abbr, const char *word)
   3392   1.1       jtc {
   3393   1.1       jtc 	if (lowerit(*abbr) != lowerit(*word))
   3394  1.51  christos 		return false;
   3395   1.1       jtc 	++word;
   3396   1.1       jtc 	while (*++abbr != '\0')
   3397   1.3       jtc 		do {
   3398   1.3       jtc 			if (*word == '\0')
   3399  1.51  christos 				return false;
   3400   1.3       jtc 		} while (lowerit(*word++) != lowerit(*abbr));
   3401  1.51  christos 	return true;
   3402   1.1       jtc }
   3403   1.1       jtc 
   3404  1.69  christos /* Return true if ABBR is an initial prefix of WORD, ignoring ASCII case.  */
   3405  1.69  christos 
   3406  1.73  christos static ATTRIBUTE_PURE bool
   3407  1.69  christos ciprefix(char const *abbr, char const *word)
   3408  1.69  christos {
   3409  1.69  christos   do
   3410  1.69  christos     if (!*abbr)
   3411  1.69  christos       return true;
   3412  1.69  christos   while (lowerit(*abbr++) == lowerit(*word++));
   3413  1.69  christos 
   3414  1.69  christos   return false;
   3415  1.69  christos }
   3416  1.69  christos 
   3417  1.69  christos static const struct lookup *
   3418  1.55  christos byword(const char *word, const struct lookup *table)
   3419   1.1       jtc {
   3420  1.31  christos 	const struct lookup *	foundlp;
   3421  1.31  christos 	const struct lookup *	lp;
   3422   1.1       jtc 
   3423   1.1       jtc 	if (word == NULL || table == NULL)
   3424   1.1       jtc 		return NULL;
   3425  1.69  christos 
   3426  1.69  christos 	/* If TABLE is LASTS and the word starts with "last" followed
   3427  1.69  christos 	   by a non-'-', skip the "last" and look in WDAY_NAMES instead.
   3428  1.69  christos 	   Warn about any usage of the undocumented prefix "last-".  */
   3429  1.69  christos 	if (table == lasts && ciprefix("last", word) && word[4]) {
   3430  1.69  christos 	  if (word[4] == '-')
   3431  1.69  christos 	    warning(_("\"%s\" is undocumented; use \"last%s\" instead"),
   3432  1.69  christos 		    word, word + 5);
   3433  1.69  christos 	  else {
   3434  1.69  christos 	    word += 4;
   3435  1.69  christos 	    table = wday_names;
   3436  1.69  christos 	  }
   3437  1.69  christos 	}
   3438  1.69  christos 
   3439   1.1       jtc 	/*
   3440   1.1       jtc 	** Look for exact match.
   3441   1.1       jtc 	*/
   3442   1.1       jtc 	for (lp = table; lp->l_word != NULL; ++lp)
   3443   1.1       jtc 		if (ciequal(word, lp->l_word))
   3444   1.1       jtc 			return lp;
   3445   1.1       jtc 	/*
   3446   1.1       jtc 	** Look for inexact match.
   3447   1.1       jtc 	*/
   3448   1.1       jtc 	foundlp = NULL;
   3449   1.1       jtc 	for (lp = table; lp->l_word != NULL; ++lp)
   3450  1.69  christos 		if (ciprefix(word, lp->l_word)) {
   3451   1.1       jtc 			if (foundlp == NULL)
   3452   1.1       jtc 				foundlp = lp;
   3453   1.1       jtc 			else	return NULL;	/* multiple inexact matches */
   3454  1.11       jtc 		}
   3455  1.69  christos 
   3456  1.75  christos 	if (foundlp && noise) {
   3457  1.75  christos 	  /* Warn about any backward-compatibility issue with pre-2017c zic.  */
   3458  1.69  christos 	  bool pre_2017c_match = false;
   3459  1.69  christos 	  for (lp = table; lp->l_word; lp++)
   3460  1.69  christos 	    if (itsabbr(word, lp->l_word)) {
   3461  1.69  christos 	      if (pre_2017c_match) {
   3462  1.69  christos 		warning(_("\"%s\" is ambiguous in pre-2017c zic"), word);
   3463  1.69  christos 		break;
   3464  1.69  christos 	      }
   3465  1.69  christos 	      pre_2017c_match = true;
   3466  1.69  christos 	    }
   3467  1.69  christos 	}
   3468  1.69  christos 
   3469   1.1       jtc 	return foundlp;
   3470   1.1       jtc }
   3471   1.1       jtc 
   3472  1.82  christos static int
   3473  1.82  christos getfields(char *cp, char **array, int arrayelts)
   3474   1.1       jtc {
   3475  1.31  christos 	char *	dp;
   3476  1.31  christos 	int	nsubs;
   3477   1.1       jtc 
   3478   1.1       jtc 	nsubs = 0;
   3479   1.1       jtc 	for ( ; ; ) {
   3480  1.82  christos 		char *dstart;
   3481  1.47  christos 		while (is_space(*cp))
   3482  1.25   mlelstv 				++cp;
   3483   1.1       jtc 		if (*cp == '\0' || *cp == '#')
   3484   1.1       jtc 			break;
   3485  1.82  christos 		dstart = dp = cp;
   3486   1.1       jtc 		do {
   3487   1.1       jtc 			if ((*dp = *cp++) != '"')
   3488   1.1       jtc 				++dp;
   3489   1.1       jtc 			else while ((*dp = *cp++) != '"')
   3490   1.1       jtc 				if (*dp != '\0')
   3491   1.1       jtc 					++dp;
   3492  1.25   mlelstv 				else {
   3493  1.65  christos 				  error(_("Odd number of quotation marks"));
   3494  1.65  christos 				  exit(EXIT_FAILURE);
   3495  1.25   mlelstv 				}
   3496  1.47  christos 		} while (*cp && *cp != '#' && !is_space(*cp));
   3497  1.47  christos 		if (is_space(*cp))
   3498   1.1       jtc 			++cp;
   3499   1.1       jtc 		*dp = '\0';
   3500  1.82  christos 		if (nsubs == arrayelts) {
   3501  1.82  christos 		  error(_("Too many input fields"));
   3502  1.82  christos 		  exit(EXIT_FAILURE);
   3503  1.82  christos 		}
   3504  1.82  christos 		array[nsubs++] = dstart + (*dstart == '-' && dp == dstart + 1);
   3505   1.1       jtc 	}
   3506  1.82  christos 	return nsubs;
   3507   1.1       jtc }
   3508   1.1       jtc 
   3509  1.53  christos static _Noreturn void
   3510  1.53  christos time_overflow(void)
   3511  1.53  christos {
   3512  1.53  christos 	error(_("time overflow"));
   3513  1.53  christos 	exit(EXIT_FAILURE);
   3514  1.53  christos }
   3515  1.53  christos 
   3516  1.41  christos static ATTRIBUTE_PURE zic_t
   3517  1.55  christos oadd(zic_t t1, zic_t t2)
   3518   1.1       jtc {
   3519  1.53  christos 	if (t1 < 0 ? t2 < ZIC_MIN - t1 : ZIC_MAX - t1 < t2)
   3520  1.53  christos 		time_overflow();
   3521  1.31  christos 	return t1 + t2;
   3522   1.1       jtc }
   3523   1.1       jtc 
   3524  1.43  christos static ATTRIBUTE_PURE zic_t
   3525  1.55  christos tadd(zic_t t1, zic_t t2)
   3526   1.1       jtc {
   3527  1.53  christos 	if (t1 < 0) {
   3528  1.53  christos 		if (t2 < min_time - t1) {
   3529  1.53  christos 			if (t1 != min_time)
   3530  1.53  christos 				time_overflow();
   3531  1.53  christos 			return min_time;
   3532  1.53  christos 		}
   3533  1.53  christos 	} else {
   3534  1.53  christos 		if (max_time - t1 < t2) {
   3535  1.53  christos 			if (t1 != max_time)
   3536  1.53  christos 				time_overflow();
   3537  1.53  christos 			return max_time;
   3538  1.53  christos 		}
   3539   1.1       jtc 	}
   3540  1.31  christos 	return t1 + t2;
   3541   1.1       jtc }
   3542   1.1       jtc 
   3543   1.1       jtc /*
   3544  1.47  christos ** Given a rule, and a year, compute the date (in seconds since January 1,
   3545  1.47  christos ** 1970, 00:00 LOCAL time) in that year that the rule refers to.
   3546   1.1       jtc */
   3547   1.1       jtc 
   3548  1.25   mlelstv static zic_t
   3549  1.55  christos rpytime(const struct rule *rp, zic_t wantedy)
   3550  1.31  christos {
   3551  1.41  christos 	int	m, i;
   3552  1.38  christos 	zic_t	dayoff;			/* with a nod to Margaret O. */
   3553  1.41  christos 	zic_t	t, y;
   3554  1.79  christos 	int yrem;
   3555   1.1       jtc 
   3556  1.41  christos 	if (wantedy == ZIC_MIN)
   3557   1.1       jtc 		return min_time;
   3558  1.41  christos 	if (wantedy == ZIC_MAX)
   3559   1.1       jtc 		return max_time;
   3560   1.1       jtc 	m = TM_JANUARY;
   3561   1.1       jtc 	y = EPOCH_YEAR;
   3562  1.79  christos 
   3563  1.79  christos 	/* dayoff = floor((wantedy - y) / YEARSPERREPEAT) * DAYSPERREPEAT,
   3564  1.79  christos 	   sans overflow.  */
   3565  1.79  christos 	yrem = wantedy % YEARSPERREPEAT - y % YEARSPERREPEAT;
   3566  1.79  christos 	dayoff = ((wantedy / YEARSPERREPEAT - y / YEARSPERREPEAT
   3567  1.79  christos 		   + yrem / YEARSPERREPEAT - (yrem % YEARSPERREPEAT < 0))
   3568  1.79  christos 		  * DAYSPERREPEAT);
   3569  1.79  christos 	/* wantedy = y + ((wantedy - y) mod YEARSPERREPEAT), sans overflow.  */
   3570  1.79  christos 	wantedy = y + (yrem + 2 * YEARSPERREPEAT) % YEARSPERREPEAT;
   3571  1.79  christos 
   3572   1.1       jtc 	while (wantedy != y) {
   3573  1.79  christos 		i = len_years[isleap(y)];
   3574  1.41  christos 		dayoff = oadd(dayoff, i);
   3575  1.79  christos 		y++;
   3576   1.1       jtc 	}
   3577   1.1       jtc 	while (m != rp->r_month) {
   3578   1.1       jtc 		i = len_months[isleap(y)][m];
   3579  1.41  christos 		dayoff = oadd(dayoff, i);
   3580   1.1       jtc 		++m;
   3581   1.1       jtc 	}
   3582   1.1       jtc 	i = rp->r_dayofmonth;
   3583   1.1       jtc 	if (m == TM_FEBRUARY && i == 29 && !isleap(y)) {
   3584   1.1       jtc 		if (rp->r_dycode == DC_DOWLEQ)
   3585   1.1       jtc 			--i;
   3586   1.1       jtc 		else {
   3587   1.5       jtc 			error(_("use of 2/29 in non leap-year"));
   3588  1.25   mlelstv 			exit(EXIT_FAILURE);
   3589   1.1       jtc 		}
   3590   1.1       jtc 	}
   3591   1.1       jtc 	--i;
   3592  1.41  christos 	dayoff = oadd(dayoff, i);
   3593   1.1       jtc 	if (rp->r_dycode == DC_DOWGEQ || rp->r_dycode == DC_DOWLEQ) {
   3594   1.1       jtc 		/*
   3595   1.1       jtc 		** Don't trust mod of negative numbers.
   3596   1.1       jtc 		*/
   3597  1.79  christos 		zic_t wday = ((EPOCH_WDAY + dayoff % DAYSPERWEEK + DAYSPERWEEK)
   3598  1.79  christos 			      % DAYSPERWEEK);
   3599  1.41  christos 		while (wday != rp->r_wday)
   3600   1.1       jtc 			if (rp->r_dycode == DC_DOWGEQ) {
   3601  1.38  christos 				dayoff = oadd(dayoff, (zic_t) 1);
   3602  1.79  christos 				if (++wday >= DAYSPERWEEK)
   3603   1.1       jtc 					wday = 0;
   3604   1.1       jtc 				++i;
   3605   1.1       jtc 			} else {
   3606  1.38  christos 				dayoff = oadd(dayoff, (zic_t) -1);
   3607   1.1       jtc 				if (--wday < 0)
   3608  1.79  christos 					wday = DAYSPERWEEK - 1;
   3609   1.1       jtc 				--i;
   3610   1.1       jtc 			}
   3611   1.1       jtc 		if (i < 0 || i >= len_months[isleap(y)][m]) {
   3612  1.23    kleink 			if (noise)
   3613  1.47  christos 				warning(_("rule goes past start/end of month; \
   3614  1.25   mlelstv will not work with pre-2004 versions of zic"));
   3615   1.1       jtc 		}
   3616   1.1       jtc 	}
   3617  1.34    martin 	if (dayoff < min_time / SECSPERDAY)
   3618  1.20    kleink 		return min_time;
   3619  1.34    martin 	if (dayoff > max_time / SECSPERDAY)
   3620  1.20    kleink 		return max_time;
   3621  1.25   mlelstv 	t = (zic_t) dayoff * SECSPERDAY;
   3622   1.1       jtc 	return tadd(t, rp->r_tod);
   3623   1.1       jtc }
   3624   1.1       jtc 
   3625   1.1       jtc static void
   3626  1.55  christos newabbr(const char *string)
   3627   1.1       jtc {
   3628  1.31  christos 	int	i;
   3629   1.1       jtc 
   3630  1.25   mlelstv 	if (strcmp(string, GRANDPARENTED) != 0) {
   3631  1.31  christos 		const char *	cp;
   3632  1.31  christos 		const char *	mp;
   3633  1.25   mlelstv 
   3634  1.25   mlelstv 		cp = string;
   3635  1.31  christos 		mp = NULL;
   3636  1.55  christos 		while (is_alpha(*cp) || ('0' <= *cp && *cp <= '9')
   3637  1.55  christos 		       || *cp == '-' || *cp == '+')
   3638  1.25   mlelstv 				++cp;
   3639  1.35  christos 		if (noise && cp - string < 3)
   3640  1.55  christos 		  mp = _("time zone abbreviation has fewer than 3 characters");
   3641  1.25   mlelstv 		if (cp - string > ZIC_MAX_ABBR_LEN_WO_WARN)
   3642  1.55  christos 		  mp = _("time zone abbreviation has too many characters");
   3643  1.25   mlelstv 		if (*cp != '\0')
   3644  1.31  christos mp = _("time zone abbreviation differs from POSIX standard");
   3645  1.43  christos 		if (mp != NULL)
   3646  1.43  christos 			warning("%s (%s)", mp, string);
   3647  1.25   mlelstv 	}
   3648   1.1       jtc 	i = strlen(string) + 1;
   3649   1.1       jtc 	if (charcnt + i > TZ_MAX_CHARS) {
   3650  1.40  christos 		error(_("too many, or too long, time zone abbreviations"));
   3651  1.25   mlelstv 		exit(EXIT_FAILURE);
   3652   1.1       jtc 	}
   3653  1.57  christos 	strncpy(&chars[charcnt], string, sizeof(chars) - charcnt - 1);
   3654  1.41  christos 	charcnt += i;
   3655   1.1       jtc }
   3656  1.63  christos 
   3657  1.63  christos /* Ensure that the directories of ARGNAME exist, by making any missing
   3658  1.63  christos    ones.  If ANCESTORS, do this only for ARGNAME's ancestors; otherwise,
   3659  1.68  christos    do it for ARGNAME too.  Exit with failure if there is trouble.
   3660  1.79  christos    Do not consider an existing file to be trouble.  */
   3661  1.63  christos static void
   3662  1.63  christos mkdirs(char const *argname, bool ancestors)
   3663   1.1       jtc {
   3664  1.31  christos 	char *	name;
   3665  1.31  christos 	char *	cp;
   3666   1.1       jtc 
   3667   1.1       jtc 	cp = name = ecpyalloc(argname);
   3668  1.63  christos 
   3669  1.69  christos 	/* On MS-Windows systems, do not worry about drive letters or
   3670  1.69  christos 	   backslashes, as this should suffice in practice.  Time zone
   3671  1.69  christos 	   names do not use drive letters and backslashes.  If the -d
   3672  1.69  christos 	   option of zic does not name an already-existing directory,
   3673  1.69  christos 	   it can use slashes to separate the already-existing
   3674  1.69  christos 	   ancestor prefix from the to-be-created subdirectories.  */
   3675  1.69  christos 
   3676  1.63  christos 	/* Do not mkdir a root directory, as it must exist.  */
   3677  1.63  christos 	while (*cp == '/')
   3678  1.63  christos 	  cp++;
   3679  1.63  christos 
   3680  1.63  christos 	while (cp && ((cp = strchr(cp, '/')) || !ancestors)) {
   3681  1.63  christos 		if (cp)
   3682  1.63  christos 		  *cp = '\0';
   3683  1.47  christos 		/*
   3684  1.47  christos 		** Try to create it.  It's OK if creation fails because
   3685  1.47  christos 		** the directory already exists, perhaps because some
   3686  1.63  christos 		** other process just created it.  For simplicity do
   3687  1.63  christos 		** not check first whether it already exists, as that
   3688  1.63  christos 		** is checked anyway if the mkdir fails.
   3689  1.47  christos 		*/
   3690  1.47  christos 		if (mkdir(name, MKDIR_UMASK) != 0) {
   3691  1.79  christos 			/* Do not report an error if err == EEXIST, because
   3692  1.79  christos 			   some other process might have made the directory
   3693  1.81  christos 			   in the meantime.  Likewise for ENOSYS, because
   3694  1.81  christos 			   Solaris 10 mkdir fails with ENOSYS if the
   3695  1.81  christos 			   directory is an automounted mount point.  */
   3696  1.47  christos 			int err = errno;
   3697  1.81  christos 			if (err != EEXIST && err != ENOSYS) {
   3698  1.63  christos 				error(_("%s: Can't create directory %s: %s"),
   3699  1.63  christos 				      progname, name, strerror(err));
   3700  1.63  christos 				exit(EXIT_FAILURE);
   3701  1.63  christos 			}
   3702   1.1       jtc 		}
   3703  1.63  christos 		if (cp)
   3704  1.63  christos 		  *cp++ = '/';
   3705   1.1       jtc 	}
   3706  1.31  christos 	free(name);
   3707   1.1       jtc }
   3708