xref: /freebsd/contrib/ntp/ntpd/ntp_control.c (revision 3c4ba5f55438f7afd4f4b0b56f88f2bb505fd6a6)
1 /*
2  * ntp_control.c - respond to mode 6 control messages and send async
3  *		   traps.  Provides service to ntpq and others.
4  */
5 
6 #ifdef HAVE_CONFIG_H
7 # include <config.h>
8 #endif
9 
10 #include <stdio.h>
11 #include <ctype.h>
12 #include <signal.h>
13 #include <sys/stat.h>
14 #ifdef HAVE_NETINET_IN_H
15 # include <netinet/in.h>
16 #endif
17 #include <arpa/inet.h>
18 
19 #include "ntpd.h"
20 #include "ntp_io.h"
21 #include "ntp_refclock.h"
22 #include "ntp_control.h"
23 #include "ntp_unixtime.h"
24 #include "ntp_stdlib.h"
25 #include "ntp_config.h"
26 #include "ntp_crypto.h"
27 #include "ntp_assert.h"
28 #include "ntp_leapsec.h"
29 #include "ntp_md5.h"	/* provides OpenSSL digest API */
30 #include "lib_strbuf.h"
31 #include "timexsup.h"
32 
33 #include <rc_cmdlength.h>
34 #ifdef KERNEL_PLL
35 # include "ntp_syscall.h"
36 #endif
37 
38 /*
39  * Structure to hold request procedure information
40  */
41 
42 struct ctl_proc {
43 	short control_code;		/* defined request code */
44 #define NO_REQUEST	(-1)
45 	u_short flags;			/* flags word */
46 	/* Only one flag.  Authentication required or not. */
47 #define NOAUTH	0
48 #define AUTH	1
49 	void (*handler) (struct recvbuf *, int); /* handle request */
50 };
51 
52 
53 /*
54  * Request processing routines
55  */
56 static	void	ctl_error	(u_char);
57 #ifdef REFCLOCK
58 static	u_short ctlclkstatus	(struct refclockstat *);
59 #endif
60 static	void	ctl_flushpkt	(u_char);
61 static	void	ctl_putdata	(const char *, unsigned int, int);
62 static	void	ctl_putstr	(const char *, const char *, size_t);
63 static	void	ctl_putdblf	(const char *, int, int, double);
64 #define	ctl_putdbl(tag, d)	ctl_putdblf(tag, 1, 3, d)
65 #define	ctl_putdbl6(tag, d)	ctl_putdblf(tag, 1, 6, d)
66 #define	ctl_putsfp(tag, sfp)	ctl_putdblf(tag, 0, -1, \
67 					    FPTOD(sfp))
68 static	void	ctl_putuint	(const char *, u_long);
69 static	void	ctl_puthex	(const char *, u_long);
70 static	void	ctl_putint	(const char *, long);
71 static	void	ctl_putts	(const char *, l_fp *);
72 static	void	ctl_putadr	(const char *, u_int32,
73 				 sockaddr_u *);
74 static	void	ctl_putrefid	(const char *, u_int32);
75 static	void	ctl_putarray	(const char *, double *, int);
76 static	void	ctl_putsys	(int);
77 static	void	ctl_putpeer	(int, struct peer *);
78 static	void	ctl_putfs	(const char *, tstamp_t);
79 static	void	ctl_printf	(const char *, ...) NTP_PRINTF(1, 2);
80 #ifdef REFCLOCK
81 static	void	ctl_putclock	(int, struct refclockstat *, int);
82 #endif	/* REFCLOCK */
83 static	const struct ctl_var *ctl_getitem(const struct ctl_var *,
84 					  char **);
85 static	u_short	count_var	(const struct ctl_var *);
86 static	void	control_unspec	(struct recvbuf *, int);
87 static	void	read_status	(struct recvbuf *, int);
88 static	void	read_sysvars	(void);
89 static	void	read_peervars	(void);
90 static	void	read_variables	(struct recvbuf *, int);
91 static	void	write_variables (struct recvbuf *, int);
92 static	void	read_clockstatus(struct recvbuf *, int);
93 static	void	write_clockstatus(struct recvbuf *, int);
94 static	void	set_trap	(struct recvbuf *, int);
95 static	void	save_config	(struct recvbuf *, int);
96 static	void	configure	(struct recvbuf *, int);
97 static	void	send_mru_entry	(mon_entry *, int);
98 static	void	send_random_tag_value(int);
99 static	void	read_mru_list	(struct recvbuf *, int);
100 static	void	send_ifstats_entry(endpt *, u_int);
101 static	void	read_ifstats	(struct recvbuf *);
102 static	void	sockaddrs_from_restrict_u(sockaddr_u *,	sockaddr_u *,
103 					  restrict_u *, int);
104 static	void	send_restrict_entry(restrict_u *, int, u_int);
105 static	void	send_restrict_list(restrict_u *, int, u_int *);
106 static	void	read_addr_restrictions(struct recvbuf *);
107 static	void	read_ordlist	(struct recvbuf *, int);
108 static	u_int32	derive_nonce	(sockaddr_u *, u_int32, u_int32);
109 static	void	generate_nonce	(struct recvbuf *, char *, size_t);
110 static	int	validate_nonce	(const char *, struct recvbuf *);
111 static	void	req_nonce	(struct recvbuf *, int);
112 static	void	unset_trap	(struct recvbuf *, int);
113 static	struct ctl_trap *ctlfindtrap(sockaddr_u *,
114 				     struct interface *);
115 
116 int/*BOOL*/ is_safe_filename(const char * name);
117 
118 static const struct ctl_proc control_codes[] = {
119 	{ CTL_OP_UNSPEC,		NOAUTH,	control_unspec },
120 	{ CTL_OP_READSTAT,		NOAUTH,	read_status },
121 	{ CTL_OP_READVAR,		NOAUTH,	read_variables },
122 	{ CTL_OP_WRITEVAR,		AUTH,	write_variables },
123 	{ CTL_OP_READCLOCK,		NOAUTH,	read_clockstatus },
124 	{ CTL_OP_WRITECLOCK,		AUTH,	write_clockstatus },
125 	{ CTL_OP_SETTRAP,		AUTH,	set_trap },
126 	{ CTL_OP_CONFIGURE,		AUTH,	configure },
127 	{ CTL_OP_SAVECONFIG,		AUTH,	save_config },
128 	{ CTL_OP_READ_MRU,		NOAUTH,	read_mru_list },
129 	{ CTL_OP_READ_ORDLIST_A,	AUTH,	read_ordlist },
130 	{ CTL_OP_REQ_NONCE,		NOAUTH,	req_nonce },
131 	{ CTL_OP_UNSETTRAP,		AUTH,	unset_trap },
132 	{ NO_REQUEST,			0,	NULL }
133 };
134 
135 /*
136  * System variables we understand
137  */
138 #define	CS_LEAP			1
139 #define	CS_STRATUM		2
140 #define	CS_PRECISION		3
141 #define	CS_ROOTDELAY		4
142 #define	CS_ROOTDISPERSION	5
143 #define	CS_REFID		6
144 #define	CS_REFTIME		7
145 #define	CS_POLL			8
146 #define	CS_PEERID		9
147 #define	CS_OFFSET		10
148 #define	CS_DRIFT		11
149 #define	CS_JITTER		12
150 #define	CS_ERROR		13
151 #define	CS_CLOCK		14
152 #define	CS_PROCESSOR		15
153 #define	CS_SYSTEM		16
154 #define	CS_VERSION		17
155 #define	CS_STABIL		18
156 #define	CS_VARLIST		19
157 #define	CS_TAI			20
158 #define	CS_LEAPTAB		21
159 #define	CS_LEAPEND		22
160 #define	CS_RATE			23
161 #define	CS_MRU_ENABLED		24
162 #define	CS_MRU_DEPTH		25
163 #define	CS_MRU_DEEPEST		26
164 #define	CS_MRU_MINDEPTH		27
165 #define	CS_MRU_MAXAGE		28
166 #define	CS_MRU_MAXDEPTH		29
167 #define	CS_MRU_MEM		30
168 #define	CS_MRU_MAXMEM		31
169 #define	CS_SS_UPTIME		32
170 #define	CS_SS_RESET		33
171 #define	CS_SS_RECEIVED		34
172 #define	CS_SS_THISVER		35
173 #define	CS_SS_OLDVER		36
174 #define	CS_SS_BADFORMAT		37
175 #define	CS_SS_BADAUTH		38
176 #define	CS_SS_DECLINED		39
177 #define	CS_SS_RESTRICTED	40
178 #define	CS_SS_LIMITED		41
179 #define	CS_SS_KODSENT		42
180 #define	CS_SS_PROCESSED		43
181 #define	CS_SS_LAMPORT		44
182 #define	CS_SS_TSROUNDING	45
183 #define	CS_PEERADR		46
184 #define	CS_PEERMODE		47
185 #define	CS_BCASTDELAY		48
186 #define	CS_AUTHDELAY		49
187 #define	CS_AUTHKEYS		50
188 #define	CS_AUTHFREEK		51
189 #define	CS_AUTHKLOOKUPS		52
190 #define	CS_AUTHKNOTFOUND	53
191 #define	CS_AUTHKUNCACHED	54
192 #define	CS_AUTHKEXPIRED		55
193 #define	CS_AUTHENCRYPTS		56
194 #define	CS_AUTHDECRYPTS		57
195 #define	CS_AUTHRESET		58
196 #define	CS_K_OFFSET		59
197 #define	CS_K_FREQ		60
198 #define	CS_K_MAXERR		61
199 #define	CS_K_ESTERR		62
200 #define	CS_K_STFLAGS		63
201 #define	CS_K_TIMECONST		64
202 #define	CS_K_PRECISION		65
203 #define	CS_K_FREQTOL		66
204 #define	CS_K_PPS_FREQ		67
205 #define	CS_K_PPS_STABIL		68
206 #define	CS_K_PPS_JITTER		69
207 #define	CS_K_PPS_CALIBDUR	70
208 #define	CS_K_PPS_CALIBS		71
209 #define	CS_K_PPS_CALIBERRS	72
210 #define	CS_K_PPS_JITEXC		73
211 #define	CS_K_PPS_STBEXC		74
212 #define	CS_KERN_FIRST		CS_K_OFFSET
213 #define	CS_KERN_LAST		CS_K_PPS_STBEXC
214 #define	CS_IOSTATS_RESET	75
215 #define	CS_TOTAL_RBUF		76
216 #define	CS_FREE_RBUF		77
217 #define	CS_USED_RBUF		78
218 #define	CS_RBUF_LOWATER		79
219 #define	CS_IO_DROPPED		80
220 #define	CS_IO_IGNORED		81
221 #define	CS_IO_RECEIVED		82
222 #define	CS_IO_SENT		83
223 #define	CS_IO_SENDFAILED	84
224 #define	CS_IO_WAKEUPS		85
225 #define	CS_IO_GOODWAKEUPS	86
226 #define	CS_TIMERSTATS_RESET	87
227 #define	CS_TIMER_OVERRUNS	88
228 #define	CS_TIMER_XMTS		89
229 #define	CS_FUZZ			90
230 #define	CS_WANDER_THRESH	91
231 #define	CS_LEAPSMEARINTV	92
232 #define	CS_LEAPSMEAROFFS	93
233 #define	CS_MAX_NOAUTOKEY	CS_LEAPSMEAROFFS
234 #ifdef AUTOKEY
235 #define	CS_FLAGS		(1 + CS_MAX_NOAUTOKEY)
236 #define	CS_HOST			(2 + CS_MAX_NOAUTOKEY)
237 #define	CS_PUBLIC		(3 + CS_MAX_NOAUTOKEY)
238 #define	CS_CERTIF		(4 + CS_MAX_NOAUTOKEY)
239 #define	CS_SIGNATURE		(5 + CS_MAX_NOAUTOKEY)
240 #define	CS_REVTIME		(6 + CS_MAX_NOAUTOKEY)
241 #define	CS_IDENT		(7 + CS_MAX_NOAUTOKEY)
242 #define	CS_DIGEST		(8 + CS_MAX_NOAUTOKEY)
243 #define	CS_MAXCODE		CS_DIGEST
244 #else	/* !AUTOKEY follows */
245 #define	CS_MAXCODE		CS_MAX_NOAUTOKEY
246 #endif	/* !AUTOKEY */
247 
248 /*
249  * Peer variables we understand
250  */
251 #define	CP_CONFIG		1
252 #define	CP_AUTHENABLE		2
253 #define	CP_AUTHENTIC		3
254 #define	CP_SRCADR		4
255 #define	CP_SRCPORT		5
256 #define	CP_DSTADR		6
257 #define	CP_DSTPORT		7
258 #define	CP_LEAP			8
259 #define	CP_HMODE		9
260 #define	CP_STRATUM		10
261 #define	CP_PPOLL		11
262 #define	CP_HPOLL		12
263 #define	CP_PRECISION		13
264 #define	CP_ROOTDELAY		14
265 #define	CP_ROOTDISPERSION	15
266 #define	CP_REFID		16
267 #define	CP_REFTIME		17
268 #define	CP_ORG			18
269 #define	CP_REC			19
270 #define	CP_XMT			20
271 #define	CP_REACH		21
272 #define	CP_UNREACH		22
273 #define	CP_TIMER		23
274 #define	CP_DELAY		24
275 #define	CP_OFFSET		25
276 #define	CP_JITTER		26
277 #define	CP_DISPERSION		27
278 #define	CP_KEYID		28
279 #define	CP_FILTDELAY		29
280 #define	CP_FILTOFFSET		30
281 #define	CP_PMODE		31
282 #define	CP_RECEIVED		32
283 #define	CP_SENT			33
284 #define	CP_FILTERROR		34
285 #define	CP_FLASH		35
286 #define	CP_TTL			36
287 #define	CP_VARLIST		37
288 #define	CP_IN			38
289 #define	CP_OUT			39
290 #define	CP_RATE			40
291 #define	CP_BIAS			41
292 #define	CP_SRCHOST		42
293 #define	CP_TIMEREC		43
294 #define	CP_TIMEREACH		44
295 #define	CP_BADAUTH		45
296 #define	CP_BOGUSORG		46
297 #define	CP_OLDPKT		47
298 #define	CP_SELDISP		48
299 #define	CP_SELBROKEN		49
300 #define	CP_CANDIDATE		50
301 #define	CP_MAX_NOAUTOKEY	CP_CANDIDATE
302 #ifdef AUTOKEY
303 #define	CP_FLAGS		(1 + CP_MAX_NOAUTOKEY)
304 #define	CP_HOST			(2 + CP_MAX_NOAUTOKEY)
305 #define	CP_VALID		(3 + CP_MAX_NOAUTOKEY)
306 #define	CP_INITSEQ		(4 + CP_MAX_NOAUTOKEY)
307 #define	CP_INITKEY		(5 + CP_MAX_NOAUTOKEY)
308 #define	CP_INITTSP		(6 + CP_MAX_NOAUTOKEY)
309 #define	CP_SIGNATURE		(7 + CP_MAX_NOAUTOKEY)
310 #define	CP_IDENT		(8 + CP_MAX_NOAUTOKEY)
311 #define	CP_MAXCODE		CP_IDENT
312 #else	/* !AUTOKEY follows */
313 #define	CP_MAXCODE		CP_MAX_NOAUTOKEY
314 #endif	/* !AUTOKEY */
315 
316 /*
317  * Clock variables we understand
318  */
319 #define	CC_TYPE		1
320 #define	CC_TIMECODE	2
321 #define	CC_POLL		3
322 #define	CC_NOREPLY	4
323 #define	CC_BADFORMAT	5
324 #define	CC_BADDATA	6
325 #define	CC_FUDGETIME1	7
326 #define	CC_FUDGETIME2	8
327 #define	CC_FUDGEVAL1	9
328 #define	CC_FUDGEVAL2	10
329 #define	CC_FLAGS	11
330 #define	CC_DEVICE	12
331 #define	CC_VARLIST	13
332 #define	CC_FUDGEMINJIT	14
333 #define	CC_MAXCODE	CC_FUDGEMINJIT
334 
335 /*
336  * System variable values. The array can be indexed by the variable
337  * index to find the textual name.
338  */
339 static const struct ctl_var sys_var[] = {
340 	{ 0,		PADDING, "" },		/* 0 */
341 	{ CS_LEAP,	RW, "leap" },		/* 1 */
342 	{ CS_STRATUM,	RO, "stratum" },	/* 2 */
343 	{ CS_PRECISION, RO, "precision" },	/* 3 */
344 	{ CS_ROOTDELAY, RO, "rootdelay" },	/* 4 */
345 	{ CS_ROOTDISPERSION, RO, "rootdisp" },	/* 5 */
346 	{ CS_REFID,	RO, "refid" },		/* 6 */
347 	{ CS_REFTIME,	RO, "reftime" },	/* 7 */
348 	{ CS_POLL,	RO, "tc" },		/* 8 */
349 	{ CS_PEERID,	RO, "peer" },		/* 9 */
350 	{ CS_OFFSET,	RO, "offset" },		/* 10 */
351 	{ CS_DRIFT,	RO, "frequency" },	/* 11 */
352 	{ CS_JITTER,	RO, "sys_jitter" },	/* 12 */
353 	{ CS_ERROR,	RO, "clk_jitter" },	/* 13 */
354 	{ CS_CLOCK,	RO, "clock" },		/* 14 */
355 	{ CS_PROCESSOR, RO, "processor" },	/* 15 */
356 	{ CS_SYSTEM,	RO, "system" },		/* 16 */
357 	{ CS_VERSION,	RO, "version" },	/* 17 */
358 	{ CS_STABIL,	RO, "clk_wander" },	/* 18 */
359 	{ CS_VARLIST,	RO, "sys_var_list" },	/* 19 */
360 	{ CS_TAI,	RO, "tai" },		/* 20 */
361 	{ CS_LEAPTAB,	RO, "leapsec" },	/* 21 */
362 	{ CS_LEAPEND,	RO, "expire" },		/* 22 */
363 	{ CS_RATE,	RO, "mintc" },		/* 23 */
364 	{ CS_MRU_ENABLED,	RO, "mru_enabled" },	/* 24 */
365 	{ CS_MRU_DEPTH,		RO, "mru_depth" },	/* 25 */
366 	{ CS_MRU_DEEPEST,	RO, "mru_deepest" },	/* 26 */
367 	{ CS_MRU_MINDEPTH,	RO, "mru_mindepth" },	/* 27 */
368 	{ CS_MRU_MAXAGE,	RO, "mru_maxage" },	/* 28 */
369 	{ CS_MRU_MAXDEPTH,	RO, "mru_maxdepth" },	/* 29 */
370 	{ CS_MRU_MEM,		RO, "mru_mem" },	/* 30 */
371 	{ CS_MRU_MAXMEM,	RO, "mru_maxmem" },	/* 31 */
372 	{ CS_SS_UPTIME,		RO, "ss_uptime" },	/* 32 */
373 	{ CS_SS_RESET,		RO, "ss_reset" },	/* 33 */
374 	{ CS_SS_RECEIVED,	RO, "ss_received" },	/* 34 */
375 	{ CS_SS_THISVER,	RO, "ss_thisver" },	/* 35 */
376 	{ CS_SS_OLDVER,		RO, "ss_oldver" },	/* 36 */
377 	{ CS_SS_BADFORMAT,	RO, "ss_badformat" },	/* 37 */
378 	{ CS_SS_BADAUTH,	RO, "ss_badauth" },	/* 38 */
379 	{ CS_SS_DECLINED,	RO, "ss_declined" },	/* 39 */
380 	{ CS_SS_RESTRICTED,	RO, "ss_restricted" },	/* 40 */
381 	{ CS_SS_LIMITED,	RO, "ss_limited" },	/* 41 */
382 	{ CS_SS_KODSENT,	RO, "ss_kodsent" },	/* 42 */
383 	{ CS_SS_PROCESSED,	RO, "ss_processed" },	/* 43 */
384 	{ CS_SS_LAMPORT,	RO, "ss_lamport" },	/* 44 */
385 	{ CS_SS_TSROUNDING,	RO, "ss_tsrounding" },	/* 45 */
386 	{ CS_PEERADR,		RO, "peeradr" },	/* 46 */
387 	{ CS_PEERMODE,		RO, "peermode" },	/* 47 */
388 	{ CS_BCASTDELAY,	RO, "bcastdelay" },	/* 48 */
389 	{ CS_AUTHDELAY,		RO, "authdelay" },	/* 49 */
390 	{ CS_AUTHKEYS,		RO, "authkeys" },	/* 50 */
391 	{ CS_AUTHFREEK,		RO, "authfreek" },	/* 51 */
392 	{ CS_AUTHKLOOKUPS,	RO, "authklookups" },	/* 52 */
393 	{ CS_AUTHKNOTFOUND,	RO, "authknotfound" },	/* 53 */
394 	{ CS_AUTHKUNCACHED,	RO, "authkuncached" },	/* 54 */
395 	{ CS_AUTHKEXPIRED,	RO, "authkexpired" },	/* 55 */
396 	{ CS_AUTHENCRYPTS,	RO, "authencrypts" },	/* 56 */
397 	{ CS_AUTHDECRYPTS,	RO, "authdecrypts" },	/* 57 */
398 	{ CS_AUTHRESET,		RO, "authreset" },	/* 58 */
399 	{ CS_K_OFFSET,		RO, "koffset" },	/* 59 */
400 	{ CS_K_FREQ,		RO, "kfreq" },		/* 60 */
401 	{ CS_K_MAXERR,		RO, "kmaxerr" },	/* 61 */
402 	{ CS_K_ESTERR,		RO, "kesterr" },	/* 62 */
403 	{ CS_K_STFLAGS,		RO, "kstflags" },	/* 63 */
404 	{ CS_K_TIMECONST,	RO, "ktimeconst" },	/* 64 */
405 	{ CS_K_PRECISION,	RO, "kprecis" },	/* 65 */
406 	{ CS_K_FREQTOL,		RO, "kfreqtol" },	/* 66 */
407 	{ CS_K_PPS_FREQ,	RO, "kppsfreq" },	/* 67 */
408 	{ CS_K_PPS_STABIL,	RO, "kppsstab" },	/* 68 */
409 	{ CS_K_PPS_JITTER,	RO, "kppsjitter" },	/* 69 */
410 	{ CS_K_PPS_CALIBDUR,	RO, "kppscalibdur" },	/* 70 */
411 	{ CS_K_PPS_CALIBS,	RO, "kppscalibs" },	/* 71 */
412 	{ CS_K_PPS_CALIBERRS,	RO, "kppscaliberrs" },	/* 72 */
413 	{ CS_K_PPS_JITEXC,	RO, "kppsjitexc" },	/* 73 */
414 	{ CS_K_PPS_STBEXC,	RO, "kppsstbexc" },	/* 74 */
415 	{ CS_IOSTATS_RESET,	RO, "iostats_reset" },	/* 75 */
416 	{ CS_TOTAL_RBUF,	RO, "total_rbuf" },	/* 76 */
417 	{ CS_FREE_RBUF,		RO, "free_rbuf" },	/* 77 */
418 	{ CS_USED_RBUF,		RO, "used_rbuf" },	/* 78 */
419 	{ CS_RBUF_LOWATER,	RO, "rbuf_lowater" },	/* 79 */
420 	{ CS_IO_DROPPED,	RO, "io_dropped" },	/* 80 */
421 	{ CS_IO_IGNORED,	RO, "io_ignored" },	/* 81 */
422 	{ CS_IO_RECEIVED,	RO, "io_received" },	/* 82 */
423 	{ CS_IO_SENT,		RO, "io_sent" },	/* 83 */
424 	{ CS_IO_SENDFAILED,	RO, "io_sendfailed" },	/* 84 */
425 	{ CS_IO_WAKEUPS,	RO, "io_wakeups" },	/* 85 */
426 	{ CS_IO_GOODWAKEUPS,	RO, "io_goodwakeups" },	/* 86 */
427 	{ CS_TIMERSTATS_RESET,	RO, "timerstats_reset" },/* 87 */
428 	{ CS_TIMER_OVERRUNS,	RO, "timer_overruns" },	/* 88 */
429 	{ CS_TIMER_XMTS,	RO, "timer_xmts" },	/* 89 */
430 	{ CS_FUZZ,		RO, "fuzz" },		/* 90 */
431 	{ CS_WANDER_THRESH,	RO, "clk_wander_threshold" }, /* 91 */
432 
433 	{ CS_LEAPSMEARINTV,	RO, "leapsmearinterval" },    /* 92 */
434 	{ CS_LEAPSMEAROFFS,	RO, "leapsmearoffset" },      /* 93 */
435 
436 #ifdef AUTOKEY
437 	{ CS_FLAGS,	RO, "flags" },		/* 1 + CS_MAX_NOAUTOKEY */
438 	{ CS_HOST,	RO, "host" },		/* 2 + CS_MAX_NOAUTOKEY */
439 	{ CS_PUBLIC,	RO, "update" },		/* 3 + CS_MAX_NOAUTOKEY */
440 	{ CS_CERTIF,	RO, "cert" },		/* 4 + CS_MAX_NOAUTOKEY */
441 	{ CS_SIGNATURE,	RO, "signature" },	/* 5 + CS_MAX_NOAUTOKEY */
442 	{ CS_REVTIME,	RO, "until" },		/* 6 + CS_MAX_NOAUTOKEY */
443 	{ CS_IDENT,	RO, "ident" },		/* 7 + CS_MAX_NOAUTOKEY */
444 	{ CS_DIGEST,	RO, "digest" },		/* 8 + CS_MAX_NOAUTOKEY */
445 #endif	/* AUTOKEY */
446 	{ 0,		EOV, "" }		/* 94/102 */
447 };
448 
449 static struct ctl_var *ext_sys_var = NULL;
450 
451 /*
452  * System variables we print by default (in fuzzball order,
453  * more-or-less)
454  */
455 static const u_char def_sys_var[] = {
456 	CS_VERSION,
457 	CS_PROCESSOR,
458 	CS_SYSTEM,
459 	CS_LEAP,
460 	CS_STRATUM,
461 	CS_PRECISION,
462 	CS_ROOTDELAY,
463 	CS_ROOTDISPERSION,
464 	CS_REFID,
465 	CS_REFTIME,
466 	CS_CLOCK,
467 	CS_PEERID,
468 	CS_POLL,
469 	CS_RATE,
470 	CS_OFFSET,
471 	CS_DRIFT,
472 	CS_JITTER,
473 	CS_ERROR,
474 	CS_STABIL,
475 	CS_TAI,
476 	CS_LEAPTAB,
477 	CS_LEAPEND,
478 	CS_LEAPSMEARINTV,
479 	CS_LEAPSMEAROFFS,
480 #ifdef AUTOKEY
481 	CS_HOST,
482 	CS_IDENT,
483 	CS_FLAGS,
484 	CS_DIGEST,
485 	CS_SIGNATURE,
486 	CS_PUBLIC,
487 	CS_CERTIF,
488 #endif	/* AUTOKEY */
489 	0
490 };
491 
492 
493 /*
494  * Peer variable list
495  */
496 static const struct ctl_var peer_var[] = {
497 	{ 0,		PADDING, "" },		/* 0 */
498 	{ CP_CONFIG,	RO, "config" },		/* 1 */
499 	{ CP_AUTHENABLE, RO,	"authenable" },	/* 2 */
500 	{ CP_AUTHENTIC, RO, "authentic" },	/* 3 */
501 	{ CP_SRCADR,	RO, "srcadr" },		/* 4 */
502 	{ CP_SRCPORT,	RO, "srcport" },	/* 5 */
503 	{ CP_DSTADR,	RO, "dstadr" },		/* 6 */
504 	{ CP_DSTPORT,	RO, "dstport" },	/* 7 */
505 	{ CP_LEAP,	RO, "leap" },		/* 8 */
506 	{ CP_HMODE,	RO, "hmode" },		/* 9 */
507 	{ CP_STRATUM,	RO, "stratum" },	/* 10 */
508 	{ CP_PPOLL,	RO, "ppoll" },		/* 11 */
509 	{ CP_HPOLL,	RO, "hpoll" },		/* 12 */
510 	{ CP_PRECISION,	RO, "precision" },	/* 13 */
511 	{ CP_ROOTDELAY,	RO, "rootdelay" },	/* 14 */
512 	{ CP_ROOTDISPERSION, RO, "rootdisp" },	/* 15 */
513 	{ CP_REFID,	RO, "refid" },		/* 16 */
514 	{ CP_REFTIME,	RO, "reftime" },	/* 17 */
515 	{ CP_ORG,	RO, "org" },		/* 18 */
516 	{ CP_REC,	RO, "rec" },		/* 19 */
517 	{ CP_XMT,	RO, "xleave" },		/* 20 */
518 	{ CP_REACH,	RO, "reach" },		/* 21 */
519 	{ CP_UNREACH,	RO, "unreach" },	/* 22 */
520 	{ CP_TIMER,	RO, "timer" },		/* 23 */
521 	{ CP_DELAY,	RO, "delay" },		/* 24 */
522 	{ CP_OFFSET,	RO, "offset" },		/* 25 */
523 	{ CP_JITTER,	RO, "jitter" },		/* 26 */
524 	{ CP_DISPERSION, RO, "dispersion" },	/* 27 */
525 	{ CP_KEYID,	RO, "keyid" },		/* 28 */
526 	{ CP_FILTDELAY,	RO, "filtdelay" },	/* 29 */
527 	{ CP_FILTOFFSET, RO, "filtoffset" },	/* 30 */
528 	{ CP_PMODE,	RO, "pmode" },		/* 31 */
529 	{ CP_RECEIVED,	RO, "received"},	/* 32 */
530 	{ CP_SENT,	RO, "sent" },		/* 33 */
531 	{ CP_FILTERROR,	RO, "filtdisp" },	/* 34 */
532 	{ CP_FLASH,	RO, "flash" },		/* 35 */
533 	{ CP_TTL,	RO, "ttl" },		/* 36 */
534 	{ CP_VARLIST,	RO, "peer_var_list" },	/* 37 */
535 	{ CP_IN,	RO, "in" },		/* 38 */
536 	{ CP_OUT,	RO, "out" },		/* 39 */
537 	{ CP_RATE,	RO, "headway" },	/* 40 */
538 	{ CP_BIAS,	RO, "bias" },		/* 41 */
539 	{ CP_SRCHOST,	RO, "srchost" },	/* 42 */
540 	{ CP_TIMEREC,	RO, "timerec" },	/* 43 */
541 	{ CP_TIMEREACH,	RO, "timereach" },	/* 44 */
542 	{ CP_BADAUTH,	RO, "badauth" },	/* 45 */
543 	{ CP_BOGUSORG,	RO, "bogusorg" },	/* 46 */
544 	{ CP_OLDPKT,	RO, "oldpkt" },		/* 47 */
545 	{ CP_SELDISP,	RO, "seldisp" },	/* 48 */
546 	{ CP_SELBROKEN,	RO, "selbroken" },	/* 49 */
547 	{ CP_CANDIDATE, RO, "candidate" },	/* 50 */
548 #ifdef AUTOKEY
549 	{ CP_FLAGS,	RO, "flags" },		/* 1 + CP_MAX_NOAUTOKEY */
550 	{ CP_HOST,	RO, "host" },		/* 2 + CP_MAX_NOAUTOKEY */
551 	{ CP_VALID,	RO, "valid" },		/* 3 + CP_MAX_NOAUTOKEY */
552 	{ CP_INITSEQ,	RO, "initsequence" },	/* 4 + CP_MAX_NOAUTOKEY */
553 	{ CP_INITKEY,	RO, "initkey" },	/* 5 + CP_MAX_NOAUTOKEY */
554 	{ CP_INITTSP,	RO, "timestamp" },	/* 6 + CP_MAX_NOAUTOKEY */
555 	{ CP_SIGNATURE,	RO, "signature" },	/* 7 + CP_MAX_NOAUTOKEY */
556 	{ CP_IDENT,	RO, "ident" },		/* 8 + CP_MAX_NOAUTOKEY */
557 #endif	/* AUTOKEY */
558 	{ 0,		EOV, "" }		/* 50/58 */
559 };
560 
561 
562 /*
563  * Peer variables we print by default
564  */
565 static const u_char def_peer_var[] = {
566 	CP_SRCADR,
567 	CP_SRCPORT,
568 	CP_SRCHOST,
569 	CP_DSTADR,
570 	CP_DSTPORT,
571 	CP_OUT,
572 	CP_IN,
573 	CP_LEAP,
574 	CP_STRATUM,
575 	CP_PRECISION,
576 	CP_ROOTDELAY,
577 	CP_ROOTDISPERSION,
578 	CP_REFID,
579 	CP_REFTIME,
580 	CP_REC,
581 	CP_REACH,
582 	CP_UNREACH,
583 	CP_HMODE,
584 	CP_PMODE,
585 	CP_HPOLL,
586 	CP_PPOLL,
587 	CP_RATE,
588 	CP_FLASH,
589 	CP_KEYID,
590 	CP_TTL,
591 	CP_OFFSET,
592 	CP_DELAY,
593 	CP_DISPERSION,
594 	CP_JITTER,
595 	CP_XMT,
596 	CP_BIAS,
597 	CP_FILTDELAY,
598 	CP_FILTOFFSET,
599 	CP_FILTERROR,
600 #ifdef AUTOKEY
601 	CP_HOST,
602 	CP_FLAGS,
603 	CP_SIGNATURE,
604 	CP_VALID,
605 	CP_INITSEQ,
606 	CP_IDENT,
607 #endif	/* AUTOKEY */
608 	0
609 };
610 
611 
612 #ifdef REFCLOCK
613 /*
614  * Clock variable list
615  */
616 static const struct ctl_var clock_var[] = {
617 	{ 0,		PADDING, "" },		/* 0 */
618 	{ CC_TYPE,	RO, "type" },		/* 1 */
619 	{ CC_TIMECODE,	RO, "timecode" },	/* 2 */
620 	{ CC_POLL,	RO, "poll" },		/* 3 */
621 	{ CC_NOREPLY,	RO, "noreply" },	/* 4 */
622 	{ CC_BADFORMAT, RO, "badformat" },	/* 5 */
623 	{ CC_BADDATA,	RO, "baddata" },	/* 6 */
624 	{ CC_FUDGETIME1, RO, "fudgetime1" },	/* 7 */
625 	{ CC_FUDGETIME2, RO, "fudgetime2" },	/* 8 */
626 	{ CC_FUDGEVAL1, RO, "stratum" },	/* 9 */
627 	{ CC_FUDGEVAL2, RO, "refid" },		/* 10 */
628 	{ CC_FLAGS,	RO, "flags" },		/* 11 */
629 	{ CC_DEVICE,	RO, "device" },		/* 12 */
630 	{ CC_VARLIST,	RO, "clock_var_list" },	/* 13 */
631 	{ CC_FUDGEMINJIT, RO, "minjitter" },	/* 14 */
632 	{ 0,		EOV, ""  }		/* 15 */
633 };
634 
635 
636 /*
637  * Clock variables printed by default
638  */
639 static const u_char def_clock_var[] = {
640 	CC_DEVICE,
641 	CC_TYPE,	/* won't be output if device = known */
642 	CC_TIMECODE,
643 	CC_POLL,
644 	CC_NOREPLY,
645 	CC_BADFORMAT,
646 	CC_BADDATA,
647 	CC_FUDGEMINJIT,
648 	CC_FUDGETIME1,
649 	CC_FUDGETIME2,
650 	CC_FUDGEVAL1,
651 	CC_FUDGEVAL2,
652 	CC_FLAGS,
653 	0
654 };
655 #endif
656 
657 /*
658  * MRU string constants shared by send_mru_entry() and read_mru_list().
659  */
660 static const char addr_fmt[] =		"addr.%d";
661 static const char last_fmt[] =		"last.%d";
662 
663 /*
664  * System and processor definitions.
665  */
666 #ifndef HAVE_UNAME
667 # ifndef STR_SYSTEM
668 #  define		STR_SYSTEM	"UNIX"
669 # endif
670 # ifndef STR_PROCESSOR
671 #  define		STR_PROCESSOR	"unknown"
672 # endif
673 
674 static const char str_system[] = STR_SYSTEM;
675 static const char str_processor[] = STR_PROCESSOR;
676 #else
677 # include <sys/utsname.h>
678 static struct utsname utsnamebuf;
679 #endif /* HAVE_UNAME */
680 
681 /*
682  * Trap structures. We only allow a few of these, and send a copy of
683  * each async message to each live one. Traps time out after an hour, it
684  * is up to the trap receipient to keep resetting it to avoid being
685  * timed out.
686  */
687 /* ntp_request.c */
688 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
689 int num_ctl_traps;
690 
691 /*
692  * Type bits, for ctlsettrap() call.
693  */
694 #define TRAP_TYPE_CONFIG	0	/* used by configuration code */
695 #define TRAP_TYPE_PRIO		1	/* priority trap */
696 #define TRAP_TYPE_NONPRIO	2	/* nonpriority trap */
697 
698 
699 /*
700  * List relating reference clock types to control message time sources.
701  * Index by the reference clock type. This list will only be used iff
702  * the reference clock driver doesn't set peer->sstclktype to something
703  * different than CTL_SST_TS_UNSPEC.
704  */
705 #ifdef REFCLOCK
706 static const u_char clocktypes[] = {
707 	CTL_SST_TS_NTP,		/* REFCLK_NONE (0) */
708 	CTL_SST_TS_LOCAL,	/* REFCLK_LOCALCLOCK (1) */
709 	CTL_SST_TS_UHF,		/* deprecated REFCLK_GPS_TRAK (2) */
710 	CTL_SST_TS_HF,		/* REFCLK_WWV_PST (3) */
711 	CTL_SST_TS_LF,		/* REFCLK_WWVB_SPECTRACOM (4) */
712 	CTL_SST_TS_UHF,		/* REFCLK_TRUETIME (5) */
713 	CTL_SST_TS_UHF,		/* REFCLK_IRIG_AUDIO (6) */
714 	CTL_SST_TS_HF,		/* REFCLK_CHU (7) */
715 	CTL_SST_TS_LF,		/* REFCLOCK_PARSE (default) (8) */
716 	CTL_SST_TS_LF,		/* REFCLK_GPS_MX4200 (9) */
717 	CTL_SST_TS_UHF,		/* REFCLK_GPS_AS2201 (10) */
718 	CTL_SST_TS_UHF,		/* REFCLK_GPS_ARBITER (11) */
719 	CTL_SST_TS_UHF,		/* REFCLK_IRIG_TPRO (12) */
720 	CTL_SST_TS_ATOM,	/* REFCLK_ATOM_LEITCH (13) */
721 	CTL_SST_TS_LF,		/* deprecated REFCLK_MSF_EES (14) */
722 	CTL_SST_TS_NTP,		/* not used (15) */
723 	CTL_SST_TS_UHF,		/* REFCLK_IRIG_BANCOMM (16) */
724 	CTL_SST_TS_UHF,		/* REFCLK_GPS_DATU (17) */
725 	CTL_SST_TS_TELEPHONE,	/* REFCLK_NIST_ACTS (18) */
726 	CTL_SST_TS_HF,		/* REFCLK_WWV_HEATH (19) */
727 	CTL_SST_TS_UHF,		/* REFCLK_GPS_NMEA (20) */
728 	CTL_SST_TS_UHF,		/* REFCLK_GPS_VME (21) */
729 	CTL_SST_TS_ATOM,	/* REFCLK_ATOM_PPS (22) */
730 	CTL_SST_TS_NTP,		/* not used (23) */
731 	CTL_SST_TS_NTP,		/* not used (24) */
732 	CTL_SST_TS_NTP,		/* not used (25) */
733 	CTL_SST_TS_UHF,		/* REFCLK_GPS_HP (26) */
734 	CTL_SST_TS_LF,		/* REFCLK_ARCRON_MSF (27) */
735 	CTL_SST_TS_UHF,		/* REFCLK_SHM (28) */
736 	CTL_SST_TS_UHF,		/* REFCLK_PALISADE (29) */
737 	CTL_SST_TS_UHF,		/* REFCLK_ONCORE (30) */
738 	CTL_SST_TS_UHF,		/* REFCLK_JUPITER (31) */
739 	CTL_SST_TS_LF,		/* REFCLK_CHRONOLOG (32) */
740 	CTL_SST_TS_LF,		/* REFCLK_DUMBCLOCK (33) */
741 	CTL_SST_TS_LF,		/* REFCLK_ULINK (34) */
742 	CTL_SST_TS_LF,		/* REFCLK_PCF (35) */
743 	CTL_SST_TS_HF,		/* REFCLK_WWV (36) */
744 	CTL_SST_TS_LF,		/* REFCLK_FG (37) */
745 	CTL_SST_TS_UHF,		/* REFCLK_HOPF_SERIAL (38) */
746 	CTL_SST_TS_UHF,		/* REFCLK_HOPF_PCI (39) */
747 	CTL_SST_TS_LF,		/* REFCLK_JJY (40) */
748 	CTL_SST_TS_UHF,		/* REFCLK_TT560 (41) */
749 	CTL_SST_TS_UHF,		/* REFCLK_ZYFER (42) */
750 	CTL_SST_TS_UHF,		/* REFCLK_RIPENCC (43) */
751 	CTL_SST_TS_UHF,		/* REFCLK_NEOCLOCK4X (44) */
752 	CTL_SST_TS_UHF,		/* REFCLK_TSYNCPCI (45) */
753 	CTL_SST_TS_UHF		/* REFCLK_GPSDJSON (46) */
754 };
755 #endif  /* REFCLOCK */
756 
757 
758 /*
759  * Keyid used for authenticating write requests.
760  */
761 keyid_t ctl_auth_keyid;
762 
763 /*
764  * We keep track of the last error reported by the system internally
765  */
766 static	u_char ctl_sys_last_event;
767 static	u_char ctl_sys_num_events;
768 
769 
770 /*
771  * Statistic counters to keep track of requests and responses.
772  */
773 u_long ctltimereset;		/* time stats reset */
774 u_long numctlreq;		/* number of requests we've received */
775 u_long numctlbadpkts;		/* number of bad control packets */
776 u_long numctlresponses;		/* number of resp packets sent with data */
777 u_long numctlfrags;		/* number of fragments sent */
778 u_long numctlerrors;		/* number of error responses sent */
779 u_long numctltooshort;		/* number of too short input packets */
780 u_long numctlinputresp;		/* number of responses on input */
781 u_long numctlinputfrag;		/* number of fragments on input */
782 u_long numctlinputerr;		/* number of input pkts with err bit set */
783 u_long numctlbadoffset;		/* number of input pkts with nonzero offset */
784 u_long numctlbadversion;	/* number of input pkts with unknown version */
785 u_long numctldatatooshort;	/* data too short for count */
786 u_long numctlbadop;		/* bad op code found in packet */
787 u_long numasyncmsgs;		/* number of async messages we've sent */
788 
789 /*
790  * Response packet used by these routines. Also some state information
791  * so that we can handle packet formatting within a common set of
792  * subroutines.  Note we try to enter data in place whenever possible,
793  * but the need to set the more bit correctly means we occasionally
794  * use the extra buffer and copy.
795  */
796 static struct ntp_control rpkt;
797 static u_char	res_version;
798 static u_char	res_opcode;
799 static associd_t res_associd;
800 static u_short	res_frags;	/* datagrams in this response */
801 static int	res_offset;	/* offset of payload in response */
802 static u_char * datapt;
803 static u_char * dataend;
804 static int	datalinelen;
805 static int	datasent;	/* flag to avoid initial ", " */
806 static int	datanotbinflag;
807 static sockaddr_u *rmt_addr;
808 static struct interface *lcl_inter;
809 
810 static u_char	res_authenticate;
811 static u_char	res_authokay;
812 static keyid_t	res_keyid;
813 
814 #define MAXDATALINELEN	(72)
815 
816 static u_char	res_async;	/* sending async trap response? */
817 
818 /*
819  * Pointers for saving state when decoding request packets
820  */
821 static	char *reqpt;
822 static	char *reqend;
823 
824 #ifndef MIN
825 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
826 #endif
827 
828 /*
829  * init_control - initialize request data
830  */
831 void
832 init_control(void)
833 {
834 	size_t i;
835 
836 #ifdef HAVE_UNAME
837 	uname(&utsnamebuf);
838 #endif /* HAVE_UNAME */
839 
840 	ctl_clr_stats();
841 
842 	ctl_auth_keyid = 0;
843 	ctl_sys_last_event = EVNT_UNSPEC;
844 	ctl_sys_num_events = 0;
845 
846 	num_ctl_traps = 0;
847 	for (i = 0; i < COUNTOF(ctl_traps); i++)
848 		ctl_traps[i].tr_flags = 0;
849 }
850 
851 
852 /*
853  * ctl_error - send an error response for the current request
854  */
855 static void
856 ctl_error(
857 	u_char errcode
858 	)
859 {
860 	size_t		maclen;
861 
862 	numctlerrors++;
863 	DPRINTF(3, ("sending control error %u\n", errcode));
864 
865 	/*
866 	 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
867 	 * have already been filled in.
868 	 */
869 	rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
870 			(res_opcode & CTL_OP_MASK);
871 	rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
872 	rpkt.count = 0;
873 
874 	/*
875 	 * send packet and bump counters
876 	 */
877 	if (res_authenticate && sys_authenticate) {
878 		maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
879 				     CTL_HEADER_LEN);
880 		sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
881 			CTL_HEADER_LEN + maclen);
882 	} else
883 		sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
884 			CTL_HEADER_LEN);
885 }
886 
887 int/*BOOL*/
888 is_safe_filename(const char * name)
889 {
890 	/* We need a strict validation of filenames we should write: The
891 	 * daemon might run with special permissions and is remote
892 	 * controllable, so we better take care what we allow as file
893 	 * name!
894 	 *
895 	 * The first character must be digit or a letter from the ASCII
896 	 * base plane or a '_' ([_A-Za-z0-9]), the following characters
897 	 * must be from [-._+A-Za-z0-9].
898 	 *
899 	 * We do not trust the character classification much here: Since
900 	 * the NTP protocol makes no provisions for UTF-8 or local code
901 	 * pages, we strictly require the 7bit ASCII code page.
902 	 *
903 	 * The following table is a packed bit field of 128 two-bit
904 	 * groups. The LSB in each group tells us if a character is
905 	 * acceptable at the first position, the MSB if the character is
906 	 * accepted at any other position.
907 	 *
908 	 * This does not ensure that the file name is syntactically
909 	 * correct (multiple dots will not work with VMS...) but it will
910 	 * exclude potential globbing bombs and directory traversal. It
911 	 * also rules out drive selection. (For systems that have this
912 	 * notion, like Windows or VMS.)
913 	 */
914 	static const uint32_t chclass[8] = {
915 		0x00000000, 0x00000000,
916 		0x28800000, 0x000FFFFF,
917 		0xFFFFFFFC, 0xC03FFFFF,
918 		0xFFFFFFFC, 0x003FFFFF
919 	};
920 
921 	u_int widx, bidx, mask;
922 	if ( ! (name && *name))
923 		return FALSE;
924 
925 	mask = 1u;
926 	while (0 != (widx = (u_char)*name++)) {
927 		bidx = (widx & 15) << 1;
928 		widx = widx >> 4;
929 		if (widx >= sizeof(chclass)/sizeof(chclass[0]))
930 			return FALSE;
931 		if (0 == ((chclass[widx] >> bidx) & mask))
932 			return FALSE;
933 		mask = 2u;
934 	}
935 	return TRUE;
936 }
937 
938 
939 /*
940  * save_config - Implements ntpq -c "saveconfig <filename>"
941  *		 Writes current configuration including any runtime
942  *		 changes by ntpq's :config or config-from-file
943  *
944  * Note: There should be no buffer overflow or truncation in the
945  * processing of file names -- both cause security problems. This is bit
946  * painful to code but essential here.
947  */
948 void
949 save_config(
950 	struct recvbuf *rbufp,
951 	int restrict_mask
952 	)
953 {
954 	/* block directory traversal by searching for characters that
955 	 * indicate directory components in a file path.
956 	 *
957 	 * Conceptually we should be searching for DIRSEP in filename,
958 	 * however Windows actually recognizes both forward and
959 	 * backslashes as equivalent directory separators at the API
960 	 * level.  On POSIX systems we could allow '\\' but such
961 	 * filenames are tricky to manipulate from a shell, so just
962 	 * reject both types of slashes on all platforms.
963 	 */
964 	/* TALOS-CAN-0062: block directory traversal for VMS, too */
965 	static const char * illegal_in_filename =
966 #if defined(VMS)
967 	    ":[]"	/* do not allow drive and path components here */
968 #elif defined(SYS_WINNT)
969 	    ":\\/"	/* path and drive separators */
970 #else
971 	    "\\/"	/* separator and critical char for POSIX */
972 #endif
973 	    ;
974 	char reply[128];
975 #ifdef SAVECONFIG
976 	static const char savedconfig_eq[] = "savedconfig=";
977 
978 	/* Build a safe open mode from the available mode flags. We want
979 	 * to create a new file and write it in text mode (when
980 	 * applicable -- only Windows does this...)
981 	 */
982 	static const int openmode = O_CREAT | O_TRUNC | O_WRONLY
983 #  if defined(O_EXCL)		/* posix, vms */
984 	    | O_EXCL
985 #  elif defined(_O_EXCL)	/* windows is alway very special... */
986 	    | _O_EXCL
987 #  endif
988 #  if defined(_O_TEXT)		/* windows, again */
989 	    | _O_TEXT
990 #endif
991 	    ;
992 
993 	char filespec[128];
994 	char filename[128];
995 	char fullpath[512];
996 	char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
997 	time_t now;
998 	int fd;
999 	FILE *fptr;
1000 	int prc;
1001 	size_t reqlen;
1002 #endif
1003 
1004 	if (RES_NOMODIFY & restrict_mask) {
1005 		ctl_printf("%s", "saveconfig prohibited by restrict ... nomodify");
1006 		ctl_flushpkt(0);
1007 		NLOG(NLOG_SYSINFO)
1008 			msyslog(LOG_NOTICE,
1009 				"saveconfig from %s rejected due to nomodify restriction",
1010 				stoa(&rbufp->recv_srcadr));
1011 		sys_restricted++;
1012 		return;
1013 	}
1014 
1015 #ifdef SAVECONFIG
1016 	if (NULL == saveconfigdir) {
1017 		ctl_printf("%s", "saveconfig prohibited, no saveconfigdir configured");
1018 		ctl_flushpkt(0);
1019 		NLOG(NLOG_SYSINFO)
1020 			msyslog(LOG_NOTICE,
1021 				"saveconfig from %s rejected, no saveconfigdir",
1022 				stoa(&rbufp->recv_srcadr));
1023 		return;
1024 	}
1025 
1026 	/* The length checking stuff gets serious. Do not assume a NUL
1027 	 * byte can be found, but if so, use it to calculate the needed
1028 	 * buffer size. If the available buffer is too short, bail out;
1029 	 * likewise if there is no file spec. (The latter will not
1030 	 * happen when using NTPQ, but there are other ways to craft a
1031 	 * network packet!)
1032 	 */
1033 	reqlen = (size_t)(reqend - reqpt);
1034 	if (0 != reqlen) {
1035 		char * nulpos = (char*)memchr(reqpt, 0, reqlen);
1036 		if (NULL != nulpos)
1037 			reqlen = (size_t)(nulpos - reqpt);
1038 	}
1039 	if (0 == reqlen)
1040 		return;
1041 	if (reqlen >= sizeof(filespec)) {
1042 		ctl_printf("saveconfig exceeded maximum raw name length (%u)",
1043 			   (u_int)sizeof(filespec));
1044 		ctl_flushpkt(0);
1045 		msyslog(LOG_NOTICE,
1046 			"saveconfig exceeded maximum raw name length from %s",
1047 			stoa(&rbufp->recv_srcadr));
1048 		return;
1049 	}
1050 
1051 	/* copy data directly as we exactly know the size */
1052 	memcpy(filespec, reqpt, reqlen);
1053 	filespec[reqlen] = '\0';
1054 
1055 	/*
1056 	 * allow timestamping of the saved config filename with
1057 	 * strftime() format such as:
1058 	 *   ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
1059 	 * XXX: Nice feature, but not too safe.
1060 	 * YYY: The check for permitted characters in file names should
1061 	 *      weed out the worst. Let's hope 'strftime()' does not
1062 	 *      develop pathological problems.
1063 	 */
1064 	time(&now);
1065 	if (0 == strftime(filename, sizeof(filename), filespec,
1066 			  localtime(&now)))
1067 	{
1068 		/*
1069 		 * If we arrive here, 'strftime()' balked; most likely
1070 		 * the buffer was too short. (Or it encounterd an empty
1071 		 * format, or just a format that expands to an empty
1072 		 * string.) We try to use the original name, though this
1073 		 * is very likely to fail later if there are format
1074 		 * specs in the string. Note that truncation cannot
1075 		 * happen here as long as both buffers have the same
1076 		 * size!
1077 		 */
1078 		strlcpy(filename, filespec, sizeof(filename));
1079 	}
1080 
1081 	/*
1082 	 * Check the file name for sanity. This might/will rule out file
1083 	 * names that would be legal but problematic, and it blocks
1084 	 * directory traversal.
1085 	 */
1086 	if (!is_safe_filename(filename)) {
1087 		ctl_printf("saveconfig rejects unsafe file name '%s'",
1088 			   filename);
1089 		ctl_flushpkt(0);
1090 		msyslog(LOG_NOTICE,
1091 			"saveconfig rejects unsafe file name from %s",
1092 			stoa(&rbufp->recv_srcadr));
1093 		return;
1094 	}
1095 
1096 	/*
1097 	 * XXX: This next test may not be needed with is_safe_filename()
1098 	 */
1099 
1100 	/* block directory/drive traversal */
1101 	/* TALOS-CAN-0062: block directory traversal for VMS, too */
1102 	if (NULL != strpbrk(filename, illegal_in_filename)) {
1103 		snprintf(reply, sizeof(reply),
1104 			 "saveconfig does not allow directory in filename");
1105 		ctl_putdata(reply, strlen(reply), 0);
1106 		ctl_flushpkt(0);
1107 		msyslog(LOG_NOTICE,
1108 			"saveconfig rejects unsafe file name from %s",
1109 			stoa(&rbufp->recv_srcadr));
1110 		return;
1111 	}
1112 
1113 	/* concatenation of directory and path can cause another
1114 	 * truncation...
1115 	 */
1116 	prc = snprintf(fullpath, sizeof(fullpath), "%s%s",
1117 		       saveconfigdir, filename);
1118 	if (prc < 0 || (size_t)prc >= sizeof(fullpath)) {
1119 		ctl_printf("saveconfig exceeded maximum path length (%u)",
1120 			   (u_int)sizeof(fullpath));
1121 		ctl_flushpkt(0);
1122 		msyslog(LOG_NOTICE,
1123 			"saveconfig exceeded maximum path length from %s",
1124 			stoa(&rbufp->recv_srcadr));
1125 		return;
1126 	}
1127 
1128 	fd = open(fullpath, openmode, S_IRUSR | S_IWUSR);
1129 	if (-1 == fd)
1130 		fptr = NULL;
1131 	else
1132 		fptr = fdopen(fd, "w");
1133 
1134 	if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
1135 		ctl_printf("Unable to save configuration to file '%s': %s",
1136 			   filename, strerror(errno));
1137 		msyslog(LOG_ERR,
1138 			"saveconfig %s from %s failed", filename,
1139 			stoa(&rbufp->recv_srcadr));
1140 	} else {
1141 		ctl_printf("Configuration saved to '%s'", filename);
1142 		msyslog(LOG_NOTICE,
1143 			"Configuration saved to '%s' (requested by %s)",
1144 			fullpath, stoa(&rbufp->recv_srcadr));
1145 		/*
1146 		 * save the output filename in system variable
1147 		 * savedconfig, retrieved with:
1148 		 *   ntpq -c "rv 0 savedconfig"
1149 		 * Note: the way 'savedconfig' is defined makes overflow
1150 		 * checks unnecessary here.
1151 		 */
1152 		snprintf(savedconfig, sizeof(savedconfig), "%s%s",
1153 			 savedconfig_eq, filename);
1154 		set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1155 	}
1156 
1157 	if (NULL != fptr)
1158 		fclose(fptr);
1159 #else	/* !SAVECONFIG follows */
1160 	ctl_printf("%s",
1161 		   "saveconfig unavailable, configured with --disable-saveconfig");
1162 #endif
1163 	ctl_flushpkt(0);
1164 }
1165 
1166 
1167 /*
1168  * process_control - process an incoming control message
1169  */
1170 void
1171 process_control(
1172 	struct recvbuf *rbufp,
1173 	int restrict_mask
1174 	)
1175 {
1176 	struct ntp_control *pkt;
1177 	int req_count;
1178 	int req_data;
1179 	const struct ctl_proc *cc;
1180 	keyid_t *pkid;
1181 	int properlen;
1182 	size_t maclen;
1183 
1184 	DPRINTF(3, ("in process_control()\n"));
1185 
1186 	/*
1187 	 * Save the addresses for error responses
1188 	 */
1189 	numctlreq++;
1190 	rmt_addr = &rbufp->recv_srcadr;
1191 	lcl_inter = rbufp->dstadr;
1192 	pkt = (struct ntp_control *)&rbufp->recv_pkt;
1193 
1194 	/*
1195 	 * If the length is less than required for the header,
1196 	 * ignore it.
1197 	 */
1198 	if (rbufp->recv_length < (int)CTL_HEADER_LEN) {
1199 		DPRINTF(1, ("Short control packet\n"));
1200 		numctltooshort++;
1201 		return;
1202 	}
1203 
1204 	/*
1205 	 * If this packet is a response or a fragment, ignore it.
1206 	 */
1207 	if (   (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1208 	    || pkt->offset != 0) {
1209 		DPRINTF(1, ("invalid format in control packet\n"));
1210 		if (CTL_RESPONSE & pkt->r_m_e_op)
1211 			numctlinputresp++;
1212 		if (CTL_MORE & pkt->r_m_e_op)
1213 			numctlinputfrag++;
1214 		if (CTL_ERROR & pkt->r_m_e_op)
1215 			numctlinputerr++;
1216 		if (pkt->offset != 0)
1217 			numctlbadoffset++;
1218 		return;
1219 	}
1220 
1221 	res_version = PKT_VERSION(pkt->li_vn_mode);
1222 	if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1223 		DPRINTF(1, ("unknown version %d in control packet\n",
1224 			    res_version));
1225 		numctlbadversion++;
1226 		return;
1227 	}
1228 
1229 	/*
1230 	 * Pull enough data from the packet to make intelligent
1231 	 * responses
1232 	 */
1233 	rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1234 					 MODE_CONTROL);
1235 	res_opcode = pkt->r_m_e_op;
1236 	rpkt.sequence = pkt->sequence;
1237 	rpkt.associd = pkt->associd;
1238 	rpkt.status = 0;
1239 	res_frags = 1;
1240 	res_offset = 0;
1241 	res_associd = htons(pkt->associd);
1242 	res_async = FALSE;
1243 	res_authenticate = FALSE;
1244 	res_keyid = 0;
1245 	res_authokay = FALSE;
1246 	req_count = (int)ntohs(pkt->count);
1247 	datanotbinflag = FALSE;
1248 	datalinelen = 0;
1249 	datasent = 0;
1250 	datapt = rpkt.u.data;
1251 	dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1252 
1253 	if ((rbufp->recv_length & 0x3) != 0)
1254 		DPRINTF(3, ("Control packet length %d unrounded\n",
1255 			    rbufp->recv_length));
1256 
1257 	/*
1258 	 * We're set up now. Make sure we've got at least enough
1259 	 * incoming data space to match the count.
1260 	 */
1261 	req_data = rbufp->recv_length - CTL_HEADER_LEN;
1262 	if (req_data < req_count || rbufp->recv_length & 0x3) {
1263 		ctl_error(CERR_BADFMT);
1264 		numctldatatooshort++;
1265 		return;
1266 	}
1267 
1268 	properlen = req_count + CTL_HEADER_LEN;
1269 	/* round up proper len to a 8 octet boundary */
1270 
1271 	properlen = (properlen + 7) & ~7;
1272 	maclen = rbufp->recv_length - properlen;
1273 	if ((rbufp->recv_length & 3) == 0 &&
1274 	    maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1275 	    sys_authenticate) {
1276 		res_authenticate = TRUE;
1277 		pkid = (void *)((char *)pkt + properlen);
1278 		res_keyid = ntohl(*pkid);
1279 		DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1280 			    rbufp->recv_length, properlen, res_keyid,
1281 			    maclen));
1282 
1283 		if (!authistrustedip(res_keyid, &rbufp->recv_srcadr))
1284 			DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1285 		else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1286 				     rbufp->recv_length - maclen,
1287 				     maclen)) {
1288 			res_authokay = TRUE;
1289 			DPRINTF(3, ("authenticated okay\n"));
1290 		} else {
1291 			res_keyid = 0;
1292 			DPRINTF(3, ("authentication failed\n"));
1293 		}
1294 	}
1295 
1296 	/*
1297 	 * Set up translate pointers
1298 	 */
1299 	reqpt = (char *)pkt->u.data;
1300 	reqend = reqpt + req_count;
1301 
1302 	/*
1303 	 * Look for the opcode processor
1304 	 */
1305 	for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1306 		if (cc->control_code == res_opcode) {
1307 			DPRINTF(3, ("opcode %d, found command handler\n",
1308 				    res_opcode));
1309 			if (cc->flags == AUTH
1310 			    && (!res_authokay
1311 				|| res_keyid != ctl_auth_keyid)) {
1312 				ctl_error(CERR_PERMISSION);
1313 				return;
1314 			}
1315 			(cc->handler)(rbufp, restrict_mask);
1316 			return;
1317 		}
1318 	}
1319 
1320 	/*
1321 	 * Can't find this one, return an error.
1322 	 */
1323 	numctlbadop++;
1324 	ctl_error(CERR_BADOP);
1325 	return;
1326 }
1327 
1328 
1329 /*
1330  * ctlpeerstatus - return a status word for this peer
1331  */
1332 u_short
1333 ctlpeerstatus(
1334 	register struct peer *p
1335 	)
1336 {
1337 	u_short status;
1338 
1339 	status = p->status;
1340 	if (FLAG_CONFIG & p->flags)
1341 		status |= CTL_PST_CONFIG;
1342 	if (p->keyid)
1343 		status |= CTL_PST_AUTHENABLE;
1344 	if (FLAG_AUTHENTIC & p->flags)
1345 		status |= CTL_PST_AUTHENTIC;
1346 	if (p->reach)
1347 		status |= CTL_PST_REACH;
1348 	if (MDF_TXONLY_MASK & p->cast_flags)
1349 		status |= CTL_PST_BCAST;
1350 
1351 	return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1352 }
1353 
1354 
1355 /*
1356  * ctlclkstatus - return a status word for this clock
1357  */
1358 #ifdef REFCLOCK
1359 static u_short
1360 ctlclkstatus(
1361 	struct refclockstat *pcs
1362 	)
1363 {
1364 	return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1365 }
1366 #endif
1367 
1368 
1369 /*
1370  * ctlsysstatus - return the system status word
1371  */
1372 u_short
1373 ctlsysstatus(void)
1374 {
1375 	register u_char this_clock;
1376 
1377 	this_clock = CTL_SST_TS_UNSPEC;
1378 #ifdef REFCLOCK
1379 	if (sys_peer != NULL) {
1380 		if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1381 			this_clock = sys_peer->sstclktype;
1382 		else if (sys_peer->refclktype < COUNTOF(clocktypes))
1383 			this_clock = clocktypes[sys_peer->refclktype];
1384 	}
1385 #else /* REFCLOCK */
1386 	if (sys_peer != 0)
1387 		this_clock = CTL_SST_TS_NTP;
1388 #endif /* REFCLOCK */
1389 	return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1390 			      ctl_sys_last_event);
1391 }
1392 
1393 
1394 /*
1395  * ctl_flushpkt - write out the current packet and prepare
1396  *		  another if necessary.
1397  */
1398 static void
1399 ctl_flushpkt(
1400 	u_char more
1401 	)
1402 {
1403 	size_t i;
1404 	size_t dlen;
1405 	size_t sendlen;
1406 	size_t maclen;
1407 	size_t totlen;
1408 	keyid_t keyid;
1409 
1410 	dlen = datapt - rpkt.u.data;
1411 	if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1412 		/*
1413 		 * Big hack, output a trailing \r\n
1414 		 */
1415 		*datapt++ = '\r';
1416 		*datapt++ = '\n';
1417 		dlen += 2;
1418 	}
1419 	sendlen = dlen + CTL_HEADER_LEN;
1420 
1421 	/*
1422 	 * Pad to a multiple of 32 bits
1423 	 */
1424 	while (sendlen & 0x3) {
1425 		*datapt++ = '\0';
1426 		sendlen++;
1427 	}
1428 
1429 	/*
1430 	 * Fill in the packet with the current info
1431 	 */
1432 	rpkt.r_m_e_op = CTL_RESPONSE | more |
1433 			(res_opcode & CTL_OP_MASK);
1434 	rpkt.count = htons((u_short)dlen);
1435 	rpkt.offset = htons((u_short)res_offset);
1436 	if (res_async) {
1437 		for (i = 0; i < COUNTOF(ctl_traps); i++) {
1438 			if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1439 				rpkt.li_vn_mode =
1440 				    PKT_LI_VN_MODE(
1441 					sys_leap,
1442 					ctl_traps[i].tr_version,
1443 					MODE_CONTROL);
1444 				rpkt.sequence =
1445 				    htons(ctl_traps[i].tr_sequence);
1446 				sendpkt(&ctl_traps[i].tr_addr,
1447 					ctl_traps[i].tr_localaddr, -4,
1448 					(struct pkt *)&rpkt, sendlen);
1449 				if (!more)
1450 					ctl_traps[i].tr_sequence++;
1451 				numasyncmsgs++;
1452 			}
1453 		}
1454 	} else {
1455 		if (res_authenticate && sys_authenticate) {
1456 			totlen = sendlen;
1457 			/*
1458 			 * If we are going to authenticate, then there
1459 			 * is an additional requirement that the MAC
1460 			 * begin on a 64 bit boundary.
1461 			 */
1462 			while (totlen & 7) {
1463 				*datapt++ = '\0';
1464 				totlen++;
1465 			}
1466 			keyid = htonl(res_keyid);
1467 			memcpy(datapt, &keyid, sizeof(keyid));
1468 			maclen = authencrypt(res_keyid,
1469 					     (u_int32 *)&rpkt, totlen);
1470 			sendpkt(rmt_addr, lcl_inter, -5,
1471 				(struct pkt *)&rpkt, totlen + maclen);
1472 		} else {
1473 			sendpkt(rmt_addr, lcl_inter, -6,
1474 				(struct pkt *)&rpkt, sendlen);
1475 		}
1476 		if (more)
1477 			numctlfrags++;
1478 		else
1479 			numctlresponses++;
1480 	}
1481 
1482 	/*
1483 	 * Set us up for another go around.
1484 	 */
1485 	res_frags++;
1486 	res_offset += dlen;
1487 	datapt = rpkt.u.data;
1488 }
1489 
1490 
1491 /* --------------------------------------------------------------------
1492  * block transfer API -- stream string/data fragments into xmit buffer
1493  * without additional copying
1494  */
1495 
1496 /* buffer descriptor: address & size of fragment
1497  * 'buf' may only be NULL when 'len' is zero!
1498  */
1499 typedef struct {
1500 	const void  *buf;
1501 	size_t       len;
1502 } CtlMemBufT;
1503 
1504 /* put ctl data in a gather-style operation */
1505 static void
1506 ctl_putdata_ex(
1507 	const CtlMemBufT * argv,
1508 	size_t             argc,
1509 	int/*BOOL*/        bin		/* set to 1 when data is binary */
1510 	)
1511 {
1512 	const char * src_ptr;
1513 	size_t       src_len, cur_len, add_len, argi;
1514 
1515 	/* text / binary preprocessing, possibly create new linefeed */
1516 	if (bin) {
1517 		add_len = 0;
1518 	} else {
1519 		datanotbinflag = TRUE;
1520 		add_len = 3;
1521 
1522 		if (datasent) {
1523 			*datapt++ = ',';
1524 			datalinelen++;
1525 
1526 			/* sum up total length */
1527 			for (argi = 0, src_len = 0; argi < argc; ++argi)
1528 				src_len += argv[argi].len;
1529 			/* possibly start a new line, assume no size_t overflow */
1530 			if ((src_len + datalinelen + 1) >= MAXDATALINELEN) {
1531 				*datapt++ = '\r';
1532 				*datapt++ = '\n';
1533 				datalinelen = 0;
1534 			} else {
1535 				*datapt++ = ' ';
1536 				datalinelen++;
1537 			}
1538 		}
1539 	}
1540 
1541 	/* now stream out all buffers */
1542 	for (argi = 0; argi < argc; ++argi) {
1543 		src_ptr = argv[argi].buf;
1544 		src_len = argv[argi].len;
1545 
1546 		if ( ! (src_ptr && src_len))
1547 			continue;
1548 
1549 		cur_len = (size_t)(dataend - datapt);
1550 		while ((src_len + add_len) > cur_len) {
1551 			/* Not enough room in this one, flush it out. */
1552 			if (src_len < cur_len)
1553 				cur_len = src_len;
1554 
1555 			memcpy(datapt, src_ptr, cur_len);
1556 			datapt      += cur_len;
1557 			datalinelen += cur_len;
1558 
1559 			src_ptr     += cur_len;
1560 			src_len     -= cur_len;
1561 
1562 			ctl_flushpkt(CTL_MORE);
1563 			cur_len = (size_t)(dataend - datapt);
1564 		}
1565 
1566 		memcpy(datapt, src_ptr, src_len);
1567 		datapt      += src_len;
1568 		datalinelen += src_len;
1569 
1570 		datasent = TRUE;
1571 	}
1572 }
1573 
1574 /*
1575  * ctl_putdata - write data into the packet, fragmenting and starting
1576  * another if this one is full.
1577  */
1578 static void
1579 ctl_putdata(
1580 	const char *dp,
1581 	unsigned int dlen,
1582 	int bin			/* set to 1 when data is binary */
1583 	)
1584 {
1585 	CtlMemBufT args[1];
1586 
1587 	args[0].buf = dp;
1588 	args[0].len = dlen;
1589 	ctl_putdata_ex(args, 1, bin);
1590 }
1591 
1592 /*
1593  * ctl_putstr - write a tagged string into the response packet
1594  *		in the form:
1595  *
1596  *		tag="data"
1597  *
1598  *		len is the data length excluding the NUL terminator,
1599  *		as in ctl_putstr("var", "value", strlen("value"));
1600  */
1601 static void
1602 ctl_putstr(
1603 	const char *	tag,
1604 	const char *	data,
1605 	size_t		len
1606 	)
1607 {
1608 	CtlMemBufT args[4];
1609 
1610 	args[0].buf = tag;
1611 	args[0].len = strlen(tag);
1612 	if (data && len) {
1613 	    args[1].buf = "=\"";
1614 	    args[1].len = 2;
1615 	    args[2].buf = data;
1616 	    args[2].len = len;
1617 	    args[3].buf = "\"";
1618 	    args[3].len = 1;
1619 	    ctl_putdata_ex(args, 4, FALSE);
1620 	} else {
1621 	    args[1].buf = "=\"\"";
1622 	    args[1].len = 3;
1623 	    ctl_putdata_ex(args, 2, FALSE);
1624 	}
1625 }
1626 
1627 
1628 /*
1629  * ctl_putunqstr - write a tagged string into the response packet
1630  *		   in the form:
1631  *
1632  *		   tag=data
1633  *
1634  *	len is the data length excluding the NUL terminator.
1635  *	data must not contain a comma or whitespace.
1636  */
1637 static void
1638 ctl_putunqstr(
1639 	const char *	tag,
1640 	const char *	data,
1641 	size_t		len
1642 	)
1643 {
1644 	CtlMemBufT args[3];
1645 
1646 	args[0].buf = tag;
1647 	args[0].len = strlen(tag);
1648 	args[1].buf = "=";
1649 	args[1].len = 1;
1650 	if (data && len) {
1651 		args[2].buf = data;
1652 		args[2].len = len;
1653 		ctl_putdata_ex(args, 3, FALSE);
1654 	} else {
1655 		ctl_putdata_ex(args, 2, FALSE);
1656 	}
1657 }
1658 
1659 
1660 /*
1661  * ctl_putdblf - write a tagged, signed double into the response packet
1662  */
1663 static void
1664 ctl_putdblf(
1665 	const char *	tag,
1666 	int		use_f,
1667 	int		precision,
1668 	double		d
1669 	)
1670 {
1671 	char buffer[40];
1672 	int  rc;
1673 
1674 	rc = snprintf(buffer, sizeof(buffer),
1675 		      (use_f ? "%.*f" : "%.*g"),
1676 		      precision, d);
1677 	INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1678 	ctl_putunqstr(tag, buffer, rc);
1679 }
1680 
1681 /*
1682  * ctl_putuint - write a tagged unsigned integer into the response
1683  */
1684 static void
1685 ctl_putuint(
1686 	const char *tag,
1687 	u_long uval
1688 	)
1689 {
1690 	char buffer[24]; /* needs to fit for 64 bits! */
1691 	int  rc;
1692 
1693 	rc = snprintf(buffer, sizeof(buffer), "%lu", uval);
1694 	INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1695 	ctl_putunqstr(tag, buffer, rc);
1696 }
1697 
1698 /*
1699  * ctl_putcal - write a decoded calendar data into the response.
1700  * only used with AUTOKEY currently, so compiled conditional
1701  */
1702 #ifdef AUTOKEY
1703 static void
1704 ctl_putcal(
1705 	const char *tag,
1706 	const struct calendar *pcal
1707 	)
1708 {
1709 	char buffer[16];
1710 	int  rc;
1711 
1712 	rc = snprintf(buffer, sizeof(buffer),
1713 		      "%04d%02d%02d%02d%02d",
1714 		      pcal->year, pcal->month, pcal->monthday,
1715 		      pcal->hour, pcal->minute
1716 		);
1717 	INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1718 	ctl_putunqstr(tag, buffer, rc);
1719 }
1720 #endif
1721 
1722 /*
1723  * ctl_putfs - write a decoded filestamp into the response
1724  */
1725 static void
1726 ctl_putfs(
1727 	const char *tag,
1728 	tstamp_t uval
1729 	)
1730 {
1731 	char buffer[16];
1732 	int  rc;
1733 
1734 	time_t fstamp = (time_t)uval - JAN_1970;
1735 	struct tm *tm = gmtime(&fstamp);
1736 
1737 	if (NULL == tm)
1738 		return;
1739 
1740 	rc = snprintf(buffer, sizeof(buffer),
1741 		      "%04d%02d%02d%02d%02d",
1742 		      tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1743 		      tm->tm_hour, tm->tm_min);
1744 	INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1745 	ctl_putunqstr(tag, buffer, rc);
1746 }
1747 
1748 
1749 /*
1750  * ctl_puthex - write a tagged unsigned integer, in hex, into the
1751  * response
1752  */
1753 static void
1754 ctl_puthex(
1755 	const char *tag,
1756 	u_long uval
1757 	)
1758 {
1759 	char buffer[24];	/* must fit 64bit int! */
1760 	int  rc;
1761 
1762 	rc = snprintf(buffer, sizeof(buffer), "0x%lx", uval);
1763 	INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1764 	ctl_putunqstr(tag, buffer, rc);
1765 }
1766 
1767 
1768 /*
1769  * ctl_putint - write a tagged signed integer into the response
1770  */
1771 static void
1772 ctl_putint(
1773 	const char *tag,
1774 	long ival
1775 	)
1776 {
1777 	char buffer[24];	/*must fit 64bit int */
1778 	int  rc;
1779 
1780 	rc = snprintf(buffer, sizeof(buffer), "%ld", ival);
1781 	INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1782 	ctl_putunqstr(tag, buffer, rc);
1783 }
1784 
1785 
1786 /*
1787  * ctl_putts - write a tagged timestamp, in hex, into the response
1788  */
1789 static void
1790 ctl_putts(
1791 	const char *tag,
1792 	l_fp *ts
1793 	)
1794 {
1795 	char buffer[24];
1796 	int  rc;
1797 
1798 	rc = snprintf(buffer, sizeof(buffer),
1799 		      "0x%08lx.%08lx",
1800 		      (u_long)ts->l_ui, (u_long)ts->l_uf);
1801 	INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1802 	ctl_putunqstr(tag, buffer, rc);
1803 }
1804 
1805 
1806 /*
1807  * ctl_putadr - write an IP address into the response
1808  */
1809 static void
1810 ctl_putadr(
1811 	const char *tag,
1812 	u_int32 addr32,
1813 	sockaddr_u *addr
1814 	)
1815 {
1816 	const char *cq;
1817 
1818 	if (NULL == addr)
1819 		cq = numtoa(addr32);
1820 	else
1821 		cq = stoa(addr);
1822 	ctl_putunqstr(tag, cq, strlen(cq));
1823 }
1824 
1825 
1826 /*
1827  * ctl_putrefid - send a u_int32 refid as printable text
1828  */
1829 static void
1830 ctl_putrefid(
1831 	const char *	tag,
1832 	u_int32		refid
1833 	)
1834 {
1835 	size_t nc;
1836 
1837 	union {
1838 		uint32_t w;
1839 		uint8_t  b[sizeof(uint32_t)];
1840 	} bytes;
1841 
1842 	bytes.w = refid;
1843 	for (nc = 0; nc < sizeof(bytes.b) && bytes.b[nc]; ++nc)
1844 		if (  !isprint(bytes.b[nc])
1845 		    || isspace(bytes.b[nc])
1846 		    || bytes.b[nc] == ','  )
1847 			bytes.b[nc] = '.';
1848 	ctl_putunqstr(tag, (const char*)bytes.b, nc);
1849 }
1850 
1851 
1852 /*
1853  * ctl_putarray - write a tagged eight element double array into the response
1854  */
1855 static void
1856 ctl_putarray(
1857 	const char *tag,
1858 	double *arr,
1859 	int start
1860 	)
1861 {
1862 	char *cp, *ep;
1863 	char buffer[200];
1864 	int  i, rc;
1865 
1866 	cp = buffer;
1867 	ep = buffer + sizeof(buffer);
1868 	i  = start;
1869 	do {
1870 		if (i == 0)
1871 			i = NTP_SHIFT;
1872 		i--;
1873 		rc = snprintf(cp, (size_t)(ep - cp), " %.2f", arr[i] * 1e3);
1874 		INSIST(rc >= 0 && (size_t)rc < (size_t)(ep - cp));
1875 		cp += rc;
1876 	} while (i != start);
1877 	ctl_putunqstr(tag, buffer, (size_t)(cp - buffer));
1878 }
1879 
1880 /*
1881  * ctl_printf - put a formatted string into the data buffer
1882  */
1883 static void
1884 ctl_printf(
1885 	const char * fmt,
1886 	...
1887 	)
1888 {
1889 	static const char * ellipsis = "[...]";
1890 	va_list va;
1891 	char    fmtbuf[128];
1892 	int     rc;
1893 
1894 	va_start(va, fmt);
1895 	rc = vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, va);
1896 	va_end(va);
1897 	if (rc < 0 || (size_t)rc >= sizeof(fmtbuf))
1898 		strcpy(fmtbuf + sizeof(fmtbuf) - strlen(ellipsis) - 1,
1899 		       ellipsis);
1900 	ctl_putdata(fmtbuf, strlen(fmtbuf), 0);
1901 }
1902 
1903 
1904 /*
1905  * ctl_putsys - output a system variable
1906  */
1907 static void
1908 ctl_putsys(
1909 	int varid
1910 	)
1911 {
1912 	l_fp tmp;
1913 	char str[256];
1914 	u_int u;
1915 	double kb;
1916 	double dtemp;
1917 	const char *ss;
1918 #ifdef AUTOKEY
1919 	struct cert_info *cp;
1920 #endif	/* AUTOKEY */
1921 #ifdef KERNEL_PLL
1922 	static struct timex ntx;
1923 	static u_long ntp_adjtime_time;
1924 
1925 	/*
1926 	 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1927 	 */
1928 	if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1929 	    current_time != ntp_adjtime_time) {
1930 		ZERO(ntx);
1931 		if (ntp_adjtime(&ntx) < 0)
1932 			msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1933 		else
1934 			ntp_adjtime_time = current_time;
1935 	}
1936 #endif	/* KERNEL_PLL */
1937 
1938 	switch (varid) {
1939 
1940 	case CS_LEAP:
1941 		ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1942 		break;
1943 
1944 	case CS_STRATUM:
1945 		ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1946 		break;
1947 
1948 	case CS_PRECISION:
1949 		ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1950 		break;
1951 
1952 	case CS_ROOTDELAY:
1953 		ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1954 			   1e3);
1955 		break;
1956 
1957 	case CS_ROOTDISPERSION:
1958 		ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1959 			   sys_rootdisp * 1e3);
1960 		break;
1961 
1962 	case CS_REFID:
1963 		if (REFID_ISTEXT(sys_stratum))
1964 			ctl_putrefid(sys_var[varid].text, sys_refid);
1965 		else
1966 			ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1967 		break;
1968 
1969 	case CS_REFTIME:
1970 		ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1971 		break;
1972 
1973 	case CS_POLL:
1974 		ctl_putuint(sys_var[CS_POLL].text, sys_poll);
1975 		break;
1976 
1977 	case CS_PEERID:
1978 		if (sys_peer == NULL)
1979 			ctl_putuint(sys_var[CS_PEERID].text, 0);
1980 		else
1981 			ctl_putuint(sys_var[CS_PEERID].text,
1982 				    sys_peer->associd);
1983 		break;
1984 
1985 	case CS_PEERADR:
1986 		if (sys_peer != NULL && sys_peer->dstadr != NULL)
1987 			ss = sptoa(&sys_peer->srcadr);
1988 		else
1989 			ss = "0.0.0.0:0";
1990 		ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
1991 		break;
1992 
1993 	case CS_PEERMODE:
1994 		u = (sys_peer != NULL)
1995 			? sys_peer->hmode
1996 			: MODE_UNSPEC;
1997 		ctl_putuint(sys_var[CS_PEERMODE].text, u);
1998 		break;
1999 
2000 	case CS_OFFSET:
2001 		ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
2002 		break;
2003 
2004 	case CS_DRIFT:
2005 		ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
2006 		break;
2007 
2008 	case CS_JITTER:
2009 		ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
2010 		break;
2011 
2012 	case CS_ERROR:
2013 		ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
2014 		break;
2015 
2016 	case CS_CLOCK:
2017 		get_systime(&tmp);
2018 		ctl_putts(sys_var[CS_CLOCK].text, &tmp);
2019 		break;
2020 
2021 	case CS_PROCESSOR:
2022 #ifndef HAVE_UNAME
2023 		ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
2024 			   sizeof(str_processor) - 1);
2025 #else
2026 		ctl_putstr(sys_var[CS_PROCESSOR].text,
2027 			   utsnamebuf.machine, strlen(utsnamebuf.machine));
2028 #endif /* HAVE_UNAME */
2029 		break;
2030 
2031 	case CS_SYSTEM:
2032 #ifndef HAVE_UNAME
2033 		ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
2034 			   sizeof(str_system) - 1);
2035 #else
2036 		snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
2037 			 utsnamebuf.release);
2038 		ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
2039 #endif /* HAVE_UNAME */
2040 		break;
2041 
2042 	case CS_VERSION:
2043 		ctl_putstr(sys_var[CS_VERSION].text, Version,
2044 			   strlen(Version));
2045 		break;
2046 
2047 	case CS_STABIL:
2048 		ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
2049 			   1e6);
2050 		break;
2051 
2052 	case CS_VARLIST:
2053 	{
2054 		char buf[CTL_MAX_DATA_LEN];
2055 		//buffPointer, firstElementPointer, buffEndPointer
2056 		char *buffp, *buffend;
2057 		int firstVarName;
2058 		const char *ss1;
2059 		int len;
2060 		const struct ctl_var *k;
2061 
2062 		buffp = buf;
2063 		buffend = buf + sizeof(buf);
2064 		if (strlen(sys_var[CS_VARLIST].text) > (sizeof(buf) - 4))
2065 			break;	/* really long var name */
2066 
2067 		snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
2068 		buffp += strlen(buffp);
2069 		firstVarName = TRUE;
2070 		for (k = sys_var; !(k->flags & EOV); k++) {
2071 			if (k->flags & PADDING)
2072 				continue;
2073 			len = strlen(k->text);
2074 			if (len + 1 >= buffend - buffp)
2075 				break;
2076 			if (!firstVarName)
2077 				*buffp++ = ',';
2078 			else
2079 				firstVarName = FALSE;
2080 			memcpy(buffp, k->text, len);
2081 			buffp += len;
2082 		}
2083 
2084 		for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
2085 			if (k->flags & PADDING)
2086 				continue;
2087 			if (NULL == k->text)
2088 				continue;
2089 			ss1 = strchr(k->text, '=');
2090 			if (NULL == ss1)
2091 				len = strlen(k->text);
2092 			else
2093 				len = ss1 - k->text;
2094 			if (len + 1 >= buffend - buffp)
2095 				break;
2096 			if (firstVarName) {
2097 				*buffp++ = ',';
2098 				firstVarName = FALSE;
2099 			}
2100 			memcpy(buffp, k->text,(unsigned)len);
2101 			buffp += len;
2102 		}
2103 		if (2 >= buffend - buffp)
2104 			break;
2105 
2106 		*buffp++ = '"';
2107 		*buffp = '\0';
2108 
2109 		ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
2110 		break;
2111 	}
2112 
2113 	case CS_TAI:
2114 		if (sys_tai > 0)
2115 			ctl_putuint(sys_var[CS_TAI].text, sys_tai);
2116 		break;
2117 
2118 	case CS_LEAPTAB:
2119 	{
2120 		leap_signature_t lsig;
2121 		leapsec_getsig(&lsig);
2122 		if (lsig.ttime > 0)
2123 			ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
2124 		break;
2125 	}
2126 
2127 	case CS_LEAPEND:
2128 	{
2129 		leap_signature_t lsig;
2130 		leapsec_getsig(&lsig);
2131 		if (lsig.etime > 0)
2132 			ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2133 		break;
2134 	}
2135 
2136 #ifdef LEAP_SMEAR
2137 	case CS_LEAPSMEARINTV:
2138 		if (leap_smear_intv > 0)
2139 			ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2140 		break;
2141 
2142 	case CS_LEAPSMEAROFFS:
2143 		if (leap_smear_intv > 0)
2144 			ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2145 				   leap_smear.doffset * 1e3);
2146 		break;
2147 #endif	/* LEAP_SMEAR */
2148 
2149 	case CS_RATE:
2150 		ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2151 		break;
2152 
2153 	case CS_MRU_ENABLED:
2154 		ctl_puthex(sys_var[varid].text, mon_enabled);
2155 		break;
2156 
2157 	case CS_MRU_DEPTH:
2158 		ctl_putuint(sys_var[varid].text, mru_entries);
2159 		break;
2160 
2161 	case CS_MRU_MEM:
2162 		kb = mru_entries * (sizeof(mon_entry) / 1024.);
2163 		u = (u_int)kb;
2164 		if (kb - u >= 0.5)
2165 			u++;
2166 		ctl_putuint(sys_var[varid].text, u);
2167 		break;
2168 
2169 	case CS_MRU_DEEPEST:
2170 		ctl_putuint(sys_var[varid].text, mru_peakentries);
2171 		break;
2172 
2173 	case CS_MRU_MINDEPTH:
2174 		ctl_putuint(sys_var[varid].text, mru_mindepth);
2175 		break;
2176 
2177 	case CS_MRU_MAXAGE:
2178 		ctl_putint(sys_var[varid].text, mru_maxage);
2179 		break;
2180 
2181 	case CS_MRU_MAXDEPTH:
2182 		ctl_putuint(sys_var[varid].text, mru_maxdepth);
2183 		break;
2184 
2185 	case CS_MRU_MAXMEM:
2186 		kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2187 		u = (u_int)kb;
2188 		if (kb - u >= 0.5)
2189 			u++;
2190 		ctl_putuint(sys_var[varid].text, u);
2191 		break;
2192 
2193 	case CS_SS_UPTIME:
2194 		ctl_putuint(sys_var[varid].text, current_time);
2195 		break;
2196 
2197 	case CS_SS_RESET:
2198 		ctl_putuint(sys_var[varid].text,
2199 			    current_time - sys_stattime);
2200 		break;
2201 
2202 	case CS_SS_RECEIVED:
2203 		ctl_putuint(sys_var[varid].text, sys_received);
2204 		break;
2205 
2206 	case CS_SS_THISVER:
2207 		ctl_putuint(sys_var[varid].text, sys_newversion);
2208 		break;
2209 
2210 	case CS_SS_OLDVER:
2211 		ctl_putuint(sys_var[varid].text, sys_oldversion);
2212 		break;
2213 
2214 	case CS_SS_BADFORMAT:
2215 		ctl_putuint(sys_var[varid].text, sys_badlength);
2216 		break;
2217 
2218 	case CS_SS_BADAUTH:
2219 		ctl_putuint(sys_var[varid].text, sys_badauth);
2220 		break;
2221 
2222 	case CS_SS_DECLINED:
2223 		ctl_putuint(sys_var[varid].text, sys_declined);
2224 		break;
2225 
2226 	case CS_SS_RESTRICTED:
2227 		ctl_putuint(sys_var[varid].text, sys_restricted);
2228 		break;
2229 
2230 	case CS_SS_LIMITED:
2231 		ctl_putuint(sys_var[varid].text, sys_limitrejected);
2232 		break;
2233 
2234 	case CS_SS_LAMPORT:
2235 		ctl_putuint(sys_var[varid].text, sys_lamport);
2236 		break;
2237 
2238 	case CS_SS_TSROUNDING:
2239 		ctl_putuint(sys_var[varid].text, sys_tsrounding);
2240 		break;
2241 
2242 	case CS_SS_KODSENT:
2243 		ctl_putuint(sys_var[varid].text, sys_kodsent);
2244 		break;
2245 
2246 	case CS_SS_PROCESSED:
2247 		ctl_putuint(sys_var[varid].text, sys_processed);
2248 		break;
2249 
2250 	case CS_BCASTDELAY:
2251 		ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2252 		break;
2253 
2254 	case CS_AUTHDELAY:
2255 		LFPTOD(&sys_authdelay, dtemp);
2256 		ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2257 		break;
2258 
2259 	case CS_AUTHKEYS:
2260 		ctl_putuint(sys_var[varid].text, authnumkeys);
2261 		break;
2262 
2263 	case CS_AUTHFREEK:
2264 		ctl_putuint(sys_var[varid].text, authnumfreekeys);
2265 		break;
2266 
2267 	case CS_AUTHKLOOKUPS:
2268 		ctl_putuint(sys_var[varid].text, authkeylookups);
2269 		break;
2270 
2271 	case CS_AUTHKNOTFOUND:
2272 		ctl_putuint(sys_var[varid].text, authkeynotfound);
2273 		break;
2274 
2275 	case CS_AUTHKUNCACHED:
2276 		ctl_putuint(sys_var[varid].text, authkeyuncached);
2277 		break;
2278 
2279 	case CS_AUTHKEXPIRED:
2280 		ctl_putuint(sys_var[varid].text, authkeyexpired);
2281 		break;
2282 
2283 	case CS_AUTHENCRYPTS:
2284 		ctl_putuint(sys_var[varid].text, authencryptions);
2285 		break;
2286 
2287 	case CS_AUTHDECRYPTS:
2288 		ctl_putuint(sys_var[varid].text, authdecryptions);
2289 		break;
2290 
2291 	case CS_AUTHRESET:
2292 		ctl_putuint(sys_var[varid].text,
2293 			    current_time - auth_timereset);
2294 		break;
2295 
2296 		/*
2297 		 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2298 		 * unavailable, otherwise calls putfunc with args.
2299 		 */
2300 #ifndef KERNEL_PLL
2301 # define	CTL_IF_KERNLOOP(putfunc, args)	\
2302 		ctl_putint(sys_var[varid].text, 0)
2303 #else
2304 # define	CTL_IF_KERNLOOP(putfunc, args)	\
2305 		putfunc args
2306 #endif
2307 
2308 		/*
2309 		 * CTL_IF_KERNPPS() puts a zero if either the kernel
2310 		 * loop is unavailable, or kernel hard PPS is not
2311 		 * active, otherwise calls putfunc with args.
2312 		 */
2313 #ifndef KERNEL_PLL
2314 # define	CTL_IF_KERNPPS(putfunc, args)	\
2315 		ctl_putint(sys_var[varid].text, 0)
2316 #else
2317 # define	CTL_IF_KERNPPS(putfunc, args)			\
2318 		if (0 == ntx.shift)				\
2319 			ctl_putint(sys_var[varid].text, 0);	\
2320 		else						\
2321 			putfunc args	/* no trailing ; */
2322 #endif
2323 
2324 	case CS_K_OFFSET:
2325 		CTL_IF_KERNLOOP(
2326 			ctl_putdblf,
2327 			(sys_var[varid].text, 0, -1,
2328 			 1000 * dbl_from_var_long(ntx.offset, ntx.status))
2329 		);
2330 		break;
2331 
2332 	case CS_K_FREQ:
2333 		CTL_IF_KERNLOOP(
2334 			ctl_putsfp,
2335 			(sys_var[varid].text, ntx.freq)
2336 		);
2337 		break;
2338 
2339 	case CS_K_MAXERR:
2340 		CTL_IF_KERNLOOP(
2341 			ctl_putdblf,
2342 			(sys_var[varid].text, 0, 6,
2343 			 1000 * dbl_from_usec_long(ntx.maxerror))
2344 		);
2345 		break;
2346 
2347 	case CS_K_ESTERR:
2348 		CTL_IF_KERNLOOP(
2349 			ctl_putdblf,
2350 			(sys_var[varid].text, 0, 6,
2351 			 1000 * dbl_from_usec_long(ntx.esterror))
2352 		);
2353 		break;
2354 
2355 	case CS_K_STFLAGS:
2356 #ifndef KERNEL_PLL
2357 		ss = "";
2358 #else
2359 		ss = k_st_flags(ntx.status);
2360 #endif
2361 		ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2362 		break;
2363 
2364 	case CS_K_TIMECONST:
2365 		CTL_IF_KERNLOOP(
2366 			ctl_putint,
2367 			(sys_var[varid].text, ntx.constant)
2368 		);
2369 		break;
2370 
2371 	case CS_K_PRECISION:
2372 		CTL_IF_KERNLOOP(
2373 			ctl_putdblf,
2374 			(sys_var[varid].text, 0, 6,
2375 			 1000 * dbl_from_var_long(ntx.precision, ntx.status))
2376 		);
2377 		break;
2378 
2379 	case CS_K_FREQTOL:
2380 		CTL_IF_KERNLOOP(
2381 			ctl_putsfp,
2382 			(sys_var[varid].text, ntx.tolerance)
2383 		);
2384 		break;
2385 
2386 	case CS_K_PPS_FREQ:
2387 		CTL_IF_KERNPPS(
2388 			ctl_putsfp,
2389 			(sys_var[varid].text, ntx.ppsfreq)
2390 		);
2391 		break;
2392 
2393 	case CS_K_PPS_STABIL:
2394 		CTL_IF_KERNPPS(
2395 			ctl_putsfp,
2396 			(sys_var[varid].text, ntx.stabil)
2397 		);
2398 		break;
2399 
2400 	case CS_K_PPS_JITTER:
2401 		CTL_IF_KERNPPS(
2402 			ctl_putdbl,
2403 			(sys_var[varid].text,
2404 			 1000 * dbl_from_var_long(ntx.jitter, ntx.status))
2405 		);
2406 		break;
2407 
2408 	case CS_K_PPS_CALIBDUR:
2409 		CTL_IF_KERNPPS(
2410 			ctl_putint,
2411 			(sys_var[varid].text, 1 << ntx.shift)
2412 		);
2413 		break;
2414 
2415 	case CS_K_PPS_CALIBS:
2416 		CTL_IF_KERNPPS(
2417 			ctl_putint,
2418 			(sys_var[varid].text, ntx.calcnt)
2419 		);
2420 		break;
2421 
2422 	case CS_K_PPS_CALIBERRS:
2423 		CTL_IF_KERNPPS(
2424 			ctl_putint,
2425 			(sys_var[varid].text, ntx.errcnt)
2426 		);
2427 		break;
2428 
2429 	case CS_K_PPS_JITEXC:
2430 		CTL_IF_KERNPPS(
2431 			ctl_putint,
2432 			(sys_var[varid].text, ntx.jitcnt)
2433 		);
2434 		break;
2435 
2436 	case CS_K_PPS_STBEXC:
2437 		CTL_IF_KERNPPS(
2438 			ctl_putint,
2439 			(sys_var[varid].text, ntx.stbcnt)
2440 		);
2441 		break;
2442 
2443 	case CS_IOSTATS_RESET:
2444 		ctl_putuint(sys_var[varid].text,
2445 			    current_time - io_timereset);
2446 		break;
2447 
2448 	case CS_TOTAL_RBUF:
2449 		ctl_putuint(sys_var[varid].text, total_recvbuffs());
2450 		break;
2451 
2452 	case CS_FREE_RBUF:
2453 		ctl_putuint(sys_var[varid].text, free_recvbuffs());
2454 		break;
2455 
2456 	case CS_USED_RBUF:
2457 		ctl_putuint(sys_var[varid].text, full_recvbuffs());
2458 		break;
2459 
2460 	case CS_RBUF_LOWATER:
2461 		ctl_putuint(sys_var[varid].text, lowater_additions());
2462 		break;
2463 
2464 	case CS_IO_DROPPED:
2465 		ctl_putuint(sys_var[varid].text, packets_dropped);
2466 		break;
2467 
2468 	case CS_IO_IGNORED:
2469 		ctl_putuint(sys_var[varid].text, packets_ignored);
2470 		break;
2471 
2472 	case CS_IO_RECEIVED:
2473 		ctl_putuint(sys_var[varid].text, packets_received);
2474 		break;
2475 
2476 	case CS_IO_SENT:
2477 		ctl_putuint(sys_var[varid].text, packets_sent);
2478 		break;
2479 
2480 	case CS_IO_SENDFAILED:
2481 		ctl_putuint(sys_var[varid].text, packets_notsent);
2482 		break;
2483 
2484 	case CS_IO_WAKEUPS:
2485 		ctl_putuint(sys_var[varid].text, handler_calls);
2486 		break;
2487 
2488 	case CS_IO_GOODWAKEUPS:
2489 		ctl_putuint(sys_var[varid].text, handler_pkts);
2490 		break;
2491 
2492 	case CS_TIMERSTATS_RESET:
2493 		ctl_putuint(sys_var[varid].text,
2494 			    current_time - timer_timereset);
2495 		break;
2496 
2497 	case CS_TIMER_OVERRUNS:
2498 		ctl_putuint(sys_var[varid].text, alarm_overflow);
2499 		break;
2500 
2501 	case CS_TIMER_XMTS:
2502 		ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2503 		break;
2504 
2505 	case CS_FUZZ:
2506 		ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2507 		break;
2508 	case CS_WANDER_THRESH:
2509 		ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2510 		break;
2511 #ifdef AUTOKEY
2512 	case CS_FLAGS:
2513 		if (crypto_flags)
2514 			ctl_puthex(sys_var[CS_FLAGS].text,
2515 			    crypto_flags);
2516 		break;
2517 
2518 	case CS_DIGEST:
2519 		if (crypto_flags) {
2520 			strlcpy(str, OBJ_nid2ln(crypto_nid),
2521 			    COUNTOF(str));
2522 			ctl_putstr(sys_var[CS_DIGEST].text, str,
2523 			    strlen(str));
2524 		}
2525 		break;
2526 
2527 	case CS_SIGNATURE:
2528 		if (crypto_flags) {
2529 			const EVP_MD *dp;
2530 
2531 			dp = EVP_get_digestbynid(crypto_flags >> 16);
2532 			strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2533 			    COUNTOF(str));
2534 			ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2535 			    strlen(str));
2536 		}
2537 		break;
2538 
2539 	case CS_HOST:
2540 		if (hostval.ptr != NULL)
2541 			ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2542 			    strlen(hostval.ptr));
2543 		break;
2544 
2545 	case CS_IDENT:
2546 		if (sys_ident != NULL)
2547 			ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2548 			    strlen(sys_ident));
2549 		break;
2550 
2551 	case CS_CERTIF:
2552 		for (cp = cinfo; cp != NULL; cp = cp->link) {
2553 			snprintf(str, sizeof(str), "%s %s 0x%x",
2554 			    cp->subject, cp->issuer, cp->flags);
2555 			ctl_putstr(sys_var[CS_CERTIF].text, str,
2556 			    strlen(str));
2557 			ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2558 		}
2559 		break;
2560 
2561 	case CS_PUBLIC:
2562 		if (hostval.tstamp != 0)
2563 			ctl_putfs(sys_var[CS_PUBLIC].text,
2564 			    ntohl(hostval.tstamp));
2565 		break;
2566 #endif	/* AUTOKEY */
2567 
2568 	default:
2569 		break;
2570 	}
2571 }
2572 
2573 
2574 /*
2575  * ctl_putpeer - output a peer variable
2576  */
2577 static void
2578 ctl_putpeer(
2579 	int id,
2580 	struct peer *p
2581 	)
2582 {
2583 	char buf[CTL_MAX_DATA_LEN];
2584 	char *s;
2585 	char *t;
2586 	char *be;
2587 	int i;
2588 	const struct ctl_var *k;
2589 #ifdef AUTOKEY
2590 	struct autokey *ap;
2591 	const EVP_MD *dp;
2592 	const char *str;
2593 #endif	/* AUTOKEY */
2594 
2595 	switch (id) {
2596 
2597 	case CP_CONFIG:
2598 		ctl_putuint(peer_var[id].text,
2599 			    !(FLAG_PREEMPT & p->flags));
2600 		break;
2601 
2602 	case CP_AUTHENABLE:
2603 		ctl_putuint(peer_var[id].text, !(p->keyid));
2604 		break;
2605 
2606 	case CP_AUTHENTIC:
2607 		ctl_putuint(peer_var[id].text,
2608 			    !!(FLAG_AUTHENTIC & p->flags));
2609 		break;
2610 
2611 	case CP_SRCADR:
2612 		ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2613 		break;
2614 
2615 	case CP_SRCPORT:
2616 		ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2617 		break;
2618 
2619 	case CP_SRCHOST:
2620 		if (p->hostname != NULL)
2621 			ctl_putstr(peer_var[id].text, p->hostname,
2622 				   strlen(p->hostname));
2623 		break;
2624 
2625 	case CP_DSTADR:
2626 		ctl_putadr(peer_var[id].text, 0,
2627 			   (p->dstadr != NULL)
2628 				? &p->dstadr->sin
2629 				: NULL);
2630 		break;
2631 
2632 	case CP_DSTPORT:
2633 		ctl_putuint(peer_var[id].text,
2634 			    (p->dstadr != NULL)
2635 				? SRCPORT(&p->dstadr->sin)
2636 				: 0);
2637 		break;
2638 
2639 	case CP_IN:
2640 		if (p->r21 > 0.)
2641 			ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2642 		break;
2643 
2644 	case CP_OUT:
2645 		if (p->r34 > 0.)
2646 			ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2647 		break;
2648 
2649 	case CP_RATE:
2650 		ctl_putuint(peer_var[id].text, p->throttle);
2651 		break;
2652 
2653 	case CP_LEAP:
2654 		ctl_putuint(peer_var[id].text, p->leap);
2655 		break;
2656 
2657 	case CP_HMODE:
2658 		ctl_putuint(peer_var[id].text, p->hmode);
2659 		break;
2660 
2661 	case CP_STRATUM:
2662 		ctl_putuint(peer_var[id].text, p->stratum);
2663 		break;
2664 
2665 	case CP_PPOLL:
2666 		ctl_putuint(peer_var[id].text, p->ppoll);
2667 		break;
2668 
2669 	case CP_HPOLL:
2670 		ctl_putuint(peer_var[id].text, p->hpoll);
2671 		break;
2672 
2673 	case CP_PRECISION:
2674 		ctl_putint(peer_var[id].text, p->precision);
2675 		break;
2676 
2677 	case CP_ROOTDELAY:
2678 		ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2679 		break;
2680 
2681 	case CP_ROOTDISPERSION:
2682 		ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2683 		break;
2684 
2685 	case CP_REFID:
2686 #ifdef REFCLOCK
2687 		if (p->flags & FLAG_REFCLOCK) {
2688 			ctl_putrefid(peer_var[id].text, p->refid);
2689 			break;
2690 		}
2691 #endif
2692 		if (REFID_ISTEXT(p->stratum))
2693 			ctl_putrefid(peer_var[id].text, p->refid);
2694 		else
2695 			ctl_putadr(peer_var[id].text, p->refid, NULL);
2696 		break;
2697 
2698 	case CP_REFTIME:
2699 		ctl_putts(peer_var[id].text, &p->reftime);
2700 		break;
2701 
2702 	case CP_ORG:
2703 		ctl_putts(peer_var[id].text, &p->aorg);
2704 		break;
2705 
2706 	case CP_REC:
2707 		ctl_putts(peer_var[id].text, &p->dst);
2708 		break;
2709 
2710 	case CP_XMT:
2711 		if (p->xleave)
2712 			ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2713 		break;
2714 
2715 	case CP_BIAS:
2716 		if (p->bias != 0.)
2717 			ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2718 		break;
2719 
2720 	case CP_REACH:
2721 		ctl_puthex(peer_var[id].text, p->reach);
2722 		break;
2723 
2724 	case CP_FLASH:
2725 		ctl_puthex(peer_var[id].text, p->flash);
2726 		break;
2727 
2728 	case CP_TTL:
2729 #ifdef REFCLOCK
2730 		if (p->flags & FLAG_REFCLOCK) {
2731 			ctl_putuint(peer_var[id].text, p->ttl);
2732 			break;
2733 		}
2734 #endif
2735 		if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2736 			ctl_putint(peer_var[id].text,
2737 				   sys_ttl[p->ttl]);
2738 		break;
2739 
2740 	case CP_UNREACH:
2741 		ctl_putuint(peer_var[id].text, p->unreach);
2742 		break;
2743 
2744 	case CP_TIMER:
2745 		ctl_putuint(peer_var[id].text,
2746 			    p->nextdate - current_time);
2747 		break;
2748 
2749 	case CP_DELAY:
2750 		ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2751 		break;
2752 
2753 	case CP_OFFSET:
2754 		ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2755 		break;
2756 
2757 	case CP_JITTER:
2758 		ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2759 		break;
2760 
2761 	case CP_DISPERSION:
2762 		ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2763 		break;
2764 
2765 	case CP_KEYID:
2766 		if (p->keyid > NTP_MAXKEY)
2767 			ctl_puthex(peer_var[id].text, p->keyid);
2768 		else
2769 			ctl_putuint(peer_var[id].text, p->keyid);
2770 		break;
2771 
2772 	case CP_FILTDELAY:
2773 		ctl_putarray(peer_var[id].text, p->filter_delay,
2774 			     p->filter_nextpt);
2775 		break;
2776 
2777 	case CP_FILTOFFSET:
2778 		ctl_putarray(peer_var[id].text, p->filter_offset,
2779 			     p->filter_nextpt);
2780 		break;
2781 
2782 	case CP_FILTERROR:
2783 		ctl_putarray(peer_var[id].text, p->filter_disp,
2784 			     p->filter_nextpt);
2785 		break;
2786 
2787 	case CP_PMODE:
2788 		ctl_putuint(peer_var[id].text, p->pmode);
2789 		break;
2790 
2791 	case CP_RECEIVED:
2792 		ctl_putuint(peer_var[id].text, p->received);
2793 		break;
2794 
2795 	case CP_SENT:
2796 		ctl_putuint(peer_var[id].text, p->sent);
2797 		break;
2798 
2799 	case CP_VARLIST:
2800 		s = buf;
2801 		be = buf + sizeof(buf);
2802 		if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2803 			break;	/* really long var name */
2804 
2805 		snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2806 		s += strlen(s);
2807 		t = s;
2808 		for (k = peer_var; !(EOV & k->flags); k++) {
2809 			if (PADDING & k->flags)
2810 				continue;
2811 			i = strlen(k->text);
2812 			if (s + i + 1 >= be)
2813 				break;
2814 			if (s != t)
2815 				*s++ = ',';
2816 			memcpy(s, k->text, i);
2817 			s += i;
2818 		}
2819 		if (s + 2 < be) {
2820 			*s++ = '"';
2821 			*s = '\0';
2822 			ctl_putdata(buf, (u_int)(s - buf), 0);
2823 		}
2824 		break;
2825 
2826 	case CP_TIMEREC:
2827 		ctl_putuint(peer_var[id].text,
2828 			    current_time - p->timereceived);
2829 		break;
2830 
2831 	case CP_TIMEREACH:
2832 		ctl_putuint(peer_var[id].text,
2833 			    current_time - p->timereachable);
2834 		break;
2835 
2836 	case CP_BADAUTH:
2837 		ctl_putuint(peer_var[id].text, p->badauth);
2838 		break;
2839 
2840 	case CP_BOGUSORG:
2841 		ctl_putuint(peer_var[id].text, p->bogusorg);
2842 		break;
2843 
2844 	case CP_OLDPKT:
2845 		ctl_putuint(peer_var[id].text, p->oldpkt);
2846 		break;
2847 
2848 	case CP_SELDISP:
2849 		ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2850 		break;
2851 
2852 	case CP_SELBROKEN:
2853 		ctl_putuint(peer_var[id].text, p->selbroken);
2854 		break;
2855 
2856 	case CP_CANDIDATE:
2857 		ctl_putuint(peer_var[id].text, p->status);
2858 		break;
2859 #ifdef AUTOKEY
2860 	case CP_FLAGS:
2861 		if (p->crypto)
2862 			ctl_puthex(peer_var[id].text, p->crypto);
2863 		break;
2864 
2865 	case CP_SIGNATURE:
2866 		if (p->crypto) {
2867 			dp = EVP_get_digestbynid(p->crypto >> 16);
2868 			str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2869 			ctl_putstr(peer_var[id].text, str, strlen(str));
2870 		}
2871 		break;
2872 
2873 	case CP_HOST:
2874 		if (p->subject != NULL)
2875 			ctl_putstr(peer_var[id].text, p->subject,
2876 			    strlen(p->subject));
2877 		break;
2878 
2879 	case CP_VALID:		/* not used */
2880 		break;
2881 
2882 	case CP_INITSEQ:
2883 		if (NULL == (ap = p->recval.ptr))
2884 			break;
2885 
2886 		ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2887 		ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2888 		ctl_putfs(peer_var[CP_INITTSP].text,
2889 			  ntohl(p->recval.tstamp));
2890 		break;
2891 
2892 	case CP_IDENT:
2893 		if (p->ident != NULL)
2894 			ctl_putstr(peer_var[id].text, p->ident,
2895 			    strlen(p->ident));
2896 		break;
2897 
2898 
2899 #endif	/* AUTOKEY */
2900 	}
2901 }
2902 
2903 
2904 #ifdef REFCLOCK
2905 /*
2906  * ctl_putclock - output clock variables
2907  */
2908 static void
2909 ctl_putclock(
2910 	int id,
2911 	struct refclockstat *pcs,
2912 	int mustput
2913 	)
2914 {
2915 	char buf[CTL_MAX_DATA_LEN];
2916 	char *s, *t, *be;
2917 	const char *ss;
2918 	int i;
2919 	const struct ctl_var *k;
2920 
2921 	switch (id) {
2922 
2923 	case CC_TYPE:
2924 		if (mustput || pcs->clockdesc == NULL
2925 		    || *(pcs->clockdesc) == '\0') {
2926 			ctl_putuint(clock_var[id].text, pcs->type);
2927 		}
2928 		break;
2929 	case CC_TIMECODE:
2930 		ctl_putstr(clock_var[id].text,
2931 			   pcs->p_lastcode,
2932 			   (unsigned)pcs->lencode);
2933 		break;
2934 
2935 	case CC_POLL:
2936 		ctl_putuint(clock_var[id].text, pcs->polls);
2937 		break;
2938 
2939 	case CC_NOREPLY:
2940 		ctl_putuint(clock_var[id].text,
2941 			    pcs->noresponse);
2942 		break;
2943 
2944 	case CC_BADFORMAT:
2945 		ctl_putuint(clock_var[id].text,
2946 			    pcs->badformat);
2947 		break;
2948 
2949 	case CC_BADDATA:
2950 		ctl_putuint(clock_var[id].text,
2951 			    pcs->baddata);
2952 		break;
2953 
2954 	case CC_FUDGETIME1:
2955 		if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2956 			ctl_putdbl(clock_var[id].text,
2957 				   pcs->fudgetime1 * 1e3);
2958 		break;
2959 
2960 	case CC_FUDGETIME2:
2961 		if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2962 			ctl_putdbl(clock_var[id].text,
2963 				   pcs->fudgetime2 * 1e3);
2964 		break;
2965 
2966 	case CC_FUDGEVAL1:
2967 		if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2968 			ctl_putint(clock_var[id].text,
2969 				   pcs->fudgeval1);
2970 		break;
2971 
2972 	case CC_FUDGEVAL2:
2973 		/* RefID of clocks are always text even if stratum is fudged */
2974 		if (mustput || (pcs->haveflags & CLK_HAVEVAL2))
2975 			ctl_putrefid(clock_var[id].text, pcs->fudgeval2);
2976 		break;
2977 
2978 	case CC_FLAGS:
2979 		ctl_putuint(clock_var[id].text, pcs->flags);
2980 		break;
2981 
2982 	case CC_DEVICE:
2983 		if (pcs->clockdesc == NULL ||
2984 		    *(pcs->clockdesc) == '\0') {
2985 			if (mustput)
2986 				ctl_putstr(clock_var[id].text,
2987 					   "", 0);
2988 		} else {
2989 			ctl_putstr(clock_var[id].text,
2990 				   pcs->clockdesc,
2991 				   strlen(pcs->clockdesc));
2992 		}
2993 		break;
2994 
2995 	case CC_VARLIST:
2996 		s = buf;
2997 		be = buf + sizeof(buf);
2998 		if (strlen(clock_var[CC_VARLIST].text) + 4 >
2999 		    sizeof(buf))
3000 			break;	/* really long var name */
3001 
3002 		snprintf(s, sizeof(buf), "%s=\"",
3003 			 clock_var[CC_VARLIST].text);
3004 		s += strlen(s);
3005 		t = s;
3006 
3007 		for (k = clock_var; !(EOV & k->flags); k++) {
3008 			if (PADDING & k->flags)
3009 				continue;
3010 
3011 			i = strlen(k->text);
3012 			if (s + i + 1 >= be)
3013 				break;
3014 
3015 			if (s != t)
3016 				*s++ = ',';
3017 			memcpy(s, k->text, i);
3018 			s += i;
3019 		}
3020 
3021 		for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
3022 			if (PADDING & k->flags)
3023 				continue;
3024 
3025 			ss = k->text;
3026 			if (NULL == ss)
3027 				continue;
3028 
3029 			while (*ss && *ss != '=')
3030 				ss++;
3031 			i = ss - k->text;
3032 			if (s + i + 1 >= be)
3033 				break;
3034 
3035 			if (s != t)
3036 				*s++ = ',';
3037 			memcpy(s, k->text, (unsigned)i);
3038 			s += i;
3039 			*s = '\0';
3040 		}
3041 		if (s + 2 >= be)
3042 			break;
3043 
3044 		*s++ = '"';
3045 		*s = '\0';
3046 		ctl_putdata(buf, (unsigned)(s - buf), 0);
3047 		break;
3048 
3049 	case CC_FUDGEMINJIT:
3050 		if (mustput || (pcs->haveflags & CLK_HAVEMINJIT))
3051 			ctl_putdbl(clock_var[id].text,
3052 				   pcs->fudgeminjitter * 1e3);
3053 		break;
3054 
3055 	default:
3056 		break;
3057 
3058 	}
3059 }
3060 #endif
3061 
3062 
3063 
3064 /*
3065  * ctl_getitem - get the next data item from the incoming packet
3066  */
3067 static const struct ctl_var *
3068 ctl_getitem(
3069 	const struct ctl_var *var_list,
3070 	char **data
3071 	)
3072 {
3073 	/* [Bug 3008] First check the packet data sanity, then search
3074 	 * the key. This improves the consistency of result values: If
3075 	 * the result is NULL once, it will never be EOV again for this
3076 	 * packet; If it's EOV, it will never be NULL again until the
3077 	 * variable is found and processed in a given 'var_list'. (That
3078 	 * is, a result is returned that is neither NULL nor EOV).
3079 	 */
3080 	static const struct ctl_var eol = { 0, EOV, NULL };
3081 	static char buf[128];
3082 	static u_long quiet_until;
3083 	const struct ctl_var *v;
3084 	char *cp;
3085 	char *tp;
3086 
3087 	/*
3088 	 * Part One: Validate the packet state
3089 	 */
3090 
3091 	/* Delete leading commas and white space */
3092 	while (reqpt < reqend && (*reqpt == ',' ||
3093 				  isspace((unsigned char)*reqpt)))
3094 		reqpt++;
3095 	if (reqpt >= reqend)
3096 		return NULL;
3097 
3098 	/* Scan the string in the packet until we hit comma or
3099 	 * EoB. Register position of first '=' on the fly. */
3100 	for (tp = NULL, cp = reqpt; cp != reqend; ++cp) {
3101 		if (*cp == '=' && tp == NULL)
3102 			tp = cp;
3103 		if (*cp == ',')
3104 			break;
3105 	}
3106 
3107 	/* Process payload, if any. */
3108 	*data = NULL;
3109 	if (NULL != tp) {
3110 		/* eventually strip white space from argument. */
3111 		const char *plhead = tp + 1; /* skip the '=' */
3112 		const char *pltail = cp;
3113 		size_t      plsize;
3114 
3115 		while (plhead != pltail && isspace((u_char)plhead[0]))
3116 			++plhead;
3117 		while (plhead != pltail && isspace((u_char)pltail[-1]))
3118 			--pltail;
3119 
3120 		/* check payload size, terminate packet on overflow */
3121 		plsize = (size_t)(pltail - plhead);
3122 		if (plsize >= sizeof(buf))
3123 			goto badpacket;
3124 
3125 		/* copy data, NUL terminate, and set result data ptr */
3126 		memcpy(buf, plhead, plsize);
3127 		buf[plsize] = '\0';
3128 		*data = buf;
3129 	} else {
3130 		/* no payload, current end --> current name termination */
3131 		tp = cp;
3132 	}
3133 
3134 	/* Part Two
3135 	 *
3136 	 * Now we're sure that the packet data itself is sane. Scan the
3137 	 * list now. Make sure a NULL list is properly treated by
3138 	 * returning a synthetic End-Of-Values record. We must not
3139 	 * return NULL pointers after this point, or the behaviour would
3140 	 * become inconsistent if called several times with different
3141 	 * variable lists after an EoV was returned.  (Such a behavior
3142 	 * actually caused Bug 3008.)
3143 	 */
3144 
3145 	if (NULL == var_list)
3146 		return &eol;
3147 
3148 	for (v = var_list; !(EOV & v->flags); ++v)
3149 		if (!(PADDING & v->flags)) {
3150 			/* Check if the var name matches the buffer. The
3151 			 * name is bracketed by [reqpt..tp] and not NUL
3152 			 * terminated, and it contains no '=' char. The
3153 			 * lookup value IS NUL-terminated but might
3154 			 * include a '='... We have to look out for
3155 			 * that!
3156 			 */
3157 			const char *sp1 = reqpt;
3158 			const char *sp2 = v->text;
3159 
3160 			/* [Bug 3412] do not compare past NUL byte in name */
3161 			while (   (sp1 != tp)
3162 			       && ('\0' != *sp2) && (*sp1 == *sp2)) {
3163 				++sp1;
3164 				++sp2;
3165 			}
3166 			if (sp1 == tp && (*sp2 == '\0' || *sp2 == '='))
3167 				break;
3168 		}
3169 
3170 	/* See if we have found a valid entry or not. If found, advance
3171 	 * the request pointer for the next round; if not, clear the
3172 	 * data pointer so we have no dangling garbage here.
3173 	 */
3174 	if (EOV & v->flags)
3175 		*data = NULL;
3176 	else
3177 		reqpt = cp + (cp != reqend);
3178 	return v;
3179 
3180   badpacket:
3181 	/*TODO? somehow indicate this packet was bad, apart from syslog? */
3182 	numctlbadpkts++;
3183 	NLOG(NLOG_SYSEVENT)
3184 	    if (quiet_until <= current_time) {
3185 		    quiet_until = current_time + 300;
3186 		    msyslog(LOG_WARNING,
3187 			    "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)",
3188 			    stoa(rmt_addr), SRCPORT(rmt_addr));
3189 	    }
3190 	reqpt = reqend; /* never again for this packet! */
3191 	return NULL;
3192 }
3193 
3194 
3195 /*
3196  * control_unspec - response to an unspecified op-code
3197  */
3198 /*ARGSUSED*/
3199 static void
3200 control_unspec(
3201 	struct recvbuf *rbufp,
3202 	int restrict_mask
3203 	)
3204 {
3205 	struct peer *peer;
3206 
3207 	/*
3208 	 * What is an appropriate response to an unspecified op-code?
3209 	 * I return no errors and no data, unless a specified assocation
3210 	 * doesn't exist.
3211 	 */
3212 	if (res_associd) {
3213 		peer = findpeerbyassoc(res_associd);
3214 		if (NULL == peer) {
3215 			ctl_error(CERR_BADASSOC);
3216 			return;
3217 		}
3218 		rpkt.status = htons(ctlpeerstatus(peer));
3219 	} else
3220 		rpkt.status = htons(ctlsysstatus());
3221 	ctl_flushpkt(0);
3222 }
3223 
3224 
3225 /*
3226  * read_status - return either a list of associd's, or a particular
3227  * peer's status.
3228  */
3229 /*ARGSUSED*/
3230 static void
3231 read_status(
3232 	struct recvbuf *rbufp,
3233 	int restrict_mask
3234 	)
3235 {
3236 	struct peer *peer;
3237 	const u_char *cp;
3238 	size_t n;
3239 	/* a_st holds association ID, status pairs alternating */
3240 	u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3241 
3242 #ifdef DEBUG
3243 	if (debug > 2)
3244 		printf("read_status: ID %d\n", res_associd);
3245 #endif
3246 	/*
3247 	 * Two choices here. If the specified association ID is
3248 	 * zero we return all known assocation ID's.  Otherwise
3249 	 * we return a bunch of stuff about the particular peer.
3250 	 */
3251 	if (res_associd) {
3252 		peer = findpeerbyassoc(res_associd);
3253 		if (NULL == peer) {
3254 			ctl_error(CERR_BADASSOC);
3255 			return;
3256 		}
3257 		rpkt.status = htons(ctlpeerstatus(peer));
3258 		if (res_authokay)
3259 			peer->num_events = 0;
3260 		/*
3261 		 * For now, output everything we know about the
3262 		 * peer. May be more selective later.
3263 		 */
3264 		for (cp = def_peer_var; *cp != 0; cp++)
3265 			ctl_putpeer((int)*cp, peer);
3266 		ctl_flushpkt(0);
3267 		return;
3268 	}
3269 	n = 0;
3270 	rpkt.status = htons(ctlsysstatus());
3271 	for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3272 		a_st[n++] = htons(peer->associd);
3273 		a_st[n++] = htons(ctlpeerstatus(peer));
3274 		/* two entries each loop iteration, so n + 1 */
3275 		if (n + 1 >= COUNTOF(a_st)) {
3276 			ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3277 				    1);
3278 			n = 0;
3279 		}
3280 	}
3281 	if (n)
3282 		ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3283 	ctl_flushpkt(0);
3284 }
3285 
3286 
3287 /*
3288  * read_peervars - half of read_variables() implementation
3289  */
3290 static void
3291 read_peervars(void)
3292 {
3293 	const struct ctl_var *v;
3294 	struct peer *peer;
3295 	const u_char *cp;
3296 	size_t i;
3297 	char *	valuep;
3298 	u_char	wants[CP_MAXCODE + 1];
3299 	u_int	gotvar;
3300 
3301 	/*
3302 	 * Wants info for a particular peer. See if we know
3303 	 * the guy.
3304 	 */
3305 	peer = findpeerbyassoc(res_associd);
3306 	if (NULL == peer) {
3307 		ctl_error(CERR_BADASSOC);
3308 		return;
3309 	}
3310 	rpkt.status = htons(ctlpeerstatus(peer));
3311 	if (res_authokay)
3312 		peer->num_events = 0;
3313 	ZERO(wants);
3314 	gotvar = 0;
3315 	while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3316 		if (v->flags & EOV) {
3317 			ctl_error(CERR_UNKNOWNVAR);
3318 			return;
3319 		}
3320 		INSIST(v->code < COUNTOF(wants));
3321 		wants[v->code] = 1;
3322 		gotvar = 1;
3323 	}
3324 	if (gotvar) {
3325 		for (i = 1; i < COUNTOF(wants); i++)
3326 			if (wants[i])
3327 				ctl_putpeer(i, peer);
3328 	} else
3329 		for (cp = def_peer_var; *cp != 0; cp++)
3330 			ctl_putpeer((int)*cp, peer);
3331 	ctl_flushpkt(0);
3332 }
3333 
3334 
3335 /*
3336  * read_sysvars - half of read_variables() implementation
3337  */
3338 static void
3339 read_sysvars(void)
3340 {
3341 	const struct ctl_var *v;
3342 	struct ctl_var *kv;
3343 	u_int	n;
3344 	u_int	gotvar;
3345 	const u_char *cs;
3346 	char *	valuep;
3347 	const char * pch;
3348 	u_char *wants;
3349 	size_t	wants_count;
3350 
3351 	/*
3352 	 * Wants system variables. Figure out which he wants
3353 	 * and give them to him.
3354 	 */
3355 	rpkt.status = htons(ctlsysstatus());
3356 	if (res_authokay)
3357 		ctl_sys_num_events = 0;
3358 	wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3359 	wants = emalloc_zero(wants_count);
3360 	gotvar = 0;
3361 	while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3362 		if (!(EOV & v->flags)) {
3363 			INSIST(v->code < wants_count);
3364 			wants[v->code] = 1;
3365 			gotvar = 1;
3366 		} else {
3367 			v = ctl_getitem(ext_sys_var, &valuep);
3368 			if (NULL == v) {
3369 				ctl_error(CERR_BADVALUE);
3370 				free(wants);
3371 				return;
3372 			}
3373 			if (EOV & v->flags) {
3374 				ctl_error(CERR_UNKNOWNVAR);
3375 				free(wants);
3376 				return;
3377 			}
3378 			n = v->code + CS_MAXCODE + 1;
3379 			INSIST(n < wants_count);
3380 			wants[n] = 1;
3381 			gotvar = 1;
3382 		}
3383 	}
3384 	if (gotvar) {
3385 		for (n = 1; n <= CS_MAXCODE; n++)
3386 			if (wants[n])
3387 				ctl_putsys(n);
3388 		for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3389 			if (wants[n + CS_MAXCODE + 1]) {
3390 				pch = ext_sys_var[n].text;
3391 				ctl_putdata(pch, strlen(pch), 0);
3392 			}
3393 	} else {
3394 		for (cs = def_sys_var; *cs != 0; cs++)
3395 			ctl_putsys((int)*cs);
3396 		for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3397 			if (DEF & kv->flags)
3398 				ctl_putdata(kv->text, strlen(kv->text),
3399 					    0);
3400 	}
3401 	free(wants);
3402 	ctl_flushpkt(0);
3403 }
3404 
3405 
3406 /*
3407  * read_variables - return the variables the caller asks for
3408  */
3409 /*ARGSUSED*/
3410 static void
3411 read_variables(
3412 	struct recvbuf *rbufp,
3413 	int restrict_mask
3414 	)
3415 {
3416 	if (res_associd)
3417 		read_peervars();
3418 	else
3419 		read_sysvars();
3420 }
3421 
3422 
3423 /*
3424  * write_variables - write into variables. We only allow leap bit
3425  * writing this way.
3426  */
3427 /*ARGSUSED*/
3428 static void
3429 write_variables(
3430 	struct recvbuf *rbufp,
3431 	int restrict_mask
3432 	)
3433 {
3434 	const struct ctl_var *v;
3435 	int ext_var;
3436 	char *valuep;
3437 	long val;
3438 	size_t octets;
3439 	char *vareqv;
3440 	const char *t;
3441 	char *tt;
3442 
3443 	val = 0;
3444 	/*
3445 	 * If he's trying to write into a peer tell him no way
3446 	 */
3447 	if (res_associd != 0) {
3448 		ctl_error(CERR_PERMISSION);
3449 		return;
3450 	}
3451 
3452 	/*
3453 	 * Set status
3454 	 */
3455 	rpkt.status = htons(ctlsysstatus());
3456 
3457 	/*
3458 	 * Look through the variables. Dump out at the first sign of
3459 	 * trouble.
3460 	 */
3461 	while ((v = ctl_getitem(sys_var, &valuep)) != NULL) {
3462 		ext_var = 0;
3463 		if (v->flags & EOV) {
3464 			v = ctl_getitem(ext_sys_var, &valuep);
3465 			if (v != NULL) {
3466 				if (v->flags & EOV) {
3467 					ctl_error(CERR_UNKNOWNVAR);
3468 					return;
3469 				}
3470 				ext_var = 1;
3471 			} else {
3472 				break;
3473 			}
3474 		}
3475 		if (!(v->flags & CAN_WRITE)) {
3476 			ctl_error(CERR_PERMISSION);
3477 			return;
3478 		}
3479 		/* [bug 3565] writing makes sense only if we *have* a
3480 		 * value in the packet!
3481 		 */
3482 		if (valuep == NULL) {
3483 			ctl_error(CERR_BADFMT);
3484 			return;
3485 		}
3486 		if (!ext_var) {
3487 			if ( !(*valuep && atoint(valuep, &val))) {
3488 				ctl_error(CERR_BADFMT);
3489 				return;
3490 			}
3491 			if ((val & ~LEAP_NOTINSYNC) != 0) {
3492 				ctl_error(CERR_BADVALUE);
3493 				return;
3494 			}
3495 		}
3496 
3497 		if (ext_var) {
3498 			octets = strlen(v->text) + strlen(valuep) + 2;
3499 			vareqv = emalloc(octets);
3500 			tt = vareqv;
3501 			t = v->text;
3502 			while (*t && *t != '=')
3503 				*tt++ = *t++;
3504 			*tt++ = '=';
3505 			memcpy(tt, valuep, 1 + strlen(valuep));
3506 			set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3507 			free(vareqv);
3508 		} else {
3509 			ctl_error(CERR_UNSPEC); /* really */
3510 			return;
3511 		}
3512 	}
3513 
3514 	/*
3515 	 * If we got anything, do it. xxx nothing to do ***
3516 	 */
3517 	/*
3518 	  if (leapind != ~0 || leapwarn != ~0) {
3519 	  if (!leap_setleap((int)leapind, (int)leapwarn)) {
3520 	  ctl_error(CERR_PERMISSION);
3521 	  return;
3522 	  }
3523 	  }
3524 	*/
3525 	ctl_flushpkt(0);
3526 }
3527 
3528 
3529 /*
3530  * configure() processes ntpq :config/config-from-file, allowing
3531  *		generic runtime reconfiguration.
3532  */
3533 static void configure(
3534 	struct recvbuf *rbufp,
3535 	int restrict_mask
3536 	)
3537 {
3538 	size_t data_count;
3539 	int retval;
3540 
3541 	/* I haven't yet implemented changes to an existing association.
3542 	 * Hence check if the association id is 0
3543 	 */
3544 	if (res_associd != 0) {
3545 		ctl_error(CERR_BADVALUE);
3546 		return;
3547 	}
3548 
3549 	if (RES_NOMODIFY & restrict_mask) {
3550 		snprintf(remote_config.err_msg,
3551 			 sizeof(remote_config.err_msg),
3552 			 "runtime configuration prohibited by restrict ... nomodify");
3553 		ctl_putdata(remote_config.err_msg,
3554 			    strlen(remote_config.err_msg), 0);
3555 		ctl_flushpkt(0);
3556 		NLOG(NLOG_SYSINFO)
3557 			msyslog(LOG_NOTICE,
3558 				"runtime config from %s rejected due to nomodify restriction",
3559 				stoa(&rbufp->recv_srcadr));
3560 		sys_restricted++;
3561 		return;
3562 	}
3563 
3564 	/* Initialize the remote config buffer */
3565 	data_count = remoteconfig_cmdlength(reqpt, reqend);
3566 
3567 	if (data_count > sizeof(remote_config.buffer) - 2) {
3568 		snprintf(remote_config.err_msg,
3569 			 sizeof(remote_config.err_msg),
3570 			 "runtime configuration failed: request too long");
3571 		ctl_putdata(remote_config.err_msg,
3572 			    strlen(remote_config.err_msg), 0);
3573 		ctl_flushpkt(0);
3574 		msyslog(LOG_NOTICE,
3575 			"runtime config from %s rejected: request too long",
3576 			stoa(&rbufp->recv_srcadr));
3577 		return;
3578 	}
3579 	/* Bug 2853 -- check if all characters were acceptable */
3580 	if (data_count != (size_t)(reqend - reqpt)) {
3581 		snprintf(remote_config.err_msg,
3582 			 sizeof(remote_config.err_msg),
3583 			 "runtime configuration failed: request contains an unprintable character");
3584 		ctl_putdata(remote_config.err_msg,
3585 			    strlen(remote_config.err_msg), 0);
3586 		ctl_flushpkt(0);
3587 		msyslog(LOG_NOTICE,
3588 			"runtime config from %s rejected: request contains an unprintable character: %0x",
3589 			stoa(&rbufp->recv_srcadr),
3590 			reqpt[data_count]);
3591 		return;
3592 	}
3593 
3594 	memcpy(remote_config.buffer, reqpt, data_count);
3595 	/* The buffer has no trailing linefeed or NUL right now. For
3596 	 * logging, we do not want a newline, so we do that first after
3597 	 * adding the necessary NUL byte.
3598 	 */
3599 	remote_config.buffer[data_count] = '\0';
3600 	DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3601 		remote_config.buffer));
3602 	msyslog(LOG_NOTICE, "%s config: %s",
3603 		stoa(&rbufp->recv_srcadr),
3604 		remote_config.buffer);
3605 
3606 	/* Now we have to make sure there is a NL/NUL sequence at the
3607 	 * end of the buffer before we parse it.
3608 	 */
3609 	remote_config.buffer[data_count++] = '\n';
3610 	remote_config.buffer[data_count] = '\0';
3611 	remote_config.pos = 0;
3612 	remote_config.err_pos = 0;
3613 	remote_config.no_errors = 0;
3614 	config_remotely(&rbufp->recv_srcadr);
3615 
3616 	/*
3617 	 * Check if errors were reported. If not, output 'Config
3618 	 * Succeeded'.  Else output the error count.  It would be nice
3619 	 * to output any parser error messages.
3620 	 */
3621 	if (0 == remote_config.no_errors) {
3622 		retval = snprintf(remote_config.err_msg,
3623 				  sizeof(remote_config.err_msg),
3624 				  "Config Succeeded");
3625 		if (retval > 0)
3626 			remote_config.err_pos += retval;
3627 	}
3628 
3629 	ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3630 	ctl_flushpkt(0);
3631 
3632 	DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3633 
3634 	if (remote_config.no_errors > 0)
3635 		msyslog(LOG_NOTICE, "%d error in %s config",
3636 			remote_config.no_errors,
3637 			stoa(&rbufp->recv_srcadr));
3638 }
3639 
3640 
3641 /*
3642  * derive_nonce - generate client-address-specific nonce value
3643  *		  associated with a given timestamp.
3644  */
3645 static u_int32 derive_nonce(
3646 	sockaddr_u *	addr,
3647 	u_int32		ts_i,
3648 	u_int32		ts_f
3649 	)
3650 {
3651 	static u_int32	salt[4];
3652 	static u_long	last_salt_update;
3653 	union d_tag {
3654 		u_char	digest[EVP_MAX_MD_SIZE];
3655 		u_int32 extract;
3656 	}		d;
3657 	EVP_MD_CTX	*ctx;
3658 	u_int		len;
3659 
3660 	while (!salt[0] || current_time - last_salt_update >= 3600) {
3661 		salt[0] = ntp_random();
3662 		salt[1] = ntp_random();
3663 		salt[2] = ntp_random();
3664 		salt[3] = ntp_random();
3665 		last_salt_update = current_time;
3666 	}
3667 
3668 	ctx = EVP_MD_CTX_new();
3669 #   if defined(OPENSSL) && defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW)
3670 	/* [Bug 3457] set flags and don't kill them again */
3671 	EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
3672 	EVP_DigestInit_ex(ctx, EVP_get_digestbynid(NID_md5), NULL);
3673 #   else
3674 	EVP_DigestInit(ctx, EVP_get_digestbynid(NID_md5));
3675 #   endif
3676 	EVP_DigestUpdate(ctx, salt, sizeof(salt));
3677 	EVP_DigestUpdate(ctx, &ts_i, sizeof(ts_i));
3678 	EVP_DigestUpdate(ctx, &ts_f, sizeof(ts_f));
3679 	if (IS_IPV4(addr))
3680 		EVP_DigestUpdate(ctx, &SOCK_ADDR4(addr),
3681 			         sizeof(SOCK_ADDR4(addr)));
3682 	else
3683 		EVP_DigestUpdate(ctx, &SOCK_ADDR6(addr),
3684 			         sizeof(SOCK_ADDR6(addr)));
3685 	EVP_DigestUpdate(ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3686 	EVP_DigestUpdate(ctx, salt, sizeof(salt));
3687 	EVP_DigestFinal(ctx, d.digest, &len);
3688 	EVP_MD_CTX_free(ctx);
3689 
3690 	return d.extract;
3691 }
3692 
3693 
3694 /*
3695  * generate_nonce - generate client-address-specific nonce string.
3696  */
3697 static void generate_nonce(
3698 	struct recvbuf *	rbufp,
3699 	char *			nonce,
3700 	size_t			nonce_octets
3701 	)
3702 {
3703 	u_int32 derived;
3704 
3705 	derived = derive_nonce(&rbufp->recv_srcadr,
3706 			       rbufp->recv_time.l_ui,
3707 			       rbufp->recv_time.l_uf);
3708 	snprintf(nonce, nonce_octets, "%08x%08x%08x",
3709 		 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3710 }
3711 
3712 
3713 /*
3714  * validate_nonce - validate client-address-specific nonce string.
3715  *
3716  * Returns TRUE if the local calculation of the nonce matches the
3717  * client-provided value and the timestamp is recent enough.
3718  */
3719 static int validate_nonce(
3720 	const char *		pnonce,
3721 	struct recvbuf *	rbufp
3722 	)
3723 {
3724 	u_int	ts_i;
3725 	u_int	ts_f;
3726 	l_fp	ts;
3727 	l_fp	now_delta;
3728 	u_int	supposed;
3729 	u_int	derived;
3730 
3731 	if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3732 		return FALSE;
3733 
3734 	ts.l_ui = (u_int32)ts_i;
3735 	ts.l_uf = (u_int32)ts_f;
3736 	derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3737 	get_systime(&now_delta);
3738 	L_SUB(&now_delta, &ts);
3739 
3740 	return (supposed == derived && now_delta.l_ui < 16);
3741 }
3742 
3743 
3744 /*
3745  * send_random_tag_value - send a randomly-generated three character
3746  *			   tag prefix, a '.', an index, a '=' and a
3747  *			   random integer value.
3748  *
3749  * To try to force clients to ignore unrecognized tags in mrulist,
3750  * reslist, and ifstats responses, the first and last rows are spiced
3751  * with randomly-generated tag names with correct .# index.  Make it
3752  * three characters knowing that none of the currently-used subscripted
3753  * tags have that length, avoiding the need to test for
3754  * tag collision.
3755  */
3756 static void
3757 send_random_tag_value(
3758 	int	indx
3759 	)
3760 {
3761 	int	noise;
3762 	char	buf[32];
3763 
3764 	noise = rand() ^ (rand() << 16);
3765 	buf[0] = 'a' + noise % 26;
3766 	noise >>= 5;
3767 	buf[1] = 'a' + noise % 26;
3768 	noise >>= 5;
3769 	buf[2] = 'a' + noise % 26;
3770 	noise >>= 5;
3771 	buf[3] = '.';
3772 	snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3773 	ctl_putuint(buf, noise);
3774 }
3775 
3776 
3777 /*
3778  * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3779  *
3780  * To keep clients honest about not depending on the order of values,
3781  * and thereby avoid being locked into ugly workarounds to maintain
3782  * backward compatibility later as new fields are added to the response,
3783  * the order is random.
3784  */
3785 static void
3786 send_mru_entry(
3787 	mon_entry *	mon,
3788 	int		count
3789 	)
3790 {
3791 	const char first_fmt[] =	"first.%d";
3792 	const char ct_fmt[] =		"ct.%d";
3793 	const char mv_fmt[] =		"mv.%d";
3794 	const char rs_fmt[] =		"rs.%d";
3795 	char	tag[32];
3796 	u_char	sent[6]; /* 6 tag=value pairs */
3797 	u_int32 noise;
3798 	u_int	which;
3799 	u_int	remaining;
3800 	const char * pch;
3801 
3802 	remaining = COUNTOF(sent);
3803 	ZERO(sent);
3804 	noise = (u_int32)(rand() ^ (rand() << 16));
3805 	while (remaining > 0) {
3806 		which = (noise & 7) % COUNTOF(sent);
3807 		noise >>= 3;
3808 		while (sent[which])
3809 			which = (which + 1) % COUNTOF(sent);
3810 
3811 		switch (which) {
3812 
3813 		case 0:
3814 			snprintf(tag, sizeof(tag), addr_fmt, count);
3815 			pch = sptoa(&mon->rmtadr);
3816 			ctl_putunqstr(tag, pch, strlen(pch));
3817 			break;
3818 
3819 		case 1:
3820 			snprintf(tag, sizeof(tag), last_fmt, count);
3821 			ctl_putts(tag, &mon->last);
3822 			break;
3823 
3824 		case 2:
3825 			snprintf(tag, sizeof(tag), first_fmt, count);
3826 			ctl_putts(tag, &mon->first);
3827 			break;
3828 
3829 		case 3:
3830 			snprintf(tag, sizeof(tag), ct_fmt, count);
3831 			ctl_putint(tag, mon->count);
3832 			break;
3833 
3834 		case 4:
3835 			snprintf(tag, sizeof(tag), mv_fmt, count);
3836 			ctl_putuint(tag, mon->vn_mode);
3837 			break;
3838 
3839 		case 5:
3840 			snprintf(tag, sizeof(tag), rs_fmt, count);
3841 			ctl_puthex(tag, mon->flags);
3842 			break;
3843 		}
3844 		sent[which] = TRUE;
3845 		remaining--;
3846 	}
3847 }
3848 
3849 
3850 /*
3851  * read_mru_list - supports ntpq's mrulist command.
3852  *
3853  * The challenge here is to match ntpdc's monlist functionality without
3854  * being limited to hundreds of entries returned total, and without
3855  * requiring state on the server.  If state were required, ntpq's
3856  * mrulist command would require authentication.
3857  *
3858  * The approach was suggested by Ry Jones.  A finite and variable number
3859  * of entries are retrieved per request, to avoid having responses with
3860  * such large numbers of packets that socket buffers are overflowed and
3861  * packets lost.  The entries are retrieved oldest-first, taking into
3862  * account that the MRU list will be changing between each request.  We
3863  * can expect to see duplicate entries for addresses updated in the MRU
3864  * list during the fetch operation.  In the end, the client can assemble
3865  * a close approximation of the MRU list at the point in time the last
3866  * response was sent by ntpd.  The only difference is it may be longer,
3867  * containing some number of oldest entries which have since been
3868  * reclaimed.  If necessary, the protocol could be extended to zap those
3869  * from the client snapshot at the end, but so far that doesn't seem
3870  * useful.
3871  *
3872  * To accomodate the changing MRU list, the starting point for requests
3873  * after the first request is supplied as a series of last seen
3874  * timestamps and associated addresses, the newest ones the client has
3875  * received.  As long as at least one of those entries hasn't been
3876  * bumped to the head of the MRU list, ntpd can pick up at that point.
3877  * Otherwise, the request is failed and it is up to ntpq to back up and
3878  * provide the next newest entry's timestamps and addresses, conceivably
3879  * backing up all the way to the starting point.
3880  *
3881  * input parameters:
3882  *	nonce=		Regurgitated nonce retrieved by the client
3883  *			previously using CTL_OP_REQ_NONCE, demonstrating
3884  *			ability to receive traffic sent to its address.
3885  *	frags=		Limit on datagrams (fragments) in response.  Used
3886  *			by newer ntpq versions instead of limit= when
3887  *			retrieving multiple entries.
3888  *	limit=		Limit on MRU entries returned.  One of frags= or
3889  *			limit= must be provided.
3890  *			limit=1 is a special case:  Instead of fetching
3891  *			beginning with the supplied starting point's
3892  *			newer neighbor, fetch the supplied entry, and
3893  *			in that case the #.last timestamp can be zero.
3894  *			This enables fetching a single entry by IP
3895  *			address.  When limit is not one and frags= is
3896  *			provided, the fragment limit controls.
3897  *	mincount=	(decimal) Return entries with count >= mincount.
3898  *	laddr=		Return entries associated with the server's IP
3899  *			address given.  No port specification is needed,
3900  *			and any supplied is ignored.
3901  *	resall=		0x-prefixed hex restrict bits which must all be
3902  *			lit for an MRU entry to be included.
3903  *			Has precedence over any resany=.
3904  *	resany=		0x-prefixed hex restrict bits, at least one of
3905  *			which must be list for an MRU entry to be
3906  *			included.
3907  *	last.0=		0x-prefixed hex l_fp timestamp of newest entry
3908  *			which client previously received.
3909  *	addr.0=		text of newest entry's IP address and port,
3910  *			IPv6 addresses in bracketed form: [::]:123
3911  *	last.1=		timestamp of 2nd newest entry client has.
3912  *	addr.1=		address of 2nd newest entry.
3913  *	[...]
3914  *
3915  * ntpq provides as many last/addr pairs as will fit in a single request
3916  * packet, except for the first request in a MRU fetch operation.
3917  *
3918  * The response begins with a new nonce value to be used for any
3919  * followup request.  Following the nonce is the next newer entry than
3920  * referred to by last.0 and addr.0, if the "0" entry has not been
3921  * bumped to the front.  If it has, the first entry returned will be the
3922  * next entry newer than referred to by last.1 and addr.1, and so on.
3923  * If none of the referenced entries remain unchanged, the request fails
3924  * and ntpq backs up to the next earlier set of entries to resync.
3925  *
3926  * Except for the first response, the response begins with confirmation
3927  * of the entry that precedes the first additional entry provided:
3928  *
3929  *	last.older=	hex l_fp timestamp matching one of the input
3930  *			.last timestamps, which entry now precedes the
3931  *			response 0. entry in the MRU list.
3932  *	addr.older=	text of address corresponding to older.last.
3933  *
3934  * And in any case, a successful response contains sets of values
3935  * comprising entries, with the oldest numbered 0 and incrementing from
3936  * there:
3937  *
3938  *	addr.#		text of IPv4 or IPv6 address and port
3939  *	last.#		hex l_fp timestamp of last receipt
3940  *	first.#		hex l_fp timestamp of first receipt
3941  *	ct.#		count of packets received
3942  *	mv.#		mode and version
3943  *	rs.#		restriction mask (RES_* bits)
3944  *
3945  * Note the code currently assumes there are no valid three letter
3946  * tags sent with each row, and needs to be adjusted if that changes.
3947  *
3948  * The client should accept the values in any order, and ignore .#
3949  * values which it does not understand, to allow a smooth path to
3950  * future changes without requiring a new opcode.  Clients can rely
3951  * on all *.0 values preceding any *.1 values, that is all values for
3952  * a given index number are together in the response.
3953  *
3954  * The end of the response list is noted with one or two tag=value
3955  * pairs.  Unconditionally:
3956  *
3957  *	now=		0x-prefixed l_fp timestamp at the server marking
3958  *			the end of the operation.
3959  *
3960  * If any entries were returned, now= is followed by:
3961  *
3962  *	last.newest=	hex l_fp identical to last.# of the prior
3963  *			entry.
3964  */
3965 static void read_mru_list(
3966 	struct recvbuf *rbufp,
3967 	int restrict_mask
3968 	)
3969 {
3970 	static const char	nulltxt[1] = 		{ '\0' };
3971 	static const char	nonce_text[] =		"nonce";
3972 	static const char	frags_text[] =		"frags";
3973 	static const char	limit_text[] =		"limit";
3974 	static const char	mincount_text[] =	"mincount";
3975 	static const char	resall_text[] =		"resall";
3976 	static const char	resany_text[] =		"resany";
3977 	static const char	maxlstint_text[] =	"maxlstint";
3978 	static const char	laddr_text[] =		"laddr";
3979 	static const char	resaxx_fmt[] =		"0x%hx";
3980 
3981 	u_int			limit;
3982 	u_short			frags;
3983 	u_short			resall;
3984 	u_short			resany;
3985 	int			mincount;
3986 	u_int			maxlstint;
3987 	sockaddr_u		laddr;
3988 	struct interface *	lcladr;
3989 	u_int			count;
3990 	u_int			ui;
3991 	u_int			uf;
3992 	l_fp			last[16];
3993 	sockaddr_u		addr[COUNTOF(last)];
3994 	char			buf[128];
3995 	struct ctl_var *	in_parms;
3996 	const struct ctl_var *	v;
3997 	const char *		val;
3998 	const char *		pch;
3999 	char *			pnonce;
4000 	int			nonce_valid;
4001 	size_t			i;
4002 	int			priors;
4003 	u_short			hash;
4004 	mon_entry *		mon;
4005 	mon_entry *		prior_mon;
4006 	l_fp			now;
4007 
4008 	if (RES_NOMRULIST & restrict_mask) {
4009 		ctl_error(CERR_PERMISSION);
4010 		NLOG(NLOG_SYSINFO)
4011 			msyslog(LOG_NOTICE,
4012 				"mrulist from %s rejected due to nomrulist restriction",
4013 				stoa(&rbufp->recv_srcadr));
4014 		sys_restricted++;
4015 		return;
4016 	}
4017 	/*
4018 	 * fill in_parms var list with all possible input parameters.
4019 	 */
4020 	in_parms = NULL;
4021 	set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
4022 	set_var(&in_parms, frags_text, sizeof(frags_text), 0);
4023 	set_var(&in_parms, limit_text, sizeof(limit_text), 0);
4024 	set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
4025 	set_var(&in_parms, resall_text, sizeof(resall_text), 0);
4026 	set_var(&in_parms, resany_text, sizeof(resany_text), 0);
4027 	set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
4028 	set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
4029 	for (i = 0; i < COUNTOF(last); i++) {
4030 		snprintf(buf, sizeof(buf), last_fmt, (int)i);
4031 		set_var(&in_parms, buf, strlen(buf) + 1, 0);
4032 		snprintf(buf, sizeof(buf), addr_fmt, (int)i);
4033 		set_var(&in_parms, buf, strlen(buf) + 1, 0);
4034 	}
4035 
4036 	/* decode input parms */
4037 	pnonce = NULL;
4038 	frags = 0;
4039 	limit = 0;
4040 	mincount = 0;
4041 	resall = 0;
4042 	resany = 0;
4043 	maxlstint = 0;
4044 	lcladr = NULL;
4045 	priors = 0;
4046 	ZERO(last);
4047 	ZERO(addr);
4048 
4049 	/* have to go through '(void*)' to drop 'const' property from pointer.
4050 	 * ctl_getitem()' needs some cleanup, too.... perlinger@ntp.org
4051 	 */
4052 	while (NULL != (v = ctl_getitem(in_parms, (void*)&val)) &&
4053 	       !(EOV & v->flags)) {
4054 		int si;
4055 
4056 		if (NULL == val)
4057 			val = nulltxt;
4058 
4059 		if (!strcmp(nonce_text, v->text)) {
4060 			free(pnonce);
4061 			pnonce = (*val) ? estrdup(val) : NULL;
4062 		} else if (!strcmp(frags_text, v->text)) {
4063 			if (1 != sscanf(val, "%hu", &frags))
4064 				goto blooper;
4065 		} else if (!strcmp(limit_text, v->text)) {
4066 			if (1 != sscanf(val, "%u", &limit))
4067 				goto blooper;
4068 		} else if (!strcmp(mincount_text, v->text)) {
4069 			if (1 != sscanf(val, "%d", &mincount))
4070 				goto blooper;
4071 			if (mincount < 0)
4072 				mincount = 0;
4073 		} else if (!strcmp(resall_text, v->text)) {
4074 			if (1 != sscanf(val, resaxx_fmt, &resall))
4075 				goto blooper;
4076 		} else if (!strcmp(resany_text, v->text)) {
4077 			if (1 != sscanf(val, resaxx_fmt, &resany))
4078 				goto blooper;
4079 		} else if (!strcmp(maxlstint_text, v->text)) {
4080 			if (1 != sscanf(val, "%u", &maxlstint))
4081 				goto blooper;
4082 		} else if (!strcmp(laddr_text, v->text)) {
4083 			if (!decodenetnum(val, &laddr))
4084 				goto blooper;
4085 			lcladr = getinterface(&laddr, 0);
4086 		} else if (1 == sscanf(v->text, last_fmt, &si) &&
4087 			   (size_t)si < COUNTOF(last)) {
4088 			if (2 != sscanf(val, "0x%08x.%08x", &ui, &uf))
4089 				goto blooper;
4090 			last[si].l_ui = ui;
4091 			last[si].l_uf = uf;
4092 			if (!SOCK_UNSPEC(&addr[si]) && si == priors)
4093 				priors++;
4094 		} else if (1 == sscanf(v->text, addr_fmt, &si) &&
4095 			   (size_t)si < COUNTOF(addr)) {
4096 			if (!decodenetnum(val, &addr[si]))
4097 				goto blooper;
4098 			if (last[si].l_ui && last[si].l_uf && si == priors)
4099 				priors++;
4100 		} else {
4101 			DPRINTF(1, ("read_mru_list: invalid key item: '%s' (ignored)\n",
4102 				    v->text));
4103 			continue;
4104 
4105 		blooper:
4106 			DPRINTF(1, ("read_mru_list: invalid param for '%s': '%s' (bailing)\n",
4107 				    v->text, val));
4108 			free(pnonce);
4109 			pnonce = NULL;
4110 			break;
4111 		}
4112 	}
4113 	free_varlist(in_parms);
4114 	in_parms = NULL;
4115 
4116 	/* return no responses until the nonce is validated */
4117 	if (NULL == pnonce)
4118 		return;
4119 
4120 	nonce_valid = validate_nonce(pnonce, rbufp);
4121 	free(pnonce);
4122 	if (!nonce_valid)
4123 		return;
4124 
4125 	if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
4126 	    frags > MRU_FRAGS_LIMIT) {
4127 		ctl_error(CERR_BADVALUE);
4128 		return;
4129 	}
4130 
4131 	/*
4132 	 * If either frags or limit is not given, use the max.
4133 	 */
4134 	if (0 != frags && 0 == limit)
4135 		limit = UINT_MAX;
4136 	else if (0 != limit && 0 == frags)
4137 		frags = MRU_FRAGS_LIMIT;
4138 
4139 	/*
4140 	 * Find the starting point if one was provided.
4141 	 */
4142 	mon = NULL;
4143 	for (i = 0; i < (size_t)priors; i++) {
4144 		hash = MON_HASH(&addr[i]);
4145 		for (mon = mon_hash[hash];
4146 		     mon != NULL;
4147 		     mon = mon->hash_next)
4148 			if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
4149 				break;
4150 		if (mon != NULL) {
4151 			if (L_ISEQU(&mon->last, &last[i]))
4152 				break;
4153 			mon = NULL;
4154 		}
4155 	}
4156 
4157 	/* If a starting point was provided... */
4158 	if (priors) {
4159 		/* and none could be found unmodified... */
4160 		if (NULL == mon) {
4161 			/* tell ntpq to try again with older entries */
4162 			ctl_error(CERR_UNKNOWNVAR);
4163 			return;
4164 		}
4165 		/* confirm the prior entry used as starting point */
4166 		ctl_putts("last.older", &mon->last);
4167 		pch = sptoa(&mon->rmtadr);
4168 		ctl_putunqstr("addr.older", pch, strlen(pch));
4169 
4170 		/*
4171 		 * Move on to the first entry the client doesn't have,
4172 		 * except in the special case of a limit of one.  In
4173 		 * that case return the starting point entry.
4174 		 */
4175 		if (limit > 1)
4176 			mon = PREV_DLIST(mon_mru_list, mon, mru);
4177 	} else {	/* start with the oldest */
4178 		mon = TAIL_DLIST(mon_mru_list, mru);
4179 	}
4180 
4181 	/*
4182 	 * send up to limit= entries in up to frags= datagrams
4183 	 */
4184 	get_systime(&now);
4185 	generate_nonce(rbufp, buf, sizeof(buf));
4186 	ctl_putunqstr("nonce", buf, strlen(buf));
4187 	prior_mon = NULL;
4188 	for (count = 0;
4189 	     mon != NULL && res_frags < frags && count < limit;
4190 	     mon = PREV_DLIST(mon_mru_list, mon, mru)) {
4191 
4192 		if (mon->count < mincount)
4193 			continue;
4194 		if (resall && resall != (resall & mon->flags))
4195 			continue;
4196 		if (resany && !(resany & mon->flags))
4197 			continue;
4198 		if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
4199 		    maxlstint)
4200 			continue;
4201 		if (lcladr != NULL && mon->lcladr != lcladr)
4202 			continue;
4203 
4204 		send_mru_entry(mon, count);
4205 		if (!count)
4206 			send_random_tag_value(0);
4207 		count++;
4208 		prior_mon = mon;
4209 	}
4210 
4211 	/*
4212 	 * If this batch completes the MRU list, say so explicitly with
4213 	 * a now= l_fp timestamp.
4214 	 */
4215 	if (NULL == mon) {
4216 		if (count > 1)
4217 			send_random_tag_value(count - 1);
4218 		ctl_putts("now", &now);
4219 		/* if any entries were returned confirm the last */
4220 		if (prior_mon != NULL)
4221 			ctl_putts("last.newest", &prior_mon->last);
4222 	}
4223 	ctl_flushpkt(0);
4224 }
4225 
4226 
4227 /*
4228  * Send a ifstats entry in response to a "ntpq -c ifstats" request.
4229  *
4230  * To keep clients honest about not depending on the order of values,
4231  * and thereby avoid being locked into ugly workarounds to maintain
4232  * backward compatibility later as new fields are added to the response,
4233  * the order is random.
4234  */
4235 static void
4236 send_ifstats_entry(
4237 	endpt *	la,
4238 	u_int	ifnum
4239 	)
4240 {
4241 	const char addr_fmtu[] =	"addr.%u";
4242 	const char bcast_fmt[] =	"bcast.%u";
4243 	const char en_fmt[] =		"en.%u";	/* enabled */
4244 	const char name_fmt[] =		"name.%u";
4245 	const char flags_fmt[] =	"flags.%u";
4246 	const char tl_fmt[] =		"tl.%u";	/* ttl */
4247 	const char mc_fmt[] =		"mc.%u";	/* mcast count */
4248 	const char rx_fmt[] =		"rx.%u";
4249 	const char tx_fmt[] =		"tx.%u";
4250 	const char txerr_fmt[] =	"txerr.%u";
4251 	const char pc_fmt[] =		"pc.%u";	/* peer count */
4252 	const char up_fmt[] =		"up.%u";	/* uptime */
4253 	char	tag[32];
4254 	u_char	sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4255 	int	noisebits;
4256 	u_int32 noise;
4257 	u_int	which;
4258 	u_int	remaining;
4259 	const char *pch;
4260 
4261 	remaining = COUNTOF(sent);
4262 	ZERO(sent);
4263 	noise = 0;
4264 	noisebits = 0;
4265 	while (remaining > 0) {
4266 		if (noisebits < 4) {
4267 			noise = rand() ^ (rand() << 16);
4268 			noisebits = 31;
4269 		}
4270 		which = (noise & 0xf) % COUNTOF(sent);
4271 		noise >>= 4;
4272 		noisebits -= 4;
4273 
4274 		while (sent[which])
4275 			which = (which + 1) % COUNTOF(sent);
4276 
4277 		switch (which) {
4278 
4279 		case 0:
4280 			snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4281 			pch = sptoa(&la->sin);
4282 			ctl_putunqstr(tag, pch, strlen(pch));
4283 			break;
4284 
4285 		case 1:
4286 			snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4287 			if (INT_BCASTOPEN & la->flags)
4288 				pch = sptoa(&la->bcast);
4289 			else
4290 				pch = "";
4291 			ctl_putunqstr(tag, pch, strlen(pch));
4292 			break;
4293 
4294 		case 2:
4295 			snprintf(tag, sizeof(tag), en_fmt, ifnum);
4296 			ctl_putint(tag, !la->ignore_packets);
4297 			break;
4298 
4299 		case 3:
4300 			snprintf(tag, sizeof(tag), name_fmt, ifnum);
4301 			ctl_putstr(tag, la->name, strlen(la->name));
4302 			break;
4303 
4304 		case 4:
4305 			snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4306 			ctl_puthex(tag, (u_int)la->flags);
4307 			break;
4308 
4309 		case 5:
4310 			snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4311 			ctl_putint(tag, la->last_ttl);
4312 			break;
4313 
4314 		case 6:
4315 			snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4316 			ctl_putint(tag, la->num_mcast);
4317 			break;
4318 
4319 		case 7:
4320 			snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4321 			ctl_putint(tag, la->received);
4322 			break;
4323 
4324 		case 8:
4325 			snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4326 			ctl_putint(tag, la->sent);
4327 			break;
4328 
4329 		case 9:
4330 			snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4331 			ctl_putint(tag, la->notsent);
4332 			break;
4333 
4334 		case 10:
4335 			snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4336 			ctl_putuint(tag, la->peercnt);
4337 			break;
4338 
4339 		case 11:
4340 			snprintf(tag, sizeof(tag), up_fmt, ifnum);
4341 			ctl_putuint(tag, current_time - la->starttime);
4342 			break;
4343 		}
4344 		sent[which] = TRUE;
4345 		remaining--;
4346 	}
4347 	send_random_tag_value((int)ifnum);
4348 }
4349 
4350 
4351 /*
4352  * read_ifstats - send statistics for each local address, exposed by
4353  *		  ntpq -c ifstats
4354  */
4355 static void
4356 read_ifstats(
4357 	struct recvbuf *	rbufp
4358 	)
4359 {
4360 	u_int	ifidx;
4361 	endpt *	la;
4362 
4363 	/*
4364 	 * loop over [0..sys_ifnum] searching ep_list for each
4365 	 * ifnum in turn.
4366 	 */
4367 	for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4368 		for (la = ep_list; la != NULL; la = la->elink)
4369 			if (ifidx == la->ifnum)
4370 				break;
4371 		if (NULL == la)
4372 			continue;
4373 		/* return stats for one local address */
4374 		send_ifstats_entry(la, ifidx);
4375 	}
4376 	ctl_flushpkt(0);
4377 }
4378 
4379 static void
4380 sockaddrs_from_restrict_u(
4381 	sockaddr_u *	psaA,
4382 	sockaddr_u *	psaM,
4383 	restrict_u *	pres,
4384 	int		ipv6
4385 	)
4386 {
4387 	ZERO(*psaA);
4388 	ZERO(*psaM);
4389 	if (!ipv6) {
4390 		psaA->sa.sa_family = AF_INET;
4391 		psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4392 		psaM->sa.sa_family = AF_INET;
4393 		psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4394 	} else {
4395 		psaA->sa.sa_family = AF_INET6;
4396 		memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4397 		       sizeof(psaA->sa6.sin6_addr));
4398 		psaM->sa.sa_family = AF_INET6;
4399 		memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4400 		       sizeof(psaA->sa6.sin6_addr));
4401 	}
4402 }
4403 
4404 
4405 /*
4406  * Send a restrict entry in response to a "ntpq -c reslist" request.
4407  *
4408  * To keep clients honest about not depending on the order of values,
4409  * and thereby avoid being locked into ugly workarounds to maintain
4410  * backward compatibility later as new fields are added to the response,
4411  * the order is random.
4412  */
4413 static void
4414 send_restrict_entry(
4415 	restrict_u *	pres,
4416 	int		ipv6,
4417 	u_int		idx
4418 	)
4419 {
4420 	const char addr_fmtu[] =	"addr.%u";
4421 	const char mask_fmtu[] =	"mask.%u";
4422 	const char hits_fmt[] =		"hits.%u";
4423 	const char flags_fmt[] =	"flags.%u";
4424 	char		tag[32];
4425 	u_char		sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4426 	int		noisebits;
4427 	u_int32		noise;
4428 	u_int		which;
4429 	u_int		remaining;
4430 	sockaddr_u	addr;
4431 	sockaddr_u	mask;
4432 	const char *	pch;
4433 	char *		buf;
4434 	const char *	match_str;
4435 	const char *	access_str;
4436 
4437 	sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4438 	remaining = COUNTOF(sent);
4439 	ZERO(sent);
4440 	noise = 0;
4441 	noisebits = 0;
4442 	while (remaining > 0) {
4443 		if (noisebits < 2) {
4444 			noise = rand() ^ (rand() << 16);
4445 			noisebits = 31;
4446 		}
4447 		which = (noise & 0x3) % COUNTOF(sent);
4448 		noise >>= 2;
4449 		noisebits -= 2;
4450 
4451 		while (sent[which])
4452 			which = (which + 1) % COUNTOF(sent);
4453 
4454 		/* XXX: Numbers?  Really? */
4455 		switch (which) {
4456 
4457 		case 0:
4458 			snprintf(tag, sizeof(tag), addr_fmtu, idx);
4459 			pch = stoa(&addr);
4460 			ctl_putunqstr(tag, pch, strlen(pch));
4461 			break;
4462 
4463 		case 1:
4464 			snprintf(tag, sizeof(tag), mask_fmtu, idx);
4465 			pch = stoa(&mask);
4466 			ctl_putunqstr(tag, pch, strlen(pch));
4467 			break;
4468 
4469 		case 2:
4470 			snprintf(tag, sizeof(tag), hits_fmt, idx);
4471 			ctl_putuint(tag, pres->count);
4472 			break;
4473 
4474 		case 3:
4475 			snprintf(tag, sizeof(tag), flags_fmt, idx);
4476 			match_str = res_match_flags(pres->mflags);
4477 			access_str = res_access_flags(pres->rflags);
4478 			if ('\0' == match_str[0]) {
4479 				pch = access_str;
4480 			} else {
4481 				LIB_GETBUF(buf);
4482 				snprintf(buf, LIB_BUFLENGTH, "%s %s",
4483 					 match_str, access_str);
4484 				pch = buf;
4485 			}
4486 			ctl_putunqstr(tag, pch, strlen(pch));
4487 			break;
4488 		}
4489 		sent[which] = TRUE;
4490 		remaining--;
4491 	}
4492 	send_random_tag_value((int)idx);
4493 }
4494 
4495 
4496 static void
4497 send_restrict_list(
4498 	restrict_u *	pres,
4499 	int		ipv6,
4500 	u_int *		pidx
4501 	)
4502 {
4503 	for ( ; pres != NULL; pres = pres->link) {
4504 		send_restrict_entry(pres, ipv6, *pidx);
4505 		(*pidx)++;
4506 	}
4507 }
4508 
4509 
4510 /*
4511  * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4512  */
4513 static void
4514 read_addr_restrictions(
4515 	struct recvbuf *	rbufp
4516 )
4517 {
4518 	u_int idx;
4519 
4520 	idx = 0;
4521 	send_restrict_list(restrictlist4, FALSE, &idx);
4522 	send_restrict_list(restrictlist6, TRUE, &idx);
4523 	ctl_flushpkt(0);
4524 }
4525 
4526 
4527 /*
4528  * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4529  */
4530 static void
4531 read_ordlist(
4532 	struct recvbuf *	rbufp,
4533 	int			restrict_mask
4534 	)
4535 {
4536 	const char ifstats_s[] = "ifstats";
4537 	const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4538 	const char addr_rst_s[] = "addr_restrictions";
4539 	const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4540 	struct ntp_control *	cpkt;
4541 	u_short			qdata_octets;
4542 
4543 	/*
4544 	 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4545 	 * used only for ntpq -c ifstats.  With the addition of reslist
4546 	 * the same opcode was generalized to retrieve ordered lists
4547 	 * which require authentication.  The request data is empty or
4548 	 * contains "ifstats" (not null terminated) to retrieve local
4549 	 * addresses and associated stats.  It is "addr_restrictions"
4550 	 * to retrieve the IPv4 then IPv6 remote address restrictions,
4551 	 * which are access control lists.  Other request data return
4552 	 * CERR_UNKNOWNVAR.
4553 	 */
4554 	cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4555 	qdata_octets = ntohs(cpkt->count);
4556 	if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4557 	    !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4558 		read_ifstats(rbufp);
4559 		return;
4560 	}
4561 	if (a_r_chars == qdata_octets &&
4562 	    !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4563 		read_addr_restrictions(rbufp);
4564 		return;
4565 	}
4566 	ctl_error(CERR_UNKNOWNVAR);
4567 }
4568 
4569 
4570 /*
4571  * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4572  */
4573 static void req_nonce(
4574 	struct recvbuf *	rbufp,
4575 	int			restrict_mask
4576 	)
4577 {
4578 	char	buf[64];
4579 
4580 	generate_nonce(rbufp, buf, sizeof(buf));
4581 	ctl_putunqstr("nonce", buf, strlen(buf));
4582 	ctl_flushpkt(0);
4583 }
4584 
4585 
4586 /*
4587  * read_clockstatus - return clock radio status
4588  */
4589 /*ARGSUSED*/
4590 static void
4591 read_clockstatus(
4592 	struct recvbuf *rbufp,
4593 	int restrict_mask
4594 	)
4595 {
4596 #ifndef REFCLOCK
4597 	/*
4598 	 * If no refclock support, no data to return
4599 	 */
4600 	ctl_error(CERR_BADASSOC);
4601 #else
4602 	const struct ctl_var *	v;
4603 	int			i;
4604 	struct peer *		peer;
4605 	char *			valuep;
4606 	u_char *		wants;
4607 	size_t			wants_alloc;
4608 	int			gotvar;
4609 	const u_char *		cc;
4610 	struct ctl_var *	kv;
4611 	struct refclockstat	cs;
4612 
4613 	if (res_associd != 0) {
4614 		peer = findpeerbyassoc(res_associd);
4615 	} else {
4616 		/*
4617 		 * Find a clock for this jerk.	If the system peer
4618 		 * is a clock use it, else search peer_list for one.
4619 		 */
4620 		if (sys_peer != NULL && (FLAG_REFCLOCK &
4621 		    sys_peer->flags))
4622 			peer = sys_peer;
4623 		else
4624 			for (peer = peer_list;
4625 			     peer != NULL;
4626 			     peer = peer->p_link)
4627 				if (FLAG_REFCLOCK & peer->flags)
4628 					break;
4629 	}
4630 	if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4631 		ctl_error(CERR_BADASSOC);
4632 		return;
4633 	}
4634 	/*
4635 	 * If we got here we have a peer which is a clock. Get his
4636 	 * status.
4637 	 */
4638 	cs.kv_list = NULL;
4639 	refclock_control(&peer->srcadr, NULL, &cs);
4640 	kv = cs.kv_list;
4641 	/*
4642 	 * Look for variables in the packet.
4643 	 */
4644 	rpkt.status = htons(ctlclkstatus(&cs));
4645 	wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4646 	wants = emalloc_zero(wants_alloc);
4647 	gotvar = FALSE;
4648 	while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4649 		if (!(EOV & v->flags)) {
4650 			wants[v->code] = TRUE;
4651 			gotvar = TRUE;
4652 		} else {
4653 			v = ctl_getitem(kv, &valuep);
4654 			if (NULL == v) {
4655 				ctl_error(CERR_BADVALUE);
4656 				free(wants);
4657 				free_varlist(cs.kv_list);
4658 				return;
4659 			}
4660 			if (EOV & v->flags) {
4661 				ctl_error(CERR_UNKNOWNVAR);
4662 				free(wants);
4663 				free_varlist(cs.kv_list);
4664 				return;
4665 			}
4666 			wants[CC_MAXCODE + 1 + v->code] = TRUE;
4667 			gotvar = TRUE;
4668 		}
4669 	}
4670 
4671 	if (gotvar) {
4672 		for (i = 1; i <= CC_MAXCODE; i++)
4673 			if (wants[i])
4674 				ctl_putclock(i, &cs, TRUE);
4675 		if (kv != NULL)
4676 			for (i = 0; !(EOV & kv[i].flags); i++)
4677 				if (wants[i + CC_MAXCODE + 1])
4678 					ctl_putdata(kv[i].text,
4679 						    strlen(kv[i].text),
4680 						    FALSE);
4681 	} else {
4682 		for (cc = def_clock_var; *cc != 0; cc++)
4683 			ctl_putclock((int)*cc, &cs, FALSE);
4684 		for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4685 			if (DEF & kv->flags)
4686 				ctl_putdata(kv->text, strlen(kv->text),
4687 					    FALSE);
4688 	}
4689 
4690 	free(wants);
4691 	free_varlist(cs.kv_list);
4692 
4693 	ctl_flushpkt(0);
4694 #endif
4695 }
4696 
4697 
4698 /*
4699  * write_clockstatus - we don't do this
4700  */
4701 /*ARGSUSED*/
4702 static void
4703 write_clockstatus(
4704 	struct recvbuf *rbufp,
4705 	int restrict_mask
4706 	)
4707 {
4708 	ctl_error(CERR_PERMISSION);
4709 }
4710 
4711 /*
4712  * Trap support from here on down. We send async trap messages when the
4713  * upper levels report trouble. Traps can by set either by control
4714  * messages or by configuration.
4715  */
4716 /*
4717  * set_trap - set a trap in response to a control message
4718  */
4719 static void
4720 set_trap(
4721 	struct recvbuf *rbufp,
4722 	int restrict_mask
4723 	)
4724 {
4725 	int traptype;
4726 
4727 	/*
4728 	 * See if this guy is allowed
4729 	 */
4730 	if (restrict_mask & RES_NOTRAP) {
4731 		ctl_error(CERR_PERMISSION);
4732 		return;
4733 	}
4734 
4735 	/*
4736 	 * Determine his allowed trap type.
4737 	 */
4738 	traptype = TRAP_TYPE_PRIO;
4739 	if (restrict_mask & RES_LPTRAP)
4740 		traptype = TRAP_TYPE_NONPRIO;
4741 
4742 	/*
4743 	 * Call ctlsettrap() to do the work.  Return
4744 	 * an error if it can't assign the trap.
4745 	 */
4746 	if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4747 			(int)res_version))
4748 		ctl_error(CERR_NORESOURCE);
4749 	ctl_flushpkt(0);
4750 }
4751 
4752 
4753 /*
4754  * unset_trap - unset a trap in response to a control message
4755  */
4756 static void
4757 unset_trap(
4758 	struct recvbuf *rbufp,
4759 	int restrict_mask
4760 	)
4761 {
4762 	int traptype;
4763 
4764 	/*
4765 	 * We don't prevent anyone from removing his own trap unless the
4766 	 * trap is configured. Note we also must be aware of the
4767 	 * possibility that restriction flags were changed since this
4768 	 * guy last set his trap. Set the trap type based on this.
4769 	 */
4770 	traptype = TRAP_TYPE_PRIO;
4771 	if (restrict_mask & RES_LPTRAP)
4772 		traptype = TRAP_TYPE_NONPRIO;
4773 
4774 	/*
4775 	 * Call ctlclrtrap() to clear this out.
4776 	 */
4777 	if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4778 		ctl_error(CERR_BADASSOC);
4779 	ctl_flushpkt(0);
4780 }
4781 
4782 
4783 /*
4784  * ctlsettrap - called to set a trap
4785  */
4786 int
4787 ctlsettrap(
4788 	sockaddr_u *raddr,
4789 	struct interface *linter,
4790 	int traptype,
4791 	int version
4792 	)
4793 {
4794 	size_t n;
4795 	struct ctl_trap *tp;
4796 	struct ctl_trap *tptouse;
4797 
4798 	/*
4799 	 * See if we can find this trap.  If so, we only need update
4800 	 * the flags and the time.
4801 	 */
4802 	if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4803 		switch (traptype) {
4804 
4805 		case TRAP_TYPE_CONFIG:
4806 			tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4807 			break;
4808 
4809 		case TRAP_TYPE_PRIO:
4810 			if (tp->tr_flags & TRAP_CONFIGURED)
4811 				return (1); /* don't change anything */
4812 			tp->tr_flags = TRAP_INUSE;
4813 			break;
4814 
4815 		case TRAP_TYPE_NONPRIO:
4816 			if (tp->tr_flags & TRAP_CONFIGURED)
4817 				return (1); /* don't change anything */
4818 			tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4819 			break;
4820 		}
4821 		tp->tr_settime = current_time;
4822 		tp->tr_resets++;
4823 		return (1);
4824 	}
4825 
4826 	/*
4827 	 * First we heard of this guy.	Try to find a trap structure
4828 	 * for him to use, clearing out lesser priority guys if we
4829 	 * have to. Clear out anyone who's expired while we're at it.
4830 	 */
4831 	tptouse = NULL;
4832 	for (n = 0; n < COUNTOF(ctl_traps); n++) {
4833 		tp = &ctl_traps[n];
4834 		if ((TRAP_INUSE & tp->tr_flags) &&
4835 		    !(TRAP_CONFIGURED & tp->tr_flags) &&
4836 		    ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4837 			tp->tr_flags = 0;
4838 			num_ctl_traps--;
4839 		}
4840 		if (!(TRAP_INUSE & tp->tr_flags)) {
4841 			tptouse = tp;
4842 		} else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4843 			switch (traptype) {
4844 
4845 			case TRAP_TYPE_CONFIG:
4846 				if (tptouse == NULL) {
4847 					tptouse = tp;
4848 					break;
4849 				}
4850 				if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4851 				    !(TRAP_NONPRIO & tp->tr_flags))
4852 					break;
4853 
4854 				if (!(TRAP_NONPRIO & tptouse->tr_flags)
4855 				    && (TRAP_NONPRIO & tp->tr_flags)) {
4856 					tptouse = tp;
4857 					break;
4858 				}
4859 				if (tptouse->tr_origtime <
4860 				    tp->tr_origtime)
4861 					tptouse = tp;
4862 				break;
4863 
4864 			case TRAP_TYPE_PRIO:
4865 				if ( TRAP_NONPRIO & tp->tr_flags) {
4866 					if (tptouse == NULL ||
4867 					    ((TRAP_INUSE &
4868 					      tptouse->tr_flags) &&
4869 					     tptouse->tr_origtime <
4870 					     tp->tr_origtime))
4871 						tptouse = tp;
4872 				}
4873 				break;
4874 
4875 			case TRAP_TYPE_NONPRIO:
4876 				break;
4877 			}
4878 		}
4879 	}
4880 
4881 	/*
4882 	 * If we don't have room for him return an error.
4883 	 */
4884 	if (tptouse == NULL)
4885 		return (0);
4886 
4887 	/*
4888 	 * Set up this structure for him.
4889 	 */
4890 	tptouse->tr_settime = tptouse->tr_origtime = current_time;
4891 	tptouse->tr_count = tptouse->tr_resets = 0;
4892 	tptouse->tr_sequence = 1;
4893 	tptouse->tr_addr = *raddr;
4894 	tptouse->tr_localaddr = linter;
4895 	tptouse->tr_version = (u_char) version;
4896 	tptouse->tr_flags = TRAP_INUSE;
4897 	if (traptype == TRAP_TYPE_CONFIG)
4898 		tptouse->tr_flags |= TRAP_CONFIGURED;
4899 	else if (traptype == TRAP_TYPE_NONPRIO)
4900 		tptouse->tr_flags |= TRAP_NONPRIO;
4901 	num_ctl_traps++;
4902 	return (1);
4903 }
4904 
4905 
4906 /*
4907  * ctlclrtrap - called to clear a trap
4908  */
4909 int
4910 ctlclrtrap(
4911 	sockaddr_u *raddr,
4912 	struct interface *linter,
4913 	int traptype
4914 	)
4915 {
4916 	register struct ctl_trap *tp;
4917 
4918 	if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4919 		return (0);
4920 
4921 	if (tp->tr_flags & TRAP_CONFIGURED
4922 	    && traptype != TRAP_TYPE_CONFIG)
4923 		return (0);
4924 
4925 	tp->tr_flags = 0;
4926 	num_ctl_traps--;
4927 	return (1);
4928 }
4929 
4930 
4931 /*
4932  * ctlfindtrap - find a trap given the remote and local addresses
4933  */
4934 static struct ctl_trap *
4935 ctlfindtrap(
4936 	sockaddr_u *raddr,
4937 	struct interface *linter
4938 	)
4939 {
4940 	size_t	n;
4941 
4942 	for (n = 0; n < COUNTOF(ctl_traps); n++)
4943 		if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4944 		    && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4945 		    && (linter == ctl_traps[n].tr_localaddr))
4946 			return &ctl_traps[n];
4947 
4948 	return NULL;
4949 }
4950 
4951 
4952 /*
4953  * report_event - report an event to the trappers
4954  */
4955 void
4956 report_event(
4957 	int	err,		/* error code */
4958 	struct peer *peer,	/* peer structure pointer */
4959 	const char *str		/* protostats string */
4960 	)
4961 {
4962 	char	statstr[NTP_MAXSTRLEN];
4963 	int	i;
4964 	size_t	len;
4965 
4966 	/*
4967 	 * Report the error to the protostats file, system log and
4968 	 * trappers.
4969 	 */
4970 	if (peer == NULL) {
4971 
4972 		/*
4973 		 * Discard a system report if the number of reports of
4974 		 * the same type exceeds the maximum.
4975 		 */
4976 		if (ctl_sys_last_event != (u_char)err)
4977 			ctl_sys_num_events= 0;
4978 		if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4979 			return;
4980 
4981 		ctl_sys_last_event = (u_char)err;
4982 		ctl_sys_num_events++;
4983 		snprintf(statstr, sizeof(statstr),
4984 		    "0.0.0.0 %04x %02x %s",
4985 		    ctlsysstatus(), err, eventstr(err));
4986 		if (str != NULL) {
4987 			len = strlen(statstr);
4988 			snprintf(statstr + len, sizeof(statstr) - len,
4989 			    " %s", str);
4990 		}
4991 		NLOG(NLOG_SYSEVENT)
4992 			msyslog(LOG_INFO, "%s", statstr);
4993 	} else {
4994 
4995 		/*
4996 		 * Discard a peer report if the number of reports of
4997 		 * the same type exceeds the maximum for that peer.
4998 		 */
4999 		const char *	src;
5000 		u_char		errlast;
5001 
5002 		errlast = (u_char)err & ~PEER_EVENT;
5003 		if (peer->last_event != errlast)
5004 			peer->num_events = 0;
5005 		if (peer->num_events >= CTL_PEER_MAXEVENTS)
5006 			return;
5007 
5008 		peer->last_event = errlast;
5009 		peer->num_events++;
5010 		if (ISREFCLOCKADR(&peer->srcadr))
5011 			src = refnumtoa(&peer->srcadr);
5012 		else
5013 			src = stoa(&peer->srcadr);
5014 
5015 		snprintf(statstr, sizeof(statstr),
5016 		    "%s %04x %02x %s", src,
5017 		    ctlpeerstatus(peer), err, eventstr(err));
5018 		if (str != NULL) {
5019 			len = strlen(statstr);
5020 			snprintf(statstr + len, sizeof(statstr) - len,
5021 			    " %s", str);
5022 		}
5023 		NLOG(NLOG_PEEREVENT)
5024 			msyslog(LOG_INFO, "%s", statstr);
5025 	}
5026 	record_proto_stats(statstr);
5027 #if DEBUG
5028 	if (debug)
5029 		printf("event at %lu %s\n", current_time, statstr);
5030 #endif
5031 
5032 	/*
5033 	 * If no trappers, return.
5034 	 */
5035 	if (num_ctl_traps <= 0)
5036 		return;
5037 
5038 	/* [Bug 3119]
5039 	 * Peer Events should be associated with a peer -- hence the
5040 	 * name. But there are instances where this function is called
5041 	 * *without* a valid peer. This happens e.g. with an unsolicited
5042 	 * CryptoNAK, or when a leap second alarm is going off while
5043 	 * currently without a system peer.
5044 	 *
5045 	 * The most sensible approach to this seems to bail out here if
5046 	 * this happens. Avoiding to call this function would also
5047 	 * bypass the log reporting in the first part of this function,
5048 	 * and this is probably not the best of all options.
5049 	 *   -*-perlinger@ntp.org-*-
5050 	 */
5051 	if ((err & PEER_EVENT) && !peer)
5052 		return;
5053 
5054 	/*
5055 	 * Set up the outgoing packet variables
5056 	 */
5057 	res_opcode = CTL_OP_ASYNCMSG;
5058 	res_offset = 0;
5059 	res_async = TRUE;
5060 	res_authenticate = FALSE;
5061 	datapt = rpkt.u.data;
5062 	dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
5063 	if (!(err & PEER_EVENT)) {
5064 		rpkt.associd = 0;
5065 		rpkt.status = htons(ctlsysstatus());
5066 
5067 		/* Include the core system variables and the list. */
5068 		for (i = 1; i <= CS_VARLIST; i++)
5069 			ctl_putsys(i);
5070 	} else if (NULL != peer) { /* paranoia -- skip output */
5071 		rpkt.associd = htons(peer->associd);
5072 		rpkt.status = htons(ctlpeerstatus(peer));
5073 
5074 		/* Dump it all. Later, maybe less. */
5075 		for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
5076 			ctl_putpeer(i, peer);
5077 #	    ifdef REFCLOCK
5078 		/*
5079 		 * for clock exception events: add clock variables to
5080 		 * reflect info on exception
5081 		 */
5082 		if (err == PEVNT_CLOCK) {
5083 			struct refclockstat cs;
5084 			struct ctl_var *kv;
5085 
5086 			cs.kv_list = NULL;
5087 			refclock_control(&peer->srcadr, NULL, &cs);
5088 
5089 			ctl_puthex("refclockstatus",
5090 				   ctlclkstatus(&cs));
5091 
5092 			for (i = 1; i <= CC_MAXCODE; i++)
5093 				ctl_putclock(i, &cs, FALSE);
5094 			for (kv = cs.kv_list;
5095 			     kv != NULL && !(EOV & kv->flags);
5096 			     kv++)
5097 				if (DEF & kv->flags)
5098 					ctl_putdata(kv->text,
5099 						    strlen(kv->text),
5100 						    FALSE);
5101 			free_varlist(cs.kv_list);
5102 		}
5103 #	    endif /* REFCLOCK */
5104 	}
5105 
5106 	/*
5107 	 * We're done, return.
5108 	 */
5109 	ctl_flushpkt(0);
5110 }
5111 
5112 
5113 /*
5114  * mprintf_event - printf-style varargs variant of report_event()
5115  */
5116 int
5117 mprintf_event(
5118 	int		evcode,		/* event code */
5119 	struct peer *	p,		/* may be NULL */
5120 	const char *	fmt,		/* msnprintf format */
5121 	...
5122 	)
5123 {
5124 	va_list	ap;
5125 	int	rc;
5126 	char	msg[512];
5127 
5128 	va_start(ap, fmt);
5129 	rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
5130 	va_end(ap);
5131 	report_event(evcode, p, msg);
5132 
5133 	return rc;
5134 }
5135 
5136 
5137 /*
5138  * ctl_clr_stats - clear stat counters
5139  */
5140 void
5141 ctl_clr_stats(void)
5142 {
5143 	ctltimereset = current_time;
5144 	numctlreq = 0;
5145 	numctlbadpkts = 0;
5146 	numctlresponses = 0;
5147 	numctlfrags = 0;
5148 	numctlerrors = 0;
5149 	numctlfrags = 0;
5150 	numctltooshort = 0;
5151 	numctlinputresp = 0;
5152 	numctlinputfrag = 0;
5153 	numctlinputerr = 0;
5154 	numctlbadoffset = 0;
5155 	numctlbadversion = 0;
5156 	numctldatatooshort = 0;
5157 	numctlbadop = 0;
5158 	numasyncmsgs = 0;
5159 }
5160 
5161 static u_short
5162 count_var(
5163 	const struct ctl_var *k
5164 	)
5165 {
5166 	u_int c;
5167 
5168 	if (NULL == k)
5169 		return 0;
5170 
5171 	c = 0;
5172 	while (!(EOV & (k++)->flags))
5173 		c++;
5174 
5175 	ENSURE(c <= USHRT_MAX);
5176 	return (u_short)c;
5177 }
5178 
5179 
5180 char *
5181 add_var(
5182 	struct ctl_var **kv,
5183 	u_long size,
5184 	u_short def
5185 	)
5186 {
5187 	u_short		c;
5188 	struct ctl_var *k;
5189 	char *		buf;
5190 
5191 	c = count_var(*kv);
5192 	*kv  = erealloc(*kv, (c + 2) * sizeof(**kv));
5193 	k = *kv;
5194 	buf = emalloc(size);
5195 	k[c].code  = c;
5196 	k[c].text  = buf;
5197 	k[c].flags = def;
5198 	k[c + 1].code  = 0;
5199 	k[c + 1].text  = NULL;
5200 	k[c + 1].flags = EOV;
5201 
5202 	return buf;
5203 }
5204 
5205 
5206 void
5207 set_var(
5208 	struct ctl_var **kv,
5209 	const char *data,
5210 	u_long size,
5211 	u_short def
5212 	)
5213 {
5214 	struct ctl_var *k;
5215 	const char *s;
5216 	const char *t;
5217 	char *td;
5218 
5219 	if (NULL == data || !size)
5220 		return;
5221 
5222 	k = *kv;
5223 	if (k != NULL) {
5224 		while (!(EOV & k->flags)) {
5225 			if (NULL == k->text)	{
5226 				td = emalloc(size);
5227 				memcpy(td, data, size);
5228 				k->text = td;
5229 				k->flags = def;
5230 				return;
5231 			} else {
5232 				s = data;
5233 				t = k->text;
5234 				while (*t != '=' && *s == *t) {
5235 					s++;
5236 					t++;
5237 				}
5238 				if (*s == *t && ((*t == '=') || !*t)) {
5239 					td = erealloc((void *)(intptr_t)k->text, size);
5240 					memcpy(td, data, size);
5241 					k->text = td;
5242 					k->flags = def;
5243 					return;
5244 				}
5245 			}
5246 			k++;
5247 		}
5248 	}
5249 	td = add_var(kv, size, def);
5250 	memcpy(td, data, size);
5251 }
5252 
5253 
5254 void
5255 set_sys_var(
5256 	const char *data,
5257 	u_long size,
5258 	u_short def
5259 	)
5260 {
5261 	set_var(&ext_sys_var, data, size, def);
5262 }
5263 
5264 
5265 /*
5266  * get_ext_sys_var() retrieves the value of a user-defined variable or
5267  * NULL if the variable has not been setvar'd.
5268  */
5269 const char *
5270 get_ext_sys_var(const char *tag)
5271 {
5272 	struct ctl_var *	v;
5273 	size_t			c;
5274 	const char *		val;
5275 
5276 	val = NULL;
5277 	c = strlen(tag);
5278 	for (v = ext_sys_var; !(EOV & v->flags); v++) {
5279 		if (NULL != v->text && !memcmp(tag, v->text, c)) {
5280 			if ('=' == v->text[c]) {
5281 				val = v->text + c + 1;
5282 				break;
5283 			} else if ('\0' == v->text[c]) {
5284 				val = "";
5285 				break;
5286 			}
5287 		}
5288 	}
5289 
5290 	return val;
5291 }
5292 
5293 
5294 void
5295 free_varlist(
5296 	struct ctl_var *kv
5297 	)
5298 {
5299 	struct ctl_var *k;
5300 	if (kv) {
5301 		for (k = kv; !(k->flags & EOV); k++)
5302 			free((void *)(intptr_t)k->text);
5303 		free((void *)kv);
5304 	}
5305 }
5306