2 * ntp_control.c - respond to mode 6 control messages and send async
3 * traps. Provides service to ntpq and others.
14 #ifdef HAVE_NETINET_IN_H
15 # include <netinet/in.h>
17 #include <arpa/inet.h>
21 #include "ntp_refclock.h"
22 #include "ntp_control.h"
23 #include "ntp_unixtime.h"
24 #include "ntp_stdlib.h"
25 #include "ntp_config.h"
26 #include "ntp_crypto.h"
27 #include "ntp_assert.h"
28 #include "ntp_leapsec.h"
29 #include "ntp_md5.h" /* provides OpenSSL digest API */
30 #include "lib_strbuf.h"
31 #include <rc_cmdlength.h>
33 # include "ntp_syscall.h"
38 * Structure to hold request procedure information
42 short control_code; /* defined request code */
43 #define NO_REQUEST (-1)
44 u_short flags; /* flags word */
45 /* Only one flag. Authentication required or not. */
48 void (*handler) (struct recvbuf *, int); /* handle request */
53 * Request processing routines
55 static void ctl_error (u_char);
57 static u_short ctlclkstatus (struct refclockstat *);
59 static void ctl_flushpkt (u_char);
60 static void ctl_putdata (const char *, unsigned int, int);
61 static void ctl_putstr (const char *, const char *, size_t);
62 static void ctl_putdblf (const char *, int, int, double);
63 #define ctl_putdbl(tag, d) ctl_putdblf(tag, 1, 3, d)
64 #define ctl_putdbl6(tag, d) ctl_putdblf(tag, 1, 6, d)
65 #define ctl_putsfp(tag, sfp) ctl_putdblf(tag, 0, -1, \
67 static void ctl_putuint (const char *, u_long);
68 static void ctl_puthex (const char *, u_long);
69 static void ctl_putint (const char *, long);
70 static void ctl_putts (const char *, l_fp *);
71 static void ctl_putadr (const char *, u_int32,
73 static void ctl_putrefid (const char *, u_int32);
74 static void ctl_putarray (const char *, double *, int);
75 static void ctl_putsys (int);
76 static void ctl_putpeer (int, struct peer *);
77 static void ctl_putfs (const char *, tstamp_t);
79 static void ctl_putclock (int, struct refclockstat *, int);
81 static const struct ctl_var *ctl_getitem(const struct ctl_var *,
83 static u_short count_var (const struct ctl_var *);
84 static void control_unspec (struct recvbuf *, int);
85 static void read_status (struct recvbuf *, int);
86 static void read_sysvars (void);
87 static void read_peervars (void);
88 static void read_variables (struct recvbuf *, int);
89 static void write_variables (struct recvbuf *, int);
90 static void read_clockstatus(struct recvbuf *, int);
91 static void write_clockstatus(struct recvbuf *, int);
92 static void set_trap (struct recvbuf *, int);
93 static void save_config (struct recvbuf *, int);
94 static void configure (struct recvbuf *, int);
95 static void send_mru_entry (mon_entry *, int);
96 static void send_random_tag_value(int);
97 static void read_mru_list (struct recvbuf *, int);
98 static void send_ifstats_entry(endpt *, u_int);
99 static void read_ifstats (struct recvbuf *);
100 static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *,
102 static void send_restrict_entry(restrict_u *, int, u_int);
103 static void send_restrict_list(restrict_u *, int, u_int *);
104 static void read_addr_restrictions(struct recvbuf *);
105 static void read_ordlist (struct recvbuf *, int);
106 static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32);
107 static void generate_nonce (struct recvbuf *, char *, size_t);
108 static int validate_nonce (const char *, struct recvbuf *);
109 static void req_nonce (struct recvbuf *, int);
110 static void unset_trap (struct recvbuf *, int);
111 static struct ctl_trap *ctlfindtrap(sockaddr_u *,
114 static const struct ctl_proc control_codes[] = {
115 { CTL_OP_UNSPEC, NOAUTH, control_unspec },
116 { CTL_OP_READSTAT, NOAUTH, read_status },
117 { CTL_OP_READVAR, NOAUTH, read_variables },
118 { CTL_OP_WRITEVAR, AUTH, write_variables },
119 { CTL_OP_READCLOCK, NOAUTH, read_clockstatus },
120 { CTL_OP_WRITECLOCK, NOAUTH, write_clockstatus },
121 { CTL_OP_SETTRAP, NOAUTH, set_trap },
122 { CTL_OP_CONFIGURE, AUTH, configure },
123 { CTL_OP_SAVECONFIG, AUTH, save_config },
124 { CTL_OP_READ_MRU, NOAUTH, read_mru_list },
125 { CTL_OP_READ_ORDLIST_A, AUTH, read_ordlist },
126 { CTL_OP_REQ_NONCE, NOAUTH, req_nonce },
127 { CTL_OP_UNSETTRAP, NOAUTH, unset_trap },
128 { NO_REQUEST, 0, NULL }
132 * System variables we understand
136 #define CS_PRECISION 3
137 #define CS_ROOTDELAY 4
138 #define CS_ROOTDISPERSION 5
148 #define CS_PROCESSOR 15
150 #define CS_VERSION 17
152 #define CS_VARLIST 19
154 #define CS_LEAPTAB 21
155 #define CS_LEAPEND 22
157 #define CS_MRU_ENABLED 24
158 #define CS_MRU_DEPTH 25
159 #define CS_MRU_DEEPEST 26
160 #define CS_MRU_MINDEPTH 27
161 #define CS_MRU_MAXAGE 28
162 #define CS_MRU_MAXDEPTH 29
163 #define CS_MRU_MEM 30
164 #define CS_MRU_MAXMEM 31
165 #define CS_SS_UPTIME 32
166 #define CS_SS_RESET 33
167 #define CS_SS_RECEIVED 34
168 #define CS_SS_THISVER 35
169 #define CS_SS_OLDVER 36
170 #define CS_SS_BADFORMAT 37
171 #define CS_SS_BADAUTH 38
172 #define CS_SS_DECLINED 39
173 #define CS_SS_RESTRICTED 40
174 #define CS_SS_LIMITED 41
175 #define CS_SS_KODSENT 42
176 #define CS_SS_PROCESSED 43
177 #define CS_PEERADR 44
178 #define CS_PEERMODE 45
179 #define CS_BCASTDELAY 46
180 #define CS_AUTHDELAY 47
181 #define CS_AUTHKEYS 48
182 #define CS_AUTHFREEK 49
183 #define CS_AUTHKLOOKUPS 50
184 #define CS_AUTHKNOTFOUND 51
185 #define CS_AUTHKUNCACHED 52
186 #define CS_AUTHKEXPIRED 53
187 #define CS_AUTHENCRYPTS 54
188 #define CS_AUTHDECRYPTS 55
189 #define CS_AUTHRESET 56
190 #define CS_K_OFFSET 57
192 #define CS_K_MAXERR 59
193 #define CS_K_ESTERR 60
194 #define CS_K_STFLAGS 61
195 #define CS_K_TIMECONST 62
196 #define CS_K_PRECISION 63
197 #define CS_K_FREQTOL 64
198 #define CS_K_PPS_FREQ 65
199 #define CS_K_PPS_STABIL 66
200 #define CS_K_PPS_JITTER 67
201 #define CS_K_PPS_CALIBDUR 68
202 #define CS_K_PPS_CALIBS 69
203 #define CS_K_PPS_CALIBERRS 70
204 #define CS_K_PPS_JITEXC 71
205 #define CS_K_PPS_STBEXC 72
206 #define CS_KERN_FIRST CS_K_OFFSET
207 #define CS_KERN_LAST CS_K_PPS_STBEXC
208 #define CS_IOSTATS_RESET 73
209 #define CS_TOTAL_RBUF 74
210 #define CS_FREE_RBUF 75
211 #define CS_USED_RBUF 76
212 #define CS_RBUF_LOWATER 77
213 #define CS_IO_DROPPED 78
214 #define CS_IO_IGNORED 79
215 #define CS_IO_RECEIVED 80
216 #define CS_IO_SENT 81
217 #define CS_IO_SENDFAILED 82
218 #define CS_IO_WAKEUPS 83
219 #define CS_IO_GOODWAKEUPS 84
220 #define CS_TIMERSTATS_RESET 85
221 #define CS_TIMER_OVERRUNS 86
222 #define CS_TIMER_XMTS 87
224 #define CS_WANDER_THRESH 89
225 #define CS_LEAPSMEARINTV 90
226 #define CS_LEAPSMEAROFFS 91
227 #define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS
229 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
230 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
231 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
232 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
233 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
234 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
235 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
236 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
237 #define CS_MAXCODE CS_DIGEST
238 #else /* !AUTOKEY follows */
239 #define CS_MAXCODE CS_MAX_NOAUTOKEY
240 #endif /* !AUTOKEY */
243 * Peer variables we understand
246 #define CP_AUTHENABLE 2
247 #define CP_AUTHENTIC 3
254 #define CP_STRATUM 10
257 #define CP_PRECISION 13
258 #define CP_ROOTDELAY 14
259 #define CP_ROOTDISPERSION 15
261 #define CP_REFTIME 17
266 #define CP_UNREACH 22
271 #define CP_DISPERSION 27
273 #define CP_FILTDELAY 29
274 #define CP_FILTOFFSET 30
276 #define CP_RECEIVED 32
278 #define CP_FILTERROR 34
281 #define CP_VARLIST 37
286 #define CP_SRCHOST 42
287 #define CP_TIMEREC 43
288 #define CP_TIMEREACH 44
289 #define CP_BADAUTH 45
290 #define CP_BOGUSORG 46
292 #define CP_SELDISP 48
293 #define CP_SELBROKEN 49
294 #define CP_CANDIDATE 50
295 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
297 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
298 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
299 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
300 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
301 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
302 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
303 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
304 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
305 #define CP_MAXCODE CP_IDENT
306 #else /* !AUTOKEY follows */
307 #define CP_MAXCODE CP_MAX_NOAUTOKEY
308 #endif /* !AUTOKEY */
311 * Clock variables we understand
314 #define CC_TIMECODE 2
317 #define CC_BADFORMAT 5
319 #define CC_FUDGETIME1 7
320 #define CC_FUDGETIME2 8
321 #define CC_FUDGEVAL1 9
322 #define CC_FUDGEVAL2 10
325 #define CC_VARLIST 13
326 #define CC_MAXCODE CC_VARLIST
329 * System variable values. The array can be indexed by the variable
330 * index to find the textual name.
332 static const struct ctl_var sys_var[] = {
333 { 0, PADDING, "" }, /* 0 */
334 { CS_LEAP, RW, "leap" }, /* 1 */
335 { CS_STRATUM, RO, "stratum" }, /* 2 */
336 { CS_PRECISION, RO, "precision" }, /* 3 */
337 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
338 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
339 { CS_REFID, RO, "refid" }, /* 6 */
340 { CS_REFTIME, RO, "reftime" }, /* 7 */
341 { CS_POLL, RO, "tc" }, /* 8 */
342 { CS_PEERID, RO, "peer" }, /* 9 */
343 { CS_OFFSET, RO, "offset" }, /* 10 */
344 { CS_DRIFT, RO, "frequency" }, /* 11 */
345 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
346 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
347 { CS_CLOCK, RO, "clock" }, /* 14 */
348 { CS_PROCESSOR, RO, "processor" }, /* 15 */
349 { CS_SYSTEM, RO, "system" }, /* 16 */
350 { CS_VERSION, RO, "version" }, /* 17 */
351 { CS_STABIL, RO, "clk_wander" }, /* 18 */
352 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
353 { CS_TAI, RO, "tai" }, /* 20 */
354 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
355 { CS_LEAPEND, RO, "expire" }, /* 22 */
356 { CS_RATE, RO, "mintc" }, /* 23 */
357 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
358 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
359 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
360 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
361 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
362 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
363 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
364 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
365 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
366 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
367 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
368 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
369 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
370 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
371 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
372 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
373 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
374 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
375 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
376 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
377 { CS_PEERADR, RO, "peeradr" }, /* 44 */
378 { CS_PEERMODE, RO, "peermode" }, /* 45 */
379 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 46 */
380 { CS_AUTHDELAY, RO, "authdelay" }, /* 47 */
381 { CS_AUTHKEYS, RO, "authkeys" }, /* 48 */
382 { CS_AUTHFREEK, RO, "authfreek" }, /* 49 */
383 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 50 */
384 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 51 */
385 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 52 */
386 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 53 */
387 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 54 */
388 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 55 */
389 { CS_AUTHRESET, RO, "authreset" }, /* 56 */
390 { CS_K_OFFSET, RO, "koffset" }, /* 57 */
391 { CS_K_FREQ, RO, "kfreq" }, /* 58 */
392 { CS_K_MAXERR, RO, "kmaxerr" }, /* 59 */
393 { CS_K_ESTERR, RO, "kesterr" }, /* 60 */
394 { CS_K_STFLAGS, RO, "kstflags" }, /* 61 */
395 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 62 */
396 { CS_K_PRECISION, RO, "kprecis" }, /* 63 */
397 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 64 */
398 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 65 */
399 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 66 */
400 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 67 */
401 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 68 */
402 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 69 */
403 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 70 */
404 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 71 */
405 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 72 */
406 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 73 */
407 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 74 */
408 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 75 */
409 { CS_USED_RBUF, RO, "used_rbuf" }, /* 76 */
410 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 77 */
411 { CS_IO_DROPPED, RO, "io_dropped" }, /* 78 */
412 { CS_IO_IGNORED, RO, "io_ignored" }, /* 79 */
413 { CS_IO_RECEIVED, RO, "io_received" }, /* 80 */
414 { CS_IO_SENT, RO, "io_sent" }, /* 81 */
415 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 82 */
416 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 83 */
417 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 84 */
418 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 85 */
419 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 86 */
420 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 87 */
421 { CS_FUZZ, RO, "fuzz" }, /* 88 */
422 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 89 */
424 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 90 */
425 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 91 */
428 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
429 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
430 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
431 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
432 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
433 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
434 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
435 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
437 { 0, EOV, "" } /* 87/95 */
440 static struct ctl_var *ext_sys_var = NULL;
443 * System variables we print by default (in fuzzball order,
446 static const u_char def_sys_var[] = {
487 static const struct ctl_var peer_var[] = {
488 { 0, PADDING, "" }, /* 0 */
489 { CP_CONFIG, RO, "config" }, /* 1 */
490 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
491 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
492 { CP_SRCADR, RO, "srcadr" }, /* 4 */
493 { CP_SRCPORT, RO, "srcport" }, /* 5 */
494 { CP_DSTADR, RO, "dstadr" }, /* 6 */
495 { CP_DSTPORT, RO, "dstport" }, /* 7 */
496 { CP_LEAP, RO, "leap" }, /* 8 */
497 { CP_HMODE, RO, "hmode" }, /* 9 */
498 { CP_STRATUM, RO, "stratum" }, /* 10 */
499 { CP_PPOLL, RO, "ppoll" }, /* 11 */
500 { CP_HPOLL, RO, "hpoll" }, /* 12 */
501 { CP_PRECISION, RO, "precision" }, /* 13 */
502 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
503 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
504 { CP_REFID, RO, "refid" }, /* 16 */
505 { CP_REFTIME, RO, "reftime" }, /* 17 */
506 { CP_ORG, RO, "org" }, /* 18 */
507 { CP_REC, RO, "rec" }, /* 19 */
508 { CP_XMT, RO, "xleave" }, /* 20 */
509 { CP_REACH, RO, "reach" }, /* 21 */
510 { CP_UNREACH, RO, "unreach" }, /* 22 */
511 { CP_TIMER, RO, "timer" }, /* 23 */
512 { CP_DELAY, RO, "delay" }, /* 24 */
513 { CP_OFFSET, RO, "offset" }, /* 25 */
514 { CP_JITTER, RO, "jitter" }, /* 26 */
515 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
516 { CP_KEYID, RO, "keyid" }, /* 28 */
517 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
518 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
519 { CP_PMODE, RO, "pmode" }, /* 31 */
520 { CP_RECEIVED, RO, "received"}, /* 32 */
521 { CP_SENT, RO, "sent" }, /* 33 */
522 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
523 { CP_FLASH, RO, "flash" }, /* 35 */
524 { CP_TTL, RO, "ttl" }, /* 36 */
525 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
526 { CP_IN, RO, "in" }, /* 38 */
527 { CP_OUT, RO, "out" }, /* 39 */
528 { CP_RATE, RO, "headway" }, /* 40 */
529 { CP_BIAS, RO, "bias" }, /* 41 */
530 { CP_SRCHOST, RO, "srchost" }, /* 42 */
531 { CP_TIMEREC, RO, "timerec" }, /* 43 */
532 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
533 { CP_BADAUTH, RO, "badauth" }, /* 45 */
534 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
535 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
536 { CP_SELDISP, RO, "seldisp" }, /* 48 */
537 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
538 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
540 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
541 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
542 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
543 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
544 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
545 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
546 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
547 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
549 { 0, EOV, "" } /* 50/58 */
554 * Peer variables we print by default
556 static const u_char def_peer_var[] = {
605 * Clock variable list
607 static const struct ctl_var clock_var[] = {
608 { 0, PADDING, "" }, /* 0 */
609 { CC_TYPE, RO, "type" }, /* 1 */
610 { CC_TIMECODE, RO, "timecode" }, /* 2 */
611 { CC_POLL, RO, "poll" }, /* 3 */
612 { CC_NOREPLY, RO, "noreply" }, /* 4 */
613 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
614 { CC_BADDATA, RO, "baddata" }, /* 6 */
615 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
616 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
617 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
618 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
619 { CC_FLAGS, RO, "flags" }, /* 11 */
620 { CC_DEVICE, RO, "device" }, /* 12 */
621 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
622 { 0, EOV, "" } /* 14 */
627 * Clock variables printed by default
629 static const u_char def_clock_var[] = {
631 CC_TYPE, /* won't be output if device = known */
647 * MRU string constants shared by send_mru_entry() and read_mru_list().
649 static const char addr_fmt[] = "addr.%d";
650 static const char last_fmt[] = "last.%d";
653 * System and processor definitions.
657 # define STR_SYSTEM "UNIX"
659 # ifndef STR_PROCESSOR
660 # define STR_PROCESSOR "unknown"
663 static const char str_system[] = STR_SYSTEM;
664 static const char str_processor[] = STR_PROCESSOR;
666 # include <sys/utsname.h>
667 static struct utsname utsnamebuf;
668 #endif /* HAVE_UNAME */
671 * Trap structures. We only allow a few of these, and send a copy of
672 * each async message to each live one. Traps time out after an hour, it
673 * is up to the trap receipient to keep resetting it to avoid being
677 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
681 * Type bits, for ctlsettrap() call.
683 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
684 #define TRAP_TYPE_PRIO 1 /* priority trap */
685 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
689 * List relating reference clock types to control message time sources.
690 * Index by the reference clock type. This list will only be used iff
691 * the reference clock driver doesn't set peer->sstclktype to something
692 * different than CTL_SST_TS_UNSPEC.
695 static const u_char clocktypes[] = {
696 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
697 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
698 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
699 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
700 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
701 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
702 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
703 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
704 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
705 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
706 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
707 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
708 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
709 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
710 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
711 CTL_SST_TS_NTP, /* not used (15) */
712 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
713 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
714 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
715 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
716 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
717 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
718 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
719 CTL_SST_TS_NTP, /* not used (23) */
720 CTL_SST_TS_NTP, /* not used (24) */
721 CTL_SST_TS_NTP, /* not used (25) */
722 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
723 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
724 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
725 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
726 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
727 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
728 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
729 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
730 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
731 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
732 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
733 CTL_SST_TS_LF, /* REFCLK_FG (37) */
734 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
735 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
736 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
737 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
738 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
739 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
740 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
741 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
742 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
744 #endif /* REFCLOCK */
748 * Keyid used for authenticating write requests.
750 keyid_t ctl_auth_keyid;
753 * We keep track of the last error reported by the system internally
755 static u_char ctl_sys_last_event;
756 static u_char ctl_sys_num_events;
760 * Statistic counters to keep track of requests and responses.
762 u_long ctltimereset; /* time stats reset */
763 u_long numctlreq; /* number of requests we've received */
764 u_long numctlbadpkts; /* number of bad control packets */
765 u_long numctlresponses; /* number of resp packets sent with data */
766 u_long numctlfrags; /* number of fragments sent */
767 u_long numctlerrors; /* number of error responses sent */
768 u_long numctltooshort; /* number of too short input packets */
769 u_long numctlinputresp; /* number of responses on input */
770 u_long numctlinputfrag; /* number of fragments on input */
771 u_long numctlinputerr; /* number of input pkts with err bit set */
772 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
773 u_long numctlbadversion; /* number of input pkts with unknown version */
774 u_long numctldatatooshort; /* data too short for count */
775 u_long numctlbadop; /* bad op code found in packet */
776 u_long numasyncmsgs; /* number of async messages we've sent */
779 * Response packet used by these routines. Also some state information
780 * so that we can handle packet formatting within a common set of
781 * subroutines. Note we try to enter data in place whenever possible,
782 * but the need to set the more bit correctly means we occasionally
783 * use the extra buffer and copy.
785 static struct ntp_control rpkt;
786 static u_char res_version;
787 static u_char res_opcode;
788 static associd_t res_associd;
789 static u_short res_frags; /* datagrams in this response */
790 static int res_offset; /* offset of payload in response */
791 static u_char * datapt;
792 static u_char * dataend;
793 static int datalinelen;
794 static int datasent; /* flag to avoid initial ", " */
795 static int datanotbinflag;
796 static sockaddr_u *rmt_addr;
797 static struct interface *lcl_inter;
799 static u_char res_authenticate;
800 static u_char res_authokay;
801 static keyid_t res_keyid;
803 #define MAXDATALINELEN (72)
805 static u_char res_async; /* sending async trap response? */
808 * Pointers for saving state when decoding request packets
814 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
818 * init_control - initialize request data
827 #endif /* HAVE_UNAME */
832 ctl_sys_last_event = EVNT_UNSPEC;
833 ctl_sys_num_events = 0;
836 for (i = 0; i < COUNTOF(ctl_traps); i++)
837 ctl_traps[i].tr_flags = 0;
842 * ctl_error - send an error response for the current request
852 DPRINTF(3, ("sending control error %u\n", errcode));
855 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
856 * have already been filled in.
858 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
859 (res_opcode & CTL_OP_MASK);
860 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
864 * send packet and bump counters
866 if (res_authenticate && sys_authenticate) {
867 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
869 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
870 CTL_HEADER_LEN + maclen);
872 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
877 * save_config - Implements ntpq -c "saveconfig <filename>"
878 * Writes current configuration including any runtime
879 * changes by ntpq's :config or config-from-file
883 struct recvbuf *rbufp,
887 /* block directory traversal by searching for characters that
888 * indicate directory components in a file path.
890 * Conceptually we should be searching for DIRSEP in filename,
891 * however Windows actually recognizes both forward and
892 * backslashes as equivalent directory separators at the API
893 * level. On POSIX systems we could allow '\\' but such
894 * filenames are tricky to manipulate from a shell, so just
895 * reject both types of slashes on all platforms.
897 /* TALOS-CAN-0062: block directory traversal for VMS, too */
898 static const char * illegal_in_filename =
900 ":[]" /* do not allow drive and path components here */
901 #elif defined(SYS_WINNT)
902 ":\\/" /* path and drive separators */
904 "\\/" /* separator and critical char for POSIX */
914 const char savedconfig_eq[] = "savedconfig=";
915 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
921 if (RES_NOMODIFY & restrict_mask) {
922 snprintf(reply, sizeof(reply),
923 "saveconfig prohibited by restrict ... nomodify");
924 ctl_putdata(reply, strlen(reply), 0);
928 "saveconfig from %s rejected due to nomodify restriction",
929 stoa(&rbufp->recv_srcadr));
935 if (NULL == saveconfigdir) {
936 snprintf(reply, sizeof(reply),
937 "saveconfig prohibited, no saveconfigdir configured");
938 ctl_putdata(reply, strlen(reply), 0);
942 "saveconfig from %s rejected, no saveconfigdir",
943 stoa(&rbufp->recv_srcadr));
947 if (0 == reqend - reqpt)
950 strlcpy(filespec, reqpt, sizeof(filespec));
954 * allow timestamping of the saved config filename with
955 * strftime() format such as:
956 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
957 * XXX: Nice feature, but not too safe.
959 if (0 == strftime(filename, sizeof(filename), filespec,
961 strlcpy(filename, filespec, sizeof(filename));
963 /* block directory/drive traversal */
964 /* TALOS-CAN-0062: block directory traversal for VMS, too */
965 if (NULL != strpbrk(filename, illegal_in_filename)) {
966 snprintf(reply, sizeof(reply),
967 "saveconfig does not allow directory in filename");
968 ctl_putdata(reply, strlen(reply), 0);
971 "saveconfig with path from %s rejected",
972 stoa(&rbufp->recv_srcadr));
976 snprintf(fullpath, sizeof(fullpath), "%s%s",
977 saveconfigdir, filename);
979 fd = open(fullpath, O_CREAT | O_TRUNC | O_WRONLY,
984 fptr = fdopen(fd, "w");
986 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
987 snprintf(reply, sizeof(reply),
988 "Unable to save configuration to file %s",
991 "saveconfig %s from %s failed", filename,
992 stoa(&rbufp->recv_srcadr));
994 snprintf(reply, sizeof(reply),
995 "Configuration saved to %s", filename);
997 "Configuration saved to %s (requested by %s)",
998 fullpath, stoa(&rbufp->recv_srcadr));
1000 * save the output filename in system variable
1001 * savedconfig, retrieved with:
1002 * ntpq -c "rv 0 savedconfig"
1004 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
1005 savedconfig_eq, filename);
1006 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1011 #else /* !SAVECONFIG follows */
1012 snprintf(reply, sizeof(reply),
1013 "saveconfig unavailable, configured with --disable-saveconfig");
1016 ctl_putdata(reply, strlen(reply), 0);
1022 * process_control - process an incoming control message
1026 struct recvbuf *rbufp,
1030 struct ntp_control *pkt;
1033 const struct ctl_proc *cc;
1038 DPRINTF(3, ("in process_control()\n"));
1041 * Save the addresses for error responses
1044 rmt_addr = &rbufp->recv_srcadr;
1045 lcl_inter = rbufp->dstadr;
1046 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1049 * If the length is less than required for the header, or
1050 * it is a response or a fragment, ignore this.
1052 if (rbufp->recv_length < (int)CTL_HEADER_LEN
1053 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1054 || pkt->offset != 0) {
1055 DPRINTF(1, ("invalid format in control packet\n"));
1056 if (rbufp->recv_length < (int)CTL_HEADER_LEN)
1058 if (CTL_RESPONSE & pkt->r_m_e_op)
1060 if (CTL_MORE & pkt->r_m_e_op)
1062 if (CTL_ERROR & pkt->r_m_e_op)
1064 if (pkt->offset != 0)
1068 res_version = PKT_VERSION(pkt->li_vn_mode);
1069 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1070 DPRINTF(1, ("unknown version %d in control packet\n",
1077 * Pull enough data from the packet to make intelligent
1080 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1082 res_opcode = pkt->r_m_e_op;
1083 rpkt.sequence = pkt->sequence;
1084 rpkt.associd = pkt->associd;
1088 res_associd = htons(pkt->associd);
1090 res_authenticate = FALSE;
1092 res_authokay = FALSE;
1093 req_count = (int)ntohs(pkt->count);
1094 datanotbinflag = FALSE;
1097 datapt = rpkt.u.data;
1098 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1100 if ((rbufp->recv_length & 0x3) != 0)
1101 DPRINTF(3, ("Control packet length %d unrounded\n",
1102 rbufp->recv_length));
1105 * We're set up now. Make sure we've got at least enough
1106 * incoming data space to match the count.
1108 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1109 if (req_data < req_count || rbufp->recv_length & 0x3) {
1110 ctl_error(CERR_BADFMT);
1111 numctldatatooshort++;
1115 properlen = req_count + CTL_HEADER_LEN;
1116 /* round up proper len to a 8 octet boundary */
1118 properlen = (properlen + 7) & ~7;
1119 maclen = rbufp->recv_length - properlen;
1120 if ((rbufp->recv_length & 3) == 0 &&
1121 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1123 res_authenticate = TRUE;
1124 pkid = (void *)((char *)pkt + properlen);
1125 res_keyid = ntohl(*pkid);
1126 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1127 rbufp->recv_length, properlen, res_keyid,
1130 if (!authistrusted(res_keyid))
1131 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1132 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1133 rbufp->recv_length - maclen,
1135 res_authokay = TRUE;
1136 DPRINTF(3, ("authenticated okay\n"));
1139 DPRINTF(3, ("authentication failed\n"));
1144 * Set up translate pointers
1146 reqpt = (char *)pkt->u.data;
1147 reqend = reqpt + req_count;
1150 * Look for the opcode processor
1152 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1153 if (cc->control_code == res_opcode) {
1154 DPRINTF(3, ("opcode %d, found command handler\n",
1156 if (cc->flags == AUTH
1158 || res_keyid != ctl_auth_keyid)) {
1159 ctl_error(CERR_PERMISSION);
1162 (cc->handler)(rbufp, restrict_mask);
1168 * Can't find this one, return an error.
1171 ctl_error(CERR_BADOP);
1177 * ctlpeerstatus - return a status word for this peer
1181 register struct peer *p
1187 if (FLAG_CONFIG & p->flags)
1188 status |= CTL_PST_CONFIG;
1190 status |= CTL_PST_AUTHENABLE;
1191 if (FLAG_AUTHENTIC & p->flags)
1192 status |= CTL_PST_AUTHENTIC;
1194 status |= CTL_PST_REACH;
1195 if (MDF_TXONLY_MASK & p->cast_flags)
1196 status |= CTL_PST_BCAST;
1198 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1203 * ctlclkstatus - return a status word for this clock
1208 struct refclockstat *pcs
1211 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1217 * ctlsysstatus - return the system status word
1222 register u_char this_clock;
1224 this_clock = CTL_SST_TS_UNSPEC;
1226 if (sys_peer != NULL) {
1227 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1228 this_clock = sys_peer->sstclktype;
1229 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1230 this_clock = clocktypes[sys_peer->refclktype];
1232 #else /* REFCLOCK */
1234 this_clock = CTL_SST_TS_NTP;
1235 #endif /* REFCLOCK */
1236 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1237 ctl_sys_last_event);
1242 * ctl_flushpkt - write out the current packet and prepare
1243 * another if necessary.
1257 dlen = datapt - rpkt.u.data;
1258 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1260 * Big hack, output a trailing \r\n
1266 sendlen = dlen + CTL_HEADER_LEN;
1269 * Pad to a multiple of 32 bits
1271 while (sendlen & 0x3) {
1277 * Fill in the packet with the current info
1279 rpkt.r_m_e_op = CTL_RESPONSE | more |
1280 (res_opcode & CTL_OP_MASK);
1281 rpkt.count = htons((u_short)dlen);
1282 rpkt.offset = htons((u_short)res_offset);
1284 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1285 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1289 ctl_traps[i].tr_version,
1292 htons(ctl_traps[i].tr_sequence);
1293 sendpkt(&ctl_traps[i].tr_addr,
1294 ctl_traps[i].tr_localaddr, -4,
1295 (struct pkt *)&rpkt, sendlen);
1297 ctl_traps[i].tr_sequence++;
1302 if (res_authenticate && sys_authenticate) {
1305 * If we are going to authenticate, then there
1306 * is an additional requirement that the MAC
1307 * begin on a 64 bit boundary.
1309 while (totlen & 7) {
1313 keyid = htonl(res_keyid);
1314 memcpy(datapt, &keyid, sizeof(keyid));
1315 maclen = authencrypt(res_keyid,
1316 (u_int32 *)&rpkt, totlen);
1317 sendpkt(rmt_addr, lcl_inter, -5,
1318 (struct pkt *)&rpkt, totlen + maclen);
1320 sendpkt(rmt_addr, lcl_inter, -6,
1321 (struct pkt *)&rpkt, sendlen);
1330 * Set us up for another go around.
1334 datapt = rpkt.u.data;
1339 * ctl_putdata - write data into the packet, fragmenting and starting
1340 * another if this one is full.
1346 int bin /* set to 1 when data is binary */
1350 unsigned int currentlen;
1354 datanotbinflag = TRUE;
1359 if ((dlen + datalinelen + 1) >= MAXDATALINELEN) {
1371 * Save room for trailing junk
1373 while (dlen + overhead + datapt > dataend) {
1375 * Not enough room in this one, flush it out.
1377 currentlen = MIN(dlen, (unsigned int)(dataend - datapt));
1379 memcpy(datapt, dp, currentlen);
1381 datapt += currentlen;
1384 datalinelen += currentlen;
1386 ctl_flushpkt(CTL_MORE);
1389 memcpy(datapt, dp, dlen);
1391 datalinelen += dlen;
1397 * ctl_putstr - write a tagged string into the response packet
1402 * len is the data length excluding the NUL terminator,
1403 * as in ctl_putstr("var", "value", strlen("value"));
1417 memcpy(buffer, tag, tl);
1420 INSIST(tl + 3 + len <= sizeof(buffer));
1423 memcpy(cp, data, len);
1427 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1432 * ctl_putunqstr - write a tagged string into the response packet
1437 * len is the data length excluding the NUL terminator.
1438 * data must not contain a comma or whitespace.
1452 memcpy(buffer, tag, tl);
1455 INSIST(tl + 1 + len <= sizeof(buffer));
1457 memcpy(cp, data, len);
1460 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1465 * ctl_putdblf - write a tagged, signed double into the response packet
1484 INSIST((size_t)(cp - buffer) < sizeof(buffer));
1485 snprintf(cp, sizeof(buffer) - (cp - buffer), use_f ? "%.*f" : "%.*g",
1488 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1492 * ctl_putuint - write a tagged unsigned integer into the response
1501 register const char *cq;
1510 INSIST((cp - buffer) < (int)sizeof(buffer));
1511 snprintf(cp, sizeof(buffer) - (cp - buffer), "%lu", uval);
1513 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1517 * ctl_putcal - write a decoded calendar data into the response
1522 const struct calendar *pcal
1528 numch = snprintf(buffer, sizeof(buffer),
1529 "%s=%04d%02d%02d%02d%02d",
1537 INSIST(numch < sizeof(buffer));
1538 ctl_putdata(buffer, numch, 0);
1544 * ctl_putfs - write a decoded filestamp into the response
1553 register const char *cq;
1555 struct tm *tm = NULL;
1564 fstamp = uval - JAN_1970;
1565 tm = gmtime(&fstamp);
1568 INSIST((cp - buffer) < (int)sizeof(buffer));
1569 snprintf(cp, sizeof(buffer) - (cp - buffer),
1570 "%04d%02d%02d%02d%02d", tm->tm_year + 1900,
1571 tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);
1573 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1578 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1588 register const char *cq;
1597 INSIST((cp - buffer) < (int)sizeof(buffer));
1598 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%lx", uval);
1600 ctl_putdata(buffer,(unsigned)( cp - buffer ), 0);
1605 * ctl_putint - write a tagged signed integer into the response
1614 register const char *cq;
1623 INSIST((cp - buffer) < (int)sizeof(buffer));
1624 snprintf(cp, sizeof(buffer) - (cp - buffer), "%ld", ival);
1626 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1631 * ctl_putts - write a tagged timestamp, in hex, into the response
1640 register const char *cq;
1649 INSIST((size_t)(cp - buffer) < sizeof(buffer));
1650 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%08x.%08x",
1651 (u_int)ts->l_ui, (u_int)ts->l_uf);
1653 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1658 * ctl_putadr - write an IP address into the response
1668 register const char *cq;
1678 cq = numtoa(addr32);
1681 INSIST((cp - buffer) < (int)sizeof(buffer));
1682 snprintf(cp, sizeof(buffer) - (cp - buffer), "%s", cq);
1684 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1689 * ctl_putrefid - send a u_int32 refid as printable text
1705 oplim = output + sizeof(output);
1706 while (optr < oplim && '\0' != *tag)
1712 if (!(optr < oplim))
1714 iptr = (char *)&refid;
1715 iplim = iptr + sizeof(refid);
1716 for ( ; optr < oplim && iptr < iplim && '\0' != *iptr;
1718 if (isprint((int)*iptr))
1722 if (!(optr <= oplim))
1724 ctl_putdata(output, (u_int)(optr - output), FALSE);
1729 * ctl_putarray - write a tagged eight element double array into the response
1739 register const char *cq;
1752 INSIST((cp - buffer) < (int)sizeof(buffer));
1753 snprintf(cp, sizeof(buffer) - (cp - buffer),
1754 " %.2f", arr[i] * 1e3);
1756 } while (i != start);
1757 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1762 * ctl_putsys - output a system variable
1776 struct cert_info *cp;
1777 #endif /* AUTOKEY */
1779 static struct timex ntx;
1780 static u_long ntp_adjtime_time;
1782 static const double to_ms =
1784 1.0e-6; /* nsec to msec */
1786 1.0e-3; /* usec to msec */
1790 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1792 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1793 current_time != ntp_adjtime_time) {
1795 if (ntp_adjtime(&ntx) < 0)
1796 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1798 ntp_adjtime_time = current_time;
1800 #endif /* KERNEL_PLL */
1805 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1809 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1813 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1817 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1821 case CS_ROOTDISPERSION:
1822 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1823 sys_rootdisp * 1e3);
1827 if (sys_stratum > 1 && sys_stratum < STRATUM_UNSPEC)
1828 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1830 ctl_putrefid(sys_var[varid].text, sys_refid);
1834 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1838 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
1842 if (sys_peer == NULL)
1843 ctl_putuint(sys_var[CS_PEERID].text, 0);
1845 ctl_putuint(sys_var[CS_PEERID].text,
1850 if (sys_peer != NULL && sys_peer->dstadr != NULL)
1851 ss = sptoa(&sys_peer->srcadr);
1854 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
1858 u = (sys_peer != NULL)
1861 ctl_putuint(sys_var[CS_PEERMODE].text, u);
1865 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
1869 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
1873 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
1877 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
1882 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
1887 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
1888 sizeof(str_processor) - 1);
1890 ctl_putstr(sys_var[CS_PROCESSOR].text,
1891 utsnamebuf.machine, strlen(utsnamebuf.machine));
1892 #endif /* HAVE_UNAME */
1897 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
1898 sizeof(str_system) - 1);
1900 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
1901 utsnamebuf.release);
1902 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
1903 #endif /* HAVE_UNAME */
1907 ctl_putstr(sys_var[CS_VERSION].text, Version,
1912 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
1918 char buf[CTL_MAX_DATA_LEN];
1919 //buffPointer, firstElementPointer, buffEndPointer
1920 char *buffp, *buffend;
1924 const struct ctl_var *k;
1927 buffend = buf + sizeof(buf);
1928 if (buffp + strlen(sys_var[CS_VARLIST].text) + 4 > buffend)
1929 break; /* really long var name */
1931 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
1932 buffp += strlen(buffp);
1933 firstVarName = TRUE;
1934 for (k = sys_var; !(k->flags & EOV); k++) {
1935 if (k->flags & PADDING)
1937 len = strlen(k->text);
1938 if (buffp + len + 1 >= buffend)
1943 firstVarName = FALSE;
1944 memcpy(buffp, k->text, len);
1948 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
1949 if (k->flags & PADDING)
1951 if (NULL == k->text)
1953 ss1 = strchr(k->text, '=');
1955 len = strlen(k->text);
1957 len = ss1 - k->text;
1958 if (buffp + len + 1 >= buffend)
1962 firstVarName = FALSE;
1964 memcpy(buffp, k->text,(unsigned)len);
1967 if (buffp + 2 >= buffend)
1973 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
1979 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
1984 leap_signature_t lsig;
1985 leapsec_getsig(&lsig);
1987 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
1993 leap_signature_t lsig;
1994 leapsec_getsig(&lsig);
1996 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2001 case CS_LEAPSMEARINTV:
2002 if (leap_smear_intv > 0)
2003 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2006 case CS_LEAPSMEAROFFS:
2007 if (leap_smear_intv > 0)
2008 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2009 leap_smear.doffset * 1e3);
2011 #endif /* LEAP_SMEAR */
2014 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2017 case CS_MRU_ENABLED:
2018 ctl_puthex(sys_var[varid].text, mon_enabled);
2022 ctl_putuint(sys_var[varid].text, mru_entries);
2026 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2030 ctl_putuint(sys_var[varid].text, u);
2033 case CS_MRU_DEEPEST:
2034 ctl_putuint(sys_var[varid].text, mru_peakentries);
2037 case CS_MRU_MINDEPTH:
2038 ctl_putuint(sys_var[varid].text, mru_mindepth);
2042 ctl_putint(sys_var[varid].text, mru_maxage);
2045 case CS_MRU_MAXDEPTH:
2046 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2050 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2054 ctl_putuint(sys_var[varid].text, u);
2058 ctl_putuint(sys_var[varid].text, current_time);
2062 ctl_putuint(sys_var[varid].text,
2063 current_time - sys_stattime);
2066 case CS_SS_RECEIVED:
2067 ctl_putuint(sys_var[varid].text, sys_received);
2071 ctl_putuint(sys_var[varid].text, sys_newversion);
2075 ctl_putuint(sys_var[varid].text, sys_oldversion);
2078 case CS_SS_BADFORMAT:
2079 ctl_putuint(sys_var[varid].text, sys_badlength);
2083 ctl_putuint(sys_var[varid].text, sys_badauth);
2086 case CS_SS_DECLINED:
2087 ctl_putuint(sys_var[varid].text, sys_declined);
2090 case CS_SS_RESTRICTED:
2091 ctl_putuint(sys_var[varid].text, sys_restricted);
2095 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2099 ctl_putuint(sys_var[varid].text, sys_kodsent);
2102 case CS_SS_PROCESSED:
2103 ctl_putuint(sys_var[varid].text, sys_processed);
2107 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2111 LFPTOD(&sys_authdelay, dtemp);
2112 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2116 ctl_putuint(sys_var[varid].text, authnumkeys);
2120 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2123 case CS_AUTHKLOOKUPS:
2124 ctl_putuint(sys_var[varid].text, authkeylookups);
2127 case CS_AUTHKNOTFOUND:
2128 ctl_putuint(sys_var[varid].text, authkeynotfound);
2131 case CS_AUTHKUNCACHED:
2132 ctl_putuint(sys_var[varid].text, authkeyuncached);
2135 case CS_AUTHKEXPIRED:
2136 ctl_putuint(sys_var[varid].text, authkeyexpired);
2139 case CS_AUTHENCRYPTS:
2140 ctl_putuint(sys_var[varid].text, authencryptions);
2143 case CS_AUTHDECRYPTS:
2144 ctl_putuint(sys_var[varid].text, authdecryptions);
2148 ctl_putuint(sys_var[varid].text,
2149 current_time - auth_timereset);
2153 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2154 * unavailable, otherwise calls putfunc with args.
2157 # define CTL_IF_KERNLOOP(putfunc, args) \
2158 ctl_putint(sys_var[varid].text, 0)
2160 # define CTL_IF_KERNLOOP(putfunc, args) \
2165 * CTL_IF_KERNPPS() puts a zero if either the kernel
2166 * loop is unavailable, or kernel hard PPS is not
2167 * active, otherwise calls putfunc with args.
2170 # define CTL_IF_KERNPPS(putfunc, args) \
2171 ctl_putint(sys_var[varid].text, 0)
2173 # define CTL_IF_KERNPPS(putfunc, args) \
2174 if (0 == ntx.shift) \
2175 ctl_putint(sys_var[varid].text, 0); \
2177 putfunc args /* no trailing ; */
2183 (sys_var[varid].text, 0, -1, to_ms * ntx.offset)
2190 (sys_var[varid].text, ntx.freq)
2197 (sys_var[varid].text, 0, 6,
2198 to_ms * ntx.maxerror)
2205 (sys_var[varid].text, 0, 6,
2206 to_ms * ntx.esterror)
2214 ss = k_st_flags(ntx.status);
2216 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2219 case CS_K_TIMECONST:
2222 (sys_var[varid].text, ntx.constant)
2226 case CS_K_PRECISION:
2229 (sys_var[varid].text, 0, 6,
2230 to_ms * ntx.precision)
2237 (sys_var[varid].text, ntx.tolerance)
2244 (sys_var[varid].text, ntx.ppsfreq)
2248 case CS_K_PPS_STABIL:
2251 (sys_var[varid].text, ntx.stabil)
2255 case CS_K_PPS_JITTER:
2258 (sys_var[varid].text, to_ms * ntx.jitter)
2262 case CS_K_PPS_CALIBDUR:
2265 (sys_var[varid].text, 1 << ntx.shift)
2269 case CS_K_PPS_CALIBS:
2272 (sys_var[varid].text, ntx.calcnt)
2276 case CS_K_PPS_CALIBERRS:
2279 (sys_var[varid].text, ntx.errcnt)
2283 case CS_K_PPS_JITEXC:
2286 (sys_var[varid].text, ntx.jitcnt)
2290 case CS_K_PPS_STBEXC:
2293 (sys_var[varid].text, ntx.stbcnt)
2297 case CS_IOSTATS_RESET:
2298 ctl_putuint(sys_var[varid].text,
2299 current_time - io_timereset);
2303 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2307 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2311 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2314 case CS_RBUF_LOWATER:
2315 ctl_putuint(sys_var[varid].text, lowater_additions());
2319 ctl_putuint(sys_var[varid].text, packets_dropped);
2323 ctl_putuint(sys_var[varid].text, packets_ignored);
2326 case CS_IO_RECEIVED:
2327 ctl_putuint(sys_var[varid].text, packets_received);
2331 ctl_putuint(sys_var[varid].text, packets_sent);
2334 case CS_IO_SENDFAILED:
2335 ctl_putuint(sys_var[varid].text, packets_notsent);
2339 ctl_putuint(sys_var[varid].text, handler_calls);
2342 case CS_IO_GOODWAKEUPS:
2343 ctl_putuint(sys_var[varid].text, handler_pkts);
2346 case CS_TIMERSTATS_RESET:
2347 ctl_putuint(sys_var[varid].text,
2348 current_time - timer_timereset);
2351 case CS_TIMER_OVERRUNS:
2352 ctl_putuint(sys_var[varid].text, alarm_overflow);
2356 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2360 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2362 case CS_WANDER_THRESH:
2363 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2368 ctl_puthex(sys_var[CS_FLAGS].text,
2374 strlcpy(str, OBJ_nid2ln(crypto_nid),
2376 ctl_putstr(sys_var[CS_DIGEST].text, str,
2385 dp = EVP_get_digestbynid(crypto_flags >> 16);
2386 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2388 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2394 if (hostval.ptr != NULL)
2395 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2396 strlen(hostval.ptr));
2400 if (sys_ident != NULL)
2401 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2406 for (cp = cinfo; cp != NULL; cp = cp->link) {
2407 snprintf(str, sizeof(str), "%s %s 0x%x",
2408 cp->subject, cp->issuer, cp->flags);
2409 ctl_putstr(sys_var[CS_CERTIF].text, str,
2411 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2416 if (hostval.tstamp != 0)
2417 ctl_putfs(sys_var[CS_PUBLIC].text,
2418 ntohl(hostval.tstamp));
2420 #endif /* AUTOKEY */
2429 * ctl_putpeer - output a peer variable
2437 char buf[CTL_MAX_DATA_LEN];
2442 const struct ctl_var *k;
2447 #endif /* AUTOKEY */
2452 ctl_putuint(peer_var[id].text,
2453 !(FLAG_PREEMPT & p->flags));
2457 ctl_putuint(peer_var[id].text, !(p->keyid));
2461 ctl_putuint(peer_var[id].text,
2462 !!(FLAG_AUTHENTIC & p->flags));
2466 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2470 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2474 if (p->hostname != NULL)
2475 ctl_putstr(peer_var[id].text, p->hostname,
2476 strlen(p->hostname));
2480 ctl_putadr(peer_var[id].text, 0,
2487 ctl_putuint(peer_var[id].text,
2489 ? SRCPORT(&p->dstadr->sin)
2495 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2500 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2504 ctl_putuint(peer_var[id].text, p->throttle);
2508 ctl_putuint(peer_var[id].text, p->leap);
2512 ctl_putuint(peer_var[id].text, p->hmode);
2516 ctl_putuint(peer_var[id].text, p->stratum);
2520 ctl_putuint(peer_var[id].text, p->ppoll);
2524 ctl_putuint(peer_var[id].text, p->hpoll);
2528 ctl_putint(peer_var[id].text, p->precision);
2532 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2535 case CP_ROOTDISPERSION:
2536 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2541 if (p->flags & FLAG_REFCLOCK) {
2542 ctl_putrefid(peer_var[id].text, p->refid);
2546 if (p->stratum > 1 && p->stratum < STRATUM_UNSPEC)
2547 ctl_putadr(peer_var[id].text, p->refid,
2550 ctl_putrefid(peer_var[id].text, p->refid);
2554 ctl_putts(peer_var[id].text, &p->reftime);
2558 ctl_putts(peer_var[id].text, &p->aorg);
2562 ctl_putts(peer_var[id].text, &p->dst);
2567 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2572 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2576 ctl_puthex(peer_var[id].text, p->reach);
2580 ctl_puthex(peer_var[id].text, p->flash);
2585 if (p->flags & FLAG_REFCLOCK) {
2586 ctl_putuint(peer_var[id].text, p->ttl);
2590 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2591 ctl_putint(peer_var[id].text,
2596 ctl_putuint(peer_var[id].text, p->unreach);
2600 ctl_putuint(peer_var[id].text,
2601 p->nextdate - current_time);
2605 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2609 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2613 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2617 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2621 if (p->keyid > NTP_MAXKEY)
2622 ctl_puthex(peer_var[id].text, p->keyid);
2624 ctl_putuint(peer_var[id].text, p->keyid);
2628 ctl_putarray(peer_var[id].text, p->filter_delay,
2633 ctl_putarray(peer_var[id].text, p->filter_offset,
2638 ctl_putarray(peer_var[id].text, p->filter_disp,
2643 ctl_putuint(peer_var[id].text, p->pmode);
2647 ctl_putuint(peer_var[id].text, p->received);
2651 ctl_putuint(peer_var[id].text, p->sent);
2656 be = buf + sizeof(buf);
2657 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2658 break; /* really long var name */
2660 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2663 for (k = peer_var; !(EOV & k->flags); k++) {
2664 if (PADDING & k->flags)
2666 i = strlen(k->text);
2667 if (s + i + 1 >= be)
2671 memcpy(s, k->text, i);
2677 ctl_putdata(buf, (u_int)(s - buf), 0);
2682 ctl_putuint(peer_var[id].text,
2683 current_time - p->timereceived);
2687 ctl_putuint(peer_var[id].text,
2688 current_time - p->timereachable);
2692 ctl_putuint(peer_var[id].text, p->badauth);
2696 ctl_putuint(peer_var[id].text, p->bogusorg);
2700 ctl_putuint(peer_var[id].text, p->oldpkt);
2704 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2708 ctl_putuint(peer_var[id].text, p->selbroken);
2712 ctl_putuint(peer_var[id].text, p->status);
2717 ctl_puthex(peer_var[id].text, p->crypto);
2722 dp = EVP_get_digestbynid(p->crypto >> 16);
2723 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2724 ctl_putstr(peer_var[id].text, str, strlen(str));
2729 if (p->subject != NULL)
2730 ctl_putstr(peer_var[id].text, p->subject,
2731 strlen(p->subject));
2734 case CP_VALID: /* not used */
2738 if (NULL == (ap = p->recval.ptr))
2741 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2742 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2743 ctl_putfs(peer_var[CP_INITTSP].text,
2744 ntohl(p->recval.tstamp));
2748 if (p->ident != NULL)
2749 ctl_putstr(peer_var[id].text, p->ident,
2754 #endif /* AUTOKEY */
2761 * ctl_putclock - output clock variables
2766 struct refclockstat *pcs,
2770 char buf[CTL_MAX_DATA_LEN];
2774 const struct ctl_var *k;
2779 if (mustput || pcs->clockdesc == NULL
2780 || *(pcs->clockdesc) == '\0') {
2781 ctl_putuint(clock_var[id].text, pcs->type);
2785 ctl_putstr(clock_var[id].text,
2787 (unsigned)pcs->lencode);
2791 ctl_putuint(clock_var[id].text, pcs->polls);
2795 ctl_putuint(clock_var[id].text,
2800 ctl_putuint(clock_var[id].text,
2805 ctl_putuint(clock_var[id].text,
2810 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2811 ctl_putdbl(clock_var[id].text,
2812 pcs->fudgetime1 * 1e3);
2816 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2817 ctl_putdbl(clock_var[id].text,
2818 pcs->fudgetime2 * 1e3);
2822 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2823 ctl_putint(clock_var[id].text,
2828 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2829 if (pcs->fudgeval1 > 1)
2830 ctl_putadr(clock_var[id].text,
2831 pcs->fudgeval2, NULL);
2833 ctl_putrefid(clock_var[id].text,
2839 ctl_putuint(clock_var[id].text, pcs->flags);
2843 if (pcs->clockdesc == NULL ||
2844 *(pcs->clockdesc) == '\0') {
2846 ctl_putstr(clock_var[id].text,
2849 ctl_putstr(clock_var[id].text,
2851 strlen(pcs->clockdesc));
2857 be = buf + sizeof(buf);
2858 if (strlen(clock_var[CC_VARLIST].text) + 4 >
2860 break; /* really long var name */
2862 snprintf(s, sizeof(buf), "%s=\"",
2863 clock_var[CC_VARLIST].text);
2867 for (k = clock_var; !(EOV & k->flags); k++) {
2868 if (PADDING & k->flags)
2871 i = strlen(k->text);
2872 if (s + i + 1 >= be)
2877 memcpy(s, k->text, i);
2881 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
2882 if (PADDING & k->flags)
2889 while (*ss && *ss != '=')
2892 if (s + i + 1 >= be)
2897 memcpy(s, k->text, (unsigned)i);
2906 ctl_putdata(buf, (unsigned)(s - buf), 0);
2915 * ctl_getitem - get the next data item from the incoming packet
2917 static const struct ctl_var *
2919 const struct ctl_var *var_list,
2923 static const struct ctl_var eol = { 0, EOV, NULL };
2924 static char buf[128];
2925 static u_long quiet_until;
2926 const struct ctl_var *v;
2932 * Delete leading commas and white space
2934 while (reqpt < reqend && (*reqpt == ',' ||
2935 isspace((unsigned char)*reqpt)))
2937 if (reqpt >= reqend)
2940 if (NULL == var_list)
2944 * Look for a first character match on the tag. If we find
2945 * one, see if it is a full match.
2948 for (v = var_list; !(EOV & v->flags); v++) {
2949 if (!(PADDING & v->flags) && *cp == *(v->text)) {
2951 while ('\0' != *pch && '=' != *pch && cp < reqend
2956 if ('\0' == *pch || '=' == *pch) {
2957 while (cp < reqend && isspace((u_char)*cp))
2959 if (cp == reqend || ',' == *cp) {
2970 while (cp < reqend && isspace((u_char)*cp))
2972 while (cp < reqend && *cp != ',') {
2974 if ((size_t)(tp - buf) >= sizeof(buf)) {
2975 ctl_error(CERR_BADFMT);
2978 if (quiet_until <= current_time) {
2979 quiet_until = current_time + 300;
2980 msyslog(LOG_WARNING,
2981 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)", stoa(rmt_addr), SRCPORT(rmt_addr));
2989 while (tp >= buf && isspace((u_char)*tp))
3004 * control_unspec - response to an unspecified op-code
3009 struct recvbuf *rbufp,
3016 * What is an appropriate response to an unspecified op-code?
3017 * I return no errors and no data, unless a specified assocation
3021 peer = findpeerbyassoc(res_associd);
3023 ctl_error(CERR_BADASSOC);
3026 rpkt.status = htons(ctlpeerstatus(peer));
3028 rpkt.status = htons(ctlsysstatus());
3034 * read_status - return either a list of associd's, or a particular
3040 struct recvbuf *rbufp,
3047 /* a_st holds association ID, status pairs alternating */
3048 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3052 printf("read_status: ID %d\n", res_associd);
3055 * Two choices here. If the specified association ID is
3056 * zero we return all known assocation ID's. Otherwise
3057 * we return a bunch of stuff about the particular peer.
3060 peer = findpeerbyassoc(res_associd);
3062 ctl_error(CERR_BADASSOC);
3065 rpkt.status = htons(ctlpeerstatus(peer));
3067 peer->num_events = 0;
3069 * For now, output everything we know about the
3070 * peer. May be more selective later.
3072 for (cp = def_peer_var; *cp != 0; cp++)
3073 ctl_putpeer((int)*cp, peer);
3078 rpkt.status = htons(ctlsysstatus());
3079 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3080 a_st[n++] = htons(peer->associd);
3081 a_st[n++] = htons(ctlpeerstatus(peer));
3082 /* two entries each loop iteration, so n + 1 */
3083 if (n + 1 >= COUNTOF(a_st)) {
3084 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3090 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3096 * read_peervars - half of read_variables() implementation
3101 const struct ctl_var *v;
3106 u_char wants[CP_MAXCODE + 1];
3110 * Wants info for a particular peer. See if we know
3113 peer = findpeerbyassoc(res_associd);
3115 ctl_error(CERR_BADASSOC);
3118 rpkt.status = htons(ctlpeerstatus(peer));
3120 peer->num_events = 0;
3123 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3124 if (v->flags & EOV) {
3125 ctl_error(CERR_UNKNOWNVAR);
3128 INSIST(v->code < COUNTOF(wants));
3133 for (i = 1; i < COUNTOF(wants); i++)
3135 ctl_putpeer(i, peer);
3137 for (cp = def_peer_var; *cp != 0; cp++)
3138 ctl_putpeer((int)*cp, peer);
3144 * read_sysvars - half of read_variables() implementation
3149 const struct ctl_var *v;
3160 * Wants system variables. Figure out which he wants
3161 * and give them to him.
3163 rpkt.status = htons(ctlsysstatus());
3165 ctl_sys_num_events = 0;
3166 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3167 wants = emalloc_zero(wants_count);
3169 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3170 if (!(EOV & v->flags)) {
3171 INSIST(v->code < wants_count);
3175 v = ctl_getitem(ext_sys_var, &valuep);
3177 if (EOV & v->flags) {
3178 ctl_error(CERR_UNKNOWNVAR);
3182 n = v->code + CS_MAXCODE + 1;
3183 INSIST(n < wants_count);
3189 for (n = 1; n <= CS_MAXCODE; n++)
3192 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3193 if (wants[n + CS_MAXCODE + 1]) {
3194 pch = ext_sys_var[n].text;
3195 ctl_putdata(pch, strlen(pch), 0);
3198 for (cs = def_sys_var; *cs != 0; cs++)
3199 ctl_putsys((int)*cs);
3200 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3201 if (DEF & kv->flags)
3202 ctl_putdata(kv->text, strlen(kv->text),
3211 * read_variables - return the variables the caller asks for
3216 struct recvbuf *rbufp,
3228 * write_variables - write into variables. We only allow leap bit
3234 struct recvbuf *rbufp,
3238 const struct ctl_var *v;
3249 * If he's trying to write into a peer tell him no way
3251 if (res_associd != 0) {
3252 ctl_error(CERR_PERMISSION);
3259 rpkt.status = htons(ctlsysstatus());
3262 * Look through the variables. Dump out at the first sign of
3265 while ((v = ctl_getitem(sys_var, &valuep)) != 0) {
3267 if (v->flags & EOV) {
3268 if ((v = ctl_getitem(ext_sys_var, &valuep)) !=
3270 if (v->flags & EOV) {
3271 ctl_error(CERR_UNKNOWNVAR);
3279 if (!(v->flags & CAN_WRITE)) {
3280 ctl_error(CERR_PERMISSION);
3283 if (!ext_var && (*valuep == '\0' || !atoint(valuep,
3285 ctl_error(CERR_BADFMT);
3288 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) {
3289 ctl_error(CERR_BADVALUE);
3294 octets = strlen(v->text) + strlen(valuep) + 2;
3295 vareqv = emalloc(octets);
3298 while (*t && *t != '=')
3301 memcpy(tt, valuep, 1 + strlen(valuep));
3302 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3305 ctl_error(CERR_UNSPEC); /* really */
3311 * If we got anything, do it. xxx nothing to do ***
3314 if (leapind != ~0 || leapwarn != ~0) {
3315 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3316 ctl_error(CERR_PERMISSION);
3326 * configure() processes ntpq :config/config-from-file, allowing
3327 * generic runtime reconfiguration.
3329 static void configure(
3330 struct recvbuf *rbufp,
3337 /* I haven't yet implemented changes to an existing association.
3338 * Hence check if the association id is 0
3340 if (res_associd != 0) {
3341 ctl_error(CERR_BADVALUE);
3345 if (RES_NOMODIFY & restrict_mask) {
3346 snprintf(remote_config.err_msg,
3347 sizeof(remote_config.err_msg),
3348 "runtime configuration prohibited by restrict ... nomodify");
3349 ctl_putdata(remote_config.err_msg,
3350 strlen(remote_config.err_msg), 0);
3354 "runtime config from %s rejected due to nomodify restriction",
3355 stoa(&rbufp->recv_srcadr));
3360 /* Initialize the remote config buffer */
3361 data_count = remoteconfig_cmdlength(reqpt, reqend);
3363 if (data_count > sizeof(remote_config.buffer) - 2) {
3364 snprintf(remote_config.err_msg,
3365 sizeof(remote_config.err_msg),
3366 "runtime configuration failed: request too long");
3367 ctl_putdata(remote_config.err_msg,
3368 strlen(remote_config.err_msg), 0);
3371 "runtime config from %s rejected: request too long",
3372 stoa(&rbufp->recv_srcadr));
3375 /* Bug 2853 -- check if all characters were acceptable */
3376 if (data_count != (size_t)(reqend - reqpt)) {
3377 snprintf(remote_config.err_msg,
3378 sizeof(remote_config.err_msg),
3379 "runtime configuration failed: request contains an unprintable character");
3380 ctl_putdata(remote_config.err_msg,
3381 strlen(remote_config.err_msg), 0);
3384 "runtime config from %s rejected: request contains an unprintable character: %0x",
3385 stoa(&rbufp->recv_srcadr),
3390 memcpy(remote_config.buffer, reqpt, data_count);
3391 /* The buffer has no trailing linefeed or NUL right now. For
3392 * logging, we do not want a newline, so we do that first after
3393 * adding the necessary NUL byte.
3395 remote_config.buffer[data_count] = '\0';
3396 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3397 remote_config.buffer));
3398 msyslog(LOG_NOTICE, "%s config: %s",
3399 stoa(&rbufp->recv_srcadr),
3400 remote_config.buffer);
3402 /* Now we have to make sure there is a NL/NUL sequence at the
3403 * end of the buffer before we parse it.
3405 remote_config.buffer[data_count++] = '\n';
3406 remote_config.buffer[data_count] = '\0';
3407 remote_config.pos = 0;
3408 remote_config.err_pos = 0;
3409 remote_config.no_errors = 0;
3410 config_remotely(&rbufp->recv_srcadr);
3413 * Check if errors were reported. If not, output 'Config
3414 * Succeeded'. Else output the error count. It would be nice
3415 * to output any parser error messages.
3417 if (0 == remote_config.no_errors) {
3418 retval = snprintf(remote_config.err_msg,
3419 sizeof(remote_config.err_msg),
3420 "Config Succeeded");
3422 remote_config.err_pos += retval;
3425 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3428 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3430 if (remote_config.no_errors > 0)
3431 msyslog(LOG_NOTICE, "%d error in %s config",
3432 remote_config.no_errors,
3433 stoa(&rbufp->recv_srcadr));
3438 * derive_nonce - generate client-address-specific nonce value
3439 * associated with a given timestamp.
3441 static u_int32 derive_nonce(
3447 static u_int32 salt[4];
3448 static u_long last_salt_update;
3450 u_char digest[EVP_MAX_MD_SIZE];
3456 while (!salt[0] || current_time - last_salt_update >= 3600) {
3457 salt[0] = ntp_random();
3458 salt[1] = ntp_random();
3459 salt[2] = ntp_random();
3460 salt[3] = ntp_random();
3461 last_salt_update = current_time;
3464 EVP_DigestInit(&ctx, EVP_get_digestbynid(NID_md5));
3465 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3466 EVP_DigestUpdate(&ctx, &ts_i, sizeof(ts_i));
3467 EVP_DigestUpdate(&ctx, &ts_f, sizeof(ts_f));
3469 EVP_DigestUpdate(&ctx, &SOCK_ADDR4(addr),
3470 sizeof(SOCK_ADDR4(addr)));
3472 EVP_DigestUpdate(&ctx, &SOCK_ADDR6(addr),
3473 sizeof(SOCK_ADDR6(addr)));
3474 EVP_DigestUpdate(&ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3475 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3476 EVP_DigestFinal(&ctx, d.digest, &len);
3483 * generate_nonce - generate client-address-specific nonce string.
3485 static void generate_nonce(
3486 struct recvbuf * rbufp,
3493 derived = derive_nonce(&rbufp->recv_srcadr,
3494 rbufp->recv_time.l_ui,
3495 rbufp->recv_time.l_uf);
3496 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3497 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3502 * validate_nonce - validate client-address-specific nonce string.
3504 * Returns TRUE if the local calculation of the nonce matches the
3505 * client-provided value and the timestamp is recent enough.
3507 static int validate_nonce(
3508 const char * pnonce,
3509 struct recvbuf * rbufp
3519 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3522 ts.l_ui = (u_int32)ts_i;
3523 ts.l_uf = (u_int32)ts_f;
3524 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3525 get_systime(&now_delta);
3526 L_SUB(&now_delta, &ts);
3528 return (supposed == derived && now_delta.l_ui < 16);
3533 * send_random_tag_value - send a randomly-generated three character
3534 * tag prefix, a '.', an index, a '=' and a
3535 * random integer value.
3537 * To try to force clients to ignore unrecognized tags in mrulist,
3538 * reslist, and ifstats responses, the first and last rows are spiced
3539 * with randomly-generated tag names with correct .# index. Make it
3540 * three characters knowing that none of the currently-used subscripted
3541 * tags have that length, avoiding the need to test for
3545 send_random_tag_value(
3552 noise = rand() ^ (rand() << 16);
3553 buf[0] = 'a' + noise % 26;
3555 buf[1] = 'a' + noise % 26;
3557 buf[2] = 'a' + noise % 26;
3560 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3561 ctl_putuint(buf, noise);
3566 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3568 * To keep clients honest about not depending on the order of values,
3569 * and thereby avoid being locked into ugly workarounds to maintain
3570 * backward compatibility later as new fields are added to the response,
3571 * the order is random.
3579 const char first_fmt[] = "first.%d";
3580 const char ct_fmt[] = "ct.%d";
3581 const char mv_fmt[] = "mv.%d";
3582 const char rs_fmt[] = "rs.%d";
3584 u_char sent[6]; /* 6 tag=value pairs */
3590 remaining = COUNTOF(sent);
3592 noise = (u_int32)(rand() ^ (rand() << 16));
3593 while (remaining > 0) {
3594 which = (noise & 7) % COUNTOF(sent);
3597 which = (which + 1) % COUNTOF(sent);
3602 snprintf(tag, sizeof(tag), addr_fmt, count);
3603 pch = sptoa(&mon->rmtadr);
3604 ctl_putunqstr(tag, pch, strlen(pch));
3608 snprintf(tag, sizeof(tag), last_fmt, count);
3609 ctl_putts(tag, &mon->last);
3613 snprintf(tag, sizeof(tag), first_fmt, count);
3614 ctl_putts(tag, &mon->first);
3618 snprintf(tag, sizeof(tag), ct_fmt, count);
3619 ctl_putint(tag, mon->count);
3623 snprintf(tag, sizeof(tag), mv_fmt, count);
3624 ctl_putuint(tag, mon->vn_mode);
3628 snprintf(tag, sizeof(tag), rs_fmt, count);
3629 ctl_puthex(tag, mon->flags);
3639 * read_mru_list - supports ntpq's mrulist command.
3641 * The challenge here is to match ntpdc's monlist functionality without
3642 * being limited to hundreds of entries returned total, and without
3643 * requiring state on the server. If state were required, ntpq's
3644 * mrulist command would require authentication.
3646 * The approach was suggested by Ry Jones. A finite and variable number
3647 * of entries are retrieved per request, to avoid having responses with
3648 * such large numbers of packets that socket buffers are overflowed and
3649 * packets lost. The entries are retrieved oldest-first, taking into
3650 * account that the MRU list will be changing between each request. We
3651 * can expect to see duplicate entries for addresses updated in the MRU
3652 * list during the fetch operation. In the end, the client can assemble
3653 * a close approximation of the MRU list at the point in time the last
3654 * response was sent by ntpd. The only difference is it may be longer,
3655 * containing some number of oldest entries which have since been
3656 * reclaimed. If necessary, the protocol could be extended to zap those
3657 * from the client snapshot at the end, but so far that doesn't seem
3660 * To accomodate the changing MRU list, the starting point for requests
3661 * after the first request is supplied as a series of last seen
3662 * timestamps and associated addresses, the newest ones the client has
3663 * received. As long as at least one of those entries hasn't been
3664 * bumped to the head of the MRU list, ntpd can pick up at that point.
3665 * Otherwise, the request is failed and it is up to ntpq to back up and
3666 * provide the next newest entry's timestamps and addresses, conceivably
3667 * backing up all the way to the starting point.
3670 * nonce= Regurgitated nonce retrieved by the client
3671 * previously using CTL_OP_REQ_NONCE, demonstrating
3672 * ability to receive traffic sent to its address.
3673 * frags= Limit on datagrams (fragments) in response. Used
3674 * by newer ntpq versions instead of limit= when
3675 * retrieving multiple entries.
3676 * limit= Limit on MRU entries returned. One of frags= or
3677 * limit= must be provided.
3678 * limit=1 is a special case: Instead of fetching
3679 * beginning with the supplied starting point's
3680 * newer neighbor, fetch the supplied entry, and
3681 * in that case the #.last timestamp can be zero.
3682 * This enables fetching a single entry by IP
3683 * address. When limit is not one and frags= is
3684 * provided, the fragment limit controls.
3685 * mincount= (decimal) Return entries with count >= mincount.
3686 * laddr= Return entries associated with the server's IP
3687 * address given. No port specification is needed,
3688 * and any supplied is ignored.
3689 * resall= 0x-prefixed hex restrict bits which must all be
3690 * lit for an MRU entry to be included.
3691 * Has precedence over any resany=.
3692 * resany= 0x-prefixed hex restrict bits, at least one of
3693 * which must be list for an MRU entry to be
3695 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3696 * which client previously received.
3697 * addr.0= text of newest entry's IP address and port,
3698 * IPv6 addresses in bracketed form: [::]:123
3699 * last.1= timestamp of 2nd newest entry client has.
3700 * addr.1= address of 2nd newest entry.
3703 * ntpq provides as many last/addr pairs as will fit in a single request
3704 * packet, except for the first request in a MRU fetch operation.
3706 * The response begins with a new nonce value to be used for any
3707 * followup request. Following the nonce is the next newer entry than
3708 * referred to by last.0 and addr.0, if the "0" entry has not been
3709 * bumped to the front. If it has, the first entry returned will be the
3710 * next entry newer than referred to by last.1 and addr.1, and so on.
3711 * If none of the referenced entries remain unchanged, the request fails
3712 * and ntpq backs up to the next earlier set of entries to resync.
3714 * Except for the first response, the response begins with confirmation
3715 * of the entry that precedes the first additional entry provided:
3717 * last.older= hex l_fp timestamp matching one of the input
3718 * .last timestamps, which entry now precedes the
3719 * response 0. entry in the MRU list.
3720 * addr.older= text of address corresponding to older.last.
3722 * And in any case, a successful response contains sets of values
3723 * comprising entries, with the oldest numbered 0 and incrementing from
3726 * addr.# text of IPv4 or IPv6 address and port
3727 * last.# hex l_fp timestamp of last receipt
3728 * first.# hex l_fp timestamp of first receipt
3729 * ct.# count of packets received
3730 * mv.# mode and version
3731 * rs.# restriction mask (RES_* bits)
3733 * Note the code currently assumes there are no valid three letter
3734 * tags sent with each row, and needs to be adjusted if that changes.
3736 * The client should accept the values in any order, and ignore .#
3737 * values which it does not understand, to allow a smooth path to
3738 * future changes without requiring a new opcode. Clients can rely
3739 * on all *.0 values preceding any *.1 values, that is all values for
3740 * a given index number are together in the response.
3742 * The end of the response list is noted with one or two tag=value
3743 * pairs. Unconditionally:
3745 * now= 0x-prefixed l_fp timestamp at the server marking
3746 * the end of the operation.
3748 * If any entries were returned, now= is followed by:
3750 * last.newest= hex l_fp identical to last.# of the prior
3753 static void read_mru_list(
3754 struct recvbuf *rbufp,
3758 const char nonce_text[] = "nonce";
3759 const char frags_text[] = "frags";
3760 const char limit_text[] = "limit";
3761 const char mincount_text[] = "mincount";
3762 const char resall_text[] = "resall";
3763 const char resany_text[] = "resany";
3764 const char maxlstint_text[] = "maxlstint";
3765 const char laddr_text[] = "laddr";
3766 const char resaxx_fmt[] = "0x%hx";
3774 struct interface * lcladr;
3779 sockaddr_u addr[COUNTOF(last)];
3781 struct ctl_var * in_parms;
3782 const struct ctl_var * v;
3791 mon_entry * prior_mon;
3794 if (RES_NOMRULIST & restrict_mask) {
3795 ctl_error(CERR_PERMISSION);
3798 "mrulist from %s rejected due to nomrulist restriction",
3799 stoa(&rbufp->recv_srcadr));
3804 * fill in_parms var list with all possible input parameters.
3807 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
3808 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
3809 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
3810 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
3811 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
3812 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
3813 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
3814 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
3815 for (i = 0; i < COUNTOF(last); i++) {
3816 snprintf(buf, sizeof(buf), last_fmt, (int)i);
3817 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3818 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
3819 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3822 /* decode input parms */
3835 while (NULL != (v = ctl_getitem(in_parms, &val)) &&
3836 !(EOV & v->flags)) {
3839 if (!strcmp(nonce_text, v->text)) {
3842 pnonce = estrdup(val);
3843 } else if (!strcmp(frags_text, v->text)) {
3844 sscanf(val, "%hu", &frags);
3845 } else if (!strcmp(limit_text, v->text)) {
3846 sscanf(val, "%u", &limit);
3847 } else if (!strcmp(mincount_text, v->text)) {
3848 if (1 != sscanf(val, "%d", &mincount) ||
3851 } else if (!strcmp(resall_text, v->text)) {
3852 sscanf(val, resaxx_fmt, &resall);
3853 } else if (!strcmp(resany_text, v->text)) {
3854 sscanf(val, resaxx_fmt, &resany);
3855 } else if (!strcmp(maxlstint_text, v->text)) {
3856 sscanf(val, "%u", &maxlstint);
3857 } else if (!strcmp(laddr_text, v->text)) {
3858 if (decodenetnum(val, &laddr))
3859 lcladr = getinterface(&laddr, 0);
3860 } else if (1 == sscanf(v->text, last_fmt, &si) &&
3861 (size_t)si < COUNTOF(last)) {
3862 if (2 == sscanf(val, "0x%08x.%08x", &ui, &uf)) {
3865 if (!SOCK_UNSPEC(&addr[si]) &&
3869 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
3870 (size_t)si < COUNTOF(addr)) {
3871 if (decodenetnum(val, &addr[si])
3872 && last[si].l_ui && last[si].l_uf &&
3877 free_varlist(in_parms);
3880 /* return no responses until the nonce is validated */
3884 nonce_valid = validate_nonce(pnonce, rbufp);
3889 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
3890 frags > MRU_FRAGS_LIMIT) {
3891 ctl_error(CERR_BADVALUE);
3896 * If either frags or limit is not given, use the max.
3898 if (0 != frags && 0 == limit)
3900 else if (0 != limit && 0 == frags)
3901 frags = MRU_FRAGS_LIMIT;
3904 * Find the starting point if one was provided.
3907 for (i = 0; i < (size_t)priors; i++) {
3908 hash = MON_HASH(&addr[i]);
3909 for (mon = mon_hash[hash];
3911 mon = mon->hash_next)
3912 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
3915 if (L_ISEQU(&mon->last, &last[i]))
3921 /* If a starting point was provided... */
3923 /* and none could be found unmodified... */
3925 /* tell ntpq to try again with older entries */
3926 ctl_error(CERR_UNKNOWNVAR);
3929 /* confirm the prior entry used as starting point */
3930 ctl_putts("last.older", &mon->last);
3931 pch = sptoa(&mon->rmtadr);
3932 ctl_putunqstr("addr.older", pch, strlen(pch));
3935 * Move on to the first entry the client doesn't have,
3936 * except in the special case of a limit of one. In
3937 * that case return the starting point entry.
3940 mon = PREV_DLIST(mon_mru_list, mon, mru);
3941 } else { /* start with the oldest */
3942 mon = TAIL_DLIST(mon_mru_list, mru);
3946 * send up to limit= entries in up to frags= datagrams
3949 generate_nonce(rbufp, buf, sizeof(buf));
3950 ctl_putunqstr("nonce", buf, strlen(buf));
3953 mon != NULL && res_frags < frags && count < limit;
3954 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
3956 if (mon->count < mincount)
3958 if (resall && resall != (resall & mon->flags))
3960 if (resany && !(resany & mon->flags))
3962 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
3965 if (lcladr != NULL && mon->lcladr != lcladr)
3968 send_mru_entry(mon, count);
3970 send_random_tag_value(0);
3976 * If this batch completes the MRU list, say so explicitly with
3977 * a now= l_fp timestamp.
3981 send_random_tag_value(count - 1);
3982 ctl_putts("now", &now);
3983 /* if any entries were returned confirm the last */
3984 if (prior_mon != NULL)
3985 ctl_putts("last.newest", &prior_mon->last);
3992 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
3994 * To keep clients honest about not depending on the order of values,
3995 * and thereby avoid being locked into ugly workarounds to maintain
3996 * backward compatibility later as new fields are added to the response,
3997 * the order is random.
4005 const char addr_fmtu[] = "addr.%u";
4006 const char bcast_fmt[] = "bcast.%u";
4007 const char en_fmt[] = "en.%u"; /* enabled */
4008 const char name_fmt[] = "name.%u";
4009 const char flags_fmt[] = "flags.%u";
4010 const char tl_fmt[] = "tl.%u"; /* ttl */
4011 const char mc_fmt[] = "mc.%u"; /* mcast count */
4012 const char rx_fmt[] = "rx.%u";
4013 const char tx_fmt[] = "tx.%u";
4014 const char txerr_fmt[] = "txerr.%u";
4015 const char pc_fmt[] = "pc.%u"; /* peer count */
4016 const char up_fmt[] = "up.%u"; /* uptime */
4018 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4025 remaining = COUNTOF(sent);
4029 while (remaining > 0) {
4030 if (noisebits < 4) {
4031 noise = rand() ^ (rand() << 16);
4034 which = (noise & 0xf) % COUNTOF(sent);
4039 which = (which + 1) % COUNTOF(sent);
4044 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4045 pch = sptoa(&la->sin);
4046 ctl_putunqstr(tag, pch, strlen(pch));
4050 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4051 if (INT_BCASTOPEN & la->flags)
4052 pch = sptoa(&la->bcast);
4055 ctl_putunqstr(tag, pch, strlen(pch));
4059 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4060 ctl_putint(tag, !la->ignore_packets);
4064 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4065 ctl_putstr(tag, la->name, strlen(la->name));
4069 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4070 ctl_puthex(tag, (u_int)la->flags);
4074 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4075 ctl_putint(tag, la->last_ttl);
4079 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4080 ctl_putint(tag, la->num_mcast);
4084 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4085 ctl_putint(tag, la->received);
4089 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4090 ctl_putint(tag, la->sent);
4094 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4095 ctl_putint(tag, la->notsent);
4099 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4100 ctl_putuint(tag, la->peercnt);
4104 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4105 ctl_putuint(tag, current_time - la->starttime);
4111 send_random_tag_value((int)ifnum);
4116 * read_ifstats - send statistics for each local address, exposed by
4121 struct recvbuf * rbufp
4128 * loop over [0..sys_ifnum] searching ep_list for each
4131 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4132 for (la = ep_list; la != NULL; la = la->elink)
4133 if (ifidx == la->ifnum)
4137 /* return stats for one local address */
4138 send_ifstats_entry(la, ifidx);
4144 sockaddrs_from_restrict_u(
4154 psaA->sa.sa_family = AF_INET;
4155 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4156 psaM->sa.sa_family = AF_INET;
4157 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4159 psaA->sa.sa_family = AF_INET6;
4160 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4161 sizeof(psaA->sa6.sin6_addr));
4162 psaM->sa.sa_family = AF_INET6;
4163 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4164 sizeof(psaA->sa6.sin6_addr));
4170 * Send a restrict entry in response to a "ntpq -c reslist" request.
4172 * To keep clients honest about not depending on the order of values,
4173 * and thereby avoid being locked into ugly workarounds to maintain
4174 * backward compatibility later as new fields are added to the response,
4175 * the order is random.
4178 send_restrict_entry(
4184 const char addr_fmtu[] = "addr.%u";
4185 const char mask_fmtu[] = "mask.%u";
4186 const char hits_fmt[] = "hits.%u";
4187 const char flags_fmt[] = "flags.%u";
4189 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4198 const char * match_str;
4199 const char * access_str;
4201 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4202 remaining = COUNTOF(sent);
4206 while (remaining > 0) {
4207 if (noisebits < 2) {
4208 noise = rand() ^ (rand() << 16);
4211 which = (noise & 0x3) % COUNTOF(sent);
4216 which = (which + 1) % COUNTOF(sent);
4221 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4223 ctl_putunqstr(tag, pch, strlen(pch));
4227 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4229 ctl_putunqstr(tag, pch, strlen(pch));
4233 snprintf(tag, sizeof(tag), hits_fmt, idx);
4234 ctl_putuint(tag, pres->count);
4238 snprintf(tag, sizeof(tag), flags_fmt, idx);
4239 match_str = res_match_flags(pres->mflags);
4240 access_str = res_access_flags(pres->flags);
4241 if ('\0' == match_str[0]) {
4245 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4246 match_str, access_str);
4249 ctl_putunqstr(tag, pch, strlen(pch));
4255 send_random_tag_value((int)idx);
4266 for ( ; pres != NULL; pres = pres->link) {
4267 send_restrict_entry(pres, ipv6, *pidx);
4274 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4277 read_addr_restrictions(
4278 struct recvbuf * rbufp
4284 send_restrict_list(restrictlist4, FALSE, &idx);
4285 send_restrict_list(restrictlist6, TRUE, &idx);
4291 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4295 struct recvbuf * rbufp,
4299 const char ifstats_s[] = "ifstats";
4300 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4301 const char addr_rst_s[] = "addr_restrictions";
4302 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4303 struct ntp_control * cpkt;
4304 u_short qdata_octets;
4307 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4308 * used only for ntpq -c ifstats. With the addition of reslist
4309 * the same opcode was generalized to retrieve ordered lists
4310 * which require authentication. The request data is empty or
4311 * contains "ifstats" (not null terminated) to retrieve local
4312 * addresses and associated stats. It is "addr_restrictions"
4313 * to retrieve the IPv4 then IPv6 remote address restrictions,
4314 * which are access control lists. Other request data return
4317 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4318 qdata_octets = ntohs(cpkt->count);
4319 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4320 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4321 read_ifstats(rbufp);
4324 if (a_r_chars == qdata_octets &&
4325 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4326 read_addr_restrictions(rbufp);
4329 ctl_error(CERR_UNKNOWNVAR);
4334 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4336 static void req_nonce(
4337 struct recvbuf * rbufp,
4343 generate_nonce(rbufp, buf, sizeof(buf));
4344 ctl_putunqstr("nonce", buf, strlen(buf));
4350 * read_clockstatus - return clock radio status
4355 struct recvbuf *rbufp,
4361 * If no refclock support, no data to return
4363 ctl_error(CERR_BADASSOC);
4365 const struct ctl_var * v;
4373 struct ctl_var * kv;
4374 struct refclockstat cs;
4376 if (res_associd != 0) {
4377 peer = findpeerbyassoc(res_associd);
4380 * Find a clock for this jerk. If the system peer
4381 * is a clock use it, else search peer_list for one.
4383 if (sys_peer != NULL && (FLAG_REFCLOCK &
4387 for (peer = peer_list;
4389 peer = peer->p_link)
4390 if (FLAG_REFCLOCK & peer->flags)
4393 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4394 ctl_error(CERR_BADASSOC);
4398 * If we got here we have a peer which is a clock. Get his
4402 refclock_control(&peer->srcadr, NULL, &cs);
4405 * Look for variables in the packet.
4407 rpkt.status = htons(ctlclkstatus(&cs));
4408 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4409 wants = emalloc_zero(wants_alloc);
4411 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4412 if (!(EOV & v->flags)) {
4413 wants[v->code] = TRUE;
4416 v = ctl_getitem(kv, &valuep);
4418 if (EOV & v->flags) {
4419 ctl_error(CERR_UNKNOWNVAR);
4421 free_varlist(cs.kv_list);
4424 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4430 for (i = 1; i <= CC_MAXCODE; i++)
4432 ctl_putclock(i, &cs, TRUE);
4434 for (i = 0; !(EOV & kv[i].flags); i++)
4435 if (wants[i + CC_MAXCODE + 1])
4436 ctl_putdata(kv[i].text,
4440 for (cc = def_clock_var; *cc != 0; cc++)
4441 ctl_putclock((int)*cc, &cs, FALSE);
4442 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4443 if (DEF & kv->flags)
4444 ctl_putdata(kv->text, strlen(kv->text),
4449 free_varlist(cs.kv_list);
4457 * write_clockstatus - we don't do this
4462 struct recvbuf *rbufp,
4466 ctl_error(CERR_PERMISSION);
4470 * Trap support from here on down. We send async trap messages when the
4471 * upper levels report trouble. Traps can by set either by control
4472 * messages or by configuration.
4475 * set_trap - set a trap in response to a control message
4479 struct recvbuf *rbufp,
4486 * See if this guy is allowed
4488 if (restrict_mask & RES_NOTRAP) {
4489 ctl_error(CERR_PERMISSION);
4494 * Determine his allowed trap type.
4496 traptype = TRAP_TYPE_PRIO;
4497 if (restrict_mask & RES_LPTRAP)
4498 traptype = TRAP_TYPE_NONPRIO;
4501 * Call ctlsettrap() to do the work. Return
4502 * an error if it can't assign the trap.
4504 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4506 ctl_error(CERR_NORESOURCE);
4512 * unset_trap - unset a trap in response to a control message
4516 struct recvbuf *rbufp,
4523 * We don't prevent anyone from removing his own trap unless the
4524 * trap is configured. Note we also must be aware of the
4525 * possibility that restriction flags were changed since this
4526 * guy last set his trap. Set the trap type based on this.
4528 traptype = TRAP_TYPE_PRIO;
4529 if (restrict_mask & RES_LPTRAP)
4530 traptype = TRAP_TYPE_NONPRIO;
4533 * Call ctlclrtrap() to clear this out.
4535 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4536 ctl_error(CERR_BADASSOC);
4542 * ctlsettrap - called to set a trap
4547 struct interface *linter,
4553 struct ctl_trap *tp;
4554 struct ctl_trap *tptouse;
4557 * See if we can find this trap. If so, we only need update
4558 * the flags and the time.
4560 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4563 case TRAP_TYPE_CONFIG:
4564 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4567 case TRAP_TYPE_PRIO:
4568 if (tp->tr_flags & TRAP_CONFIGURED)
4569 return (1); /* don't change anything */
4570 tp->tr_flags = TRAP_INUSE;
4573 case TRAP_TYPE_NONPRIO:
4574 if (tp->tr_flags & TRAP_CONFIGURED)
4575 return (1); /* don't change anything */
4576 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4579 tp->tr_settime = current_time;
4585 * First we heard of this guy. Try to find a trap structure
4586 * for him to use, clearing out lesser priority guys if we
4587 * have to. Clear out anyone who's expired while we're at it.
4590 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4592 if ((TRAP_INUSE & tp->tr_flags) &&
4593 !(TRAP_CONFIGURED & tp->tr_flags) &&
4594 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4598 if (!(TRAP_INUSE & tp->tr_flags)) {
4600 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4603 case TRAP_TYPE_CONFIG:
4604 if (tptouse == NULL) {
4608 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4609 !(TRAP_NONPRIO & tp->tr_flags))
4612 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4613 && (TRAP_NONPRIO & tp->tr_flags)) {
4617 if (tptouse->tr_origtime <
4622 case TRAP_TYPE_PRIO:
4623 if ( TRAP_NONPRIO & tp->tr_flags) {
4624 if (tptouse == NULL ||
4626 tptouse->tr_flags) &&
4627 tptouse->tr_origtime <
4633 case TRAP_TYPE_NONPRIO:
4640 * If we don't have room for him return an error.
4642 if (tptouse == NULL)
4646 * Set up this structure for him.
4648 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4649 tptouse->tr_count = tptouse->tr_resets = 0;
4650 tptouse->tr_sequence = 1;
4651 tptouse->tr_addr = *raddr;
4652 tptouse->tr_localaddr = linter;
4653 tptouse->tr_version = (u_char) version;
4654 tptouse->tr_flags = TRAP_INUSE;
4655 if (traptype == TRAP_TYPE_CONFIG)
4656 tptouse->tr_flags |= TRAP_CONFIGURED;
4657 else if (traptype == TRAP_TYPE_NONPRIO)
4658 tptouse->tr_flags |= TRAP_NONPRIO;
4665 * ctlclrtrap - called to clear a trap
4670 struct interface *linter,
4674 register struct ctl_trap *tp;
4676 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4679 if (tp->tr_flags & TRAP_CONFIGURED
4680 && traptype != TRAP_TYPE_CONFIG)
4690 * ctlfindtrap - find a trap given the remote and local addresses
4692 static struct ctl_trap *
4695 struct interface *linter
4700 for (n = 0; n < COUNTOF(ctl_traps); n++)
4701 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4702 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4703 && (linter == ctl_traps[n].tr_localaddr))
4704 return &ctl_traps[n];
4711 * report_event - report an event to the trappers
4715 int err, /* error code */
4716 struct peer *peer, /* peer structure pointer */
4717 const char *str /* protostats string */
4720 char statstr[NTP_MAXSTRLEN];
4725 * Report the error to the protostats file, system log and
4731 * Discard a system report if the number of reports of
4732 * the same type exceeds the maximum.
4734 if (ctl_sys_last_event != (u_char)err)
4735 ctl_sys_num_events= 0;
4736 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4739 ctl_sys_last_event = (u_char)err;
4740 ctl_sys_num_events++;
4741 snprintf(statstr, sizeof(statstr),
4742 "0.0.0.0 %04x %02x %s",
4743 ctlsysstatus(), err, eventstr(err));
4745 len = strlen(statstr);
4746 snprintf(statstr + len, sizeof(statstr) - len,
4750 msyslog(LOG_INFO, "%s", statstr);
4754 * Discard a peer report if the number of reports of
4755 * the same type exceeds the maximum for that peer.
4760 errlast = (u_char)err & ~PEER_EVENT;
4761 if (peer->last_event == errlast)
4762 peer->num_events = 0;
4763 if (peer->num_events >= CTL_PEER_MAXEVENTS)
4766 peer->last_event = errlast;
4768 if (ISREFCLOCKADR(&peer->srcadr))
4769 src = refnumtoa(&peer->srcadr);
4771 src = stoa(&peer->srcadr);
4773 snprintf(statstr, sizeof(statstr),
4774 "%s %04x %02x %s", src,
4775 ctlpeerstatus(peer), err, eventstr(err));
4777 len = strlen(statstr);
4778 snprintf(statstr + len, sizeof(statstr) - len,
4781 NLOG(NLOG_PEEREVENT)
4782 msyslog(LOG_INFO, "%s", statstr);
4784 record_proto_stats(statstr);
4787 printf("event at %lu %s\n", current_time, statstr);
4791 * If no trappers, return.
4793 if (num_ctl_traps <= 0)
4797 * Set up the outgoing packet variables
4799 res_opcode = CTL_OP_ASYNCMSG;
4802 res_authenticate = FALSE;
4803 datapt = rpkt.u.data;
4804 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
4805 if (!(err & PEER_EVENT)) {
4807 rpkt.status = htons(ctlsysstatus());
4809 /* Include the core system variables and the list. */
4810 for (i = 1; i <= CS_VARLIST; i++)
4813 INSIST(peer != NULL);
4814 rpkt.associd = htons(peer->associd);
4815 rpkt.status = htons(ctlpeerstatus(peer));
4817 /* Dump it all. Later, maybe less. */
4818 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
4819 ctl_putpeer(i, peer);
4822 * for clock exception events: add clock variables to
4823 * reflect info on exception
4825 if (err == PEVNT_CLOCK) {
4826 struct refclockstat cs;
4830 refclock_control(&peer->srcadr, NULL, &cs);
4832 ctl_puthex("refclockstatus",
4835 for (i = 1; i <= CC_MAXCODE; i++)
4836 ctl_putclock(i, &cs, FALSE);
4837 for (kv = cs.kv_list;
4838 kv != NULL && !(EOV & kv->flags);
4840 if (DEF & kv->flags)
4841 ctl_putdata(kv->text,
4844 free_varlist(cs.kv_list);
4846 #endif /* REFCLOCK */
4850 * We're done, return.
4857 * mprintf_event - printf-style varargs variant of report_event()
4861 int evcode, /* event code */
4862 struct peer * p, /* may be NULL */
4863 const char * fmt, /* msnprintf format */
4872 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
4874 report_event(evcode, p, msg);
4881 * ctl_clr_stats - clear stat counters
4886 ctltimereset = current_time;
4889 numctlresponses = 0;
4894 numctlinputresp = 0;
4895 numctlinputfrag = 0;
4897 numctlbadoffset = 0;
4898 numctlbadversion = 0;
4899 numctldatatooshort = 0;
4906 const struct ctl_var *k
4915 while (!(EOV & (k++)->flags))
4918 ENSURE(c <= USHRT_MAX);
4925 struct ctl_var **kv,
4935 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
4937 buf = emalloc(size);
4942 k[c + 1].text = NULL;
4943 k[c + 1].flags = EOV;
4951 struct ctl_var **kv,
4962 if (NULL == data || !size)
4967 while (!(EOV & k->flags)) {
4968 if (NULL == k->text) {
4970 memcpy(td, data, size);
4977 while (*t != '=' && *s == *t) {
4981 if (*s == *t && ((*t == '=') || !*t)) {
4982 td = erealloc((void *)(intptr_t)k->text, size);
4983 memcpy(td, data, size);
4992 td = add_var(kv, size, def);
4993 memcpy(td, data, size);
5004 set_var(&ext_sys_var, data, size, def);
5009 * get_ext_sys_var() retrieves the value of a user-defined variable or
5010 * NULL if the variable has not been setvar'd.
5013 get_ext_sys_var(const char *tag)
5021 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5022 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5023 if ('=' == v->text[c]) {
5024 val = v->text + c + 1;
5026 } else if ('\0' == v->text[c]) {
5044 for (k = kv; !(k->flags & EOV); k++)
5045 free((void *)(intptr_t)k->text);