Home | History | Annotate | Line # | Download | only in ntpq
ntpq.c revision 1.22
      1  1.22  christos /*	$NetBSD: ntpq.c,v 1.22 2020/05/27 23:52:19 christos Exp $	*/
      2   1.1    kardel 
      3   1.1    kardel /*
      4   1.1    kardel  * ntpq - query an NTP server using mode 6 commands
      5   1.1    kardel  */
      6   1.9  christos #include <config.h>
      7   1.1    kardel #include <ctype.h>
      8   1.1    kardel #include <signal.h>
      9   1.1    kardel #include <setjmp.h>
     10  1.19  christos #include <stddef.h>
     11  1.19  christos #include <stdio.h>
     12   1.1    kardel #include <sys/types.h>
     13   1.1    kardel #include <sys/time.h>
     14   1.9  christos #ifdef HAVE_UNISTD_H
     15   1.9  christos # include <unistd.h>
     16   1.9  christos #endif
     17   1.9  christos #ifdef HAVE_FCNTL_H
     18   1.9  christos # include <fcntl.h>
     19   1.9  christos #endif
     20   1.9  christos #ifdef SYS_WINNT
     21   1.9  christos # include <mswsock.h>
     22   1.9  christos #endif
     23   1.9  christos #include <isc/net.h>
     24   1.9  christos #include <isc/result.h>
     25   1.1    kardel 
     26   1.1    kardel #include "ntpq.h"
     27  1.12  christos #include "ntp_assert.h"
     28   1.9  christos #include "ntp_stdlib.h"
     29   1.1    kardel #include "ntp_unixtime.h"
     30   1.1    kardel #include "ntp_calendar.h"
     31   1.1    kardel #include "ntp_select.h"
     32   1.1    kardel #include "ntp_assert.h"
     33   1.9  christos #include "lib_strbuf.h"
     34   1.1    kardel #include "ntp_lineedit.h"
     35   1.1    kardel #include "ntp_debug.h"
     36   1.9  christos #ifdef OPENSSL
     37  1.20  christos # include "openssl/evp.h"
     38  1.20  christos # include "openssl/objects.h"
     39  1.20  christos # include "openssl/err.h"
     40  1.20  christos # ifdef SYS_WINNT
     41  1.20  christos #  include "openssl/opensslv.h"
     42  1.20  christos #  if !defined(HAVE_EVP_MD_DO_ALL_SORTED) && OPENSSL_VERSION_NUMBER > 0x10000000L
     43  1.20  christos #     define HAVE_EVP_MD_DO_ALL_SORTED	1
     44  1.20  christos #  endif
     45  1.20  christos # endif
     46  1.20  christos # include "libssl_compat.h"
     47  1.20  christos # ifdef HAVE_OPENSSL_CMAC_H
     48  1.20  christos #  include <openssl/cmac.h>
     49  1.20  christos #  define CMAC "AES128CMAC"
     50  1.19  christos # endif
     51  1.19  christos #endif
     52   1.1    kardel #include <ssl_applink.c>
     53   1.1    kardel 
     54   1.4    kardel #include "ntp_libopts.h"
     55  1.14  christos #include "safecast.h"
     56   1.1    kardel 
     57   1.9  christos #ifdef SYS_VXWORKS		/* vxWorks needs mode flag -casey*/
     58   1.1    kardel # define open(name, flags)   open(name, flags, 0777)
     59   1.1    kardel # define SERVER_PORT_NUM     123
     60   1.1    kardel #endif
     61   1.1    kardel 
     62   1.1    kardel /* we use COMMAND as an autogen keyword */
     63   1.1    kardel #ifdef COMMAND
     64   1.1    kardel # undef COMMAND
     65   1.1    kardel #endif
     66   1.1    kardel 
     67   1.1    kardel /*
     68   1.1    kardel  * Because we potentially understand a lot of commands we will run
     69   1.1    kardel  * interactive if connected to a terminal.
     70   1.1    kardel  */
     71   1.1    kardel int interactive = 0;		/* set to 1 when we should prompt */
     72   1.1    kardel const char *prompt = "ntpq> ";	/* prompt to ask him about */
     73   1.1    kardel 
     74   1.1    kardel /*
     75   1.1    kardel  * use old readvars behavior?  --old-rv processing in ntpq resets
     76   1.1    kardel  * this value based on the presence or absence of --old-rv.  It is
     77   1.1    kardel  * initialized to 1 here to maintain backward compatibility with
     78   1.1    kardel  * libntpq clients such as ntpsnmpd, which are free to reset it as
     79   1.1    kardel  * desired.
     80   1.1    kardel  */
     81   1.1    kardel int	old_rv = 1;
     82   1.1    kardel 
     83  1.15  christos /*
     84  1.15  christos  * How should we display the refid?
     85  1.15  christos  * REFID_HASH, REFID_IPV4
     86  1.15  christos  */
     87  1.15  christos te_Refid drefid = -1;
     88   1.1    kardel 
     89   1.1    kardel /*
     90   1.1    kardel  * for get_systime()
     91   1.1    kardel  */
     92   1.1    kardel s_char	sys_precision;		/* local clock precision (log2 s) */
     93   1.1    kardel 
     94   1.1    kardel /*
     95   1.1    kardel  * Keyid used for authenticated requests.  Obtained on the fly.
     96   1.1    kardel  */
     97   1.1    kardel u_long info_auth_keyid = 0;
     98   1.1    kardel 
     99   1.1    kardel static	int	info_auth_keytype = NID_md5;	/* MD5 */
    100   1.1    kardel static	size_t	info_auth_hashlen = 16;		/* MD5 */
    101   1.1    kardel u_long	current_time;		/* needed by authkeys; not used */
    102   1.1    kardel 
    103   1.1    kardel /*
    104   1.1    kardel  * Flag which indicates we should always send authenticated requests
    105   1.1    kardel  */
    106   1.1    kardel int always_auth = 0;
    107   1.1    kardel 
    108   1.1    kardel /*
    109   1.1    kardel  * Flag which indicates raw mode output.
    110   1.1    kardel  */
    111   1.1    kardel int rawmode = 0;
    112   1.1    kardel 
    113   1.1    kardel /*
    114   1.1    kardel  * Packet version number we use
    115   1.1    kardel  */
    116   1.1    kardel u_char pktversion = NTP_OLDVERSION + 1;
    117   1.1    kardel 
    118   1.1    kardel 
    119   1.1    kardel /*
    120   1.1    kardel  * Format values
    121   1.1    kardel  */
    122   1.1    kardel #define	PADDING	0
    123   1.9  christos #define	HA	1	/* host address */
    124   1.9  christos #define	NA	2	/* network address */
    125   1.9  christos #define	LP	3	/* leap (print in binary) */
    126   1.9  christos #define	RF	4	/* refid (sometimes string, sometimes not) */
    127  1.21  christos #define	AU	5	/* array of unsigned times */
    128   1.9  christos #define FX	6	/* test flags */
    129   1.9  christos #define TS	7	/* l_fp timestamp in hex */
    130   1.9  christos #define	OC	8	/* integer, print in octal */
    131  1.21  christos #define	AS	9	/* array of signed times */
    132  1.21  christos #define	SN	10	/* signed number: must display +/- sign */
    133   1.1    kardel #define	EOV	255	/* end of table */
    134   1.1    kardel 
    135   1.1    kardel /*
    136   1.9  christos  * For the most part ntpq simply displays what ntpd provides in the
    137   1.9  christos  * mostly plain-text mode 6 responses.  A few variable names are by
    138   1.9  christos  * default "cooked" to provide more human-friendly output.
    139   1.9  christos  */
    140   1.9  christos const var_format cookedvars[] = {
    141   1.9  christos 	{ "leap",		LP },
    142   1.9  christos 	{ "reach",		OC },
    143   1.9  christos 	{ "refid",		RF },
    144   1.9  christos 	{ "reftime",		TS },
    145   1.9  christos 	{ "clock",		TS },
    146   1.9  christos 	{ "org",		TS },
    147   1.9  christos 	{ "rec",		TS },
    148   1.9  christos 	{ "xmt",		TS },
    149   1.9  christos 	{ "flash",		FX },
    150   1.9  christos 	{ "srcadr",		HA },
    151   1.9  christos 	{ "peeradr",		HA },	/* compat with others */
    152   1.9  christos 	{ "dstadr",		NA },
    153  1.21  christos 	{ "filtdelay",		AU },
    154  1.21  christos 	{ "filtoffset",		AS },
    155  1.21  christos 	{ "filtdisp",		AU },
    156  1.21  christos 	{ "filterror",		AU },	/* compat with others */
    157  1.21  christos 	{ "offset",		SN },
    158  1.21  christos 	{ "frequency",		SN }
    159   1.1    kardel };
    160   1.1    kardel 
    161   1.1    kardel 
    162   1.1    kardel 
    163   1.1    kardel /*
    164   1.1    kardel  * flasher bits
    165   1.1    kardel  */
    166   1.1    kardel static const char *tstflagnames[] = {
    167   1.1    kardel 	"pkt_dup",		/* TEST1 */
    168   1.1    kardel 	"pkt_bogus",		/* TEST2 */
    169   1.1    kardel 	"pkt_unsync",		/* TEST3 */
    170   1.1    kardel 	"pkt_denied",		/* TEST4 */
    171   1.1    kardel 	"pkt_auth",		/* TEST5 */
    172   1.1    kardel 	"pkt_stratum",		/* TEST6 */
    173   1.1    kardel 	"pkt_header",		/* TEST7 */
    174   1.1    kardel 	"pkt_autokey",		/* TEST8 */
    175   1.1    kardel 	"pkt_crypto",		/* TEST9 */
    176   1.1    kardel 	"peer_stratum",		/* TEST10 */
    177   1.1    kardel 	"peer_dist",		/* TEST11 */
    178   1.1    kardel 	"peer_loop",		/* TEST12 */
    179   1.1    kardel 	"peer_unreach"		/* TEST13 */
    180   1.1    kardel };
    181   1.1    kardel 
    182   1.1    kardel 
    183   1.1    kardel int		ntpqmain	(int,	char **);
    184   1.1    kardel /*
    185   1.1    kardel  * Built in command handler declarations
    186   1.1    kardel  */
    187   1.9  christos static	int	openhost	(const char *, int);
    188   1.9  christos static	void	dump_hex_printable(const void *, size_t);
    189   1.1    kardel static	int	sendpkt		(void *, size_t);
    190  1.14  christos static	int	getresponse	(int, int, u_short *, size_t *, const char **, int);
    191  1.14  christos static	int	sendrequest	(int, associd_t, int, size_t, const char *);
    192   1.1    kardel static	char *	tstflags	(u_long);
    193   1.1    kardel #ifndef BUILD_AS_LIB
    194   1.1    kardel static	void	getcmds		(void);
    195   1.1    kardel #ifndef SYS_WINNT
    196  1.14  christos static	int	abortcmd	(void);
    197   1.1    kardel #endif	/* SYS_WINNT */
    198   1.1    kardel static	void	docmd		(const char *);
    199   1.1    kardel static	void	tokenize	(const char *, char **, int *);
    200   1.9  christos static	int	getarg		(const char *, int, arg_v *);
    201   1.1    kardel #endif	/* BUILD_AS_LIB */
    202   1.9  christos static	int	findcmd		(const char *, struct xcmd *,
    203   1.9  christos 				 struct xcmd *, struct xcmd **);
    204   1.1    kardel static	int	rtdatetolfp	(char *, l_fp *);
    205  1.19  christos static	int	decodearr	(char *, int *, l_fp *, int);
    206   1.1    kardel static	void	help		(struct parse *, FILE *);
    207   1.1    kardel static	int	helpsort	(const void *, const void *);
    208   1.1    kardel static	void	printusage	(struct xcmd *, FILE *);
    209   1.1    kardel static	void	timeout		(struct parse *, FILE *);
    210   1.1    kardel static	void	auth_delay	(struct parse *, FILE *);
    211   1.1    kardel static	void	host		(struct parse *, FILE *);
    212   1.1    kardel static	void	ntp_poll	(struct parse *, FILE *);
    213   1.1    kardel static	void	keyid		(struct parse *, FILE *);
    214   1.1    kardel static	void	keytype		(struct parse *, FILE *);
    215   1.1    kardel static	void	passwd		(struct parse *, FILE *);
    216   1.1    kardel static	void	hostnames	(struct parse *, FILE *);
    217   1.1    kardel static	void	setdebug	(struct parse *, FILE *);
    218   1.1    kardel static	void	quit		(struct parse *, FILE *);
    219  1.15  christos static	void	showdrefid	(struct parse *, FILE *);
    220   1.1    kardel static	void	version		(struct parse *, FILE *);
    221   1.1    kardel static	void	raw		(struct parse *, FILE *);
    222   1.1    kardel static	void	cooked		(struct parse *, FILE *);
    223   1.1    kardel static	void	authenticate	(struct parse *, FILE *);
    224   1.1    kardel static	void	ntpversion	(struct parse *, FILE *);
    225  1.20  christos static	void	warning		(const char *, ...) NTP_PRINTF(1, 2);
    226  1.20  christos static	void	error		(const char *, ...) NTP_PRINTF(1, 2);
    227   1.1    kardel static	u_long	getkeyid	(const char *);
    228   1.1    kardel static	void	atoascii	(const char *, size_t, char *, size_t);
    229  1.14  christos static	void	cookedprint	(int, size_t, const char *, int, int, FILE *);
    230  1.14  christos static	void	rawprint	(int, size_t, const char *, int, int, FILE *);
    231   1.1    kardel static	void	startoutput	(void);
    232   1.9  christos static	void	output		(FILE *, const char *, const char *);
    233   1.1    kardel static	void	endoutput	(FILE *);
    234  1.21  christos static	void	outputarr	(FILE *, char *, int, l_fp *, int);
    235   1.1    kardel static	int	assoccmp	(const void *, const void *);
    236  1.20  christos 	u_short	varfmt		(const char *);
    237  1.20  christos 	void	ntpq_custom_opt_handler(tOptions *, tOptDesc *);
    238  1.20  christos 
    239  1.20  christos #ifndef BUILD_AS_LIB
    240  1.20  christos static	char   *list_digest_names(void);
    241  1.20  christos static	char   *insert_cmac	(char *list);
    242  1.14  christos static	void	on_ctrlc	(void);
    243  1.15  christos static	int	my_easprintf	(char**, const char *, ...) NTP_PRINTF(2, 3);
    244  1.20  christos # if defined(OPENSSL) && defined(HAVE_EVP_MD_DO_ALL_SORTED)
    245  1.20  christos static	void	list_md_fn	(const EVP_MD *m, const char *from,
    246  1.20  christos 				 const char *to, void *arg);
    247  1.20  christos # endif /* defined(OPENSSL) && defined(HAVE_EVP_MD_DO_ALL_SORTED) */
    248  1.20  christos #endif /* !defined(BUILD_AS_LIB) */
    249  1.20  christos 
    250   1.1    kardel 
    251  1.19  christos /* read a character from memory and expand to integer */
    252  1.19  christos static inline int
    253  1.19  christos pgetc(
    254  1.19  christos 	const char *cp
    255  1.19  christos 	)
    256  1.19  christos {
    257  1.19  christos 	return (int)*(const unsigned char*)cp;
    258  1.19  christos }
    259  1.19  christos 
    260  1.19  christos 
    261   1.1    kardel 
    262   1.1    kardel /*
    263   1.1    kardel  * Built-in commands we understand
    264   1.1    kardel  */
    265   1.1    kardel struct xcmd builtins[] = {
    266   1.1    kardel 	{ "?",		help,		{  OPT|NTP_STR, NO, NO, NO },
    267   1.1    kardel 	  { "command", "", "", "" },
    268   1.1    kardel 	  "tell the use and syntax of commands" },
    269   1.1    kardel 	{ "help",	help,		{  OPT|NTP_STR, NO, NO, NO },
    270   1.1    kardel 	  { "command", "", "", "" },
    271   1.1    kardel 	  "tell the use and syntax of commands" },
    272   1.1    kardel 	{ "timeout",	timeout,	{ OPT|NTP_UINT, NO, NO, NO },
    273   1.1    kardel 	  { "msec", "", "", "" },
    274   1.1    kardel 	  "set the primary receive time out" },
    275   1.1    kardel 	{ "delay",	auth_delay,	{ OPT|NTP_INT, NO, NO, NO },
    276   1.1    kardel 	  { "msec", "", "", "" },
    277   1.1    kardel 	  "set the delay added to encryption time stamps" },
    278   1.1    kardel 	{ "host",	host,		{ OPT|NTP_STR, OPT|NTP_STR, NO, NO },
    279   1.1    kardel 	  { "-4|-6", "hostname", "", "" },
    280   1.1    kardel 	  "specify the host whose NTP server we talk to" },
    281   1.1    kardel 	{ "poll",	ntp_poll,	{ OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
    282   1.1    kardel 	  { "n", "verbose", "", "" },
    283   1.1    kardel 	  "poll an NTP server in client mode `n' times" },
    284   1.9  christos 	{ "passwd",	passwd,		{ OPT|NTP_STR, NO, NO, NO },
    285   1.1    kardel 	  { "", "", "", "" },
    286   1.1    kardel 	  "specify a password to use for authenticated requests"},
    287   1.1    kardel 	{ "hostnames",	hostnames,	{ OPT|NTP_STR, NO, NO, NO },
    288   1.1    kardel 	  { "yes|no", "", "", "" },
    289   1.1    kardel 	  "specify whether hostnames or net numbers are printed"},
    290   1.1    kardel 	{ "debug",	setdebug,	{ OPT|NTP_STR, NO, NO, NO },
    291   1.1    kardel 	  { "no|more|less", "", "", "" },
    292   1.1    kardel 	  "set/change debugging level" },
    293   1.1    kardel 	{ "quit",	quit,		{ NO, NO, NO, NO },
    294   1.1    kardel 	  { "", "", "", "" },
    295   1.1    kardel 	  "exit ntpq" },
    296   1.1    kardel 	{ "exit",	quit,		{ NO, NO, NO, NO },
    297   1.1    kardel 	  { "", "", "", "" },
    298   1.1    kardel 	  "exit ntpq" },
    299   1.1    kardel 	{ "keyid",	keyid,		{ OPT|NTP_UINT, NO, NO, NO },
    300   1.1    kardel 	  { "key#", "", "", "" },
    301   1.1    kardel 	  "set keyid to use for authenticated requests" },
    302  1.15  christos 	{ "drefid",	showdrefid,	{ OPT|NTP_STR, NO, NO, NO },
    303  1.15  christos 	  { "hash|ipv4", "", "", "" },
    304  1.15  christos 	  "display refid's as IPv4 or hash" },
    305   1.1    kardel 	{ "version",	version,	{ NO, NO, NO, NO },
    306   1.1    kardel 	  { "", "", "", "" },
    307   1.1    kardel 	  "print version number" },
    308   1.1    kardel 	{ "raw",	raw,		{ NO, NO, NO, NO },
    309   1.1    kardel 	  { "", "", "", "" },
    310   1.1    kardel 	  "do raw mode variable output" },
    311   1.1    kardel 	{ "cooked",	cooked,		{ NO, NO, NO, NO },
    312   1.1    kardel 	  { "", "", "", "" },
    313   1.1    kardel 	  "do cooked mode variable output" },
    314   1.1    kardel 	{ "authenticate", authenticate,	{ OPT|NTP_STR, NO, NO, NO },
    315   1.1    kardel 	  { "yes|no", "", "", "" },
    316   1.1    kardel 	  "always authenticate requests to this server" },
    317   1.1    kardel 	{ "ntpversion",	ntpversion,	{ OPT|NTP_UINT, NO, NO, NO },
    318   1.1    kardel 	  { "version number", "", "", "" },
    319   1.1    kardel 	  "set the NTP version number to use for requests" },
    320   1.1    kardel 	{ "keytype",	keytype,	{ OPT|NTP_STR, NO, NO, NO },
    321  1.12  christos 	  { "key type %s", "", "", "" },
    322  1.12  christos 	  NULL },
    323   1.1    kardel 	{ 0,		0,		{ NO, NO, NO, NO },
    324   1.1    kardel 	  { "", "", "", "" }, "" }
    325   1.1    kardel };
    326   1.1    kardel 
    327   1.1    kardel 
    328   1.1    kardel /*
    329   1.1    kardel  * Default values we use.
    330   1.1    kardel  */
    331   1.1    kardel #define	DEFHOST		"localhost"	/* default host name */
    332   1.9  christos #define	DEFTIMEOUT	5		/* wait 5 seconds for 1st pkt */
    333   1.9  christos #define	DEFSTIMEOUT	3		/* and 3 more for each additional */
    334   1.9  christos /*
    335   1.9  christos  * Requests are automatically retried once, so total timeout with no
    336   1.9  christos  * response is a bit over 2 * DEFTIMEOUT, or 10 seconds.  At the other
    337   1.9  christos  * extreme, a request eliciting 32 packets of responses each for some
    338   1.9  christos  * reason nearly DEFSTIMEOUT seconds after the prior in that series,
    339   1.9  christos  * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
    340   1.9  christos  * 93 seconds to fail each of two times, or 186 seconds.
    341   1.9  christos  * Some commands involve a series of requests, such as "peers" and
    342   1.9  christos  * "mrulist", so the cumulative timeouts are even longer for those.
    343   1.9  christos  */
    344   1.1    kardel #define	DEFDELAY	0x51EB852	/* 20 milliseconds, l_fp fraction */
    345   1.1    kardel #define	LENHOSTNAME	256		/* host name is 256 characters long */
    346   1.1    kardel #define	MAXCMDS		100		/* maximum commands on cmd line */
    347   1.1    kardel #define	MAXHOSTS	200		/* maximum hosts on cmd line */
    348   1.1    kardel #define	MAXLINE		512		/* maximum line length */
    349   1.1    kardel #define	MAXTOKENS	(1+MAXARGS+2)	/* maximum number of usable tokens */
    350   1.1    kardel #define	MAXVARLEN	256		/* maximum length of a variable name */
    351   1.9  christos #define	MAXVALLEN	2048		/* maximum length of a variable value */
    352   1.1    kardel #define	MAXOUTLINE	72		/* maximum length of an output line */
    353   1.1    kardel #define SCREENWIDTH	76		/* nominal screen width in columns */
    354   1.1    kardel 
    355   1.1    kardel /*
    356   1.1    kardel  * Some variables used and manipulated locally
    357   1.1    kardel  */
    358   1.1    kardel struct sock_timeval tvout = { DEFTIMEOUT, 0 };	/* time out for reads */
    359   1.1    kardel struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
    360   1.1    kardel l_fp delay_time;				/* delay time */
    361   1.1    kardel char currenthost[LENHOSTNAME];			/* current host name */
    362   1.4    kardel int currenthostisnum;				/* is prior text from IP? */
    363   1.5    kardel struct sockaddr_in hostaddr;			/* host address */
    364   1.1    kardel int showhostnames = 1;				/* show host names by default */
    365  1.10  christos int wideremote = 0;				/* show wide remote names? */
    366   1.1    kardel 
    367   1.1    kardel int ai_fam_templ;				/* address family */
    368   1.1    kardel int ai_fam_default;				/* default address family */
    369   1.1    kardel SOCKET sockfd;					/* fd socket is opened on */
    370   1.1    kardel int havehost = 0;				/* set to 1 when host open */
    371   1.1    kardel int s_port = 0;
    372   1.1    kardel struct servent *server_entry = NULL;		/* server entry for ntp */
    373   1.1    kardel 
    374   1.1    kardel 
    375   1.1    kardel /*
    376   1.1    kardel  * Sequence number used for requests.  It is incremented before
    377   1.1    kardel  * it is used.
    378   1.1    kardel  */
    379   1.1    kardel u_short sequence;
    380   1.1    kardel 
    381   1.1    kardel /*
    382   1.1    kardel  * Holds data returned from queries.  Declare buffer long to be sure of
    383   1.1    kardel  * alignment.
    384   1.1    kardel  */
    385   1.1    kardel #define	DATASIZE	(MAXFRAGS*480)	/* maximum amount of data */
    386   1.1    kardel long pktdata[DATASIZE/sizeof(long)];
    387   1.1    kardel 
    388   1.1    kardel /*
    389   1.9  christos  * assoc_cache[] is a dynamic array which allows references to
    390   1.9  christos  * associations using &1 ... &N for n associations, avoiding manual
    391   1.9  christos  * lookup of the current association IDs for a given ntpd.  It also
    392   1.9  christos  * caches the status word for each association, retrieved incidentally.
    393   1.9  christos  */
    394   1.9  christos struct association *	assoc_cache;
    395   1.9  christos u_int assoc_cache_slots;/* count of allocated array entries */
    396   1.9  christos u_int numassoc;		/* number of cached associations */
    397   1.1    kardel 
    398   1.1    kardel /*
    399   1.1    kardel  * For commands typed on the command line (with the -c option)
    400   1.1    kardel  */
    401  1.12  christos size_t numcmds = 0;
    402   1.1    kardel const char *ccmds[MAXCMDS];
    403   1.1    kardel #define	ADDCMD(cp)	if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
    404   1.1    kardel 
    405   1.1    kardel /*
    406   1.1    kardel  * When multiple hosts are specified.
    407   1.1    kardel  */
    408   1.1    kardel 
    409   1.9  christos u_int numhosts;
    410   1.9  christos 
    411   1.9  christos chost chosts[MAXHOSTS];
    412   1.9  christos #define	ADDHOST(cp)						\
    413   1.9  christos 	do {							\
    414   1.9  christos 		if (numhosts < MAXHOSTS) {			\
    415   1.9  christos 			chosts[numhosts].name = (cp);		\
    416   1.9  christos 			chosts[numhosts].fam = ai_fam_templ;	\
    417   1.9  christos 			numhosts++;				\
    418   1.9  christos 		}						\
    419   1.9  christos 	} while (0)
    420   1.1    kardel 
    421   1.1    kardel /*
    422   1.1    kardel  * Macro definitions we use
    423   1.1    kardel  */
    424   1.1    kardel #define	ISSPACE(c)	((c) == ' ' || (c) == '\t')
    425   1.1    kardel #define	ISEOL(c)	((c) == '\n' || (c) == '\r' || (c) == '\0')
    426   1.1    kardel #define	STREQ(a, b)	(*(a) == *(b) && strcmp((a), (b)) == 0)
    427   1.1    kardel 
    428   1.1    kardel /*
    429  1.20  christos  * Jump buffer for longjumping back to the command level.
    430  1.20  christos  *
    431  1.20  christos  * Since we do this from a signal handler, we use 'sig{set,long}jmp()'
    432  1.20  christos  * if available. The signal is blocked by default during the excution of
    433  1.20  christos  * a signal handler, and it is unspecified if '{set,long}jmp()' save and
    434  1.20  christos  * restore the signal mask. They do on BSD, it depends on the GLIBC
    435  1.20  christos  * version on Linux, and the gods know what happens on other OSes...
    436  1.20  christos  *
    437  1.20  christos  * So we use the 'sig{set,long}jmp()' functions where available, because
    438  1.20  christos  * for them the semantics are well-defined. If we have to fall back to
    439  1.20  christos  * '{set,long}jmp()', the CTRL-C handling might be a bit erratic.
    440  1.20  christos  */
    441  1.20  christos #if HAVE_DECL_SIGSETJMP && HAVE_DECL_SIGLONGJMP
    442  1.20  christos # define JMP_BUF	sigjmp_buf
    443  1.20  christos # define SETJMP(x)	sigsetjmp((x), 1)
    444  1.20  christos # define LONGJMP(x, v)	siglongjmp((x),(v))
    445  1.20  christos #else
    446  1.20  christos # define JMP_BUF	jmp_buf
    447  1.20  christos # define SETJMP(x)	setjmp((x))
    448  1.20  christos # define LONGJMP(x, v)	longjmp((x),(v))
    449  1.20  christos #endif
    450  1.20  christos static	JMP_BUF		interrupt_buf;
    451  1.20  christos static	volatile int	jump = 0;
    452   1.1    kardel 
    453   1.1    kardel /*
    454   1.1    kardel  * Points at file being currently printed into
    455   1.1    kardel  */
    456  1.20  christos FILE *current_output = NULL;
    457   1.1    kardel 
    458   1.1    kardel /*
    459   1.1    kardel  * Command table imported from ntpdc_ops.c
    460   1.1    kardel  */
    461   1.1    kardel extern struct xcmd opcmds[];
    462   1.1    kardel 
    463  1.13  christos char const *progname;
    464   1.1    kardel 
    465   1.1    kardel #ifdef NO_MAIN_ALLOWED
    466   1.1    kardel #ifndef BUILD_AS_LIB
    467   1.1    kardel CALL(ntpq,"ntpq",ntpqmain);
    468   1.1    kardel 
    469   1.1    kardel void clear_globals(void)
    470   1.1    kardel {
    471   1.1    kardel 	extern int ntp_optind;
    472   1.1    kardel 	showhostnames = 0;	/* don'tshow host names by default */
    473   1.1    kardel 	ntp_optind = 0;
    474   1.1    kardel 	server_entry = NULL;	/* server entry for ntp */
    475   1.1    kardel 	havehost = 0;		/* set to 1 when host open */
    476   1.1    kardel 	numassoc = 0;		/* number of cached associations */
    477   1.1    kardel 	numcmds = 0;
    478   1.1    kardel 	numhosts = 0;
    479   1.1    kardel }
    480   1.1    kardel #endif /* !BUILD_AS_LIB */
    481   1.1    kardel #endif /* NO_MAIN_ALLOWED */
    482   1.1    kardel 
    483   1.1    kardel /*
    484   1.1    kardel  * main - parse arguments and handle options
    485   1.1    kardel  */
    486   1.1    kardel #ifndef NO_MAIN_ALLOWED
    487   1.1    kardel int
    488   1.1    kardel main(
    489   1.1    kardel 	int argc,
    490   1.1    kardel 	char *argv[]
    491   1.1    kardel 	)
    492   1.1    kardel {
    493   1.1    kardel 	return ntpqmain(argc, argv);
    494   1.1    kardel }
    495   1.1    kardel #endif
    496   1.1    kardel 
    497  1.19  christos 
    498   1.1    kardel #ifndef BUILD_AS_LIB
    499   1.1    kardel int
    500   1.1    kardel ntpqmain(
    501   1.1    kardel 	int argc,
    502   1.1    kardel 	char *argv[]
    503   1.1    kardel 	)
    504   1.1    kardel {
    505   1.9  christos 	u_int ihost;
    506  1.12  christos 	size_t icmd;
    507   1.9  christos 
    508   1.1    kardel 
    509   1.1    kardel #ifdef SYS_VXWORKS
    510   1.1    kardel 	clear_globals();
    511   1.1    kardel 	taskPrioritySet(taskIdSelf(), 100 );
    512   1.1    kardel #endif
    513   1.1    kardel 
    514   1.1    kardel 	delay_time.l_ui = 0;
    515   1.1    kardel 	delay_time.l_uf = DEFDELAY;
    516   1.1    kardel 
    517   1.1    kardel 	init_lib();	/* sets up ipv4_works, ipv6_works */
    518   1.1    kardel 	ssl_applink();
    519   1.9  christos 	init_auth();
    520   1.1    kardel 
    521   1.1    kardel 	/* Check to see if we have IPv6. Otherwise default to IPv4 */
    522   1.1    kardel 	if (!ipv6_works)
    523   1.1    kardel 		ai_fam_default = AF_INET;
    524   1.1    kardel 
    525  1.12  christos 	/* Fixup keytype's help based on available digest names */
    526  1.12  christos 
    527  1.12  christos 	{
    528  1.12  christos 	    char *list;
    529  1.12  christos 	    char *msg;
    530  1.12  christos 
    531  1.12  christos 	    list = list_digest_names();
    532  1.19  christos 
    533  1.19  christos 	    for (icmd = 0; icmd < sizeof(builtins)/sizeof(*builtins); icmd++) {
    534  1.19  christos 		if (strcmp("keytype", builtins[icmd].keyword) == 0) {
    535  1.12  christos 		    break;
    536  1.19  christos 		}
    537  1.12  christos 	    }
    538  1.12  christos 
    539  1.12  christos 	    /* CID: 1295478 */
    540  1.12  christos 	    /* This should only "trip" if "keytype" is removed from builtins */
    541  1.19  christos 	    INSIST(icmd < sizeof(builtins)/sizeof(*builtins));
    542  1.12  christos 
    543  1.12  christos #ifdef OPENSSL
    544  1.12  christos 	    builtins[icmd].desc[0] = "digest-name";
    545  1.15  christos 	    my_easprintf(&msg,
    546  1.15  christos 			 "set key type to use for authenticated requests, one of:%s",
    547  1.15  christos 			 list);
    548  1.12  christos #else
    549  1.12  christos 	    builtins[icmd].desc[0] = "md5";
    550  1.15  christos 	    my_easprintf(&msg,
    551  1.15  christos 			 "set key type to use for authenticated requests (%s)",
    552  1.15  christos 			 list);
    553  1.12  christos #endif
    554  1.12  christos 	    builtins[icmd].comment = msg;
    555  1.12  christos 	    free(list);
    556  1.12  christos 	}
    557  1.12  christos 
    558   1.1    kardel 	progname = argv[0];
    559   1.1    kardel 
    560   1.1    kardel 	{
    561   1.4    kardel 		int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
    562   1.1    kardel 		argc -= optct;
    563   1.1    kardel 		argv += optct;
    564   1.1    kardel 	}
    565   1.1    kardel 
    566   1.1    kardel 	/*
    567   1.1    kardel 	 * Process options other than -c and -p, which are specially
    568   1.1    kardel 	 * handled by ntpq_custom_opt_handler().
    569   1.1    kardel 	 */
    570   1.1    kardel 
    571   1.9  christos 	debug = OPT_VALUE_SET_DEBUG_LEVEL;
    572   1.1    kardel 
    573   1.1    kardel 	if (HAVE_OPT(IPV4))
    574   1.1    kardel 		ai_fam_templ = AF_INET;
    575   1.1    kardel 	else if (HAVE_OPT(IPV6))
    576   1.1    kardel 		ai_fam_templ = AF_INET6;
    577   1.1    kardel 	else
    578   1.1    kardel 		ai_fam_templ = ai_fam_default;
    579   1.1    kardel 
    580   1.1    kardel 	if (HAVE_OPT(INTERACTIVE))
    581   1.1    kardel 		interactive = 1;
    582   1.1    kardel 
    583   1.1    kardel 	if (HAVE_OPT(NUMERIC))
    584   1.1    kardel 		showhostnames = 0;
    585   1.1    kardel 
    586  1.10  christos 	if (HAVE_OPT(WIDE))
    587  1.10  christos 		wideremote = 1;
    588  1.10  christos 
    589   1.1    kardel 	old_rv = HAVE_OPT(OLD_RV);
    590   1.1    kardel 
    591  1.15  christos 	drefid = OPT_VALUE_REFID;
    592  1.15  christos 
    593   1.9  christos 	if (0 == argc) {
    594   1.1    kardel 		ADDHOST(DEFHOST);
    595   1.1    kardel 	} else {
    596   1.9  christos 		for (ihost = 0; ihost < (u_int)argc; ihost++) {
    597   1.9  christos 			if ('-' == *argv[ihost]) {
    598   1.9  christos 				//
    599   1.9  christos 				// If I really cared I'd also check:
    600   1.9  christos 				// 0 == argv[ihost][2]
    601   1.9  christos 				//
    602   1.9  christos 				// and there are other cases as well...
    603   1.9  christos 				//
    604   1.9  christos 				if ('4' == argv[ihost][1]) {
    605   1.9  christos 					ai_fam_templ = AF_INET;
    606   1.9  christos 					continue;
    607   1.9  christos 				} else if ('6' == argv[ihost][1]) {
    608   1.9  christos 					ai_fam_templ = AF_INET6;
    609   1.9  christos 					continue;
    610   1.9  christos 				} else {
    611   1.9  christos 					// XXX Throw a usage error
    612   1.9  christos 				}
    613   1.9  christos 			}
    614   1.9  christos 			ADDHOST(argv[ihost]);
    615   1.9  christos 		}
    616   1.1    kardel 	}
    617   1.1    kardel 
    618   1.1    kardel 	if (numcmds == 0 && interactive == 0
    619   1.1    kardel 	    && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
    620   1.1    kardel 		interactive = 1;
    621   1.1    kardel 	}
    622   1.1    kardel 
    623  1.14  christos 	set_ctrl_c_hook(on_ctrlc);
    624   1.1    kardel #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
    625   1.1    kardel 	if (interactive)
    626  1.14  christos 		push_ctrl_c_handler(abortcmd);
    627   1.1    kardel #endif /* SYS_WINNT */
    628   1.1    kardel 
    629   1.1    kardel 	if (numcmds == 0) {
    630   1.9  christos 		(void) openhost(chosts[0].name, chosts[0].fam);
    631   1.1    kardel 		getcmds();
    632   1.1    kardel 	} else {
    633   1.1    kardel 		for (ihost = 0; ihost < numhosts; ihost++) {
    634  1.19  christos 			if (openhost(chosts[ihost].name, chosts[ihost].fam)) {
    635  1.20  christos 				if (ihost && current_output)
    636  1.19  christos 					fputc('\n', current_output);
    637  1.19  christos 				for (icmd = 0; icmd < numcmds; icmd++) {
    638  1.20  christos 					if (icmd && current_output)
    639  1.19  christos 						fputc('\n', current_output);
    640   1.1    kardel 					docmd(ccmds[icmd]);
    641  1.19  christos 				}
    642  1.19  christos 			}
    643   1.1    kardel 		}
    644   1.1    kardel 	}
    645   1.1    kardel #ifdef SYS_WINNT
    646   1.1    kardel 	WSACleanup();
    647   1.1    kardel #endif /* SYS_WINNT */
    648   1.1    kardel 	return 0;
    649   1.1    kardel }
    650   1.1    kardel #endif /* !BUILD_AS_LIB */
    651   1.1    kardel 
    652   1.1    kardel /*
    653   1.1    kardel  * openhost - open a socket to a host
    654   1.1    kardel  */
    655   1.1    kardel static	int
    656   1.1    kardel openhost(
    657   1.9  christos 	const char *hname,
    658   1.9  christos 	int	    fam
    659   1.1    kardel 	)
    660   1.1    kardel {
    661   1.9  christos 	const char svc[] = "ntp";
    662   1.1    kardel 	char temphost[LENHOSTNAME];
    663  1.20  christos 	int a_info;
    664   1.9  christos 	struct addrinfo hints, *ai;
    665   1.9  christos 	sockaddr_u addr;
    666   1.9  christos 	size_t octets;
    667  1.20  christos 	const char *cp;
    668   1.1    kardel 	char name[LENHOSTNAME];
    669   1.1    kardel 
    670   1.1    kardel 	/*
    671   1.1    kardel 	 * We need to get by the [] if they were entered
    672   1.1    kardel 	 */
    673  1.20  christos 	if (*hname == '[') {
    674  1.20  christos 		cp = strchr(hname + 1, ']');
    675  1.20  christos 		if (!cp || (octets = (size_t)(cp - hname) - 1) >= sizeof(name)) {
    676  1.20  christos 			errno = EINVAL;
    677  1.20  christos 			warning("%s", "bad hostname/address");
    678   1.1    kardel 			return 0;
    679   1.1    kardel 		}
    680  1.20  christos 		memcpy(name, hname + 1, octets);
    681  1.20  christos 		name[octets] = '\0';
    682  1.20  christos 		hname = name;
    683   1.1    kardel 	}
    684   1.1    kardel 
    685   1.1    kardel 	/*
    686   1.1    kardel 	 * First try to resolve it as an ip address and if that fails,
    687   1.1    kardel 	 * do a fullblown (dns) lookup. That way we only use the dns
    688   1.1    kardel 	 * when it is needed and work around some implementations that
    689   1.1    kardel 	 * will return an "IPv4-mapped IPv6 address" address if you
    690   1.1    kardel 	 * give it an IPv4 address to lookup.
    691   1.1    kardel 	 */
    692   1.4    kardel 	ZERO(hints);
    693   1.9  christos 	hints.ai_family = fam;
    694   1.1    kardel 	hints.ai_protocol = IPPROTO_UDP;
    695   1.1    kardel 	hints.ai_socktype = SOCK_DGRAM;
    696   1.4    kardel 	hints.ai_flags = Z_AI_NUMERICHOST;
    697   1.9  christos 	ai = NULL;
    698   1.1    kardel 
    699   1.9  christos 	a_info = getaddrinfo(hname, svc, &hints, &ai);
    700   1.1    kardel 	if (a_info == EAI_NONAME
    701   1.1    kardel #ifdef EAI_NODATA
    702   1.1    kardel 	    || a_info == EAI_NODATA
    703   1.1    kardel #endif
    704   1.1    kardel 	   ) {
    705   1.1    kardel 		hints.ai_flags = AI_CANONNAME;
    706   1.1    kardel #ifdef AI_ADDRCONFIG
    707   1.1    kardel 		hints.ai_flags |= AI_ADDRCONFIG;
    708   1.1    kardel #endif
    709   1.9  christos 		a_info = getaddrinfo(hname, svc, &hints, &ai);
    710   1.1    kardel 	}
    711   1.1    kardel #ifdef AI_ADDRCONFIG
    712   1.1    kardel 	/* Some older implementations don't like AI_ADDRCONFIG. */
    713   1.1    kardel 	if (a_info == EAI_BADFLAGS) {
    714   1.9  christos 		hints.ai_flags &= ~AI_ADDRCONFIG;
    715   1.9  christos 		a_info = getaddrinfo(hname, svc, &hints, &ai);
    716   1.1    kardel 	}
    717   1.1    kardel #endif
    718   1.1    kardel 	if (a_info != 0) {
    719   1.9  christos 		fprintf(stderr, "%s\n", gai_strerror(a_info));
    720   1.1    kardel 		return 0;
    721   1.1    kardel 	}
    722   1.1    kardel 
    723   1.9  christos 	INSIST(ai != NULL);
    724   1.9  christos 	ZERO(addr);
    725   1.9  christos 	octets = min(sizeof(addr), ai->ai_addrlen);
    726   1.9  christos 	memcpy(&addr, ai->ai_addr, octets);
    727   1.9  christos 
    728   1.9  christos 	if (ai->ai_canonname == NULL) {
    729   1.9  christos 		strlcpy(temphost, stoa(&addr), sizeof(temphost));
    730   1.4    kardel 		currenthostisnum = TRUE;
    731   1.1    kardel 	} else {
    732   1.9  christos 		strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
    733   1.4    kardel 		currenthostisnum = FALSE;
    734   1.1    kardel 	}
    735   1.1    kardel 
    736   1.1    kardel 	if (debug > 2)
    737   1.9  christos 		printf("Opening host %s (%s)\n",
    738   1.9  christos 			temphost,
    739   1.9  christos 			(ai->ai_family == AF_INET)
    740   1.9  christos 			? "AF_INET"
    741   1.9  christos 			: (ai->ai_family == AF_INET6)
    742   1.9  christos 			  ? "AF_INET6"
    743   1.9  christos 			  : "AF-???"
    744   1.9  christos 			);
    745   1.1    kardel 
    746   1.1    kardel 	if (havehost == 1) {
    747   1.1    kardel 		if (debug > 2)
    748   1.1    kardel 			printf("Closing old host %s\n", currenthost);
    749   1.9  christos 		closesocket(sockfd);
    750   1.1    kardel 		havehost = 0;
    751   1.1    kardel 	}
    752   1.9  christos 	strlcpy(currenthost, temphost, sizeof(currenthost));
    753   1.1    kardel 
    754   1.1    kardel 	/* port maps to the same location in both families */
    755   1.9  christos 	s_port = NSRCPORT(&addr);
    756   1.1    kardel #ifdef SYS_VXWORKS
    757   1.1    kardel 	((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
    758   1.1    kardel 	if (ai->ai_family == AF_INET)
    759   1.1    kardel 		*(struct sockaddr_in *)&hostaddr=
    760   1.1    kardel 			*((struct sockaddr_in *)ai->ai_addr);
    761   1.1    kardel 	else
    762   1.1    kardel 		*(struct sockaddr_in6 *)&hostaddr=
    763   1.1    kardel 			*((struct sockaddr_in6 *)ai->ai_addr);
    764   1.1    kardel #endif /* SYS_VXWORKS */
    765   1.1    kardel 
    766   1.1    kardel #ifdef SYS_WINNT
    767   1.1    kardel 	{
    768   1.1    kardel 		int optionValue = SO_SYNCHRONOUS_NONALERT;
    769   1.1    kardel 		int err;
    770   1.1    kardel 
    771   1.1    kardel 		err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
    772  1.19  christos 				 (void *)&optionValue, sizeof(optionValue));
    773   1.1    kardel 		if (err) {
    774   1.9  christos 			mfprintf(stderr,
    775   1.9  christos 				 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
    776   1.9  christos 				 " error: %m\n");
    777   1.9  christos 			freeaddrinfo(ai);
    778   1.1    kardel 			exit(1);
    779   1.1    kardel 		}
    780   1.1    kardel 	}
    781   1.1    kardel #endif /* SYS_WINNT */
    782   1.1    kardel 
    783   1.9  christos 	sockfd = socket(ai->ai_family, ai->ai_socktype,
    784   1.9  christos 			ai->ai_protocol);
    785   1.1    kardel 	if (sockfd == INVALID_SOCKET) {
    786   1.3  christos 		error("socket");
    787   1.9  christos 		freeaddrinfo(ai);
    788   1.9  christos 		return 0;
    789   1.1    kardel 	}
    790   1.1    kardel 
    791   1.9  christos 
    792   1.1    kardel #ifdef NEED_RCVBUF_SLOP
    793   1.1    kardel # ifdef SO_RCVBUF
    794   1.1    kardel 	{ int rbufsize = DATASIZE + 2048;	/* 2K for slop */
    795   1.1    kardel 	if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
    796  1.19  christos 		       (void *)&rbufsize, sizeof(int)) == -1)
    797   1.9  christos 		error("setsockopt");
    798   1.1    kardel 	}
    799   1.1    kardel # endif
    800   1.1    kardel #endif
    801   1.1    kardel 
    802   1.9  christos 	if
    803   1.1    kardel #ifdef SYS_VXWORKS
    804   1.9  christos 	   (connect(sockfd, (struct sockaddr *)&hostaddr,
    805   1.1    kardel 		    sizeof(hostaddr)) == -1)
    806   1.1    kardel #else
    807   1.9  christos 	   (connect(sockfd, (struct sockaddr *)ai->ai_addr,
    808  1.14  christos 		ai->ai_addrlen) == -1)
    809   1.1    kardel #endif /* SYS_VXWORKS */
    810  1.14  christos 	{
    811   1.9  christos 		error("connect");
    812   1.1    kardel 		freeaddrinfo(ai);
    813   1.9  christos 		return 0;
    814   1.9  christos 	}
    815   1.9  christos 	freeaddrinfo(ai);
    816   1.1    kardel 	havehost = 1;
    817   1.9  christos 	numassoc = 0;
    818   1.9  christos 
    819   1.1    kardel 	return 1;
    820   1.1    kardel }
    821   1.1    kardel 
    822   1.1    kardel 
    823   1.9  christos static void
    824   1.9  christos dump_hex_printable(
    825   1.9  christos 	const void *	data,
    826   1.9  christos 	size_t		len
    827   1.9  christos 	)
    828   1.9  christos {
    829  1.18  christos 	/* every line shows at most 16 bytes, so we need a buffer of
    830  1.18  christos 	 *   4 * 16 (2 xdigits, 1 char, one sep for xdigits)
    831  1.18  christos 	 * + 2 * 1  (block separators)
    832  1.18  christos 	 * + <LF> + <NUL>
    833  1.18  christos 	 *---------------
    834  1.18  christos 	 *  68 bytes
    835  1.18  christos 	 */
    836  1.18  christos 	static const char s_xdig[16] = "0123456789ABCDEF";
    837  1.18  christos 
    838  1.18  christos 	char lbuf[68];
    839  1.18  christos 	int  ch, rowlen;
    840  1.18  christos 	const u_char * cdata = data;
    841  1.18  christos 	char *xptr, *pptr;
    842  1.18  christos 
    843  1.18  christos 	while (len) {
    844  1.18  christos 		memset(lbuf, ' ', sizeof(lbuf));
    845  1.18  christos 		xptr = lbuf;
    846  1.18  christos 		pptr = lbuf + 3*16 + 2;
    847  1.18  christos 
    848  1.18  christos 		rowlen = (len > 16) ? 16 : (int)len;
    849   1.9  christos 		len -= rowlen;
    850  1.18  christos 
    851  1.18  christos 		do {
    852  1.18  christos 			ch = *cdata++;
    853  1.18  christos 
    854  1.18  christos 			*xptr++ = s_xdig[ch >> 4  ];
    855  1.18  christos 			*xptr++ = s_xdig[ch & 0x0F];
    856  1.18  christos 			if (++xptr == lbuf + 3*8)
    857  1.18  christos 				++xptr;
    858  1.18  christos 
    859  1.18  christos 			*pptr++ = isprint(ch) ? (char)ch : '.';
    860  1.18  christos 		} while (--rowlen);
    861  1.18  christos 
    862  1.18  christos 		*pptr++ = '\n';
    863  1.18  christos 		*pptr   = '\0';
    864  1.18  christos 		fputs(lbuf, stdout);
    865   1.9  christos 	}
    866   1.9  christos }
    867   1.9  christos 
    868   1.9  christos 
    869   1.1    kardel /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
    870   1.1    kardel /*
    871   1.1    kardel  * sendpkt - send a packet to the remote host
    872   1.1    kardel  */
    873   1.1    kardel static int
    874   1.1    kardel sendpkt(
    875   1.1    kardel 	void *	xdata,
    876   1.1    kardel 	size_t	xdatalen
    877   1.1    kardel 	)
    878   1.1    kardel {
    879   1.1    kardel 	if (debug >= 3)
    880   1.2  christos 		printf("Sending %zu octets\n", xdatalen);
    881   1.1    kardel 
    882  1.14  christos 	if (send(sockfd, xdata, xdatalen, 0) == -1) {
    883   1.3  christos 		warning("write to %s failed", currenthost);
    884   1.1    kardel 		return -1;
    885   1.1    kardel 	}
    886   1.1    kardel 
    887   1.1    kardel 	if (debug >= 4) {
    888   1.9  christos 		printf("Request packet:\n");
    889   1.9  christos 		dump_hex_printable(xdata, xdatalen);
    890   1.1    kardel 	}
    891   1.1    kardel 	return 0;
    892   1.1    kardel }
    893   1.1    kardel 
    894   1.1    kardel /*
    895   1.1    kardel  * getresponse - get a (series of) response packet(s) and return the data
    896   1.1    kardel  */
    897   1.1    kardel static int
    898   1.1    kardel getresponse(
    899   1.1    kardel 	int opcode,
    900   1.1    kardel 	int associd,
    901   1.1    kardel 	u_short *rstatus,
    902  1.14  christos 	size_t *rsize,
    903   1.4    kardel 	const char **rdata,
    904   1.1    kardel 	int timeo
    905   1.1    kardel 	)
    906   1.1    kardel {
    907   1.1    kardel 	struct ntp_control rpkt;
    908   1.1    kardel 	struct sock_timeval tvo;
    909   1.1    kardel 	u_short offsets[MAXFRAGS+1];
    910   1.1    kardel 	u_short counts[MAXFRAGS+1];
    911   1.1    kardel 	u_short offset;
    912   1.1    kardel 	u_short count;
    913   1.4    kardel 	size_t numfrags;
    914   1.4    kardel 	size_t f;
    915   1.4    kardel 	size_t ff;
    916   1.1    kardel 	int seenlastfrag;
    917   1.1    kardel 	int shouldbesize;
    918   1.1    kardel 	fd_set fds;
    919   1.1    kardel 	int n;
    920   1.9  christos 	int errcode;
    921  1.15  christos 	/* absolute timeout checks. Not 'time_t' by intention! */
    922  1.15  christos 	uint32_t tobase;	/* base value for timeout */
    923  1.15  christos 	uint32_t tospan;	/* timeout span (max delay) */
    924  1.15  christos 	uint32_t todiff;	/* current delay */
    925   1.1    kardel 
    926  1.18  christos 	memset(offsets, 0, sizeof(offsets));
    927  1.18  christos 	memset(counts , 0, sizeof(counts ));
    928  1.18  christos 
    929   1.1    kardel 	/*
    930   1.1    kardel 	 * This is pretty tricky.  We may get between 1 and MAXFRAG packets
    931   1.1    kardel 	 * back in response to the request.  We peel the data out of
    932   1.1    kardel 	 * each packet and collect it in one long block.  When the last
    933   1.1    kardel 	 * packet in the sequence is received we'll know how much data we
    934   1.1    kardel 	 * should have had.  Note we use one long time out, should reconsider.
    935   1.1    kardel 	 */
    936   1.1    kardel 	*rsize = 0;
    937   1.1    kardel 	if (rstatus)
    938   1.4    kardel 		*rstatus = 0;
    939   1.1    kardel 	*rdata = (char *)pktdata;
    940   1.1    kardel 
    941   1.1    kardel 	numfrags = 0;
    942   1.1    kardel 	seenlastfrag = 0;
    943   1.1    kardel 
    944  1.15  christos 	tobase = (uint32_t)time(NULL);
    945  1.15  christos 
    946   1.1    kardel 	FD_ZERO(&fds);
    947   1.1    kardel 
    948   1.1    kardel 	/*
    949   1.1    kardel 	 * Loop until we have an error or a complete response.  Nearly all
    950   1.4    kardel 	 * code paths to loop again use continue.
    951   1.1    kardel 	 */
    952   1.1    kardel 	for (;;) {
    953   1.1    kardel 
    954   1.1    kardel 		if (numfrags == 0)
    955   1.4    kardel 			tvo = tvout;
    956   1.1    kardel 		else
    957   1.4    kardel 			tvo = tvsout;
    958  1.15  christos 		tospan = (uint32_t)tvo.tv_sec + (tvo.tv_usec != 0);
    959   1.9  christos 
    960   1.1    kardel 		FD_SET(sockfd, &fds);
    961  1.14  christos 		n = select(sockfd+1, &fds, NULL, NULL, &tvo);
    962   1.1    kardel 		if (n == -1) {
    963  1.15  christos #if !defined(SYS_WINNT) && defined(EINTR)
    964  1.15  christos 			/* Windows does not know about EINTR (until very
    965  1.15  christos 			 * recently) and the handling of console events
    966  1.15  christos 			 * is *very* different from POSIX/UNIX signal
    967  1.15  christos 			 * handling anyway.
    968  1.15  christos 			 *
    969  1.15  christos 			 * Under non-windows targets we map EINTR as
    970  1.15  christos 			 * 'last packet was received' and try to exit
    971  1.15  christos 			 * the receive sequence.
    972  1.15  christos 			 */
    973  1.15  christos 			if (errno == EINTR) {
    974  1.15  christos 				seenlastfrag = 1;
    975  1.15  christos 				goto maybe_final;
    976  1.15  christos 			}
    977  1.15  christos #endif
    978   1.3  christos 			warning("select fails");
    979   1.1    kardel 			return -1;
    980   1.1    kardel 		}
    981  1.15  christos 
    982  1.15  christos 		/*
    983  1.15  christos 		 * Check if this is already too late. Trash the data and
    984  1.15  christos 		 * fake a timeout if this is so.
    985  1.15  christos 		 */
    986  1.15  christos 		todiff = (((uint32_t)time(NULL)) - tobase) & 0x7FFFFFFFu;
    987  1.15  christos 		if ((n > 0) && (todiff > tospan)) {
    988  1.15  christos 			n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
    989  1.18  christos 			n -= n; /* faked timeout return from 'select()',
    990  1.18  christos 				 * execute RMW cycle on 'n'
    991  1.18  christos 				 */
    992  1.15  christos 		}
    993  1.15  christos 
    994  1.18  christos 		if (n <= 0) {
    995   1.1    kardel 			/*
    996   1.1    kardel 			 * Timed out.  Return what we have
    997   1.1    kardel 			 */
    998   1.1    kardel 			if (numfrags == 0) {
    999   1.1    kardel 				if (timeo)
   1000   1.4    kardel 					fprintf(stderr,
   1001   1.4    kardel 						"%s: timed out, nothing received\n",
   1002   1.4    kardel 						currenthost);
   1003   1.1    kardel 				return ERR_TIMEOUT;
   1004   1.1    kardel 			}
   1005   1.4    kardel 			if (timeo)
   1006   1.4    kardel 				fprintf(stderr,
   1007   1.4    kardel 					"%s: timed out with incomplete data\n",
   1008   1.4    kardel 					currenthost);
   1009   1.4    kardel 			if (debug) {
   1010   1.4    kardel 				fprintf(stderr,
   1011   1.4    kardel 					"ERR_INCOMPLETE: Received fragments:\n");
   1012   1.4    kardel 				for (f = 0; f < numfrags; f++)
   1013   1.4    kardel 					fprintf(stderr,
   1014   1.9  christos 						"%2u: %5d %5d\t%3d octets\n",
   1015   1.9  christos 						(u_int)f, offsets[f],
   1016   1.4    kardel 						offsets[f] +
   1017   1.4    kardel 						counts[f],
   1018   1.4    kardel 						counts[f]);
   1019   1.4    kardel 				fprintf(stderr,
   1020   1.4    kardel 					"last fragment %sreceived\n",
   1021   1.4    kardel 					(seenlastfrag)
   1022   1.4    kardel 					    ? ""
   1023   1.4    kardel 					    : "not ");
   1024   1.4    kardel 			}
   1025   1.4    kardel 			return ERR_INCOMPLETE;
   1026   1.1    kardel 		}
   1027   1.1    kardel 
   1028   1.1    kardel 		n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
   1029  1.18  christos 		if (n < 0) {
   1030   1.3  christos 			warning("read");
   1031   1.1    kardel 			return -1;
   1032   1.1    kardel 		}
   1033   1.1    kardel 
   1034   1.1    kardel 		if (debug >= 4) {
   1035   1.9  christos 			printf("Response packet:\n");
   1036   1.9  christos 			dump_hex_printable(&rpkt, n);
   1037   1.1    kardel 		}
   1038   1.1    kardel 
   1039   1.1    kardel 		/*
   1040   1.1    kardel 		 * Check for format errors.  Bug proofing.
   1041   1.1    kardel 		 */
   1042   1.5    kardel 		if (n < (int)CTL_HEADER_LEN) {
   1043   1.1    kardel 			if (debug)
   1044   1.4    kardel 				printf("Short (%d byte) packet received\n", n);
   1045   1.1    kardel 			continue;
   1046   1.1    kardel 		}
   1047   1.1    kardel 		if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
   1048   1.1    kardel 		    || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
   1049   1.1    kardel 			if (debug)
   1050   1.4    kardel 				printf("Packet received with version %d\n",
   1051   1.4    kardel 				       PKT_VERSION(rpkt.li_vn_mode));
   1052   1.1    kardel 			continue;
   1053   1.1    kardel 		}
   1054   1.1    kardel 		if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
   1055   1.1    kardel 			if (debug)
   1056   1.4    kardel 				printf("Packet received with mode %d\n",
   1057   1.4    kardel 				       PKT_MODE(rpkt.li_vn_mode));
   1058   1.1    kardel 			continue;
   1059   1.1    kardel 		}
   1060   1.1    kardel 		if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
   1061   1.1    kardel 			if (debug)
   1062   1.4    kardel 				printf("Received request packet, wanted response\n");
   1063   1.1    kardel 			continue;
   1064   1.1    kardel 		}
   1065   1.1    kardel 
   1066   1.1    kardel 		/*
   1067   1.1    kardel 		 * Check opcode and sequence number for a match.
   1068   1.1    kardel 		 * Could be old data getting to us.
   1069   1.1    kardel 		 */
   1070   1.1    kardel 		if (ntohs(rpkt.sequence) != sequence) {
   1071   1.1    kardel 			if (debug)
   1072   1.4    kardel 				printf("Received sequnce number %d, wanted %d\n",
   1073   1.4    kardel 				       ntohs(rpkt.sequence), sequence);
   1074   1.1    kardel 			continue;
   1075   1.1    kardel 		}
   1076   1.1    kardel 		if (CTL_OP(rpkt.r_m_e_op) != opcode) {
   1077   1.1    kardel 			if (debug)
   1078   1.1    kardel 			    printf(
   1079   1.1    kardel 				    "Received opcode %d, wanted %d (sequence number okay)\n",
   1080   1.1    kardel 				    CTL_OP(rpkt.r_m_e_op), opcode);
   1081   1.1    kardel 			continue;
   1082   1.1    kardel 		}
   1083   1.1    kardel 
   1084   1.1    kardel 		/*
   1085   1.1    kardel 		 * Check the error code.  If non-zero, return it.
   1086   1.1    kardel 		 */
   1087   1.1    kardel 		if (CTL_ISERROR(rpkt.r_m_e_op)) {
   1088   1.1    kardel 			errcode = (ntohs(rpkt.status) >> 8) & 0xff;
   1089   1.9  christos 			if (CTL_ISMORE(rpkt.r_m_e_op))
   1090   1.9  christos 				TRACE(1, ("Error code %d received on not-final packet\n",
   1091   1.9  christos 					  errcode));
   1092   1.1    kardel 			if (errcode == CERR_UNSPEC)
   1093   1.9  christos 				return ERR_UNSPEC;
   1094   1.1    kardel 			return errcode;
   1095   1.1    kardel 		}
   1096   1.1    kardel 
   1097   1.1    kardel 		/*
   1098   1.1    kardel 		 * Check the association ID to make sure it matches what
   1099   1.1    kardel 		 * we sent.
   1100   1.1    kardel 		 */
   1101   1.1    kardel 		if (ntohs(rpkt.associd) != associd) {
   1102   1.9  christos 			TRACE(1, ("Association ID %d doesn't match expected %d\n",
   1103   1.9  christos 				  ntohs(rpkt.associd), associd));
   1104   1.1    kardel 			/*
   1105   1.1    kardel 			 * Hack for silly fuzzballs which, at the time of writing,
   1106   1.1    kardel 			 * return an assID of sys.peer when queried for system variables.
   1107   1.1    kardel 			 */
   1108   1.1    kardel #ifdef notdef
   1109   1.1    kardel 			continue;
   1110   1.1    kardel #endif
   1111   1.1    kardel 		}
   1112   1.1    kardel 
   1113   1.1    kardel 		/*
   1114   1.1    kardel 		 * Collect offset and count.  Make sure they make sense.
   1115   1.1    kardel 		 */
   1116   1.1    kardel 		offset = ntohs(rpkt.offset);
   1117   1.1    kardel 		count = ntohs(rpkt.count);
   1118   1.1    kardel 
   1119   1.1    kardel 		/*
   1120   1.1    kardel 		 * validate received payload size is padded to next 32-bit
   1121   1.1    kardel 		 * boundary and no smaller than claimed by rpkt.count
   1122   1.1    kardel 		 */
   1123   1.1    kardel 		if (n & 0x3) {
   1124   1.9  christos 			TRACE(1, ("Response packet not padded, size = %d\n",
   1125   1.9  christos 				  n));
   1126   1.1    kardel 			continue;
   1127   1.1    kardel 		}
   1128   1.1    kardel 
   1129   1.1    kardel 		shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
   1130   1.1    kardel 
   1131   1.1    kardel 		if (n < shouldbesize) {
   1132   1.9  christos 			printf("Response packet claims %u octets payload, above %ld received\n",
   1133  1.16  christos 			       count, (long)(n - CTL_HEADER_LEN));
   1134   1.1    kardel 			return ERR_INCOMPLETE;
   1135   1.1    kardel 		}
   1136   1.1    kardel 
   1137   1.1    kardel 		if (debug >= 3 && shouldbesize > n) {
   1138   1.1    kardel 			u_int32 key;
   1139   1.1    kardel 			u_int32 *lpkt;
   1140   1.1    kardel 			int maclen;
   1141   1.1    kardel 
   1142   1.1    kardel 			/*
   1143   1.1    kardel 			 * Usually we ignore authentication, but for debugging purposes
   1144   1.1    kardel 			 * we watch it here.
   1145   1.1    kardel 			 */
   1146   1.1    kardel 			/* round to 8 octet boundary */
   1147   1.1    kardel 			shouldbesize = (shouldbesize + 7) & ~7;
   1148   1.1    kardel 
   1149   1.1    kardel 			maclen = n - shouldbesize;
   1150   1.2  christos 			if (maclen >= (int)MIN_MAC_LEN) {
   1151   1.1    kardel 				printf(
   1152   1.1    kardel 					"Packet shows signs of authentication (total %d, data %d, mac %d)\n",
   1153   1.1    kardel 					n, shouldbesize, maclen);
   1154   1.1    kardel 				lpkt = (u_int32 *)&rpkt;
   1155   1.1    kardel 				printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
   1156   1.1    kardel 				       (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
   1157   1.1    kardel 				       (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
   1158   1.1    kardel 				       (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
   1159   1.1    kardel 				       (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
   1160   1.1    kardel 				       (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
   1161   1.1    kardel 				       (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
   1162   1.1    kardel 				key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
   1163   1.1    kardel 				printf("Authenticated with keyid %lu\n", (u_long)key);
   1164   1.1    kardel 				if (key != 0 && key != info_auth_keyid) {
   1165   1.1    kardel 					printf("We don't know that key\n");
   1166   1.1    kardel 				} else {
   1167   1.1    kardel 					if (authdecrypt(key, (u_int32 *)&rpkt,
   1168   1.1    kardel 					    n - maclen, maclen)) {
   1169   1.1    kardel 						printf("Auth okay!\n");
   1170   1.1    kardel 					} else {
   1171   1.1    kardel 						printf("Auth failed!\n");
   1172   1.1    kardel 					}
   1173   1.1    kardel 				}
   1174   1.1    kardel 			}
   1175   1.1    kardel 		}
   1176   1.1    kardel 
   1177   1.9  christos 		TRACE(2, ("Got packet, size = %d\n", n));
   1178   1.9  christos 		if (count > (n - CTL_HEADER_LEN)) {
   1179   1.9  christos 			TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
   1180   1.9  christos 				  count, (long)n - CTL_HEADER_LEN));
   1181   1.1    kardel 			continue;
   1182   1.1    kardel 		}
   1183   1.1    kardel 		if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
   1184   1.9  christos 			TRACE(1, ("Received count of 0 in non-final fragment\n"));
   1185   1.1    kardel 			continue;
   1186   1.1    kardel 		}
   1187   1.1    kardel 		if (offset + count > sizeof(pktdata)) {
   1188   1.9  christos 			TRACE(1, ("Offset %u, count %u, too big for buffer\n",
   1189   1.9  christos 				  offset, count));
   1190   1.1    kardel 			return ERR_TOOMUCH;
   1191   1.1    kardel 		}
   1192   1.1    kardel 		if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
   1193   1.9  christos 			TRACE(1, ("Received second last fragment packet\n"));
   1194   1.1    kardel 			continue;
   1195   1.1    kardel 		}
   1196   1.1    kardel 
   1197   1.1    kardel 		/*
   1198   1.1    kardel 		 * So far, so good.  Record this fragment, making sure it doesn't
   1199   1.1    kardel 		 * overlap anything.
   1200   1.1    kardel 		 */
   1201   1.9  christos 		TRACE(2, ("Packet okay\n"));
   1202   1.1    kardel 
   1203   1.1    kardel 		if (numfrags > (MAXFRAGS - 1)) {
   1204   1.9  christos 			TRACE(2, ("Number of fragments exceeds maximum %d\n",
   1205   1.9  christos 				  MAXFRAGS - 1));
   1206   1.1    kardel 			return ERR_TOOMUCH;
   1207   1.1    kardel 		}
   1208   1.1    kardel 
   1209   1.1    kardel 		/*
   1210   1.1    kardel 		 * Find the position for the fragment relative to any
   1211   1.1    kardel 		 * previously received.
   1212   1.1    kardel 		 */
   1213   1.9  christos 		for (f = 0;
   1214   1.9  christos 		     f < numfrags && offsets[f] < offset;
   1215   1.4    kardel 		     f++) {
   1216   1.1    kardel 			/* empty body */ ;
   1217   1.1    kardel 		}
   1218   1.1    kardel 
   1219   1.4    kardel 		if (f < numfrags && offset == offsets[f]) {
   1220   1.9  christos 			TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
   1221   1.9  christos 				  count, offset, counts[f], offsets[f]));
   1222   1.1    kardel 			continue;
   1223   1.1    kardel 		}
   1224   1.1    kardel 
   1225   1.4    kardel 		if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
   1226   1.9  christos 			TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
   1227   1.9  christos 				  offset, counts[f-1], offsets[f-1]));
   1228   1.1    kardel 			continue;
   1229   1.1    kardel 		}
   1230   1.1    kardel 
   1231   1.4    kardel 		if (f < numfrags && (offset + count) > offsets[f]) {
   1232   1.9  christos 			TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
   1233   1.9  christos 				  count, offset, offsets[f]));
   1234   1.1    kardel 			continue;
   1235   1.1    kardel 		}
   1236   1.1    kardel 
   1237   1.4    kardel 		for (ff = numfrags; ff > f; ff--) {
   1238   1.4    kardel 			offsets[ff] = offsets[ff-1];
   1239   1.4    kardel 			counts[ff] = counts[ff-1];
   1240   1.1    kardel 		}
   1241   1.4    kardel 		offsets[f] = offset;
   1242   1.4    kardel 		counts[f] = count;
   1243   1.1    kardel 		numfrags++;
   1244   1.1    kardel 
   1245   1.1    kardel 		/*
   1246   1.1    kardel 		 * Got that stuffed in right.  Figure out if this was the last.
   1247   1.1    kardel 		 * Record status info out of the last packet.
   1248   1.1    kardel 		 */
   1249   1.1    kardel 		if (!CTL_ISMORE(rpkt.r_m_e_op)) {
   1250   1.1    kardel 			seenlastfrag = 1;
   1251   1.1    kardel 			if (rstatus != 0)
   1252   1.4    kardel 				*rstatus = ntohs(rpkt.status);
   1253   1.1    kardel 		}
   1254   1.1    kardel 
   1255   1.1    kardel 		/*
   1256  1.15  christos 		 * Copy the data into the data buffer, and bump the
   1257  1.15  christos 		 * timout base in case we need more.
   1258   1.1    kardel 		 */
   1259   1.9  christos 		memcpy((char *)pktdata + offset, &rpkt.u, count);
   1260  1.15  christos 		tobase = (uint32_t)time(NULL);
   1261  1.15  christos 
   1262   1.1    kardel 		/*
   1263   1.1    kardel 		 * If we've seen the last fragment, look for holes in the sequence.
   1264   1.1    kardel 		 * If there aren't any, we're done.
   1265   1.1    kardel 		 */
   1266  1.16  christos #if !defined(SYS_WINNT) && defined(EINTR)
   1267  1.16  christos 		maybe_final:
   1268  1.16  christos #endif
   1269  1.16  christos 
   1270   1.1    kardel 		if (seenlastfrag && offsets[0] == 0) {
   1271   1.4    kardel 			for (f = 1; f < numfrags; f++)
   1272   1.4    kardel 				if (offsets[f-1] + counts[f-1] !=
   1273   1.4    kardel 				    offsets[f])
   1274   1.1    kardel 					break;
   1275   1.4    kardel 			if (f == numfrags) {
   1276   1.4    kardel 				*rsize = offsets[f-1] + counts[f-1];
   1277   1.9  christos 				TRACE(1, ("%lu packets reassembled into response\n",
   1278   1.9  christos 					  (u_long)numfrags));
   1279   1.1    kardel 				return 0;
   1280   1.1    kardel 			}
   1281   1.1    kardel 		}
   1282   1.1    kardel 	}  /* giant for (;;) collecting response packets */
   1283   1.1    kardel }  /* getresponse() */
   1284   1.1    kardel 
   1285   1.1    kardel 
   1286   1.1    kardel /*
   1287   1.1    kardel  * sendrequest - format and send a request packet
   1288   1.1    kardel  */
   1289   1.1    kardel static int
   1290   1.1    kardel sendrequest(
   1291   1.1    kardel 	int opcode,
   1292   1.9  christos 	associd_t associd,
   1293   1.1    kardel 	int auth,
   1294  1.14  christos 	size_t qsize,
   1295   1.9  christos 	const char *qdata
   1296   1.1    kardel 	)
   1297   1.1    kardel {
   1298   1.1    kardel 	struct ntp_control qpkt;
   1299  1.14  christos 	size_t	pktsize;
   1300   1.1    kardel 	u_long	key_id;
   1301   1.1    kardel 	char *	pass;
   1302  1.14  christos 	size_t	maclen;
   1303   1.1    kardel 
   1304   1.1    kardel 	/*
   1305   1.1    kardel 	 * Check to make sure the data will fit in one packet
   1306   1.1    kardel 	 */
   1307   1.1    kardel 	if (qsize > CTL_MAX_DATA_LEN) {
   1308   1.1    kardel 		fprintf(stderr,
   1309  1.14  christos 			"***Internal error!  qsize (%zu) too large\n",
   1310   1.1    kardel 			qsize);
   1311   1.1    kardel 		return 1;
   1312   1.1    kardel 	}
   1313   1.1    kardel 
   1314   1.1    kardel 	/*
   1315   1.1    kardel 	 * Fill in the packet
   1316   1.1    kardel 	 */
   1317   1.1    kardel 	qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
   1318   1.1    kardel 	qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
   1319   1.1    kardel 	qpkt.sequence = htons(sequence);
   1320   1.1    kardel 	qpkt.status = 0;
   1321   1.1    kardel 	qpkt.associd = htons((u_short)associd);
   1322   1.1    kardel 	qpkt.offset = 0;
   1323   1.1    kardel 	qpkt.count = htons((u_short)qsize);
   1324   1.1    kardel 
   1325   1.1    kardel 	pktsize = CTL_HEADER_LEN;
   1326   1.1    kardel 
   1327   1.1    kardel 	/*
   1328   1.1    kardel 	 * If we have data, copy and pad it out to a 32-bit boundary.
   1329   1.1    kardel 	 */
   1330   1.1    kardel 	if (qsize > 0) {
   1331   1.9  christos 		memcpy(&qpkt.u, qdata, (size_t)qsize);
   1332   1.1    kardel 		pktsize += qsize;
   1333   1.1    kardel 		while (pktsize & (sizeof(u_int32) - 1)) {
   1334   1.9  christos 			qpkt.u.data[qsize++] = 0;
   1335   1.1    kardel 			pktsize++;
   1336   1.1    kardel 		}
   1337   1.1    kardel 	}
   1338   1.1    kardel 
   1339   1.1    kardel 	/*
   1340   1.1    kardel 	 * If it isn't authenticated we can just send it.  Otherwise
   1341   1.1    kardel 	 * we're going to have to think about it a little.
   1342   1.1    kardel 	 */
   1343   1.1    kardel 	if (!auth && !always_auth) {
   1344   1.1    kardel 		return sendpkt(&qpkt, pktsize);
   1345   1.9  christos 	}
   1346   1.1    kardel 
   1347   1.1    kardel 	/*
   1348   1.1    kardel 	 * Pad out packet to a multiple of 8 octets to be sure
   1349   1.1    kardel 	 * receiver can handle it.
   1350   1.1    kardel 	 */
   1351   1.1    kardel 	while (pktsize & 7) {
   1352   1.9  christos 		qpkt.u.data[qsize++] = 0;
   1353   1.1    kardel 		pktsize++;
   1354   1.1    kardel 	}
   1355   1.1    kardel 
   1356   1.1    kardel 	/*
   1357   1.1    kardel 	 * Get the keyid and the password if we don't have one.
   1358   1.1    kardel 	 */
   1359   1.1    kardel 	if (info_auth_keyid == 0) {
   1360   1.1    kardel 		key_id = getkeyid("Keyid: ");
   1361   1.1    kardel 		if (key_id == 0 || key_id > NTP_MAXKEY) {
   1362   1.9  christos 			fprintf(stderr,
   1363   1.1    kardel 				"Invalid key identifier\n");
   1364   1.1    kardel 			return 1;
   1365   1.1    kardel 		}
   1366   1.1    kardel 		info_auth_keyid = key_id;
   1367   1.1    kardel 	}
   1368   1.1    kardel 	if (!authistrusted(info_auth_keyid)) {
   1369   1.4    kardel 		pass = getpass_keytype(info_auth_keytype);
   1370   1.1    kardel 		if ('\0' == pass[0]) {
   1371   1.1    kardel 			fprintf(stderr, "Invalid password\n");
   1372   1.1    kardel 			return 1;
   1373   1.1    kardel 		}
   1374   1.1    kardel 		authusekey(info_auth_keyid, info_auth_keytype,
   1375   1.1    kardel 			   (u_char *)pass);
   1376   1.1    kardel 		authtrust(info_auth_keyid, 1);
   1377   1.1    kardel 	}
   1378   1.1    kardel 
   1379   1.1    kardel 	/*
   1380   1.1    kardel 	 * Do the encryption.
   1381   1.1    kardel 	 */
   1382   1.1    kardel 	maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
   1383   1.9  christos 	if (!maclen) {
   1384   1.1    kardel 		fprintf(stderr, "Key not found\n");
   1385   1.1    kardel 		return 1;
   1386   1.1    kardel 	} else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
   1387   1.1    kardel 		fprintf(stderr,
   1388  1.14  christos 			"%zu octet MAC, %zu expected with %zu octet digest\n",
   1389   1.1    kardel 			maclen, (info_auth_hashlen + sizeof(keyid_t)),
   1390   1.1    kardel 			info_auth_hashlen);
   1391   1.1    kardel 		return 1;
   1392   1.1    kardel 	}
   1393   1.9  christos 
   1394   1.1    kardel 	return sendpkt((char *)&qpkt, pktsize + maclen);
   1395   1.1    kardel }
   1396   1.1    kardel 
   1397   1.1    kardel 
   1398   1.1    kardel /*
   1399   1.4    kardel  * show_error_msg - display the error text for a mode 6 error response.
   1400   1.4    kardel  */
   1401   1.4    kardel void
   1402   1.4    kardel show_error_msg(
   1403   1.4    kardel 	int		m6resp,
   1404   1.4    kardel 	associd_t	associd
   1405   1.4    kardel 	)
   1406   1.4    kardel {
   1407   1.4    kardel 	if (numhosts > 1)
   1408   1.4    kardel 		fprintf(stderr, "server=%s ", currenthost);
   1409   1.4    kardel 
   1410  1.15  christos 	switch (m6resp) {
   1411   1.4    kardel 
   1412   1.4    kardel 	case CERR_BADFMT:
   1413   1.4    kardel 		fprintf(stderr,
   1414   1.4    kardel 		    "***Server reports a bad format request packet\n");
   1415   1.4    kardel 		break;
   1416   1.4    kardel 
   1417   1.4    kardel 	case CERR_PERMISSION:
   1418   1.4    kardel 		fprintf(stderr,
   1419   1.4    kardel 		    "***Server disallowed request (authentication?)\n");
   1420   1.4    kardel 		break;
   1421   1.4    kardel 
   1422   1.4    kardel 	case CERR_BADOP:
   1423   1.4    kardel 		fprintf(stderr,
   1424   1.4    kardel 		    "***Server reports a bad opcode in request\n");
   1425   1.4    kardel 		break;
   1426   1.4    kardel 
   1427   1.4    kardel 	case CERR_BADASSOC:
   1428   1.4    kardel 		fprintf(stderr,
   1429   1.4    kardel 		    "***Association ID %d unknown to server\n",
   1430   1.4    kardel 		    associd);
   1431   1.4    kardel 		break;
   1432   1.4    kardel 
   1433   1.4    kardel 	case CERR_UNKNOWNVAR:
   1434   1.4    kardel 		fprintf(stderr,
   1435   1.4    kardel 		    "***A request variable unknown to the server\n");
   1436   1.4    kardel 		break;
   1437   1.4    kardel 
   1438   1.4    kardel 	case CERR_BADVALUE:
   1439   1.4    kardel 		fprintf(stderr,
   1440   1.4    kardel 		    "***Server indicates a request variable was bad\n");
   1441   1.4    kardel 		break;
   1442   1.4    kardel 
   1443   1.4    kardel 	case ERR_UNSPEC:
   1444   1.4    kardel 		fprintf(stderr,
   1445   1.4    kardel 		    "***Server returned an unspecified error\n");
   1446   1.4    kardel 		break;
   1447   1.4    kardel 
   1448   1.4    kardel 	case ERR_TIMEOUT:
   1449   1.4    kardel 		fprintf(stderr, "***Request timed out\n");
   1450   1.4    kardel 		break;
   1451   1.4    kardel 
   1452   1.4    kardel 	case ERR_INCOMPLETE:
   1453   1.4    kardel 		fprintf(stderr,
   1454   1.4    kardel 		    "***Response from server was incomplete\n");
   1455   1.4    kardel 		break;
   1456   1.4    kardel 
   1457   1.4    kardel 	case ERR_TOOMUCH:
   1458   1.4    kardel 		fprintf(stderr,
   1459   1.4    kardel 		    "***Buffer size exceeded for returned data\n");
   1460   1.4    kardel 		break;
   1461   1.4    kardel 
   1462   1.4    kardel 	default:
   1463   1.4    kardel 		fprintf(stderr,
   1464   1.4    kardel 		    "***Server returns unknown error code %d\n",
   1465   1.4    kardel 		    m6resp);
   1466   1.4    kardel 	}
   1467   1.4    kardel }
   1468   1.4    kardel 
   1469   1.4    kardel /*
   1470   1.4    kardel  * doquery - send a request and process the response, displaying
   1471   1.4    kardel  *	     error messages for any error responses.
   1472   1.1    kardel  */
   1473   1.1    kardel int
   1474   1.1    kardel doquery(
   1475   1.1    kardel 	int opcode,
   1476   1.4    kardel 	associd_t associd,
   1477   1.4    kardel 	int auth,
   1478  1.14  christos 	size_t qsize,
   1479   1.9  christos 	const char *qdata,
   1480   1.4    kardel 	u_short *rstatus,
   1481  1.14  christos 	size_t *rsize,
   1482   1.4    kardel 	const char **rdata
   1483   1.4    kardel 	)
   1484   1.4    kardel {
   1485   1.4    kardel 	return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
   1486   1.4    kardel 			 rsize, rdata, FALSE);
   1487   1.4    kardel }
   1488   1.4    kardel 
   1489   1.4    kardel 
   1490   1.4    kardel /*
   1491   1.4    kardel  * doqueryex - send a request and process the response, optionally
   1492   1.4    kardel  *	       displaying error messages for any error responses.
   1493   1.4    kardel  */
   1494   1.4    kardel int
   1495   1.4    kardel doqueryex(
   1496   1.4    kardel 	int opcode,
   1497   1.4    kardel 	associd_t associd,
   1498   1.1    kardel 	int auth,
   1499  1.14  christos 	size_t qsize,
   1500   1.9  christos 	const char *qdata,
   1501   1.1    kardel 	u_short *rstatus,
   1502  1.14  christos 	size_t *rsize,
   1503   1.4    kardel 	const char **rdata,
   1504   1.4    kardel 	int quiet
   1505   1.1    kardel 	)
   1506   1.1    kardel {
   1507   1.1    kardel 	int res;
   1508   1.1    kardel 	int done;
   1509   1.1    kardel 
   1510   1.1    kardel 	/*
   1511   1.1    kardel 	 * Check to make sure host is open
   1512   1.1    kardel 	 */
   1513   1.1    kardel 	if (!havehost) {
   1514   1.4    kardel 		fprintf(stderr, "***No host open, use `host' command\n");
   1515   1.1    kardel 		return -1;
   1516   1.1    kardel 	}
   1517   1.1    kardel 
   1518   1.1    kardel 	done = 0;
   1519   1.1    kardel 	sequence++;
   1520   1.1    kardel 
   1521   1.1    kardel     again:
   1522   1.1    kardel 	/*
   1523   1.1    kardel 	 * send a request
   1524   1.1    kardel 	 */
   1525   1.1    kardel 	res = sendrequest(opcode, associd, auth, qsize, qdata);
   1526   1.1    kardel 	if (res != 0)
   1527   1.4    kardel 		return res;
   1528   1.9  christos 
   1529   1.1    kardel 	/*
   1530   1.1    kardel 	 * Get the response.  If we got a standard error, print a message
   1531   1.1    kardel 	 */
   1532   1.1    kardel 	res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
   1533   1.1    kardel 
   1534   1.1    kardel 	if (res > 0) {
   1535   1.1    kardel 		if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
   1536   1.1    kardel 			if (res == ERR_INCOMPLETE) {
   1537   1.1    kardel 				/*
   1538   1.1    kardel 				 * better bump the sequence so we don't
   1539   1.1    kardel 				 * get confused about differing fragments.
   1540   1.1    kardel 				 */
   1541   1.1    kardel 				sequence++;
   1542   1.1    kardel 			}
   1543   1.1    kardel 			done = 1;
   1544   1.1    kardel 			goto again;
   1545   1.1    kardel 		}
   1546   1.4    kardel 		if (!quiet)
   1547   1.4    kardel 			show_error_msg(res, associd);
   1548   1.4    kardel 
   1549   1.1    kardel 	}
   1550   1.1    kardel 	return res;
   1551   1.1    kardel }
   1552   1.1    kardel 
   1553   1.1    kardel 
   1554   1.1    kardel #ifndef BUILD_AS_LIB
   1555   1.1    kardel /*
   1556   1.1    kardel  * getcmds - read commands from the standard input and execute them
   1557   1.1    kardel  */
   1558   1.1    kardel static void
   1559   1.1    kardel getcmds(void)
   1560   1.1    kardel {
   1561   1.1    kardel 	char *	line;
   1562   1.1    kardel 	int	count;
   1563   1.1    kardel 
   1564   1.1    kardel 	ntp_readline_init(interactive ? prompt : NULL);
   1565   1.1    kardel 
   1566   1.1    kardel 	for (;;) {
   1567   1.1    kardel 		line = ntp_readline(&count);
   1568   1.1    kardel 		if (NULL == line)
   1569   1.1    kardel 			break;
   1570   1.1    kardel 		docmd(line);
   1571   1.1    kardel 		free(line);
   1572   1.1    kardel 	}
   1573   1.1    kardel 
   1574   1.1    kardel 	ntp_readline_uninit();
   1575   1.1    kardel }
   1576   1.1    kardel #endif /* !BUILD_AS_LIB */
   1577   1.1    kardel 
   1578   1.1    kardel 
   1579   1.1    kardel #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
   1580   1.1    kardel /*
   1581   1.1    kardel  * abortcmd - catch interrupts and abort the current command
   1582   1.1    kardel  */
   1583  1.14  christos static int
   1584  1.14  christos abortcmd(void)
   1585   1.1    kardel {
   1586   1.1    kardel 	if (current_output == stdout)
   1587  1.14  christos 		(void) fflush(stdout);
   1588   1.1    kardel 	putc('\n', stderr);
   1589   1.1    kardel 	(void) fflush(stderr);
   1590  1.14  christos 	if (jump) {
   1591  1.14  christos 		jump = 0;
   1592  1.20  christos 		LONGJMP(interrupt_buf, 1);
   1593  1.14  christos 	}
   1594  1.14  christos 	return TRUE;
   1595   1.1    kardel }
   1596   1.1    kardel #endif	/* !SYS_WINNT && !BUILD_AS_LIB */
   1597   1.1    kardel 
   1598   1.1    kardel 
   1599   1.1    kardel #ifndef	BUILD_AS_LIB
   1600   1.1    kardel /*
   1601   1.1    kardel  * docmd - decode the command line and execute a command
   1602   1.1    kardel  */
   1603   1.1    kardel static void
   1604   1.1    kardel docmd(
   1605   1.1    kardel 	const char *cmdline
   1606   1.1    kardel 	)
   1607   1.1    kardel {
   1608   1.1    kardel 	char *tokens[1+MAXARGS+2];
   1609   1.1    kardel 	struct parse pcmd;
   1610   1.1    kardel 	int ntok;
   1611   1.1    kardel 	static int i;
   1612   1.1    kardel 	struct xcmd *xcmd;
   1613   1.1    kardel 
   1614   1.1    kardel 	/*
   1615   1.1    kardel 	 * Tokenize the command line.  If nothing on it, return.
   1616   1.1    kardel 	 */
   1617   1.1    kardel 	tokenize(cmdline, tokens, &ntok);
   1618   1.1    kardel 	if (ntok == 0)
   1619   1.1    kardel 	    return;
   1620   1.9  christos 
   1621   1.1    kardel 	/*
   1622   1.1    kardel 	 * Find the appropriate command description.
   1623   1.1    kardel 	 */
   1624   1.1    kardel 	i = findcmd(tokens[0], builtins, opcmds, &xcmd);
   1625   1.1    kardel 	if (i == 0) {
   1626   1.1    kardel 		(void) fprintf(stderr, "***Command `%s' unknown\n",
   1627   1.1    kardel 			       tokens[0]);
   1628   1.1    kardel 		return;
   1629   1.1    kardel 	} else if (i >= 2) {
   1630   1.1    kardel 		(void) fprintf(stderr, "***Command `%s' ambiguous\n",
   1631   1.1    kardel 			       tokens[0]);
   1632   1.1    kardel 		return;
   1633   1.1    kardel 	}
   1634   1.9  christos 
   1635   1.9  christos 	/* Warn about ignored extra args */
   1636   1.9  christos 	for (i = MAXARGS + 1; i < ntok ; ++i) {
   1637   1.9  christos 		fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
   1638   1.9  christos 	}
   1639   1.9  christos 
   1640   1.1    kardel 	/*
   1641   1.1    kardel 	 * Save the keyword, then walk through the arguments, interpreting
   1642   1.1    kardel 	 * as we go.
   1643   1.1    kardel 	 */
   1644   1.1    kardel 	pcmd.keyword = tokens[0];
   1645   1.1    kardel 	pcmd.nargs = 0;
   1646   1.1    kardel 	for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
   1647   1.1    kardel 		if ((i+1) >= ntok) {
   1648   1.1    kardel 			if (!(xcmd->arg[i] & OPT)) {
   1649   1.1    kardel 				printusage(xcmd, stderr);
   1650   1.1    kardel 				return;
   1651   1.1    kardel 			}
   1652   1.1    kardel 			break;
   1653   1.1    kardel 		}
   1654   1.1    kardel 		if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
   1655   1.1    kardel 			break;
   1656   1.1    kardel 		if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
   1657   1.1    kardel 			return;
   1658   1.1    kardel 		pcmd.nargs++;
   1659   1.1    kardel 	}
   1660   1.1    kardel 
   1661   1.1    kardel 	i++;
   1662   1.1    kardel 	if (i < ntok && *tokens[i] == '>') {
   1663   1.1    kardel 		char *fname;
   1664   1.1    kardel 
   1665   1.1    kardel 		if (*(tokens[i]+1) != '\0')
   1666   1.1    kardel 			fname = tokens[i]+1;
   1667   1.1    kardel 		else if ((i+1) < ntok)
   1668   1.1    kardel 			fname = tokens[i+1];
   1669   1.1    kardel 		else {
   1670   1.1    kardel 			(void) fprintf(stderr, "***No file for redirect\n");
   1671   1.1    kardel 			return;
   1672   1.1    kardel 		}
   1673   1.1    kardel 
   1674   1.1    kardel 		current_output = fopen(fname, "w");
   1675   1.1    kardel 		if (current_output == NULL) {
   1676   1.1    kardel 			(void) fprintf(stderr, "***Error opening %s: ", fname);
   1677   1.1    kardel 			perror("");
   1678   1.1    kardel 			return;
   1679   1.1    kardel 		}
   1680   1.1    kardel 	} else {
   1681   1.1    kardel 		current_output = stdout;
   1682   1.1    kardel 	}
   1683   1.1    kardel 
   1684  1.20  christos 	if (interactive) {
   1685  1.20  christos 		if ( ! SETJMP(interrupt_buf)) {
   1686  1.20  christos 			jump = 1;
   1687  1.20  christos 			(xcmd->handler)(&pcmd, current_output);
   1688  1.20  christos 			jump = 0;
   1689  1.20  christos 		} else {
   1690  1.20  christos 			fflush(current_output);
   1691  1.20  christos 			fputs("\n >>> command aborted <<<\n", stderr);
   1692  1.20  christos 			fflush(stderr);
   1693  1.20  christos 		}
   1694  1.20  christos 
   1695  1.20  christos 	} else {
   1696   1.1    kardel 		jump = 0;
   1697   1.1    kardel 		(xcmd->handler)(&pcmd, current_output);
   1698   1.1    kardel 	}
   1699  1.20  christos 	if ((NULL != current_output) && (stdout != current_output)) {
   1700  1.20  christos 		(void)fclose(current_output);
   1701  1.20  christos 		current_output = NULL;
   1702  1.20  christos 	}
   1703   1.1    kardel }
   1704   1.1    kardel 
   1705   1.1    kardel 
   1706   1.1    kardel /*
   1707   1.1    kardel  * tokenize - turn a command line into tokens
   1708   1.1    kardel  *
   1709   1.9  christos  * SK: Modified to allow a quoted string
   1710   1.1    kardel  *
   1711   1.1    kardel  * HMS: If the first character of the first token is a ':' then (after
   1712   1.1    kardel  * eating inter-token whitespace) the 2nd token is the rest of the line.
   1713   1.1    kardel  */
   1714   1.1    kardel 
   1715   1.1    kardel static void
   1716   1.1    kardel tokenize(
   1717   1.1    kardel 	const char *line,
   1718   1.1    kardel 	char **tokens,
   1719   1.1    kardel 	int *ntok
   1720   1.1    kardel 	)
   1721   1.1    kardel {
   1722   1.1    kardel 	register const char *cp;
   1723   1.1    kardel 	register char *sp;
   1724   1.1    kardel 	static char tspace[MAXLINE];
   1725   1.1    kardel 
   1726   1.1    kardel 	sp = tspace;
   1727   1.1    kardel 	cp = line;
   1728   1.1    kardel 	for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
   1729   1.1    kardel 		tokens[*ntok] = sp;
   1730   1.1    kardel 
   1731   1.1    kardel 		/* Skip inter-token whitespace */
   1732   1.1    kardel 		while (ISSPACE(*cp))
   1733   1.1    kardel 		    cp++;
   1734   1.1    kardel 
   1735   1.1    kardel 		/* If we're at EOL we're done */
   1736   1.1    kardel 		if (ISEOL(*cp))
   1737   1.1    kardel 		    break;
   1738   1.1    kardel 
   1739   1.1    kardel 		/* If this is the 2nd token and the first token begins
   1740   1.1    kardel 		 * with a ':', then just grab to EOL.
   1741   1.1    kardel 		 */
   1742   1.1    kardel 
   1743   1.1    kardel 		if (*ntok == 1 && tokens[0][0] == ':') {
   1744   1.1    kardel 			do {
   1745  1.10  christos 				if (sp - tspace >= MAXLINE)
   1746  1.10  christos 					goto toobig;
   1747   1.1    kardel 				*sp++ = *cp++;
   1748   1.1    kardel 			} while (!ISEOL(*cp));
   1749   1.1    kardel 		}
   1750   1.1    kardel 
   1751   1.1    kardel 		/* Check if this token begins with a double quote.
   1752   1.1    kardel 		 * If yes, continue reading till the next double quote
   1753   1.1    kardel 		 */
   1754   1.1    kardel 		else if (*cp == '\"') {
   1755   1.1    kardel 			++cp;
   1756   1.1    kardel 			do {
   1757  1.10  christos 				if (sp - tspace >= MAXLINE)
   1758  1.10  christos 					goto toobig;
   1759   1.1    kardel 				*sp++ = *cp++;
   1760   1.1    kardel 			} while ((*cp != '\"') && !ISEOL(*cp));
   1761   1.1    kardel 			/* HMS: a missing closing " should be an error */
   1762   1.1    kardel 		}
   1763   1.1    kardel 		else {
   1764   1.1    kardel 			do {
   1765  1.10  christos 				if (sp - tspace >= MAXLINE)
   1766  1.10  christos 					goto toobig;
   1767   1.1    kardel 				*sp++ = *cp++;
   1768   1.1    kardel 			} while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
   1769   1.1    kardel 			/* HMS: Why check for a " in the previous line? */
   1770   1.1    kardel 		}
   1771   1.1    kardel 
   1772  1.10  christos 		if (sp - tspace >= MAXLINE)
   1773  1.10  christos 			goto toobig;
   1774   1.1    kardel 		*sp++ = '\0';
   1775   1.1    kardel 	}
   1776  1.10  christos 	return;
   1777  1.10  christos 
   1778  1.10  christos   toobig:
   1779  1.10  christos 	*ntok = 0;
   1780  1.10  christos 	fprintf(stderr,
   1781  1.10  christos 		"***Line `%s' is too big\n",
   1782  1.10  christos 		line);
   1783  1.10  christos 	return;
   1784   1.1    kardel }
   1785   1.1    kardel 
   1786   1.1    kardel 
   1787   1.1    kardel /*
   1788   1.1    kardel  * getarg - interpret an argument token
   1789   1.1    kardel  */
   1790   1.1    kardel static int
   1791   1.1    kardel getarg(
   1792   1.9  christos 	const char *str,
   1793   1.1    kardel 	int code,
   1794   1.1    kardel 	arg_v *argp
   1795   1.1    kardel 	)
   1796   1.1    kardel {
   1797   1.9  christos 	u_long ul;
   1798   1.1    kardel 
   1799   1.1    kardel 	switch (code & ~OPT) {
   1800   1.9  christos 	case NTP_STR:
   1801   1.1    kardel 		argp->string = str;
   1802   1.1    kardel 		break;
   1803   1.9  christos 
   1804   1.9  christos 	case NTP_ADD:
   1805   1.9  christos 		if (!getnetnum(str, &argp->netnum, NULL, 0))
   1806   1.1    kardel 			return 0;
   1807   1.1    kardel 		break;
   1808   1.9  christos 
   1809   1.9  christos 	case NTP_UINT:
   1810   1.9  christos 		if ('&' == str[0]) {
   1811   1.9  christos 			if (!atouint(&str[1], &ul)) {
   1812   1.9  christos 				fprintf(stderr,
   1813   1.9  christos 					"***Association index `%s' invalid/undecodable\n",
   1814   1.9  christos 					str);
   1815   1.1    kardel 				return 0;
   1816   1.1    kardel 			}
   1817   1.9  christos 			if (0 == numassoc) {
   1818   1.9  christos 				dogetassoc(stdout);
   1819   1.9  christos 				if (0 == numassoc) {
   1820   1.9  christos 					fprintf(stderr,
   1821   1.9  christos 						"***No associations found, `%s' unknown\n",
   1822   1.9  christos 						str);
   1823   1.1    kardel 					return 0;
   1824   1.1    kardel 				}
   1825   1.1    kardel 			}
   1826   1.9  christos 			ul = min(ul, numassoc);
   1827   1.9  christos 			argp->uval = assoc_cache[ul - 1].assid;
   1828   1.1    kardel 			break;
   1829   1.1    kardel 		}
   1830   1.9  christos 		if (!atouint(str, &argp->uval)) {
   1831   1.9  christos 			fprintf(stderr, "***Illegal unsigned value %s\n",
   1832   1.9  christos 				str);
   1833   1.9  christos 			return 0;
   1834   1.1    kardel 		}
   1835   1.9  christos 		break;
   1836   1.1    kardel 
   1837   1.9  christos 	case NTP_INT:
   1838   1.9  christos 		if (!atoint(str, &argp->ival)) {
   1839   1.9  christos 			fprintf(stderr, "***Illegal integer value %s\n",
   1840   1.9  christos 				str);
   1841   1.9  christos 			return 0;
   1842   1.1    kardel 		}
   1843   1.1    kardel 		break;
   1844   1.9  christos 
   1845   1.9  christos 	case IP_VERSION:
   1846   1.9  christos 		if (!strcmp("-6", str)) {
   1847   1.9  christos 			argp->ival = 6;
   1848   1.9  christos 		} else if (!strcmp("-4", str)) {
   1849   1.9  christos 			argp->ival = 4;
   1850   1.9  christos 		} else {
   1851   1.9  christos 			fprintf(stderr, "***Version must be either 4 or 6\n");
   1852   1.1    kardel 			return 0;
   1853   1.1    kardel 		}
   1854   1.1    kardel 		break;
   1855   1.1    kardel 	}
   1856   1.1    kardel 
   1857   1.1    kardel 	return 1;
   1858   1.1    kardel }
   1859   1.1    kardel #endif	/* !BUILD_AS_LIB */
   1860   1.1    kardel 
   1861   1.1    kardel 
   1862   1.1    kardel /*
   1863   1.1    kardel  * findcmd - find a command in a command description table
   1864   1.1    kardel  */
   1865   1.1    kardel static int
   1866   1.1    kardel findcmd(
   1867   1.9  christos 	const char *	str,
   1868   1.9  christos 	struct xcmd *	clist1,
   1869   1.9  christos 	struct xcmd *	clist2,
   1870   1.9  christos 	struct xcmd **	cmd
   1871   1.1    kardel 	)
   1872   1.1    kardel {
   1873   1.9  christos 	struct xcmd *cl;
   1874  1.14  christos 	size_t clen;
   1875   1.1    kardel 	int nmatch;
   1876   1.1    kardel 	struct xcmd *nearmatch = NULL;
   1877   1.1    kardel 	struct xcmd *clist;
   1878   1.1    kardel 
   1879   1.1    kardel 	clen = strlen(str);
   1880   1.1    kardel 	nmatch = 0;
   1881   1.1    kardel 	if (clist1 != 0)
   1882   1.1    kardel 	    clist = clist1;
   1883   1.1    kardel 	else if (clist2 != 0)
   1884   1.1    kardel 	    clist = clist2;
   1885   1.1    kardel 	else
   1886   1.1    kardel 	    return 0;
   1887   1.1    kardel 
   1888   1.1    kardel     again:
   1889   1.1    kardel 	for (cl = clist; cl->keyword != 0; cl++) {
   1890   1.1    kardel 		/* do a first character check, for efficiency */
   1891   1.1    kardel 		if (*str != *(cl->keyword))
   1892   1.1    kardel 		    continue;
   1893   1.1    kardel 		if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
   1894   1.1    kardel 			/*
   1895   1.1    kardel 			 * Could be extact match, could be approximate.
   1896   1.1    kardel 			 * Is exact if the length of the keyword is the
   1897   1.1    kardel 			 * same as the str.
   1898   1.1    kardel 			 */
   1899   1.1    kardel 			if (*((cl->keyword) + clen) == '\0') {
   1900   1.1    kardel 				*cmd = cl;
   1901   1.1    kardel 				return 1;
   1902   1.1    kardel 			}
   1903   1.1    kardel 			nmatch++;
   1904   1.1    kardel 			nearmatch = cl;
   1905   1.1    kardel 		}
   1906   1.1    kardel 	}
   1907   1.1    kardel 
   1908   1.1    kardel 	/*
   1909   1.1    kardel 	 * See if there is more to do.  If so, go again.  Sorry about the
   1910   1.1    kardel 	 * goto, too much looking at BSD sources...
   1911   1.1    kardel 	 */
   1912   1.1    kardel 	if (clist == clist1 && clist2 != 0) {
   1913   1.1    kardel 		clist = clist2;
   1914   1.1    kardel 		goto again;
   1915   1.1    kardel 	}
   1916   1.1    kardel 
   1917   1.1    kardel 	/*
   1918   1.1    kardel 	 * If we got extactly 1 near match, use it, else return number
   1919   1.1    kardel 	 * of matches.
   1920   1.1    kardel 	 */
   1921   1.1    kardel 	if (nmatch == 1) {
   1922   1.1    kardel 		*cmd = nearmatch;
   1923   1.1    kardel 		return 1;
   1924   1.1    kardel 	}
   1925   1.1    kardel 	return nmatch;
   1926   1.1    kardel }
   1927   1.1    kardel 
   1928   1.1    kardel 
   1929   1.1    kardel /*
   1930   1.1    kardel  * getnetnum - given a host name, return its net number
   1931   1.1    kardel  *	       and (optional) full name
   1932   1.1    kardel  */
   1933   1.1    kardel int
   1934   1.1    kardel getnetnum(
   1935   1.1    kardel 	const char *hname,
   1936   1.1    kardel 	sockaddr_u *num,
   1937   1.1    kardel 	char *fullhost,
   1938   1.1    kardel 	int af
   1939   1.1    kardel 	)
   1940   1.1    kardel {
   1941   1.1    kardel 	struct addrinfo hints, *ai = NULL;
   1942   1.1    kardel 
   1943   1.4    kardel 	ZERO(hints);
   1944   1.1    kardel 	hints.ai_flags = AI_CANONNAME;
   1945   1.1    kardel #ifdef AI_ADDRCONFIG
   1946   1.1    kardel 	hints.ai_flags |= AI_ADDRCONFIG;
   1947   1.1    kardel #endif
   1948   1.9  christos 
   1949   1.4    kardel 	/*
   1950   1.4    kardel 	 * decodenetnum only works with addresses, but handles syntax
   1951   1.4    kardel 	 * that getaddrinfo doesn't:  [2001::1]:1234
   1952   1.4    kardel 	 */
   1953   1.1    kardel 	if (decodenetnum(hname, num)) {
   1954   1.4    kardel 		if (fullhost != NULL)
   1955   1.4    kardel 			getnameinfo(&num->sa, SOCKLEN(num), fullhost,
   1956   1.4    kardel 				    LENHOSTNAME, NULL, 0, 0);
   1957   1.1    kardel 		return 1;
   1958   1.1    kardel 	} else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
   1959   1.9  christos 		INSIST(sizeof(*num) >= ai->ai_addrlen);
   1960   1.4    kardel 		memcpy(num, ai->ai_addr, ai->ai_addrlen);
   1961   1.4    kardel 		if (fullhost != NULL) {
   1962   1.9  christos 			if (ai->ai_canonname != NULL)
   1963   1.9  christos 				strlcpy(fullhost, ai->ai_canonname,
   1964   1.4    kardel 					LENHOSTNAME);
   1965   1.9  christos 			else
   1966   1.4    kardel 				getnameinfo(&num->sa, SOCKLEN(num),
   1967   1.4    kardel 					    fullhost, LENHOSTNAME, NULL,
   1968   1.4    kardel 					    0, 0);
   1969   1.4    kardel 		}
   1970   1.9  christos 		freeaddrinfo(ai);
   1971   1.1    kardel 		return 1;
   1972   1.1    kardel 	}
   1973   1.4    kardel 	fprintf(stderr, "***Can't find host %s\n", hname);
   1974   1.4    kardel 
   1975   1.4    kardel 	return 0;
   1976   1.1    kardel }
   1977   1.1    kardel 
   1978   1.9  christos 
   1979   1.1    kardel /*
   1980   1.1    kardel  * nntohost - convert network number to host name.  This routine enforces
   1981   1.1    kardel  *	       the showhostnames setting.
   1982   1.1    kardel  */
   1983   1.4    kardel const char *
   1984   1.1    kardel nntohost(
   1985   1.1    kardel 	sockaddr_u *netnum
   1986   1.1    kardel 	)
   1987   1.1    kardel {
   1988   1.4    kardel 	return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
   1989   1.4    kardel }
   1990   1.4    kardel 
   1991   1.4    kardel 
   1992   1.4    kardel /*
   1993   1.4    kardel  * nntohost_col - convert network number to host name in fixed width.
   1994   1.4    kardel  *		  This routine enforces the showhostnames setting.
   1995   1.4    kardel  *		  When displaying hostnames longer than the width,
   1996   1.4    kardel  *		  the first part of the hostname is displayed.  When
   1997   1.4    kardel  *		  displaying numeric addresses longer than the width,
   1998   1.4    kardel  *		  Such as IPv6 addresses, the caller decides whether
   1999   1.4    kardel  *		  the first or last of the numeric address is used.
   2000   1.4    kardel  */
   2001   1.4    kardel const char *
   2002   1.4    kardel nntohost_col(
   2003   1.4    kardel 	sockaddr_u *	addr,
   2004   1.4    kardel 	size_t		width,
   2005   1.4    kardel 	int		preserve_lowaddrbits
   2006   1.4    kardel 	)
   2007   1.4    kardel {
   2008   1.4    kardel 	const char *	out;
   2009   1.4    kardel 
   2010   1.9  christos 	if (!showhostnames || SOCK_UNSPEC(addr)) {
   2011   1.4    kardel 		if (preserve_lowaddrbits)
   2012   1.4    kardel 			out = trunc_left(stoa(addr), width);
   2013   1.4    kardel 		else
   2014   1.4    kardel 			out = trunc_right(stoa(addr), width);
   2015   1.4    kardel 	} else if (ISREFCLOCKADR(addr)) {
   2016   1.4    kardel 		out = refnumtoa(addr);
   2017   1.4    kardel 	} else {
   2018   1.4    kardel 		out = trunc_right(socktohost(addr), width);
   2019   1.4    kardel 	}
   2020   1.4    kardel 	return out;
   2021   1.1    kardel }
   2022   1.1    kardel 
   2023   1.1    kardel 
   2024   1.1    kardel /*
   2025   1.9  christos  * nntohostp() is the same as nntohost() plus a :port suffix
   2026   1.9  christos  */
   2027   1.9  christos const char *
   2028   1.9  christos nntohostp(
   2029   1.9  christos 	sockaddr_u *netnum
   2030   1.9  christos 	)
   2031   1.9  christos {
   2032   1.9  christos 	const char *	hostn;
   2033   1.9  christos 	char *		buf;
   2034   1.9  christos 
   2035   1.9  christos 	if (!showhostnames || SOCK_UNSPEC(netnum))
   2036   1.9  christos 		return sptoa(netnum);
   2037   1.9  christos 	else if (ISREFCLOCKADR(netnum))
   2038   1.9  christos 		return refnumtoa(netnum);
   2039   1.9  christos 
   2040   1.9  christos 	hostn = socktohost(netnum);
   2041   1.9  christos 	LIB_GETBUF(buf);
   2042   1.9  christos 	snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
   2043   1.9  christos 
   2044   1.9  christos 	return buf;
   2045   1.9  christos }
   2046   1.9  christos 
   2047   1.9  christos /*
   2048   1.1    kardel  * rtdatetolfp - decode an RT-11 date into an l_fp
   2049   1.1    kardel  */
   2050   1.1    kardel static int
   2051   1.1    kardel rtdatetolfp(
   2052   1.1    kardel 	char *str,
   2053   1.1    kardel 	l_fp *lfp
   2054   1.1    kardel 	)
   2055   1.1    kardel {
   2056   1.1    kardel 	register char *cp;
   2057   1.1    kardel 	register int i;
   2058   1.1    kardel 	struct calendar cal;
   2059   1.1    kardel 	char buf[4];
   2060   1.1    kardel 
   2061   1.1    kardel 	cal.yearday = 0;
   2062   1.1    kardel 
   2063   1.1    kardel 	/*
   2064   1.1    kardel 	 * An RT-11 date looks like:
   2065   1.1    kardel 	 *
   2066   1.1    kardel 	 * d[d]-Mth-y[y] hh:mm:ss
   2067   1.1    kardel 	 *
   2068   1.1    kardel 	 * (No docs, but assume 4-digit years are also legal...)
   2069   1.1    kardel 	 *
   2070   1.1    kardel 	 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
   2071   1.1    kardel 	 */
   2072   1.1    kardel 	cp = str;
   2073  1.19  christos 	if (!isdigit(pgetc(cp))) {
   2074   1.1    kardel 		if (*cp == '-') {
   2075   1.1    kardel 			/*
   2076   1.1    kardel 			 * Catch special case
   2077   1.1    kardel 			 */
   2078   1.1    kardel 			L_CLR(lfp);
   2079   1.1    kardel 			return 1;
   2080   1.1    kardel 		}
   2081   1.1    kardel 		return 0;
   2082   1.1    kardel 	}
   2083   1.1    kardel 
   2084   1.1    kardel 	cal.monthday = (u_char) (*cp++ - '0');	/* ascii dependent */
   2085  1.19  christos 	if (isdigit(pgetc(cp))) {
   2086   1.1    kardel 		cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
   2087   1.1    kardel 		cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
   2088   1.1    kardel 	}
   2089   1.1    kardel 
   2090   1.1    kardel 	if (*cp++ != '-')
   2091   1.1    kardel 	    return 0;
   2092   1.9  christos 
   2093   1.1    kardel 	for (i = 0; i < 3; i++)
   2094   1.1    kardel 	    buf[i] = *cp++;
   2095   1.1    kardel 	buf[3] = '\0';
   2096   1.1    kardel 
   2097   1.1    kardel 	for (i = 0; i < 12; i++)
   2098   1.1    kardel 	    if (STREQ(buf, months[i]))
   2099   1.1    kardel 		break;
   2100   1.1    kardel 	if (i == 12)
   2101   1.1    kardel 	    return 0;
   2102   1.1    kardel 	cal.month = (u_char)(i + 1);
   2103   1.1    kardel 
   2104   1.1    kardel 	if (*cp++ != '-')
   2105   1.1    kardel 	    return 0;
   2106   1.9  christos 
   2107  1.19  christos 	if (!isdigit(pgetc(cp)))
   2108   1.1    kardel 	    return 0;
   2109   1.1    kardel 	cal.year = (u_short)(*cp++ - '0');
   2110  1.19  christos 	if (isdigit(pgetc(cp))) {
   2111   1.1    kardel 		cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
   2112   1.1    kardel 		cal.year = (u_short)(*cp++ - '0');
   2113   1.1    kardel 	}
   2114  1.19  christos 	if (isdigit(pgetc(cp))) {
   2115   1.1    kardel 		cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
   2116   1.1    kardel 		cal.year = (u_short)(cal.year + *cp++ - '0');
   2117   1.1    kardel 	}
   2118  1.19  christos 	if (isdigit(pgetc(cp))) {
   2119   1.1    kardel 		cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
   2120   1.1    kardel 		cal.year = (u_short)(cal.year + *cp++ - '0');
   2121   1.1    kardel 	}
   2122   1.1    kardel 
   2123   1.1    kardel 	/*
   2124   1.1    kardel 	 * Catch special case.  If cal.year == 0 this is a zero timestamp.
   2125   1.1    kardel 	 */
   2126   1.1    kardel 	if (cal.year == 0) {
   2127   1.1    kardel 		L_CLR(lfp);
   2128   1.1    kardel 		return 1;
   2129   1.1    kardel 	}
   2130   1.1    kardel 
   2131  1.19  christos 	if (*cp++ != ' ' || !isdigit(pgetc(cp)))
   2132   1.1    kardel 	    return 0;
   2133   1.1    kardel 	cal.hour = (u_char)(*cp++ - '0');
   2134  1.19  christos 	if (isdigit(pgetc(cp))) {
   2135   1.1    kardel 		cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
   2136   1.1    kardel 		cal.hour = (u_char)(cal.hour + *cp++ - '0');
   2137   1.1    kardel 	}
   2138   1.1    kardel 
   2139  1.19  christos 	if (*cp++ != ':' || !isdigit(pgetc(cp)))
   2140   1.1    kardel 	    return 0;
   2141   1.1    kardel 	cal.minute = (u_char)(*cp++ - '0');
   2142  1.19  christos 	if (isdigit(pgetc(cp))) {
   2143   1.1    kardel 		cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
   2144   1.1    kardel 		cal.minute = (u_char)(cal.minute + *cp++ - '0');
   2145   1.1    kardel 	}
   2146   1.1    kardel 
   2147  1.19  christos 	if (*cp++ != ':' || !isdigit(pgetc(cp)))
   2148   1.1    kardel 	    return 0;
   2149   1.1    kardel 	cal.second = (u_char)(*cp++ - '0');
   2150  1.19  christos 	if (isdigit(pgetc(cp))) {
   2151   1.1    kardel 		cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
   2152   1.1    kardel 		cal.second = (u_char)(cal.second + *cp++ - '0');
   2153   1.1    kardel 	}
   2154   1.1    kardel 
   2155   1.1    kardel 	/*
   2156   1.1    kardel 	 * For RT-11, 1972 seems to be the pivot year
   2157   1.1    kardel 	 */
   2158   1.1    kardel 	if (cal.year < 72)
   2159   1.1    kardel 		cal.year += 2000;
   2160   1.1    kardel 	if (cal.year < 100)
   2161   1.1    kardel 		cal.year += 1900;
   2162   1.1    kardel 
   2163   1.1    kardel 	lfp->l_ui = caltontp(&cal);
   2164   1.1    kardel 	lfp->l_uf = 0;
   2165   1.1    kardel 	return 1;
   2166   1.1    kardel }
   2167   1.1    kardel 
   2168   1.1    kardel 
   2169   1.1    kardel /*
   2170   1.1    kardel  * decodets - decode a timestamp into an l_fp format number, with
   2171   1.1    kardel  *	      consideration of fuzzball formats.
   2172   1.1    kardel  */
   2173   1.1    kardel int
   2174   1.1    kardel decodets(
   2175   1.1    kardel 	char *str,
   2176   1.1    kardel 	l_fp *lfp
   2177   1.1    kardel 	)
   2178   1.1    kardel {
   2179   1.4    kardel 	char *cp;
   2180   1.4    kardel 	char buf[30];
   2181   1.4    kardel 	size_t b;
   2182   1.4    kardel 
   2183   1.1    kardel 	/*
   2184   1.1    kardel 	 * If it starts with a 0x, decode as hex.
   2185   1.1    kardel 	 */
   2186   1.1    kardel 	if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
   2187   1.1    kardel 		return hextolfp(str+2, lfp);
   2188   1.1    kardel 
   2189   1.1    kardel 	/*
   2190   1.1    kardel 	 * If it starts with a '"', try it as an RT-11 date.
   2191   1.1    kardel 	 */
   2192   1.1    kardel 	if (*str == '"') {
   2193   1.4    kardel 		cp = str + 1;
   2194   1.4    kardel 		b = 0;
   2195   1.4    kardel 		while ('"' != *cp && '\0' != *cp &&
   2196   1.4    kardel 		       b < COUNTOF(buf) - 1)
   2197   1.4    kardel 			buf[b++] = *cp++;
   2198   1.4    kardel 		buf[b] = '\0';
   2199   1.1    kardel 		return rtdatetolfp(buf, lfp);
   2200   1.1    kardel 	}
   2201   1.1    kardel 
   2202   1.1    kardel 	/*
   2203   1.1    kardel 	 * Might still be hex.  Check out the first character.  Talk
   2204   1.1    kardel 	 * about heuristics!
   2205   1.1    kardel 	 */
   2206   1.1    kardel 	if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
   2207   1.1    kardel 		return hextolfp(str, lfp);
   2208   1.1    kardel 
   2209   1.1    kardel 	/*
   2210   1.1    kardel 	 * Try it as a decimal.  If this fails, try as an unquoted
   2211   1.1    kardel 	 * RT-11 date.  This code should go away eventually.
   2212   1.1    kardel 	 */
   2213   1.1    kardel 	if (atolfp(str, lfp))
   2214   1.1    kardel 		return 1;
   2215   1.1    kardel 
   2216   1.1    kardel 	return rtdatetolfp(str, lfp);
   2217   1.1    kardel }
   2218   1.1    kardel 
   2219   1.1    kardel 
   2220   1.1    kardel /*
   2221   1.1    kardel  * decodetime - decode a time value.  It should be in milliseconds
   2222   1.1    kardel  */
   2223   1.1    kardel int
   2224   1.1    kardel decodetime(
   2225   1.1    kardel 	char *str,
   2226   1.1    kardel 	l_fp *lfp
   2227   1.1    kardel 	)
   2228   1.1    kardel {
   2229   1.1    kardel 	return mstolfp(str, lfp);
   2230   1.1    kardel }
   2231   1.1    kardel 
   2232   1.1    kardel 
   2233   1.1    kardel /*
   2234   1.1    kardel  * decodeint - decode an integer
   2235   1.1    kardel  */
   2236   1.1    kardel int
   2237   1.1    kardel decodeint(
   2238   1.1    kardel 	char *str,
   2239   1.1    kardel 	long *val
   2240   1.1    kardel 	)
   2241   1.1    kardel {
   2242   1.1    kardel 	if (*str == '0') {
   2243   1.1    kardel 		if (*(str+1) == 'x' || *(str+1) == 'X')
   2244   1.1    kardel 		    return hextoint(str+2, (u_long *)val);
   2245   1.1    kardel 		return octtoint(str, (u_long *)val);
   2246   1.1    kardel 	}
   2247   1.1    kardel 	return atoint(str, val);
   2248   1.1    kardel }
   2249   1.1    kardel 
   2250   1.1    kardel 
   2251   1.1    kardel /*
   2252   1.1    kardel  * decodeuint - decode an unsigned integer
   2253   1.1    kardel  */
   2254   1.1    kardel int
   2255   1.1    kardel decodeuint(
   2256   1.1    kardel 	char *str,
   2257   1.1    kardel 	u_long *val
   2258   1.1    kardel 	)
   2259   1.1    kardel {
   2260   1.1    kardel 	if (*str == '0') {
   2261   1.1    kardel 		if (*(str + 1) == 'x' || *(str + 1) == 'X')
   2262   1.1    kardel 			return (hextoint(str + 2, val));
   2263   1.1    kardel 		return (octtoint(str, val));
   2264   1.1    kardel 	}
   2265   1.1    kardel 	return (atouint(str, val));
   2266   1.1    kardel }
   2267   1.1    kardel 
   2268   1.1    kardel 
   2269   1.1    kardel /*
   2270   1.1    kardel  * decodearr - decode an array of time values
   2271   1.1    kardel  */
   2272   1.1    kardel static int
   2273   1.1    kardel decodearr(
   2274  1.19  christos 	char *cp,
   2275  1.19  christos 	int  *narr,
   2276  1.19  christos 	l_fp *lfpa,
   2277  1.19  christos 	int   amax
   2278   1.1    kardel 	)
   2279   1.1    kardel {
   2280  1.19  christos 	char *bp;
   2281   1.1    kardel 	char buf[60];
   2282   1.1    kardel 
   2283   1.1    kardel 	*narr = 0;
   2284   1.1    kardel 
   2285  1.19  christos 	while (*narr < amax && *cp) {
   2286  1.19  christos 		if (isspace(pgetc(cp))) {
   2287  1.19  christos 			do
   2288  1.19  christos 				++cp;
   2289  1.19  christos 			while (*cp && isspace(pgetc(cp)));
   2290  1.19  christos 		} else {
   2291  1.19  christos 			bp = buf;
   2292  1.19  christos 			do {
   2293  1.19  christos 				if (bp != (buf + sizeof(buf) - 1))
   2294  1.19  christos 					*bp++ = *cp;
   2295  1.19  christos 				++cp;
   2296  1.19  christos 			} while (*cp && !isspace(pgetc(cp)));
   2297  1.19  christos 			*bp = '\0';
   2298   1.1    kardel 
   2299  1.19  christos 			if (!decodetime(buf, lfpa))
   2300  1.19  christos 				return 0;
   2301  1.19  christos 			++(*narr);
   2302  1.19  christos 			++lfpa;
   2303  1.19  christos 		}
   2304   1.1    kardel 	}
   2305   1.1    kardel 	return 1;
   2306   1.1    kardel }
   2307   1.1    kardel 
   2308   1.1    kardel 
   2309   1.1    kardel /*
   2310   1.1    kardel  * Finally, the built in command handlers
   2311   1.1    kardel  */
   2312   1.1    kardel 
   2313   1.1    kardel /*
   2314   1.1    kardel  * help - tell about commands, or details of a particular command
   2315   1.1    kardel  */
   2316   1.1    kardel static void
   2317   1.1    kardel help(
   2318   1.1    kardel 	struct parse *pcmd,
   2319   1.1    kardel 	FILE *fp
   2320   1.1    kardel 	)
   2321   1.1    kardel {
   2322   1.1    kardel 	struct xcmd *xcp = NULL;	/* quiet warning */
   2323   1.9  christos 	const char *cmd;
   2324   1.1    kardel 	const char *list[100];
   2325   1.4    kardel 	size_t word, words;
   2326   1.4    kardel 	size_t row, rows;
   2327   1.4    kardel 	size_t col, cols;
   2328   1.4    kardel 	size_t length;
   2329   1.1    kardel 
   2330   1.1    kardel 	if (pcmd->nargs == 0) {
   2331   1.1    kardel 		words = 0;
   2332   1.4    kardel 		for (xcp = builtins; xcp->keyword != NULL; xcp++) {
   2333   1.9  christos 			if (*(xcp->keyword) != '?' &&
   2334   1.9  christos 			    words < COUNTOF(list))
   2335   1.1    kardel 				list[words++] = xcp->keyword;
   2336   1.1    kardel 		}
   2337   1.4    kardel 		for (xcp = opcmds; xcp->keyword != NULL; xcp++)
   2338   1.9  christos 			if (words < COUNTOF(list))
   2339   1.9  christos 				list[words++] = xcp->keyword;
   2340   1.1    kardel 
   2341   1.9  christos 		qsort((void *)list, words, sizeof(list[0]), helpsort);
   2342   1.1    kardel 		col = 0;
   2343   1.1    kardel 		for (word = 0; word < words; word++) {
   2344   1.9  christos 			length = strlen(list[word]);
   2345   1.4    kardel 			col = max(col, length);
   2346   1.1    kardel 		}
   2347   1.1    kardel 
   2348   1.1    kardel 		cols = SCREENWIDTH / ++col;
   2349   1.1    kardel 		rows = (words + cols - 1) / cols;
   2350   1.1    kardel 
   2351   1.4    kardel 		fprintf(fp, "ntpq commands:\n");
   2352   1.1    kardel 
   2353   1.1    kardel 		for (row = 0; row < rows; row++) {
   2354   1.4    kardel 			for (word = row; word < words; word += rows)
   2355   1.9  christos 				fprintf(fp, "%-*.*s", (int)col,
   2356   1.9  christos 					(int)col - 1, list[word]);
   2357   1.4    kardel 			fprintf(fp, "\n");
   2358   1.1    kardel 		}
   2359   1.1    kardel 	} else {
   2360   1.1    kardel 		cmd = pcmd->argval[0].string;
   2361   1.1    kardel 		words = findcmd(cmd, builtins, opcmds, &xcp);
   2362   1.1    kardel 		if (words == 0) {
   2363   1.4    kardel 			fprintf(stderr,
   2364   1.4    kardel 				"Command `%s' is unknown\n", cmd);
   2365   1.1    kardel 			return;
   2366   1.1    kardel 		} else if (words >= 2) {
   2367   1.4    kardel 			fprintf(stderr,
   2368   1.4    kardel 				"Command `%s' is ambiguous\n", cmd);
   2369   1.1    kardel 			return;
   2370   1.1    kardel 		}
   2371   1.4    kardel 		fprintf(fp, "function: %s\n", xcp->comment);
   2372   1.1    kardel 		printusage(xcp, fp);
   2373   1.1    kardel 	}
   2374   1.1    kardel }
   2375   1.1    kardel 
   2376   1.1    kardel 
   2377   1.1    kardel /*
   2378   1.1    kardel  * helpsort - do hostname qsort comparisons
   2379   1.1    kardel  */
   2380   1.1    kardel static int
   2381   1.1    kardel helpsort(
   2382   1.1    kardel 	const void *t1,
   2383   1.1    kardel 	const void *t2
   2384   1.1    kardel 	)
   2385   1.1    kardel {
   2386   1.4    kardel 	const char * const *	name1 = t1;
   2387   1.4    kardel 	const char * const *	name2 = t2;
   2388   1.1    kardel 
   2389   1.1    kardel 	return strcmp(*name1, *name2);
   2390   1.1    kardel }
   2391   1.1    kardel 
   2392   1.1    kardel 
   2393   1.1    kardel /*
   2394   1.1    kardel  * printusage - print usage information for a command
   2395   1.1    kardel  */
   2396   1.1    kardel static void
   2397   1.1    kardel printusage(
   2398   1.1    kardel 	struct xcmd *xcp,
   2399   1.1    kardel 	FILE *fp
   2400   1.1    kardel 	)
   2401   1.1    kardel {
   2402   1.1    kardel 	register int i;
   2403   1.1    kardel 
   2404   1.9  christos 	/* XXX: Do we need to warn about extra args here too? */
   2405   1.9  christos 
   2406   1.1    kardel 	(void) fprintf(fp, "usage: %s", xcp->keyword);
   2407   1.1    kardel 	for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
   2408   1.1    kardel 		if (xcp->arg[i] & OPT)
   2409   1.1    kardel 		    (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
   2410   1.1    kardel 		else
   2411   1.1    kardel 		    (void) fprintf(fp, " %s", xcp->desc[i]);
   2412   1.1    kardel 	}
   2413   1.1    kardel 	(void) fprintf(fp, "\n");
   2414   1.1    kardel }
   2415   1.1    kardel 
   2416   1.1    kardel 
   2417   1.1    kardel /*
   2418   1.1    kardel  * timeout - set time out time
   2419   1.1    kardel  */
   2420   1.1    kardel static void
   2421   1.1    kardel timeout(
   2422   1.1    kardel 	struct parse *pcmd,
   2423   1.1    kardel 	FILE *fp
   2424   1.1    kardel 	)
   2425   1.1    kardel {
   2426   1.1    kardel 	int val;
   2427   1.1    kardel 
   2428   1.1    kardel 	if (pcmd->nargs == 0) {
   2429   1.1    kardel 		val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
   2430   1.1    kardel 		(void) fprintf(fp, "primary timeout %d ms\n", val);
   2431   1.1    kardel 	} else {
   2432   1.1    kardel 		tvout.tv_sec = pcmd->argval[0].uval / 1000;
   2433   1.1    kardel 		tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
   2434   1.1    kardel 			* 1000;
   2435   1.1    kardel 	}
   2436   1.1    kardel }
   2437   1.1    kardel 
   2438   1.1    kardel 
   2439   1.1    kardel /*
   2440   1.1    kardel  * auth_delay - set delay for auth requests
   2441   1.1    kardel  */
   2442   1.1    kardel static void
   2443   1.1    kardel auth_delay(
   2444   1.1    kardel 	struct parse *pcmd,
   2445   1.1    kardel 	FILE *fp
   2446   1.1    kardel 	)
   2447   1.1    kardel {
   2448   1.1    kardel 	int isneg;
   2449   1.1    kardel 	u_long val;
   2450   1.1    kardel 
   2451   1.1    kardel 	if (pcmd->nargs == 0) {
   2452   1.1    kardel 		val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
   2453   1.1    kardel 		(void) fprintf(fp, "delay %lu ms\n", val);
   2454   1.1    kardel 	} else {
   2455   1.1    kardel 		if (pcmd->argval[0].ival < 0) {
   2456   1.1    kardel 			isneg = 1;
   2457   1.1    kardel 			val = (u_long)(-pcmd->argval[0].ival);
   2458   1.1    kardel 		} else {
   2459   1.1    kardel 			isneg = 0;
   2460   1.1    kardel 			val = (u_long)pcmd->argval[0].ival;
   2461   1.1    kardel 		}
   2462   1.1    kardel 
   2463   1.1    kardel 		delay_time.l_ui = val / 1000;
   2464   1.1    kardel 		val %= 1000;
   2465   1.1    kardel 		delay_time.l_uf = val * 4294967;	/* 2**32/1000 */
   2466   1.1    kardel 
   2467   1.1    kardel 		if (isneg)
   2468   1.1    kardel 		    L_NEG(&delay_time);
   2469   1.1    kardel 	}
   2470   1.1    kardel }
   2471   1.1    kardel 
   2472   1.1    kardel 
   2473   1.1    kardel /*
   2474   1.1    kardel  * host - set the host we are dealing with.
   2475   1.1    kardel  */
   2476   1.1    kardel static void
   2477   1.1    kardel host(
   2478   1.1    kardel 	struct parse *pcmd,
   2479   1.1    kardel 	FILE *fp
   2480   1.1    kardel 	)
   2481   1.1    kardel {
   2482   1.1    kardel 	int i;
   2483   1.1    kardel 
   2484   1.1    kardel 	if (pcmd->nargs == 0) {
   2485   1.1    kardel 		if (havehost)
   2486   1.1    kardel 			(void) fprintf(fp, "current host is %s\n",
   2487   1.1    kardel 					   currenthost);
   2488   1.1    kardel 		else
   2489   1.1    kardel 			(void) fprintf(fp, "no current host\n");
   2490   1.1    kardel 		return;
   2491   1.1    kardel 	}
   2492   1.1    kardel 
   2493   1.1    kardel 	i = 0;
   2494   1.1    kardel 	ai_fam_templ = ai_fam_default;
   2495   1.1    kardel 	if (pcmd->nargs == 2) {
   2496   1.1    kardel 		if (!strcmp("-4", pcmd->argval[i].string))
   2497   1.1    kardel 			ai_fam_templ = AF_INET;
   2498   1.1    kardel 		else if (!strcmp("-6", pcmd->argval[i].string))
   2499   1.1    kardel 			ai_fam_templ = AF_INET6;
   2500   1.9  christos 		else
   2501   1.9  christos 			goto no_change;
   2502   1.1    kardel 		i = 1;
   2503   1.1    kardel 	}
   2504   1.9  christos 	if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
   2505   1.9  christos 		fprintf(fp, "current host set to %s\n", currenthost);
   2506   1.1    kardel 	} else {
   2507   1.9  christos     no_change:
   2508   1.1    kardel 		if (havehost)
   2509   1.9  christos 			fprintf(fp, "current host remains %s\n",
   2510   1.9  christos 				currenthost);
   2511   1.1    kardel 		else
   2512   1.9  christos 			fprintf(fp, "still no current host\n");
   2513   1.1    kardel 	}
   2514   1.1    kardel }
   2515   1.1    kardel 
   2516   1.1    kardel 
   2517   1.1    kardel /*
   2518   1.1    kardel  * poll - do one (or more) polls of the host via NTP
   2519   1.1    kardel  */
   2520   1.1    kardel /*ARGSUSED*/
   2521   1.1    kardel static void
   2522   1.1    kardel ntp_poll(
   2523   1.1    kardel 	struct parse *pcmd,
   2524   1.1    kardel 	FILE *fp
   2525   1.1    kardel 	)
   2526   1.1    kardel {
   2527   1.1    kardel 	(void) fprintf(fp, "poll not implemented yet\n");
   2528   1.1    kardel }
   2529   1.1    kardel 
   2530   1.1    kardel 
   2531   1.1    kardel /*
   2532  1.15  christos  * showdrefid2str - return a string explanation of the value of drefid
   2533  1.15  christos  */
   2534  1.15  christos static const char *
   2535  1.15  christos showdrefid2str(void)
   2536  1.15  christos {
   2537  1.15  christos 	switch (drefid) {
   2538  1.15  christos 	    case REFID_HASH:
   2539  1.15  christos 	    	return "hash";
   2540  1.15  christos 	    case REFID_IPV4:
   2541  1.15  christos 	    	return "ipv4";
   2542  1.15  christos 	    default:
   2543  1.15  christos 	    	return "Unknown";
   2544  1.15  christos 	}
   2545  1.15  christos }
   2546  1.15  christos 
   2547  1.15  christos 
   2548  1.15  christos /*
   2549  1.15  christos  * drefid - display/change "display hash"
   2550  1.15  christos  */
   2551  1.15  christos static void
   2552  1.15  christos showdrefid(
   2553  1.15  christos 	struct parse *pcmd,
   2554  1.15  christos 	FILE *fp
   2555  1.15  christos 	)
   2556  1.15  christos {
   2557  1.15  christos 	if (pcmd->nargs == 0) {
   2558  1.15  christos 		(void) fprintf(fp, "drefid value is %s\n", showdrefid2str());
   2559  1.15  christos 		return;
   2560  1.15  christos 	} else if (STREQ(pcmd->argval[0].string, "hash")) {
   2561  1.15  christos 		drefid = REFID_HASH;
   2562  1.15  christos 	} else if (STREQ(pcmd->argval[0].string, "ipv4")) {
   2563  1.15  christos 		drefid = REFID_IPV4;
   2564  1.15  christos 	} else {
   2565  1.15  christos 		(void) fprintf(fp, "What?\n");
   2566  1.15  christos 		return;
   2567  1.15  christos 	}
   2568  1.15  christos 	(void) fprintf(fp, "drefid value set to %s\n", showdrefid2str());
   2569  1.15  christos }
   2570  1.15  christos 
   2571  1.15  christos 
   2572  1.15  christos /*
   2573   1.1    kardel  * keyid - get a keyid to use for authenticating requests
   2574   1.1    kardel  */
   2575   1.1    kardel static void
   2576   1.1    kardel keyid(
   2577   1.1    kardel 	struct parse *pcmd,
   2578   1.1    kardel 	FILE *fp
   2579   1.1    kardel 	)
   2580   1.1    kardel {
   2581   1.1    kardel 	if (pcmd->nargs == 0) {
   2582   1.1    kardel 		if (info_auth_keyid == 0)
   2583   1.1    kardel 		    (void) fprintf(fp, "no keyid defined\n");
   2584   1.1    kardel 		else
   2585   1.1    kardel 		    (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
   2586   1.1    kardel 	} else {
   2587   1.1    kardel 		/* allow zero so that keyid can be cleared. */
   2588   1.1    kardel 		if(pcmd->argval[0].uval > NTP_MAXKEY)
   2589   1.1    kardel 		    (void) fprintf(fp, "Invalid key identifier\n");
   2590   1.1    kardel 		info_auth_keyid = pcmd->argval[0].uval;
   2591   1.1    kardel 	}
   2592   1.1    kardel }
   2593   1.1    kardel 
   2594   1.1    kardel /*
   2595   1.1    kardel  * keytype - get type of key to use for authenticating requests
   2596   1.1    kardel  */
   2597   1.1    kardel static void
   2598   1.1    kardel keytype(
   2599   1.1    kardel 	struct parse *pcmd,
   2600   1.1    kardel 	FILE *fp
   2601   1.1    kardel 	)
   2602   1.1    kardel {
   2603   1.1    kardel 	const char *	digest_name;
   2604   1.1    kardel 	size_t		digest_len;
   2605   1.1    kardel 	int		key_type;
   2606   1.1    kardel 
   2607   1.1    kardel 	if (!pcmd->nargs) {
   2608   1.6    kardel 		fprintf(fp, "keytype is %s with %lu octet digests\n",
   2609   1.1    kardel 			keytype_name(info_auth_keytype),
   2610   1.4    kardel 			(u_long)info_auth_hashlen);
   2611   1.1    kardel 		return;
   2612   1.1    kardel 	}
   2613   1.1    kardel 
   2614   1.1    kardel 	digest_name = pcmd->argval[0].string;
   2615   1.1    kardel 	digest_len = 0;
   2616   1.1    kardel 	key_type = keytype_from_text(digest_name, &digest_len);
   2617   1.1    kardel 
   2618   1.1    kardel 	if (!key_type) {
   2619  1.12  christos 		fprintf(fp, "keytype is not valid. "
   2620   1.1    kardel #ifdef OPENSSL
   2621  1.12  christos 			"Type \"help keytype\" for the available digest types.\n");
   2622   1.1    kardel #else
   2623  1.12  christos 			"Only \"md5\" is available.\n");
   2624   1.1    kardel #endif
   2625   1.1    kardel 		return;
   2626   1.1    kardel 	}
   2627   1.1    kardel 
   2628   1.1    kardel 	info_auth_keytype = key_type;
   2629   1.1    kardel 	info_auth_hashlen = digest_len;
   2630   1.1    kardel }
   2631   1.1    kardel 
   2632   1.1    kardel 
   2633   1.1    kardel /*
   2634   1.1    kardel  * passwd - get an authentication key
   2635   1.1    kardel  */
   2636   1.1    kardel /*ARGSUSED*/
   2637   1.1    kardel static void
   2638   1.1    kardel passwd(
   2639   1.1    kardel 	struct parse *pcmd,
   2640   1.1    kardel 	FILE *fp
   2641   1.1    kardel 	)
   2642   1.1    kardel {
   2643   1.9  christos 	const char *pass;
   2644   1.1    kardel 
   2645   1.1    kardel 	if (info_auth_keyid == 0) {
   2646   1.9  christos 		info_auth_keyid = getkeyid("Keyid: ");
   2647   1.9  christos 		if (info_auth_keyid == 0) {
   2648   1.9  christos 			(void)fprintf(fp, "Keyid must be defined\n");
   2649   1.1    kardel 			return;
   2650   1.1    kardel 		}
   2651   1.1    kardel 	}
   2652   1.4    kardel 	if (pcmd->nargs >= 1)
   2653   1.4    kardel 		pass = pcmd->argval[0].string;
   2654   1.1    kardel 	else {
   2655   1.4    kardel 		pass = getpass_keytype(info_auth_keytype);
   2656   1.4    kardel 		if ('\0' == pass[0]) {
   2657   1.4    kardel 			fprintf(fp, "Password unchanged\n");
   2658   1.4    kardel 			return;
   2659   1.4    kardel 		}
   2660   1.1    kardel 	}
   2661   1.9  christos 	authusekey(info_auth_keyid, info_auth_keytype,
   2662   1.9  christos 		   (const u_char *)pass);
   2663   1.4    kardel 	authtrust(info_auth_keyid, 1);
   2664   1.1    kardel }
   2665   1.1    kardel 
   2666   1.1    kardel 
   2667   1.1    kardel /*
   2668   1.1    kardel  * hostnames - set the showhostnames flag
   2669   1.1    kardel  */
   2670   1.1    kardel static void
   2671   1.1    kardel hostnames(
   2672   1.1    kardel 	struct parse *pcmd,
   2673   1.1    kardel 	FILE *fp
   2674   1.1    kardel 	)
   2675   1.1    kardel {
   2676   1.1    kardel 	if (pcmd->nargs == 0) {
   2677   1.1    kardel 		if (showhostnames)
   2678   1.1    kardel 		    (void) fprintf(fp, "hostnames being shown\n");
   2679   1.1    kardel 		else
   2680   1.1    kardel 		    (void) fprintf(fp, "hostnames not being shown\n");
   2681   1.1    kardel 	} else {
   2682   1.1    kardel 		if (STREQ(pcmd->argval[0].string, "yes"))
   2683   1.1    kardel 		    showhostnames = 1;
   2684   1.1    kardel 		else if (STREQ(pcmd->argval[0].string, "no"))
   2685   1.1    kardel 		    showhostnames = 0;
   2686   1.1    kardel 		else
   2687   1.1    kardel 		    (void)fprintf(stderr, "What?\n");
   2688   1.1    kardel 	}
   2689   1.1    kardel }
   2690   1.1    kardel 
   2691   1.1    kardel 
   2692   1.1    kardel 
   2693   1.1    kardel /*
   2694   1.1    kardel  * setdebug - set/change debugging level
   2695   1.1    kardel  */
   2696   1.1    kardel static void
   2697   1.1    kardel setdebug(
   2698   1.1    kardel 	struct parse *pcmd,
   2699   1.1    kardel 	FILE *fp
   2700   1.1    kardel 	)
   2701   1.1    kardel {
   2702   1.1    kardel 	if (pcmd->nargs == 0) {
   2703   1.1    kardel 		(void) fprintf(fp, "debug level is %d\n", debug);
   2704   1.1    kardel 		return;
   2705   1.1    kardel 	} else if (STREQ(pcmd->argval[0].string, "no")) {
   2706   1.1    kardel 		debug = 0;
   2707   1.1    kardel 	} else if (STREQ(pcmd->argval[0].string, "more")) {
   2708   1.1    kardel 		debug++;
   2709   1.1    kardel 	} else if (STREQ(pcmd->argval[0].string, "less")) {
   2710   1.1    kardel 		debug--;
   2711   1.1    kardel 	} else {
   2712   1.1    kardel 		(void) fprintf(fp, "What?\n");
   2713   1.1    kardel 		return;
   2714   1.1    kardel 	}
   2715   1.1    kardel 	(void) fprintf(fp, "debug level set to %d\n", debug);
   2716   1.1    kardel }
   2717   1.1    kardel 
   2718   1.1    kardel 
   2719   1.1    kardel /*
   2720   1.1    kardel  * quit - stop this nonsense
   2721   1.1    kardel  */
   2722   1.1    kardel /*ARGSUSED*/
   2723   1.1    kardel static void
   2724   1.1    kardel quit(
   2725   1.1    kardel 	struct parse *pcmd,
   2726   1.1    kardel 	FILE *fp
   2727   1.1    kardel 	)
   2728   1.1    kardel {
   2729   1.1    kardel 	if (havehost)
   2730   1.1    kardel 	    closesocket(sockfd);	/* cleanliness next to godliness */
   2731   1.1    kardel 	exit(0);
   2732   1.1    kardel }
   2733   1.1    kardel 
   2734   1.1    kardel 
   2735   1.1    kardel /*
   2736   1.1    kardel  * version - print the current version number
   2737   1.1    kardel  */
   2738   1.1    kardel /*ARGSUSED*/
   2739   1.1    kardel static void
   2740   1.1    kardel version(
   2741   1.1    kardel 	struct parse *pcmd,
   2742   1.1    kardel 	FILE *fp
   2743   1.1    kardel 	)
   2744   1.1    kardel {
   2745   1.1    kardel 
   2746   1.1    kardel 	(void) fprintf(fp, "%s\n", Version);
   2747   1.1    kardel 	return;
   2748   1.1    kardel }
   2749   1.1    kardel 
   2750   1.1    kardel 
   2751   1.1    kardel /*
   2752   1.1    kardel  * raw - set raw mode output
   2753   1.1    kardel  */
   2754   1.1    kardel /*ARGSUSED*/
   2755   1.1    kardel static void
   2756   1.1    kardel raw(
   2757   1.1    kardel 	struct parse *pcmd,
   2758   1.1    kardel 	FILE *fp
   2759   1.1    kardel 	)
   2760   1.1    kardel {
   2761   1.1    kardel 	rawmode = 1;
   2762   1.1    kardel 	(void) fprintf(fp, "Output set to raw\n");
   2763   1.1    kardel }
   2764   1.1    kardel 
   2765   1.1    kardel 
   2766   1.1    kardel /*
   2767   1.1    kardel  * cooked - set cooked mode output
   2768   1.1    kardel  */
   2769   1.1    kardel /*ARGSUSED*/
   2770   1.1    kardel static void
   2771   1.1    kardel cooked(
   2772   1.1    kardel 	struct parse *pcmd,
   2773   1.1    kardel 	FILE *fp
   2774   1.1    kardel 	)
   2775   1.1    kardel {
   2776   1.1    kardel 	rawmode = 0;
   2777   1.1    kardel 	(void) fprintf(fp, "Output set to cooked\n");
   2778   1.1    kardel 	return;
   2779   1.1    kardel }
   2780   1.1    kardel 
   2781   1.1    kardel 
   2782   1.1    kardel /*
   2783   1.1    kardel  * authenticate - always authenticate requests to this host
   2784   1.1    kardel  */
   2785   1.1    kardel static void
   2786   1.1    kardel authenticate(
   2787   1.1    kardel 	struct parse *pcmd,
   2788   1.1    kardel 	FILE *fp
   2789   1.1    kardel 	)
   2790   1.1    kardel {
   2791   1.1    kardel 	if (pcmd->nargs == 0) {
   2792   1.1    kardel 		if (always_auth) {
   2793   1.1    kardel 			(void) fprintf(fp,
   2794   1.1    kardel 				       "authenticated requests being sent\n");
   2795   1.1    kardel 		} else
   2796   1.1    kardel 		    (void) fprintf(fp,
   2797   1.1    kardel 				   "unauthenticated requests being sent\n");
   2798   1.1    kardel 	} else {
   2799   1.1    kardel 		if (STREQ(pcmd->argval[0].string, "yes")) {
   2800   1.1    kardel 			always_auth = 1;
   2801   1.1    kardel 		} else if (STREQ(pcmd->argval[0].string, "no")) {
   2802   1.1    kardel 			always_auth = 0;
   2803   1.1    kardel 		} else
   2804   1.1    kardel 		    (void)fprintf(stderr, "What?\n");
   2805   1.1    kardel 	}
   2806   1.1    kardel }
   2807   1.1    kardel 
   2808   1.1    kardel 
   2809   1.1    kardel /*
   2810   1.1    kardel  * ntpversion - choose the NTP version to use
   2811   1.1    kardel  */
   2812   1.1    kardel static void
   2813   1.1    kardel ntpversion(
   2814   1.1    kardel 	struct parse *pcmd,
   2815   1.1    kardel 	FILE *fp
   2816   1.1    kardel 	)
   2817   1.1    kardel {
   2818   1.1    kardel 	if (pcmd->nargs == 0) {
   2819   1.1    kardel 		(void) fprintf(fp,
   2820   1.1    kardel 			       "NTP version being claimed is %d\n", pktversion);
   2821   1.1    kardel 	} else {
   2822   1.1    kardel 		if (pcmd->argval[0].uval < NTP_OLDVERSION
   2823   1.1    kardel 		    || pcmd->argval[0].uval > NTP_VERSION) {
   2824   1.1    kardel 			(void) fprintf(stderr, "versions %d to %d, please\n",
   2825   1.1    kardel 				       NTP_OLDVERSION, NTP_VERSION);
   2826   1.1    kardel 		} else {
   2827   1.1    kardel 			pktversion = (u_char) pcmd->argval[0].uval;
   2828   1.1    kardel 		}
   2829   1.1    kardel 	}
   2830   1.1    kardel }
   2831   1.1    kardel 
   2832   1.1    kardel 
   2833   1.3  christos static void __attribute__((__format__(__printf__, 1, 0)))
   2834   1.3  christos vwarning(const char *fmt, va_list ap)
   2835   1.3  christos {
   2836   1.3  christos 	int serrno = errno;
   2837   1.3  christos 	(void) fprintf(stderr, "%s: ", progname);
   2838   1.3  christos 	vfprintf(stderr, fmt, ap);
   2839  1.14  christos 	(void) fprintf(stderr, ": %s\n", strerror(serrno));
   2840   1.3  christos }
   2841   1.3  christos 
   2842   1.1    kardel /*
   2843   1.1    kardel  * warning - print a warning message
   2844   1.1    kardel  */
   2845   1.3  christos static void __attribute__((__format__(__printf__, 1, 2)))
   2846   1.1    kardel warning(
   2847   1.1    kardel 	const char *fmt,
   2848   1.3  christos 	...
   2849   1.1    kardel 	)
   2850   1.1    kardel {
   2851   1.3  christos 	va_list ap;
   2852   1.3  christos 	va_start(ap, fmt);
   2853   1.3  christos 	vwarning(fmt, ap);
   2854   1.3  christos 	va_end(ap);
   2855   1.1    kardel }
   2856   1.1    kardel 
   2857   1.1    kardel 
   2858   1.1    kardel /*
   2859   1.1    kardel  * error - print a message and exit
   2860   1.1    kardel  */
   2861   1.3  christos static void __attribute__((__format__(__printf__, 1, 2)))
   2862   1.1    kardel error(
   2863   1.1    kardel 	const char *fmt,
   2864   1.3  christos 	...
   2865   1.1    kardel 	)
   2866   1.1    kardel {
   2867   1.3  christos 	va_list ap;
   2868   1.3  christos 	va_start(ap, fmt);
   2869   1.3  christos 	vwarning(fmt, ap);
   2870   1.3  christos 	va_end(ap);
   2871   1.1    kardel 	exit(1);
   2872   1.1    kardel }
   2873   1.1    kardel /*
   2874   1.1    kardel  * getkeyid - prompt the user for a keyid to use
   2875   1.1    kardel  */
   2876   1.1    kardel static u_long
   2877   1.1    kardel getkeyid(
   2878   1.1    kardel 	const char *keyprompt
   2879   1.1    kardel 	)
   2880   1.1    kardel {
   2881   1.4    kardel 	int c;
   2882   1.1    kardel 	FILE *fi;
   2883   1.1    kardel 	char pbuf[20];
   2884   1.4    kardel 	size_t i;
   2885   1.4    kardel 	size_t ilim;
   2886   1.1    kardel 
   2887   1.1    kardel #ifndef SYS_WINNT
   2888   1.1    kardel 	if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
   2889   1.1    kardel #else
   2890   1.1    kardel 	if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
   2891   1.1    kardel #endif /* SYS_WINNT */
   2892   1.1    kardel 		fi = stdin;
   2893   1.4    kardel 	else
   2894   1.1    kardel 		setbuf(fi, (char *)NULL);
   2895   1.1    kardel 	fprintf(stderr, "%s", keyprompt); fflush(stderr);
   2896   1.4    kardel 	for (i = 0, ilim = COUNTOF(pbuf) - 1;
   2897   1.4    kardel 	     i < ilim && (c = getc(fi)) != '\n' && c != EOF;
   2898   1.4    kardel 	     )
   2899   1.4    kardel 		pbuf[i++] = (char)c;
   2900   1.4    kardel 	pbuf[i] = '\0';
   2901   1.1    kardel 	if (fi != stdin)
   2902   1.4    kardel 		fclose(fi);
   2903   1.1    kardel 
   2904   1.1    kardel 	return (u_long) atoi(pbuf);
   2905   1.1    kardel }
   2906   1.1    kardel 
   2907   1.1    kardel 
   2908   1.1    kardel /*
   2909   1.1    kardel  * atoascii - printable-ize possibly ascii data using the character
   2910   1.1    kardel  *	      transformations cat -v uses.
   2911   1.1    kardel  */
   2912   1.1    kardel static void
   2913   1.1    kardel atoascii(
   2914   1.1    kardel 	const char *in,
   2915   1.1    kardel 	size_t in_octets,
   2916   1.1    kardel 	char *out,
   2917   1.1    kardel 	size_t out_octets
   2918   1.1    kardel 	)
   2919   1.1    kardel {
   2920   1.9  christos 	const u_char *	pchIn;
   2921   1.9  christos 	const u_char *	pchInLimit;
   2922   1.9  christos 	u_char *	pchOut;
   2923   1.9  christos 	u_char		c;
   2924   1.1    kardel 
   2925   1.1    kardel 	pchIn = (const u_char *)in;
   2926   1.1    kardel 	pchInLimit = pchIn + in_octets;
   2927   1.1    kardel 	pchOut = (u_char *)out;
   2928   1.1    kardel 
   2929   1.1    kardel 	if (NULL == pchIn) {
   2930   1.1    kardel 		if (0 < out_octets)
   2931   1.1    kardel 			*pchOut = '\0';
   2932   1.1    kardel 		return;
   2933   1.1    kardel 	}
   2934   1.1    kardel 
   2935   1.1    kardel #define	ONEOUT(c)					\
   2936   1.1    kardel do {							\
   2937   1.1    kardel 	if (0 == --out_octets) {			\
   2938   1.1    kardel 		*pchOut = '\0';				\
   2939   1.1    kardel 		return;					\
   2940   1.1    kardel 	}						\
   2941   1.1    kardel 	*pchOut++ = (c);				\
   2942   1.1    kardel } while (0)
   2943   1.1    kardel 
   2944   1.1    kardel 	for (	; pchIn < pchInLimit; pchIn++) {
   2945   1.1    kardel 		c = *pchIn;
   2946   1.1    kardel 		if ('\0' == c)
   2947   1.1    kardel 			break;
   2948   1.1    kardel 		if (c & 0x80) {
   2949   1.1    kardel 			ONEOUT('M');
   2950   1.1    kardel 			ONEOUT('-');
   2951   1.1    kardel 			c &= 0x7f;
   2952   1.1    kardel 		}
   2953   1.1    kardel 		if (c < ' ') {
   2954   1.1    kardel 			ONEOUT('^');
   2955   1.1    kardel 			ONEOUT((u_char)(c + '@'));
   2956   1.1    kardel 		} else if (0x7f == c) {
   2957   1.1    kardel 			ONEOUT('^');
   2958   1.1    kardel 			ONEOUT('?');
   2959   1.1    kardel 		} else
   2960   1.1    kardel 			ONEOUT(c);
   2961   1.1    kardel 	}
   2962   1.1    kardel 	ONEOUT('\0');
   2963   1.1    kardel 
   2964   1.1    kardel #undef ONEOUT
   2965   1.1    kardel }
   2966   1.1    kardel 
   2967   1.1    kardel 
   2968   1.1    kardel /*
   2969   1.1    kardel  * makeascii - print possibly ascii data using the character
   2970   1.1    kardel  *	       transformations that cat -v uses.
   2971   1.1    kardel  */
   2972   1.4    kardel void
   2973   1.1    kardel makeascii(
   2974  1.14  christos 	size_t length,
   2975   1.4    kardel 	const char *data,
   2976   1.1    kardel 	FILE *fp
   2977   1.1    kardel 	)
   2978   1.1    kardel {
   2979   1.4    kardel 	const u_char *data_u_char;
   2980   1.4    kardel 	const u_char *cp;
   2981   1.4    kardel 	int c;
   2982   1.4    kardel 
   2983   1.4    kardel 	data_u_char = (const u_char *)data;
   2984   1.1    kardel 
   2985   1.4    kardel 	for (cp = data_u_char; cp < data_u_char + length; cp++) {
   2986   1.1    kardel 		c = (int)*cp;
   2987   1.1    kardel 		if (c & 0x80) {
   2988   1.1    kardel 			putc('M', fp);
   2989   1.1    kardel 			putc('-', fp);
   2990   1.1    kardel 			c &= 0x7f;
   2991   1.1    kardel 		}
   2992   1.1    kardel 
   2993   1.1    kardel 		if (c < ' ') {
   2994   1.1    kardel 			putc('^', fp);
   2995   1.1    kardel 			putc(c + '@', fp);
   2996   1.1    kardel 		} else if (0x7f == c) {
   2997   1.1    kardel 			putc('^', fp);
   2998   1.1    kardel 			putc('?', fp);
   2999   1.1    kardel 		} else
   3000   1.1    kardel 			putc(c, fp);
   3001   1.1    kardel 	}
   3002   1.1    kardel }
   3003   1.1    kardel 
   3004   1.1    kardel 
   3005   1.1    kardel /*
   3006   1.1    kardel  * asciize - same thing as makeascii except add a newline
   3007   1.1    kardel  */
   3008   1.1    kardel void
   3009   1.1    kardel asciize(
   3010   1.1    kardel 	int length,
   3011   1.1    kardel 	char *data,
   3012   1.1    kardel 	FILE *fp
   3013   1.1    kardel 	)
   3014   1.1    kardel {
   3015   1.1    kardel 	makeascii(length, data, fp);
   3016   1.1    kardel 	putc('\n', fp);
   3017   1.1    kardel }
   3018   1.1    kardel 
   3019   1.1    kardel 
   3020   1.1    kardel /*
   3021   1.4    kardel  * truncate string to fit clipping excess at end.
   3022   1.4    kardel  *	"too long"	->	"too l"
   3023   1.4    kardel  * Used for hostnames.
   3024   1.4    kardel  */
   3025   1.4    kardel const char *
   3026   1.4    kardel trunc_right(
   3027   1.4    kardel 	const char *	src,
   3028   1.4    kardel 	size_t		width
   3029   1.4    kardel 	)
   3030   1.4    kardel {
   3031   1.4    kardel 	size_t	sl;
   3032   1.4    kardel 	char *	out;
   3033   1.4    kardel 
   3034   1.9  christos 
   3035   1.4    kardel 	sl = strlen(src);
   3036   1.4    kardel 	if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
   3037   1.4    kardel 		LIB_GETBUF(out);
   3038   1.4    kardel 		memcpy(out, src, width);
   3039   1.4    kardel 		out[width] = '\0';
   3040   1.4    kardel 
   3041   1.4    kardel 		return out;
   3042   1.4    kardel 	}
   3043   1.4    kardel 
   3044   1.4    kardel 	return src;
   3045   1.4    kardel }
   3046   1.4    kardel 
   3047   1.4    kardel 
   3048   1.4    kardel /*
   3049   1.4    kardel  * truncate string to fit by preserving right side and using '_' to hint
   3050   1.4    kardel  *	"too long"	->	"_long"
   3051   1.4    kardel  * Used for local IPv6 addresses, where low bits differentiate.
   3052   1.4    kardel  */
   3053   1.4    kardel const char *
   3054   1.4    kardel trunc_left(
   3055   1.4    kardel 	const char *	src,
   3056   1.4    kardel 	size_t		width
   3057   1.4    kardel 	)
   3058   1.4    kardel {
   3059   1.4    kardel 	size_t	sl;
   3060   1.4    kardel 	char *	out;
   3061   1.4    kardel 
   3062   1.4    kardel 
   3063   1.4    kardel 	sl = strlen(src);
   3064   1.4    kardel 	if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
   3065   1.4    kardel 		LIB_GETBUF(out);
   3066   1.4    kardel 		out[0] = '_';
   3067   1.4    kardel 		memcpy(&out[1], &src[sl + 1 - width], width);
   3068   1.4    kardel 
   3069   1.4    kardel 		return out;
   3070   1.4    kardel 	}
   3071   1.4    kardel 
   3072   1.4    kardel 	return src;
   3073   1.4    kardel }
   3074   1.4    kardel 
   3075   1.4    kardel 
   3076   1.4    kardel /*
   3077   1.1    kardel  * Some circular buffer space
   3078   1.1    kardel  */
   3079   1.1    kardel #define	CBLEN	80
   3080   1.1    kardel #define	NUMCB	6
   3081   1.1    kardel 
   3082   1.1    kardel char circ_buf[NUMCB][CBLEN];
   3083   1.1    kardel int nextcb = 0;
   3084   1.1    kardel 
   3085  1.20  christos /* --------------------------------------------------------------------
   3086  1.20  christos  * Parsing a response value list
   3087  1.20  christos  *
   3088  1.20  christos  * This sounds simple (and it actually is not really hard) but it has
   3089  1.20  christos  * some pitfalls.
   3090  1.20  christos  *
   3091  1.20  christos  * Rule1: CR/LF is never embedded in an item
   3092  1.20  christos  * Rule2: An item is a name, optionally followed by a value
   3093  1.20  christos  * Rule3: The value is separated from the name by a '='
   3094  1.20  christos  * Rule4: Items are separated by a ','
   3095  1.20  christos  * Rule5: values can be quoted by '"', in which case they can contain
   3096  1.20  christos  *        arbitrary characters but *not* '"', CR and LF
   3097  1.20  christos  *
   3098  1.20  christos  * There are a few implementations out there that require a somewhat
   3099  1.20  christos  * relaxed attitude when parsing a value list, especially since we want
   3100  1.20  christos  * to copy names and values into local buffers. If these would overflow,
   3101  1.20  christos  * the item should be skipped without terminating the parsing sequence.
   3102  1.20  christos  *
   3103  1.20  christos  * Also, for empty values, there might be a '=' after the name or not;
   3104  1.20  christos  * we treat that equivalent.
   3105  1.20  christos  *
   3106  1.20  christos  * Parsing an item definitely breaks on a CR/LF. If an item is not
   3107  1.20  christos  * followed by a comma (','), parsing stops. In the middle of a quoted
   3108  1.20  christos  * character sequence CR/LF terminates the parsing finally without
   3109  1.20  christos  * returning a value.
   3110  1.20  christos  *
   3111  1.20  christos  * White space and other noise is ignored when parsing the data buffer;
   3112  1.20  christos  * only CR, LF, ',', '=' and '"' are characters with a special meaning.
   3113  1.20  christos  * White space is stripped from the names and values *after* working
   3114  1.20  christos  * through the buffer, before making the local copies. If whitespace
   3115  1.20  christos  * stripping results in an empty name, parsing resumes.
   3116  1.20  christos  */
   3117  1.20  christos 
   3118  1.20  christos /*
   3119  1.20  christos  * nextvar parsing helpers
   3120  1.20  christos  */
   3121  1.20  christos 
   3122  1.20  christos /* predicate: allowed chars inside a quoted string */
   3123  1.20  christos static int/*BOOL*/ cp_qschar(int ch)
   3124  1.20  christos {
   3125  1.20  christos 	return ch && (ch != '"' && ch != '\r' && ch != '\n');
   3126  1.20  christos }
   3127  1.20  christos 
   3128  1.20  christos /* predicate: allowed chars inside an unquoted string */
   3129  1.20  christos static int/*BOOL*/ cp_uqchar(int ch)
   3130  1.20  christos {
   3131  1.20  christos 	return ch && (ch != ',' && ch != '"' && ch != '\r' && ch != '\n');
   3132  1.20  christos }
   3133  1.20  christos 
   3134  1.20  christos /* predicate: allowed chars inside a value name */
   3135  1.20  christos static int/*BOOL*/ cp_namechar(int ch)
   3136  1.20  christos {
   3137  1.20  christos 	return ch && (ch != ',' && ch != '=' && ch != '\r' && ch != '\n');
   3138  1.20  christos }
   3139  1.20  christos 
   3140  1.20  christos /* predicate: characters *between* list items. We're relaxed here. */
   3141  1.20  christos static int/*BOOL*/ cp_ivspace(int ch)
   3142  1.20  christos {
   3143  1.20  christos 	return (ch == ',' || (ch > 0 && ch <= ' '));
   3144  1.20  christos }
   3145  1.20  christos 
   3146  1.20  christos /* get current character (or NUL when on end) */
   3147  1.20  christos static inline int
   3148  1.20  christos pf_getch(
   3149  1.20  christos 	const char **	datap,
   3150  1.20  christos 	const char *	endp
   3151  1.20  christos 	)
   3152  1.20  christos {
   3153  1.20  christos 	return (*datap != endp)
   3154  1.20  christos 	    ? *(const unsigned char*)*datap
   3155  1.20  christos 	    : '\0';
   3156  1.20  christos }
   3157  1.20  christos 
   3158  1.20  christos /* get next character (or NUL when on end) */
   3159  1.20  christos static inline int
   3160  1.20  christos pf_nextch(
   3161  1.20  christos 	const char **	datap,
   3162  1.20  christos 	const char *	endp
   3163  1.20  christos 	)
   3164  1.20  christos {
   3165  1.20  christos 	return (*datap != endp && ++(*datap) != endp)
   3166  1.20  christos 	    ? *(const unsigned char*)*datap
   3167  1.20  christos 	    : '\0';
   3168  1.20  christos }
   3169  1.20  christos 
   3170  1.20  christos static size_t
   3171  1.20  christos str_strip(
   3172  1.20  christos 	const char ** 	datap,
   3173  1.20  christos 	size_t		len
   3174  1.20  christos 	)
   3175  1.20  christos {
   3176  1.20  christos 	static const char empty[] = "";
   3177  1.20  christos 
   3178  1.20  christos 	if (*datap && len) {
   3179  1.20  christos 		const char * cpl = *datap;
   3180  1.20  christos 		const char * cpr = cpl + len;
   3181  1.20  christos 
   3182  1.20  christos 		while (cpl != cpr && *(const unsigned char*)cpl <= ' ')
   3183  1.20  christos 			++cpl;
   3184  1.20  christos 		while (cpl != cpr && *(const unsigned char*)(cpr - 1) <= ' ')
   3185  1.20  christos 			--cpr;
   3186  1.20  christos 		*datap = cpl;
   3187  1.20  christos 		len = (size_t)(cpr - cpl);
   3188  1.20  christos 	} else {
   3189  1.20  christos 		*datap = empty;
   3190  1.20  christos 		len = 0;
   3191  1.20  christos 	}
   3192  1.20  christos 	return len;
   3193  1.20  christos }
   3194  1.20  christos 
   3195  1.20  christos static void
   3196  1.20  christos pf_error(
   3197  1.20  christos 	const char *	what,
   3198  1.20  christos 	const char *	where,
   3199  1.20  christos 	const char *	whend
   3200  1.20  christos 	)
   3201  1.20  christos {
   3202  1.20  christos #   ifndef BUILD_AS_LIB
   3203  1.20  christos 
   3204  1.20  christos 	FILE *	ofp = (debug > 0) ? stdout : stderr;
   3205  1.20  christos 	size_t	len = (size_t)(whend - where);
   3206  1.20  christos 
   3207  1.20  christos 	if (len > 50) /* *must* fit into an 'int'! */
   3208  1.20  christos 		len = 50;
   3209  1.20  christos 	fprintf(ofp, "nextvar: %s: '%.*s'\n",
   3210  1.20  christos 		what, (int)len, where);
   3211  1.20  christos 
   3212  1.20  christos #   else  /*defined(BUILD_AS_LIB)*/
   3213  1.20  christos 
   3214  1.20  christos 	UNUSED_ARG(what);
   3215  1.20  christos 	UNUSED_ARG(where);
   3216  1.20  christos 	UNUSED_ARG(whend);
   3217  1.20  christos 
   3218  1.20  christos #   endif /*defined(BUILD_AS_LIB)*/
   3219  1.20  christos }
   3220  1.20  christos 
   3221   1.1    kardel /*
   3222   1.1    kardel  * nextvar - find the next variable in the buffer
   3223   1.1    kardel  */
   3224  1.20  christos int/*BOOL*/
   3225   1.1    kardel nextvar(
   3226  1.14  christos 	size_t *datalen,
   3227   1.4    kardel 	const char **datap,
   3228   1.1    kardel 	char **vname,
   3229   1.1    kardel 	char **vvalue
   3230   1.1    kardel 	)
   3231   1.1    kardel {
   3232  1.20  christos 	enum PState 	{ sDone, sInit, sName, sValU, sValQ };
   3233  1.20  christos 
   3234  1.20  christos 	static char	name[MAXVARLEN], value[MAXVALLEN];
   3235   1.1    kardel 
   3236  1.20  christos 	const char	*cp, *cpend;
   3237  1.20  christos 	const char	*np, *vp;
   3238  1.20  christos 	size_t		nlen, vlen;
   3239  1.20  christos 	int		ch;
   3240  1.20  christos 	enum PState	st;
   3241  1.20  christos 
   3242  1.20  christos 	cpend = *datap + *datalen;
   3243   1.1    kardel 
   3244  1.20  christos   again:
   3245  1.20  christos 	np   = vp   = NULL;
   3246  1.20  christos 	nlen = vlen = 0;
   3247  1.20  christos 
   3248  1.20  christos 	st = sInit;
   3249  1.20  christos 	ch = pf_getch(datap, cpend);
   3250   1.9  christos 
   3251  1.20  christos 	while (st != sDone) {
   3252  1.20  christos 		switch (st)
   3253  1.20  christos 		{
   3254  1.20  christos 		case sInit:	/* handle inter-item chars */
   3255  1.20  christos 			while (cp_ivspace(ch))
   3256  1.20  christos 				ch = pf_nextch(datap, cpend);
   3257  1.20  christos 			if (cp_namechar(ch)) {
   3258  1.20  christos 				np = *datap;
   3259  1.20  christos 				cp = np;
   3260  1.20  christos 				st = sName;
   3261  1.20  christos 				ch = pf_nextch(datap, cpend);
   3262  1.20  christos 			} else {
   3263  1.20  christos 				goto final_done;
   3264  1.20  christos 			}
   3265  1.20  christos 			break;
   3266  1.20  christos 
   3267  1.20  christos 		case sName:	/* collect name */
   3268  1.20  christos 			while (cp_namechar(ch))
   3269  1.20  christos 				ch = pf_nextch(datap, cpend);
   3270  1.20  christos 			nlen = (size_t)(*datap - np);
   3271  1.20  christos 			if (ch == '=') {
   3272  1.20  christos 				ch = pf_nextch(datap, cpend);
   3273  1.20  christos 				vp = *datap;
   3274  1.20  christos 				st = sValU;
   3275  1.20  christos 			} else {
   3276  1.20  christos 				if (ch != ',')
   3277  1.20  christos 					*datap = cpend;
   3278  1.20  christos 				st = sDone;
   3279  1.20  christos 			}
   3280  1.20  christos 			break;
   3281  1.20  christos 
   3282  1.20  christos 		case sValU:	/* collect unquoted part(s) of value */
   3283  1.20  christos 			while (cp_uqchar(ch))
   3284  1.20  christos 				ch = pf_nextch(datap, cpend);
   3285  1.20  christos 			if (ch == '"') {
   3286  1.20  christos 				ch = pf_nextch(datap, cpend);
   3287  1.20  christos 				st = sValQ;
   3288  1.20  christos 			} else {
   3289  1.20  christos 				vlen = (size_t)(*datap - vp);
   3290  1.20  christos 				if (ch != ',')
   3291  1.20  christos 					*datap = cpend;
   3292  1.20  christos 				st = sDone;
   3293  1.20  christos 			}
   3294  1.20  christos 			break;
   3295  1.20  christos 
   3296  1.20  christos 		case sValQ:	/* collect quoted part(s) of value */
   3297  1.20  christos 			while (cp_qschar(ch))
   3298  1.20  christos 				ch = pf_nextch(datap, cpend);
   3299  1.20  christos 			if (ch == '"') {
   3300  1.20  christos 				ch = pf_nextch(datap, cpend);
   3301  1.20  christos 				st = sValU;
   3302  1.20  christos 			} else {
   3303  1.20  christos 				pf_error("no closing quote, stop", cp, cpend);
   3304  1.20  christos 				goto final_done;
   3305  1.20  christos 			}
   3306  1.20  christos 			break;
   3307  1.20  christos 
   3308  1.20  christos 		default:
   3309  1.20  christos 			pf_error("state machine error, stop", *datap, cpend);
   3310  1.20  christos 			goto final_done;
   3311  1.20  christos 		}
   3312  1.20  christos 	}
   3313   1.1    kardel 
   3314  1.20  christos 	/* If name or value do not fit their buffer, croak and start
   3315  1.20  christos 	 * over. If there's no name at all after whitespace stripping,
   3316  1.20  christos 	 * redo silently.
   3317   1.1    kardel 	 */
   3318  1.20  christos 	nlen = str_strip(&np, nlen);
   3319  1.20  christos 	vlen = str_strip(&vp, vlen);
   3320  1.20  christos 
   3321  1.20  christos 	if (nlen == 0) {
   3322  1.20  christos 		goto again;
   3323  1.20  christos 	}
   3324  1.20  christos 	if (nlen >= sizeof(name)) {
   3325  1.20  christos 		pf_error("runaway name", np, cpend);
   3326  1.20  christos 		goto again;
   3327   1.1    kardel 	}
   3328  1.20  christos 	if (vlen >= sizeof(value)) {
   3329  1.20  christos 		pf_error("runaway value", vp, cpend);
   3330  1.20  christos 		goto again;
   3331   1.1    kardel 	}
   3332   1.1    kardel 
   3333  1.20  christos 	/* copy name and value into NUL-terminated buffers */
   3334  1.20  christos 	memcpy(name, np, nlen);
   3335  1.20  christos 	name[nlen] = '\0';
   3336  1.20  christos 	*vname = name;
   3337  1.20  christos 
   3338  1.20  christos 	memcpy(value, vp, vlen);
   3339  1.20  christos 	value[vlen] = '\0';
   3340   1.1    kardel 	*vvalue = value;
   3341  1.20  christos 
   3342  1.20  christos 	/* check if there's more to do or if we are finshed */
   3343  1.20  christos 	*datalen = (size_t)(cpend - *datap);
   3344  1.20  christos 	return TRUE;
   3345  1.20  christos 
   3346  1.20  christos   final_done:
   3347  1.20  christos 	*datap = cpend;
   3348  1.20  christos 	*datalen = 0;
   3349  1.20  christos 	return FALSE;
   3350   1.1    kardel }
   3351   1.1    kardel 
   3352   1.1    kardel 
   3353   1.9  christos u_short
   3354   1.9  christos varfmt(const char * varname)
   3355   1.9  christos {
   3356   1.9  christos 	u_int n;
   3357   1.9  christos 
   3358   1.9  christos 	for (n = 0; n < COUNTOF(cookedvars); n++)
   3359   1.9  christos 		if (!strcmp(varname, cookedvars[n].varname))
   3360   1.9  christos 			return cookedvars[n].fmt;
   3361   1.9  christos 
   3362   1.9  christos 	return PADDING;
   3363   1.1    kardel }
   3364   1.1    kardel 
   3365   1.1    kardel 
   3366   1.1    kardel /*
   3367   1.1    kardel  * printvars - print variables returned in response packet
   3368   1.1    kardel  */
   3369   1.1    kardel void
   3370   1.1    kardel printvars(
   3371  1.14  christos 	size_t length,
   3372   1.4    kardel 	const char *data,
   3373   1.1    kardel 	int status,
   3374   1.1    kardel 	int sttype,
   3375   1.1    kardel 	int quiet,
   3376   1.1    kardel 	FILE *fp
   3377   1.1    kardel 	)
   3378   1.1    kardel {
   3379   1.1    kardel 	if (rawmode)
   3380   1.1    kardel 	    rawprint(sttype, length, data, status, quiet, fp);
   3381   1.1    kardel 	else
   3382   1.1    kardel 	    cookedprint(sttype, length, data, status, quiet, fp);
   3383   1.1    kardel }
   3384   1.1    kardel 
   3385   1.1    kardel 
   3386   1.1    kardel /*
   3387   1.1    kardel  * rawprint - do a printout of the data in raw mode
   3388   1.1    kardel  */
   3389   1.1    kardel static void
   3390   1.1    kardel rawprint(
   3391   1.1    kardel 	int datatype,
   3392  1.14  christos 	size_t length,
   3393   1.4    kardel 	const char *data,
   3394   1.1    kardel 	int status,
   3395   1.1    kardel 	int quiet,
   3396   1.1    kardel 	FILE *fp
   3397   1.1    kardel 	)
   3398   1.1    kardel {
   3399   1.4    kardel 	const char *cp;
   3400   1.4    kardel 	const char *cpend;
   3401   1.1    kardel 
   3402   1.1    kardel 	/*
   3403   1.1    kardel 	 * Essentially print the data as is.  We reformat unprintables, though.
   3404   1.1    kardel 	 */
   3405   1.1    kardel 	cp = data;
   3406   1.1    kardel 	cpend = data + length;
   3407   1.1    kardel 
   3408   1.1    kardel 	if (!quiet)
   3409   1.1    kardel 		(void) fprintf(fp, "status=0x%04x,\n", status);
   3410   1.1    kardel 
   3411   1.1    kardel 	while (cp < cpend) {
   3412   1.1    kardel 		if (*cp == '\r') {
   3413   1.1    kardel 			/*
   3414   1.1    kardel 			 * If this is a \r and the next character is a
   3415   1.1    kardel 			 * \n, supress this, else pretty print it.  Otherwise
   3416   1.1    kardel 			 * just output the character.
   3417   1.1    kardel 			 */
   3418   1.1    kardel 			if (cp == (cpend - 1) || *(cp + 1) != '\n')
   3419   1.1    kardel 			    makeascii(1, cp, fp);
   3420  1.19  christos 		} else if (isspace(pgetc(cp)) || isprint(pgetc(cp)))
   3421   1.1    kardel 			putc(*cp, fp);
   3422   1.1    kardel 		else
   3423   1.1    kardel 			makeascii(1, cp, fp);
   3424   1.1    kardel 		cp++;
   3425   1.1    kardel 	}
   3426   1.1    kardel }
   3427   1.1    kardel 
   3428   1.1    kardel 
   3429   1.1    kardel /*
   3430   1.1    kardel  * Global data used by the cooked output routines
   3431   1.1    kardel  */
   3432   1.1    kardel int out_chars;		/* number of characters output */
   3433   1.1    kardel int out_linecount;	/* number of characters output on this line */
   3434   1.1    kardel 
   3435   1.1    kardel 
   3436   1.1    kardel /*
   3437   1.1    kardel  * startoutput - get ready to do cooked output
   3438   1.1    kardel  */
   3439   1.1    kardel static void
   3440   1.1    kardel startoutput(void)
   3441   1.1    kardel {
   3442   1.1    kardel 	out_chars = 0;
   3443   1.1    kardel 	out_linecount = 0;
   3444   1.1    kardel }
   3445   1.1    kardel 
   3446   1.1    kardel 
   3447   1.1    kardel /*
   3448   1.1    kardel  * output - output a variable=value combination
   3449   1.1    kardel  */
   3450   1.1    kardel static void
   3451   1.1    kardel output(
   3452   1.1    kardel 	FILE *fp,
   3453   1.9  christos 	const char *name,
   3454   1.4    kardel 	const char *value
   3455   1.1    kardel 	)
   3456   1.1    kardel {
   3457  1.14  christos 	int len;
   3458   1.1    kardel 
   3459   1.1    kardel 	/* strlen of "name=value" */
   3460  1.14  christos 	len = size2int_sat(strlen(name) + 1 + strlen(value));
   3461   1.1    kardel 
   3462   1.1    kardel 	if (out_chars != 0) {
   3463   1.1    kardel 		out_chars += 2;
   3464   1.1    kardel 		if ((out_linecount + len + 2) > MAXOUTLINE) {
   3465   1.1    kardel 			fputs(",\n", fp);
   3466   1.1    kardel 			out_linecount = 0;
   3467   1.1    kardel 		} else {
   3468   1.1    kardel 			fputs(", ", fp);
   3469   1.1    kardel 			out_linecount += 2;
   3470   1.1    kardel 		}
   3471   1.1    kardel 	}
   3472   1.1    kardel 
   3473   1.1    kardel 	fputs(name, fp);
   3474   1.1    kardel 	putc('=', fp);
   3475   1.1    kardel 	fputs(value, fp);
   3476   1.1    kardel 	out_chars += len;
   3477   1.1    kardel 	out_linecount += len;
   3478   1.1    kardel }
   3479   1.1    kardel 
   3480   1.1    kardel 
   3481   1.1    kardel /*
   3482   1.1    kardel  * endoutput - terminate a block of cooked output
   3483   1.1    kardel  */
   3484   1.1    kardel static void
   3485   1.1    kardel endoutput(
   3486   1.1    kardel 	FILE *fp
   3487   1.1    kardel 	)
   3488   1.1    kardel {
   3489   1.1    kardel 	if (out_chars != 0)
   3490   1.1    kardel 		putc('\n', fp);
   3491   1.1    kardel }
   3492   1.1    kardel 
   3493   1.1    kardel 
   3494   1.1    kardel /*
   3495   1.1    kardel  * outputarr - output an array of values
   3496   1.1    kardel  */
   3497   1.1    kardel static void
   3498   1.1    kardel outputarr(
   3499   1.1    kardel 	FILE *fp,
   3500   1.1    kardel 	char *name,
   3501   1.1    kardel 	int narr,
   3502  1.21  christos 	l_fp *lfp,
   3503  1.21  christos 	int issigned
   3504   1.1    kardel 	)
   3505   1.1    kardel {
   3506  1.14  christos 	char *bp;
   3507  1.14  christos 	char *cp;
   3508  1.14  christos 	size_t i;
   3509  1.14  christos 	size_t len;
   3510   1.1    kardel 	char buf[256];
   3511   1.1    kardel 
   3512   1.1    kardel 	bp = buf;
   3513   1.1    kardel 	/*
   3514   1.1    kardel 	 * Hack to align delay and offset values
   3515   1.1    kardel 	 */
   3516   1.1    kardel 	for (i = (int)strlen(name); i < 11; i++)
   3517  1.20  christos 		*bp++ = ' ';
   3518   1.9  christos 
   3519   1.1    kardel 	for (i = narr; i > 0; i--) {
   3520  1.14  christos 		if (i != (size_t)narr)
   3521  1.20  christos 			*bp++ = ' ';
   3522  1.21  christos 		cp = (issigned ? lfptoms(lfp, 2) : ulfptoms(lfp, 2));
   3523   1.1    kardel 		len = strlen(cp);
   3524   1.1    kardel 		if (len > 7) {
   3525   1.1    kardel 			cp[7] = '\0';
   3526   1.1    kardel 			len = 7;
   3527   1.1    kardel 		}
   3528   1.1    kardel 		while (len < 7) {
   3529   1.1    kardel 			*bp++ = ' ';
   3530   1.1    kardel 			len++;
   3531   1.1    kardel 		}
   3532   1.1    kardel 		while (*cp != '\0')
   3533   1.1    kardel 		    *bp++ = *cp++;
   3534   1.1    kardel 		lfp++;
   3535   1.1    kardel 	}
   3536   1.1    kardel 	*bp = '\0';
   3537   1.1    kardel 	output(fp, name, buf);
   3538   1.1    kardel }
   3539   1.1    kardel 
   3540   1.1    kardel static char *
   3541   1.1    kardel tstflags(
   3542   1.1    kardel 	u_long val
   3543   1.1    kardel 	)
   3544   1.1    kardel {
   3545  1.20  christos #	if CBLEN < 10
   3546  1.20  christos #	 error BLEN is too small -- increase!
   3547  1.20  christos #	endif
   3548  1.20  christos 
   3549  1.20  christos 	char *cp, *s;
   3550  1.20  christos 	size_t cb, i;
   3551  1.20  christos 	int l;
   3552   1.1    kardel 
   3553   1.4    kardel 	s = cp = circ_buf[nextcb];
   3554   1.1    kardel 	if (++nextcb >= NUMCB)
   3555   1.4    kardel 		nextcb = 0;
   3556   1.4    kardel 	cb = sizeof(circ_buf[0]);
   3557   1.1    kardel 
   3558  1.20  christos 	l = snprintf(cp, cb, "%02lx", val);
   3559  1.20  christos 	if (l < 0 || (size_t)l >= cb)
   3560  1.20  christos 		goto fail;
   3561  1.20  christos 	cp += l;
   3562  1.20  christos 	cb -= l;
   3563   1.1    kardel 	if (!val) {
   3564  1.20  christos 		l = strlcat(cp, " ok", cb);
   3565  1.20  christos 		if ((size_t)l >= cb)
   3566  1.20  christos 			goto fail;
   3567  1.20  christos 		cp += l;
   3568  1.20  christos 		cb -= l;
   3569   1.1    kardel 	} else {
   3570  1.20  christos 		const char *sep;
   3571  1.20  christos 
   3572  1.20  christos 		sep = " ";
   3573  1.20  christos 		for (i = 0; i < COUNTOF(tstflagnames); i++) {
   3574   1.1    kardel 			if (val & 0x1) {
   3575  1.20  christos 				l = snprintf(cp, cb, "%s%s", sep,
   3576  1.20  christos 					     tstflagnames[i]);
   3577  1.20  christos 				if (l < 0)
   3578  1.20  christos 					goto fail;
   3579  1.20  christos 				if ((size_t)l >= cb) {
   3580  1.20  christos 					cp += cb - 4;
   3581  1.20  christos 					cb = 4;
   3582  1.20  christos 					l = strlcpy (cp, "...", cb);
   3583  1.20  christos 					cp += l;
   3584  1.20  christos 					cb -= l;
   3585  1.20  christos 					break;
   3586  1.20  christos 				}
   3587   1.1    kardel 				sep = ", ";
   3588  1.20  christos 				cp += l;
   3589  1.20  christos 				cb -= l;
   3590   1.1    kardel 			}
   3591   1.1    kardel 			val >>= 1;
   3592   1.1    kardel 		}
   3593   1.1    kardel 	}
   3594   1.4    kardel 
   3595   1.1    kardel 	return s;
   3596  1.20  christos 
   3597  1.20  christos   fail:
   3598  1.20  christos 	*cp = '\0';
   3599  1.20  christos 	return s;
   3600   1.1    kardel }
   3601   1.1    kardel 
   3602   1.1    kardel /*
   3603   1.1    kardel  * cookedprint - output variables in cooked mode
   3604   1.1    kardel  */
   3605   1.1    kardel static void
   3606   1.1    kardel cookedprint(
   3607   1.1    kardel 	int datatype,
   3608  1.14  christos 	size_t length,
   3609   1.4    kardel 	const char *data,
   3610   1.1    kardel 	int status,
   3611   1.1    kardel 	int quiet,
   3612   1.1    kardel 	FILE *fp
   3613   1.1    kardel 	)
   3614   1.1    kardel {
   3615   1.1    kardel 	char *name;
   3616   1.1    kardel 	char *value;
   3617   1.1    kardel 	char output_raw;
   3618   1.1    kardel 	int fmt;
   3619   1.1    kardel 	l_fp lfp;
   3620   1.1    kardel 	sockaddr_u hval;
   3621   1.1    kardel 	u_long uval;
   3622   1.9  christos 	int narr;
   3623   1.9  christos 	size_t len;
   3624   1.1    kardel 	l_fp lfparr[8];
   3625   1.9  christos 	char b[12];
   3626   1.9  christos 	char bn[2 * MAXVARLEN];
   3627   1.9  christos 	char bv[2 * MAXVALLEN];
   3628   1.1    kardel 
   3629   1.9  christos 	UNUSED_ARG(datatype);
   3630   1.1    kardel 
   3631   1.1    kardel 	if (!quiet)
   3632   1.1    kardel 		fprintf(fp, "status=%04x %s,\n", status,
   3633   1.1    kardel 			statustoa(datatype, status));
   3634   1.1    kardel 
   3635   1.1    kardel 	startoutput();
   3636   1.1    kardel 	while (nextvar(&length, &data, &name, &value)) {
   3637   1.9  christos 		fmt = varfmt(name);
   3638   1.9  christos 		output_raw = 0;
   3639   1.9  christos 		switch (fmt) {
   3640   1.9  christos 
   3641   1.9  christos 		case PADDING:
   3642   1.1    kardel 			output_raw = '*';
   3643   1.9  christos 			break;
   3644   1.9  christos 
   3645   1.9  christos 		case TS:
   3646  1.19  christos 			if (!value || !decodets(value, &lfp))
   3647   1.9  christos 				output_raw = '?';
   3648   1.9  christos 			else
   3649   1.9  christos 				output(fp, name, prettydate(&lfp));
   3650   1.9  christos 			break;
   3651   1.9  christos 
   3652   1.9  christos 		case HA:	/* fallthru */
   3653   1.9  christos 		case NA:
   3654  1.19  christos 			if (!value || !decodenetnum(value, &hval)) {
   3655   1.9  christos 				output_raw = '?';
   3656   1.9  christos 			} else if (fmt == HA){
   3657   1.9  christos 				output(fp, name, nntohost(&hval));
   3658   1.9  christos 			} else {
   3659   1.9  christos 				output(fp, name, stoa(&hval));
   3660   1.9  christos 			}
   3661   1.9  christos 			break;
   3662   1.1    kardel 
   3663   1.9  christos 		case RF:
   3664  1.19  christos 			if (!value) {
   3665  1.19  christos 				output_raw = '?';
   3666  1.19  christos 			} else if (decodenetnum(value, &hval)) {
   3667  1.21  christos 				if (datatype == TYPE_CLOCK && IS_IPV4(&hval)) {
   3668  1.21  christos 					/*
   3669  1.21  christos 					 * Workaround to override numeric refid formats
   3670  1.21  christos 					 * for refclocks received from faulty nptd servers
   3671  1.21  christos 					 * and output them as text.
   3672  1.21  christos 					 */
   3673  1.21  christos 					int i;
   3674  1.21  christos 					unsigned char *str = (unsigned char *)&(hval.sa4).sin_addr;
   3675  1.21  christos 					char refid_buf[5];
   3676  1.21  christos 					for (i=0; i<4 && str[i]; i++)
   3677  1.21  christos 						refid_buf[i] = (isprint(str[i]) ? str[i] : '?');
   3678  1.21  christos 					refid_buf[i] = 0; /* Null terminator */
   3679  1.21  christos 					output(fp, name, refid_buf);
   3680  1.21  christos 				} else if (ISREFCLOCKADR(&hval)) {
   3681  1.21  christos 					output(fp, name, refnumtoa(&hval));
   3682  1.21  christos 				} else {
   3683  1.21  christos 					if (drefid == REFID_IPV4) {
   3684  1.21  christos 						output(fp, name, stoa(&hval));
   3685  1.21  christos 					} else {
   3686  1.21  christos 						char refid_buf[12];
   3687  1.21  christos 						snprintf (refid_buf, sizeof(refid_buf),
   3688  1.21  christos 							  "0x%08x", ntohl(addr2refid(&hval)));
   3689  1.21  christos 						output(fp, name, refid_buf);
   3690  1.21  christos 					}
   3691  1.21  christos 				}
   3692   1.9  christos 			} else if (strlen(value) <= 4) {
   3693   1.9  christos 				output(fp, name, value);
   3694   1.9  christos 			} else {
   3695   1.9  christos 				output_raw = '?';
   3696   1.9  christos 			}
   3697   1.9  christos 			break;
   3698   1.1    kardel 
   3699   1.9  christos 		case LP:
   3700  1.19  christos 			if (!value || !decodeuint(value, &uval) || uval > 3) {
   3701   1.9  christos 				output_raw = '?';
   3702   1.9  christos 			} else {
   3703   1.9  christos 				b[0] = (0x2 & uval)
   3704   1.9  christos 					   ? '1'
   3705   1.9  christos 					   : '0';
   3706   1.9  christos 				b[1] = (0x1 & uval)
   3707   1.9  christos 					   ? '1'
   3708   1.9  christos 					   : '0';
   3709   1.9  christos 				b[2] = '\0';
   3710   1.9  christos 				output(fp, name, b);
   3711   1.9  christos 			}
   3712   1.9  christos 			break;
   3713   1.1    kardel 
   3714   1.9  christos 		case OC:
   3715  1.19  christos 			if (!value || !decodeuint(value, &uval)) {
   3716   1.9  christos 				output_raw = '?';
   3717   1.9  christos 			} else {
   3718   1.9  christos 				snprintf(b, sizeof(b), "%03lo", uval);
   3719   1.9  christos 				output(fp, name, b);
   3720   1.9  christos 			}
   3721   1.9  christos 			break;
   3722   1.1    kardel 
   3723  1.21  christos 		case AU:
   3724  1.21  christos 		case AS:
   3725  1.19  christos 			if (!value || !decodearr(value, &narr, lfparr, 8))
   3726   1.9  christos 				output_raw = '?';
   3727   1.9  christos 			else
   3728  1.21  christos 				outputarr(fp, name, narr, lfparr, (fmt==AS));
   3729   1.9  christos 			break;
   3730   1.1    kardel 
   3731   1.9  christos 		case FX:
   3732  1.19  christos 			if (!value || !decodeuint(value, &uval))
   3733   1.9  christos 				output_raw = '?';
   3734   1.9  christos 			else
   3735   1.9  christos 				output(fp, name, tstflags(uval));
   3736   1.9  christos 			break;
   3737   1.1    kardel 
   3738  1.21  christos 		case SN:
   3739  1.21  christos 			if (!value)
   3740  1.21  christos 				output_raw = '?';
   3741  1.22  christos 			else if (isdigit(*(const unsigned char *)value)) {	/* number without sign */
   3742  1.21  christos 				bv[0] = '+';
   3743  1.21  christos 				atoascii (value, MAXVALLEN, bv+1, sizeof(bv)-1);
   3744  1.21  christos 				output(fp, name, bv);
   3745  1.21  christos 			} else
   3746  1.21  christos 				output_raw = '*';		/* output as-is */
   3747  1.21  christos 			break;
   3748  1.21  christos 
   3749   1.9  christos 		default:
   3750   1.9  christos 			fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
   3751   1.9  christos 				name, value, fmt);
   3752   1.9  christos 			output_raw = '?';
   3753   1.9  christos 			break;
   3754   1.1    kardel 		}
   3755   1.9  christos 
   3756   1.1    kardel 		if (output_raw != 0) {
   3757  1.13  christos 			/* TALOS-CAN-0063: avoid buffer overrun */
   3758   1.1    kardel 			atoascii(name, MAXVARLEN, bn, sizeof(bn));
   3759   1.1    kardel 			if (output_raw != '*') {
   3760  1.13  christos 				atoascii(value, MAXVALLEN,
   3761  1.13  christos 					 bv, sizeof(bv) - 1);
   3762   1.1    kardel 				len = strlen(bv);
   3763   1.1    kardel 				bv[len] = output_raw;
   3764   1.1    kardel 				bv[len+1] = '\0';
   3765  1.13  christos 			} else {
   3766  1.13  christos 				atoascii(value, MAXVALLEN,
   3767  1.13  christos 					 bv, sizeof(bv));
   3768   1.1    kardel 			}
   3769   1.1    kardel 			output(fp, bn, bv);
   3770   1.1    kardel 		}
   3771   1.1    kardel 	}
   3772   1.1    kardel 	endoutput(fp);
   3773   1.1    kardel }
   3774   1.1    kardel 
   3775   1.1    kardel 
   3776   1.1    kardel /*
   3777   1.1    kardel  * sortassoc - sort associations in the cache into ascending order
   3778   1.1    kardel  */
   3779   1.1    kardel void
   3780   1.1    kardel sortassoc(void)
   3781   1.1    kardel {
   3782   1.1    kardel 	if (numassoc > 1)
   3783   1.9  christos 		qsort(assoc_cache, (size_t)numassoc,
   3784   1.9  christos 		      sizeof(assoc_cache[0]), &assoccmp);
   3785   1.1    kardel }
   3786   1.1    kardel 
   3787   1.1    kardel 
   3788   1.1    kardel /*
   3789   1.1    kardel  * assoccmp - compare two associations
   3790   1.1    kardel  */
   3791   1.1    kardel static int
   3792   1.1    kardel assoccmp(
   3793   1.1    kardel 	const void *t1,
   3794   1.1    kardel 	const void *t2
   3795   1.1    kardel 	)
   3796   1.1    kardel {
   3797   1.4    kardel 	const struct association *ass1 = t1;
   3798   1.4    kardel 	const struct association *ass2 = t2;
   3799   1.1    kardel 
   3800   1.1    kardel 	if (ass1->assid < ass2->assid)
   3801   1.1    kardel 		return -1;
   3802   1.1    kardel 	if (ass1->assid > ass2->assid)
   3803   1.1    kardel 		return 1;
   3804   1.1    kardel 	return 0;
   3805   1.1    kardel }
   3806   1.4    kardel 
   3807   1.1    kardel 
   3808   1.1    kardel /*
   3809   1.9  christos  * grow_assoc_cache() - enlarge dynamic assoc_cache array
   3810   1.9  christos  *
   3811   1.9  christos  * The strategy is to add an assumed 4k page size at a time, leaving
   3812   1.9  christos  * room for malloc() bookkeeping overhead equivalent to 4 pointers.
   3813   1.9  christos  */
   3814   1.9  christos void
   3815   1.9  christos grow_assoc_cache(void)
   3816   1.9  christos {
   3817   1.9  christos 	static size_t	prior_sz;
   3818   1.9  christos 	size_t		new_sz;
   3819   1.9  christos 
   3820   1.9  christos 	new_sz = prior_sz + 4 * 1024;
   3821   1.9  christos 	if (0 == prior_sz) {
   3822   1.9  christos 		new_sz -= 4 * sizeof(void *);
   3823   1.9  christos 	}
   3824   1.9  christos 	assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
   3825   1.9  christos 	prior_sz = new_sz;
   3826  1.14  christos 	assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
   3827   1.9  christos }
   3828   1.9  christos 
   3829   1.9  christos 
   3830   1.9  christos /*
   3831   1.1    kardel  * ntpq_custom_opt_handler - autoopts handler for -c and -p
   3832   1.1    kardel  *
   3833   1.1    kardel  * By default, autoopts loses the relative order of -c and -p options
   3834   1.1    kardel  * on the command line.  This routine replaces the default handler for
   3835   1.1    kardel  * those routines and builds a list of commands to execute preserving
   3836   1.1    kardel  * the order.
   3837   1.1    kardel  */
   3838   1.1    kardel void
   3839   1.1    kardel ntpq_custom_opt_handler(
   3840   1.1    kardel 	tOptions *pOptions,
   3841   1.1    kardel 	tOptDesc *pOptDesc
   3842   1.1    kardel 	)
   3843   1.1    kardel {
   3844   1.1    kardel 	switch (pOptDesc->optValue) {
   3845   1.9  christos 
   3846   1.1    kardel 	default:
   3847   1.9  christos 		fprintf(stderr,
   3848   1.1    kardel 			"ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
   3849   1.1    kardel 			pOptDesc->optValue, pOptDesc->optValue);
   3850   1.9  christos 		exit(1);
   3851   1.1    kardel 
   3852   1.1    kardel 	case 'c':
   3853   1.1    kardel 		ADDCMD(pOptDesc->pzLastArg);
   3854   1.1    kardel 		break;
   3855   1.1    kardel 
   3856   1.1    kardel 	case 'p':
   3857   1.1    kardel 		ADDCMD("peers");
   3858   1.1    kardel 		break;
   3859   1.1    kardel 	}
   3860   1.1    kardel }
   3861  1.12  christos /*
   3862  1.12  christos  * Obtain list of digest names
   3863  1.12  christos  */
   3864  1.12  christos 
   3865  1.19  christos #if defined(OPENSSL) && !defined(HAVE_EVP_MD_DO_ALL_SORTED)
   3866  1.19  christos # if defined(_MSC_VER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
   3867  1.19  christos #  define HAVE_EVP_MD_DO_ALL_SORTED
   3868  1.19  christos # endif
   3869  1.19  christos #endif
   3870  1.19  christos 
   3871  1.12  christos #ifdef OPENSSL
   3872  1.12  christos # ifdef HAVE_EVP_MD_DO_ALL_SORTED
   3873  1.19  christos #  define K_PER_LINE	8
   3874  1.19  christos #  define K_NL_PFX_STR	"\n    "
   3875  1.19  christos #  define K_DELIM_STR	", "
   3876  1.19  christos 
   3877  1.12  christos struct hstate {
   3878  1.20  christos 	char *list;
   3879  1.20  christos 	const char **seen;
   3880  1.20  christos 	int idx;
   3881  1.12  christos };
   3882  1.19  christos 
   3883  1.19  christos 
   3884  1.20  christos #  ifndef BUILD_AS_LIB
   3885  1.19  christos static void
   3886  1.19  christos list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg)
   3887  1.12  christos {
   3888  1.20  christos 	size_t 	       len, n;
   3889  1.20  christos 	const char    *name, **seen;
   3890  1.20  christos 	struct hstate *hstate = arg;
   3891  1.20  christos 	const char    *cp;
   3892  1.20  christos 
   3893  1.20  christos 	/* m is MD obj, from is name or alias, to is base name for alias */
   3894  1.20  christos 	if (!m || !from || to)
   3895  1.20  christos 		return; /* Ignore aliases */
   3896  1.20  christos 
   3897  1.20  christos 	/* Discard MACs that NTP won't accept. */
   3898  1.20  christos 	/* Keep this consistent with keytype_from_text() in ssl_init.c. */
   3899  1.20  christos 	if (EVP_MD_size(m) > (int)(MAX_MAC_LEN - sizeof(keyid_t)))
   3900  1.20  christos 		return;
   3901  1.20  christos 
   3902  1.20  christos 	name = EVP_MD_name(m);
   3903  1.20  christos 
   3904  1.20  christos 	/* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
   3905  1.20  christos 
   3906  1.20  christos 	for (cp = name; *cp; cp++)
   3907  1.20  christos 		if (islower((unsigned char)*cp))
   3908  1.20  christos 			return;
   3909  1.12  christos 
   3910  1.20  christos 	len = (cp - name) + 1;
   3911  1.20  christos 
   3912  1.20  christos 	/* There are duplicates.  Discard if name has been seen. */
   3913  1.20  christos 
   3914  1.20  christos 	for (seen = hstate->seen; *seen; seen++)
   3915  1.20  christos 		if (!strcmp(*seen, name))
   3916  1.20  christos 			return;
   3917  1.12  christos 
   3918  1.20  christos 	n = (seen - hstate->seen) + 2;
   3919  1.20  christos 	hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
   3920  1.20  christos 	hstate->seen[n-2] = name;
   3921  1.20  christos 	hstate->seen[n-1] = NULL;
   3922  1.20  christos 
   3923  1.20  christos 	if (hstate->list != NULL)
   3924  1.20  christos 		len += strlen(hstate->list);
   3925  1.12  christos 
   3926  1.20  christos 	len += (hstate->idx >= K_PER_LINE)
   3927  1.20  christos 	    ? strlen(K_NL_PFX_STR)
   3928  1.20  christos 	    : strlen(K_DELIM_STR);
   3929  1.20  christos 
   3930  1.20  christos 	if (hstate->list == NULL) {
   3931  1.20  christos 		hstate->list = (char *)emalloc(len);
   3932  1.20  christos 		hstate->list[0] = '\0';
   3933  1.20  christos 	} else {
   3934  1.20  christos 		hstate->list = (char *)erealloc(hstate->list, len);
   3935  1.19  christos 	}
   3936  1.20  christos 
   3937  1.20  christos 	sprintf(hstate->list + strlen(hstate->list), "%s%s",
   3938  1.20  christos 		((hstate->idx >= K_PER_LINE) ? K_NL_PFX_STR : K_DELIM_STR),
   3939  1.20  christos 		name);
   3940  1.20  christos 
   3941  1.20  christos 	if (hstate->idx >= K_PER_LINE)
   3942  1.20  christos 		hstate->idx = 1;
   3943  1.20  christos 	else
   3944  1.20  christos 		hstate->idx++;
   3945  1.19  christos }
   3946  1.20  christos #  endif /* !defined(BUILD_AS_LIB) */
   3947  1.19  christos 
   3948  1.20  christos #  ifndef BUILD_AS_LIB
   3949  1.19  christos /* Insert CMAC into SSL digests list */
   3950  1.19  christos static char *
   3951  1.19  christos insert_cmac(char *list)
   3952  1.19  christos {
   3953  1.20  christos #ifdef ENABLE_CMAC
   3954  1.20  christos 	int insert;
   3955  1.20  christos 	size_t len;
   3956  1.19  christos 
   3957  1.19  christos 
   3958  1.20  christos 	/* If list empty, we need to insert CMAC on new line */
   3959  1.20  christos 	insert = (!list || !*list);
   3960  1.20  christos 
   3961  1.19  christos 	if (insert) {
   3962  1.20  christos 		len = strlen(K_NL_PFX_STR) + strlen(CMAC);
   3963  1.19  christos 		list = (char *)erealloc(list, len + 1);
   3964  1.20  christos 		sprintf(list, "%s%s", K_NL_PFX_STR, CMAC);
   3965  1.20  christos 	} else {	/* List not empty */
   3966  1.20  christos 		/* Check if CMAC already in list - future proofing */
   3967  1.20  christos 		const char *cmac_sn;
   3968  1.20  christos 		char *cmac_p;
   3969  1.20  christos 
   3970  1.20  christos 		cmac_sn = OBJ_nid2sn(NID_cmac);
   3971  1.20  christos 		cmac_p = list;
   3972  1.20  christos 		insert = cmac_sn != NULL && *cmac_sn != '\0';
   3973  1.20  christos 
   3974  1.20  christos 		/* CMAC in list if found, followed by nul char or ',' */
   3975  1.20  christos 		while (insert && NULL != (cmac_p = strstr(cmac_p, cmac_sn))) {
   3976  1.20  christos 			cmac_p += strlen(cmac_sn);
   3977  1.20  christos 			/* Still need to insert if not nul and not ',' */
   3978  1.20  christos 			insert = *cmac_p && ',' != *cmac_p;
   3979  1.20  christos 		}
   3980  1.20  christos 
   3981  1.20  christos 		/* Find proper insertion point */
   3982  1.20  christos 		if (insert) {
   3983  1.20  christos 			char *last_nl;
   3984  1.20  christos 			char *point;
   3985  1.20  christos 			char *delim;
   3986  1.20  christos 			int found;
   3987  1.20  christos 
   3988  1.20  christos 			/* Default to start if list empty */
   3989  1.20  christos 			found = 0;
   3990  1.20  christos 			delim = list;
   3991  1.20  christos 			len = strlen(list);
   3992  1.20  christos 
   3993  1.20  christos 			/* While new lines */
   3994  1.20  christos 			while (delim < list + len && *delim &&
   3995  1.20  christos 			       !strncmp(K_NL_PFX_STR, delim, strlen(K_NL_PFX_STR))) {
   3996  1.20  christos 				point = delim + strlen(K_NL_PFX_STR);
   3997  1.20  christos 
   3998  1.20  christos 				/* While digest names on line */
   3999  1.20  christos 				while (point < list + len && *point) {
   4000  1.20  christos 					/* Another digest after on same or next line? */
   4001  1.20  christos 					delim = strstr( point, K_DELIM_STR);
   4002  1.20  christos 					last_nl = strstr( point, K_NL_PFX_STR);
   4003  1.20  christos 
   4004  1.20  christos 					/* No - end of list */
   4005  1.20  christos 					if (!delim && !last_nl) {
   4006  1.20  christos 						delim = list + len;
   4007  1.20  christos 					} else
   4008  1.20  christos 						/* New line and no delim or before delim? */
   4009  1.20  christos 						if (last_nl && (!delim || last_nl < delim)) {
   4010  1.20  christos 							delim = last_nl;
   4011  1.20  christos 						}
   4012  1.20  christos 
   4013  1.20  christos 					/* Found insertion point where CMAC before entry? */
   4014  1.20  christos 					if (strncmp(CMAC, point, delim - point) < 0) {
   4015  1.20  christos 						found = 1;
   4016  1.20  christos 						break;
   4017  1.20  christos 					}
   4018  1.20  christos 
   4019  1.20  christos 					if (delim < list + len && *delim &&
   4020  1.20  christos 					    !strncmp(K_DELIM_STR, delim, strlen(K_DELIM_STR))) {
   4021  1.20  christos 						point += strlen(K_DELIM_STR);
   4022  1.20  christos 					} else {
   4023  1.20  christos 						break;
   4024  1.20  christos 					}
   4025  1.20  christos 				} /* While digest names on line */
   4026  1.20  christos 			} /* While new lines */
   4027  1.20  christos 
   4028  1.20  christos 			/* If found in list */
   4029  1.20  christos 			if (found) {
   4030  1.20  christos 				/* insert cmac and delim */
   4031  1.20  christos 				/* Space for list could move - save offset */
   4032  1.20  christos 				ptrdiff_t p_offset = point - list;
   4033  1.20  christos 				len += strlen(CMAC) + strlen(K_DELIM_STR);
   4034  1.20  christos 				list = (char *)erealloc(list, len + 1);
   4035  1.20  christos 				point = list + p_offset;
   4036  1.20  christos 				/* move to handle src/dest overlap */
   4037  1.20  christos 				memmove(point + strlen(CMAC) + strlen(K_DELIM_STR),
   4038  1.19  christos 					point, strlen(point) + 1);
   4039  1.20  christos 				strncpy(point, CMAC, strlen(CMAC));
   4040  1.20  christos 				strncpy(point + strlen(CMAC), K_DELIM_STR, strlen(K_DELIM_STR));
   4041  1.20  christos 			} else {	/* End of list */
   4042  1.20  christos 				/* append delim and cmac */
   4043  1.20  christos 				len += strlen(K_DELIM_STR) + strlen(CMAC);
   4044  1.20  christos 				list = (char *)erealloc(list, len + 1);
   4045  1.20  christos 				strcpy(list + strlen(list), K_DELIM_STR);
   4046  1.20  christos 				strcpy(list + strlen(list), CMAC);
   4047  1.20  christos 			}
   4048  1.20  christos 		} /* insert */
   4049  1.20  christos 	} /* List not empty */
   4050  1.20  christos #endif /*ENABLE_CMAC*/
   4051  1.20  christos 	return list;
   4052  1.12  christos }
   4053  1.20  christos #  endif /* !defined(BUILD_AS_LIB) */
   4054  1.12  christos # endif
   4055  1.12  christos #endif
   4056  1.12  christos 
   4057  1.19  christos 
   4058  1.20  christos #ifndef BUILD_AS_LIB
   4059  1.19  christos static char *
   4060  1.19  christos list_digest_names(void)
   4061  1.12  christos {
   4062  1.20  christos 	char *list = NULL;
   4063  1.20  christos 
   4064  1.12  christos #ifdef OPENSSL
   4065  1.12  christos # ifdef HAVE_EVP_MD_DO_ALL_SORTED
   4066  1.20  christos 	struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
   4067  1.20  christos 
   4068  1.20  christos 	/* replace calloc(1, sizeof(const char *)) */
   4069  1.20  christos 	hstate.seen = (const char **)emalloc_zero(sizeof(const char *));
   4070  1.20  christos 
   4071  1.20  christos 	INIT_SSL();
   4072  1.20  christos 	EVP_MD_do_all_sorted(list_md_fn, &hstate);
   4073  1.20  christos 	list = hstate.list;
   4074  1.20  christos 	free(hstate.seen);
   4075  1.20  christos 
   4076  1.20  christos 	list = insert_cmac(list);	/* Insert CMAC into SSL digests list */
   4077  1.20  christos 
   4078  1.12  christos # else
   4079  1.20  christos 	list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
   4080  1.20  christos 	strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
   4081  1.12  christos # endif
   4082  1.12  christos #else
   4083  1.20  christos 	list = (char *)emalloc(sizeof("md5"));
   4084  1.20  christos 	strcpy(list, "md5");
   4085  1.12  christos #endif
   4086  1.20  christos 
   4087  1.20  christos 	return list;
   4088  1.12  christos }
   4089  1.20  christos #endif /* !defined(BUILD_AS_LIB) */
   4090  1.14  christos 
   4091  1.14  christos #define CTRLC_STACK_MAX 4
   4092  1.14  christos static volatile size_t		ctrlc_stack_len = 0;
   4093  1.14  christos static volatile Ctrl_C_Handler	ctrlc_stack[CTRLC_STACK_MAX];
   4094  1.14  christos 
   4095  1.14  christos 
   4096  1.14  christos 
   4097  1.14  christos int/*BOOL*/
   4098  1.14  christos push_ctrl_c_handler(
   4099  1.14  christos 	Ctrl_C_Handler func
   4100  1.14  christos 	)
   4101  1.14  christos {
   4102  1.14  christos 	size_t size = ctrlc_stack_len;
   4103  1.14  christos 	if (func && (size < CTRLC_STACK_MAX)) {
   4104  1.14  christos 		ctrlc_stack[size] = func;
   4105  1.14  christos 		ctrlc_stack_len = size + 1;
   4106  1.14  christos 		return TRUE;
   4107  1.14  christos 	}
   4108  1.14  christos 	return FALSE;
   4109  1.14  christos }
   4110  1.14  christos 
   4111  1.14  christos int/*BOOL*/
   4112  1.14  christos pop_ctrl_c_handler(
   4113  1.14  christos 	Ctrl_C_Handler func
   4114  1.14  christos 	)
   4115  1.14  christos {
   4116  1.14  christos 	size_t size = ctrlc_stack_len;
   4117  1.14  christos 	if (size) {
   4118  1.14  christos 		--size;
   4119  1.14  christos 		if (func == NULL || func == ctrlc_stack[size]) {
   4120  1.14  christos 			ctrlc_stack_len = size;
   4121  1.14  christos 			return TRUE;
   4122  1.14  christos 		}
   4123  1.14  christos 	}
   4124  1.14  christos 	return FALSE;
   4125  1.14  christos }
   4126  1.14  christos 
   4127  1.20  christos #ifndef BUILD_AS_LIB
   4128  1.14  christos static void
   4129  1.14  christos on_ctrlc(void)
   4130  1.14  christos {
   4131  1.14  christos 	size_t size = ctrlc_stack_len;
   4132  1.14  christos 	while (size)
   4133  1.14  christos 		if ((*ctrlc_stack[--size])())
   4134  1.14  christos 			break;
   4135  1.14  christos }
   4136  1.20  christos #endif /* !defined(BUILD_AS_LIB) */
   4137  1.15  christos 
   4138  1.20  christos #ifndef BUILD_AS_LIB
   4139  1.15  christos static int
   4140  1.15  christos my_easprintf(
   4141  1.15  christos 	char ** 	ppinto,
   4142  1.15  christos 	const char *	fmt   ,
   4143  1.15  christos 	...
   4144  1.15  christos 	)
   4145  1.15  christos {
   4146  1.15  christos 	va_list	va;
   4147  1.15  christos 	int	prc;
   4148  1.15  christos 	size_t	len = 128;
   4149  1.15  christos 	char *	buf = emalloc(len);
   4150  1.15  christos 
   4151  1.15  christos   again:
   4152  1.15  christos 	/* Note: we expect the memory allocation to fail long before the
   4153  1.15  christos 	 * increment in buffer size actually overflows.
   4154  1.15  christos 	 */
   4155  1.15  christos 	buf = (buf) ? erealloc(buf, len) : emalloc(len);
   4156  1.15  christos 
   4157  1.15  christos 	va_start(va, fmt);
   4158  1.15  christos 	prc = vsnprintf(buf, len, fmt, va);
   4159  1.15  christos 	va_end(va);
   4160  1.15  christos 
   4161  1.15  christos 	if (prc < 0) {
   4162  1.15  christos 		/* might be very old vsnprintf. Or actually MSVC... */
   4163  1.15  christos 		len += len >> 1;
   4164  1.15  christos 		goto again;
   4165  1.15  christos 	}
   4166  1.15  christos 	if ((size_t)prc >= len) {
   4167  1.15  christos 		/* at least we have the proper size now... */
   4168  1.15  christos 		len = (size_t)prc + 1;
   4169  1.15  christos 		goto again;
   4170  1.15  christos 	}
   4171  1.15  christos 	if ((size_t)prc < (len - 32))
   4172  1.15  christos 		buf = erealloc(buf, (size_t)prc + 1);
   4173  1.15  christos 	*ppinto = buf;
   4174  1.15  christos 	return prc;
   4175  1.15  christos }
   4176  1.20  christos #endif /* !defined(BUILD_AS_LIB) */
   4177