ntpq-subs.c revision c62812877398840dae0ba74b03e9e6a43cc56fc5
1/*
2 * ntpq-subs.c - subroutines which are called to perform ntpq commands.
3 */
4#include <config.h>
5#include <stdio.h>
6#include <ctype.h>
7#include <sys/types.h>
8#include <sys/time.h>
9
10#include "ntpq.h"
11#include "ntpq-opts.h"
12
13extern char	currenthost[];
14extern int	currenthostisnum;
15size_t		maxhostlen;
16
17/*
18 * Declarations for command handlers in here
19 */
20static	associd_t checkassocid	(u_int32);
21static	struct varlist *findlistvar (struct varlist *, char *);
22static	void	doaddvlist	(struct varlist *, const char *);
23static	void	dormvlist	(struct varlist *, const char *);
24static	void	doclearvlist	(struct varlist *);
25static	void	makequerydata	(struct varlist *, int *, char *);
26static	int	doquerylist	(struct varlist *, int, associd_t, int,
27				 u_short *, int *, const char **);
28static	void	doprintvlist	(struct varlist *, FILE *);
29static	void	addvars 	(struct parse *, FILE *);
30static	void	rmvars		(struct parse *, FILE *);
31static	void	clearvars	(struct parse *, FILE *);
32static	void	showvars	(struct parse *, FILE *);
33static	int	dolist		(struct varlist *, associd_t, int, int,
34				 FILE *);
35static	void	readlist	(struct parse *, FILE *);
36static	void	writelist	(struct parse *, FILE *);
37static	void	readvar 	(struct parse *, FILE *);
38static	void	writevar	(struct parse *, FILE *);
39static	void	clocklist	(struct parse *, FILE *);
40static	void	clockvar	(struct parse *, FILE *);
41static	int	findassidrange	(u_int32, u_int32, int *, int *,
42				 FILE *);
43static	void	mreadlist	(struct parse *, FILE *);
44static	void	mreadvar	(struct parse *, FILE *);
45static	void	printassoc	(int, FILE *);
46static	void	associations	(struct parse *, FILE *);
47static	void	lassociations	(struct parse *, FILE *);
48static	void	passociations	(struct parse *, FILE *);
49static	void	lpassociations	(struct parse *, FILE *);
50
51#ifdef	UNUSED
52static	void	radiostatus (struct parse *, FILE *);
53#endif	/* UNUSED */
54
55static	void	authinfo	(struct parse *, FILE *);
56static	void	pstats	 	(struct parse *, FILE *);
57static	long	when		(l_fp *, l_fp *, l_fp *);
58static	char *	prettyinterval	(char *, size_t, long);
59static	int	doprintpeers	(struct varlist *, int, int, int, const char *, FILE *, int);
60static	int	dogetpeers	(struct varlist *, associd_t, FILE *, int);
61static	void	dopeers 	(int, FILE *, int);
62static	void	peers		(struct parse *, FILE *);
63static	void	doapeers 	(int, FILE *, int);
64static	void	apeers		(struct parse *, FILE *);
65static	void	lpeers		(struct parse *, FILE *);
66static	void	doopeers	(int, FILE *, int);
67static	void	opeers		(struct parse *, FILE *);
68static	void	lopeers 	(struct parse *, FILE *);
69static	void	config		(struct parse *, FILE *);
70static	void	saveconfig	(struct parse *, FILE *);
71static	void	config_from_file(struct parse *, FILE *);
72static	void	mrulist		(struct parse *, FILE *);
73static	void	ifstats		(struct parse *, FILE *);
74static	void	reslist		(struct parse *, FILE *);
75static	void	sysstats	(struct parse *, FILE *);
76static	void	sysinfo		(struct parse *, FILE *);
77static	void	kerninfo	(struct parse *, FILE *);
78static	void	monstats	(struct parse *, FILE *);
79static	void	iostats		(struct parse *, FILE *);
80static	void	timerstats	(struct parse *, FILE *);
81
82/*
83 * Commands we understand.	Ntpdc imports this.
84 */
85struct xcmd opcmds[] = {
86	{ "saveconfig", saveconfig, { NTP_STR, NO, NO, NO },
87		{ "filename", "", "", ""},
88		"save ntpd configuration to file, . for current config file"},
89	{ "associations", associations, {  NO, NO, NO, NO },
90	  { "", "", "", "" },
91	  "print list of association ID's and statuses for the server's peers" },
92	{ "passociations", passociations,   {  NO, NO, NO, NO },
93	  { "", "", "", "" },
94	  "print list of associations returned by last associations command" },
95	{ "lassociations", lassociations,   {  NO, NO, NO, NO },
96	  { "", "", "", "" },
97	  "print list of associations including all client information" },
98	{ "lpassociations", lpassociations, {  NO, NO, NO, NO },
99	  { "", "", "", "" },
100	  "print last obtained list of associations, including client information" },
101	{ "addvars",    addvars,    { NTP_STR, NO, NO, NO },
102	  { "name[=value][,...]", "", "", "" },
103	  "add variables to the variable list or change their values" },
104	{ "rmvars", rmvars,     { NTP_STR, NO, NO, NO },
105	  { "name[,...]", "", "", "" },
106	  "remove variables from the variable list" },
107	{ "clearvars",  clearvars,  { NO, NO, NO, NO },
108	  { "", "", "", "" },
109	  "remove all variables from the variable list" },
110	{ "showvars",   showvars,   { NO, NO, NO, NO },
111	  { "", "", "", "" },
112	  "print variables on the variable list" },
113	{ "readlist",   readlist,   { OPT|NTP_UINT, NO, NO, NO },
114	  { "assocID", "", "", "" },
115	  "read the system or peer variables included in the variable list" },
116	{ "rl",     readlist,   { OPT|NTP_UINT, NO, NO, NO },
117	  { "assocID", "", "", "" },
118	  "read the system or peer variables included in the variable list" },
119	{ "writelist",  writelist,  { OPT|NTP_UINT, NO, NO, NO },
120	  { "assocID", "", "", "" },
121	  "write the system or peer variables included in the variable list" },
122	{ "readvar", readvar,    { OPT|NTP_UINT, OPT|NTP_STR, OPT|NTP_STR, OPT|NTP_STR, },
123	  { "assocID", "varname1", "varname2", "varname3" },
124	  "read system or peer variables" },
125	{ "rv",      readvar,    { OPT|NTP_UINT, OPT|NTP_STR, OPT|NTP_STR, OPT|NTP_STR, },
126	  { "assocID", "varname1", "varname2", "varname3" },
127	  "read system or peer variables" },
128	{ "writevar",   writevar,   { NTP_UINT, NTP_STR, NO, NO },
129	  { "assocID", "name=value,[...]", "", "" },
130	  "write system or peer variables" },
131	{ "mreadlist",  mreadlist,  { NTP_UINT, NTP_UINT, NO, NO },
132	  { "assocIDlow", "assocIDhigh", "", "" },
133	  "read the peer variables in the variable list for multiple peers" },
134	{ "mrl",    mreadlist,  { NTP_UINT, NTP_UINT, NO, NO },
135	  { "assocIDlow", "assocIDhigh", "", "" },
136	  "read the peer variables in the variable list for multiple peers" },
137	{ "mreadvar",   mreadvar,   { NTP_UINT, NTP_UINT, OPT|NTP_STR, NO },
138	  { "assocIDlow", "assocIDhigh", "name=value[,...]", "" },
139	  "read peer variables from multiple peers" },
140	{ "mrv",    mreadvar,   { NTP_UINT, NTP_UINT, OPT|NTP_STR, NO },
141	  { "assocIDlow", "assocIDhigh", "name=value[,...]", "" },
142	  "read peer variables from multiple peers" },
143	{ "clocklist",  clocklist,  { OPT|NTP_UINT, NO, NO, NO },
144	  { "assocID", "", "", "" },
145	  "read the clock variables included in the variable list" },
146	{ "cl",     clocklist,  { OPT|NTP_UINT, NO, NO, NO },
147	  { "assocID", "", "", "" },
148	  "read the clock variables included in the variable list" },
149	{ "clockvar",   clockvar,   { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
150	  { "assocID", "name=value[,...]", "", "" },
151	  "read clock variables" },
152	{ "cv",     clockvar,   { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
153	  { "assocID", "name=value[,...]", "", "" },
154	  "read clock variables" },
155	{ "pstats",    pstats,    { NTP_UINT, NO, NO, NO },
156	  { "assocID", "", "", "" },
157	  "show statistics for a peer" },
158	{ "peers",  peers,      { OPT|IP_VERSION, NO, NO, NO },
159	  { "-4|-6", "", "", "" },
160	  "obtain and print a list of the server's peers [IP version]" },
161	{ "apeers",  apeers,      { OPT|IP_VERSION, NO, NO, NO },
162	  { "-4|-6", "", "", "" },
163	  "obtain and print a list of the server's peers and their assocIDs [IP version]" },
164	{ "lpeers", lpeers,     { OPT|IP_VERSION, NO, NO, NO },
165	  { "-4|-6", "", "", "" },
166	  "obtain and print a list of all peers and clients [IP version]" },
167	{ "opeers", opeers,     { OPT|IP_VERSION, NO, NO, NO },
168	  { "-4|-6", "", "", "" },
169	  "print peer list the old way, with dstadr shown rather than refid [IP version]" },
170	{ "lopeers", lopeers,   { OPT|IP_VERSION, NO, NO, NO },
171	  { "-4|-6", "", "", "" },
172	  "obtain and print a list of all peers and clients showing dstadr [IP version]" },
173	{ ":config", config,   { NTP_STR, NO, NO, NO },
174	  { "<configuration command line>", "", "", "" },
175	  "send a remote configuration command to ntpd" },
176	{ "config-from-file", config_from_file, { NTP_STR, NO, NO, NO },
177	  { "<configuration filename>", "", "", "" },
178	  "configure ntpd using the configuration filename" },
179	{ "mrulist", mrulist, { OPT|NTP_STR, OPT|NTP_STR, OPT|NTP_STR, OPT|NTP_STR },
180	  { "tag=value", "tag=value", "tag=value", "tag=value" },
181	  "display the list of most recently seen source addresses, tags mincount=... resall=0x... resany=0x..." },
182	{ "ifstats", ifstats, { NO, NO, NO, NO },
183	  { "", "", "", "" },
184	  "show statistics for each local address ntpd is using" },
185	{ "reslist", reslist, { NO, NO, NO, NO },
186	  { "", "", "", "" },
187	  "show ntpd access control list" },
188	{ "sysinfo", sysinfo, { NO, NO, NO, NO },
189	  { "", "", "", "" },
190	  "display system summary" },
191	{ "kerninfo", kerninfo, { NO, NO, NO, NO },
192	  { "", "", "", "" },
193	  "display kernel loop and PPS statistics" },
194	{ "sysstats", sysstats, { NO, NO, NO, NO },
195	  { "", "", "", "" },
196	  "display system uptime and packet counts" },
197	{ "monstats", monstats, { NO, NO, NO, NO },
198	  { "", "", "", "" },
199	  "display monitor (mrulist) counters and limits" },
200	{ "authinfo", authinfo, { NO, NO, NO, NO },
201	  { "", "", "", "" },
202	  "display symmetric authentication counters" },
203	{ "iostats", iostats, { NO, NO, NO, NO },
204	  { "", "", "", "" },
205	  "display network input and output counters" },
206	{ "timerstats", timerstats, { NO, NO, NO, NO },
207	  { "", "", "", "" },
208	  "display interval timer counters" },
209	{ 0,		0,		{ NO, NO, NO, NO },
210	  { "-4|-6", "", "", "" }, "" }
211};
212
213
214/*
215 * Variable list data space
216 */
217#define MAXLINE		512	/* maximum length of a line */
218#define MAXLIST		128	/* maximum variables in list */
219#define LENHOSTNAME	256	/* host name limit */
220
221#define MRU_GOT_COUNT	0x1
222#define MRU_GOT_LAST	0x2
223#define MRU_GOT_FIRST	0x4
224#define MRU_GOT_MV	0x8
225#define MRU_GOT_RS	0x10
226#define MRU_GOT_ADDR	0x20
227#define MRU_GOT_ALL	(MRU_GOT_COUNT | MRU_GOT_LAST | MRU_GOT_FIRST \
228			 | MRU_GOT_MV | MRU_GOT_RS | MRU_GOT_ADDR)
229
230/*
231 * mrulist() depends on MRUSORT_DEF and MRUSORT_RDEF being the first two
232 */
233typedef enum mru_sort_order_tag {
234	MRUSORT_DEF = 0,	/* lstint ascending */
235	MRUSORT_R_DEF,		/* lstint descending */
236	MRUSORT_AVGINT,		/* avgint ascending */
237	MRUSORT_R_AVGINT,	/* avgint descending */
238	MRUSORT_ADDR,		/* IPv4 asc. then IPv6 asc. */
239	MRUSORT_R_ADDR,		/* IPv6 desc. then IPv4 desc. */
240	MRUSORT_COUNT,		/* hit count ascending */
241	MRUSORT_R_COUNT,	/* hit count descending */
242	MRUSORT_MAX,		/* special: count of this enum */
243} mru_sort_order;
244
245const char * const mru_sort_keywords[MRUSORT_MAX] = {
246	"lstint",		/* MRUSORT_DEF */
247	"-lstint",		/* MRUSORT_R_DEF */
248	"avgint",		/* MRUSORT_AVGINT */
249	"-avgint",		/* MRUSORT_R_AVGINT */
250	"addr",			/* MRUSORT_ADDR */
251	"-addr",		/* MRUSORT_R_ADDR */
252	"count",		/* MRUSORT_COUNT */
253	"-count",		/* MRUSORT_R_COUNT */
254};
255
256typedef int (*qsort_cmp)(const void *, const void *);
257
258/*
259 * Old CTL_PST defines for version 2.
260 */
261#define OLD_CTL_PST_CONFIG		0x80
262#define OLD_CTL_PST_AUTHENABLE		0x40
263#define OLD_CTL_PST_AUTHENTIC		0x20
264#define OLD_CTL_PST_REACH		0x10
265#define OLD_CTL_PST_SANE		0x08
266#define OLD_CTL_PST_DISP		0x04
267
268#define OLD_CTL_PST_SEL_REJECT		0
269#define OLD_CTL_PST_SEL_SELCAND 	1
270#define OLD_CTL_PST_SEL_SYNCCAND	2
271#define OLD_CTL_PST_SEL_SYSPEER 	3
272
273char flash2[] = " .+*    "; /* flash decode for version 2 */
274char flash3[] = " x.-+#*o"; /* flash decode for peer status version 3 */
275
276struct varlist {
277	const char *name;
278	char *value;
279} g_varlist[MAXLIST] = { { 0, 0 } };
280
281/*
282 * Imported from ntpq.c
283 */
284extern int showhostnames;
285extern int wideremote;
286extern int rawmode;
287extern struct servent *server_entry;
288extern struct association *assoc_cache;
289extern u_char pktversion;
290
291typedef struct mru_tag mru;
292struct mru_tag {
293	mru *		hlink;	/* next in hash table bucket */
294	DECL_DLIST_LINK(mru, mlink);
295	int		count;
296	l_fp		last;
297	l_fp		first;
298	u_char		mode;
299	u_char		ver;
300	u_short		rs;
301	sockaddr_u	addr;
302};
303
304typedef struct ifstats_row_tag {
305	u_int		ifnum;
306	sockaddr_u	addr;
307	sockaddr_u	bcast;
308	int		enabled;
309	u_int		flags;
310	int		mcast_count;
311	char		name[32];
312	int		peer_count;
313	int		received;
314	int		sent;
315	int		send_errors;
316	u_int		ttl;
317	u_int		uptime;
318} ifstats_row;
319
320typedef struct reslist_row_tag {
321	u_int		idx;
322	sockaddr_u	addr;
323	sockaddr_u	mask;
324	u_long		hits;
325	char		flagstr[128];
326} reslist_row;
327
328typedef struct var_display_collection_tag {
329	const char * const tag;		/* system variable */
330	const char * const display;	/* descriptive text */
331	u_char type;			/* NTP_STR, etc */
332	union {
333		char *		str;
334		sockaddr_u	sau;	/* NTP_ADD */
335		l_fp		lfp;	/* NTP_LFP */
336	} v;				/* retrieved value */
337} vdc;
338#if !defined(MISSING_C99_STRUCT_INIT)
339# define VDC_INIT(a, b, c) { .tag = a, .display = b, .type = c }
340#else
341# define VDC_INIT(a, b, c) { a, b, c }
342#endif
343/*
344 * other local function prototypes
345 */
346void		mrulist_ctrl_c_hook(void);
347static mru *	add_mru(mru *);
348static int	collect_mru_list(const char *, l_fp *);
349static int	fetch_nonce(char *, size_t);
350static int	qcmp_mru_avgint(const void *, const void *);
351static int	qcmp_mru_r_avgint(const void *, const void *);
352static int	qcmp_mru_addr(const void *, const void *);
353static int	qcmp_mru_r_addr(const void *, const void *);
354static int	qcmp_mru_count(const void *, const void *);
355static int	qcmp_mru_r_count(const void *, const void *);
356static void	validate_ifnum(FILE *, u_int, int *, ifstats_row *);
357static void	another_ifstats_field(int *, ifstats_row *, FILE *);
358static void	collect_display_vdc(associd_t as, vdc *table,
359				    int decodestatus, FILE *fp);
360
361/*
362 * static globals
363 */
364static u_int	mru_count;
365static u_int	mru_dupes;
366volatile int	mrulist_interrupted;
367static mru	mru_list;		/* listhead */
368static mru **	hash_table;
369
370/*
371 * qsort comparison function table for mrulist().  The first two
372 * entries are NULL because they are handled without qsort().
373 */
374static const qsort_cmp mru_qcmp_table[MRUSORT_MAX] = {
375	NULL,			/* MRUSORT_DEF unused */
376	NULL,			/* MRUSORT_R_DEF unused */
377	&qcmp_mru_avgint,	/* MRUSORT_AVGINT */
378	&qcmp_mru_r_avgint,	/* MRUSORT_R_AVGINT */
379	&qcmp_mru_addr,		/* MRUSORT_ADDR */
380	&qcmp_mru_r_addr,	/* MRUSORT_R_ADDR */
381	&qcmp_mru_count,	/* MRUSORT_COUNT */
382	&qcmp_mru_r_count,	/* MRUSORT_R_COUNT */
383};
384
385/*
386 * checkassocid - return the association ID, checking to see if it is valid
387 */
388static associd_t
389checkassocid(
390	u_int32 value
391	)
392{
393	associd_t	associd;
394	u_long		ulvalue;
395
396	associd = (associd_t)value;
397	if (0 == associd || value != associd) {
398		ulvalue = value;
399		fprintf(stderr,
400			"***Invalid association ID %lu specified\n",
401			ulvalue);
402		return 0;
403	}
404
405	return associd;
406}
407
408
409/*
410 * findlistvar - Look for the named variable in a varlist.  If found,
411 *		 return a pointer to it.  Otherwise, if the list has
412 *		 slots available, return the pointer to the first free
413 *		 slot, or NULL if it's full.
414 */
415static struct varlist *
416findlistvar(
417	struct varlist *list,
418	char *name
419	)
420{
421	struct varlist *vl;
422
423	for (vl = list; vl < list + MAXLIST && vl->name != NULL; vl++)
424		if (!strcmp(name, vl->name))
425			return vl;
426	if (vl < list + MAXLIST)
427		return vl;
428
429	return NULL;
430}
431
432
433/*
434 * doaddvlist - add variable(s) to the variable list
435 */
436static void
437doaddvlist(
438	struct varlist *vlist,
439	const char *vars
440	)
441{
442	struct varlist *vl;
443	int len;
444	char *name;
445	char *value;
446
447	len = strlen(vars);
448	while (nextvar(&len, &vars, &name, &value)) {
449		vl = findlistvar(vlist, name);
450		if (NULL == vl) {
451			fprintf(stderr, "Variable list full\n");
452			return;
453		}
454
455		if (NULL == vl->name) {
456			vl->name = estrdup(name);
457		} else if (vl->value != NULL) {
458			free(vl->value);
459			vl->value = NULL;
460		}
461
462		if (value != NULL)
463			vl->value = estrdup(value);
464	}
465}
466
467
468/*
469 * dormvlist - remove variable(s) from the variable list
470 */
471static void
472dormvlist(
473	struct varlist *vlist,
474	const char *vars
475	)
476{
477	struct varlist *vl;
478	int len;
479	char *name;
480	char *value;
481
482	len = strlen(vars);
483	while (nextvar(&len, &vars, &name, &value)) {
484		vl = findlistvar(vlist, name);
485		if (vl == 0 || vl->name == 0) {
486			(void) fprintf(stderr, "Variable `%s' not found\n",
487				       name);
488		} else {
489			free((void *)(intptr_t)vl->name);
490			if (vl->value != 0)
491			    free(vl->value);
492			for ( ; (vl+1) < (g_varlist + MAXLIST)
493				      && (vl+1)->name != 0; vl++) {
494				vl->name = (vl+1)->name;
495				vl->value = (vl+1)->value;
496			}
497			vl->name = vl->value = 0;
498		}
499	}
500}
501
502
503/*
504 * doclearvlist - clear a variable list
505 */
506static void
507doclearvlist(
508	struct varlist *vlist
509	)
510{
511	register struct varlist *vl;
512
513	for (vl = vlist; vl < vlist + MAXLIST && vl->name != 0; vl++) {
514		free((void *)(intptr_t)vl->name);
515		vl->name = 0;
516		if (vl->value != 0) {
517			free(vl->value);
518			vl->value = 0;
519		}
520	}
521}
522
523
524/*
525 * makequerydata - form a data buffer to be included with a query
526 */
527static void
528makequerydata(
529	struct varlist *vlist,
530	int *datalen,
531	char *data
532	)
533{
534	register struct varlist *vl;
535	register char *cp, *cpend;
536	register int namelen, valuelen;
537	register int totallen;
538
539	cp = data;
540	cpend = data + *datalen;
541
542	for (vl = vlist; vl < vlist + MAXLIST && vl->name != 0; vl++) {
543		namelen = strlen(vl->name);
544		if (vl->value == 0)
545			valuelen = 0;
546		else
547			valuelen = strlen(vl->value);
548		totallen = namelen + valuelen + (valuelen != 0) + (cp != data);
549		if (cp + totallen > cpend) {
550		    fprintf(stderr,
551			    "***Ignoring variables starting with `%s'\n",
552			    vl->name);
553		    break;
554		}
555
556		if (cp != data)
557			*cp++ = ',';
558		memcpy(cp, vl->name, (size_t)namelen);
559		cp += namelen;
560		if (valuelen != 0) {
561			*cp++ = '=';
562			memcpy(cp, vl->value, (size_t)valuelen);
563			cp += valuelen;
564		}
565	}
566	*datalen = cp - data;
567}
568
569
570/*
571 * doquerylist - send a message including variables in a list
572 */
573static int
574doquerylist(
575	struct varlist *vlist,
576	int op,
577	associd_t associd,
578	int auth,
579	u_short *rstatus,
580	int *dsize,
581	const char **datap
582	)
583{
584	char data[CTL_MAX_DATA_LEN];
585	int datalen;
586
587	datalen = sizeof(data);
588	makequerydata(vlist, &datalen, data);
589
590	return doquery(op, associd, auth, datalen, data, rstatus, dsize,
591		       datap);
592}
593
594
595/*
596 * doprintvlist - print the variables on a list
597 */
598static void
599doprintvlist(
600	struct varlist *vlist,
601	FILE *fp
602	)
603{
604	size_t n;
605
606	if (NULL == vlist->name) {
607		fprintf(fp, "No variables on list\n");
608		return;
609	}
610	for (n = 0; n < MAXLIST && vlist[n].name != NULL; n++) {
611		if (NULL == vlist[n].value)
612			fprintf(fp, "%s\n", vlist[n].name);
613		else
614			fprintf(fp, "%s=%s\n", vlist[n].name,
615				vlist[n].value);
616	}
617}
618
619/*
620 * addvars - add variables to the variable list
621 */
622/*ARGSUSED*/
623static void
624addvars(
625	struct parse *pcmd,
626	FILE *fp
627	)
628{
629	doaddvlist(g_varlist, pcmd->argval[0].string);
630}
631
632
633/*
634 * rmvars - remove variables from the variable list
635 */
636/*ARGSUSED*/
637static void
638rmvars(
639	struct parse *pcmd,
640	FILE *fp
641	)
642{
643	dormvlist(g_varlist, pcmd->argval[0].string);
644}
645
646
647/*
648 * clearvars - clear the variable list
649 */
650/*ARGSUSED*/
651static void
652clearvars(
653	struct parse *pcmd,
654	FILE *fp
655	)
656{
657	doclearvlist(g_varlist);
658}
659
660
661/*
662 * showvars - show variables on the variable list
663 */
664/*ARGSUSED*/
665static void
666showvars(
667	struct parse *pcmd,
668	FILE *fp
669	)
670{
671	doprintvlist(g_varlist, fp);
672}
673
674
675/*
676 * dolist - send a request with the given list of variables
677 */
678static int
679dolist(
680	struct varlist *vlist,
681	associd_t associd,
682	int op,
683	int type,
684	FILE *fp
685	)
686{
687	const char *datap;
688	int res;
689	int dsize;
690	u_short rstatus;
691	int quiet;
692
693	/*
694	 * if we're asking for specific variables don't include the
695	 * status header line in the output.
696	 */
697	if (old_rv)
698		quiet = 0;
699	else
700		quiet = (vlist->name != NULL);
701
702	res = doquerylist(vlist, op, associd, 0, &rstatus, &dsize, &datap);
703
704	if (res != 0)
705		return 0;
706
707	if (numhosts > 1)
708		fprintf(fp, "server=%s ", currenthost);
709	if (dsize == 0) {
710		if (associd == 0)
711			fprintf(fp, "No system%s variables returned\n",
712				(type == TYPE_CLOCK) ? " clock" : "");
713		else
714			fprintf(fp,
715				"No information returned for%s association %u\n",
716				(type == TYPE_CLOCK) ? " clock" : "",
717				associd);
718		return 1;
719	}
720
721	if (!quiet)
722		fprintf(fp, "associd=%u ", associd);
723	printvars(dsize, datap, (int)rstatus, type, quiet, fp);
724	return 1;
725}
726
727
728/*
729 * readlist - send a read variables request with the variables on the list
730 */
731static void
732readlist(
733	struct parse *pcmd,
734	FILE *fp
735	)
736{
737	associd_t	associd;
738	int		type;
739
740	if (pcmd->nargs == 0) {
741		associd = 0;
742	} else {
743	  /* HMS: I think we want the u_int32 target here, not the u_long */
744		if (pcmd->argval[0].uval == 0)
745			associd = 0;
746		else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
747			return;
748	}
749
750	type = (0 == associd)
751		   ? TYPE_SYS
752		   : TYPE_PEER;
753	dolist(g_varlist, associd, CTL_OP_READVAR, type, fp);
754}
755
756
757/*
758 * writelist - send a write variables request with the variables on the list
759 */
760static void
761writelist(
762	struct parse *pcmd,
763	FILE *fp
764	)
765{
766	const char *datap;
767	int res;
768	associd_t associd;
769	int dsize;
770	u_short rstatus;
771
772	if (pcmd->nargs == 0) {
773		associd = 0;
774	} else {
775		/* HMS: Do we really want uval here? */
776		if (pcmd->argval[0].uval == 0)
777			associd = 0;
778		else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
779			return;
780	}
781
782	res = doquerylist(g_varlist, CTL_OP_WRITEVAR, associd, 1, &rstatus,
783			  &dsize, &datap);
784
785	if (res != 0)
786		return;
787
788	if (numhosts > 1)
789		(void) fprintf(fp, "server=%s ", currenthost);
790	if (dsize == 0)
791		(void) fprintf(fp, "done! (no data returned)\n");
792	else {
793		(void) fprintf(fp,"associd=%u ", associd);
794		printvars(dsize, datap, (int)rstatus,
795			  (associd != 0) ? TYPE_PEER : TYPE_SYS, 0, fp);
796	}
797	return;
798}
799
800
801/*
802 * readvar - send a read variables request with the specified variables
803 */
804static void
805readvar(
806	struct parse *pcmd,
807	FILE *fp
808	)
809{
810	associd_t	associd;
811	u_int		tmpcount;
812	u_int		u;
813	int		type;
814	struct varlist	tmplist[MAXLIST];
815
816
817	/* HMS: uval? */
818	if (pcmd->nargs == 0 || pcmd->argval[0].uval == 0)
819		associd = 0;
820	else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
821		return;
822
823	ZERO(tmplist);
824	if (pcmd->nargs > 1) {
825		tmpcount = pcmd->nargs - 1;
826		for (u = 0; u < tmpcount; u++)
827			doaddvlist(tmplist, pcmd->argval[1 + u].string);
828	}
829
830	type = (0 == associd)
831		   ? TYPE_SYS
832		   : TYPE_PEER;
833	dolist(tmplist, associd, CTL_OP_READVAR, type, fp);
834
835	doclearvlist(tmplist);
836}
837
838
839/*
840 * writevar - send a write variables request with the specified variables
841 */
842static void
843writevar(
844	struct parse *pcmd,
845	FILE *fp
846	)
847{
848	const char *datap;
849	int res;
850	associd_t associd;
851	int type;
852	int dsize;
853	u_short rstatus;
854	struct varlist tmplist[MAXLIST];
855
856	/* HMS: uval? */
857	if (pcmd->argval[0].uval == 0)
858		associd = 0;
859	else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
860		return;
861
862	ZERO(tmplist);
863	doaddvlist(tmplist, pcmd->argval[1].string);
864
865	res = doquerylist(tmplist, CTL_OP_WRITEVAR, associd, 1, &rstatus,
866			  &dsize, &datap);
867
868	doclearvlist(tmplist);
869
870	if (res != 0)
871		return;
872
873	if (numhosts > 1)
874		fprintf(fp, "server=%s ", currenthost);
875	if (dsize == 0)
876		fprintf(fp, "done! (no data returned)\n");
877	else {
878		fprintf(fp,"associd=%u ", associd);
879		type = (0 == associd)
880			   ? TYPE_SYS
881			   : TYPE_PEER;
882		printvars(dsize, datap, (int)rstatus, type, 0, fp);
883	}
884	return;
885}
886
887
888/*
889 * clocklist - send a clock variables request with the variables on the list
890 */
891static void
892clocklist(
893	struct parse *pcmd,
894	FILE *fp
895	)
896{
897	associd_t associd;
898
899	/* HMS: uval? */
900	if (pcmd->nargs == 0) {
901		associd = 0;
902	} else {
903		if (pcmd->argval[0].uval == 0)
904			associd = 0;
905		else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
906			return;
907	}
908
909	dolist(g_varlist, associd, CTL_OP_READCLOCK, TYPE_CLOCK, fp);
910}
911
912
913/*
914 * clockvar - send a clock variables request with the specified variables
915 */
916static void
917clockvar(
918	struct parse *pcmd,
919	FILE *fp
920	)
921{
922	associd_t associd;
923	struct varlist tmplist[MAXLIST];
924
925	/* HMS: uval? */
926	if (pcmd->nargs == 0 || pcmd->argval[0].uval == 0)
927		associd = 0;
928	else if ((associd = checkassocid(pcmd->argval[0].uval)) == 0)
929		return;
930
931	ZERO(tmplist);
932	if (pcmd->nargs >= 2)
933		doaddvlist(tmplist, pcmd->argval[1].string);
934
935	dolist(tmplist, associd, CTL_OP_READCLOCK, TYPE_CLOCK, fp);
936
937	doclearvlist(tmplist);
938}
939
940
941/*
942 * findassidrange - verify a range of association ID's
943 */
944static int
945findassidrange(
946	u_int32	assid1,
947	u_int32	assid2,
948	int *	from,
949	int *	to,
950	FILE *	fp
951	)
952{
953	associd_t	assids[2];
954	int		ind[COUNTOF(assids)];
955	u_int		i;
956	size_t		a;
957
958
959	if (0 == numassoc)
960		dogetassoc(fp);
961
962	assids[0] = checkassocid(assid1);
963	if (0 == assids[0])
964		return 0;
965	assids[1] = checkassocid(assid2);
966	if (0 == assids[1])
967		return 0;
968
969	for (a = 0; a < COUNTOF(assids); a++) {
970		ind[a] = -1;
971		for (i = 0; i < numassoc; i++)
972			if (assoc_cache[i].assid == assids[a])
973				ind[a] = i;
974	}
975	for (a = 0; a < COUNTOF(assids); a++)
976		if (-1 == ind[a]) {
977			fprintf(stderr,
978				"***Association ID %u not found in list\n",
979				assids[a]);
980			return 0;
981		}
982
983	if (ind[0] < ind[1]) {
984		*from = ind[0];
985		*to = ind[1];
986	} else {
987		*to = ind[0];
988		*from = ind[1];
989	}
990	return 1;
991}
992
993
994
995/*
996 * mreadlist - send a read variables request for multiple associations
997 */
998static void
999mreadlist(
1000	struct parse *pcmd,
1001	FILE *fp
1002	)
1003{
1004	int i;
1005	int from;
1006	int to;
1007
1008	if (!findassidrange(pcmd->argval[0].uval, pcmd->argval[1].uval,
1009			    &from, &to, fp))
1010		return;
1011
1012	for (i = from; i <= to; i++) {
1013		if (i != from)
1014			fprintf(fp, "\n");
1015		if (!dolist(g_varlist, assoc_cache[i].assid,
1016			    CTL_OP_READVAR, TYPE_PEER, fp))
1017			return;
1018	}
1019	return;
1020}
1021
1022
1023/*
1024 * mreadvar - send a read variables request for multiple associations
1025 */
1026static void
1027mreadvar(
1028	struct parse *pcmd,
1029	FILE *fp
1030	)
1031{
1032	int i;
1033	int from;
1034	int to;
1035	struct varlist tmplist[MAXLIST];
1036	struct varlist *pvars;
1037
1038	if (!findassidrange(pcmd->argval[0].uval, pcmd->argval[1].uval,
1039				&from, &to, fp))
1040		return;
1041
1042	ZERO(tmplist);
1043	if (pcmd->nargs >= 3) {
1044		doaddvlist(tmplist, pcmd->argval[2].string);
1045		pvars = tmplist;
1046	} else {
1047		pvars = g_varlist;
1048	}
1049
1050	for (i = from; i <= to; i++) {
1051		if (!dolist(pvars, assoc_cache[i].assid, CTL_OP_READVAR,
1052			    TYPE_PEER, fp))
1053			break;
1054	}
1055
1056	if (pvars == tmplist)
1057		doclearvlist(tmplist);
1058
1059	return;
1060}
1061
1062
1063/*
1064 * dogetassoc - query the host for its list of associations
1065 */
1066int
1067dogetassoc(
1068	FILE *fp
1069	)
1070{
1071	const char *datap;
1072	const u_short *pus;
1073	int res;
1074	int dsize;
1075	u_short rstatus;
1076
1077	res = doquery(CTL_OP_READSTAT, 0, 0, 0, (char *)0, &rstatus,
1078			  &dsize, &datap);
1079
1080	if (res != 0)
1081		return 0;
1082
1083	if (dsize == 0) {
1084		if (numhosts > 1)
1085			fprintf(fp, "server=%s ", currenthost);
1086		fprintf(fp, "No association ID's returned\n");
1087		return 0;
1088	}
1089
1090	if (dsize & 0x3) {
1091		if (numhosts > 1)
1092			fprintf(stderr, "server=%s ", currenthost);
1093		fprintf(stderr,
1094			"***Server returned %d octets, should be multiple of 4\n",
1095			dsize);
1096		return 0;
1097	}
1098
1099	numassoc = 0;
1100
1101	while (dsize > 0) {
1102		if (numassoc >= assoc_cache_slots) {
1103			grow_assoc_cache();
1104		}
1105		pus = (const void *)datap;
1106		assoc_cache[numassoc].assid = ntohs(*pus);
1107		datap += sizeof(*pus);
1108		pus = (const void *)datap;
1109		assoc_cache[numassoc].status = ntohs(*pus);
1110		datap += sizeof(*pus);
1111		dsize -= 2 * sizeof(*pus);
1112		if (debug) {
1113			fprintf(stderr, "[%u] ",
1114				assoc_cache[numassoc].assid);
1115		}
1116		numassoc++;
1117	}
1118	if (debug) {
1119		fprintf(stderr, "\n%d associations total\n", numassoc);
1120	}
1121	sortassoc();
1122	return 1;
1123}
1124
1125
1126/*
1127 * printassoc - print the current list of associations
1128 */
1129static void
1130printassoc(
1131	int showall,
1132	FILE *fp
1133	)
1134{
1135	register char *bp;
1136	u_int i;
1137	u_char statval;
1138	int event;
1139	u_long event_count;
1140	const char *conf;
1141	const char *reach;
1142	const char *auth;
1143	const char *condition = "";
1144	const char *last_event;
1145	char buf[128];
1146
1147	if (numassoc == 0) {
1148		(void) fprintf(fp, "No association ID's in list\n");
1149		return;
1150	}
1151
1152	/*
1153	 * Output a header
1154	 */
1155	(void) fprintf(fp,
1156			   "\nind assid status  conf reach auth condition  last_event cnt\n");
1157	(void) fprintf(fp,
1158			   "===========================================================\n");
1159	for (i = 0; i < numassoc; i++) {
1160		statval = (u_char) CTL_PEER_STATVAL(assoc_cache[i].status);
1161		if (!showall && !(statval & (CTL_PST_CONFIG|CTL_PST_REACH)))
1162			continue;
1163		event = CTL_PEER_EVENT(assoc_cache[i].status);
1164		event_count = CTL_PEER_NEVNT(assoc_cache[i].status);
1165		if (statval & CTL_PST_CONFIG)
1166			conf = "yes";
1167		else
1168			conf = "no";
1169		if (statval & CTL_PST_BCAST) {
1170			reach = "none";
1171			if (statval & CTL_PST_AUTHENABLE)
1172				auth = "yes";
1173			else
1174				auth = "none";
1175		} else {
1176			if (statval & CTL_PST_REACH)
1177				reach = "yes";
1178			else
1179				reach = "no";
1180			if (statval & CTL_PST_AUTHENABLE) {
1181				if (statval & CTL_PST_AUTHENTIC)
1182					auth = "ok ";
1183				else
1184					auth = "bad";
1185			} else {
1186				auth = "none";
1187			}
1188		}
1189		if (pktversion > NTP_OLDVERSION) {
1190			switch (statval & 0x7) {
1191
1192			case CTL_PST_SEL_REJECT:
1193				condition = "reject";
1194				break;
1195
1196			case CTL_PST_SEL_SANE:
1197				condition = "falsetick";
1198				break;
1199
1200			case CTL_PST_SEL_CORRECT:
1201				condition = "excess";
1202				break;
1203
1204			case CTL_PST_SEL_SELCAND:
1205				condition = "outlier";
1206				break;
1207
1208			case CTL_PST_SEL_SYNCCAND:
1209				condition = "candidate";
1210				break;
1211
1212			case CTL_PST_SEL_EXCESS:
1213				condition = "backup";
1214				break;
1215
1216			case CTL_PST_SEL_SYSPEER:
1217				condition = "sys.peer";
1218				break;
1219
1220			case CTL_PST_SEL_PPS:
1221				condition = "pps.peer";
1222				break;
1223			}
1224		} else {
1225			switch (statval & 0x3) {
1226
1227			case OLD_CTL_PST_SEL_REJECT:
1228				if (!(statval & OLD_CTL_PST_SANE))
1229					condition = "insane";
1230				else if (!(statval & OLD_CTL_PST_DISP))
1231					condition = "hi_disp";
1232				else
1233					condition = "";
1234				break;
1235
1236			case OLD_CTL_PST_SEL_SELCAND:
1237				condition = "sel_cand";
1238				break;
1239
1240			case OLD_CTL_PST_SEL_SYNCCAND:
1241				condition = "sync_cand";
1242				break;
1243
1244			case OLD_CTL_PST_SEL_SYSPEER:
1245				condition = "sys_peer";
1246				break;
1247			}
1248		}
1249		switch (PEER_EVENT|event) {
1250
1251		case PEVNT_MOBIL:
1252			last_event = "mobilize";
1253			break;
1254
1255		case PEVNT_DEMOBIL:
1256			last_event = "demobilize";
1257			break;
1258
1259		case PEVNT_REACH:
1260			last_event = "reachable";
1261			break;
1262
1263		case PEVNT_UNREACH:
1264			last_event = "unreachable";
1265			break;
1266
1267		case PEVNT_RESTART:
1268			last_event = "restart";
1269			break;
1270
1271		case PEVNT_REPLY:
1272			last_event = "no_reply";
1273			break;
1274
1275		case PEVNT_RATE:
1276			last_event = "rate_exceeded";
1277			break;
1278
1279		case PEVNT_DENY:
1280			last_event = "access_denied";
1281			break;
1282
1283		case PEVNT_ARMED:
1284			last_event = "leap_armed";
1285			break;
1286
1287		case PEVNT_NEWPEER:
1288			last_event = "sys_peer";
1289			break;
1290
1291		case PEVNT_CLOCK:
1292			last_event = "clock_alarm";
1293			break;
1294
1295		default:
1296			last_event = "";
1297			break;
1298		}
1299		snprintf(buf, sizeof(buf),
1300			 "%3d %5u  %04x   %3.3s  %4s  %4.4s %9.9s %11s %2lu",
1301			 i + 1, assoc_cache[i].assid,
1302			 assoc_cache[i].status, conf, reach, auth,
1303			 condition, last_event, event_count);
1304		bp = buf + strlen(buf);
1305		while (bp > buf && ' ' == bp[-1])
1306			--bp;
1307		bp[0] = '\0';
1308		fprintf(fp, "%s\n", buf);
1309	}
1310}
1311
1312
1313/*
1314 * associations - get, record and print a list of associations
1315 */
1316/*ARGSUSED*/
1317static void
1318associations(
1319	struct parse *pcmd,
1320	FILE *fp
1321	)
1322{
1323	if (dogetassoc(fp))
1324		printassoc(0, fp);
1325}
1326
1327
1328/*
1329 * lassociations - get, record and print a long list of associations
1330 */
1331/*ARGSUSED*/
1332static void
1333lassociations(
1334	struct parse *pcmd,
1335	FILE *fp
1336	)
1337{
1338	if (dogetassoc(fp))
1339		printassoc(1, fp);
1340}
1341
1342
1343/*
1344 * passociations - print the association list
1345 */
1346/*ARGSUSED*/
1347static void
1348passociations(
1349	struct parse *pcmd,
1350	FILE *fp
1351	)
1352{
1353	printassoc(0, fp);
1354}
1355
1356
1357/*
1358 * lpassociations - print the long association list
1359 */
1360/*ARGSUSED*/
1361static void
1362lpassociations(
1363	struct parse *pcmd,
1364	FILE *fp
1365	)
1366{
1367	printassoc(1, fp);
1368}
1369
1370
1371/*
1372 *  saveconfig - dump ntp server configuration to server file
1373 */
1374static void
1375saveconfig(
1376	struct parse *pcmd,
1377	FILE *fp
1378	)
1379{
1380	const char *datap;
1381	int res;
1382	int dsize;
1383	u_short rstatus;
1384
1385	if (0 == pcmd->nargs)
1386		return;
1387
1388	res = doquery(CTL_OP_SAVECONFIG, 0, 1,
1389		      strlen(pcmd->argval[0].string),
1390		      pcmd->argval[0].string, &rstatus, &dsize,
1391		      &datap);
1392
1393	if (res != 0)
1394		return;
1395
1396	if (0 == dsize)
1397		fprintf(fp, "(no response message, curiously)");
1398	else
1399		fprintf(fp, "%.*s", dsize, datap);
1400}
1401
1402
1403#ifdef	UNUSED
1404/*
1405 * radiostatus - print the radio status returned by the server
1406 */
1407/*ARGSUSED*/
1408static void
1409radiostatus(
1410	struct parse *pcmd,
1411	FILE *fp
1412	)
1413{
1414	char *datap;
1415	int res;
1416	int dsize;
1417	u_short rstatus;
1418
1419	res = doquery(CTL_OP_READCLOCK, 0, 0, 0, (char *)0, &rstatus,
1420			  &dsize, &datap);
1421
1422	if (res != 0)
1423		return;
1424
1425	if (numhosts > 1)
1426		(void) fprintf(fp, "server=%s ", currenthost);
1427	if (dsize == 0) {
1428		(void) fprintf(fp, "No radio status string returned\n");
1429		return;
1430	}
1431
1432	asciize(dsize, datap, fp);
1433}
1434#endif	/* UNUSED */
1435
1436/*
1437 * when - print how long its been since his last packet arrived
1438 */
1439static long
1440when(
1441	l_fp *ts,
1442	l_fp *rec,
1443	l_fp *reftime
1444	)
1445{
1446	l_fp *lasttime;
1447
1448	if (rec->l_ui != 0)
1449		lasttime = rec;
1450	else if (reftime->l_ui != 0)
1451		lasttime = reftime;
1452	else
1453		return 0;
1454
1455	return (ts->l_ui - lasttime->l_ui);
1456}
1457
1458
1459/*
1460 * Pretty-print an interval into the given buffer, in a human-friendly format.
1461 */
1462static char *
1463prettyinterval(
1464	char *buf,
1465	size_t cb,
1466	long diff
1467	)
1468{
1469	if (diff <= 0) {
1470		buf[0] = '-';
1471		buf[1] = 0;
1472		return buf;
1473	}
1474
1475	if (diff <= 2048) {
1476		snprintf(buf, cb, "%ld", diff);
1477		return buf;
1478	}
1479
1480	diff = (diff + 29) / 60;
1481	if (diff <= 300) {
1482		snprintf(buf, cb, "%ldm", diff);
1483		return buf;
1484	}
1485
1486	diff = (diff + 29) / 60;
1487	if (diff <= 96) {
1488		snprintf(buf, cb, "%ldh", diff);
1489		return buf;
1490	}
1491
1492	diff = (diff + 11) / 24;
1493	snprintf(buf, cb, "%ldd", diff);
1494	return buf;
1495}
1496
1497static char
1498decodeaddrtype(
1499	sockaddr_u *sock
1500	)
1501{
1502	char ch = '-';
1503	u_int32 dummy;
1504
1505	switch(AF(sock)) {
1506	case AF_INET:
1507		dummy = SRCADR(sock);
1508		ch = (char)(((dummy&0xf0000000)==0xe0000000) ? 'm' :
1509			((dummy&0x000000ff)==0x000000ff) ? 'b' :
1510			((dummy&0xffffffff)==0x7f000001) ? 'l' :
1511			((dummy&0xffffffe0)==0x00000000) ? '-' :
1512			'u');
1513		break;
1514	case AF_INET6:
1515		if (IN6_IS_ADDR_MULTICAST(PSOCK_ADDR6(sock)))
1516			ch = 'm';
1517		else
1518			ch = 'u';
1519		break;
1520	default:
1521		ch = '-';
1522		break;
1523	}
1524	return ch;
1525}
1526
1527/*
1528 * A list of variables required by the peers command
1529 */
1530struct varlist opeervarlist[] = {
1531	{ "srcadr",	0 },	/* 0 */
1532	{ "dstadr",	0 },	/* 1 */
1533	{ "stratum",	0 },	/* 2 */
1534	{ "hpoll",	0 },	/* 3 */
1535	{ "ppoll",	0 },	/* 4 */
1536	{ "reach",	0 },	/* 5 */
1537	{ "delay",	0 },	/* 6 */
1538	{ "offset",	0 },	/* 7 */
1539	{ "jitter",	0 },	/* 8 */
1540	{ "dispersion", 0 },	/* 9 */
1541	{ "rec",	0 },	/* 10 */
1542	{ "reftime",	0 },	/* 11 */
1543	{ "srcport",	0 },	/* 12 */
1544	{ "hmode",	0 },	/* 13 */
1545	{ 0,		0 }
1546};
1547
1548struct varlist peervarlist[] = {
1549	{ "srcadr",	0 },	/* 0 */
1550	{ "refid",	0 },	/* 1 */
1551	{ "stratum",	0 },	/* 2 */
1552	{ "hpoll",	0 },	/* 3 */
1553	{ "ppoll",	0 },	/* 4 */
1554	{ "reach",	0 },	/* 5 */
1555	{ "delay",	0 },	/* 6 */
1556	{ "offset",	0 },	/* 7 */
1557	{ "jitter",	0 },	/* 8 */
1558	{ "dispersion", 0 },	/* 9 */
1559	{ "rec",	0 },	/* 10 */
1560	{ "reftime",	0 },	/* 11 */
1561	{ "srcport",	0 },	/* 12 */
1562	{ "hmode",	0 },	/* 13 */
1563	{ "srchost",	0 },	/* 14 */
1564	{ 0,		0 }
1565};
1566
1567struct varlist apeervarlist[] = {
1568	{ "srcadr",	0 },	/* 0 */
1569	{ "refid",	0 },	/* 1 */
1570	{ "assid",	0 },	/* 2 */
1571	{ "stratum",	0 },	/* 3 */
1572	{ "hpoll",	0 },	/* 4 */
1573	{ "ppoll",	0 },	/* 5 */
1574	{ "reach",	0 },	/* 6 */
1575	{ "delay",	0 },	/* 7 */
1576	{ "offset",	0 },	/* 8 */
1577	{ "jitter",	0 },	/* 9 */
1578	{ "dispersion", 0 },	/* 10 */
1579	{ "rec",	0 },	/* 11 */
1580	{ "reftime",	0 },	/* 12 */
1581	{ "srcport",	0 },	/* 13 */
1582	{ "hmode",	0 },	/* 14 */
1583	{ "srchost",	0 },	/* 15 */
1584	{ 0,		0 }
1585};
1586
1587
1588/*
1589 * Decode an incoming data buffer and print a line in the peer list
1590 */
1591static int
1592doprintpeers(
1593	struct varlist *pvl,
1594	int associd,
1595	int rstatus,
1596	int datalen,
1597	const char *data,
1598	FILE *fp,
1599	int af
1600	)
1601{
1602	char *name;
1603	char *value = NULL;
1604	int c;
1605	int len;
1606	int have_srchost;
1607	int have_dstadr;
1608	int have_da_rid;
1609	int have_jitter;
1610	sockaddr_u srcadr;
1611	sockaddr_u dstadr;
1612	sockaddr_u dum_store;
1613	sockaddr_u refidadr;
1614	long hmode = 0;
1615	u_long srcport = 0;
1616	u_int32 u32;
1617	const char *dstadr_refid = "0.0.0.0";
1618	const char *serverlocal;
1619	size_t drlen;
1620	u_long stratum = 0;
1621	long ppoll = 0;
1622	long hpoll = 0;
1623	u_long reach = 0;
1624	l_fp estoffset;
1625	l_fp estdelay;
1626	l_fp estjitter;
1627	l_fp estdisp;
1628	l_fp reftime;
1629	l_fp rec;
1630	l_fp ts;
1631	u_long poll_sec;
1632	char type = '?';
1633	char whenbuf[8], pollbuf[8];
1634	char clock_name[LENHOSTNAME];
1635
1636	get_systime(&ts);
1637
1638	have_srchost = FALSE;
1639	have_dstadr = FALSE;
1640	have_da_rid = FALSE;
1641	have_jitter = FALSE;
1642	ZERO_SOCK(&srcadr);
1643	ZERO_SOCK(&dstadr);
1644	clock_name[0] = '\0';
1645	ZERO(estoffset);
1646	ZERO(estdelay);
1647	ZERO(estjitter);
1648	ZERO(estdisp);
1649
1650	while (nextvar(&datalen, &data, &name, &value)) {
1651		if (!strcmp("srcadr", name) ||
1652		    !strcmp("peeradr", name)) {
1653			if (!decodenetnum(value, &srcadr))
1654				fprintf(stderr, "malformed %s=%s\n",
1655					name, value);
1656		} else if (!strcmp("srchost", name)) {
1657			if (pvl == peervarlist || pvl == apeervarlist) {
1658				len = strlen(value);
1659				if (2 < len &&
1660				    (size_t)len < sizeof(clock_name)) {
1661					/* strip quotes */
1662					value++;
1663					len -= 2;
1664					memcpy(clock_name, value, len);
1665					clock_name[len] = '\0';
1666					have_srchost = TRUE;
1667				}
1668			}
1669		} else if (!strcmp("dstadr", name)) {
1670			if (decodenetnum(value, &dum_store)) {
1671				type = decodeaddrtype(&dum_store);
1672				have_dstadr = TRUE;
1673				dstadr = dum_store;
1674				if (pvl == opeervarlist) {
1675					have_da_rid = TRUE;
1676					dstadr_refid = trunc_left(stoa(&dstadr), 15);
1677				}
1678			}
1679		} else if (!strcmp("hmode", name)) {
1680			decodeint(value, &hmode);
1681		} else if (!strcmp("refid", name)) {
1682			if (pvl == peervarlist) {
1683				have_da_rid = TRUE;
1684				drlen = strlen(value);
1685				if (0 == drlen) {
1686					dstadr_refid = "";
1687				} else if (drlen <= 4) {
1688					ZERO(u32);
1689					memcpy(&u32, value, drlen);
1690					dstadr_refid = refid_str(u32, 1);
1691				} else if (decodenetnum(value, &refidadr)) {
1692					if (SOCK_UNSPEC(&refidadr))
1693						dstadr_refid = "0.0.0.0";
1694					else if (ISREFCLOCKADR(&refidadr))
1695						dstadr_refid =
1696						    refnumtoa(&refidadr);
1697					else
1698						dstadr_refid =
1699						    stoa(&refidadr);
1700				} else {
1701					have_da_rid = FALSE;
1702				}
1703			} else if (pvl == apeervarlist) {
1704				have_da_rid = TRUE;
1705				drlen = strlen(value);
1706				if (0 == drlen) {
1707					dstadr_refid = "";
1708				} else if (drlen <= 4) {
1709					ZERO(u32);
1710					memcpy(&u32, value, drlen);
1711					dstadr_refid = refid_str(u32, 1);
1712					//fprintf(stderr, "apeervarlist S1 refid: value=<%s>\n", value);
1713				} else if (decodenetnum(value, &refidadr)) {
1714					if (SOCK_UNSPEC(&refidadr))
1715						dstadr_refid = "0.0.0.0";
1716					else if (ISREFCLOCKADR(&refidadr))
1717						dstadr_refid =
1718						    refnumtoa(&refidadr);
1719					else {
1720						char *buf = emalloc(10);
1721						int i = ntohl(refidadr.sa4.sin_addr.s_addr);
1722
1723						snprintf(buf, 10,
1724							"%0x", i);
1725						dstadr_refid = buf;
1726					//fprintf(stderr, "apeervarlist refid: value=<%x>\n", i);
1727					}
1728					//fprintf(stderr, "apeervarlist refid: value=<%s>\n", value);
1729				} else {
1730					have_da_rid = FALSE;
1731				}
1732			}
1733		} else if (!strcmp("stratum", name)) {
1734			decodeuint(value, &stratum);
1735		} else if (!strcmp("hpoll", name)) {
1736			if (decodeint(value, &hpoll) && hpoll < 0)
1737				hpoll = NTP_MINPOLL;
1738		} else if (!strcmp("ppoll", name)) {
1739			if (decodeint(value, &ppoll) && ppoll < 0)
1740				ppoll = NTP_MINPOLL;
1741		} else if (!strcmp("reach", name)) {
1742			decodeuint(value, &reach);
1743		} else if (!strcmp("delay", name)) {
1744			decodetime(value, &estdelay);
1745		} else if (!strcmp("offset", name)) {
1746			decodetime(value, &estoffset);
1747		} else if (!strcmp("jitter", name)) {
1748			if ((pvl == peervarlist || pvl == apeervarlist)
1749			    && decodetime(value, &estjitter))
1750				have_jitter = 1;
1751		} else if (!strcmp("rootdisp", name) ||
1752			   !strcmp("dispersion", name)) {
1753			decodetime(value, &estdisp);
1754		} else if (!strcmp("rec", name)) {
1755			decodets(value, &rec);
1756		} else if (!strcmp("srcport", name) ||
1757			   !strcmp("peerport", name)) {
1758			decodeuint(value, &srcport);
1759		} else if (!strcmp("reftime", name)) {
1760			if (!decodets(value, &reftime))
1761				L_CLR(&reftime);
1762		} else {
1763			// fprintf(stderr, "UNRECOGNIZED name=%s ", name);
1764		}
1765	}
1766
1767	/*
1768	 * hmode gives the best guidance for the t column.  If the response
1769	 * did not include hmode we'll use the old decodeaddrtype() result.
1770	 */
1771	switch (hmode) {
1772
1773	case MODE_BCLIENT:
1774		/* broadcastclient or multicastclient */
1775		type = 'b';
1776		break;
1777
1778	case MODE_BROADCAST:
1779		/* broadcast or multicast server */
1780		if (IS_MCAST(&srcadr))
1781			type = 'M';
1782		else
1783			type = 'B';
1784		break;
1785
1786	case MODE_CLIENT:
1787		if (ISREFCLOCKADR(&srcadr))
1788			type = 'l';	/* local refclock*/
1789		else if (SOCK_UNSPEC(&srcadr))
1790			type = 'p';	/* pool */
1791		else if (IS_MCAST(&srcadr))
1792			type = 'a';	/* manycastclient */
1793		else
1794			type = 'u';	/* unicast */
1795		break;
1796
1797	case MODE_ACTIVE:
1798		type = 's';		/* symmetric active */
1799		break;			/* configured */
1800
1801	case MODE_PASSIVE:
1802		type = 'S';		/* symmetric passive */
1803		break;			/* ephemeral */
1804	}
1805
1806	/*
1807	 * Got everything, format the line
1808	 */
1809	poll_sec = 1 << min(ppoll, hpoll);
1810	if (pktversion > NTP_OLDVERSION)
1811		c = flash3[CTL_PEER_STATVAL(rstatus) & 0x7];
1812	else
1813		c = flash2[CTL_PEER_STATVAL(rstatus) & 0x3];
1814	if (numhosts > 1) {
1815		if ((pvl == peervarlist || pvl == apeervarlist)
1816		    && have_dstadr) {
1817			serverlocal = nntohost_col(&dstadr,
1818			    (size_t)min(LIB_BUFLENGTH - 1, maxhostlen),
1819			    TRUE);
1820		} else {
1821			if (currenthostisnum)
1822				serverlocal = trunc_left(currenthost,
1823							 maxhostlen);
1824			else
1825				serverlocal = currenthost;
1826		}
1827		fprintf(fp, "%-*s ", (int)maxhostlen, serverlocal);
1828	}
1829	if (AF_UNSPEC == af || AF(&srcadr) == af) {
1830		if (!have_srchost)
1831			strlcpy(clock_name, nntohost(&srcadr),
1832				sizeof(clock_name));
1833		if (wideremote && 15 < strlen(clock_name))
1834			fprintf(fp, "%c%s\n                 ", c, clock_name);
1835		else
1836			fprintf(fp, "%c%-15.15s ", c, clock_name);
1837		if (!have_da_rid) {
1838			drlen = 0;
1839		} else {
1840			drlen = strlen(dstadr_refid);
1841			makeascii(drlen, dstadr_refid, fp);
1842		}
1843		if (pvl == apeervarlist) {
1844			while (drlen++ < 9)
1845				fputc(' ', fp);
1846			fprintf(fp, "%-6d", associd);
1847		} else {
1848			while (drlen++ < 15)
1849				fputc(' ', fp);
1850		}
1851		fprintf(fp,
1852			" %2ld %c %4.4s %4.4s  %3lo  %7.7s %8.7s %7.7s\n",
1853			stratum, type,
1854			prettyinterval(whenbuf, sizeof(whenbuf),
1855				       when(&ts, &rec, &reftime)),
1856			prettyinterval(pollbuf, sizeof(pollbuf),
1857				       (int)poll_sec),
1858			reach, lfptoms(&estdelay, 3),
1859			lfptoms(&estoffset, 3),
1860			(have_jitter)
1861			    ? lfptoms(&estjitter, 3)
1862			    : lfptoms(&estdisp, 3));
1863		return (1);
1864	}
1865	else
1866		return(1);
1867}
1868
1869
1870/*
1871 * dogetpeers - given an association ID, read and print the spreadsheet
1872 *		peer variables.
1873 */
1874static int
1875dogetpeers(
1876	struct varlist *pvl,
1877	associd_t associd,
1878	FILE *fp,
1879	int af
1880	)
1881{
1882	const char *datap;
1883	int res;
1884	int dsize;
1885	u_short rstatus;
1886
1887#ifdef notdef
1888	res = doquerylist(pvl, CTL_OP_READVAR, associd, 0, &rstatus,
1889			  &dsize, &datap);
1890#else
1891	/*
1892	 * Damn fuzzballs
1893	 */
1894	res = doquery(CTL_OP_READVAR, associd, 0, 0, NULL, &rstatus,
1895			  &dsize, &datap);
1896#endif
1897
1898	if (res != 0)
1899		return 0;
1900
1901	if (dsize == 0) {
1902		if (numhosts > 1)
1903			fprintf(stderr, "server=%s ", currenthost);
1904		fprintf(stderr,
1905			"***No information returned for association %u\n",
1906			associd);
1907		return 0;
1908	}
1909
1910	return doprintpeers(pvl, associd, (int)rstatus, dsize, datap,
1911			    fp, af);
1912}
1913
1914
1915/*
1916 * peers - print a peer spreadsheet
1917 */
1918static void
1919dopeers(
1920	int showall,
1921	FILE *fp,
1922	int af
1923	)
1924{
1925	u_int		u;
1926	char		fullname[LENHOSTNAME];
1927	sockaddr_u	netnum;
1928	const char *	name_or_num;
1929	size_t		sl;
1930
1931	if (!dogetassoc(fp))
1932		return;
1933
1934	for (u = 0; u < numhosts; u++) {
1935		if (getnetnum(chosts[u].name, &netnum, fullname, af)) {
1936			name_or_num = nntohost(&netnum);
1937			sl = strlen(name_or_num);
1938			maxhostlen = max(maxhostlen, sl);
1939		}
1940	}
1941	if (numhosts > 1)
1942		fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
1943			"server (local)");
1944	fprintf(fp,
1945		"     remote           refid      st t when poll reach   delay   offset  jitter\n");
1946	if (numhosts > 1)
1947		for (u = 0; u <= maxhostlen; u++)
1948			fprintf(fp, "=");
1949	fprintf(fp,
1950		"==============================================================================\n");
1951
1952	for (u = 0; u < numassoc; u++) {
1953		if (!showall &&
1954		    !(CTL_PEER_STATVAL(assoc_cache[u].status)
1955		      & (CTL_PST_CONFIG|CTL_PST_REACH))) {
1956			if (debug)
1957				fprintf(stderr, "eliding [%d]\n",
1958					(int)assoc_cache[u].assid);
1959			continue;
1960		}
1961		if (!dogetpeers(peervarlist, (int)assoc_cache[u].assid,
1962				fp, af))
1963			return;
1964	}
1965	return;
1966}
1967
1968
1969/*
1970 * doapeers - print a peer spreadsheet with assocIDs
1971 */
1972static void
1973doapeers(
1974	int showall,
1975	FILE *fp,
1976	int af
1977	)
1978{
1979	u_int		u;
1980	char		fullname[LENHOSTNAME];
1981	sockaddr_u	netnum;
1982	const char *	name_or_num;
1983	size_t		sl;
1984
1985	if (!dogetassoc(fp))
1986		return;
1987
1988	for (u = 0; u < numhosts; u++) {
1989		if (getnetnum(chosts[u].name, &netnum, fullname, af)) {
1990			name_or_num = nntohost(&netnum);
1991			sl = strlen(name_or_num);
1992			maxhostlen = max(maxhostlen, sl);
1993		}
1994	}
1995	if (numhosts > 1)
1996		fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
1997			"server (local)");
1998	fprintf(fp,
1999		"     remote       refid   assid  st t when poll reach   delay   offset  jitter\n");
2000	if (numhosts > 1)
2001		for (u = 0; u <= maxhostlen; u++)
2002			fprintf(fp, "=");
2003	fprintf(fp,
2004		"==============================================================================\n");
2005
2006	for (u = 0; u < numassoc; u++) {
2007		if (!showall &&
2008		    !(CTL_PEER_STATVAL(assoc_cache[u].status)
2009		      & (CTL_PST_CONFIG|CTL_PST_REACH))) {
2010			if (debug)
2011				fprintf(stderr, "eliding [%d]\n",
2012					(int)assoc_cache[u].assid);
2013			continue;
2014		}
2015		if (!dogetpeers(apeervarlist, (int)assoc_cache[u].assid,
2016				fp, af))
2017			return;
2018	}
2019	return;
2020}
2021
2022
2023/*
2024 * peers - print a peer spreadsheet
2025 */
2026/*ARGSUSED*/
2027static void
2028peers(
2029	struct parse *pcmd,
2030	FILE *fp
2031	)
2032{
2033	int af = 0;
2034
2035	if (pcmd->nargs == 1) {
2036		if (pcmd->argval->ival == 6)
2037			af = AF_INET6;
2038		else
2039			af = AF_INET;
2040	}
2041	dopeers(0, fp, af);
2042}
2043
2044
2045/*
2046 * apeers - print a peer spreadsheet, with assocIDs
2047 */
2048/*ARGSUSED*/
2049static void
2050apeers(
2051	struct parse *pcmd,
2052	FILE *fp
2053	)
2054{
2055	int af = 0;
2056
2057	if (pcmd->nargs == 1) {
2058		if (pcmd->argval->ival == 6)
2059			af = AF_INET6;
2060		else
2061			af = AF_INET;
2062	}
2063	doapeers(0, fp, af);
2064}
2065
2066
2067/*
2068 * lpeers - print a peer spreadsheet including all fuzzball peers
2069 */
2070/*ARGSUSED*/
2071static void
2072lpeers(
2073	struct parse *pcmd,
2074	FILE *fp
2075	)
2076{
2077	int af = 0;
2078
2079	if (pcmd->nargs == 1) {
2080		if (pcmd->argval->ival == 6)
2081			af = AF_INET6;
2082		else
2083			af = AF_INET;
2084	}
2085	dopeers(1, fp, af);
2086}
2087
2088
2089/*
2090 * opeers - print a peer spreadsheet
2091 */
2092static void
2093doopeers(
2094	int showall,
2095	FILE *fp,
2096	int af
2097	)
2098{
2099	u_int i;
2100	char fullname[LENHOSTNAME];
2101	sockaddr_u netnum;
2102
2103	if (!dogetassoc(fp))
2104		return;
2105
2106	for (i = 0; i < numhosts; ++i) {
2107		if (getnetnum(chosts[i].name, &netnum, fullname, af))
2108			if (strlen(fullname) > maxhostlen)
2109				maxhostlen = strlen(fullname);
2110	}
2111	if (numhosts > 1)
2112		fprintf(fp, "%-*.*s ", (int)maxhostlen, (int)maxhostlen,
2113			"server");
2114	fprintf(fp,
2115	    "     remote           local      st t when poll reach   delay   offset    disp\n");
2116	if (numhosts > 1)
2117		for (i = 0; i <= maxhostlen; ++i)
2118			fprintf(fp, "=");
2119	fprintf(fp,
2120	    "==============================================================================\n");
2121
2122	for (i = 0; i < numassoc; i++) {
2123		if (!showall &&
2124		    !(CTL_PEER_STATVAL(assoc_cache[i].status) &
2125		      (CTL_PST_CONFIG | CTL_PST_REACH)))
2126			continue;
2127		if (!dogetpeers(opeervarlist, assoc_cache[i].assid, fp, af))
2128			return;
2129	}
2130	return;
2131}
2132
2133
2134/*
2135 * opeers - print a peer spreadsheet the old way
2136 */
2137/*ARGSUSED*/
2138static void
2139opeers(
2140	struct parse *pcmd,
2141	FILE *fp
2142	)
2143{
2144	int af = 0;
2145
2146	if (pcmd->nargs == 1) {
2147		if (pcmd->argval->ival == 6)
2148			af = AF_INET6;
2149		else
2150			af = AF_INET;
2151	}
2152	doopeers(0, fp, af);
2153}
2154
2155
2156/*
2157 * lopeers - print a peer spreadsheet including all fuzzball peers
2158 */
2159/*ARGSUSED*/
2160static void
2161lopeers(
2162	struct parse *pcmd,
2163	FILE *fp
2164	)
2165{
2166	int af = 0;
2167
2168	if (pcmd->nargs == 1) {
2169		if (pcmd->argval->ival == 6)
2170			af = AF_INET6;
2171		else
2172			af = AF_INET;
2173	}
2174	doopeers(1, fp, af);
2175}
2176
2177
2178/*
2179 * config - send a configuration command to a remote host
2180 */
2181static void
2182config (
2183	struct parse *pcmd,
2184	FILE *fp
2185	)
2186{
2187	const char *cfgcmd;
2188	u_short rstatus;
2189	int rsize;
2190	const char *rdata;
2191	char *resp;
2192	int res;
2193	int col;
2194	int i;
2195
2196	cfgcmd = pcmd->argval[0].string;
2197
2198	if (debug > 2)
2199		fprintf(stderr,
2200			"In Config\n"
2201			"Keyword = %s\n"
2202			"Command = %s\n", pcmd->keyword, cfgcmd);
2203
2204	res = doquery(CTL_OP_CONFIGURE, 0, 1, strlen(cfgcmd), cfgcmd,
2205		      &rstatus, &rsize, &rdata);
2206
2207	if (res != 0)
2208		return;
2209
2210	if (rsize > 0 && '\n' == rdata[rsize - 1])
2211		rsize--;
2212
2213	resp = emalloc(rsize + 1);
2214	memcpy(resp, rdata, rsize);
2215	resp[rsize] = '\0';
2216
2217	col = -1;
2218	if (1 == sscanf(resp, "column %d syntax error", &col)
2219	    && col >= 0 && (size_t)col <= strlen(cfgcmd) + 1) {
2220		if (interactive) {
2221			printf("______");	/* "ntpq> " */
2222			printf("________");	/* ":config " */
2223		} else
2224			printf("%s\n", cfgcmd);
2225		for (i = 1; i < col; i++)
2226			putchar('_');
2227		printf("^\n");
2228	}
2229	printf("%s\n", resp);
2230	free(resp);
2231}
2232
2233
2234/*
2235 * config_from_file - remotely configure an ntpd daemon using the
2236 * specified configuration file
2237 * SK: This function is a kludge at best and is full of bad design
2238 * bugs:
2239 * 1. ntpq uses UDP, which means that there is no guarantee of in-order,
2240 *    error-free delivery.
2241 * 2. The maximum length of a packet is constrained, and as a result, the
2242 *    maximum length of a line in a configuration file is constrained.
2243 *    Longer lines will lead to unpredictable results.
2244 * 3. Since this function is sending a line at a time, we can't update
2245 *    the control key through the configuration file (YUCK!!)
2246 */
2247static void
2248config_from_file (
2249	struct parse *pcmd,
2250	FILE *fp
2251	)
2252{
2253	u_short rstatus;
2254	int rsize;
2255	const char *rdata;
2256	int res;
2257	FILE *config_fd;
2258	char config_cmd[MAXLINE];
2259	size_t config_len;
2260	int i;
2261	int retry_limit;
2262
2263	if (debug > 2)
2264		fprintf(stderr,
2265			"In Config\n"
2266			"Keyword = %s\n"
2267			"Filename = %s\n", pcmd->keyword,
2268			pcmd->argval[0].string);
2269
2270	config_fd = fopen(pcmd->argval[0].string, "r");
2271	if (NULL == config_fd) {
2272		printf("ERROR!! Couldn't open file: %s\n",
2273		       pcmd->argval[0].string);
2274		return;
2275	}
2276
2277	printf("Sending configuration file, one line at a time.\n");
2278	i = 0;
2279	while (fgets(config_cmd, MAXLINE, config_fd) != NULL) {
2280		config_len = strlen(config_cmd);
2281		/* ensure even the last line has newline, if possible */
2282		if (config_len > 0 &&
2283		    config_len + 2 < sizeof(config_cmd) &&
2284		    '\n' != config_cmd[config_len - 1])
2285			config_cmd[config_len++] = '\n';
2286		++i;
2287		retry_limit = 2;
2288		do
2289			res = doquery(CTL_OP_CONFIGURE, 0, 1,
2290				      strlen(config_cmd), config_cmd,
2291				      &rstatus, &rsize, &rdata);
2292		while (res != 0 && retry_limit--);
2293		if (res != 0) {
2294			printf("Line No: %d query failed: %s", i,
2295			       config_cmd);
2296			printf("Subsequent lines not sent.\n");
2297			fclose(config_fd);
2298			return;
2299		}
2300
2301		if (rsize > 0 && '\n' == rdata[rsize - 1])
2302			rsize--;
2303		if (rsize > 0 && '\r' == rdata[rsize - 1])
2304			rsize--;
2305		printf("Line No: %d %.*s: %s", i, rsize, rdata,
2306		       config_cmd);
2307	}
2308	printf("Done sending file\n");
2309	fclose(config_fd);
2310}
2311
2312
2313static int
2314fetch_nonce(
2315	char *	nonce,
2316	size_t	cb_nonce
2317	)
2318{
2319	const char	nonce_eq[] = "nonce=";
2320	int		qres;
2321	u_short		rstatus;
2322	int		rsize;
2323	const char *	rdata;
2324	int		chars;
2325
2326	/*
2327	 * Retrieve a nonce specific to this client to demonstrate to
2328	 * ntpd that we're capable of receiving responses to our source
2329	 * IP address, and thereby unlikely to be forging the source.
2330	 */
2331	qres = doquery(CTL_OP_REQ_NONCE, 0, 0, 0, NULL, &rstatus,
2332		       &rsize, &rdata);
2333	if (qres) {
2334		fprintf(stderr, "nonce request failed\n");
2335		return FALSE;
2336	}
2337
2338	if ((size_t)rsize <= sizeof(nonce_eq) - 1 ||
2339	    strncmp(rdata, nonce_eq, sizeof(nonce_eq) - 1)) {
2340		fprintf(stderr, "unexpected nonce response format: %.*s\n",
2341			rsize, rdata);
2342		return FALSE;
2343	}
2344	chars = rsize - (sizeof(nonce_eq) - 1);
2345	if (chars >= (int)cb_nonce)
2346		return FALSE;
2347	memcpy(nonce, rdata + sizeof(nonce_eq) - 1, chars);
2348	nonce[chars] = '\0';
2349	while (chars > 0 &&
2350	       ('\r' == nonce[chars - 1] || '\n' == nonce[chars - 1])) {
2351		chars--;
2352		nonce[chars] = '\0';
2353	}
2354
2355	return TRUE;
2356}
2357
2358
2359/*
2360 * add_mru	Add and entry to mru list, hash table, and allocate
2361 *		and return a replacement.
2362 *		This is a helper for collect_mru_list().
2363 */
2364static mru *
2365add_mru(
2366	mru *add
2367	)
2368{
2369	u_short hash;
2370	mru *mon;
2371	mru *unlinked;
2372
2373
2374	hash = NTP_HASH_ADDR(&add->addr);
2375	/* see if we have it among previously received entries */
2376	for (mon = hash_table[hash]; mon != NULL; mon = mon->hlink)
2377		if (SOCK_EQ(&mon->addr, &add->addr))
2378			break;
2379	if (mon != NULL) {
2380		if (!L_ISGEQ(&add->first, &mon->first)) {
2381			fprintf(stderr,
2382				"add_mru duplicate %s new first ts %08x.%08x precedes prior %08x.%08x\n",
2383				sptoa(&add->addr), add->last.l_ui,
2384				add->last.l_uf, mon->last.l_ui,
2385				mon->last.l_uf);
2386			exit(1);
2387		}
2388		UNLINK_DLIST(mon, mlink);
2389		UNLINK_SLIST(unlinked, hash_table[hash], mon, hlink, mru);
2390		INSIST(unlinked == mon);
2391		mru_dupes++;
2392		TRACE(2, ("(updated from %08x.%08x) ", mon->last.l_ui,
2393		      mon->last.l_uf));
2394	}
2395	LINK_DLIST(mru_list, add, mlink);
2396	LINK_SLIST(hash_table[hash], add, hlink);
2397	TRACE(2, ("add_mru %08x.%08x c %d m %d v %d rest %x first %08x.%08x %s\n",
2398	      add->last.l_ui, add->last.l_uf, add->count,
2399	      (int)add->mode, (int)add->ver, (u_int)add->rs,
2400	      add->first.l_ui, add->first.l_uf, sptoa(&add->addr)));
2401	/* if we didn't update an existing entry, alloc replacement */
2402	if (NULL == mon) {
2403		mon = emalloc(sizeof(*mon));
2404		mru_count++;
2405	}
2406	ZERO(*mon);
2407
2408	return mon;
2409}
2410
2411
2412/* MGOT macro is specific to collect_mru_list() */
2413#define MGOT(bit)				\
2414	do {					\
2415		got |= (bit);			\
2416		if (MRU_GOT_ALL == got) {	\
2417			got = 0;		\
2418			mon = add_mru(mon);	\
2419			ci++;			\
2420		}				\
2421	} while (0)
2422
2423
2424void
2425mrulist_ctrl_c_hook(void)
2426{
2427	mrulist_interrupted = TRUE;
2428}
2429
2430
2431static int
2432collect_mru_list(
2433	const char *	parms,
2434	l_fp *		pnow
2435	)
2436{
2437	const u_int sleep_msecs = 5;
2438	static int ntpd_row_limit = MRU_ROW_LIMIT;
2439	int c_mru_l_rc;		/* this function's return code */
2440	u_char got;		/* MRU_GOT_* bits */
2441	time_t next_report;
2442	size_t cb;
2443	mru *mon;
2444	mru *head;
2445	mru *recent;
2446	int list_complete;
2447	char nonce[128];
2448	char buf[128];
2449	char req_buf[CTL_MAX_DATA_LEN];
2450	char *req;
2451	char *req_end;
2452	int chars;
2453	int qres;
2454	u_short rstatus;
2455	int rsize;
2456	const char *rdata;
2457	int limit;
2458	int frags;
2459	int cap_frags;
2460	char *tag;
2461	char *val;
2462	int si;		/* server index in response */
2463	int ci;		/* client (our) index for validation */
2464	int ri;		/* request index (.# suffix) */
2465	int mv;
2466	l_fp newest;
2467	l_fp last_older;
2468	sockaddr_u addr_older;
2469	int have_now;
2470	int have_addr_older;
2471	int have_last_older;
2472	u_int restarted_count;
2473	u_int nonce_uses;
2474	u_short hash;
2475	mru *unlinked;
2476
2477	if (!fetch_nonce(nonce, sizeof(nonce)))
2478		return FALSE;
2479
2480	nonce_uses = 0;
2481	restarted_count = 0;
2482	mru_count = 0;
2483	INIT_DLIST(mru_list, mlink);
2484	cb = NTP_HASH_SIZE * sizeof(*hash_table);
2485	INSIST(NULL == hash_table);
2486	hash_table = emalloc_zero(cb);
2487
2488	c_mru_l_rc = FALSE;
2489	list_complete = FALSE;
2490	have_now = FALSE;
2491	cap_frags = TRUE;
2492	got = 0;
2493	ri = 0;
2494	cb = sizeof(*mon);
2495	mon = emalloc_zero(cb);
2496	ZERO(*pnow);
2497	ZERO(last_older);
2498	mrulist_interrupted = FALSE;
2499	set_ctrl_c_hook(&mrulist_ctrl_c_hook);
2500	fprintf(stderr,
2501		"Ctrl-C will stop MRU retrieval and display partial results.\n");
2502	fflush(stderr);
2503	next_report = time(NULL) + MRU_REPORT_SECS;
2504
2505	limit = min(3 * MAXFRAGS, ntpd_row_limit);
2506	frags = MAXFRAGS;
2507	snprintf(req_buf, sizeof(req_buf), "nonce=%s, frags=%d%s",
2508		 nonce, frags, parms);
2509	nonce_uses++;
2510
2511	while (TRUE) {
2512		if (debug)
2513			fprintf(stderr, "READ_MRU parms: %s\n", req_buf);
2514
2515		qres = doqueryex(CTL_OP_READ_MRU, 0, 0, strlen(req_buf),
2516			         req_buf, &rstatus, &rsize, &rdata, TRUE);
2517
2518		if (CERR_UNKNOWNVAR == qres && ri > 0) {
2519			/*
2520			 * None of the supplied prior entries match, so
2521			 * toss them from our list and try again.
2522			 */
2523			if (debug)
2524				fprintf(stderr,
2525					"no overlap between %d prior entries and server MRU list\n",
2526					ri);
2527			while (ri--) {
2528				recent = HEAD_DLIST(mru_list, mlink);
2529				INSIST(recent != NULL);
2530				if (debug)
2531					fprintf(stderr,
2532						"tossing prior entry %s to resync\n",
2533						sptoa(&recent->addr));
2534				UNLINK_DLIST(recent, mlink);
2535				hash = NTP_HASH_ADDR(&recent->addr);
2536				UNLINK_SLIST(unlinked, hash_table[hash],
2537					     recent, hlink, mru);
2538				INSIST(unlinked == recent);
2539				free(recent);
2540				mru_count--;
2541			}
2542			if (NULL == HEAD_DLIST(mru_list, mlink)) {
2543				restarted_count++;
2544				if (restarted_count > 8) {
2545					fprintf(stderr,
2546						"Giving up after 8 restarts from the beginning.\n"
2547						"With high-traffic NTP servers, this can occur if the\n"
2548						"MRU list is limited to less than about 16 seconds' of\n"
2549						"entries.  See the 'mru' ntp.conf directive to adjust.\n");
2550					goto cleanup_return;
2551				}
2552				if (debug)
2553					fprintf(stderr,
2554						"--->   Restarting from the beginning, retry #%u\n",
2555						restarted_count);
2556			}
2557		} else if (CERR_UNKNOWNVAR == qres) {
2558			fprintf(stderr,
2559				"CERR_UNKNOWNVAR from ntpd but no priors given.\n");
2560			goto cleanup_return;
2561		} else if (CERR_BADVALUE == qres) {
2562			if (cap_frags) {
2563				cap_frags = FALSE;
2564				if (debug)
2565					fprintf(stderr,
2566						"Reverted to row limit from fragments limit.\n");
2567			} else {
2568				/* ntpd has lower cap on row limit */
2569				ntpd_row_limit--;
2570				limit = min(limit, ntpd_row_limit);
2571				if (debug)
2572					fprintf(stderr,
2573						"Row limit reduced to %d following CERR_BADVALUE.\n",
2574						limit);
2575			}
2576		} else if (ERR_INCOMPLETE == qres ||
2577			   ERR_TIMEOUT == qres) {
2578			/*
2579			 * Reduce the number of rows/frags requested by
2580			 * half to recover from lost response fragments.
2581			 */
2582			if (cap_frags) {
2583				frags = max(2, frags / 2);
2584				if (debug)
2585					fprintf(stderr,
2586						"Frag limit reduced to %d following incomplete response.\n",
2587						frags);
2588			} else {
2589				limit = max(2, limit / 2);
2590				if (debug)
2591					fprintf(stderr,
2592						"Row limit reduced to %d following incomplete response.\n",
2593						limit);
2594			}
2595		} else if (qres) {
2596			show_error_msg(qres, 0);
2597			goto cleanup_return;
2598		}
2599		/*
2600		 * This is a cheap cop-out implementation of rawmode
2601		 * output for mrulist.  A better approach would be to
2602		 * dump similar output after the list is collected by
2603		 * ntpq with a continuous sequence of indexes.  This
2604		 * cheap approach has indexes resetting to zero for
2605		 * each query/response, and duplicates are not
2606		 * coalesced.
2607		 */
2608		if (!qres && rawmode)
2609			printvars(rsize, rdata, rstatus, TYPE_SYS, 1, stdout);
2610		ci = 0;
2611		have_addr_older = FALSE;
2612		have_last_older = FALSE;
2613		while (!qres && nextvar(&rsize, &rdata, &tag, &val)) {
2614			if (debug > 1)
2615				fprintf(stderr, "nextvar gave: %s = %s\n",
2616					tag, val);
2617			switch(tag[0]) {
2618
2619			case 'a':
2620				if (!strcmp(tag, "addr.older")) {
2621					if (!have_last_older) {
2622						fprintf(stderr,
2623							"addr.older %s before last.older\n",
2624							val);
2625						goto cleanup_return;
2626					}
2627					if (!decodenetnum(val, &addr_older)) {
2628						fprintf(stderr,
2629							"addr.older %s garbled\n",
2630							val);
2631						goto cleanup_return;
2632					}
2633					hash = NTP_HASH_ADDR(&addr_older);
2634					for (recent = hash_table[hash];
2635					     recent != NULL;
2636					     recent = recent->hlink)
2637						if (ADDR_PORT_EQ(
2638						      &addr_older,
2639						      &recent->addr))
2640							break;
2641					if (NULL == recent) {
2642						fprintf(stderr,
2643							"addr.older %s not in hash table\n",
2644							val);
2645						goto cleanup_return;
2646					}
2647					if (!L_ISEQU(&last_older,
2648						     &recent->last)) {
2649						fprintf(stderr,
2650							"last.older %08x.%08x mismatches %08x.%08x expected.\n",
2651							last_older.l_ui,
2652							last_older.l_uf,
2653							recent->last.l_ui,
2654							recent->last.l_uf);
2655						goto cleanup_return;
2656					}
2657					have_addr_older = TRUE;
2658				} else if (1 != sscanf(tag, "addr.%d", &si)
2659					   || si != ci)
2660					goto nomatch;
2661				else if (decodenetnum(val, &mon->addr))
2662					MGOT(MRU_GOT_ADDR);
2663				break;
2664
2665			case 'l':
2666				if (!strcmp(tag, "last.older")) {
2667					if ('0' != val[0] ||
2668					    'x' != val[1] ||
2669					    !hextolfp(val + 2, &last_older)) {
2670						fprintf(stderr,
2671							"last.older %s garbled\n",
2672							val);
2673						goto cleanup_return;
2674					}
2675					have_last_older = TRUE;
2676				} else if (!strcmp(tag, "last.newest")) {
2677					if (0 != got) {
2678						fprintf(stderr,
2679							"last.newest %s before complete row, got = 0x%x\n",
2680							val, (u_int)got);
2681						goto cleanup_return;
2682					}
2683					if (!have_now) {
2684						fprintf(stderr,
2685							"last.newest %s before now=\n",
2686							val);
2687						goto cleanup_return;
2688					}
2689					head = HEAD_DLIST(mru_list, mlink);
2690					if (NULL != head) {
2691						if ('0' != val[0] ||
2692						    'x' != val[1] ||
2693						    !hextolfp(val + 2, &newest) ||
2694						    !L_ISEQU(&newest,
2695							     &head->last)) {
2696							fprintf(stderr,
2697								"last.newest %s mismatches %08x.%08x",
2698								val,
2699								head->last.l_ui,
2700								head->last.l_uf);
2701							goto cleanup_return;
2702						}
2703					}
2704					list_complete = TRUE;
2705				} else if (1 != sscanf(tag, "last.%d", &si) ||
2706					   si != ci || '0' != val[0] ||
2707					   'x' != val[1] ||
2708					   !hextolfp(val + 2, &mon->last)) {
2709					goto nomatch;
2710				} else {
2711					MGOT(MRU_GOT_LAST);
2712					/*
2713					 * allow interrupted retrieval,
2714					 * using most recent retrieved
2715					 * entry's last seen timestamp
2716					 * as the end of operation.
2717					 */
2718					*pnow = mon->last;
2719				}
2720				break;
2721
2722			case 'f':
2723				if (1 != sscanf(tag, "first.%d", &si) ||
2724				    si != ci || '0' != val[0] ||
2725				    'x' != val[1] ||
2726				    !hextolfp(val + 2, &mon->first))
2727					goto nomatch;
2728				MGOT(MRU_GOT_FIRST);
2729				break;
2730
2731			case 'n':
2732				if (!strcmp(tag, "nonce")) {
2733					strlcpy(nonce, val, sizeof(nonce));
2734					nonce_uses = 0;
2735					break; /* case */
2736				} else if (strcmp(tag, "now") ||
2737					   '0' != val[0] ||
2738					   'x' != val[1] ||
2739					    !hextolfp(val + 2, pnow))
2740					goto nomatch;
2741				have_now = TRUE;
2742				break;
2743
2744			case 'c':
2745				if (1 != sscanf(tag, "ct.%d", &si) ||
2746				    si != ci ||
2747				    1 != sscanf(val, "%d", &mon->count)
2748				    || mon->count < 1)
2749					goto nomatch;
2750				MGOT(MRU_GOT_COUNT);
2751				break;
2752
2753			case 'm':
2754				if (1 != sscanf(tag, "mv.%d", &si) ||
2755				    si != ci ||
2756				    1 != sscanf(val, "%d", &mv))
2757					goto nomatch;
2758				mon->mode = PKT_MODE(mv);
2759				mon->ver = PKT_VERSION(mv);
2760				MGOT(MRU_GOT_MV);
2761				break;
2762
2763			case 'r':
2764				if (1 != sscanf(tag, "rs.%d", &si) ||
2765				    si != ci ||
2766				    1 != sscanf(val, "0x%hx", &mon->rs))
2767					goto nomatch;
2768				MGOT(MRU_GOT_RS);
2769				break;
2770
2771			default:
2772			nomatch:
2773				/* empty stmt */ ;
2774				/* ignore unknown tags */
2775			}
2776		}
2777		if (have_now)
2778			list_complete = TRUE;
2779		if (list_complete) {
2780			INSIST(0 == ri || have_addr_older);
2781		}
2782		if (mrulist_interrupted) {
2783			printf("mrulist retrieval interrupted by operator.\n"
2784			       "Displaying partial client list.\n");
2785			fflush(stdout);
2786		}
2787		if (list_complete || mrulist_interrupted) {
2788			fprintf(stderr,
2789				"\rRetrieved %u unique MRU entries and %u updates.\n",
2790				mru_count, mru_dupes);
2791			fflush(stderr);
2792			break;
2793		}
2794		if (time(NULL) >= next_report) {
2795			next_report += MRU_REPORT_SECS;
2796			fprintf(stderr, "\r%u (%u updates) ", mru_count,
2797				mru_dupes);
2798			fflush(stderr);
2799		}
2800
2801		/*
2802		 * Snooze for a bit between queries to let ntpd catch
2803		 * up with other duties.
2804		 */
2805#ifdef SYS_WINNT
2806		Sleep(sleep_msecs);
2807#elif !defined(HAVE_NANOSLEEP)
2808		sleep((sleep_msecs / 1000) + 1);
2809#else
2810		{
2811			struct timespec interv = { 0,
2812						   1000 * sleep_msecs };
2813			nanosleep(&interv, NULL);
2814		}
2815#endif
2816		/*
2817		 * If there were no errors, increase the number of rows
2818		 * to a maximum of 3 * MAXFRAGS (the most packets ntpq
2819		 * can handle in one response), on the assumption that
2820		 * no less than 3 rows fit in each packet, capped at
2821		 * our best guess at the server's row limit.
2822		 */
2823		if (!qres) {
2824			if (cap_frags) {
2825				frags = min(MAXFRAGS, frags + 1);
2826			} else {
2827				limit = min3(3 * MAXFRAGS,
2828					     ntpd_row_limit,
2829					     max(limit + 1,
2830					         limit * 33 / 32));
2831			}
2832		}
2833		/*
2834		 * prepare next query with as many address and last-seen
2835		 * timestamps as will fit in a single packet.
2836		 */
2837		req = req_buf;
2838		req_end = req_buf + sizeof(req_buf);
2839#define REQ_ROOM	(req_end - req)
2840		snprintf(req, REQ_ROOM, "nonce=%s, %s=%d%s", nonce,
2841			 (cap_frags)
2842			     ? "frags"
2843			     : "limit",
2844			 (cap_frags)
2845			     ? frags
2846			     : limit,
2847			 parms);
2848		req += strlen(req);
2849		nonce_uses++;
2850		if (nonce_uses >= 4) {
2851			if (!fetch_nonce(nonce, sizeof(nonce)))
2852				goto cleanup_return;
2853			nonce_uses = 0;
2854		}
2855
2856
2857		for (ri = 0, recent = HEAD_DLIST(mru_list, mlink);
2858		     recent != NULL;
2859		     ri++, recent = NEXT_DLIST(mru_list, recent, mlink)) {
2860
2861			snprintf(buf, sizeof(buf),
2862				 ", addr.%d=%s, last.%d=0x%08x.%08x",
2863				 ri, sptoa(&recent->addr), ri,
2864				 recent->last.l_ui, recent->last.l_uf);
2865			chars = strlen(buf);
2866			if (REQ_ROOM - chars < 1)
2867				break;
2868			memcpy(req, buf, chars + 1);
2869			req += chars;
2870		}
2871	}
2872
2873	set_ctrl_c_hook(NULL);
2874	c_mru_l_rc = TRUE;
2875	goto retain_hash_table;
2876
2877cleanup_return:
2878	free(hash_table);
2879	hash_table = NULL;
2880
2881retain_hash_table:
2882	if (mon != NULL)
2883		free(mon);
2884
2885	return c_mru_l_rc;
2886}
2887
2888
2889/*
2890 * qcmp_mru_addr - sort MRU entries by remote address.
2891 *
2892 * All IPv4 addresses sort before any IPv6, addresses are sorted by
2893 * value within address family.
2894 */
2895static int
2896qcmp_mru_addr(
2897	const void *v1,
2898	const void *v2
2899	)
2900{
2901	const mru * const *	ppm1 = v1;
2902	const mru * const *	ppm2 = v2;
2903	const mru *		pm1;
2904	const mru *		pm2;
2905	u_short			af1;
2906	u_short			af2;
2907	size_t			cmplen;
2908	size_t			addr_off;
2909
2910	pm1 = *ppm1;
2911	pm2 = *ppm2;
2912
2913	af1 = AF(&pm1->addr);
2914	af2 = AF(&pm2->addr);
2915
2916	if (af1 != af2)
2917		return (AF_INET == af1)
2918			   ? -1
2919			   : 1;
2920
2921	cmplen = SIZEOF_INADDR(af1);
2922	addr_off = (AF_INET == af1)
2923		      ? offsetof(struct sockaddr_in, sin_addr)
2924		      : offsetof(struct sockaddr_in6, sin6_addr);
2925
2926	return memcmp((const char *)&pm1->addr + addr_off,
2927		      (const char *)&pm2->addr + addr_off,
2928		      cmplen);
2929}
2930
2931
2932static int
2933qcmp_mru_r_addr(
2934	const void *v1,
2935	const void *v2
2936	)
2937{
2938	return -qcmp_mru_addr(v1, v2);
2939}
2940
2941
2942/*
2943 * qcmp_mru_count - sort MRU entries by times seen (hit count).
2944 */
2945static int
2946qcmp_mru_count(
2947	const void *v1,
2948	const void *v2
2949	)
2950{
2951	const mru * const *	ppm1 = v1;
2952	const mru * const *	ppm2 = v2;
2953	const mru *		pm1;
2954	const mru *		pm2;
2955
2956	pm1 = *ppm1;
2957	pm2 = *ppm2;
2958
2959	return (pm1->count < pm2->count)
2960		   ? -1
2961		   : ((pm1->count == pm2->count)
2962			  ? 0
2963			  : 1);
2964}
2965
2966
2967static int
2968qcmp_mru_r_count(
2969	const void *v1,
2970	const void *v2
2971	)
2972{
2973	return -qcmp_mru_count(v1, v2);
2974}
2975
2976
2977/*
2978 * qcmp_mru_avgint - sort MRU entries by average interval.
2979 */
2980static int
2981qcmp_mru_avgint(
2982	const void *v1,
2983	const void *v2
2984	)
2985{
2986	const mru * const *	ppm1 = v1;
2987	const mru * const *	ppm2 = v2;
2988	const mru *		pm1;
2989	const mru *		pm2;
2990	l_fp			interval;
2991	double			avg1;
2992	double			avg2;
2993
2994	pm1 = *ppm1;
2995	pm2 = *ppm2;
2996
2997	interval = pm1->last;
2998	L_SUB(&interval, &pm1->first);
2999	LFPTOD(&interval, avg1);
3000	avg1 /= pm1->count;
3001
3002	interval = pm2->last;
3003	L_SUB(&interval, &pm2->first);
3004	LFPTOD(&interval, avg2);
3005	avg2 /= pm2->count;
3006
3007	if (avg1 < avg2)
3008		return -1;
3009	else if (avg1 > avg2)
3010		return 1;
3011
3012	/* secondary sort on lstint - rarely tested */
3013	if (L_ISEQU(&pm1->last, &pm2->last))
3014		return 0;
3015	else if (L_ISGEQ(&pm1->last, &pm2->last))
3016		return -1;
3017	else
3018		return 1;
3019}
3020
3021
3022static int
3023qcmp_mru_r_avgint(
3024	const void *v1,
3025	const void *v2
3026	)
3027{
3028	return -qcmp_mru_avgint(v1, v2);
3029}
3030
3031
3032/*
3033 * mrulist - ntpq's mrulist command to fetch an arbitrarily large Most
3034 *	     Recently Used (seen) remote address list from ntpd.
3035 *
3036 * Similar to ntpdc's monlist command, but not limited to a single
3037 * request/response, and thereby not limited to a few hundred remote
3038 * addresses.
3039 *
3040 * See ntpd/ntp_control.c read_mru_list() for comments on the way
3041 * CTL_OP_READ_MRU is designed to be used.
3042 *
3043 * mrulist intentionally differs from monlist in the way the avgint
3044 * column is calculated.  monlist includes the time after the last
3045 * packet from the client until the monlist query time in the average,
3046 * while mrulist excludes it.  That is, monlist's average interval grows
3047 * over time for remote addresses not heard from in some time, while it
3048 * remains unchanged in mrulist.  This also affects the avgint value for
3049 * entries representing a single packet, with identical first and last
3050 * timestamps.  mrulist shows 0 avgint, monlist shows a value identical
3051 * to lstint.
3052 */
3053static void
3054mrulist(
3055	struct parse *	pcmd,
3056	FILE *		fp
3057	)
3058{
3059	const char mincount_eq[] =	"mincount=";
3060	const char resall_eq[] =	"resall=";
3061	const char resany_eq[] =	"resany=";
3062	const char maxlstint_eq[] =	"maxlstint=";
3063	const char laddr_eq[] =		"laddr=";
3064	const char sort_eq[] =		"sort=";
3065	mru_sort_order order;
3066	size_t n;
3067	char parms_buf[128];
3068	char buf[24];
3069	char *parms;
3070	const char *arg;
3071	size_t cb;
3072	mru **sorted;
3073	mru **ppentry;
3074	mru *recent;
3075	l_fp now;
3076	l_fp interval;
3077	double favgint;
3078	double flstint;
3079	int avgint;
3080	int lstint;
3081	size_t i;
3082
3083	order = MRUSORT_DEF;
3084	parms_buf[0] = '\0';
3085	parms = parms_buf;
3086	for (i = 0; i < pcmd->nargs; i++) {
3087		arg = pcmd->argval[i].string;
3088		if (arg != NULL) {
3089			cb = strlen(arg) + 1;
3090			if ((!strncmp(resall_eq, arg, sizeof(resall_eq)
3091			    - 1) || !strncmp(resany_eq, arg,
3092			    sizeof(resany_eq) - 1) || !strncmp(
3093			    mincount_eq, arg, sizeof(mincount_eq) - 1)
3094			    || !strncmp(laddr_eq, arg, sizeof(laddr_eq)
3095			    - 1) || !strncmp(maxlstint_eq, arg,
3096			    sizeof(laddr_eq) - 1)) && parms + cb + 2 <=
3097			    parms_buf + sizeof(parms_buf)) {
3098				/* these are passed intact to ntpd */
3099				memcpy(parms, ", ", 2);
3100				parms += 2;
3101				memcpy(parms, arg, cb);
3102				parms += cb - 1;
3103			} else if (!strncmp(sort_eq, arg,
3104					    sizeof(sort_eq) - 1)) {
3105				arg += sizeof(sort_eq) - 1;
3106				for (n = 0;
3107				     n < COUNTOF(mru_sort_keywords);
3108				     n++)
3109					if (!strcmp(mru_sort_keywords[n],
3110						    arg))
3111						break;
3112				if (n < COUNTOF(mru_sort_keywords))
3113					order = n;
3114			} else if (!strcmp("limited", arg) ||
3115				   !strcmp("kod", arg)) {
3116				/* transform to resany=... */
3117				snprintf(buf, sizeof(buf),
3118					 ", resany=0x%x",
3119					 ('k' == arg[0])
3120					     ? RES_KOD
3121					     : RES_LIMITED);
3122				cb = 1 + strlen(buf);
3123				if (parms + cb <
3124					parms_buf + sizeof(parms_buf)) {
3125					memcpy(parms, buf, cb);
3126					parms += cb - 1;
3127				}
3128			} else
3129				fprintf(stderr,
3130					"ignoring unrecognized mrulist parameter: %s\n",
3131					arg);
3132		}
3133	}
3134	parms = parms_buf;
3135
3136	if (!collect_mru_list(parms, &now))
3137		return;
3138
3139	/* display the results */
3140	if (rawmode)
3141		goto cleanup_return;
3142
3143	/* construct an array of entry pointers in default order */
3144	sorted = eallocarray(mru_count, sizeof(*sorted));
3145	ppentry = sorted;
3146	if (MRUSORT_R_DEF != order) {
3147		ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3148			INSIST(ppentry < sorted + mru_count);
3149			*ppentry = recent;
3150			ppentry++;
3151		ITER_DLIST_END()
3152	} else {
3153		REV_ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3154			INSIST(ppentry < sorted + mru_count);
3155			*ppentry = recent;
3156			ppentry++;
3157		REV_ITER_DLIST_END()
3158	}
3159
3160	if (ppentry - sorted != (int)mru_count) {
3161		fprintf(stderr,
3162			"mru_count %u should match MRU list depth %ld.\n",
3163			mru_count, (long)(ppentry - sorted));
3164		free(sorted);
3165		goto cleanup_return;
3166	}
3167
3168	/* re-sort sorted[] if not default or reverse default */
3169	if (MRUSORT_R_DEF < order)
3170		qsort(sorted, mru_count, sizeof(sorted[0]),
3171		      mru_qcmp_table[order]);
3172
3173	printf(	"lstint avgint rstr r m v  count rport remote address\n"
3174		"==============================================================================\n");
3175		/* '=' x 78 */
3176	for (ppentry = sorted; ppentry < sorted + mru_count; ppentry++) {
3177		recent = *ppentry;
3178		interval = now;
3179		L_SUB(&interval, &recent->last);
3180		LFPTOD(&interval, flstint);
3181		lstint = (int)(flstint + 0.5);
3182		interval = recent->last;
3183		L_SUB(&interval, &recent->first);
3184		LFPTOD(&interval, favgint);
3185		favgint /= recent->count;
3186		avgint = (int)(favgint + 0.5);
3187		fprintf(fp, "%6d %6d %4hx %c %d %d %6d %5u %s\n",
3188			lstint, avgint, recent->rs,
3189			(RES_KOD & recent->rs)
3190			    ? 'K'
3191			    : (RES_LIMITED & recent->rs)
3192				  ? 'L'
3193				  : '.',
3194			(int)recent->mode, (int)recent->ver,
3195			recent->count, SRCPORT(&recent->addr),
3196			nntohost(&recent->addr));
3197		if (showhostnames)
3198			fflush(fp);
3199	}
3200	fflush(fp);
3201	if (debug) {
3202		fprintf(stderr,
3203			"--- completed, freeing sorted[] pointers\n");
3204		fflush(stderr);
3205	}
3206	free(sorted);
3207
3208cleanup_return:
3209	if (debug) {
3210		fprintf(stderr, "... freeing MRU entries\n");
3211		fflush(stderr);
3212	}
3213	ITER_DLIST_BEGIN(mru_list, recent, mlink, mru)
3214		free(recent);
3215	ITER_DLIST_END()
3216	if (debug) {
3217		fprintf(stderr, "... freeing hash_table[]\n");
3218		fflush(stderr);
3219	}
3220	free(hash_table);
3221	hash_table = NULL;
3222	INIT_DLIST(mru_list, mlink);
3223}
3224
3225
3226/*
3227 * validate_ifnum - helper for ifstats()
3228 *
3229 * Ensures rows are received in order and complete.
3230 */
3231static void
3232validate_ifnum(
3233	FILE *		fp,
3234	u_int		ifnum,
3235	int *		pfields,
3236	ifstats_row *	prow
3237	)
3238{
3239	if (prow->ifnum == ifnum)
3240		return;
3241	if (prow->ifnum + 1 <= ifnum) {
3242		if (*pfields < IFSTATS_FIELDS)
3243			fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3244				*pfields, IFSTATS_FIELDS);
3245		*pfields = 0;
3246		prow->ifnum = ifnum;
3247		return;
3248	}
3249	fprintf(stderr,
3250		"received if index %u, have %d of %d fields for index %u, aborting.\n",
3251		ifnum, *pfields, IFSTATS_FIELDS, prow->ifnum);
3252	exit(1);
3253}
3254
3255
3256/*
3257 * another_ifstats_field - helper for ifstats()
3258 *
3259 * If all fields for the row have been received, print it.
3260 */
3261static void
3262another_ifstats_field(
3263	int *		pfields,
3264	ifstats_row *	prow,
3265	FILE *		fp
3266	)
3267{
3268	u_int ifnum;
3269
3270	(*pfields)++;
3271	/* we understand 12 tags */
3272	if (IFSTATS_FIELDS > *pfields)
3273		return;
3274	/*
3275	"    interface name                                        send\n"
3276	" #  address/broadcast     drop flag ttl mc received sent failed peers   uptime\n"
3277	"==============================================================================\n");
3278	 */
3279	fprintf(fp,
3280		"%3u %-24.24s %c %4x %3d %2d %6d %6d %6d %5d %8d\n"
3281		"    %s\n",
3282		prow->ifnum, prow->name,
3283		(prow->enabled)
3284		    ? '.'
3285		    : 'D',
3286		prow->flags, prow->ttl, prow->mcast_count,
3287		prow->received, prow->sent, prow->send_errors,
3288		prow->peer_count, prow->uptime, sptoa(&prow->addr));
3289	if (!SOCK_UNSPEC(&prow->bcast))
3290		fprintf(fp, "    %s\n", sptoa(&prow->bcast));
3291	ifnum = prow->ifnum;
3292	ZERO(*prow);
3293	prow->ifnum = ifnum;
3294}
3295
3296
3297/*
3298 * ifstats - ntpq -c ifstats modeled on ntpdc -c ifstats.
3299 */
3300static void
3301ifstats(
3302	struct parse *	pcmd,
3303	FILE *		fp
3304	)
3305{
3306	const char	addr_fmt[] =	"addr.%u";
3307	const char	bcast_fmt[] =	"bcast.%u";
3308	const char	en_fmt[] =	"en.%u";	/* enabled */
3309	const char	flags_fmt[] =	"flags.%u";
3310	const char	mc_fmt[] =	"mc.%u";	/* mcast count */
3311	const char	name_fmt[] =	"name.%u";
3312	const char	pc_fmt[] =	"pc.%u";	/* peer count */
3313	const char	rx_fmt[] =	"rx.%u";
3314	const char	tl_fmt[] =	"tl.%u";	/* ttl */
3315	const char	tx_fmt[] =	"tx.%u";
3316	const char	txerr_fmt[] =	"txerr.%u";
3317	const char	up_fmt[] =	"up.%u";	/* uptime */
3318	const char *	datap;
3319	int		qres;
3320	int		dsize;
3321	u_short		rstatus;
3322	char *		tag;
3323	char *		val;
3324	int		fields;
3325	u_int		ui;
3326	ifstats_row	row;
3327	int		comprende;
3328	size_t		len;
3329
3330	qres = doquery(CTL_OP_READ_ORDLIST_A, 0, TRUE, 0, NULL, &rstatus,
3331		       &dsize, &datap);
3332	if (qres)	/* message already displayed */
3333		return;
3334
3335	fprintf(fp,
3336		"    interface name                                        send\n"
3337		" #  address/broadcast     drop flag ttl mc received sent failed peers   uptime\n"
3338		"==============================================================================\n");
3339		/* '=' x 78 */
3340
3341	ZERO(row);
3342	fields = 0;
3343	ui = 0;
3344	while (nextvar(&dsize, &datap, &tag, &val)) {
3345		if (debug > 1)
3346			fprintf(stderr, "nextvar gave: %s = %s\n", tag,
3347				(NULL == val)
3348				    ? ""
3349				    : val);
3350		comprende = FALSE;
3351		switch(tag[0]) {
3352
3353		case 'a':
3354			if (1 == sscanf(tag, addr_fmt, &ui) &&
3355			    decodenetnum(val, &row.addr))
3356				comprende = TRUE;
3357			break;
3358
3359		case 'b':
3360			if (1 == sscanf(tag, bcast_fmt, &ui) &&
3361			    (NULL == val ||
3362			     decodenetnum(val, &row.bcast)))
3363				comprende = TRUE;
3364			break;
3365
3366		case 'e':
3367			if (1 == sscanf(tag, en_fmt, &ui) &&
3368			    1 == sscanf(val, "%d", &row.enabled))
3369				comprende = TRUE;
3370			break;
3371
3372		case 'f':
3373			if (1 == sscanf(tag, flags_fmt, &ui) &&
3374			    1 == sscanf(val, "0x%x", &row.flags))
3375				comprende = TRUE;
3376			break;
3377
3378		case 'm':
3379			if (1 == sscanf(tag, mc_fmt, &ui) &&
3380			    1 == sscanf(val, "%d", &row.mcast_count))
3381				comprende = TRUE;
3382			break;
3383
3384		case 'n':
3385			if (1 == sscanf(tag, name_fmt, &ui)) {
3386				/* strip quotes */
3387				INSIST(val);
3388				len = strlen(val);
3389				if (len >= 2 &&
3390				    len - 2 < sizeof(row.name)) {
3391					len -= 2;
3392					memcpy(row.name, val + 1, len);
3393					row.name[len] = '\0';
3394					comprende = TRUE;
3395				}
3396			}
3397			break;
3398
3399		case 'p':
3400			if (1 == sscanf(tag, pc_fmt, &ui) &&
3401			    1 == sscanf(val, "%d", &row.peer_count))
3402				comprende = TRUE;
3403			break;
3404
3405		case 'r':
3406			if (1 == sscanf(tag, rx_fmt, &ui) &&
3407			    1 == sscanf(val, "%d", &row.received))
3408				comprende = TRUE;
3409			break;
3410
3411		case 't':
3412			if (1 == sscanf(tag, tl_fmt, &ui) &&
3413			    1 == sscanf(val, "%d", &row.ttl))
3414				comprende = TRUE;
3415			else if (1 == sscanf(tag, tx_fmt, &ui) &&
3416				 1 == sscanf(val, "%d", &row.sent))
3417				comprende = TRUE;
3418			else if (1 == sscanf(tag, txerr_fmt, &ui) &&
3419				 1 == sscanf(val, "%d", &row.send_errors))
3420				comprende = TRUE;
3421			break;
3422
3423		case 'u':
3424			if (1 == sscanf(tag, up_fmt, &ui) &&
3425			    1 == sscanf(val, "%d", &row.uptime))
3426				comprende = TRUE;
3427			break;
3428		}
3429
3430		if (comprende) {
3431			/* error out if rows out of order */
3432			validate_ifnum(fp, ui, &fields, &row);
3433			/* if the row is complete, print it */
3434			another_ifstats_field(&fields, &row, fp);
3435		}
3436	}
3437	if (fields != IFSTATS_FIELDS)
3438		fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3439			fields, IFSTATS_FIELDS);
3440
3441	fflush(fp);
3442}
3443
3444
3445/*
3446 * validate_reslist_idx - helper for reslist()
3447 *
3448 * Ensures rows are received in order and complete.
3449 */
3450static void
3451validate_reslist_idx(
3452	FILE *		fp,
3453	u_int		idx,
3454	int *		pfields,
3455	reslist_row *	prow
3456	)
3457{
3458	if (prow->idx == idx)
3459		return;
3460	if (prow->idx + 1 == idx) {
3461		if (*pfields < RESLIST_FIELDS)
3462			fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3463				*pfields, RESLIST_FIELDS);
3464		*pfields = 0;
3465		prow->idx = idx;
3466		return;
3467	}
3468	fprintf(stderr,
3469		"received reslist index %u, have %d of %d fields for index %u, aborting.\n",
3470		idx, *pfields, RESLIST_FIELDS, prow->idx);
3471	exit(1);
3472}
3473
3474
3475/*
3476 * another_reslist_field - helper for reslist()
3477 *
3478 * If all fields for the row have been received, print it.
3479 */
3480static void
3481another_reslist_field(
3482	int *		pfields,
3483	reslist_row *	prow,
3484	FILE *		fp
3485	)
3486{
3487	char	addrmaskstr[128];
3488	int	prefix;	/* subnet mask as prefix bits count */
3489	u_int	idx;
3490
3491	(*pfields)++;
3492	/* we understand 4 tags */
3493	if (RESLIST_FIELDS > *pfields)
3494		return;
3495
3496	prefix = sockaddr_masktoprefixlen(&prow->mask);
3497	if (prefix >= 0)
3498		snprintf(addrmaskstr, sizeof(addrmaskstr), "%s/%d",
3499			 stoa(&prow->addr), prefix);
3500	else
3501		snprintf(addrmaskstr, sizeof(addrmaskstr), "%s %s",
3502			 stoa(&prow->addr), stoa(&prow->mask));
3503
3504	/*
3505	"   hits    addr/prefix or addr mask\n"
3506	"           restrictions\n"
3507	"==============================================================================\n");
3508	 */
3509	fprintf(fp,
3510		"%10lu %s\n"
3511		"           %s\n",
3512		prow->hits, addrmaskstr, prow->flagstr);
3513	idx = prow->idx;
3514	ZERO(*prow);
3515	prow->idx = idx;
3516}
3517
3518
3519/*
3520 * reslist - ntpq -c reslist modeled on ntpdc -c reslist.
3521 */
3522static void
3523reslist(
3524	struct parse *	pcmd,
3525	FILE *		fp
3526	)
3527{
3528	const char addr_fmtu[] =	"addr.%u";
3529	const char mask_fmtu[] =	"mask.%u";
3530	const char hits_fmt[] =		"hits.%u";
3531	const char flags_fmt[] =	"flags.%u";
3532	const char qdata[] =		"addr_restrictions";
3533	const int qdata_chars =		COUNTOF(qdata) - 1;
3534	const char *	datap;
3535	int		qres;
3536	int		dsize;
3537	u_short		rstatus;
3538	char *		tag;
3539	char *		val;
3540	int		fields;
3541	u_int		ui;
3542	reslist_row	row;
3543	int		comprende;
3544	size_t		len;
3545
3546	qres = doquery(CTL_OP_READ_ORDLIST_A, 0, TRUE, qdata_chars,
3547		       qdata, &rstatus, &dsize, &datap);
3548	if (qres)	/* message already displayed */
3549		return;
3550
3551	fprintf(fp,
3552		"   hits    addr/prefix or addr mask\n"
3553		"           restrictions\n"
3554		"==============================================================================\n");
3555		/* '=' x 78 */
3556
3557	ZERO(row);
3558	fields = 0;
3559	ui = 0;
3560	while (nextvar(&dsize, &datap, &tag, &val)) {
3561		if (debug > 1)
3562			fprintf(stderr, "nextvar gave: %s = %s\n", tag,
3563				(NULL == val)
3564				    ? ""
3565				    : val);
3566		comprende = FALSE;
3567		switch(tag[0]) {
3568
3569		case 'a':
3570			if (1 == sscanf(tag, addr_fmtu, &ui) &&
3571			    decodenetnum(val, &row.addr))
3572				comprende = TRUE;
3573			break;
3574
3575		case 'f':
3576			if (1 == sscanf(tag, flags_fmt, &ui)) {
3577				if (NULL == val) {
3578					row.flagstr[0] = '\0';
3579					comprende = TRUE;
3580				} else {
3581					len = strlen(val);
3582					memcpy(row.flagstr, val, len);
3583					row.flagstr[len] = '\0';
3584					comprende = TRUE;
3585				}
3586			}
3587			break;
3588
3589		case 'h':
3590			if (1 == sscanf(tag, hits_fmt, &ui) &&
3591			    1 == sscanf(val, "%lu", &row.hits))
3592				comprende = TRUE;
3593			break;
3594
3595		case 'm':
3596			if (1 == sscanf(tag, mask_fmtu, &ui) &&
3597			    decodenetnum(val, &row.mask))
3598				comprende = TRUE;
3599			break;
3600		}
3601
3602		if (comprende) {
3603			/* error out if rows out of order */
3604			validate_reslist_idx(fp, ui, &fields, &row);
3605			/* if the row is complete, print it */
3606			another_reslist_field(&fields, &row, fp);
3607		}
3608	}
3609	if (fields != RESLIST_FIELDS)
3610		fprintf(fp, "Warning: incomplete row with %d (of %d) fields",
3611			fields, RESLIST_FIELDS);
3612
3613	fflush(fp);
3614}
3615
3616
3617/*
3618 * collect_display_vdc
3619 */
3620static void
3621collect_display_vdc(
3622	associd_t	as,
3623	vdc *		table,
3624	int		decodestatus,
3625	FILE *		fp
3626	)
3627{
3628	static const char * const suf[2] = { "adr", "port" };
3629	static const char * const leapbits[4] = { "00", "01",
3630						  "10", "11" };
3631	struct varlist vl[MAXLIST];
3632	char tagbuf[32];
3633	vdc *pvdc;
3634	u_short rstatus;
3635	int rsize;
3636	const char *rdata;
3637	int qres;
3638	char *tag;
3639	char *val;
3640	u_int n;
3641	size_t len;
3642	int match;
3643	u_long ul;
3644	int vtype;
3645
3646	ZERO(vl);
3647	for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3648		ZERO(pvdc->v);
3649		if (NTP_ADD != pvdc->type) {
3650			doaddvlist(vl, pvdc->tag);
3651		} else {
3652			for (n = 0; n < COUNTOF(suf); n++) {
3653				snprintf(tagbuf, sizeof(tagbuf), "%s%s",
3654					 pvdc->tag, suf[n]);
3655				doaddvlist(vl, tagbuf);
3656			}
3657		}
3658	}
3659	qres = doquerylist(vl, CTL_OP_READVAR, as, 0, &rstatus, &rsize,
3660			   &rdata);
3661	doclearvlist(vl);
3662	if (qres)
3663		return;		/* error msg already displayed */
3664
3665	/*
3666	 * iterate over the response variables filling vdc_table with
3667	 * the retrieved values.
3668	 */
3669	while (nextvar(&rsize, &rdata, &tag, &val)) {
3670		if (NULL == val)
3671			continue;
3672		n = 0;
3673		for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3674			len = strlen(pvdc->tag);
3675			if (strncmp(tag, pvdc->tag, len))
3676				continue;
3677			if (NTP_ADD != pvdc->type) {
3678				if ('\0' != tag[len])
3679					continue;
3680				break;
3681			}
3682			match = FALSE;
3683			for (n = 0; n < COUNTOF(suf); n++) {
3684				if (strcmp(tag + len, suf[n]))
3685					continue;
3686				match = TRUE;
3687				break;
3688			}
3689			if (match)
3690				break;
3691		}
3692		if (NULL == pvdc->tag)
3693			continue;
3694		switch (pvdc->type) {
3695
3696		case NTP_STR:
3697			/* strip surrounding double quotes */
3698			if ('"' == val[0]) {
3699				len = strlen(val);
3700				if (len > 0 && '"' == val[len - 1]) {
3701					val[len - 1] = '\0';
3702					val++;
3703				}
3704			}
3705			/* fallthru */
3706		case NTP_MODE:	/* fallthru */
3707		case NTP_2BIT:
3708			pvdc->v.str = estrdup(val);
3709			break;
3710
3711		case NTP_LFP:
3712			decodets(val, &pvdc->v.lfp);
3713			break;
3714
3715		case NTP_ADP:
3716			if (!decodenetnum(val, &pvdc->v.sau))
3717				fprintf(stderr, "malformed %s=%s\n",
3718					pvdc->tag, val);
3719			break;
3720
3721		case NTP_ADD:
3722			if (0 == n) {	/* adr */
3723				if (!decodenetnum(val, &pvdc->v.sau))
3724					fprintf(stderr,
3725						"malformed %s=%s\n",
3726						pvdc->tag, val);
3727			} else {	/* port */
3728				if (atouint(val, &ul))
3729					SET_PORT(&pvdc->v.sau,
3730						 (u_short)ul);
3731			}
3732			break;
3733		}
3734	}
3735
3736	/* and display */
3737	if (decodestatus) {
3738		vtype = (0 == as)
3739			    ? TYPE_SYS
3740			    : TYPE_PEER;
3741		fprintf(fp, "associd=%u status=%04x %s,\n", as, rstatus,
3742			statustoa(vtype, rstatus));
3743	}
3744
3745	for (pvdc = table; pvdc->tag != NULL; pvdc++) {
3746		switch (pvdc->type) {
3747
3748		case NTP_STR:
3749			if (pvdc->v.str != NULL) {
3750				fprintf(fp, "%s  %s\n", pvdc->display,
3751					pvdc->v.str);
3752				free(pvdc->v.str);
3753				pvdc->v.str = NULL;
3754			}
3755			break;
3756
3757		case NTP_ADD:	/* fallthru */
3758		case NTP_ADP:
3759			fprintf(fp, "%s  %s\n", pvdc->display,
3760				nntohostp(&pvdc->v.sau));
3761			break;
3762
3763		case NTP_LFP:
3764			fprintf(fp, "%s  %s\n", pvdc->display,
3765				prettydate(&pvdc->v.lfp));
3766			break;
3767
3768		case NTP_MODE:
3769			atouint(pvdc->v.str, &ul);
3770			fprintf(fp, "%s  %s\n", pvdc->display,
3771				modetoa((int)ul));
3772			break;
3773
3774		case NTP_2BIT:
3775			atouint(pvdc->v.str, &ul);
3776			fprintf(fp, "%s  %s\n", pvdc->display,
3777				leapbits[ul & 0x3]);
3778			break;
3779
3780		default:
3781			fprintf(stderr, "unexpected vdc type %d for %s\n",
3782				pvdc->type, pvdc->tag);
3783			break;
3784		}
3785	}
3786}
3787
3788
3789/*
3790 * sysstats - implements ntpq -c sysstats modeled on ntpdc -c sysstats
3791 */
3792static void
3793sysstats(
3794	struct parse *pcmd,
3795	FILE *fp
3796	)
3797{
3798    static vdc sysstats_vdc[] = {
3799	VDC_INIT("ss_uptime",		"uptime:               ", NTP_STR),
3800	VDC_INIT("ss_reset",		"sysstats reset:       ", NTP_STR),
3801	VDC_INIT("ss_received",		"packets received:     ", NTP_STR),
3802	VDC_INIT("ss_thisver",		"current version:      ", NTP_STR),
3803	VDC_INIT("ss_oldver",		"older version:        ", NTP_STR),
3804	VDC_INIT("ss_badformat",	"bad length or format: ", NTP_STR),
3805	VDC_INIT("ss_badauth",		"authentication failed:", NTP_STR),
3806	VDC_INIT("ss_declined",		"declined:             ", NTP_STR),
3807	VDC_INIT("ss_restricted",	"restricted:           ", NTP_STR),
3808	VDC_INIT("ss_limited",		"rate limited:         ", NTP_STR),
3809	VDC_INIT("ss_kodsent",		"KoD responses:        ", NTP_STR),
3810	VDC_INIT("ss_processed",	"processed for time:   ", NTP_STR),
3811	VDC_INIT(NULL,			NULL,			  0)
3812    };
3813
3814	collect_display_vdc(0, sysstats_vdc, FALSE, fp);
3815}
3816
3817
3818/*
3819 * sysinfo - modeled on ntpdc's sysinfo
3820 */
3821static void
3822sysinfo(
3823	struct parse *pcmd,
3824	FILE *fp
3825	)
3826{
3827    static vdc sysinfo_vdc[] = {
3828	VDC_INIT("peeradr",		"system peer:      ", NTP_ADP),
3829	VDC_INIT("peermode",		"system peer mode: ", NTP_MODE),
3830	VDC_INIT("leap",		"leap indicator:   ", NTP_2BIT),
3831	VDC_INIT("stratum",		"stratum:          ", NTP_STR),
3832	VDC_INIT("precision",		"log2 precision:   ", NTP_STR),
3833	VDC_INIT("rootdelay",		"root delay:       ", NTP_STR),
3834	VDC_INIT("rootdisp",		"root dispersion:  ", NTP_STR),
3835	VDC_INIT("refid",		"reference ID:     ", NTP_STR),
3836	VDC_INIT("reftime",		"reference time:   ", NTP_LFP),
3837	VDC_INIT("sys_jitter",		"system jitter:    ", NTP_STR),
3838	VDC_INIT("clk_jitter",		"clock jitter:     ", NTP_STR),
3839	VDC_INIT("clk_wander",		"clock wander:     ", NTP_STR),
3840	VDC_INIT("bcastdelay",		"broadcast delay:  ", NTP_STR),
3841	VDC_INIT("authdelay",		"symm. auth. delay:", NTP_STR),
3842	VDC_INIT(NULL,			NULL,		      0)
3843    };
3844
3845	collect_display_vdc(0, sysinfo_vdc, TRUE, fp);
3846}
3847
3848
3849/*
3850 * kerninfo - modeled on ntpdc's kerninfo
3851 */
3852static void
3853kerninfo(
3854	struct parse *pcmd,
3855	FILE *fp
3856	)
3857{
3858    static vdc kerninfo_vdc[] = {
3859	VDC_INIT("koffset",		"pll offset:          ", NTP_STR),
3860	VDC_INIT("kfreq",		"pll frequency:       ", NTP_STR),
3861	VDC_INIT("kmaxerr",		"maximum error:       ", NTP_STR),
3862	VDC_INIT("kesterr",		"estimated error:     ", NTP_STR),
3863	VDC_INIT("kstflags",		"kernel status:       ", NTP_STR),
3864	VDC_INIT("ktimeconst",		"pll time constant:   ", NTP_STR),
3865	VDC_INIT("kprecis",		"precision:           ", NTP_STR),
3866	VDC_INIT("kfreqtol",		"frequency tolerance: ", NTP_STR),
3867	VDC_INIT("kppsfreq",		"pps frequency:       ", NTP_STR),
3868	VDC_INIT("kppsstab",		"pps stability:       ", NTP_STR),
3869	VDC_INIT("kppsjitter",		"pps jitter:          ", NTP_STR),
3870	VDC_INIT("kppscalibdur",	"calibration interval ", NTP_STR),
3871	VDC_INIT("kppscalibs",		"calibration cycles:  ", NTP_STR),
3872	VDC_INIT("kppsjitexc",		"jitter exceeded:     ", NTP_STR),
3873	VDC_INIT("kppsstbexc",		"stability exceeded:  ", NTP_STR),
3874	VDC_INIT("kppscaliberrs",	"calibration errors:  ", NTP_STR),
3875	VDC_INIT(NULL,			NULL,			 0)
3876    };
3877
3878	collect_display_vdc(0, kerninfo_vdc, TRUE, fp);
3879}
3880
3881
3882/*
3883 * monstats - implements ntpq -c monstats
3884 */
3885static void
3886monstats(
3887	struct parse *pcmd,
3888	FILE *fp
3889	)
3890{
3891    static vdc monstats_vdc[] = {
3892	VDC_INIT("mru_enabled",	"enabled:            ", NTP_STR),
3893	VDC_INIT("mru_depth",		"addresses:          ", NTP_STR),
3894	VDC_INIT("mru_deepest",	"peak addresses:     ", NTP_STR),
3895	VDC_INIT("mru_maxdepth",	"maximum addresses:  ", NTP_STR),
3896	VDC_INIT("mru_mindepth",	"reclaim above count:", NTP_STR),
3897	VDC_INIT("mru_maxage",		"reclaim older than: ", NTP_STR),
3898	VDC_INIT("mru_mem",		"kilobytes:          ", NTP_STR),
3899	VDC_INIT("mru_maxmem",		"maximum kilobytes:  ", NTP_STR),
3900	VDC_INIT(NULL,			NULL,			0)
3901    };
3902
3903	collect_display_vdc(0, monstats_vdc, FALSE, fp);
3904}
3905
3906
3907/*
3908 * iostats - ntpq -c iostats - network input and output counters
3909 */
3910static void
3911iostats(
3912	struct parse *pcmd,
3913	FILE *fp
3914	)
3915{
3916    static vdc iostats_vdc[] = {
3917	VDC_INIT("iostats_reset",	"time since reset:     ", NTP_STR),
3918	VDC_INIT("total_rbuf",		"receive buffers:      ", NTP_STR),
3919	VDC_INIT("free_rbuf",		"free receive buffers: ", NTP_STR),
3920	VDC_INIT("used_rbuf",		"used receive buffers: ", NTP_STR),
3921	VDC_INIT("rbuf_lowater",	"low water refills:    ", NTP_STR),
3922	VDC_INIT("io_dropped",		"dropped packets:      ", NTP_STR),
3923	VDC_INIT("io_ignored",		"ignored packets:      ", NTP_STR),
3924	VDC_INIT("io_received",		"received packets:     ", NTP_STR),
3925	VDC_INIT("io_sent",		"packets sent:         ", NTP_STR),
3926	VDC_INIT("io_sendfailed",	"packet send failures: ", NTP_STR),
3927	VDC_INIT("io_wakeups",		"input wakeups:        ", NTP_STR),
3928	VDC_INIT("io_goodwakeups",	"useful input wakeups: ", NTP_STR),
3929	VDC_INIT(NULL,			NULL,			  0)
3930    };
3931
3932	collect_display_vdc(0, iostats_vdc, FALSE, fp);
3933}
3934
3935
3936/*
3937 * timerstats - ntpq -c timerstats - interval timer counters
3938 */
3939static void
3940timerstats(
3941	struct parse *pcmd,
3942	FILE *fp
3943	)
3944{
3945    static vdc timerstats_vdc[] = {
3946	VDC_INIT("timerstats_reset",	"time since reset:  ", NTP_STR),
3947	VDC_INIT("timer_overruns",	"timer overruns:    ", NTP_STR),
3948	VDC_INIT("timer_xmts",		"calls to transmit: ", NTP_STR),
3949	VDC_INIT(NULL,			NULL,		       0)
3950    };
3951
3952	collect_display_vdc(0, timerstats_vdc, FALSE, fp);
3953}
3954
3955
3956/*
3957 * authinfo - implements ntpq -c authinfo
3958 */
3959static void
3960authinfo(
3961	struct parse *pcmd,
3962	FILE *fp
3963	)
3964{
3965    static vdc authinfo_vdc[] = {
3966	VDC_INIT("authreset",		"time since reset:", NTP_STR),
3967	VDC_INIT("authkeys",		"stored keys:     ", NTP_STR),
3968	VDC_INIT("authfreek",		"free keys:       ", NTP_STR),
3969	VDC_INIT("authklookups",	"key lookups:     ", NTP_STR),
3970	VDC_INIT("authknotfound",	"keys not found:  ", NTP_STR),
3971	VDC_INIT("authkuncached",	"uncached keys:   ", NTP_STR),
3972	VDC_INIT("authkexpired",	"expired keys:    ", NTP_STR),
3973	VDC_INIT("authencrypts",	"encryptions:     ", NTP_STR),
3974	VDC_INIT("authdecrypts",	"decryptions:     ", NTP_STR),
3975	VDC_INIT(NULL,			NULL,		     0)
3976    };
3977
3978	collect_display_vdc(0, authinfo_vdc, FALSE, fp);
3979}
3980
3981
3982/*
3983 * pstats - show statistics for a peer
3984 */
3985static void
3986pstats(
3987	struct parse *pcmd,
3988	FILE *fp
3989	)
3990{
3991    static vdc pstats_vdc[] = {
3992	VDC_INIT("src",		"remote host:         ", NTP_ADD),
3993	VDC_INIT("dst",		"local address:       ", NTP_ADD),
3994	VDC_INIT("timerec",	"time last received:  ", NTP_STR),
3995	VDC_INIT("timer",	"time until next send:", NTP_STR),
3996	VDC_INIT("timereach",	"reachability change: ", NTP_STR),
3997	VDC_INIT("sent",	"packets sent:        ", NTP_STR),
3998	VDC_INIT("received",	"packets received:    ", NTP_STR),
3999	VDC_INIT("badauth",	"bad authentication:  ", NTP_STR),
4000	VDC_INIT("bogusorg",	"bogus origin:        ", NTP_STR),
4001	VDC_INIT("oldpkt",	"duplicate:           ", NTP_STR),
4002	VDC_INIT("seldisp",	"bad dispersion:      ", NTP_STR),
4003	VDC_INIT("selbroken",	"bad reference time:  ", NTP_STR),
4004	VDC_INIT("candidate",	"candidate order:     ", NTP_STR),
4005	VDC_INIT(NULL,		NULL,			 0)
4006    };
4007	associd_t associd;
4008
4009	associd = checkassocid(pcmd->argval[0].uval);
4010	if (0 == associd)
4011		return;
4012
4013	collect_display_vdc(associd, pstats_vdc, TRUE, fp);
4014}
4015