2 * ntp_control.c - respond to mode 6 control messages and send async
3 * traps. Provides service to ntpq and others.
7 * $FreeBSD: stable/10/contrib/ntp/ntpd/ntp_control.c 276072 2014-12-22 19:07:16Z delphij $
18 #ifdef HAVE_NETINET_IN_H
19 # include <netinet/in.h>
21 #include <arpa/inet.h>
25 #include "ntp_refclock.h"
26 #include "ntp_control.h"
27 #include "ntp_unixtime.h"
28 #include "ntp_stdlib.h"
29 #include "ntp_config.h"
30 #include "ntp_crypto.h"
31 #include "ntp_assert.h"
32 #include "ntp_leapsec.h"
33 #include "ntp_md5.h" /* provides OpenSSL digest API */
34 #include "lib_strbuf.h"
36 # include "ntp_syscall.h"
39 extern size_t remoteconfig_cmdlength( const char *src_buf, const char *src_end );
42 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
46 * Structure to hold request procedure information
50 short control_code; /* defined request code */
51 #define NO_REQUEST (-1)
52 u_short flags; /* flags word */
53 /* Only one flag. Authentication required or not. */
56 void (*handler) (struct recvbuf *, int); /* handle request */
61 * Request processing routines
63 static void ctl_error (u_char);
65 static u_short ctlclkstatus (struct refclockstat *);
67 static void ctl_flushpkt (u_char);
68 static void ctl_putdata (const char *, unsigned int, int);
69 static void ctl_putstr (const char *, const char *, size_t);
70 static void ctl_putdblf (const char *, int, int, double);
71 #define ctl_putdbl(tag, d) ctl_putdblf(tag, 1, 3, d)
72 #define ctl_putdbl6(tag, d) ctl_putdblf(tag, 1, 6, d)
73 #define ctl_putsfp(tag, sfp) ctl_putdblf(tag, 0, -1, \
75 static void ctl_putuint (const char *, u_long);
76 static void ctl_puthex (const char *, u_long);
77 static void ctl_putint (const char *, long);
78 static void ctl_putts (const char *, l_fp *);
79 static void ctl_putadr (const char *, u_int32,
81 static void ctl_putrefid (const char *, u_int32);
82 static void ctl_putarray (const char *, double *, int);
83 static void ctl_putsys (int);
84 static void ctl_putpeer (int, struct peer *);
85 static void ctl_putfs (const char *, tstamp_t);
87 static void ctl_putclock (int, struct refclockstat *, int);
89 static const struct ctl_var *ctl_getitem(const struct ctl_var *,
91 static u_short count_var (const struct ctl_var *);
92 static void control_unspec (struct recvbuf *, int);
93 static void read_status (struct recvbuf *, int);
94 static void read_sysvars (void);
95 static void read_peervars (void);
96 static void read_variables (struct recvbuf *, int);
97 static void write_variables (struct recvbuf *, int);
98 static void read_clockstatus(struct recvbuf *, int);
99 static void write_clockstatus(struct recvbuf *, int);
100 static void set_trap (struct recvbuf *, int);
101 static void save_config (struct recvbuf *, int);
102 static void configure (struct recvbuf *, int);
103 static void send_mru_entry (mon_entry *, int);
104 static void send_random_tag_value(int);
105 static void read_mru_list (struct recvbuf *, int);
106 static void send_ifstats_entry(endpt *, u_int);
107 static void read_ifstats (struct recvbuf *);
108 static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *,
110 static void send_restrict_entry(restrict_u *, int, u_int);
111 static void send_restrict_list(restrict_u *, int, u_int *);
112 static void read_addr_restrictions(struct recvbuf *);
113 static void read_ordlist (struct recvbuf *, int);
114 static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32);
115 static void generate_nonce (struct recvbuf *, char *, size_t);
116 static int validate_nonce (const char *, struct recvbuf *);
117 static void req_nonce (struct recvbuf *, int);
118 static void unset_trap (struct recvbuf *, int);
119 static struct ctl_trap *ctlfindtrap(sockaddr_u *,
122 static const struct ctl_proc control_codes[] = {
123 { CTL_OP_UNSPEC, NOAUTH, control_unspec },
124 { CTL_OP_READSTAT, NOAUTH, read_status },
125 { CTL_OP_READVAR, NOAUTH, read_variables },
126 { CTL_OP_WRITEVAR, AUTH, write_variables },
127 { CTL_OP_READCLOCK, NOAUTH, read_clockstatus },
128 { CTL_OP_WRITECLOCK, NOAUTH, write_clockstatus },
129 { CTL_OP_SETTRAP, NOAUTH, set_trap },
130 { CTL_OP_CONFIGURE, AUTH, configure },
131 { CTL_OP_SAVECONFIG, AUTH, save_config },
132 { CTL_OP_READ_MRU, NOAUTH, read_mru_list },
133 { CTL_OP_READ_ORDLIST_A, AUTH, read_ordlist },
134 { CTL_OP_REQ_NONCE, NOAUTH, req_nonce },
135 { CTL_OP_UNSETTRAP, NOAUTH, unset_trap },
136 { NO_REQUEST, 0, NULL }
140 * System variables we understand
144 #define CS_PRECISION 3
145 #define CS_ROOTDELAY 4
146 #define CS_ROOTDISPERSION 5
156 #define CS_PROCESSOR 15
158 #define CS_VERSION 17
160 #define CS_VARLIST 19
162 #define CS_LEAPTAB 21
163 #define CS_LEAPEND 22
165 #define CS_MRU_ENABLED 24
166 #define CS_MRU_DEPTH 25
167 #define CS_MRU_DEEPEST 26
168 #define CS_MRU_MINDEPTH 27
169 #define CS_MRU_MAXAGE 28
170 #define CS_MRU_MAXDEPTH 29
171 #define CS_MRU_MEM 30
172 #define CS_MRU_MAXMEM 31
173 #define CS_SS_UPTIME 32
174 #define CS_SS_RESET 33
175 #define CS_SS_RECEIVED 34
176 #define CS_SS_THISVER 35
177 #define CS_SS_OLDVER 36
178 #define CS_SS_BADFORMAT 37
179 #define CS_SS_BADAUTH 38
180 #define CS_SS_DECLINED 39
181 #define CS_SS_RESTRICTED 40
182 #define CS_SS_LIMITED 41
183 #define CS_SS_KODSENT 42
184 #define CS_SS_PROCESSED 43
185 #define CS_PEERADR 44
186 #define CS_PEERMODE 45
187 #define CS_BCASTDELAY 46
188 #define CS_AUTHDELAY 47
189 #define CS_AUTHKEYS 48
190 #define CS_AUTHFREEK 49
191 #define CS_AUTHKLOOKUPS 50
192 #define CS_AUTHKNOTFOUND 51
193 #define CS_AUTHKUNCACHED 52
194 #define CS_AUTHKEXPIRED 53
195 #define CS_AUTHENCRYPTS 54
196 #define CS_AUTHDECRYPTS 55
197 #define CS_AUTHRESET 56
198 #define CS_K_OFFSET 57
200 #define CS_K_MAXERR 59
201 #define CS_K_ESTERR 60
202 #define CS_K_STFLAGS 61
203 #define CS_K_TIMECONST 62
204 #define CS_K_PRECISION 63
205 #define CS_K_FREQTOL 64
206 #define CS_K_PPS_FREQ 65
207 #define CS_K_PPS_STABIL 66
208 #define CS_K_PPS_JITTER 67
209 #define CS_K_PPS_CALIBDUR 68
210 #define CS_K_PPS_CALIBS 69
211 #define CS_K_PPS_CALIBERRS 70
212 #define CS_K_PPS_JITEXC 71
213 #define CS_K_PPS_STBEXC 72
214 #define CS_KERN_FIRST CS_K_OFFSET
215 #define CS_KERN_LAST CS_K_PPS_STBEXC
216 #define CS_IOSTATS_RESET 73
217 #define CS_TOTAL_RBUF 74
218 #define CS_FREE_RBUF 75
219 #define CS_USED_RBUF 76
220 #define CS_RBUF_LOWATER 77
221 #define CS_IO_DROPPED 78
222 #define CS_IO_IGNORED 79
223 #define CS_IO_RECEIVED 80
224 #define CS_IO_SENT 81
225 #define CS_IO_SENDFAILED 82
226 #define CS_IO_WAKEUPS 83
227 #define CS_IO_GOODWAKEUPS 84
228 #define CS_TIMERSTATS_RESET 85
229 #define CS_TIMER_OVERRUNS 86
230 #define CS_TIMER_XMTS 87
232 #define CS_WANDER_THRESH 89
233 #define CS_LEAPSMEARINTV 90
234 #define CS_LEAPSMEAROFFS 91
235 #define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS
237 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
238 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
239 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
240 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
241 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
242 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
243 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
244 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
245 #define CS_MAXCODE CS_DIGEST
246 #else /* !AUTOKEY follows */
247 #define CS_MAXCODE CS_MAX_NOAUTOKEY
248 #endif /* !AUTOKEY */
251 * Peer variables we understand
254 #define CP_AUTHENABLE 2
255 #define CP_AUTHENTIC 3
262 #define CP_STRATUM 10
265 #define CP_PRECISION 13
266 #define CP_ROOTDELAY 14
267 #define CP_ROOTDISPERSION 15
269 #define CP_REFTIME 17
274 #define CP_UNREACH 22
279 #define CP_DISPERSION 27
281 #define CP_FILTDELAY 29
282 #define CP_FILTOFFSET 30
284 #define CP_RECEIVED 32
286 #define CP_FILTERROR 34
289 #define CP_VARLIST 37
294 #define CP_SRCHOST 42
295 #define CP_TIMEREC 43
296 #define CP_TIMEREACH 44
297 #define CP_BADAUTH 45
298 #define CP_BOGUSORG 46
300 #define CP_SELDISP 48
301 #define CP_SELBROKEN 49
302 #define CP_CANDIDATE 50
303 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
305 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
306 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
307 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
308 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
309 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
310 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
311 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
312 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
313 #define CP_MAXCODE CP_IDENT
314 #else /* !AUTOKEY follows */
315 #define CP_MAXCODE CP_MAX_NOAUTOKEY
316 #endif /* !AUTOKEY */
319 * Clock variables we understand
322 #define CC_TIMECODE 2
325 #define CC_BADFORMAT 5
327 #define CC_FUDGETIME1 7
328 #define CC_FUDGETIME2 8
329 #define CC_FUDGEVAL1 9
330 #define CC_FUDGEVAL2 10
333 #define CC_VARLIST 13
334 #define CC_MAXCODE CC_VARLIST
337 * System variable values. The array can be indexed by the variable
338 * index to find the textual name.
340 static const struct ctl_var sys_var[] = {
341 { 0, PADDING, "" }, /* 0 */
342 { CS_LEAP, RW, "leap" }, /* 1 */
343 { CS_STRATUM, RO, "stratum" }, /* 2 */
344 { CS_PRECISION, RO, "precision" }, /* 3 */
345 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
346 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
347 { CS_REFID, RO, "refid" }, /* 6 */
348 { CS_REFTIME, RO, "reftime" }, /* 7 */
349 { CS_POLL, RO, "tc" }, /* 8 */
350 { CS_PEERID, RO, "peer" }, /* 9 */
351 { CS_OFFSET, RO, "offset" }, /* 10 */
352 { CS_DRIFT, RO, "frequency" }, /* 11 */
353 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
354 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
355 { CS_CLOCK, RO, "clock" }, /* 14 */
356 { CS_PROCESSOR, RO, "processor" }, /* 15 */
357 { CS_SYSTEM, RO, "system" }, /* 16 */
358 { CS_VERSION, RO, "version" }, /* 17 */
359 { CS_STABIL, RO, "clk_wander" }, /* 18 */
360 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
361 { CS_TAI, RO, "tai" }, /* 20 */
362 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
363 { CS_LEAPEND, RO, "expire" }, /* 22 */
364 { CS_RATE, RO, "mintc" }, /* 23 */
365 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
366 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
367 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
368 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
369 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
370 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
371 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
372 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
373 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
374 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
375 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
376 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
377 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
378 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
379 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
380 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
381 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
382 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
383 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
384 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
385 { CS_PEERADR, RO, "peeradr" }, /* 44 */
386 { CS_PEERMODE, RO, "peermode" }, /* 45 */
387 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 46 */
388 { CS_AUTHDELAY, RO, "authdelay" }, /* 47 */
389 { CS_AUTHKEYS, RO, "authkeys" }, /* 48 */
390 { CS_AUTHFREEK, RO, "authfreek" }, /* 49 */
391 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 50 */
392 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 51 */
393 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 52 */
394 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 53 */
395 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 54 */
396 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 55 */
397 { CS_AUTHRESET, RO, "authreset" }, /* 56 */
398 { CS_K_OFFSET, RO, "koffset" }, /* 57 */
399 { CS_K_FREQ, RO, "kfreq" }, /* 58 */
400 { CS_K_MAXERR, RO, "kmaxerr" }, /* 59 */
401 { CS_K_ESTERR, RO, "kesterr" }, /* 60 */
402 { CS_K_STFLAGS, RO, "kstflags" }, /* 61 */
403 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 62 */
404 { CS_K_PRECISION, RO, "kprecis" }, /* 63 */
405 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 64 */
406 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 65 */
407 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 66 */
408 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 67 */
409 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 68 */
410 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 69 */
411 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 70 */
412 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 71 */
413 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 72 */
414 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 73 */
415 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 74 */
416 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 75 */
417 { CS_USED_RBUF, RO, "used_rbuf" }, /* 76 */
418 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 77 */
419 { CS_IO_DROPPED, RO, "io_dropped" }, /* 78 */
420 { CS_IO_IGNORED, RO, "io_ignored" }, /* 79 */
421 { CS_IO_RECEIVED, RO, "io_received" }, /* 80 */
422 { CS_IO_SENT, RO, "io_sent" }, /* 81 */
423 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 82 */
424 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 83 */
425 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 84 */
426 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 85 */
427 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 86 */
428 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 87 */
429 { CS_FUZZ, RO, "fuzz" }, /* 88 */
430 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 89 */
432 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 90 */
433 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 91 */
434 #endif /* LEAP_SMEAR */
436 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
437 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
438 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
439 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
440 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
441 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
442 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
443 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
445 { 0, EOV, "" } /* 87/95 */
448 static struct ctl_var *ext_sys_var = NULL;
451 * System variables we print by default (in fuzzball order,
454 static const u_char def_sys_var[] = {
495 static const struct ctl_var peer_var[] = {
496 { 0, PADDING, "" }, /* 0 */
497 { CP_CONFIG, RO, "config" }, /* 1 */
498 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
499 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
500 { CP_SRCADR, RO, "srcadr" }, /* 4 */
501 { CP_SRCPORT, RO, "srcport" }, /* 5 */
502 { CP_DSTADR, RO, "dstadr" }, /* 6 */
503 { CP_DSTPORT, RO, "dstport" }, /* 7 */
504 { CP_LEAP, RO, "leap" }, /* 8 */
505 { CP_HMODE, RO, "hmode" }, /* 9 */
506 { CP_STRATUM, RO, "stratum" }, /* 10 */
507 { CP_PPOLL, RO, "ppoll" }, /* 11 */
508 { CP_HPOLL, RO, "hpoll" }, /* 12 */
509 { CP_PRECISION, RO, "precision" }, /* 13 */
510 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
511 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
512 { CP_REFID, RO, "refid" }, /* 16 */
513 { CP_REFTIME, RO, "reftime" }, /* 17 */
514 { CP_ORG, RO, "org" }, /* 18 */
515 { CP_REC, RO, "rec" }, /* 19 */
516 { CP_XMT, RO, "xleave" }, /* 20 */
517 { CP_REACH, RO, "reach" }, /* 21 */
518 { CP_UNREACH, RO, "unreach" }, /* 22 */
519 { CP_TIMER, RO, "timer" }, /* 23 */
520 { CP_DELAY, RO, "delay" }, /* 24 */
521 { CP_OFFSET, RO, "offset" }, /* 25 */
522 { CP_JITTER, RO, "jitter" }, /* 26 */
523 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
524 { CP_KEYID, RO, "keyid" }, /* 28 */
525 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
526 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
527 { CP_PMODE, RO, "pmode" }, /* 31 */
528 { CP_RECEIVED, RO, "received"}, /* 32 */
529 { CP_SENT, RO, "sent" }, /* 33 */
530 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
531 { CP_FLASH, RO, "flash" }, /* 35 */
532 { CP_TTL, RO, "ttl" }, /* 36 */
533 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
534 { CP_IN, RO, "in" }, /* 38 */
535 { CP_OUT, RO, "out" }, /* 39 */
536 { CP_RATE, RO, "headway" }, /* 40 */
537 { CP_BIAS, RO, "bias" }, /* 41 */
538 { CP_SRCHOST, RO, "srchost" }, /* 42 */
539 { CP_TIMEREC, RO, "timerec" }, /* 43 */
540 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
541 { CP_BADAUTH, RO, "badauth" }, /* 45 */
542 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
543 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
544 { CP_SELDISP, RO, "seldisp" }, /* 48 */
545 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
546 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
548 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
549 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
550 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
551 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
552 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
553 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
554 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
555 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
557 { 0, EOV, "" } /* 50/58 */
562 * Peer variables we print by default
564 static const u_char def_peer_var[] = {
613 * Clock variable list
615 static const struct ctl_var clock_var[] = {
616 { 0, PADDING, "" }, /* 0 */
617 { CC_TYPE, RO, "type" }, /* 1 */
618 { CC_TIMECODE, RO, "timecode" }, /* 2 */
619 { CC_POLL, RO, "poll" }, /* 3 */
620 { CC_NOREPLY, RO, "noreply" }, /* 4 */
621 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
622 { CC_BADDATA, RO, "baddata" }, /* 6 */
623 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
624 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
625 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
626 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
627 { CC_FLAGS, RO, "flags" }, /* 11 */
628 { CC_DEVICE, RO, "device" }, /* 12 */
629 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
630 { 0, EOV, "" } /* 14 */
635 * Clock variables printed by default
637 static const u_char def_clock_var[] = {
639 CC_TYPE, /* won't be output if device = known */
655 * MRU string constants shared by send_mru_entry() and read_mru_list().
657 static const char addr_fmt[] = "addr.%d";
658 static const char last_fmt[] = "last.%d";
661 * System and processor definitions.
665 # define STR_SYSTEM "UNIX"
667 # ifndef STR_PROCESSOR
668 # define STR_PROCESSOR "unknown"
671 static const char str_system[] = STR_SYSTEM;
672 static const char str_processor[] = STR_PROCESSOR;
674 # include <sys/utsname.h>
675 static struct utsname utsnamebuf;
676 #endif /* HAVE_UNAME */
679 * Trap structures. We only allow a few of these, and send a copy of
680 * each async message to each live one. Traps time out after an hour, it
681 * is up to the trap receipient to keep resetting it to avoid being
685 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
689 * Type bits, for ctlsettrap() call.
691 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
692 #define TRAP_TYPE_PRIO 1 /* priority trap */
693 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
697 * List relating reference clock types to control message time sources.
698 * Index by the reference clock type. This list will only be used iff
699 * the reference clock driver doesn't set peer->sstclktype to something
700 * different than CTL_SST_TS_UNSPEC.
703 static const u_char clocktypes[] = {
704 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
705 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
706 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
707 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
708 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
709 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
710 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
711 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
712 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
713 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
714 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
715 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
716 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
717 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
718 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
719 CTL_SST_TS_NTP, /* not used (15) */
720 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
721 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
722 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
723 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
724 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
725 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
726 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
727 CTL_SST_TS_NTP, /* not used (23) */
728 CTL_SST_TS_NTP, /* not used (24) */
729 CTL_SST_TS_NTP, /* not used (25) */
730 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
731 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
732 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
733 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
734 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
735 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
736 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
737 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
738 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
739 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
740 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
741 CTL_SST_TS_LF, /* REFCLK_FG (37) */
742 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
743 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
744 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
745 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
746 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
747 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
748 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
749 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
750 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
752 #endif /* REFCLOCK */
756 * Keyid used for authenticating write requests.
758 keyid_t ctl_auth_keyid;
761 * We keep track of the last error reported by the system internally
763 static u_char ctl_sys_last_event;
764 static u_char ctl_sys_num_events;
768 * Statistic counters to keep track of requests and responses.
770 u_long ctltimereset; /* time stats reset */
771 u_long numctlreq; /* number of requests we've received */
772 u_long numctlbadpkts; /* number of bad control packets */
773 u_long numctlresponses; /* number of resp packets sent with data */
774 u_long numctlfrags; /* number of fragments sent */
775 u_long numctlerrors; /* number of error responses sent */
776 u_long numctltooshort; /* number of too short input packets */
777 u_long numctlinputresp; /* number of responses on input */
778 u_long numctlinputfrag; /* number of fragments on input */
779 u_long numctlinputerr; /* number of input pkts with err bit set */
780 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
781 u_long numctlbadversion; /* number of input pkts with unknown version */
782 u_long numctldatatooshort; /* data too short for count */
783 u_long numctlbadop; /* bad op code found in packet */
784 u_long numasyncmsgs; /* number of async messages we've sent */
787 * Response packet used by these routines. Also some state information
788 * so that we can handle packet formatting within a common set of
789 * subroutines. Note we try to enter data in place whenever possible,
790 * but the need to set the more bit correctly means we occasionally
791 * use the extra buffer and copy.
793 static struct ntp_control rpkt;
794 static u_char res_version;
795 static u_char res_opcode;
796 static associd_t res_associd;
797 static u_short res_frags; /* datagrams in this response */
798 static int res_offset; /* offset of payload in response */
799 static u_char * datapt;
800 static u_char * dataend;
801 static int datalinelen;
802 static int datasent; /* flag to avoid initial ", " */
803 static int datanotbinflag;
804 static sockaddr_u *rmt_addr;
805 static struct interface *lcl_inter;
807 static u_char res_authenticate;
808 static u_char res_authokay;
809 static keyid_t res_keyid;
811 #define MAXDATALINELEN (72)
813 static u_char res_async; /* sending async trap response? */
816 * Pointers for saving state when decoding request packets
822 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
826 * init_control - initialize request data
835 #endif /* HAVE_UNAME */
840 ctl_sys_last_event = EVNT_UNSPEC;
841 ctl_sys_num_events = 0;
844 for (i = 0; i < COUNTOF(ctl_traps); i++)
845 ctl_traps[i].tr_flags = 0;
850 * ctl_error - send an error response for the current request
860 DPRINTF(3, ("sending control error %u\n", errcode));
863 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
864 * have already been filled in.
866 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
867 (res_opcode & CTL_OP_MASK);
868 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
872 * send packet and bump counters
874 if (res_authenticate && sys_authenticate) {
875 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
877 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
878 CTL_HEADER_LEN + maclen);
880 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
885 * save_config - Implements ntpq -c "saveconfig <filename>"
886 * Writes current configuration including any runtime
887 * changes by ntpq's :config or config-from-file
891 struct recvbuf *rbufp,
900 const char savedconfig_eq[] = "savedconfig=";
901 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
907 if (RES_NOMODIFY & restrict_mask) {
908 snprintf(reply, sizeof(reply),
909 "saveconfig prohibited by restrict ... nomodify");
910 ctl_putdata(reply, strlen(reply), 0);
914 "saveconfig from %s rejected due to nomodify restriction",
915 stoa(&rbufp->recv_srcadr));
921 if (NULL == saveconfigdir) {
922 snprintf(reply, sizeof(reply),
923 "saveconfig prohibited, no saveconfigdir configured");
924 ctl_putdata(reply, strlen(reply), 0);
928 "saveconfig from %s rejected, no saveconfigdir",
929 stoa(&rbufp->recv_srcadr));
933 if (0 == reqend - reqpt)
936 strlcpy(filespec, reqpt, sizeof(filespec));
940 * allow timestamping of the saved config filename with
941 * strftime() format such as:
942 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
943 * XXX: Nice feature, but not too safe.
945 if (0 == strftime(filename, sizeof(filename), filespec,
947 strlcpy(filename, filespec, sizeof(filename));
950 * Conceptually we should be searching for DIRSEP in filename,
951 * however Windows actually recognizes both forward and
952 * backslashes as equivalent directory separators at the API
953 * level. On POSIX systems we could allow '\\' but such
954 * filenames are tricky to manipulate from a shell, so just
955 * reject both types of slashes on all platforms.
957 if (strchr(filename, '\\') || strchr(filename, '/')) {
958 snprintf(reply, sizeof(reply),
959 "saveconfig does not allow directory in filename");
960 ctl_putdata(reply, strlen(reply), 0);
963 "saveconfig with path from %s rejected",
964 stoa(&rbufp->recv_srcadr));
968 snprintf(fullpath, sizeof(fullpath), "%s%s",
969 saveconfigdir, filename);
971 fd = open(fullpath, O_CREAT | O_TRUNC | O_WRONLY,
976 fptr = fdopen(fd, "w");
978 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
979 snprintf(reply, sizeof(reply),
980 "Unable to save configuration to file %s",
983 "saveconfig %s from %s failed", filename,
984 stoa(&rbufp->recv_srcadr));
986 snprintf(reply, sizeof(reply),
987 "Configuration saved to %s", filename);
989 "Configuration saved to %s (requested by %s)",
990 fullpath, stoa(&rbufp->recv_srcadr));
992 * save the output filename in system variable
993 * savedconfig, retrieved with:
994 * ntpq -c "rv 0 savedconfig"
996 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
997 savedconfig_eq, filename);
998 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1003 #else /* !SAVECONFIG follows */
1004 snprintf(reply, sizeof(reply),
1005 "saveconfig unavailable, configured with --disable-saveconfig");
1008 ctl_putdata(reply, strlen(reply), 0);
1014 * process_control - process an incoming control message
1018 struct recvbuf *rbufp,
1022 struct ntp_control *pkt;
1025 const struct ctl_proc *cc;
1030 DPRINTF(3, ("in process_control()\n"));
1033 * Save the addresses for error responses
1036 rmt_addr = &rbufp->recv_srcadr;
1037 lcl_inter = rbufp->dstadr;
1038 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1041 * If the length is less than required for the header, or
1042 * it is a response or a fragment, ignore this.
1044 if (rbufp->recv_length < (int)CTL_HEADER_LEN
1045 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1046 || pkt->offset != 0) {
1047 DPRINTF(1, ("invalid format in control packet\n"));
1048 if (rbufp->recv_length < (int)CTL_HEADER_LEN)
1050 if (CTL_RESPONSE & pkt->r_m_e_op)
1052 if (CTL_MORE & pkt->r_m_e_op)
1054 if (CTL_ERROR & pkt->r_m_e_op)
1056 if (pkt->offset != 0)
1060 res_version = PKT_VERSION(pkt->li_vn_mode);
1061 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1062 DPRINTF(1, ("unknown version %d in control packet\n",
1069 * Pull enough data from the packet to make intelligent
1072 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1074 res_opcode = pkt->r_m_e_op;
1075 rpkt.sequence = pkt->sequence;
1076 rpkt.associd = pkt->associd;
1080 res_associd = htons(pkt->associd);
1082 res_authenticate = FALSE;
1084 res_authokay = FALSE;
1085 req_count = (int)ntohs(pkt->count);
1086 datanotbinflag = FALSE;
1089 datapt = rpkt.u.data;
1090 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1092 if ((rbufp->recv_length & 0x3) != 0)
1093 DPRINTF(3, ("Control packet length %d unrounded\n",
1094 rbufp->recv_length));
1097 * We're set up now. Make sure we've got at least enough
1098 * incoming data space to match the count.
1100 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1101 if (req_data < req_count || rbufp->recv_length & 0x3) {
1102 ctl_error(CERR_BADFMT);
1103 numctldatatooshort++;
1107 properlen = req_count + CTL_HEADER_LEN;
1108 /* round up proper len to a 8 octet boundary */
1110 properlen = (properlen + 7) & ~7;
1111 maclen = rbufp->recv_length - properlen;
1112 if ((rbufp->recv_length & 3) == 0 &&
1113 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1115 res_authenticate = TRUE;
1116 pkid = (void *)((char *)pkt + properlen);
1117 res_keyid = ntohl(*pkid);
1118 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1119 rbufp->recv_length, properlen, res_keyid,
1122 if (!authistrusted(res_keyid))
1123 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1124 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1125 rbufp->recv_length - maclen,
1127 res_authokay = TRUE;
1128 DPRINTF(3, ("authenticated okay\n"));
1131 DPRINTF(3, ("authentication failed\n"));
1136 * Set up translate pointers
1138 reqpt = (char *)pkt->u.data;
1139 reqend = reqpt + req_count;
1142 * Look for the opcode processor
1144 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1145 if (cc->control_code == res_opcode) {
1146 DPRINTF(3, ("opcode %d, found command handler\n",
1148 if (cc->flags == AUTH
1150 || res_keyid != ctl_auth_keyid)) {
1151 ctl_error(CERR_PERMISSION);
1154 (cc->handler)(rbufp, restrict_mask);
1160 * Can't find this one, return an error.
1163 ctl_error(CERR_BADOP);
1169 * ctlpeerstatus - return a status word for this peer
1173 register struct peer *p
1179 if (FLAG_CONFIG & p->flags)
1180 status |= CTL_PST_CONFIG;
1182 status |= CTL_PST_AUTHENABLE;
1183 if (FLAG_AUTHENTIC & p->flags)
1184 status |= CTL_PST_AUTHENTIC;
1186 status |= CTL_PST_REACH;
1187 if (MDF_TXONLY_MASK & p->cast_flags)
1188 status |= CTL_PST_BCAST;
1190 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1195 * ctlclkstatus - return a status word for this clock
1200 struct refclockstat *pcs
1203 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1209 * ctlsysstatus - return the system status word
1214 register u_char this_clock;
1216 this_clock = CTL_SST_TS_UNSPEC;
1218 if (sys_peer != NULL) {
1219 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1220 this_clock = sys_peer->sstclktype;
1221 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1222 this_clock = clocktypes[sys_peer->refclktype];
1224 #else /* REFCLOCK */
1226 this_clock = CTL_SST_TS_NTP;
1227 #endif /* REFCLOCK */
1228 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1229 ctl_sys_last_event);
1234 * ctl_flushpkt - write out the current packet and prepare
1235 * another if necessary.
1249 dlen = datapt - rpkt.u.data;
1250 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1252 * Big hack, output a trailing \r\n
1258 sendlen = dlen + CTL_HEADER_LEN;
1261 * Pad to a multiple of 32 bits
1263 while (sendlen & 0x3) {
1269 * Fill in the packet with the current info
1271 rpkt.r_m_e_op = CTL_RESPONSE | more |
1272 (res_opcode & CTL_OP_MASK);
1273 rpkt.count = htons((u_short)dlen);
1274 rpkt.offset = htons((u_short)res_offset);
1276 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1277 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1281 ctl_traps[i].tr_version,
1284 htons(ctl_traps[i].tr_sequence);
1285 sendpkt(&ctl_traps[i].tr_addr,
1286 ctl_traps[i].tr_localaddr, -4,
1287 (struct pkt *)&rpkt, sendlen);
1289 ctl_traps[i].tr_sequence++;
1294 if (res_authenticate && sys_authenticate) {
1297 * If we are going to authenticate, then there
1298 * is an additional requirement that the MAC
1299 * begin on a 64 bit boundary.
1301 while (totlen & 7) {
1305 keyid = htonl(res_keyid);
1306 memcpy(datapt, &keyid, sizeof(keyid));
1307 maclen = authencrypt(res_keyid,
1308 (u_int32 *)&rpkt, totlen);
1309 sendpkt(rmt_addr, lcl_inter, -5,
1310 (struct pkt *)&rpkt, totlen + maclen);
1312 sendpkt(rmt_addr, lcl_inter, -6,
1313 (struct pkt *)&rpkt, sendlen);
1322 * Set us up for another go around.
1326 datapt = rpkt.u.data;
1331 * ctl_putdata - write data into the packet, fragmenting and starting
1332 * another if this one is full.
1338 int bin /* set to 1 when data is binary */
1342 unsigned int currentlen;
1346 datanotbinflag = TRUE;
1351 if ((dlen + datalinelen + 1) >= MAXDATALINELEN) {
1363 * Save room for trailing junk
1365 while (dlen + overhead + datapt > dataend) {
1367 * Not enough room in this one, flush it out.
1369 currentlen = MIN(dlen, (unsigned int)(dataend - datapt));
1371 memcpy(datapt, dp, currentlen);
1373 datapt += currentlen;
1376 datalinelen += currentlen;
1378 ctl_flushpkt(CTL_MORE);
1381 memcpy(datapt, dp, dlen);
1383 datalinelen += dlen;
1389 * ctl_putstr - write a tagged string into the response packet
1394 * len is the data length excluding the NUL terminator,
1395 * as in ctl_putstr("var", "value", strlen("value"));
1409 memcpy(buffer, tag, tl);
1412 NTP_INSIST(tl + 3 + len <= sizeof(buffer));
1415 memcpy(cp, data, len);
1419 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1424 * ctl_putunqstr - write a tagged string into the response packet
1429 * len is the data length excluding the NUL terminator.
1430 * data must not contain a comma or whitespace.
1444 memcpy(buffer, tag, tl);
1447 NTP_INSIST(tl + 1 + len <= sizeof(buffer));
1449 memcpy(cp, data, len);
1452 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1457 * ctl_putdblf - write a tagged, signed double into the response packet
1476 NTP_INSIST((size_t)(cp - buffer) < sizeof(buffer));
1477 snprintf(cp, sizeof(buffer) - (cp - buffer), use_f ? "%.*f" : "%.*g",
1480 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1484 * ctl_putuint - write a tagged unsigned integer into the response
1493 register const char *cq;
1502 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1503 snprintf(cp, sizeof(buffer) - (cp - buffer), "%lu", uval);
1505 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1509 * ctl_putcal - write a decoded calendar data into the response
1514 const struct calendar *pcal
1520 numch = snprintf(buffer, sizeof(buffer),
1521 "%s=%04d%02d%02d%02d%02d",
1529 NTP_INSIST(numch < sizeof(buffer));
1530 ctl_putdata(buffer, numch, 0);
1536 * ctl_putfs - write a decoded filestamp into the response
1545 register const char *cq;
1547 struct tm *tm = NULL;
1556 fstamp = uval - JAN_1970;
1557 tm = gmtime(&fstamp);
1560 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1561 snprintf(cp, sizeof(buffer) - (cp - buffer),
1562 "%04d%02d%02d%02d%02d", tm->tm_year + 1900,
1563 tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);
1565 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1570 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1580 register const char *cq;
1589 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1590 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%lx", uval);
1592 ctl_putdata(buffer,(unsigned)( cp - buffer ), 0);
1597 * ctl_putint - write a tagged signed integer into the response
1606 register const char *cq;
1615 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1616 snprintf(cp, sizeof(buffer) - (cp - buffer), "%ld", ival);
1618 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1623 * ctl_putts - write a tagged timestamp, in hex, into the response
1632 register const char *cq;
1641 NTP_INSIST((size_t)(cp - buffer) < sizeof(buffer));
1642 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%08x.%08x",
1643 (u_int)ts->l_ui, (u_int)ts->l_uf);
1645 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1650 * ctl_putadr - write an IP address into the response
1660 register const char *cq;
1670 cq = numtoa(addr32);
1673 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1674 snprintf(cp, sizeof(buffer) - (cp - buffer), "%s", cq);
1676 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1681 * ctl_putrefid - send a u_int32 refid as printable text
1697 oplim = output + sizeof(output);
1698 while (optr < oplim && '\0' != *tag)
1704 if (!(optr < oplim))
1706 iptr = (char *)&refid;
1707 iplim = iptr + sizeof(refid);
1708 for ( ; optr < oplim && iptr < iplim && '\0' != *iptr;
1710 if (isprint((int)*iptr))
1714 if (!(optr <= oplim))
1716 ctl_putdata(output, (u_int)(optr - output), FALSE);
1721 * ctl_putarray - write a tagged eight element double array into the response
1731 register const char *cq;
1744 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1745 snprintf(cp, sizeof(buffer) - (cp - buffer),
1746 " %.2f", arr[i] * 1e3);
1748 } while (i != start);
1749 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1754 * ctl_putsys - output a system variable
1768 struct cert_info *cp;
1769 #endif /* AUTOKEY */
1771 static struct timex ntx;
1772 static u_long ntp_adjtime_time;
1774 static const double to_ms =
1776 1.0e-6; /* nsec to msec */
1778 1.0e-3; /* usec to msec */
1782 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1784 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1785 current_time != ntp_adjtime_time) {
1787 if (ntp_adjtime(&ntx) < 0)
1788 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1790 ntp_adjtime_time = current_time;
1792 #endif /* KERNEL_PLL */
1797 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1801 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1805 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1809 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1813 case CS_ROOTDISPERSION:
1814 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1815 sys_rootdisp * 1e3);
1819 if (sys_stratum > 1 && sys_stratum < STRATUM_UNSPEC)
1820 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1822 ctl_putrefid(sys_var[varid].text, sys_refid);
1826 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1830 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
1834 if (sys_peer == NULL)
1835 ctl_putuint(sys_var[CS_PEERID].text, 0);
1837 ctl_putuint(sys_var[CS_PEERID].text,
1842 if (sys_peer != NULL && sys_peer->dstadr != NULL)
1843 ss = sptoa(&sys_peer->srcadr);
1846 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
1850 u = (sys_peer != NULL)
1853 ctl_putuint(sys_var[CS_PEERMODE].text, u);
1857 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
1861 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
1865 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
1869 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
1874 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
1879 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
1880 sizeof(str_processor) - 1);
1882 ctl_putstr(sys_var[CS_PROCESSOR].text,
1883 utsnamebuf.machine, strlen(utsnamebuf.machine));
1884 #endif /* HAVE_UNAME */
1889 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
1890 sizeof(str_system) - 1);
1892 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
1893 utsnamebuf.release);
1894 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
1895 #endif /* HAVE_UNAME */
1899 ctl_putstr(sys_var[CS_VERSION].text, Version,
1904 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
1910 char buf[CTL_MAX_DATA_LEN];
1911 //buffPointer, firstElementPointer, buffEndPointer
1912 char *buffp, *buffend;
1916 const struct ctl_var *k;
1919 buffend = buf + sizeof(buf);
1920 if (buffp + strlen(sys_var[CS_VARLIST].text) + 4 > buffend)
1921 break; /* really long var name */
1923 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
1924 buffp += strlen(buffp);
1925 firstVarName = TRUE;
1926 for (k = sys_var; !(k->flags & EOV); k++) {
1927 if (k->flags & PADDING)
1929 len = strlen(k->text);
1930 if (buffp + len + 1 >= buffend)
1935 firstVarName = FALSE;
1936 memcpy(buffp, k->text, len);
1940 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
1941 if (k->flags & PADDING)
1943 if (NULL == k->text)
1945 ss1 = strchr(k->text, '=');
1947 len = strlen(k->text);
1949 len = ss1 - k->text;
1950 if (buffp + len + 1 >= buffend)
1954 firstVarName = FALSE;
1956 memcpy(buffp, k->text,(unsigned)len);
1959 if (buffp + 2 >= buffend)
1965 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
1971 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
1976 leap_signature_t lsig;
1977 leapsec_getsig(&lsig);
1979 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
1985 leap_signature_t lsig;
1986 leapsec_getsig(&lsig);
1988 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
1993 case CS_LEAPSMEARINTV:
1994 if (leap_smear_intv > 0)
1995 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
1998 case CS_LEAPSMEAROFFS:
1999 if (leap_smear_intv > 0)
2000 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2001 leap_smear.doffset * 1e3);
2003 #endif /* LEAP_SMEAR */
2006 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2009 case CS_MRU_ENABLED:
2010 ctl_puthex(sys_var[varid].text, mon_enabled);
2014 ctl_putuint(sys_var[varid].text, mru_entries);
2018 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2022 ctl_putuint(sys_var[varid].text, u);
2025 case CS_MRU_DEEPEST:
2026 ctl_putuint(sys_var[varid].text, mru_peakentries);
2029 case CS_MRU_MINDEPTH:
2030 ctl_putuint(sys_var[varid].text, mru_mindepth);
2034 ctl_putint(sys_var[varid].text, mru_maxage);
2037 case CS_MRU_MAXDEPTH:
2038 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2042 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2046 ctl_putuint(sys_var[varid].text, u);
2050 ctl_putuint(sys_var[varid].text, current_time);
2054 ctl_putuint(sys_var[varid].text,
2055 current_time - sys_stattime);
2058 case CS_SS_RECEIVED:
2059 ctl_putuint(sys_var[varid].text, sys_received);
2063 ctl_putuint(sys_var[varid].text, sys_newversion);
2067 ctl_putuint(sys_var[varid].text, sys_oldversion);
2070 case CS_SS_BADFORMAT:
2071 ctl_putuint(sys_var[varid].text, sys_badlength);
2075 ctl_putuint(sys_var[varid].text, sys_badauth);
2078 case CS_SS_DECLINED:
2079 ctl_putuint(sys_var[varid].text, sys_declined);
2082 case CS_SS_RESTRICTED:
2083 ctl_putuint(sys_var[varid].text, sys_restricted);
2087 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2091 ctl_putuint(sys_var[varid].text, sys_kodsent);
2094 case CS_SS_PROCESSED:
2095 ctl_putuint(sys_var[varid].text, sys_processed);
2099 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2103 LFPTOD(&sys_authdelay, dtemp);
2104 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2108 ctl_putuint(sys_var[varid].text, authnumkeys);
2112 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2115 case CS_AUTHKLOOKUPS:
2116 ctl_putuint(sys_var[varid].text, authkeylookups);
2119 case CS_AUTHKNOTFOUND:
2120 ctl_putuint(sys_var[varid].text, authkeynotfound);
2123 case CS_AUTHKUNCACHED:
2124 ctl_putuint(sys_var[varid].text, authkeyuncached);
2127 case CS_AUTHKEXPIRED:
2128 ctl_putuint(sys_var[varid].text, authkeyexpired);
2131 case CS_AUTHENCRYPTS:
2132 ctl_putuint(sys_var[varid].text, authencryptions);
2135 case CS_AUTHDECRYPTS:
2136 ctl_putuint(sys_var[varid].text, authdecryptions);
2140 ctl_putuint(sys_var[varid].text,
2141 current_time - auth_timereset);
2145 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2146 * unavailable, otherwise calls putfunc with args.
2149 # define CTL_IF_KERNLOOP(putfunc, args) \
2150 ctl_putint(sys_var[varid].text, 0)
2152 # define CTL_IF_KERNLOOP(putfunc, args) \
2157 * CTL_IF_KERNPPS() puts a zero if either the kernel
2158 * loop is unavailable, or kernel hard PPS is not
2159 * active, otherwise calls putfunc with args.
2162 # define CTL_IF_KERNPPS(putfunc, args) \
2163 ctl_putint(sys_var[varid].text, 0)
2165 # define CTL_IF_KERNPPS(putfunc, args) \
2166 if (0 == ntx.shift) \
2167 ctl_putint(sys_var[varid].text, 0); \
2169 putfunc args /* no trailing ; */
2175 (sys_var[varid].text, 0, -1, to_ms * ntx.offset)
2182 (sys_var[varid].text, ntx.freq)
2189 (sys_var[varid].text, 0, 6,
2190 to_ms * ntx.maxerror)
2197 (sys_var[varid].text, 0, 6,
2198 to_ms * ntx.esterror)
2206 ss = k_st_flags(ntx.status);
2208 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2211 case CS_K_TIMECONST:
2214 (sys_var[varid].text, ntx.constant)
2218 case CS_K_PRECISION:
2221 (sys_var[varid].text, 0, 6,
2222 to_ms * ntx.precision)
2229 (sys_var[varid].text, ntx.tolerance)
2236 (sys_var[varid].text, ntx.ppsfreq)
2240 case CS_K_PPS_STABIL:
2243 (sys_var[varid].text, ntx.stabil)
2247 case CS_K_PPS_JITTER:
2250 (sys_var[varid].text, to_ms * ntx.jitter)
2254 case CS_K_PPS_CALIBDUR:
2257 (sys_var[varid].text, 1 << ntx.shift)
2261 case CS_K_PPS_CALIBS:
2264 (sys_var[varid].text, ntx.calcnt)
2268 case CS_K_PPS_CALIBERRS:
2271 (sys_var[varid].text, ntx.errcnt)
2275 case CS_K_PPS_JITEXC:
2278 (sys_var[varid].text, ntx.jitcnt)
2282 case CS_K_PPS_STBEXC:
2285 (sys_var[varid].text, ntx.stbcnt)
2289 case CS_IOSTATS_RESET:
2290 ctl_putuint(sys_var[varid].text,
2291 current_time - io_timereset);
2295 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2299 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2303 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2306 case CS_RBUF_LOWATER:
2307 ctl_putuint(sys_var[varid].text, lowater_additions());
2311 ctl_putuint(sys_var[varid].text, packets_dropped);
2315 ctl_putuint(sys_var[varid].text, packets_ignored);
2318 case CS_IO_RECEIVED:
2319 ctl_putuint(sys_var[varid].text, packets_received);
2323 ctl_putuint(sys_var[varid].text, packets_sent);
2326 case CS_IO_SENDFAILED:
2327 ctl_putuint(sys_var[varid].text, packets_notsent);
2331 ctl_putuint(sys_var[varid].text, handler_calls);
2334 case CS_IO_GOODWAKEUPS:
2335 ctl_putuint(sys_var[varid].text, handler_pkts);
2338 case CS_TIMERSTATS_RESET:
2339 ctl_putuint(sys_var[varid].text,
2340 current_time - timer_timereset);
2343 case CS_TIMER_OVERRUNS:
2344 ctl_putuint(sys_var[varid].text, alarm_overflow);
2348 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2352 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2354 case CS_WANDER_THRESH:
2355 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2360 ctl_puthex(sys_var[CS_FLAGS].text,
2366 strlcpy(str, OBJ_nid2ln(crypto_nid),
2368 ctl_putstr(sys_var[CS_DIGEST].text, str,
2377 dp = EVP_get_digestbynid(crypto_flags >> 16);
2378 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2380 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2386 if (hostval.ptr != NULL)
2387 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2388 strlen(hostval.ptr));
2392 if (sys_ident != NULL)
2393 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2398 for (cp = cinfo; cp != NULL; cp = cp->link) {
2399 snprintf(str, sizeof(str), "%s %s 0x%x",
2400 cp->subject, cp->issuer, cp->flags);
2401 ctl_putstr(sys_var[CS_CERTIF].text, str,
2403 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2408 if (hostval.tstamp != 0)
2409 ctl_putfs(sys_var[CS_PUBLIC].text,
2410 ntohl(hostval.tstamp));
2412 #endif /* AUTOKEY */
2418 * ctl_putpeer - output a peer variable
2426 char buf[CTL_MAX_DATA_LEN];
2431 const struct ctl_var *k;
2436 #endif /* AUTOKEY */
2441 ctl_putuint(peer_var[id].text,
2442 !(FLAG_PREEMPT & p->flags));
2446 ctl_putuint(peer_var[id].text, !(p->keyid));
2450 ctl_putuint(peer_var[id].text,
2451 !!(FLAG_AUTHENTIC & p->flags));
2455 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2459 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2463 if (p->hostname != NULL)
2464 ctl_putstr(peer_var[id].text, p->hostname,
2465 strlen(p->hostname));
2469 ctl_putadr(peer_var[id].text, 0,
2476 ctl_putuint(peer_var[id].text,
2478 ? SRCPORT(&p->dstadr->sin)
2484 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2489 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2493 ctl_putuint(peer_var[id].text, p->throttle);
2497 ctl_putuint(peer_var[id].text, p->leap);
2501 ctl_putuint(peer_var[id].text, p->hmode);
2505 ctl_putuint(peer_var[id].text, p->stratum);
2509 ctl_putuint(peer_var[id].text, p->ppoll);
2513 ctl_putuint(peer_var[id].text, p->hpoll);
2517 ctl_putint(peer_var[id].text, p->precision);
2521 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2524 case CP_ROOTDISPERSION:
2525 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2530 if (p->flags & FLAG_REFCLOCK) {
2531 ctl_putrefid(peer_var[id].text, p->refid);
2535 if (p->stratum > 1 && p->stratum < STRATUM_UNSPEC)
2536 ctl_putadr(peer_var[id].text, p->refid,
2539 ctl_putrefid(peer_var[id].text, p->refid);
2543 ctl_putts(peer_var[id].text, &p->reftime);
2547 ctl_putts(peer_var[id].text, &p->aorg);
2551 ctl_putts(peer_var[id].text, &p->dst);
2556 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2561 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2565 ctl_puthex(peer_var[id].text, p->reach);
2569 ctl_puthex(peer_var[id].text, p->flash);
2574 if (p->flags & FLAG_REFCLOCK) {
2575 ctl_putuint(peer_var[id].text, p->ttl);
2579 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2580 ctl_putint(peer_var[id].text,
2585 ctl_putuint(peer_var[id].text, p->unreach);
2589 ctl_putuint(peer_var[id].text,
2590 p->nextdate - current_time);
2594 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2598 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2602 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2606 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2610 if (p->keyid > NTP_MAXKEY)
2611 ctl_puthex(peer_var[id].text, p->keyid);
2613 ctl_putuint(peer_var[id].text, p->keyid);
2617 ctl_putarray(peer_var[id].text, p->filter_delay,
2622 ctl_putarray(peer_var[id].text, p->filter_offset,
2627 ctl_putarray(peer_var[id].text, p->filter_disp,
2632 ctl_putuint(peer_var[id].text, p->pmode);
2636 ctl_putuint(peer_var[id].text, p->received);
2640 ctl_putuint(peer_var[id].text, p->sent);
2645 be = buf + sizeof(buf);
2646 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2647 break; /* really long var name */
2649 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2652 for (k = peer_var; !(EOV & k->flags); k++) {
2653 if (PADDING & k->flags)
2655 i = strlen(k->text);
2656 if (s + i + 1 >= be)
2660 memcpy(s, k->text, i);
2666 ctl_putdata(buf, (u_int)(s - buf), 0);
2671 ctl_putuint(peer_var[id].text,
2672 current_time - p->timereceived);
2676 ctl_putuint(peer_var[id].text,
2677 current_time - p->timereachable);
2681 ctl_putuint(peer_var[id].text, p->badauth);
2685 ctl_putuint(peer_var[id].text, p->bogusorg);
2689 ctl_putuint(peer_var[id].text, p->oldpkt);
2693 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2697 ctl_putuint(peer_var[id].text, p->selbroken);
2701 ctl_putuint(peer_var[id].text, p->status);
2706 ctl_puthex(peer_var[id].text, p->crypto);
2711 dp = EVP_get_digestbynid(p->crypto >> 16);
2712 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2713 ctl_putstr(peer_var[id].text, str, strlen(str));
2718 if (p->subject != NULL)
2719 ctl_putstr(peer_var[id].text, p->subject,
2720 strlen(p->subject));
2723 case CP_VALID: /* not used */
2727 if (NULL == (ap = p->recval.ptr))
2730 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2731 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2732 ctl_putfs(peer_var[CP_INITTSP].text,
2733 ntohl(p->recval.tstamp));
2737 if (p->ident != NULL)
2738 ctl_putstr(peer_var[id].text, p->ident,
2743 #endif /* AUTOKEY */
2750 * ctl_putclock - output clock variables
2755 struct refclockstat *pcs,
2759 char buf[CTL_MAX_DATA_LEN];
2763 const struct ctl_var *k;
2768 if (mustput || pcs->clockdesc == NULL
2769 || *(pcs->clockdesc) == '\0') {
2770 ctl_putuint(clock_var[id].text, pcs->type);
2774 ctl_putstr(clock_var[id].text,
2776 (unsigned)pcs->lencode);
2780 ctl_putuint(clock_var[id].text, pcs->polls);
2784 ctl_putuint(clock_var[id].text,
2789 ctl_putuint(clock_var[id].text,
2794 ctl_putuint(clock_var[id].text,
2799 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2800 ctl_putdbl(clock_var[id].text,
2801 pcs->fudgetime1 * 1e3);
2805 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2806 ctl_putdbl(clock_var[id].text,
2807 pcs->fudgetime2 * 1e3);
2811 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2812 ctl_putint(clock_var[id].text,
2817 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2818 if (pcs->fudgeval1 > 1)
2819 ctl_putadr(clock_var[id].text,
2820 pcs->fudgeval2, NULL);
2822 ctl_putrefid(clock_var[id].text,
2828 ctl_putuint(clock_var[id].text, pcs->flags);
2832 if (pcs->clockdesc == NULL ||
2833 *(pcs->clockdesc) == '\0') {
2835 ctl_putstr(clock_var[id].text,
2838 ctl_putstr(clock_var[id].text,
2840 strlen(pcs->clockdesc));
2846 be = buf + sizeof(buf);
2847 if (strlen(clock_var[CC_VARLIST].text) + 4 >
2849 break; /* really long var name */
2851 snprintf(s, sizeof(buf), "%s=\"",
2852 clock_var[CC_VARLIST].text);
2856 for (k = clock_var; !(EOV & k->flags); k++) {
2857 if (PADDING & k->flags)
2860 i = strlen(k->text);
2861 if (s + i + 1 >= be)
2866 memcpy(s, k->text, i);
2870 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
2871 if (PADDING & k->flags)
2878 while (*ss && *ss != '=')
2881 if (s + i + 1 >= be)
2886 memcpy(s, k->text, (unsigned)i);
2895 ctl_putdata(buf, (unsigned)(s - buf), 0);
2904 * ctl_getitem - get the next data item from the incoming packet
2906 static const struct ctl_var *
2908 const struct ctl_var *var_list,
2912 static const struct ctl_var eol = { 0, EOV, NULL };
2913 static char buf[128];
2914 static u_long quiet_until;
2915 const struct ctl_var *v;
2921 * Delete leading commas and white space
2923 while (reqpt < reqend && (*reqpt == ',' ||
2924 isspace((unsigned char)*reqpt)))
2926 if (reqpt >= reqend)
2929 if (NULL == var_list)
2933 * Look for a first character match on the tag. If we find
2934 * one, see if it is a full match.
2938 for (v = var_list; !(EOV & v->flags); v++) {
2939 if (!(PADDING & v->flags) && *cp == *(v->text)) {
2941 while ('\0' != *pch && '=' != *pch && cp < reqend
2946 if ('\0' == *pch || '=' == *pch) {
2947 while (cp < reqend && isspace((u_char)*cp))
2949 if (cp == reqend || ',' == *cp) {
2960 while (cp < reqend && isspace((u_char)*cp))
2962 while (cp < reqend && *cp != ',') {
2964 if ((size_t)(tp - buf) >= sizeof(buf)) {
2965 ctl_error(CERR_BADFMT);
2968 if (quiet_until <= current_time) {
2969 quiet_until = current_time + 300;
2970 msyslog(LOG_WARNING,
2971 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)", stoa(rmt_addr), SRCPORT(rmt_addr));
2979 while (tp >= buf && isspace((u_char)*tp))
2994 * control_unspec - response to an unspecified op-code
2999 struct recvbuf *rbufp,
3006 * What is an appropriate response to an unspecified op-code?
3007 * I return no errors and no data, unless a specified assocation
3011 peer = findpeerbyassoc(res_associd);
3013 ctl_error(CERR_BADASSOC);
3016 rpkt.status = htons(ctlpeerstatus(peer));
3018 rpkt.status = htons(ctlsysstatus());
3024 * read_status - return either a list of associd's, or a particular
3030 struct recvbuf *rbufp,
3037 /* a_st holds association ID, status pairs alternating */
3038 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3042 printf("read_status: ID %d\n", res_associd);
3045 * Two choices here. If the specified association ID is
3046 * zero we return all known assocation ID's. Otherwise
3047 * we return a bunch of stuff about the particular peer.
3050 peer = findpeerbyassoc(res_associd);
3052 ctl_error(CERR_BADASSOC);
3055 rpkt.status = htons(ctlpeerstatus(peer));
3057 peer->num_events = 0;
3059 * For now, output everything we know about the
3060 * peer. May be more selective later.
3062 for (cp = def_peer_var; *cp != 0; cp++)
3063 ctl_putpeer((int)*cp, peer);
3068 rpkt.status = htons(ctlsysstatus());
3069 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3070 a_st[n++] = htons(peer->associd);
3071 a_st[n++] = htons(ctlpeerstatus(peer));
3072 /* two entries each loop iteration, so n + 1 */
3073 if (n + 1 >= COUNTOF(a_st)) {
3074 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3080 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3086 * read_peervars - half of read_variables() implementation
3091 const struct ctl_var *v;
3096 u_char wants[CP_MAXCODE + 1];
3100 * Wants info for a particular peer. See if we know
3103 peer = findpeerbyassoc(res_associd);
3105 ctl_error(CERR_BADASSOC);
3108 rpkt.status = htons(ctlpeerstatus(peer));
3110 peer->num_events = 0;
3113 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3114 if (v->flags & EOV) {
3115 ctl_error(CERR_UNKNOWNVAR);
3118 NTP_INSIST(v->code < COUNTOF(wants));
3123 for (i = 1; i < COUNTOF(wants); i++)
3125 ctl_putpeer(i, peer);
3127 for (cp = def_peer_var; *cp != 0; cp++)
3128 ctl_putpeer((int)*cp, peer);
3134 * read_sysvars - half of read_variables() implementation
3139 const struct ctl_var *v;
3150 * Wants system variables. Figure out which he wants
3151 * and give them to him.
3153 rpkt.status = htons(ctlsysstatus());
3155 ctl_sys_num_events = 0;
3156 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3157 wants = emalloc_zero(wants_count);
3159 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3160 if (!(EOV & v->flags)) {
3161 NTP_INSIST(v->code < wants_count);
3165 v = ctl_getitem(ext_sys_var, &valuep);
3166 NTP_INSIST(v != NULL);
3167 if (EOV & v->flags) {
3168 ctl_error(CERR_UNKNOWNVAR);
3172 n = v->code + CS_MAXCODE + 1;
3173 NTP_INSIST(n < wants_count);
3179 for (n = 1; n <= CS_MAXCODE; n++)
3182 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3183 if (wants[n + CS_MAXCODE + 1]) {
3184 pch = ext_sys_var[n].text;
3185 ctl_putdata(pch, strlen(pch), 0);
3188 for (cs = def_sys_var; *cs != 0; cs++)
3189 ctl_putsys((int)*cs);
3190 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3191 if (DEF & kv->flags)
3192 ctl_putdata(kv->text, strlen(kv->text),
3201 * read_variables - return the variables the caller asks for
3206 struct recvbuf *rbufp,
3218 * write_variables - write into variables. We only allow leap bit
3224 struct recvbuf *rbufp,
3228 const struct ctl_var *v;
3239 * If he's trying to write into a peer tell him no way
3241 if (res_associd != 0) {
3242 ctl_error(CERR_PERMISSION);
3249 rpkt.status = htons(ctlsysstatus());
3252 * Look through the variables. Dump out at the first sign of
3255 while ((v = ctl_getitem(sys_var, &valuep)) != 0) {
3257 if (v->flags & EOV) {
3258 if ((v = ctl_getitem(ext_sys_var, &valuep)) !=
3260 if (v->flags & EOV) {
3261 ctl_error(CERR_UNKNOWNVAR);
3269 if (!(v->flags & CAN_WRITE)) {
3270 ctl_error(CERR_PERMISSION);
3273 if (!ext_var && (*valuep == '\0' || !atoint(valuep,
3275 ctl_error(CERR_BADFMT);
3278 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) {
3279 ctl_error(CERR_BADVALUE);
3284 octets = strlen(v->text) + strlen(valuep) + 2;
3285 vareqv = emalloc(octets);
3288 while (*t && *t != '=')
3291 memcpy(tt, valuep, 1 + strlen(valuep));
3292 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3295 ctl_error(CERR_UNSPEC); /* really */
3301 * If we got anything, do it. xxx nothing to do ***
3304 if (leapind != ~0 || leapwarn != ~0) {
3305 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3306 ctl_error(CERR_PERMISSION);
3316 * configure() processes ntpq :config/config-from-file, allowing
3317 * generic runtime reconfiguration.
3319 static void configure(
3320 struct recvbuf *rbufp,
3327 /* I haven't yet implemented changes to an existing association.
3328 * Hence check if the association id is 0
3330 if (res_associd != 0) {
3331 ctl_error(CERR_BADVALUE);
3335 if (RES_NOMODIFY & restrict_mask) {
3336 snprintf(remote_config.err_msg,
3337 sizeof(remote_config.err_msg),
3338 "runtime configuration prohibited by restrict ... nomodify");
3339 ctl_putdata(remote_config.err_msg,
3340 strlen(remote_config.err_msg), 0);
3344 "runtime config from %s rejected due to nomodify restriction",
3345 stoa(&rbufp->recv_srcadr));
3350 /* Initialize the remote config buffer */
3351 data_count = remoteconfig_cmdlength(reqpt, reqend);
3353 if (data_count > sizeof(remote_config.buffer) - 2) {
3354 snprintf(remote_config.err_msg,
3355 sizeof(remote_config.err_msg),
3356 "runtime configuration failed: request too long");
3357 ctl_putdata(remote_config.err_msg,
3358 strlen(remote_config.err_msg), 0);
3361 "runtime config from %s rejected: request too long",
3362 stoa(&rbufp->recv_srcadr));
3365 /* Bug 2853 -- check if all characters were acceptable */
3366 if (data_count != (size_t)(reqend - reqpt)) {
3367 snprintf(remote_config.err_msg,
3368 sizeof(remote_config.err_msg),
3369 "runtime configuration failed: request contains an unprintable character");
3370 ctl_putdata(remote_config.err_msg,
3371 strlen(remote_config.err_msg), 0);
3374 "runtime config from %s rejected: request contains an unprintable character: %0x",
3375 stoa(&rbufp->recv_srcadr),
3380 memcpy(remote_config.buffer, reqpt, data_count);
3381 /* The buffer has no trailing linefeed or NUL right now. For
3382 * logging, we do not want a newline, so we do that first after
3383 * adding the necessary NUL byte.
3385 remote_config.buffer[data_count] = '\0';
3386 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3387 remote_config.buffer));
3388 msyslog(LOG_NOTICE, "%s config: %s",
3389 stoa(&rbufp->recv_srcadr),
3390 remote_config.buffer);
3392 /* Now we have to make sure there is a NL/NUL sequence at the
3393 * end of the buffer before we parse it.
3395 remote_config.buffer[data_count++] = '\n';
3396 remote_config.buffer[data_count] = '\0';
3397 remote_config.pos = 0;
3398 remote_config.err_pos = 0;
3399 remote_config.no_errors = 0;
3400 config_remotely(&rbufp->recv_srcadr);
3403 * Check if errors were reported. If not, output 'Config
3404 * Succeeded'. Else output the error count. It would be nice
3405 * to output any parser error messages.
3407 if (0 == remote_config.no_errors) {
3408 retval = snprintf(remote_config.err_msg,
3409 sizeof(remote_config.err_msg),
3410 "Config Succeeded");
3412 remote_config.err_pos += retval;
3415 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3418 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3420 if (remote_config.no_errors > 0)
3421 msyslog(LOG_NOTICE, "%d error in %s config",
3422 remote_config.no_errors,
3423 stoa(&rbufp->recv_srcadr));
3428 * derive_nonce - generate client-address-specific nonce value
3429 * associated with a given timestamp.
3431 static u_int32 derive_nonce(
3437 static u_int32 salt[4];
3438 static u_long last_salt_update;
3440 u_char digest[EVP_MAX_MD_SIZE];
3446 while (!salt[0] || current_time - last_salt_update >= 3600) {
3447 salt[0] = ntp_random();
3448 salt[1] = ntp_random();
3449 salt[2] = ntp_random();
3450 salt[3] = ntp_random();
3451 last_salt_update = current_time;
3454 EVP_DigestInit(&ctx, EVP_get_digestbynid(NID_md5));
3455 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3456 EVP_DigestUpdate(&ctx, &ts_i, sizeof(ts_i));
3457 EVP_DigestUpdate(&ctx, &ts_f, sizeof(ts_f));
3459 EVP_DigestUpdate(&ctx, &SOCK_ADDR4(addr),
3460 sizeof(SOCK_ADDR4(addr)));
3462 EVP_DigestUpdate(&ctx, &SOCK_ADDR6(addr),
3463 sizeof(SOCK_ADDR6(addr)));
3464 EVP_DigestUpdate(&ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3465 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3466 EVP_DigestFinal(&ctx, d.digest, &len);
3473 * generate_nonce - generate client-address-specific nonce string.
3475 static void generate_nonce(
3476 struct recvbuf * rbufp,
3483 derived = derive_nonce(&rbufp->recv_srcadr,
3484 rbufp->recv_time.l_ui,
3485 rbufp->recv_time.l_uf);
3486 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3487 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3492 * validate_nonce - validate client-address-specific nonce string.
3494 * Returns TRUE if the local calculation of the nonce matches the
3495 * client-provided value and the timestamp is recent enough.
3497 static int validate_nonce(
3498 const char * pnonce,
3499 struct recvbuf * rbufp
3509 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3512 ts.l_ui = (u_int32)ts_i;
3513 ts.l_uf = (u_int32)ts_f;
3514 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3515 get_systime(&now_delta);
3516 L_SUB(&now_delta, &ts);
3518 return (supposed == derived && now_delta.l_ui < 16);
3523 * send_random_tag_value - send a randomly-generated three character
3524 * tag prefix, a '.', an index, a '=' and a
3525 * random integer value.
3527 * To try to force clients to ignore unrecognized tags in mrulist,
3528 * reslist, and ifstats responses, the first and last rows are spiced
3529 * with randomly-generated tag names with correct .# index. Make it
3530 * three characters knowing that none of the currently-used subscripted
3531 * tags have that length, avoiding the need to test for
3535 send_random_tag_value(
3542 noise = rand() ^ (rand() << 16);
3543 buf[0] = 'a' + noise % 26;
3545 buf[1] = 'a' + noise % 26;
3547 buf[2] = 'a' + noise % 26;
3550 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3551 ctl_putuint(buf, noise);
3556 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3558 * To keep clients honest about not depending on the order of values,
3559 * and thereby avoid being locked into ugly workarounds to maintain
3560 * backward compatibility later as new fields are added to the response,
3561 * the order is random.
3569 const char first_fmt[] = "first.%d";
3570 const char ct_fmt[] = "ct.%d";
3571 const char mv_fmt[] = "mv.%d";
3572 const char rs_fmt[] = "rs.%d";
3574 u_char sent[6]; /* 6 tag=value pairs */
3580 remaining = COUNTOF(sent);
3582 noise = (u_int32)(rand() ^ (rand() << 16));
3583 while (remaining > 0) {
3584 which = (noise & 7) % COUNTOF(sent);
3587 which = (which + 1) % COUNTOF(sent);
3592 snprintf(tag, sizeof(tag), addr_fmt, count);
3593 pch = sptoa(&mon->rmtadr);
3594 ctl_putunqstr(tag, pch, strlen(pch));
3598 snprintf(tag, sizeof(tag), last_fmt, count);
3599 ctl_putts(tag, &mon->last);
3603 snprintf(tag, sizeof(tag), first_fmt, count);
3604 ctl_putts(tag, &mon->first);
3608 snprintf(tag, sizeof(tag), ct_fmt, count);
3609 ctl_putint(tag, mon->count);
3613 snprintf(tag, sizeof(tag), mv_fmt, count);
3614 ctl_putuint(tag, mon->vn_mode);
3618 snprintf(tag, sizeof(tag), rs_fmt, count);
3619 ctl_puthex(tag, mon->flags);
3629 * read_mru_list - supports ntpq's mrulist command.
3631 * The challenge here is to match ntpdc's monlist functionality without
3632 * being limited to hundreds of entries returned total, and without
3633 * requiring state on the server. If state were required, ntpq's
3634 * mrulist command would require authentication.
3636 * The approach was suggested by Ry Jones. A finite and variable number
3637 * of entries are retrieved per request, to avoid having responses with
3638 * such large numbers of packets that socket buffers are overflowed and
3639 * packets lost. The entries are retrieved oldest-first, taking into
3640 * account that the MRU list will be changing between each request. We
3641 * can expect to see duplicate entries for addresses updated in the MRU
3642 * list during the fetch operation. In the end, the client can assemble
3643 * a close approximation of the MRU list at the point in time the last
3644 * response was sent by ntpd. The only difference is it may be longer,
3645 * containing some number of oldest entries which have since been
3646 * reclaimed. If necessary, the protocol could be extended to zap those
3647 * from the client snapshot at the end, but so far that doesn't seem
3650 * To accomodate the changing MRU list, the starting point for requests
3651 * after the first request is supplied as a series of last seen
3652 * timestamps and associated addresses, the newest ones the client has
3653 * received. As long as at least one of those entries hasn't been
3654 * bumped to the head of the MRU list, ntpd can pick up at that point.
3655 * Otherwise, the request is failed and it is up to ntpq to back up and
3656 * provide the next newest entry's timestamps and addresses, conceivably
3657 * backing up all the way to the starting point.
3660 * nonce= Regurgitated nonce retrieved by the client
3661 * previously using CTL_OP_REQ_NONCE, demonstrating
3662 * ability to receive traffic sent to its address.
3663 * frags= Limit on datagrams (fragments) in response. Used
3664 * by newer ntpq versions instead of limit= when
3665 * retrieving multiple entries.
3666 * limit= Limit on MRU entries returned. One of frags= or
3667 * limit= must be provided.
3668 * limit=1 is a special case: Instead of fetching
3669 * beginning with the supplied starting point's
3670 * newer neighbor, fetch the supplied entry, and
3671 * in that case the #.last timestamp can be zero.
3672 * This enables fetching a single entry by IP
3673 * address. When limit is not one and frags= is
3674 * provided, the fragment limit controls.
3675 * mincount= (decimal) Return entries with count >= mincount.
3676 * laddr= Return entries associated with the server's IP
3677 * address given. No port specification is needed,
3678 * and any supplied is ignored.
3679 * resall= 0x-prefixed hex restrict bits which must all be
3680 * lit for an MRU entry to be included.
3681 * Has precedence over any resany=.
3682 * resany= 0x-prefixed hex restrict bits, at least one of
3683 * which must be list for an MRU entry to be
3685 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3686 * which client previously received.
3687 * addr.0= text of newest entry's IP address and port,
3688 * IPv6 addresses in bracketed form: [::]:123
3689 * last.1= timestamp of 2nd newest entry client has.
3690 * addr.1= address of 2nd newest entry.
3693 * ntpq provides as many last/addr pairs as will fit in a single request
3694 * packet, except for the first request in a MRU fetch operation.
3696 * The response begins with a new nonce value to be used for any
3697 * followup request. Following the nonce is the next newer entry than
3698 * referred to by last.0 and addr.0, if the "0" entry has not been
3699 * bumped to the front. If it has, the first entry returned will be the
3700 * next entry newer than referred to by last.1 and addr.1, and so on.
3701 * If none of the referenced entries remain unchanged, the request fails
3702 * and ntpq backs up to the next earlier set of entries to resync.
3704 * Except for the first response, the response begins with confirmation
3705 * of the entry that precedes the first additional entry provided:
3707 * last.older= hex l_fp timestamp matching one of the input
3708 * .last timestamps, which entry now precedes the
3709 * response 0. entry in the MRU list.
3710 * addr.older= text of address corresponding to older.last.
3712 * And in any case, a successful response contains sets of values
3713 * comprising entries, with the oldest numbered 0 and incrementing from
3716 * addr.# text of IPv4 or IPv6 address and port
3717 * last.# hex l_fp timestamp of last receipt
3718 * first.# hex l_fp timestamp of first receipt
3719 * ct.# count of packets received
3720 * mv.# mode and version
3721 * rs.# restriction mask (RES_* bits)
3723 * Note the code currently assumes there are no valid three letter
3724 * tags sent with each row, and needs to be adjusted if that changes.
3726 * The client should accept the values in any order, and ignore .#
3727 * values which it does not understand, to allow a smooth path to
3728 * future changes without requiring a new opcode. Clients can rely
3729 * on all *.0 values preceding any *.1 values, that is all values for
3730 * a given index number are together in the response.
3732 * The end of the response list is noted with one or two tag=value
3733 * pairs. Unconditionally:
3735 * now= 0x-prefixed l_fp timestamp at the server marking
3736 * the end of the operation.
3738 * If any entries were returned, now= is followed by:
3740 * last.newest= hex l_fp identical to last.# of the prior
3743 static void read_mru_list(
3744 struct recvbuf *rbufp,
3748 const char nonce_text[] = "nonce";
3749 const char frags_text[] = "frags";
3750 const char limit_text[] = "limit";
3751 const char mincount_text[] = "mincount";
3752 const char resall_text[] = "resall";
3753 const char resany_text[] = "resany";
3754 const char maxlstint_text[] = "maxlstint";
3755 const char laddr_text[] = "laddr";
3756 const char resaxx_fmt[] = "0x%hx";
3764 struct interface * lcladr;
3769 sockaddr_u addr[COUNTOF(last)];
3771 struct ctl_var * in_parms;
3772 const struct ctl_var * v;
3781 mon_entry * prior_mon;
3784 if (RES_NOMRULIST & restrict_mask) {
3785 ctl_error(CERR_PERMISSION);
3788 "mrulist from %s rejected due to nomrulist restriction",
3789 stoa(&rbufp->recv_srcadr));
3794 * fill in_parms var list with all possible input parameters.
3797 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
3798 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
3799 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
3800 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
3801 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
3802 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
3803 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
3804 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
3805 for (i = 0; i < COUNTOF(last); i++) {
3806 snprintf(buf, sizeof(buf), last_fmt, (int)i);
3807 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3808 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
3809 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3812 /* decode input parms */
3825 while (NULL != (v = ctl_getitem(in_parms, &val)) &&
3826 !(EOV & v->flags)) {
3829 if (!strcmp(nonce_text, v->text)) {
3832 pnonce = estrdup(val);
3833 } else if (!strcmp(frags_text, v->text)) {
3834 sscanf(val, "%hu", &frags);
3835 } else if (!strcmp(limit_text, v->text)) {
3836 sscanf(val, "%u", &limit);
3837 } else if (!strcmp(mincount_text, v->text)) {
3838 if (1 != sscanf(val, "%d", &mincount) ||
3841 } else if (!strcmp(resall_text, v->text)) {
3842 sscanf(val, resaxx_fmt, &resall);
3843 } else if (!strcmp(resany_text, v->text)) {
3844 sscanf(val, resaxx_fmt, &resany);
3845 } else if (!strcmp(maxlstint_text, v->text)) {
3846 sscanf(val, "%u", &maxlstint);
3847 } else if (!strcmp(laddr_text, v->text)) {
3848 if (decodenetnum(val, &laddr))
3849 lcladr = getinterface(&laddr, 0);
3850 } else if (1 == sscanf(v->text, last_fmt, &si) &&
3851 (size_t)si < COUNTOF(last)) {
3852 if (2 == sscanf(val, "0x%08x.%08x", &ui, &uf)) {
3855 if (!SOCK_UNSPEC(&addr[si]) &&
3859 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
3860 (size_t)si < COUNTOF(addr)) {
3861 if (decodenetnum(val, &addr[si])
3862 && last[si].l_ui && last[si].l_uf &&
3867 free_varlist(in_parms);
3870 /* return no responses until the nonce is validated */
3874 nonce_valid = validate_nonce(pnonce, rbufp);
3879 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
3880 frags > MRU_FRAGS_LIMIT) {
3881 ctl_error(CERR_BADVALUE);
3886 * If either frags or limit is not given, use the max.
3888 if (0 != frags && 0 == limit)
3890 else if (0 != limit && 0 == frags)
3891 frags = MRU_FRAGS_LIMIT;
3894 * Find the starting point if one was provided.
3897 for (i = 0; i < (size_t)priors; i++) {
3898 hash = MON_HASH(&addr[i]);
3899 for (mon = mon_hash[hash];
3901 mon = mon->hash_next)
3902 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
3905 if (L_ISEQU(&mon->last, &last[i]))
3911 /* If a starting point was provided... */
3913 /* and none could be found unmodified... */
3915 /* tell ntpq to try again with older entries */
3916 ctl_error(CERR_UNKNOWNVAR);
3919 /* confirm the prior entry used as starting point */
3920 ctl_putts("last.older", &mon->last);
3921 pch = sptoa(&mon->rmtadr);
3922 ctl_putunqstr("addr.older", pch, strlen(pch));
3925 * Move on to the first entry the client doesn't have,
3926 * except in the special case of a limit of one. In
3927 * that case return the starting point entry.
3930 mon = PREV_DLIST(mon_mru_list, mon, mru);
3931 } else { /* start with the oldest */
3932 mon = TAIL_DLIST(mon_mru_list, mru);
3936 * send up to limit= entries in up to frags= datagrams
3939 generate_nonce(rbufp, buf, sizeof(buf));
3940 ctl_putunqstr("nonce", buf, strlen(buf));
3943 mon != NULL && res_frags < frags && count < limit;
3944 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
3946 if (mon->count < mincount)
3948 if (resall && resall != (resall & mon->flags))
3950 if (resany && !(resany & mon->flags))
3952 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
3955 if (lcladr != NULL && mon->lcladr != lcladr)
3958 send_mru_entry(mon, count);
3960 send_random_tag_value(0);
3966 * If this batch completes the MRU list, say so explicitly with
3967 * a now= l_fp timestamp.
3971 send_random_tag_value(count - 1);
3972 ctl_putts("now", &now);
3973 /* if any entries were returned confirm the last */
3974 if (prior_mon != NULL)
3975 ctl_putts("last.newest", &prior_mon->last);
3982 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
3984 * To keep clients honest about not depending on the order of values,
3985 * and thereby avoid being locked into ugly workarounds to maintain
3986 * backward compatibility later as new fields are added to the response,
3987 * the order is random.
3995 const char addr_fmtu[] = "addr.%u";
3996 const char bcast_fmt[] = "bcast.%u";
3997 const char en_fmt[] = "en.%u"; /* enabled */
3998 const char name_fmt[] = "name.%u";
3999 const char flags_fmt[] = "flags.%u";
4000 const char tl_fmt[] = "tl.%u"; /* ttl */
4001 const char mc_fmt[] = "mc.%u"; /* mcast count */
4002 const char rx_fmt[] = "rx.%u";
4003 const char tx_fmt[] = "tx.%u";
4004 const char txerr_fmt[] = "txerr.%u";
4005 const char pc_fmt[] = "pc.%u"; /* peer count */
4006 const char up_fmt[] = "up.%u"; /* uptime */
4008 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4015 remaining = COUNTOF(sent);
4019 while (remaining > 0) {
4020 if (noisebits < 4) {
4021 noise = rand() ^ (rand() << 16);
4024 which = (noise & 0xf) % COUNTOF(sent);
4029 which = (which + 1) % COUNTOF(sent);
4034 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4035 pch = sptoa(&la->sin);
4036 ctl_putunqstr(tag, pch, strlen(pch));
4040 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4041 if (INT_BCASTOPEN & la->flags)
4042 pch = sptoa(&la->bcast);
4045 ctl_putunqstr(tag, pch, strlen(pch));
4049 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4050 ctl_putint(tag, !la->ignore_packets);
4054 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4055 ctl_putstr(tag, la->name, strlen(la->name));
4059 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4060 ctl_puthex(tag, (u_int)la->flags);
4064 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4065 ctl_putint(tag, la->last_ttl);
4069 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4070 ctl_putint(tag, la->num_mcast);
4074 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4075 ctl_putint(tag, la->received);
4079 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4080 ctl_putint(tag, la->sent);
4084 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4085 ctl_putint(tag, la->notsent);
4089 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4090 ctl_putuint(tag, la->peercnt);
4094 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4095 ctl_putuint(tag, current_time - la->starttime);
4101 send_random_tag_value((int)ifnum);
4106 * read_ifstats - send statistics for each local address, exposed by
4111 struct recvbuf * rbufp
4118 * loop over [0..sys_ifnum] searching ep_list for each
4121 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4122 for (la = ep_list; la != NULL; la = la->elink)
4123 if (ifidx == la->ifnum)
4127 /* return stats for one local address */
4128 send_ifstats_entry(la, ifidx);
4134 sockaddrs_from_restrict_u(
4144 psaA->sa.sa_family = AF_INET;
4145 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4146 psaM->sa.sa_family = AF_INET;
4147 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4149 psaA->sa.sa_family = AF_INET6;
4150 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4151 sizeof(psaA->sa6.sin6_addr));
4152 psaM->sa.sa_family = AF_INET6;
4153 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4154 sizeof(psaA->sa6.sin6_addr));
4160 * Send a restrict entry in response to a "ntpq -c reslist" request.
4162 * To keep clients honest about not depending on the order of values,
4163 * and thereby avoid being locked into ugly workarounds to maintain
4164 * backward compatibility later as new fields are added to the response,
4165 * the order is random.
4168 send_restrict_entry(
4174 const char addr_fmtu[] = "addr.%u";
4175 const char mask_fmtu[] = "mask.%u";
4176 const char hits_fmt[] = "hits.%u";
4177 const char flags_fmt[] = "flags.%u";
4179 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4188 const char * match_str;
4189 const char * access_str;
4191 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4192 remaining = COUNTOF(sent);
4196 while (remaining > 0) {
4197 if (noisebits < 2) {
4198 noise = rand() ^ (rand() << 16);
4201 which = (noise & 0x3) % COUNTOF(sent);
4206 which = (which + 1) % COUNTOF(sent);
4211 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4213 ctl_putunqstr(tag, pch, strlen(pch));
4217 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4219 ctl_putunqstr(tag, pch, strlen(pch));
4223 snprintf(tag, sizeof(tag), hits_fmt, idx);
4224 ctl_putuint(tag, pres->count);
4228 snprintf(tag, sizeof(tag), flags_fmt, idx);
4229 match_str = res_match_flags(pres->mflags);
4230 access_str = res_access_flags(pres->flags);
4231 if ('\0' == match_str[0]) {
4235 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4236 match_str, access_str);
4239 ctl_putunqstr(tag, pch, strlen(pch));
4245 send_random_tag_value((int)idx);
4256 for ( ; pres != NULL; pres = pres->link) {
4257 send_restrict_entry(pres, ipv6, *pidx);
4264 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4267 read_addr_restrictions(
4268 struct recvbuf * rbufp
4274 send_restrict_list(restrictlist4, FALSE, &idx);
4275 send_restrict_list(restrictlist6, TRUE, &idx);
4281 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4285 struct recvbuf * rbufp,
4289 const char ifstats_s[] = "ifstats";
4290 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4291 const char addr_rst_s[] = "addr_restrictions";
4292 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4293 struct ntp_control * cpkt;
4294 u_short qdata_octets;
4297 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4298 * used only for ntpq -c ifstats. With the addition of reslist
4299 * the same opcode was generalized to retrieve ordered lists
4300 * which require authentication. The request data is empty or
4301 * contains "ifstats" (not null terminated) to retrieve local
4302 * addresses and associated stats. It is "addr_restrictions"
4303 * to retrieve the IPv4 then IPv6 remote address restrictions,
4304 * which are access control lists. Other request data return
4307 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4308 qdata_octets = ntohs(cpkt->count);
4309 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4310 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4311 read_ifstats(rbufp);
4314 if (a_r_chars == qdata_octets &&
4315 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4316 read_addr_restrictions(rbufp);
4319 ctl_error(CERR_UNKNOWNVAR);
4324 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4326 static void req_nonce(
4327 struct recvbuf * rbufp,
4333 generate_nonce(rbufp, buf, sizeof(buf));
4334 ctl_putunqstr("nonce", buf, strlen(buf));
4340 * read_clockstatus - return clock radio status
4345 struct recvbuf *rbufp,
4351 * If no refclock support, no data to return
4353 ctl_error(CERR_BADASSOC);
4355 const struct ctl_var * v;
4363 struct ctl_var * kv;
4364 struct refclockstat cs;
4366 if (res_associd != 0) {
4367 peer = findpeerbyassoc(res_associd);
4370 * Find a clock for this jerk. If the system peer
4371 * is a clock use it, else search peer_list for one.
4373 if (sys_peer != NULL && (FLAG_REFCLOCK &
4377 for (peer = peer_list;
4379 peer = peer->p_link)
4380 if (FLAG_REFCLOCK & peer->flags)
4383 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4384 ctl_error(CERR_BADASSOC);
4388 * If we got here we have a peer which is a clock. Get his
4392 refclock_control(&peer->srcadr, NULL, &cs);
4395 * Look for variables in the packet.
4397 rpkt.status = htons(ctlclkstatus(&cs));
4398 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4399 wants = emalloc_zero(wants_alloc);
4401 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4402 if (!(EOV & v->flags)) {
4403 wants[v->code] = TRUE;
4406 v = ctl_getitem(kv, &valuep);
4407 NTP_INSIST(NULL != v);
4408 if (EOV & v->flags) {
4409 ctl_error(CERR_UNKNOWNVAR);
4411 free_varlist(cs.kv_list);
4414 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4420 for (i = 1; i <= CC_MAXCODE; i++)
4422 ctl_putclock(i, &cs, TRUE);
4424 for (i = 0; !(EOV & kv[i].flags); i++)
4425 if (wants[i + CC_MAXCODE + 1])
4426 ctl_putdata(kv[i].text,
4430 for (cc = def_clock_var; *cc != 0; cc++)
4431 ctl_putclock((int)*cc, &cs, FALSE);
4432 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4433 if (DEF & kv->flags)
4434 ctl_putdata(kv->text, strlen(kv->text),
4439 free_varlist(cs.kv_list);
4447 * write_clockstatus - we don't do this
4452 struct recvbuf *rbufp,
4456 ctl_error(CERR_PERMISSION);
4460 * Trap support from here on down. We send async trap messages when the
4461 * upper levels report trouble. Traps can by set either by control
4462 * messages or by configuration.
4465 * set_trap - set a trap in response to a control message
4469 struct recvbuf *rbufp,
4476 * See if this guy is allowed
4478 if (restrict_mask & RES_NOTRAP) {
4479 ctl_error(CERR_PERMISSION);
4484 * Determine his allowed trap type.
4486 traptype = TRAP_TYPE_PRIO;
4487 if (restrict_mask & RES_LPTRAP)
4488 traptype = TRAP_TYPE_NONPRIO;
4491 * Call ctlsettrap() to do the work. Return
4492 * an error if it can't assign the trap.
4494 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4496 ctl_error(CERR_NORESOURCE);
4502 * unset_trap - unset a trap in response to a control message
4506 struct recvbuf *rbufp,
4513 * We don't prevent anyone from removing his own trap unless the
4514 * trap is configured. Note we also must be aware of the
4515 * possibility that restriction flags were changed since this
4516 * guy last set his trap. Set the trap type based on this.
4518 traptype = TRAP_TYPE_PRIO;
4519 if (restrict_mask & RES_LPTRAP)
4520 traptype = TRAP_TYPE_NONPRIO;
4523 * Call ctlclrtrap() to clear this out.
4525 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4526 ctl_error(CERR_BADASSOC);
4532 * ctlsettrap - called to set a trap
4537 struct interface *linter,
4543 struct ctl_trap *tp;
4544 struct ctl_trap *tptouse;
4547 * See if we can find this trap. If so, we only need update
4548 * the flags and the time.
4550 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4553 case TRAP_TYPE_CONFIG:
4554 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4557 case TRAP_TYPE_PRIO:
4558 if (tp->tr_flags & TRAP_CONFIGURED)
4559 return (1); /* don't change anything */
4560 tp->tr_flags = TRAP_INUSE;
4563 case TRAP_TYPE_NONPRIO:
4564 if (tp->tr_flags & TRAP_CONFIGURED)
4565 return (1); /* don't change anything */
4566 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4569 tp->tr_settime = current_time;
4575 * First we heard of this guy. Try to find a trap structure
4576 * for him to use, clearing out lesser priority guys if we
4577 * have to. Clear out anyone who's expired while we're at it.
4580 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4582 if ((TRAP_INUSE & tp->tr_flags) &&
4583 !(TRAP_CONFIGURED & tp->tr_flags) &&
4584 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4588 if (!(TRAP_INUSE & tp->tr_flags)) {
4590 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4593 case TRAP_TYPE_CONFIG:
4594 if (tptouse == NULL) {
4598 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4599 !(TRAP_NONPRIO & tp->tr_flags))
4602 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4603 && (TRAP_NONPRIO & tp->tr_flags)) {
4607 if (tptouse->tr_origtime <
4612 case TRAP_TYPE_PRIO:
4613 if ( TRAP_NONPRIO & tp->tr_flags) {
4614 if (tptouse == NULL ||
4616 tptouse->tr_flags) &&
4617 tptouse->tr_origtime <
4623 case TRAP_TYPE_NONPRIO:
4630 * If we don't have room for him return an error.
4632 if (tptouse == NULL)
4636 * Set up this structure for him.
4638 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4639 tptouse->tr_count = tptouse->tr_resets = 0;
4640 tptouse->tr_sequence = 1;
4641 tptouse->tr_addr = *raddr;
4642 tptouse->tr_localaddr = linter;
4643 tptouse->tr_version = (u_char) version;
4644 tptouse->tr_flags = TRAP_INUSE;
4645 if (traptype == TRAP_TYPE_CONFIG)
4646 tptouse->tr_flags |= TRAP_CONFIGURED;
4647 else if (traptype == TRAP_TYPE_NONPRIO)
4648 tptouse->tr_flags |= TRAP_NONPRIO;
4655 * ctlclrtrap - called to clear a trap
4660 struct interface *linter,
4664 register struct ctl_trap *tp;
4666 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4669 if (tp->tr_flags & TRAP_CONFIGURED
4670 && traptype != TRAP_TYPE_CONFIG)
4680 * ctlfindtrap - find a trap given the remote and local addresses
4682 static struct ctl_trap *
4685 struct interface *linter
4690 for (n = 0; n < COUNTOF(ctl_traps); n++)
4691 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4692 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4693 && (linter == ctl_traps[n].tr_localaddr))
4694 return &ctl_traps[n];
4701 * report_event - report an event to the trappers
4705 int err, /* error code */
4706 struct peer *peer, /* peer structure pointer */
4707 const char *str /* protostats string */
4710 char statstr[NTP_MAXSTRLEN];
4715 * Report the error to the protostats file, system log and
4721 * Discard a system report if the number of reports of
4722 * the same type exceeds the maximum.
4724 if (ctl_sys_last_event != (u_char)err)
4725 ctl_sys_num_events= 0;
4726 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4729 ctl_sys_last_event = (u_char)err;
4730 ctl_sys_num_events++;
4731 snprintf(statstr, sizeof(statstr),
4732 "0.0.0.0 %04x %02x %s",
4733 ctlsysstatus(), err, eventstr(err));
4735 len = strlen(statstr);
4736 snprintf(statstr + len, sizeof(statstr) - len,
4740 msyslog(LOG_INFO, "%s", statstr);
4744 * Discard a peer report if the number of reports of
4745 * the same type exceeds the maximum for that peer.
4750 errlast = (u_char)err & ~PEER_EVENT;
4751 if (peer->last_event == errlast)
4752 peer->num_events = 0;
4753 if (peer->num_events >= CTL_PEER_MAXEVENTS)
4756 peer->last_event = errlast;
4758 if (ISREFCLOCKADR(&peer->srcadr))
4759 src = refnumtoa(&peer->srcadr);
4761 src = stoa(&peer->srcadr);
4763 snprintf(statstr, sizeof(statstr),
4764 "%s %04x %02x %s", src,
4765 ctlpeerstatus(peer), err, eventstr(err));
4767 len = strlen(statstr);
4768 snprintf(statstr + len, sizeof(statstr) - len,
4771 NLOG(NLOG_PEEREVENT)
4772 msyslog(LOG_INFO, "%s", statstr);
4774 record_proto_stats(statstr);
4777 printf("event at %lu %s\n", current_time, statstr);
4781 * If no trappers, return.
4783 if (num_ctl_traps <= 0)
4787 * Set up the outgoing packet variables
4789 res_opcode = CTL_OP_ASYNCMSG;
4792 res_authenticate = FALSE;
4793 datapt = rpkt.u.data;
4794 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
4795 if (!(err & PEER_EVENT)) {
4797 rpkt.status = htons(ctlsysstatus());
4799 /* Include the core system variables and the list. */
4800 for (i = 1; i <= CS_VARLIST; i++)
4803 NTP_INSIST(peer != NULL);
4804 rpkt.associd = htons(peer->associd);
4805 rpkt.status = htons(ctlpeerstatus(peer));
4807 /* Dump it all. Later, maybe less. */
4808 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
4809 ctl_putpeer(i, peer);
4812 * for clock exception events: add clock variables to
4813 * reflect info on exception
4815 if (err == PEVNT_CLOCK) {
4816 struct refclockstat cs;
4820 refclock_control(&peer->srcadr, NULL, &cs);
4822 ctl_puthex("refclockstatus",
4825 for (i = 1; i <= CC_MAXCODE; i++)
4826 ctl_putclock(i, &cs, FALSE);
4827 for (kv = cs.kv_list;
4828 kv != NULL && !(EOV & kv->flags);
4830 if (DEF & kv->flags)
4831 ctl_putdata(kv->text,
4834 free_varlist(cs.kv_list);
4836 #endif /* REFCLOCK */
4840 * We're done, return.
4847 * mprintf_event - printf-style varargs variant of report_event()
4851 int evcode, /* event code */
4852 struct peer * p, /* may be NULL */
4853 const char * fmt, /* msnprintf format */
4862 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
4864 report_event(evcode, p, msg);
4871 * ctl_clr_stats - clear stat counters
4876 ctltimereset = current_time;
4879 numctlresponses = 0;
4884 numctlinputresp = 0;
4885 numctlinputfrag = 0;
4887 numctlbadoffset = 0;
4888 numctlbadversion = 0;
4889 numctldatatooshort = 0;
4896 const struct ctl_var *k
4905 while (!(EOV & (k++)->flags))
4908 NTP_ENSURE(c <= USHRT_MAX);
4915 struct ctl_var **kv,
4925 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
4927 buf = emalloc(size);
4932 k[c + 1].text = NULL;
4933 k[c + 1].flags = EOV;
4941 struct ctl_var **kv,
4952 if (NULL == data || !size)
4957 while (!(EOV & k->flags)) {
4958 if (NULL == k->text) {
4960 memcpy(td, data, size);
4967 while (*t != '=' && *s == *t) {
4971 if (*s == *t && ((*t == '=') || !*t)) {
4972 td = erealloc((void *)(intptr_t)k->text, size);
4973 memcpy(td, data, size);
4982 td = add_var(kv, size, def);
4983 memcpy(td, data, size);
4994 set_var(&ext_sys_var, data, size, def);
4999 * get_ext_sys_var() retrieves the value of a user-defined variable or
5000 * NULL if the variable has not been setvar'd.
5003 get_ext_sys_var(const char *tag)
5011 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5012 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5013 if ('=' == v->text[c]) {
5014 val = v->text + c + 1;
5016 } else if ('\0' == v->text[c]) {
5034 for (k = kv; !(k->flags & EOV); k++)
5035 free((void *)(intptr_t)k->text);