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