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