2 * ntp_control.c - respond to mode 6 control messages and send async
3 * traps. Provides service to ntpq and others.
7 * $FreeBSD: head/contrib/ntp/ntpd/ntp_control.c 276071 2014-12-22 18:54:55Z delphij $
18 #ifdef HAVE_NETINET_IN_H
19 # include <netinet/in.h>
21 #include <arpa/inet.h>
25 #include "ntp_refclock.h"
26 #include "ntp_control.h"
27 #include "ntp_unixtime.h"
28 #include "ntp_stdlib.h"
29 #include "ntp_config.h"
30 #include "ntp_crypto.h"
31 #include "ntp_assert.h"
32 #include "ntp_leapsec.h"
33 #include "ntp_md5.h" /* provides OpenSSL digest API */
34 #include "lib_strbuf.h"
36 # include "ntp_syscall.h"
41 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
45 * Structure to hold request procedure information
49 short control_code; /* defined request code */
50 #define NO_REQUEST (-1)
51 u_short flags; /* flags word */
52 /* Only one flag. Authentication required or not. */
55 void (*handler) (struct recvbuf *, int); /* handle request */
60 * Request processing routines
62 static void ctl_error (u_char);
64 static u_short ctlclkstatus (struct refclockstat *);
66 static void ctl_flushpkt (u_char);
67 static void ctl_putdata (const char *, unsigned int, int);
68 static void ctl_putstr (const char *, const char *, size_t);
69 static void ctl_putdblf (const char *, int, int, double);
70 #define ctl_putdbl(tag, d) ctl_putdblf(tag, 1, 3, d)
71 #define ctl_putdbl6(tag, d) ctl_putdblf(tag, 1, 6, d)
72 #define ctl_putsfp(tag, sfp) ctl_putdblf(tag, 0, -1, \
74 static void ctl_putuint (const char *, u_long);
75 static void ctl_puthex (const char *, u_long);
76 static void ctl_putint (const char *, long);
77 static void ctl_putts (const char *, l_fp *);
78 static void ctl_putadr (const char *, u_int32,
80 static void ctl_putrefid (const char *, u_int32);
81 static void ctl_putarray (const char *, double *, int);
82 static void ctl_putsys (int);
83 static void ctl_putpeer (int, struct peer *);
84 static void ctl_putfs (const char *, tstamp_t);
86 static void ctl_putclock (int, struct refclockstat *, int);
88 static const struct ctl_var *ctl_getitem(const struct ctl_var *,
90 static u_short count_var (const struct ctl_var *);
91 static void control_unspec (struct recvbuf *, int);
92 static void read_status (struct recvbuf *, int);
93 static void read_sysvars (void);
94 static void read_peervars (void);
95 static void read_variables (struct recvbuf *, int);
96 static void write_variables (struct recvbuf *, int);
97 static void read_clockstatus(struct recvbuf *, int);
98 static void write_clockstatus(struct recvbuf *, int);
99 static void set_trap (struct recvbuf *, int);
100 static void save_config (struct recvbuf *, int);
101 static void configure (struct recvbuf *, int);
102 static void send_mru_entry (mon_entry *, int);
103 static void send_random_tag_value(int);
104 static void read_mru_list (struct recvbuf *, int);
105 static void send_ifstats_entry(endpt *, u_int);
106 static void read_ifstats (struct recvbuf *);
107 static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *,
109 static void send_restrict_entry(restrict_u *, int, u_int);
110 static void send_restrict_list(restrict_u *, int, u_int *);
111 static void read_addr_restrictions(struct recvbuf *);
112 static void read_ordlist (struct recvbuf *, int);
113 static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32);
114 static void generate_nonce (struct recvbuf *, char *, size_t);
115 static int validate_nonce (const char *, struct recvbuf *);
116 static void req_nonce (struct recvbuf *, int);
117 static void unset_trap (struct recvbuf *, int);
118 static struct ctl_trap *ctlfindtrap(sockaddr_u *,
121 static const struct ctl_proc control_codes[] = {
122 { CTL_OP_UNSPEC, NOAUTH, control_unspec },
123 { CTL_OP_READSTAT, NOAUTH, read_status },
124 { CTL_OP_READVAR, NOAUTH, read_variables },
125 { CTL_OP_WRITEVAR, AUTH, write_variables },
126 { CTL_OP_READCLOCK, NOAUTH, read_clockstatus },
127 { CTL_OP_WRITECLOCK, NOAUTH, write_clockstatus },
128 { CTL_OP_SETTRAP, NOAUTH, set_trap },
129 { CTL_OP_CONFIGURE, AUTH, configure },
130 { CTL_OP_SAVECONFIG, AUTH, save_config },
131 { CTL_OP_READ_MRU, NOAUTH, read_mru_list },
132 { CTL_OP_READ_ORDLIST_A, AUTH, read_ordlist },
133 { CTL_OP_REQ_NONCE, NOAUTH, req_nonce },
134 { CTL_OP_UNSETTRAP, NOAUTH, unset_trap },
135 { NO_REQUEST, 0, NULL }
139 * System variables we understand
143 #define CS_PRECISION 3
144 #define CS_ROOTDELAY 4
145 #define CS_ROOTDISPERSION 5
155 #define CS_PROCESSOR 15
157 #define CS_VERSION 17
159 #define CS_VARLIST 19
161 #define CS_LEAPTAB 21
162 #define CS_LEAPEND 22
164 #define CS_MRU_ENABLED 24
165 #define CS_MRU_DEPTH 25
166 #define CS_MRU_DEEPEST 26
167 #define CS_MRU_MINDEPTH 27
168 #define CS_MRU_MAXAGE 28
169 #define CS_MRU_MAXDEPTH 29
170 #define CS_MRU_MEM 30
171 #define CS_MRU_MAXMEM 31
172 #define CS_SS_UPTIME 32
173 #define CS_SS_RESET 33
174 #define CS_SS_RECEIVED 34
175 #define CS_SS_THISVER 35
176 #define CS_SS_OLDVER 36
177 #define CS_SS_BADFORMAT 37
178 #define CS_SS_BADAUTH 38
179 #define CS_SS_DECLINED 39
180 #define CS_SS_RESTRICTED 40
181 #define CS_SS_LIMITED 41
182 #define CS_SS_KODSENT 42
183 #define CS_SS_PROCESSED 43
184 #define CS_PEERADR 44
185 #define CS_PEERMODE 45
186 #define CS_BCASTDELAY 46
187 #define CS_AUTHDELAY 47
188 #define CS_AUTHKEYS 48
189 #define CS_AUTHFREEK 49
190 #define CS_AUTHKLOOKUPS 50
191 #define CS_AUTHKNOTFOUND 51
192 #define CS_AUTHKUNCACHED 52
193 #define CS_AUTHKEXPIRED 53
194 #define CS_AUTHENCRYPTS 54
195 #define CS_AUTHDECRYPTS 55
196 #define CS_AUTHRESET 56
197 #define CS_K_OFFSET 57
199 #define CS_K_MAXERR 59
200 #define CS_K_ESTERR 60
201 #define CS_K_STFLAGS 61
202 #define CS_K_TIMECONST 62
203 #define CS_K_PRECISION 63
204 #define CS_K_FREQTOL 64
205 #define CS_K_PPS_FREQ 65
206 #define CS_K_PPS_STABIL 66
207 #define CS_K_PPS_JITTER 67
208 #define CS_K_PPS_CALIBDUR 68
209 #define CS_K_PPS_CALIBS 69
210 #define CS_K_PPS_CALIBERRS 70
211 #define CS_K_PPS_JITEXC 71
212 #define CS_K_PPS_STBEXC 72
213 #define CS_KERN_FIRST CS_K_OFFSET
214 #define CS_KERN_LAST CS_K_PPS_STBEXC
215 #define CS_IOSTATS_RESET 73
216 #define CS_TOTAL_RBUF 74
217 #define CS_FREE_RBUF 75
218 #define CS_USED_RBUF 76
219 #define CS_RBUF_LOWATER 77
220 #define CS_IO_DROPPED 78
221 #define CS_IO_IGNORED 79
222 #define CS_IO_RECEIVED 80
223 #define CS_IO_SENT 81
224 #define CS_IO_SENDFAILED 82
225 #define CS_IO_WAKEUPS 83
226 #define CS_IO_GOODWAKEUPS 84
227 #define CS_TIMERSTATS_RESET 85
228 #define CS_TIMER_OVERRUNS 86
229 #define CS_TIMER_XMTS 87
231 #define CS_MAX_NOAUTOKEY CS_FUZZ
233 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
234 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
235 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
236 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
237 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
238 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
239 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
240 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
241 #define CS_MAXCODE CS_DIGEST
242 #else /* !AUTOKEY follows */
243 #define CS_MAXCODE CS_MAX_NOAUTOKEY
244 #endif /* !AUTOKEY */
247 * Peer variables we understand
250 #define CP_AUTHENABLE 2
251 #define CP_AUTHENTIC 3
258 #define CP_STRATUM 10
261 #define CP_PRECISION 13
262 #define CP_ROOTDELAY 14
263 #define CP_ROOTDISPERSION 15
265 #define CP_REFTIME 17
270 #define CP_UNREACH 22
275 #define CP_DISPERSION 27
277 #define CP_FILTDELAY 29
278 #define CP_FILTOFFSET 30
280 #define CP_RECEIVED 32
282 #define CP_FILTERROR 34
285 #define CP_VARLIST 37
290 #define CP_SRCHOST 42
291 #define CP_TIMEREC 43
292 #define CP_TIMEREACH 44
293 #define CP_BADAUTH 45
294 #define CP_BOGUSORG 46
296 #define CP_SELDISP 48
297 #define CP_SELBROKEN 49
298 #define CP_CANDIDATE 50
299 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
301 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
302 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
303 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
304 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
305 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
306 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
307 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
308 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
309 #define CP_MAXCODE CP_IDENT
310 #else /* !AUTOKEY follows */
311 #define CP_MAXCODE CP_MAX_NOAUTOKEY
312 #endif /* !AUTOKEY */
315 * Clock variables we understand
318 #define CC_TIMECODE 2
321 #define CC_BADFORMAT 5
323 #define CC_FUDGETIME1 7
324 #define CC_FUDGETIME2 8
325 #define CC_FUDGEVAL1 9
326 #define CC_FUDGEVAL2 10
329 #define CC_VARLIST 13
330 #define CC_MAXCODE CC_VARLIST
333 * System variable values. The array can be indexed by the variable
334 * index to find the textual name.
336 static const struct ctl_var sys_var[] = {
337 { 0, PADDING, "" }, /* 0 */
338 { CS_LEAP, RW, "leap" }, /* 1 */
339 { CS_STRATUM, RO, "stratum" }, /* 2 */
340 { CS_PRECISION, RO, "precision" }, /* 3 */
341 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
342 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
343 { CS_REFID, RO, "refid" }, /* 6 */
344 { CS_REFTIME, RO, "reftime" }, /* 7 */
345 { CS_POLL, RO, "tc" }, /* 8 */
346 { CS_PEERID, RO, "peer" }, /* 9 */
347 { CS_OFFSET, RO, "offset" }, /* 10 */
348 { CS_DRIFT, RO, "frequency" }, /* 11 */
349 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
350 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
351 { CS_CLOCK, RO, "clock" }, /* 14 */
352 { CS_PROCESSOR, RO, "processor" }, /* 15 */
353 { CS_SYSTEM, RO, "system" }, /* 16 */
354 { CS_VERSION, RO, "version" }, /* 17 */
355 { CS_STABIL, RO, "clk_wander" }, /* 18 */
356 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
357 { CS_TAI, RO, "tai" }, /* 20 */
358 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
359 { CS_LEAPEND, RO, "expire" }, /* 22 */
360 { CS_RATE, RO, "mintc" }, /* 23 */
361 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
362 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
363 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
364 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
365 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
366 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
367 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
368 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
369 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
370 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
371 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
372 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
373 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
374 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
375 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
376 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
377 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
378 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
379 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
380 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
381 { CS_PEERADR, RO, "peeradr" }, /* 44 */
382 { CS_PEERMODE, RO, "peermode" }, /* 45 */
383 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 46 */
384 { CS_AUTHDELAY, RO, "authdelay" }, /* 47 */
385 { CS_AUTHKEYS, RO, "authkeys" }, /* 48 */
386 { CS_AUTHFREEK, RO, "authfreek" }, /* 49 */
387 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 50 */
388 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 51 */
389 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 52 */
390 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 53 */
391 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 54 */
392 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 55 */
393 { CS_AUTHRESET, RO, "authreset" }, /* 56 */
394 { CS_K_OFFSET, RO, "koffset" }, /* 57 */
395 { CS_K_FREQ, RO, "kfreq" }, /* 58 */
396 { CS_K_MAXERR, RO, "kmaxerr" }, /* 59 */
397 { CS_K_ESTERR, RO, "kesterr" }, /* 60 */
398 { CS_K_STFLAGS, RO, "kstflags" }, /* 61 */
399 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 62 */
400 { CS_K_PRECISION, RO, "kprecis" }, /* 63 */
401 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 64 */
402 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 65 */
403 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 66 */
404 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 67 */
405 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 68 */
406 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 69 */
407 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 70 */
408 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 71 */
409 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 72 */
410 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 73 */
411 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 74 */
412 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 75 */
413 { CS_USED_RBUF, RO, "used_rbuf" }, /* 76 */
414 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 77 */
415 { CS_IO_DROPPED, RO, "io_dropped" }, /* 78 */
416 { CS_IO_IGNORED, RO, "io_ignored" }, /* 79 */
417 { CS_IO_RECEIVED, RO, "io_received" }, /* 80 */
418 { CS_IO_SENT, RO, "io_sent" }, /* 81 */
419 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 82 */
420 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 83 */
421 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 84 */
422 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 85 */
423 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 86 */
424 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 87 */
425 { CS_FUZZ, RO, "fuzz" }, /* 88 */
427 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
428 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
429 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
430 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
431 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
432 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
433 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
434 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
436 { 0, EOV, "" } /* 87/95 */
439 static struct ctl_var *ext_sys_var = NULL;
442 * System variables we print by default (in fuzzball order,
445 static const u_char def_sys_var[] = {
484 static const struct ctl_var peer_var[] = {
485 { 0, PADDING, "" }, /* 0 */
486 { CP_CONFIG, RO, "config" }, /* 1 */
487 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
488 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
489 { CP_SRCADR, RO, "srcadr" }, /* 4 */
490 { CP_SRCPORT, RO, "srcport" }, /* 5 */
491 { CP_DSTADR, RO, "dstadr" }, /* 6 */
492 { CP_DSTPORT, RO, "dstport" }, /* 7 */
493 { CP_LEAP, RO, "leap" }, /* 8 */
494 { CP_HMODE, RO, "hmode" }, /* 9 */
495 { CP_STRATUM, RO, "stratum" }, /* 10 */
496 { CP_PPOLL, RO, "ppoll" }, /* 11 */
497 { CP_HPOLL, RO, "hpoll" }, /* 12 */
498 { CP_PRECISION, RO, "precision" }, /* 13 */
499 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
500 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
501 { CP_REFID, RO, "refid" }, /* 16 */
502 { CP_REFTIME, RO, "reftime" }, /* 17 */
503 { CP_ORG, RO, "org" }, /* 18 */
504 { CP_REC, RO, "rec" }, /* 19 */
505 { CP_XMT, RO, "xleave" }, /* 20 */
506 { CP_REACH, RO, "reach" }, /* 21 */
507 { CP_UNREACH, RO, "unreach" }, /* 22 */
508 { CP_TIMER, RO, "timer" }, /* 23 */
509 { CP_DELAY, RO, "delay" }, /* 24 */
510 { CP_OFFSET, RO, "offset" }, /* 25 */
511 { CP_JITTER, RO, "jitter" }, /* 26 */
512 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
513 { CP_KEYID, RO, "keyid" }, /* 28 */
514 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
515 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
516 { CP_PMODE, RO, "pmode" }, /* 31 */
517 { CP_RECEIVED, RO, "received"}, /* 32 */
518 { CP_SENT, RO, "sent" }, /* 33 */
519 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
520 { CP_FLASH, RO, "flash" }, /* 35 */
521 { CP_TTL, RO, "ttl" }, /* 36 */
522 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
523 { CP_IN, RO, "in" }, /* 38 */
524 { CP_OUT, RO, "out" }, /* 39 */
525 { CP_RATE, RO, "headway" }, /* 40 */
526 { CP_BIAS, RO, "bias" }, /* 41 */
527 { CP_SRCHOST, RO, "srchost" }, /* 42 */
528 { CP_TIMEREC, RO, "timerec" }, /* 43 */
529 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
530 { CP_BADAUTH, RO, "badauth" }, /* 45 */
531 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
532 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
533 { CP_SELDISP, RO, "seldisp" }, /* 48 */
534 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
535 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
537 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
538 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
539 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
540 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
541 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
542 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
543 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
544 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
546 { 0, EOV, "" } /* 50/58 */
551 * Peer variables we print by default
553 static const u_char def_peer_var[] = {
602 * Clock variable list
604 static const struct ctl_var clock_var[] = {
605 { 0, PADDING, "" }, /* 0 */
606 { CC_TYPE, RO, "type" }, /* 1 */
607 { CC_TIMECODE, RO, "timecode" }, /* 2 */
608 { CC_POLL, RO, "poll" }, /* 3 */
609 { CC_NOREPLY, RO, "noreply" }, /* 4 */
610 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
611 { CC_BADDATA, RO, "baddata" }, /* 6 */
612 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
613 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
614 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
615 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
616 { CC_FLAGS, RO, "flags" }, /* 11 */
617 { CC_DEVICE, RO, "device" }, /* 12 */
618 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
619 { 0, EOV, "" } /* 14 */
624 * Clock variables printed by default
626 static const u_char def_clock_var[] = {
628 CC_TYPE, /* won't be output if device = known */
644 * MRU string constants shared by send_mru_entry() and read_mru_list().
646 static const char addr_fmt[] = "addr.%d";
647 static const char last_fmt[] = "last.%d";
650 * System and processor definitions.
654 # define STR_SYSTEM "UNIX"
656 # ifndef STR_PROCESSOR
657 # define STR_PROCESSOR "unknown"
660 static const char str_system[] = STR_SYSTEM;
661 static const char str_processor[] = STR_PROCESSOR;
663 # include <sys/utsname.h>
664 static struct utsname utsnamebuf;
665 #endif /* HAVE_UNAME */
668 * Trap structures. We only allow a few of these, and send a copy of
669 * each async message to each live one. Traps time out after an hour, it
670 * is up to the trap receipient to keep resetting it to avoid being
674 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
678 * Type bits, for ctlsettrap() call.
680 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
681 #define TRAP_TYPE_PRIO 1 /* priority trap */
682 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
686 * List relating reference clock types to control message time sources.
687 * Index by the reference clock type. This list will only be used iff
688 * the reference clock driver doesn't set peer->sstclktype to something
689 * different than CTL_SST_TS_UNSPEC.
692 static const u_char clocktypes[] = {
693 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
694 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
695 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
696 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
697 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
698 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
699 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
700 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
701 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
702 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
703 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
704 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
705 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
706 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
707 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
708 CTL_SST_TS_NTP, /* not used (15) */
709 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
710 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
711 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
712 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
713 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
714 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
715 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
716 CTL_SST_TS_NTP, /* not used (23) */
717 CTL_SST_TS_NTP, /* not used (24) */
718 CTL_SST_TS_NTP, /* not used (25) */
719 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
720 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
721 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
722 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
723 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
724 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
725 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
726 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
727 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
728 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
729 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
730 CTL_SST_TS_LF, /* REFCLK_FG (37) */
731 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
732 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
733 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
734 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
735 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
736 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
737 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
738 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
739 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
741 #endif /* REFCLOCK */
745 * Keyid used for authenticating write requests.
747 keyid_t ctl_auth_keyid;
750 * We keep track of the last error reported by the system internally
752 static u_char ctl_sys_last_event;
753 static u_char ctl_sys_num_events;
757 * Statistic counters to keep track of requests and responses.
759 u_long ctltimereset; /* time stats reset */
760 u_long numctlreq; /* number of requests we've received */
761 u_long numctlbadpkts; /* number of bad control packets */
762 u_long numctlresponses; /* number of resp packets sent with data */
763 u_long numctlfrags; /* number of fragments sent */
764 u_long numctlerrors; /* number of error responses sent */
765 u_long numctltooshort; /* number of too short input packets */
766 u_long numctlinputresp; /* number of responses on input */
767 u_long numctlinputfrag; /* number of fragments on input */
768 u_long numctlinputerr; /* number of input pkts with err bit set */
769 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
770 u_long numctlbadversion; /* number of input pkts with unknown version */
771 u_long numctldatatooshort; /* data too short for count */
772 u_long numctlbadop; /* bad op code found in packet */
773 u_long numasyncmsgs; /* number of async messages we've sent */
776 * Response packet used by these routines. Also some state information
777 * so that we can handle packet formatting within a common set of
778 * subroutines. Note we try to enter data in place whenever possible,
779 * but the need to set the more bit correctly means we occasionally
780 * use the extra buffer and copy.
782 static struct ntp_control rpkt;
783 static u_char res_version;
784 static u_char res_opcode;
785 static associd_t res_associd;
786 static u_short res_frags; /* datagrams in this response */
787 static int res_offset; /* offset of payload in response */
788 static u_char * datapt;
789 static u_char * dataend;
790 static int datalinelen;
791 static int datasent; /* flag to avoid initial ", " */
792 static int datanotbinflag;
793 static sockaddr_u *rmt_addr;
794 static struct interface *lcl_inter;
796 static u_char res_authenticate;
797 static u_char res_authokay;
798 static keyid_t res_keyid;
800 #define MAXDATALINELEN (72)
802 static u_char res_async; /* sending async trap response? */
805 * Pointers for saving state when decoding request packets
811 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
815 * init_control - initialize request data
824 #endif /* HAVE_UNAME */
829 ctl_sys_last_event = EVNT_UNSPEC;
830 ctl_sys_num_events = 0;
833 for (i = 0; i < COUNTOF(ctl_traps); i++)
834 ctl_traps[i].tr_flags = 0;
839 * ctl_error - send an error response for the current request
849 DPRINTF(3, ("sending control error %u\n", errcode));
852 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
853 * have already been filled in.
855 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
856 (res_opcode & CTL_OP_MASK);
857 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
861 * send packet and bump counters
863 if (res_authenticate && sys_authenticate) {
864 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
866 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
867 CTL_HEADER_LEN + maclen);
869 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
874 * save_config - Implements ntpq -c "saveconfig <filename>"
875 * Writes current configuration including any runtime
876 * changes by ntpq's :config or config-from-file
880 struct recvbuf *rbufp,
889 const char savedconfig_eq[] = "savedconfig=";
890 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
896 if (RES_NOMODIFY & restrict_mask) {
897 snprintf(reply, sizeof(reply),
898 "saveconfig prohibited by restrict ... nomodify");
899 ctl_putdata(reply, strlen(reply), 0);
903 "saveconfig from %s rejected due to nomodify restriction",
904 stoa(&rbufp->recv_srcadr));
910 if (NULL == saveconfigdir) {
911 snprintf(reply, sizeof(reply),
912 "saveconfig prohibited, no saveconfigdir configured");
913 ctl_putdata(reply, strlen(reply), 0);
917 "saveconfig from %s rejected, no saveconfigdir",
918 stoa(&rbufp->recv_srcadr));
922 if (0 == reqend - reqpt)
925 strlcpy(filespec, reqpt, sizeof(filespec));
929 * allow timestamping of the saved config filename with
930 * strftime() format such as:
931 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
932 * XXX: Nice feature, but not too safe.
934 if (0 == strftime(filename, sizeof(filename), filespec,
936 strlcpy(filename, filespec, sizeof(filename));
939 * Conceptually we should be searching for DIRSEP in filename,
940 * however Windows actually recognizes both forward and
941 * backslashes as equivalent directory separators at the API
942 * level. On POSIX systems we could allow '\\' but such
943 * filenames are tricky to manipulate from a shell, so just
944 * reject both types of slashes on all platforms.
946 if (strchr(filename, '\\') || strchr(filename, '/')) {
947 snprintf(reply, sizeof(reply),
948 "saveconfig does not allow directory in filename");
949 ctl_putdata(reply, strlen(reply), 0);
952 "saveconfig with path from %s rejected",
953 stoa(&rbufp->recv_srcadr));
957 snprintf(fullpath, sizeof(fullpath), "%s%s",
958 saveconfigdir, filename);
960 fd = open(fullpath, O_CREAT | O_TRUNC | O_WRONLY,
965 fptr = fdopen(fd, "w");
967 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
968 snprintf(reply, sizeof(reply),
969 "Unable to save configuration to file %s",
972 "saveconfig %s from %s failed", filename,
973 stoa(&rbufp->recv_srcadr));
975 snprintf(reply, sizeof(reply),
976 "Configuration saved to %s", filename);
978 "Configuration saved to %s (requested by %s)",
979 fullpath, stoa(&rbufp->recv_srcadr));
981 * save the output filename in system variable
982 * savedconfig, retrieved with:
983 * ntpq -c "rv 0 savedconfig"
985 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
986 savedconfig_eq, filename);
987 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
992 #else /* !SAVECONFIG follows */
993 snprintf(reply, sizeof(reply),
994 "saveconfig unavailable, configured with --disable-saveconfig");
997 ctl_putdata(reply, strlen(reply), 0);
1003 * process_control - process an incoming control message
1007 struct recvbuf *rbufp,
1011 struct ntp_control *pkt;
1014 const struct ctl_proc *cc;
1019 DPRINTF(3, ("in process_control()\n"));
1022 * Save the addresses for error responses
1025 rmt_addr = &rbufp->recv_srcadr;
1026 lcl_inter = rbufp->dstadr;
1027 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1030 * If the length is less than required for the header, or
1031 * it is a response or a fragment, ignore this.
1033 if (rbufp->recv_length < (int)CTL_HEADER_LEN
1034 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1035 || pkt->offset != 0) {
1036 DPRINTF(1, ("invalid format in control packet\n"));
1037 if (rbufp->recv_length < (int)CTL_HEADER_LEN)
1039 if (CTL_RESPONSE & pkt->r_m_e_op)
1041 if (CTL_MORE & pkt->r_m_e_op)
1043 if (CTL_ERROR & pkt->r_m_e_op)
1045 if (pkt->offset != 0)
1049 res_version = PKT_VERSION(pkt->li_vn_mode);
1050 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1051 DPRINTF(1, ("unknown version %d in control packet\n",
1058 * Pull enough data from the packet to make intelligent
1061 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1063 res_opcode = pkt->r_m_e_op;
1064 rpkt.sequence = pkt->sequence;
1065 rpkt.associd = pkt->associd;
1069 res_associd = htons(pkt->associd);
1071 res_authenticate = FALSE;
1073 res_authokay = FALSE;
1074 req_count = (int)ntohs(pkt->count);
1075 datanotbinflag = FALSE;
1078 datapt = rpkt.u.data;
1079 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1081 if ((rbufp->recv_length & 0x3) != 0)
1082 DPRINTF(3, ("Control packet length %d unrounded\n",
1083 rbufp->recv_length));
1086 * We're set up now. Make sure we've got at least enough
1087 * incoming data space to match the count.
1089 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1090 if (req_data < req_count || rbufp->recv_length & 0x3) {
1091 ctl_error(CERR_BADFMT);
1092 numctldatatooshort++;
1096 properlen = req_count + CTL_HEADER_LEN;
1097 /* round up proper len to a 8 octet boundary */
1099 properlen = (properlen + 7) & ~7;
1100 maclen = rbufp->recv_length - properlen;
1101 if ((rbufp->recv_length & 3) == 0 &&
1102 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1104 res_authenticate = TRUE;
1105 pkid = (void *)((char *)pkt + properlen);
1106 res_keyid = ntohl(*pkid);
1107 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1108 rbufp->recv_length, properlen, res_keyid,
1111 if (!authistrusted(res_keyid))
1112 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1113 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1114 rbufp->recv_length - maclen,
1116 res_authokay = TRUE;
1117 DPRINTF(3, ("authenticated okay\n"));
1120 DPRINTF(3, ("authentication failed\n"));
1125 * Set up translate pointers
1127 reqpt = (char *)pkt->u.data;
1128 reqend = reqpt + req_count;
1131 * Look for the opcode processor
1133 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1134 if (cc->control_code == res_opcode) {
1135 DPRINTF(3, ("opcode %d, found command handler\n",
1137 if (cc->flags == AUTH
1139 || res_keyid != ctl_auth_keyid)) {
1140 ctl_error(CERR_PERMISSION);
1143 (cc->handler)(rbufp, restrict_mask);
1149 * Can't find this one, return an error.
1152 ctl_error(CERR_BADOP);
1158 * ctlpeerstatus - return a status word for this peer
1162 register struct peer *p
1168 if (FLAG_CONFIG & p->flags)
1169 status |= CTL_PST_CONFIG;
1171 status |= CTL_PST_AUTHENABLE;
1172 if (FLAG_AUTHENTIC & p->flags)
1173 status |= CTL_PST_AUTHENTIC;
1175 status |= CTL_PST_REACH;
1176 if (MDF_TXONLY_MASK & p->cast_flags)
1177 status |= CTL_PST_BCAST;
1179 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1184 * ctlclkstatus - return a status word for this clock
1189 struct refclockstat *pcs
1192 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1198 * ctlsysstatus - return the system status word
1203 register u_char this_clock;
1205 this_clock = CTL_SST_TS_UNSPEC;
1207 if (sys_peer != NULL) {
1208 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1209 this_clock = sys_peer->sstclktype;
1210 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1211 this_clock = clocktypes[sys_peer->refclktype];
1213 #else /* REFCLOCK */
1215 this_clock = CTL_SST_TS_NTP;
1216 #endif /* REFCLOCK */
1217 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1218 ctl_sys_last_event);
1223 * ctl_flushpkt - write out the current packet and prepare
1224 * another if necessary.
1238 dlen = datapt - rpkt.u.data;
1239 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1241 * Big hack, output a trailing \r\n
1247 sendlen = dlen + CTL_HEADER_LEN;
1250 * Pad to a multiple of 32 bits
1252 while (sendlen & 0x3) {
1258 * Fill in the packet with the current info
1260 rpkt.r_m_e_op = CTL_RESPONSE | more |
1261 (res_opcode & CTL_OP_MASK);
1262 rpkt.count = htons((u_short)dlen);
1263 rpkt.offset = htons((u_short)res_offset);
1265 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1266 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1270 ctl_traps[i].tr_version,
1273 htons(ctl_traps[i].tr_sequence);
1274 sendpkt(&ctl_traps[i].tr_addr,
1275 ctl_traps[i].tr_localaddr, -4,
1276 (struct pkt *)&rpkt, sendlen);
1278 ctl_traps[i].tr_sequence++;
1283 if (res_authenticate && sys_authenticate) {
1286 * If we are going to authenticate, then there
1287 * is an additional requirement that the MAC
1288 * begin on a 64 bit boundary.
1290 while (totlen & 7) {
1294 keyid = htonl(res_keyid);
1295 memcpy(datapt, &keyid, sizeof(keyid));
1296 maclen = authencrypt(res_keyid,
1297 (u_int32 *)&rpkt, totlen);
1298 sendpkt(rmt_addr, lcl_inter, -5,
1299 (struct pkt *)&rpkt, totlen + maclen);
1301 sendpkt(rmt_addr, lcl_inter, -6,
1302 (struct pkt *)&rpkt, sendlen);
1311 * Set us up for another go around.
1315 datapt = rpkt.u.data;
1320 * ctl_putdata - write data into the packet, fragmenting and starting
1321 * another if this one is full.
1327 int bin /* set to 1 when data is binary */
1331 unsigned int currentlen;
1335 datanotbinflag = TRUE;
1340 if ((dlen + datalinelen + 1) >= MAXDATALINELEN) {
1352 * Save room for trailing junk
1354 while (dlen + overhead + datapt > dataend) {
1356 * Not enough room in this one, flush it out.
1358 currentlen = MIN(dlen, (unsigned int)(dataend - datapt));
1360 memcpy(datapt, dp, currentlen);
1362 datapt += currentlen;
1365 datalinelen += currentlen;
1367 ctl_flushpkt(CTL_MORE);
1370 memcpy(datapt, dp, dlen);
1372 datalinelen += dlen;
1378 * ctl_putstr - write a tagged string into the response packet
1383 * len is the data length excluding the NUL terminator,
1384 * as in ctl_putstr("var", "value", strlen("value"));
1398 memcpy(buffer, tag, tl);
1401 NTP_INSIST(tl + 3 + len <= sizeof(buffer));
1404 memcpy(cp, data, len);
1408 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1413 * ctl_putunqstr - write a tagged string into the response packet
1418 * len is the data length excluding the NUL terminator.
1419 * data must not contain a comma or whitespace.
1433 memcpy(buffer, tag, tl);
1436 NTP_INSIST(tl + 1 + len <= sizeof(buffer));
1438 memcpy(cp, data, len);
1441 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1446 * ctl_putdblf - write a tagged, signed double into the response packet
1465 NTP_INSIST((size_t)(cp - buffer) < sizeof(buffer));
1466 snprintf(cp, sizeof(buffer) - (cp - buffer), use_f ? "%.*f" : "%.*g",
1469 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1473 * ctl_putuint - write a tagged unsigned integer into the response
1482 register const char *cq;
1491 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1492 snprintf(cp, sizeof(buffer) - (cp - buffer), "%lu", uval);
1494 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1498 * ctl_putcal - write a decoded calendar data into the response
1503 const struct calendar *pcal
1509 numch = snprintf(buffer, sizeof(buffer),
1510 "%s=%04d%02d%02d%02d%02d",
1518 NTP_INSIST(numch < sizeof(buffer));
1519 ctl_putdata(buffer, numch, 0);
1525 * ctl_putfs - write a decoded filestamp into the response
1534 register const char *cq;
1536 struct tm *tm = NULL;
1545 fstamp = uval - JAN_1970;
1546 tm = gmtime(&fstamp);
1549 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1550 snprintf(cp, sizeof(buffer) - (cp - buffer),
1551 "%04d%02d%02d%02d%02d", tm->tm_year + 1900,
1552 tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);
1554 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1559 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1569 register const char *cq;
1578 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1579 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%lx", uval);
1581 ctl_putdata(buffer,(unsigned)( cp - buffer ), 0);
1586 * ctl_putint - write a tagged signed integer into the response
1595 register const char *cq;
1604 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1605 snprintf(cp, sizeof(buffer) - (cp - buffer), "%ld", ival);
1607 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1612 * ctl_putts - write a tagged timestamp, in hex, into the response
1621 register const char *cq;
1630 NTP_INSIST((size_t)(cp - buffer) < sizeof(buffer));
1631 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%08x.%08x",
1632 (u_int)ts->l_ui, (u_int)ts->l_uf);
1634 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1639 * ctl_putadr - write an IP address into the response
1649 register const char *cq;
1659 cq = numtoa(addr32);
1662 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1663 snprintf(cp, sizeof(buffer) - (cp - buffer), "%s", cq);
1665 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1670 * ctl_putrefid - send a u_int32 refid as printable text
1686 oplim = output + sizeof(output);
1687 while (optr < oplim && '\0' != *tag)
1693 if (!(optr < oplim))
1695 iptr = (char *)&refid;
1696 iplim = iptr + sizeof(refid);
1697 for ( ; optr < oplim && iptr < iplim && '\0' != *iptr;
1699 if (isprint((int)*iptr))
1703 if (!(optr <= oplim))
1705 ctl_putdata(output, (u_int)(optr - output), FALSE);
1710 * ctl_putarray - write a tagged eight element double array into the response
1720 register const char *cq;
1733 NTP_INSIST((cp - buffer) < (int)sizeof(buffer));
1734 snprintf(cp, sizeof(buffer) - (cp - buffer),
1735 " %.2f", arr[i] * 1e3);
1737 } while (i != start);
1738 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1743 * ctl_putsys - output a system variable
1757 struct cert_info *cp;
1758 #endif /* AUTOKEY */
1760 static struct timex ntx;
1761 static u_long ntp_adjtime_time;
1763 static const double to_ms =
1765 1.0e-6; /* nsec to msec */
1767 1.0e-3; /* usec to msec */
1771 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1773 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1774 current_time != ntp_adjtime_time) {
1776 if (ntp_adjtime(&ntx) < 0)
1777 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1779 ntp_adjtime_time = current_time;
1781 #endif /* KERNEL_PLL */
1786 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1790 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1794 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1798 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1802 case CS_ROOTDISPERSION:
1803 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1804 sys_rootdisp * 1e3);
1808 if (sys_stratum > 1 && sys_stratum < STRATUM_UNSPEC)
1809 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1811 ctl_putrefid(sys_var[varid].text, sys_refid);
1815 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1819 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
1823 if (sys_peer == NULL)
1824 ctl_putuint(sys_var[CS_PEERID].text, 0);
1826 ctl_putuint(sys_var[CS_PEERID].text,
1831 if (sys_peer != NULL && sys_peer->dstadr != NULL)
1832 ss = sptoa(&sys_peer->srcadr);
1835 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
1839 u = (sys_peer != NULL)
1842 ctl_putuint(sys_var[CS_PEERMODE].text, u);
1846 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
1850 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
1854 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
1858 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
1863 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
1868 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
1869 sizeof(str_processor) - 1);
1871 ctl_putstr(sys_var[CS_PROCESSOR].text,
1872 utsnamebuf.machine, strlen(utsnamebuf.machine));
1873 #endif /* HAVE_UNAME */
1878 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
1879 sizeof(str_system) - 1);
1881 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
1882 utsnamebuf.release);
1883 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
1884 #endif /* HAVE_UNAME */
1888 ctl_putstr(sys_var[CS_VERSION].text, Version,
1893 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
1899 char buf[CTL_MAX_DATA_LEN];
1900 //buffPointer, firstElementPointer, buffEndPointer
1901 char *buffp, *buffend;
1905 const struct ctl_var *k;
1908 buffend = buf + sizeof(buf);
1909 if (buffp + strlen(sys_var[CS_VARLIST].text) + 4 > buffend)
1910 break; /* really long var name */
1912 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
1913 buffp += strlen(buffp);
1914 firstVarName = TRUE;
1915 for (k = sys_var; !(k->flags & EOV); k++) {
1916 if (k->flags & PADDING)
1918 len = strlen(k->text);
1919 if (buffp + len + 1 >= buffend)
1924 firstVarName = FALSE;
1925 memcpy(buffp, k->text, len);
1929 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
1930 if (k->flags & PADDING)
1932 if (NULL == k->text)
1934 ss1 = strchr(k->text, '=');
1936 len = strlen(k->text);
1938 len = ss1 - k->text;
1939 if (buffp + len + 1 >= buffend)
1943 firstVarName = FALSE;
1945 memcpy(buffp, k->text,(unsigned)len);
1948 if (buffp + 2 >= buffend)
1954 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
1960 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
1965 leap_signature_t lsig;
1966 leapsec_getsig(&lsig);
1968 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
1974 leap_signature_t lsig;
1975 leapsec_getsig(&lsig);
1977 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
1982 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
1985 case CS_MRU_ENABLED:
1986 ctl_puthex(sys_var[varid].text, mon_enabled);
1990 ctl_putuint(sys_var[varid].text, mru_entries);
1994 kb = mru_entries * (sizeof(mon_entry) / 1024.);
1998 ctl_putuint(sys_var[varid].text, u);
2001 case CS_MRU_DEEPEST:
2002 ctl_putuint(sys_var[varid].text, mru_peakentries);
2005 case CS_MRU_MINDEPTH:
2006 ctl_putuint(sys_var[varid].text, mru_mindepth);
2010 ctl_putint(sys_var[varid].text, mru_maxage);
2013 case CS_MRU_MAXDEPTH:
2014 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2018 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2022 ctl_putuint(sys_var[varid].text, u);
2026 ctl_putuint(sys_var[varid].text, current_time);
2030 ctl_putuint(sys_var[varid].text,
2031 current_time - sys_stattime);
2034 case CS_SS_RECEIVED:
2035 ctl_putuint(sys_var[varid].text, sys_received);
2039 ctl_putuint(sys_var[varid].text, sys_newversion);
2043 ctl_putuint(sys_var[varid].text, sys_oldversion);
2046 case CS_SS_BADFORMAT:
2047 ctl_putuint(sys_var[varid].text, sys_badlength);
2051 ctl_putuint(sys_var[varid].text, sys_badauth);
2054 case CS_SS_DECLINED:
2055 ctl_putuint(sys_var[varid].text, sys_declined);
2058 case CS_SS_RESTRICTED:
2059 ctl_putuint(sys_var[varid].text, sys_restricted);
2063 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2067 ctl_putuint(sys_var[varid].text, sys_kodsent);
2070 case CS_SS_PROCESSED:
2071 ctl_putuint(sys_var[varid].text, sys_processed);
2075 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2079 LFPTOD(&sys_authdelay, dtemp);
2080 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2084 ctl_putuint(sys_var[varid].text, authnumkeys);
2088 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2091 case CS_AUTHKLOOKUPS:
2092 ctl_putuint(sys_var[varid].text, authkeylookups);
2095 case CS_AUTHKNOTFOUND:
2096 ctl_putuint(sys_var[varid].text, authkeynotfound);
2099 case CS_AUTHKUNCACHED:
2100 ctl_putuint(sys_var[varid].text, authkeyuncached);
2103 case CS_AUTHKEXPIRED:
2104 ctl_putuint(sys_var[varid].text, authkeyexpired);
2107 case CS_AUTHENCRYPTS:
2108 ctl_putuint(sys_var[varid].text, authencryptions);
2111 case CS_AUTHDECRYPTS:
2112 ctl_putuint(sys_var[varid].text, authdecryptions);
2116 ctl_putuint(sys_var[varid].text,
2117 current_time - auth_timereset);
2121 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2122 * unavailable, otherwise calls putfunc with args.
2125 # define CTL_IF_KERNLOOP(putfunc, args) \
2126 ctl_putint(sys_var[varid].text, 0)
2128 # define CTL_IF_KERNLOOP(putfunc, args) \
2133 * CTL_IF_KERNPPS() puts a zero if either the kernel
2134 * loop is unavailable, or kernel hard PPS is not
2135 * active, otherwise calls putfunc with args.
2138 # define CTL_IF_KERNPPS(putfunc, args) \
2139 ctl_putint(sys_var[varid].text, 0)
2141 # define CTL_IF_KERNPPS(putfunc, args) \
2142 if (0 == ntx.shift) \
2143 ctl_putint(sys_var[varid].text, 0); \
2145 putfunc args /* no trailing ; */
2151 (sys_var[varid].text, 0, -1, to_ms * ntx.offset)
2158 (sys_var[varid].text, ntx.freq)
2165 (sys_var[varid].text, 0, 6,
2166 to_ms * ntx.maxerror)
2173 (sys_var[varid].text, 0, 6,
2174 to_ms * ntx.esterror)
2182 ss = k_st_flags(ntx.status);
2184 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2187 case CS_K_TIMECONST:
2190 (sys_var[varid].text, ntx.constant)
2194 case CS_K_PRECISION:
2197 (sys_var[varid].text, 0, 6,
2198 to_ms * ntx.precision)
2205 (sys_var[varid].text, ntx.tolerance)
2212 (sys_var[varid].text, ntx.ppsfreq)
2216 case CS_K_PPS_STABIL:
2219 (sys_var[varid].text, ntx.stabil)
2223 case CS_K_PPS_JITTER:
2226 (sys_var[varid].text, to_ms * ntx.jitter)
2230 case CS_K_PPS_CALIBDUR:
2233 (sys_var[varid].text, 1 << ntx.shift)
2237 case CS_K_PPS_CALIBS:
2240 (sys_var[varid].text, ntx.calcnt)
2244 case CS_K_PPS_CALIBERRS:
2247 (sys_var[varid].text, ntx.errcnt)
2251 case CS_K_PPS_JITEXC:
2254 (sys_var[varid].text, ntx.jitcnt)
2258 case CS_K_PPS_STBEXC:
2261 (sys_var[varid].text, ntx.stbcnt)
2265 case CS_IOSTATS_RESET:
2266 ctl_putuint(sys_var[varid].text,
2267 current_time - io_timereset);
2271 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2275 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2279 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2282 case CS_RBUF_LOWATER:
2283 ctl_putuint(sys_var[varid].text, lowater_additions());
2287 ctl_putuint(sys_var[varid].text, packets_dropped);
2291 ctl_putuint(sys_var[varid].text, packets_ignored);
2294 case CS_IO_RECEIVED:
2295 ctl_putuint(sys_var[varid].text, packets_received);
2299 ctl_putuint(sys_var[varid].text, packets_sent);
2302 case CS_IO_SENDFAILED:
2303 ctl_putuint(sys_var[varid].text, packets_notsent);
2307 ctl_putuint(sys_var[varid].text, handler_calls);
2310 case CS_IO_GOODWAKEUPS:
2311 ctl_putuint(sys_var[varid].text, handler_pkts);
2314 case CS_TIMERSTATS_RESET:
2315 ctl_putuint(sys_var[varid].text,
2316 current_time - timer_timereset);
2319 case CS_TIMER_OVERRUNS:
2320 ctl_putuint(sys_var[varid].text, alarm_overflow);
2324 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2328 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2333 ctl_puthex(sys_var[CS_FLAGS].text,
2339 strlcpy(str, OBJ_nid2ln(crypto_nid),
2341 ctl_putstr(sys_var[CS_DIGEST].text, str,
2350 dp = EVP_get_digestbynid(crypto_flags >> 16);
2351 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2353 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2359 if (hostval.ptr != NULL)
2360 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2361 strlen(hostval.ptr));
2365 if (sys_ident != NULL)
2366 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2371 for (cp = cinfo; cp != NULL; cp = cp->link) {
2372 snprintf(str, sizeof(str), "%s %s 0x%x",
2373 cp->subject, cp->issuer, cp->flags);
2374 ctl_putstr(sys_var[CS_CERTIF].text, str,
2376 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2381 if (hostval.tstamp != 0)
2382 ctl_putfs(sys_var[CS_PUBLIC].text,
2383 ntohl(hostval.tstamp));
2385 #endif /* AUTOKEY */
2391 * ctl_putpeer - output a peer variable
2399 char buf[CTL_MAX_DATA_LEN];
2404 const struct ctl_var *k;
2409 #endif /* AUTOKEY */
2414 ctl_putuint(peer_var[id].text,
2415 !(FLAG_PREEMPT & p->flags));
2419 ctl_putuint(peer_var[id].text, !(p->keyid));
2423 ctl_putuint(peer_var[id].text,
2424 !!(FLAG_AUTHENTIC & p->flags));
2428 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2432 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2436 if (p->hostname != NULL)
2437 ctl_putstr(peer_var[id].text, p->hostname,
2438 strlen(p->hostname));
2442 ctl_putadr(peer_var[id].text, 0,
2449 ctl_putuint(peer_var[id].text,
2451 ? SRCPORT(&p->dstadr->sin)
2457 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2462 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2466 ctl_putuint(peer_var[id].text, p->throttle);
2470 ctl_putuint(peer_var[id].text, p->leap);
2474 ctl_putuint(peer_var[id].text, p->hmode);
2478 ctl_putuint(peer_var[id].text, p->stratum);
2482 ctl_putuint(peer_var[id].text, p->ppoll);
2486 ctl_putuint(peer_var[id].text, p->hpoll);
2490 ctl_putint(peer_var[id].text, p->precision);
2494 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2497 case CP_ROOTDISPERSION:
2498 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2503 if (p->flags & FLAG_REFCLOCK) {
2504 ctl_putrefid(peer_var[id].text, p->refid);
2508 if (p->stratum > 1 && p->stratum < STRATUM_UNSPEC)
2509 ctl_putadr(peer_var[id].text, p->refid,
2512 ctl_putrefid(peer_var[id].text, p->refid);
2516 ctl_putts(peer_var[id].text, &p->reftime);
2520 ctl_putts(peer_var[id].text, &p->aorg);
2524 ctl_putts(peer_var[id].text, &p->dst);
2529 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2534 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2538 ctl_puthex(peer_var[id].text, p->reach);
2542 ctl_puthex(peer_var[id].text, p->flash);
2547 if (p->flags & FLAG_REFCLOCK) {
2548 ctl_putuint(peer_var[id].text, p->ttl);
2552 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2553 ctl_putint(peer_var[id].text,
2558 ctl_putuint(peer_var[id].text, p->unreach);
2562 ctl_putuint(peer_var[id].text,
2563 p->nextdate - current_time);
2567 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2571 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2575 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2579 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2583 if (p->keyid > NTP_MAXKEY)
2584 ctl_puthex(peer_var[id].text, p->keyid);
2586 ctl_putuint(peer_var[id].text, p->keyid);
2590 ctl_putarray(peer_var[id].text, p->filter_delay,
2595 ctl_putarray(peer_var[id].text, p->filter_offset,
2600 ctl_putarray(peer_var[id].text, p->filter_disp,
2605 ctl_putuint(peer_var[id].text, p->pmode);
2609 ctl_putuint(peer_var[id].text, p->received);
2613 ctl_putuint(peer_var[id].text, p->sent);
2618 be = buf + sizeof(buf);
2619 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2620 break; /* really long var name */
2622 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2625 for (k = peer_var; !(EOV & k->flags); k++) {
2626 if (PADDING & k->flags)
2628 i = strlen(k->text);
2629 if (s + i + 1 >= be)
2633 memcpy(s, k->text, i);
2639 ctl_putdata(buf, (u_int)(s - buf), 0);
2644 ctl_putuint(peer_var[id].text,
2645 current_time - p->timereceived);
2649 ctl_putuint(peer_var[id].text,
2650 current_time - p->timereachable);
2654 ctl_putuint(peer_var[id].text, p->badauth);
2658 ctl_putuint(peer_var[id].text, p->bogusorg);
2662 ctl_putuint(peer_var[id].text, p->oldpkt);
2666 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2670 ctl_putuint(peer_var[id].text, p->selbroken);
2674 ctl_putuint(peer_var[id].text, p->status);
2679 ctl_puthex(peer_var[id].text, p->crypto);
2684 dp = EVP_get_digestbynid(p->crypto >> 16);
2685 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2686 ctl_putstr(peer_var[id].text, str, strlen(str));
2691 if (p->subject != NULL)
2692 ctl_putstr(peer_var[id].text, p->subject,
2693 strlen(p->subject));
2696 case CP_VALID: /* not used */
2700 if (NULL == (ap = p->recval.ptr))
2703 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2704 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2705 ctl_putfs(peer_var[CP_INITTSP].text,
2706 ntohl(p->recval.tstamp));
2710 if (p->ident != NULL)
2711 ctl_putstr(peer_var[id].text, p->ident,
2716 #endif /* AUTOKEY */
2723 * ctl_putclock - output clock variables
2728 struct refclockstat *pcs,
2732 char buf[CTL_MAX_DATA_LEN];
2736 const struct ctl_var *k;
2741 if (mustput || pcs->clockdesc == NULL
2742 || *(pcs->clockdesc) == '\0') {
2743 ctl_putuint(clock_var[id].text, pcs->type);
2747 ctl_putstr(clock_var[id].text,
2749 (unsigned)pcs->lencode);
2753 ctl_putuint(clock_var[id].text, pcs->polls);
2757 ctl_putuint(clock_var[id].text,
2762 ctl_putuint(clock_var[id].text,
2767 ctl_putuint(clock_var[id].text,
2772 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2773 ctl_putdbl(clock_var[id].text,
2774 pcs->fudgetime1 * 1e3);
2778 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2779 ctl_putdbl(clock_var[id].text,
2780 pcs->fudgetime2 * 1e3);
2784 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2785 ctl_putint(clock_var[id].text,
2790 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2791 if (pcs->fudgeval1 > 1)
2792 ctl_putadr(clock_var[id].text,
2793 pcs->fudgeval2, NULL);
2795 ctl_putrefid(clock_var[id].text,
2801 ctl_putuint(clock_var[id].text, pcs->flags);
2805 if (pcs->clockdesc == NULL ||
2806 *(pcs->clockdesc) == '\0') {
2808 ctl_putstr(clock_var[id].text,
2811 ctl_putstr(clock_var[id].text,
2813 strlen(pcs->clockdesc));
2819 be = buf + sizeof(buf);
2820 if (strlen(clock_var[CC_VARLIST].text) + 4 >
2822 break; /* really long var name */
2824 snprintf(s, sizeof(buf), "%s=\"",
2825 clock_var[CC_VARLIST].text);
2829 for (k = clock_var; !(EOV & k->flags); k++) {
2830 if (PADDING & k->flags)
2833 i = strlen(k->text);
2834 if (s + i + 1 >= be)
2839 memcpy(s, k->text, i);
2843 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
2844 if (PADDING & k->flags)
2851 while (*ss && *ss != '=')
2854 if (s + i + 1 >= be)
2859 memcpy(s, k->text, (unsigned)i);
2868 ctl_putdata(buf, (unsigned)(s - buf), 0);
2877 * ctl_getitem - get the next data item from the incoming packet
2879 static const struct ctl_var *
2881 const struct ctl_var *var_list,
2885 static const struct ctl_var eol = { 0, EOV, NULL };
2886 static char buf[128];
2887 static u_long quiet_until;
2888 const struct ctl_var *v;
2894 * Delete leading commas and white space
2896 while (reqpt < reqend && (*reqpt == ',' ||
2897 isspace((unsigned char)*reqpt)))
2899 if (reqpt >= reqend)
2902 if (NULL == var_list)
2906 * Look for a first character match on the tag. If we find
2907 * one, see if it is a full match.
2911 for (v = var_list; !(EOV & v->flags); v++) {
2912 if (!(PADDING & v->flags) && *cp == *(v->text)) {
2914 while ('\0' != *pch && '=' != *pch && cp < reqend
2919 if ('\0' == *pch || '=' == *pch) {
2920 while (cp < reqend && isspace((u_char)*cp))
2922 if (cp == reqend || ',' == *cp) {
2933 while (cp < reqend && isspace((u_char)*cp))
2935 while (cp < reqend && *cp != ',') {
2937 if ((size_t)(tp - buf) >= sizeof(buf)) {
2938 ctl_error(CERR_BADFMT);
2941 if (quiet_until <= current_time) {
2942 quiet_until = current_time + 300;
2943 msyslog(LOG_WARNING,
2944 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)", stoa(rmt_addr), SRCPORT(rmt_addr));
2952 while (tp >= buf && isspace((u_char)*tp))
2967 * control_unspec - response to an unspecified op-code
2972 struct recvbuf *rbufp,
2979 * What is an appropriate response to an unspecified op-code?
2980 * I return no errors and no data, unless a specified assocation
2984 peer = findpeerbyassoc(res_associd);
2986 ctl_error(CERR_BADASSOC);
2989 rpkt.status = htons(ctlpeerstatus(peer));
2991 rpkt.status = htons(ctlsysstatus());
2997 * read_status - return either a list of associd's, or a particular
3003 struct recvbuf *rbufp,
3010 /* a_st holds association ID, status pairs alternating */
3011 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3015 printf("read_status: ID %d\n", res_associd);
3018 * Two choices here. If the specified association ID is
3019 * zero we return all known assocation ID's. Otherwise
3020 * we return a bunch of stuff about the particular peer.
3023 peer = findpeerbyassoc(res_associd);
3025 ctl_error(CERR_BADASSOC);
3028 rpkt.status = htons(ctlpeerstatus(peer));
3030 peer->num_events = 0;
3032 * For now, output everything we know about the
3033 * peer. May be more selective later.
3035 for (cp = def_peer_var; *cp != 0; cp++)
3036 ctl_putpeer((int)*cp, peer);
3041 rpkt.status = htons(ctlsysstatus());
3042 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3043 a_st[n++] = htons(peer->associd);
3044 a_st[n++] = htons(ctlpeerstatus(peer));
3045 /* two entries each loop iteration, so n + 1 */
3046 if (n + 1 >= COUNTOF(a_st)) {
3047 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3053 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3059 * read_peervars - half of read_variables() implementation
3064 const struct ctl_var *v;
3069 u_char wants[CP_MAXCODE + 1];
3073 * Wants info for a particular peer. See if we know
3076 peer = findpeerbyassoc(res_associd);
3078 ctl_error(CERR_BADASSOC);
3081 rpkt.status = htons(ctlpeerstatus(peer));
3083 peer->num_events = 0;
3086 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3087 if (v->flags & EOV) {
3088 ctl_error(CERR_UNKNOWNVAR);
3091 NTP_INSIST(v->code < COUNTOF(wants));
3096 for (i = 1; i < COUNTOF(wants); i++)
3098 ctl_putpeer(i, peer);
3100 for (cp = def_peer_var; *cp != 0; cp++)
3101 ctl_putpeer((int)*cp, peer);
3107 * read_sysvars - half of read_variables() implementation
3112 const struct ctl_var *v;
3123 * Wants system variables. Figure out which he wants
3124 * and give them to him.
3126 rpkt.status = htons(ctlsysstatus());
3128 ctl_sys_num_events = 0;
3129 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3130 wants = emalloc_zero(wants_count);
3132 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3133 if (!(EOV & v->flags)) {
3134 NTP_INSIST(v->code < wants_count);
3138 v = ctl_getitem(ext_sys_var, &valuep);
3139 NTP_INSIST(v != NULL);
3140 if (EOV & v->flags) {
3141 ctl_error(CERR_UNKNOWNVAR);
3145 n = v->code + CS_MAXCODE + 1;
3146 NTP_INSIST(n < wants_count);
3152 for (n = 1; n <= CS_MAXCODE; n++)
3155 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3156 if (wants[n + CS_MAXCODE + 1]) {
3157 pch = ext_sys_var[n].text;
3158 ctl_putdata(pch, strlen(pch), 0);
3161 for (cs = def_sys_var; *cs != 0; cs++)
3162 ctl_putsys((int)*cs);
3163 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3164 if (DEF & kv->flags)
3165 ctl_putdata(kv->text, strlen(kv->text),
3174 * read_variables - return the variables the caller asks for
3179 struct recvbuf *rbufp,
3191 * write_variables - write into variables. We only allow leap bit
3197 struct recvbuf *rbufp,
3201 const struct ctl_var *v;
3212 * If he's trying to write into a peer tell him no way
3214 if (res_associd != 0) {
3215 ctl_error(CERR_PERMISSION);
3222 rpkt.status = htons(ctlsysstatus());
3225 * Look through the variables. Dump out at the first sign of
3228 while ((v = ctl_getitem(sys_var, &valuep)) != 0) {
3230 if (v->flags & EOV) {
3231 if ((v = ctl_getitem(ext_sys_var, &valuep)) !=
3233 if (v->flags & EOV) {
3234 ctl_error(CERR_UNKNOWNVAR);
3242 if (!(v->flags & CAN_WRITE)) {
3243 ctl_error(CERR_PERMISSION);
3246 if (!ext_var && (*valuep == '\0' || !atoint(valuep,
3248 ctl_error(CERR_BADFMT);
3251 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) {
3252 ctl_error(CERR_BADVALUE);
3257 octets = strlen(v->text) + strlen(valuep) + 2;
3258 vareqv = emalloc(octets);
3261 while (*t && *t != '=')
3264 memcpy(tt, valuep, 1 + strlen(valuep));
3265 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3268 ctl_error(CERR_UNSPEC); /* really */
3274 * If we got anything, do it. xxx nothing to do ***
3277 if (leapind != ~0 || leapwarn != ~0) {
3278 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3279 ctl_error(CERR_PERMISSION);
3288 * configure() processes ntpq :config/config-from-file, allowing
3289 * generic runtime reconfiguration.
3291 static void configure(
3292 struct recvbuf *rbufp,
3300 /* I haven't yet implemented changes to an existing association.
3301 * Hence check if the association id is 0
3303 if (res_associd != 0) {
3304 ctl_error(CERR_BADVALUE);
3308 if (RES_NOMODIFY & restrict_mask) {
3309 snprintf(remote_config.err_msg,
3310 sizeof(remote_config.err_msg),
3311 "runtime configuration prohibited by restrict ... nomodify");
3312 ctl_putdata(remote_config.err_msg,
3313 strlen(remote_config.err_msg), 0);
3317 "runtime config from %s rejected due to nomodify restriction",
3318 stoa(&rbufp->recv_srcadr));
3323 /* Initialize the remote config buffer */
3324 data_count = reqend - reqpt;
3326 if (data_count > sizeof(remote_config.buffer) - 2) {
3327 snprintf(remote_config.err_msg,
3328 sizeof(remote_config.err_msg),
3329 "runtime configuration failed: request too long");
3330 ctl_putdata(remote_config.err_msg,
3331 strlen(remote_config.err_msg), 0);
3334 "runtime config from %s rejected: request too long",
3335 stoa(&rbufp->recv_srcadr));
3339 memcpy(remote_config.buffer, reqpt, data_count);
3341 && '\n' != remote_config.buffer[data_count - 1])
3342 remote_config.buffer[data_count++] = '\n';
3343 remote_config.buffer[data_count] = '\0';
3344 remote_config.pos = 0;
3345 remote_config.err_pos = 0;
3346 remote_config.no_errors = 0;
3348 /* do not include terminating newline in log */
3350 && '\n' == remote_config.buffer[data_count - 1]) {
3351 remote_config.buffer[data_count - 1] = '\0';
3357 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3358 remote_config.buffer));
3359 msyslog(LOG_NOTICE, "%s config: %s",
3360 stoa(&rbufp->recv_srcadr),
3361 remote_config.buffer);
3364 remote_config.buffer[data_count - 1] = '\n';
3366 config_remotely(&rbufp->recv_srcadr);
3369 * Check if errors were reported. If not, output 'Config
3370 * Succeeded'. Else output the error count. It would be nice
3371 * to output any parser error messages.
3373 if (0 == remote_config.no_errors) {
3374 retval = snprintf(remote_config.err_msg,
3375 sizeof(remote_config.err_msg),
3376 "Config Succeeded");
3378 remote_config.err_pos += retval;
3381 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3384 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3386 if (remote_config.no_errors > 0)
3387 msyslog(LOG_NOTICE, "%d error in %s config",
3388 remote_config.no_errors,
3389 stoa(&rbufp->recv_srcadr));
3394 * derive_nonce - generate client-address-specific nonce value
3395 * associated with a given timestamp.
3397 static u_int32 derive_nonce(
3403 static u_int32 salt[4];
3404 static u_long last_salt_update;
3406 u_char digest[EVP_MAX_MD_SIZE];
3412 while (!salt[0] || current_time - last_salt_update >= 3600) {
3413 salt[0] = ntp_random();
3414 salt[1] = ntp_random();
3415 salt[2] = ntp_random();
3416 salt[3] = ntp_random();
3417 last_salt_update = current_time;
3420 EVP_DigestInit(&ctx, EVP_get_digestbynid(NID_md5));
3421 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3422 EVP_DigestUpdate(&ctx, &ts_i, sizeof(ts_i));
3423 EVP_DigestUpdate(&ctx, &ts_f, sizeof(ts_f));
3425 EVP_DigestUpdate(&ctx, &SOCK_ADDR4(addr),
3426 sizeof(SOCK_ADDR4(addr)));
3428 EVP_DigestUpdate(&ctx, &SOCK_ADDR6(addr),
3429 sizeof(SOCK_ADDR6(addr)));
3430 EVP_DigestUpdate(&ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3431 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3432 EVP_DigestFinal(&ctx, d.digest, &len);
3439 * generate_nonce - generate client-address-specific nonce string.
3441 static void generate_nonce(
3442 struct recvbuf * rbufp,
3449 derived = derive_nonce(&rbufp->recv_srcadr,
3450 rbufp->recv_time.l_ui,
3451 rbufp->recv_time.l_uf);
3452 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3453 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3458 * validate_nonce - validate client-address-specific nonce string.
3460 * Returns TRUE if the local calculation of the nonce matches the
3461 * client-provided value and the timestamp is recent enough.
3463 static int validate_nonce(
3464 const char * pnonce,
3465 struct recvbuf * rbufp
3475 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3478 ts.l_ui = (u_int32)ts_i;
3479 ts.l_uf = (u_int32)ts_f;
3480 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3481 get_systime(&now_delta);
3482 L_SUB(&now_delta, &ts);
3484 return (supposed == derived && now_delta.l_ui < 16);
3489 * send_random_tag_value - send a randomly-generated three character
3490 * tag prefix, a '.', an index, a '=' and a
3491 * random integer value.
3493 * To try to force clients to ignore unrecognized tags in mrulist,
3494 * reslist, and ifstats responses, the first and last rows are spiced
3495 * with randomly-generated tag names with correct .# index. Make it
3496 * three characters knowing that none of the currently-used subscripted
3497 * tags have that length, avoiding the need to test for
3501 send_random_tag_value(
3508 noise = rand() ^ (rand() << 16);
3509 buf[0] = 'a' + noise % 26;
3511 buf[1] = 'a' + noise % 26;
3513 buf[2] = 'a' + noise % 26;
3516 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3517 ctl_putuint(buf, noise);
3522 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3524 * To keep clients honest about not depending on the order of values,
3525 * and thereby avoid being locked into ugly workarounds to maintain
3526 * backward compatibility later as new fields are added to the response,
3527 * the order is random.
3535 const char first_fmt[] = "first.%d";
3536 const char ct_fmt[] = "ct.%d";
3537 const char mv_fmt[] = "mv.%d";
3538 const char rs_fmt[] = "rs.%d";
3540 u_char sent[6]; /* 6 tag=value pairs */
3546 remaining = COUNTOF(sent);
3548 noise = (u_int32)(rand() ^ (rand() << 16));
3549 while (remaining > 0) {
3550 which = (noise & 7) % COUNTOF(sent);
3553 which = (which + 1) % COUNTOF(sent);
3558 snprintf(tag, sizeof(tag), addr_fmt, count);
3559 pch = sptoa(&mon->rmtadr);
3560 ctl_putunqstr(tag, pch, strlen(pch));
3564 snprintf(tag, sizeof(tag), last_fmt, count);
3565 ctl_putts(tag, &mon->last);
3569 snprintf(tag, sizeof(tag), first_fmt, count);
3570 ctl_putts(tag, &mon->first);
3574 snprintf(tag, sizeof(tag), ct_fmt, count);
3575 ctl_putint(tag, mon->count);
3579 snprintf(tag, sizeof(tag), mv_fmt, count);
3580 ctl_putuint(tag, mon->vn_mode);
3584 snprintf(tag, sizeof(tag), rs_fmt, count);
3585 ctl_puthex(tag, mon->flags);
3595 * read_mru_list - supports ntpq's mrulist command.
3597 * The challenge here is to match ntpdc's monlist functionality without
3598 * being limited to hundreds of entries returned total, and without
3599 * requiring state on the server. If state were required, ntpq's
3600 * mrulist command would require authentication.
3602 * The approach was suggested by Ry Jones. A finite and variable number
3603 * of entries are retrieved per request, to avoid having responses with
3604 * such large numbers of packets that socket buffers are overflowed and
3605 * packets lost. The entries are retrieved oldest-first, taking into
3606 * account that the MRU list will be changing between each request. We
3607 * can expect to see duplicate entries for addresses updated in the MRU
3608 * list during the fetch operation. In the end, the client can assemble
3609 * a close approximation of the MRU list at the point in time the last
3610 * response was sent by ntpd. The only difference is it may be longer,
3611 * containing some number of oldest entries which have since been
3612 * reclaimed. If necessary, the protocol could be extended to zap those
3613 * from the client snapshot at the end, but so far that doesn't seem
3616 * To accomodate the changing MRU list, the starting point for requests
3617 * after the first request is supplied as a series of last seen
3618 * timestamps and associated addresses, the newest ones the client has
3619 * received. As long as at least one of those entries hasn't been
3620 * bumped to the head of the MRU list, ntpd can pick up at that point.
3621 * Otherwise, the request is failed and it is up to ntpq to back up and
3622 * provide the next newest entry's timestamps and addresses, conceivably
3623 * backing up all the way to the starting point.
3626 * nonce= Regurgitated nonce retrieved by the client
3627 * previously using CTL_OP_REQ_NONCE, demonstrating
3628 * ability to receive traffic sent to its address.
3629 * frags= Limit on datagrams (fragments) in response. Used
3630 * by newer ntpq versions instead of limit= when
3631 * retrieving multiple entries.
3632 * limit= Limit on MRU entries returned. One of frags= or
3633 * limit= must be provided.
3634 * limit=1 is a special case: Instead of fetching
3635 * beginning with the supplied starting point's
3636 * newer neighbor, fetch the supplied entry, and
3637 * in that case the #.last timestamp can be zero.
3638 * This enables fetching a single entry by IP
3639 * address. When limit is not one and frags= is
3640 * provided, the fragment limit controls.
3641 * mincount= (decimal) Return entries with count >= mincount.
3642 * laddr= Return entries associated with the server's IP
3643 * address given. No port specification is needed,
3644 * and any supplied is ignored.
3645 * resall= 0x-prefixed hex restrict bits which must all be
3646 * lit for an MRU entry to be included.
3647 * Has precedence over any resany=.
3648 * resany= 0x-prefixed hex restrict bits, at least one of
3649 * which must be list for an MRU entry to be
3651 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3652 * which client previously received.
3653 * addr.0= text of newest entry's IP address and port,
3654 * IPv6 addresses in bracketed form: [::]:123
3655 * last.1= timestamp of 2nd newest entry client has.
3656 * addr.1= address of 2nd newest entry.
3659 * ntpq provides as many last/addr pairs as will fit in a single request
3660 * packet, except for the first request in a MRU fetch operation.
3662 * The response begins with a new nonce value to be used for any
3663 * followup request. Following the nonce is the next newer entry than
3664 * referred to by last.0 and addr.0, if the "0" entry has not been
3665 * bumped to the front. If it has, the first entry returned will be the
3666 * next entry newer than referred to by last.1 and addr.1, and so on.
3667 * If none of the referenced entries remain unchanged, the request fails
3668 * and ntpq backs up to the next earlier set of entries to resync.
3670 * Except for the first response, the response begins with confirmation
3671 * of the entry that precedes the first additional entry provided:
3673 * last.older= hex l_fp timestamp matching one of the input
3674 * .last timestamps, which entry now precedes the
3675 * response 0. entry in the MRU list.
3676 * addr.older= text of address corresponding to older.last.
3678 * And in any case, a successful response contains sets of values
3679 * comprising entries, with the oldest numbered 0 and incrementing from
3682 * addr.# text of IPv4 or IPv6 address and port
3683 * last.# hex l_fp timestamp of last receipt
3684 * first.# hex l_fp timestamp of first receipt
3685 * ct.# count of packets received
3686 * mv.# mode and version
3687 * rs.# restriction mask (RES_* bits)
3689 * Note the code currently assumes there are no valid three letter
3690 * tags sent with each row, and needs to be adjusted if that changes.
3692 * The client should accept the values in any order, and ignore .#
3693 * values which it does not understand, to allow a smooth path to
3694 * future changes without requiring a new opcode. Clients can rely
3695 * on all *.0 values preceding any *.1 values, that is all values for
3696 * a given index number are together in the response.
3698 * The end of the response list is noted with one or two tag=value
3699 * pairs. Unconditionally:
3701 * now= 0x-prefixed l_fp timestamp at the server marking
3702 * the end of the operation.
3704 * If any entries were returned, now= is followed by:
3706 * last.newest= hex l_fp identical to last.# of the prior
3709 static void read_mru_list(
3710 struct recvbuf *rbufp,
3714 const char nonce_text[] = "nonce";
3715 const char frags_text[] = "frags";
3716 const char limit_text[] = "limit";
3717 const char mincount_text[] = "mincount";
3718 const char resall_text[] = "resall";
3719 const char resany_text[] = "resany";
3720 const char maxlstint_text[] = "maxlstint";
3721 const char laddr_text[] = "laddr";
3722 const char resaxx_fmt[] = "0x%hx";
3730 struct interface * lcladr;
3735 sockaddr_u addr[COUNTOF(last)];
3737 struct ctl_var * in_parms;
3738 const struct ctl_var * v;
3747 mon_entry * prior_mon;
3750 if (RES_NOMRULIST & restrict_mask) {
3751 ctl_error(CERR_PERMISSION);
3754 "mrulist from %s rejected due to nomrulist restriction",
3755 stoa(&rbufp->recv_srcadr));
3760 * fill in_parms var list with all possible input parameters.
3763 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
3764 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
3765 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
3766 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
3767 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
3768 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
3769 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
3770 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
3771 for (i = 0; i < COUNTOF(last); i++) {
3772 snprintf(buf, sizeof(buf), last_fmt, (int)i);
3773 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3774 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
3775 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3778 /* decode input parms */
3791 while (NULL != (v = ctl_getitem(in_parms, &val)) &&
3792 !(EOV & v->flags)) {
3795 if (!strcmp(nonce_text, v->text)) {
3798 pnonce = estrdup(val);
3799 } else if (!strcmp(frags_text, v->text)) {
3800 sscanf(val, "%hu", &frags);
3801 } else if (!strcmp(limit_text, v->text)) {
3802 sscanf(val, "%u", &limit);
3803 } else if (!strcmp(mincount_text, v->text)) {
3804 if (1 != sscanf(val, "%d", &mincount) ||
3807 } else if (!strcmp(resall_text, v->text)) {
3808 sscanf(val, resaxx_fmt, &resall);
3809 } else if (!strcmp(resany_text, v->text)) {
3810 sscanf(val, resaxx_fmt, &resany);
3811 } else if (!strcmp(maxlstint_text, v->text)) {
3812 sscanf(val, "%u", &maxlstint);
3813 } else if (!strcmp(laddr_text, v->text)) {
3814 if (decodenetnum(val, &laddr))
3815 lcladr = getinterface(&laddr, 0);
3816 } else if (1 == sscanf(v->text, last_fmt, &si) &&
3817 (size_t)si < COUNTOF(last)) {
3818 if (2 == sscanf(val, "0x%08x.%08x", &ui, &uf)) {
3821 if (!SOCK_UNSPEC(&addr[si]) &&
3825 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
3826 (size_t)si < COUNTOF(addr)) {
3827 if (decodenetnum(val, &addr[si])
3828 && last[si].l_ui && last[si].l_uf &&
3833 free_varlist(in_parms);
3836 /* return no responses until the nonce is validated */
3840 nonce_valid = validate_nonce(pnonce, rbufp);
3845 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
3846 frags > MRU_FRAGS_LIMIT) {
3847 ctl_error(CERR_BADVALUE);
3852 * If either frags or limit is not given, use the max.
3854 if (0 != frags && 0 == limit)
3856 else if (0 != limit && 0 == frags)
3857 frags = MRU_FRAGS_LIMIT;
3860 * Find the starting point if one was provided.
3863 for (i = 0; i < (size_t)priors; i++) {
3864 hash = MON_HASH(&addr[i]);
3865 for (mon = mon_hash[hash];
3867 mon = mon->hash_next)
3868 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
3871 if (L_ISEQU(&mon->last, &last[i]))
3877 /* If a starting point was provided... */
3879 /* and none could be found unmodified... */
3881 /* tell ntpq to try again with older entries */
3882 ctl_error(CERR_UNKNOWNVAR);
3885 /* confirm the prior entry used as starting point */
3886 ctl_putts("last.older", &mon->last);
3887 pch = sptoa(&mon->rmtadr);
3888 ctl_putunqstr("addr.older", pch, strlen(pch));
3891 * Move on to the first entry the client doesn't have,
3892 * except in the special case of a limit of one. In
3893 * that case return the starting point entry.
3896 mon = PREV_DLIST(mon_mru_list, mon, mru);
3897 } else { /* start with the oldest */
3898 mon = TAIL_DLIST(mon_mru_list, mru);
3902 * send up to limit= entries in up to frags= datagrams
3905 generate_nonce(rbufp, buf, sizeof(buf));
3906 ctl_putunqstr("nonce", buf, strlen(buf));
3909 mon != NULL && res_frags < frags && count < limit;
3910 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
3912 if (mon->count < mincount)
3914 if (resall && resall != (resall & mon->flags))
3916 if (resany && !(resany & mon->flags))
3918 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
3921 if (lcladr != NULL && mon->lcladr != lcladr)
3924 send_mru_entry(mon, count);
3926 send_random_tag_value(0);
3932 * If this batch completes the MRU list, say so explicitly with
3933 * a now= l_fp timestamp.
3937 send_random_tag_value(count - 1);
3938 ctl_putts("now", &now);
3939 /* if any entries were returned confirm the last */
3940 if (prior_mon != NULL)
3941 ctl_putts("last.newest", &prior_mon->last);
3948 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
3950 * To keep clients honest about not depending on the order of values,
3951 * and thereby avoid being locked into ugly workarounds to maintain
3952 * backward compatibility later as new fields are added to the response,
3953 * the order is random.
3961 const char addr_fmtu[] = "addr.%u";
3962 const char bcast_fmt[] = "bcast.%u";
3963 const char en_fmt[] = "en.%u"; /* enabled */
3964 const char name_fmt[] = "name.%u";
3965 const char flags_fmt[] = "flags.%u";
3966 const char tl_fmt[] = "tl.%u"; /* ttl */
3967 const char mc_fmt[] = "mc.%u"; /* mcast count */
3968 const char rx_fmt[] = "rx.%u";
3969 const char tx_fmt[] = "tx.%u";
3970 const char txerr_fmt[] = "txerr.%u";
3971 const char pc_fmt[] = "pc.%u"; /* peer count */
3972 const char up_fmt[] = "up.%u"; /* uptime */
3974 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
3981 remaining = COUNTOF(sent);
3985 while (remaining > 0) {
3986 if (noisebits < 4) {
3987 noise = rand() ^ (rand() << 16);
3990 which = (noise & 0xf) % COUNTOF(sent);
3995 which = (which + 1) % COUNTOF(sent);
4000 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4001 pch = sptoa(&la->sin);
4002 ctl_putunqstr(tag, pch, strlen(pch));
4006 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4007 if (INT_BCASTOPEN & la->flags)
4008 pch = sptoa(&la->bcast);
4011 ctl_putunqstr(tag, pch, strlen(pch));
4015 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4016 ctl_putint(tag, !la->ignore_packets);
4020 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4021 ctl_putstr(tag, la->name, strlen(la->name));
4025 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4026 ctl_puthex(tag, (u_int)la->flags);
4030 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4031 ctl_putint(tag, la->last_ttl);
4035 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4036 ctl_putint(tag, la->num_mcast);
4040 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4041 ctl_putint(tag, la->received);
4045 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4046 ctl_putint(tag, la->sent);
4050 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4051 ctl_putint(tag, la->notsent);
4055 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4056 ctl_putuint(tag, la->peercnt);
4060 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4061 ctl_putuint(tag, current_time - la->starttime);
4067 send_random_tag_value((int)ifnum);
4072 * read_ifstats - send statistics for each local address, exposed by
4077 struct recvbuf * rbufp
4084 * loop over [0..sys_ifnum] searching ep_list for each
4087 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4088 for (la = ep_list; la != NULL; la = la->elink)
4089 if (ifidx == la->ifnum)
4093 /* return stats for one local address */
4094 send_ifstats_entry(la, ifidx);
4100 sockaddrs_from_restrict_u(
4110 psaA->sa.sa_family = AF_INET;
4111 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4112 psaM->sa.sa_family = AF_INET;
4113 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4115 psaA->sa.sa_family = AF_INET6;
4116 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4117 sizeof(psaA->sa6.sin6_addr));
4118 psaM->sa.sa_family = AF_INET6;
4119 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4120 sizeof(psaA->sa6.sin6_addr));
4126 * Send a restrict entry in response to a "ntpq -c reslist" request.
4128 * To keep clients honest about not depending on the order of values,
4129 * and thereby avoid being locked into ugly workarounds to maintain
4130 * backward compatibility later as new fields are added to the response,
4131 * the order is random.
4134 send_restrict_entry(
4140 const char addr_fmtu[] = "addr.%u";
4141 const char mask_fmtu[] = "mask.%u";
4142 const char hits_fmt[] = "hits.%u";
4143 const char flags_fmt[] = "flags.%u";
4145 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4154 const char * match_str;
4155 const char * access_str;
4157 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4158 remaining = COUNTOF(sent);
4162 while (remaining > 0) {
4163 if (noisebits < 2) {
4164 noise = rand() ^ (rand() << 16);
4167 which = (noise & 0x3) % COUNTOF(sent);
4172 which = (which + 1) % COUNTOF(sent);
4177 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4179 ctl_putunqstr(tag, pch, strlen(pch));
4183 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4185 ctl_putunqstr(tag, pch, strlen(pch));
4189 snprintf(tag, sizeof(tag), hits_fmt, idx);
4190 ctl_putuint(tag, pres->count);
4194 snprintf(tag, sizeof(tag), flags_fmt, idx);
4195 match_str = res_match_flags(pres->mflags);
4196 access_str = res_access_flags(pres->flags);
4197 if ('\0' == match_str[0]) {
4201 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4202 match_str, access_str);
4205 ctl_putunqstr(tag, pch, strlen(pch));
4211 send_random_tag_value((int)idx);
4222 for ( ; pres != NULL; pres = pres->link) {
4223 send_restrict_entry(pres, ipv6, *pidx);
4230 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4233 read_addr_restrictions(
4234 struct recvbuf * rbufp
4240 send_restrict_list(restrictlist4, FALSE, &idx);
4241 send_restrict_list(restrictlist6, TRUE, &idx);
4247 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4251 struct recvbuf * rbufp,
4255 const char ifstats_s[] = "ifstats";
4256 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4257 const char addr_rst_s[] = "addr_restrictions";
4258 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4259 struct ntp_control * cpkt;
4260 u_short qdata_octets;
4263 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4264 * used only for ntpq -c ifstats. With the addition of reslist
4265 * the same opcode was generalized to retrieve ordered lists
4266 * which require authentication. The request data is empty or
4267 * contains "ifstats" (not null terminated) to retrieve local
4268 * addresses and associated stats. It is "addr_restrictions"
4269 * to retrieve the IPv4 then IPv6 remote address restrictions,
4270 * which are access control lists. Other request data return
4273 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4274 qdata_octets = ntohs(cpkt->count);
4275 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4276 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4277 read_ifstats(rbufp);
4280 if (a_r_chars == qdata_octets &&
4281 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4282 read_addr_restrictions(rbufp);
4285 ctl_error(CERR_UNKNOWNVAR);
4290 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4292 static void req_nonce(
4293 struct recvbuf * rbufp,
4299 generate_nonce(rbufp, buf, sizeof(buf));
4300 ctl_putunqstr("nonce", buf, strlen(buf));
4306 * read_clockstatus - return clock radio status
4311 struct recvbuf *rbufp,
4317 * If no refclock support, no data to return
4319 ctl_error(CERR_BADASSOC);
4321 const struct ctl_var * v;
4329 struct ctl_var * kv;
4330 struct refclockstat cs;
4332 if (res_associd != 0) {
4333 peer = findpeerbyassoc(res_associd);
4336 * Find a clock for this jerk. If the system peer
4337 * is a clock use it, else search peer_list for one.
4339 if (sys_peer != NULL && (FLAG_REFCLOCK &
4343 for (peer = peer_list;
4345 peer = peer->p_link)
4346 if (FLAG_REFCLOCK & peer->flags)
4349 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4350 ctl_error(CERR_BADASSOC);
4354 * If we got here we have a peer which is a clock. Get his
4358 refclock_control(&peer->srcadr, NULL, &cs);
4361 * Look for variables in the packet.
4363 rpkt.status = htons(ctlclkstatus(&cs));
4364 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4365 wants = emalloc_zero(wants_alloc);
4367 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4368 if (!(EOV & v->flags)) {
4369 wants[v->code] = TRUE;
4372 v = ctl_getitem(kv, &valuep);
4373 NTP_INSIST(NULL != v);
4374 if (EOV & v->flags) {
4375 ctl_error(CERR_UNKNOWNVAR);
4377 free_varlist(cs.kv_list);
4380 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4386 for (i = 1; i <= CC_MAXCODE; i++)
4388 ctl_putclock(i, &cs, TRUE);
4390 for (i = 0; !(EOV & kv[i].flags); i++)
4391 if (wants[i + CC_MAXCODE + 1])
4392 ctl_putdata(kv[i].text,
4396 for (cc = def_clock_var; *cc != 0; cc++)
4397 ctl_putclock((int)*cc, &cs, FALSE);
4398 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4399 if (DEF & kv->flags)
4400 ctl_putdata(kv->text, strlen(kv->text),
4405 free_varlist(cs.kv_list);
4413 * write_clockstatus - we don't do this
4418 struct recvbuf *rbufp,
4422 ctl_error(CERR_PERMISSION);
4426 * Trap support from here on down. We send async trap messages when the
4427 * upper levels report trouble. Traps can by set either by control
4428 * messages or by configuration.
4431 * set_trap - set a trap in response to a control message
4435 struct recvbuf *rbufp,
4442 * See if this guy is allowed
4444 if (restrict_mask & RES_NOTRAP) {
4445 ctl_error(CERR_PERMISSION);
4450 * Determine his allowed trap type.
4452 traptype = TRAP_TYPE_PRIO;
4453 if (restrict_mask & RES_LPTRAP)
4454 traptype = TRAP_TYPE_NONPRIO;
4457 * Call ctlsettrap() to do the work. Return
4458 * an error if it can't assign the trap.
4460 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4462 ctl_error(CERR_NORESOURCE);
4468 * unset_trap - unset a trap in response to a control message
4472 struct recvbuf *rbufp,
4479 * We don't prevent anyone from removing his own trap unless the
4480 * trap is configured. Note we also must be aware of the
4481 * possibility that restriction flags were changed since this
4482 * guy last set his trap. Set the trap type based on this.
4484 traptype = TRAP_TYPE_PRIO;
4485 if (restrict_mask & RES_LPTRAP)
4486 traptype = TRAP_TYPE_NONPRIO;
4489 * Call ctlclrtrap() to clear this out.
4491 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4492 ctl_error(CERR_BADASSOC);
4498 * ctlsettrap - called to set a trap
4503 struct interface *linter,
4509 struct ctl_trap *tp;
4510 struct ctl_trap *tptouse;
4513 * See if we can find this trap. If so, we only need update
4514 * the flags and the time.
4516 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4519 case TRAP_TYPE_CONFIG:
4520 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4523 case TRAP_TYPE_PRIO:
4524 if (tp->tr_flags & TRAP_CONFIGURED)
4525 return (1); /* don't change anything */
4526 tp->tr_flags = TRAP_INUSE;
4529 case TRAP_TYPE_NONPRIO:
4530 if (tp->tr_flags & TRAP_CONFIGURED)
4531 return (1); /* don't change anything */
4532 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4535 tp->tr_settime = current_time;
4541 * First we heard of this guy. Try to find a trap structure
4542 * for him to use, clearing out lesser priority guys if we
4543 * have to. Clear out anyone who's expired while we're at it.
4546 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4548 if ((TRAP_INUSE & tp->tr_flags) &&
4549 !(TRAP_CONFIGURED & tp->tr_flags) &&
4550 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4554 if (!(TRAP_INUSE & tp->tr_flags)) {
4556 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4559 case TRAP_TYPE_CONFIG:
4560 if (tptouse == NULL) {
4564 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4565 !(TRAP_NONPRIO & tp->tr_flags))
4568 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4569 && (TRAP_NONPRIO & tp->tr_flags)) {
4573 if (tptouse->tr_origtime <
4578 case TRAP_TYPE_PRIO:
4579 if ( TRAP_NONPRIO & tp->tr_flags) {
4580 if (tptouse == NULL ||
4582 tptouse->tr_flags) &&
4583 tptouse->tr_origtime <
4589 case TRAP_TYPE_NONPRIO:
4596 * If we don't have room for him return an error.
4598 if (tptouse == NULL)
4602 * Set up this structure for him.
4604 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4605 tptouse->tr_count = tptouse->tr_resets = 0;
4606 tptouse->tr_sequence = 1;
4607 tptouse->tr_addr = *raddr;
4608 tptouse->tr_localaddr = linter;
4609 tptouse->tr_version = (u_char) version;
4610 tptouse->tr_flags = TRAP_INUSE;
4611 if (traptype == TRAP_TYPE_CONFIG)
4612 tptouse->tr_flags |= TRAP_CONFIGURED;
4613 else if (traptype == TRAP_TYPE_NONPRIO)
4614 tptouse->tr_flags |= TRAP_NONPRIO;
4621 * ctlclrtrap - called to clear a trap
4626 struct interface *linter,
4630 register struct ctl_trap *tp;
4632 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4635 if (tp->tr_flags & TRAP_CONFIGURED
4636 && traptype != TRAP_TYPE_CONFIG)
4646 * ctlfindtrap - find a trap given the remote and local addresses
4648 static struct ctl_trap *
4651 struct interface *linter
4656 for (n = 0; n < COUNTOF(ctl_traps); n++)
4657 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4658 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4659 && (linter == ctl_traps[n].tr_localaddr))
4660 return &ctl_traps[n];
4667 * report_event - report an event to the trappers
4671 int err, /* error code */
4672 struct peer *peer, /* peer structure pointer */
4673 const char *str /* protostats string */
4676 char statstr[NTP_MAXSTRLEN];
4681 * Report the error to the protostats file, system log and
4687 * Discard a system report if the number of reports of
4688 * the same type exceeds the maximum.
4690 if (ctl_sys_last_event != (u_char)err)
4691 ctl_sys_num_events= 0;
4692 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4695 ctl_sys_last_event = (u_char)err;
4696 ctl_sys_num_events++;
4697 snprintf(statstr, sizeof(statstr),
4698 "0.0.0.0 %04x %02x %s",
4699 ctlsysstatus(), err, eventstr(err));
4701 len = strlen(statstr);
4702 snprintf(statstr + len, sizeof(statstr) - len,
4706 msyslog(LOG_INFO, "%s", statstr);
4710 * Discard a peer report if the number of reports of
4711 * the same type exceeds the maximum for that peer.
4716 errlast = (u_char)err & ~PEER_EVENT;
4717 if (peer->last_event == errlast)
4718 peer->num_events = 0;
4719 if (peer->num_events >= CTL_PEER_MAXEVENTS)
4722 peer->last_event = errlast;
4724 if (ISREFCLOCKADR(&peer->srcadr))
4725 src = refnumtoa(&peer->srcadr);
4727 src = stoa(&peer->srcadr);
4729 snprintf(statstr, sizeof(statstr),
4730 "%s %04x %02x %s", src,
4731 ctlpeerstatus(peer), err, eventstr(err));
4733 len = strlen(statstr);
4734 snprintf(statstr + len, sizeof(statstr) - len,
4737 NLOG(NLOG_PEEREVENT)
4738 msyslog(LOG_INFO, "%s", statstr);
4740 record_proto_stats(statstr);
4743 printf("event at %lu %s\n", current_time, statstr);
4747 * If no trappers, return.
4749 if (num_ctl_traps <= 0)
4753 * Set up the outgoing packet variables
4755 res_opcode = CTL_OP_ASYNCMSG;
4758 res_authenticate = FALSE;
4759 datapt = rpkt.u.data;
4760 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
4761 if (!(err & PEER_EVENT)) {
4763 rpkt.status = htons(ctlsysstatus());
4765 /* Include the core system variables and the list. */
4766 for (i = 1; i <= CS_VARLIST; i++)
4769 NTP_INSIST(peer != NULL);
4770 rpkt.associd = htons(peer->associd);
4771 rpkt.status = htons(ctlpeerstatus(peer));
4773 /* Dump it all. Later, maybe less. */
4774 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
4775 ctl_putpeer(i, peer);
4778 * for clock exception events: add clock variables to
4779 * reflect info on exception
4781 if (err == PEVNT_CLOCK) {
4782 struct refclockstat cs;
4786 refclock_control(&peer->srcadr, NULL, &cs);
4788 ctl_puthex("refclockstatus",
4791 for (i = 1; i <= CC_MAXCODE; i++)
4792 ctl_putclock(i, &cs, FALSE);
4793 for (kv = cs.kv_list;
4794 kv != NULL && !(EOV & kv->flags);
4796 if (DEF & kv->flags)
4797 ctl_putdata(kv->text,
4800 free_varlist(cs.kv_list);
4802 #endif /* REFCLOCK */
4806 * We're done, return.
4813 * mprintf_event - printf-style varargs variant of report_event()
4817 int evcode, /* event code */
4818 struct peer * p, /* may be NULL */
4819 const char * fmt, /* msnprintf format */
4828 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
4830 report_event(evcode, p, msg);
4837 * ctl_clr_stats - clear stat counters
4842 ctltimereset = current_time;
4845 numctlresponses = 0;
4850 numctlinputresp = 0;
4851 numctlinputfrag = 0;
4853 numctlbadoffset = 0;
4854 numctlbadversion = 0;
4855 numctldatatooshort = 0;
4862 const struct ctl_var *k
4871 while (!(EOV & (k++)->flags))
4874 NTP_ENSURE(c <= USHRT_MAX);
4881 struct ctl_var **kv,
4891 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
4893 buf = emalloc(size);
4898 k[c + 1].text = NULL;
4899 k[c + 1].flags = EOV;
4907 struct ctl_var **kv,
4918 if (NULL == data || !size)
4923 while (!(EOV & k->flags)) {
4924 if (NULL == k->text) {
4926 memcpy(td, data, size);
4933 while (*t != '=' && *s == *t) {
4937 if (*s == *t && ((*t == '=') || !*t)) {
4938 td = erealloc((void *)(intptr_t)k->text, size);
4939 memcpy(td, data, size);
4948 td = add_var(kv, size, def);
4949 memcpy(td, data, size);
4960 set_var(&ext_sys_var, data, size, def);
4965 * get_ext_sys_var() retrieves the value of a user-defined variable or
4966 * NULL if the variable has not been setvar'd.
4969 get_ext_sys_var(const char *tag)
4977 for (v = ext_sys_var; !(EOV & v->flags); v++) {
4978 if (NULL != v->text && !memcmp(tag, v->text, c)) {
4979 if ('=' == v->text[c]) {
4980 val = v->text + c + 1;
4982 } else if ('\0' == v->text[c]) {
5000 for (k = kv; !(k->flags & EOV); k++)
5001 free((void *)(intptr_t)k->text);