2 * ntp_control.c - respond to mode 6 control messages and send async
3 * traps. Provides service to ntpq and others.
7 * $FreeBSD: projects/release-pkg/contrib/ntp/ntpd/ntp_control.c 277386 2015-01-19 16:15:12Z gjb $
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"
35 #include <rc_cmdlength.h>
37 # include "ntp_syscall.h"
42 * Structure to hold request procedure information
46 short control_code; /* defined request code */
47 #define NO_REQUEST (-1)
48 u_short flags; /* flags word */
49 /* Only one flag. Authentication required or not. */
52 void (*handler) (struct recvbuf *, int); /* handle request */
57 * Request processing routines
59 static void ctl_error (u_char);
61 static u_short ctlclkstatus (struct refclockstat *);
63 static void ctl_flushpkt (u_char);
64 static void ctl_putdata (const char *, unsigned int, int);
65 static void ctl_putstr (const char *, const char *, size_t);
66 static void ctl_putdblf (const char *, int, int, double);
67 #define ctl_putdbl(tag, d) ctl_putdblf(tag, 1, 3, d)
68 #define ctl_putdbl6(tag, d) ctl_putdblf(tag, 1, 6, d)
69 #define ctl_putsfp(tag, sfp) ctl_putdblf(tag, 0, -1, \
71 static void ctl_putuint (const char *, u_long);
72 static void ctl_puthex (const char *, u_long);
73 static void ctl_putint (const char *, long);
74 static void ctl_putts (const char *, l_fp *);
75 static void ctl_putadr (const char *, u_int32,
77 static void ctl_putrefid (const char *, u_int32);
78 static void ctl_putarray (const char *, double *, int);
79 static void ctl_putsys (int);
80 static void ctl_putpeer (int, struct peer *);
81 static void ctl_putfs (const char *, tstamp_t);
82 static void ctl_printf (const char *, ...) NTP_PRINTF(1, 2);
84 static void ctl_putclock (int, struct refclockstat *, int);
86 static const struct ctl_var *ctl_getitem(const struct ctl_var *,
88 static u_short count_var (const struct ctl_var *);
89 static void control_unspec (struct recvbuf *, int);
90 static void read_status (struct recvbuf *, int);
91 static void read_sysvars (void);
92 static void read_peervars (void);
93 static void read_variables (struct recvbuf *, int);
94 static void write_variables (struct recvbuf *, int);
95 static void read_clockstatus(struct recvbuf *, int);
96 static void write_clockstatus(struct recvbuf *, int);
97 static void set_trap (struct recvbuf *, int);
98 static void save_config (struct recvbuf *, int);
99 static void configure (struct recvbuf *, int);
100 static void send_mru_entry (mon_entry *, int);
101 static void send_random_tag_value(int);
102 static void read_mru_list (struct recvbuf *, int);
103 static void send_ifstats_entry(endpt *, u_int);
104 static void read_ifstats (struct recvbuf *);
105 static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *,
107 static void send_restrict_entry(restrict_u *, int, u_int);
108 static void send_restrict_list(restrict_u *, int, u_int *);
109 static void read_addr_restrictions(struct recvbuf *);
110 static void read_ordlist (struct recvbuf *, int);
111 static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32);
112 static void generate_nonce (struct recvbuf *, char *, size_t);
113 static int validate_nonce (const char *, struct recvbuf *);
114 static void req_nonce (struct recvbuf *, int);
115 static void unset_trap (struct recvbuf *, int);
116 static struct ctl_trap *ctlfindtrap(sockaddr_u *,
119 int/*BOOL*/ is_safe_filename(const char * name);
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_WANDER_THRESH 89
232 #define CS_LEAPSMEARINTV 90
233 #define CS_LEAPSMEAROFFS 91
234 #define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS
236 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
237 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
238 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
239 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
240 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
241 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
242 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
243 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
244 #define CS_MAXCODE CS_DIGEST
245 #else /* !AUTOKEY follows */
246 #define CS_MAXCODE CS_MAX_NOAUTOKEY
247 #endif /* !AUTOKEY */
250 * Peer variables we understand
253 #define CP_AUTHENABLE 2
254 #define CP_AUTHENTIC 3
261 #define CP_STRATUM 10
264 #define CP_PRECISION 13
265 #define CP_ROOTDELAY 14
266 #define CP_ROOTDISPERSION 15
268 #define CP_REFTIME 17
273 #define CP_UNREACH 22
278 #define CP_DISPERSION 27
280 #define CP_FILTDELAY 29
281 #define CP_FILTOFFSET 30
283 #define CP_RECEIVED 32
285 #define CP_FILTERROR 34
288 #define CP_VARLIST 37
293 #define CP_SRCHOST 42
294 #define CP_TIMEREC 43
295 #define CP_TIMEREACH 44
296 #define CP_BADAUTH 45
297 #define CP_BOGUSORG 46
299 #define CP_SELDISP 48
300 #define CP_SELBROKEN 49
301 #define CP_CANDIDATE 50
302 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
304 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
305 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
306 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
307 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
308 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
309 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
310 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
311 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
312 #define CP_MAXCODE CP_IDENT
313 #else /* !AUTOKEY follows */
314 #define CP_MAXCODE CP_MAX_NOAUTOKEY
315 #endif /* !AUTOKEY */
318 * Clock variables we understand
321 #define CC_TIMECODE 2
324 #define CC_BADFORMAT 5
326 #define CC_FUDGETIME1 7
327 #define CC_FUDGETIME2 8
328 #define CC_FUDGEVAL1 9
329 #define CC_FUDGEVAL2 10
332 #define CC_VARLIST 13
333 #define CC_MAXCODE CC_VARLIST
336 * System variable values. The array can be indexed by the variable
337 * index to find the textual name.
339 static const struct ctl_var sys_var[] = {
340 { 0, PADDING, "" }, /* 0 */
341 { CS_LEAP, RW, "leap" }, /* 1 */
342 { CS_STRATUM, RO, "stratum" }, /* 2 */
343 { CS_PRECISION, RO, "precision" }, /* 3 */
344 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
345 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
346 { CS_REFID, RO, "refid" }, /* 6 */
347 { CS_REFTIME, RO, "reftime" }, /* 7 */
348 { CS_POLL, RO, "tc" }, /* 8 */
349 { CS_PEERID, RO, "peer" }, /* 9 */
350 { CS_OFFSET, RO, "offset" }, /* 10 */
351 { CS_DRIFT, RO, "frequency" }, /* 11 */
352 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
353 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
354 { CS_CLOCK, RO, "clock" }, /* 14 */
355 { CS_PROCESSOR, RO, "processor" }, /* 15 */
356 { CS_SYSTEM, RO, "system" }, /* 16 */
357 { CS_VERSION, RO, "version" }, /* 17 */
358 { CS_STABIL, RO, "clk_wander" }, /* 18 */
359 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
360 { CS_TAI, RO, "tai" }, /* 20 */
361 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
362 { CS_LEAPEND, RO, "expire" }, /* 22 */
363 { CS_RATE, RO, "mintc" }, /* 23 */
364 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
365 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
366 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
367 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
368 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
369 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
370 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
371 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
372 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
373 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
374 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
375 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
376 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
377 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
378 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
379 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
380 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
381 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
382 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
383 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
384 { CS_PEERADR, RO, "peeradr" }, /* 44 */
385 { CS_PEERMODE, RO, "peermode" }, /* 45 */
386 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 46 */
387 { CS_AUTHDELAY, RO, "authdelay" }, /* 47 */
388 { CS_AUTHKEYS, RO, "authkeys" }, /* 48 */
389 { CS_AUTHFREEK, RO, "authfreek" }, /* 49 */
390 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 50 */
391 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 51 */
392 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 52 */
393 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 53 */
394 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 54 */
395 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 55 */
396 { CS_AUTHRESET, RO, "authreset" }, /* 56 */
397 { CS_K_OFFSET, RO, "koffset" }, /* 57 */
398 { CS_K_FREQ, RO, "kfreq" }, /* 58 */
399 { CS_K_MAXERR, RO, "kmaxerr" }, /* 59 */
400 { CS_K_ESTERR, RO, "kesterr" }, /* 60 */
401 { CS_K_STFLAGS, RO, "kstflags" }, /* 61 */
402 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 62 */
403 { CS_K_PRECISION, RO, "kprecis" }, /* 63 */
404 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 64 */
405 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 65 */
406 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 66 */
407 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 67 */
408 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 68 */
409 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 69 */
410 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 70 */
411 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 71 */
412 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 72 */
413 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 73 */
414 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 74 */
415 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 75 */
416 { CS_USED_RBUF, RO, "used_rbuf" }, /* 76 */
417 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 77 */
418 { CS_IO_DROPPED, RO, "io_dropped" }, /* 78 */
419 { CS_IO_IGNORED, RO, "io_ignored" }, /* 79 */
420 { CS_IO_RECEIVED, RO, "io_received" }, /* 80 */
421 { CS_IO_SENT, RO, "io_sent" }, /* 81 */
422 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 82 */
423 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 83 */
424 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 84 */
425 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 85 */
426 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 86 */
427 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 87 */
428 { CS_FUZZ, RO, "fuzz" }, /* 88 */
429 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 89 */
431 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 90 */
432 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 91 */
435 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
436 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
437 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
438 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
439 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
440 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
441 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
442 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
444 { 0, EOV, "" } /* 87/95 */
447 static struct ctl_var *ext_sys_var = NULL;
450 * System variables we print by default (in fuzzball order,
453 static const u_char def_sys_var[] = {
494 static const struct ctl_var peer_var[] = {
495 { 0, PADDING, "" }, /* 0 */
496 { CP_CONFIG, RO, "config" }, /* 1 */
497 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
498 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
499 { CP_SRCADR, RO, "srcadr" }, /* 4 */
500 { CP_SRCPORT, RO, "srcport" }, /* 5 */
501 { CP_DSTADR, RO, "dstadr" }, /* 6 */
502 { CP_DSTPORT, RO, "dstport" }, /* 7 */
503 { CP_LEAP, RO, "leap" }, /* 8 */
504 { CP_HMODE, RO, "hmode" }, /* 9 */
505 { CP_STRATUM, RO, "stratum" }, /* 10 */
506 { CP_PPOLL, RO, "ppoll" }, /* 11 */
507 { CP_HPOLL, RO, "hpoll" }, /* 12 */
508 { CP_PRECISION, RO, "precision" }, /* 13 */
509 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
510 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
511 { CP_REFID, RO, "refid" }, /* 16 */
512 { CP_REFTIME, RO, "reftime" }, /* 17 */
513 { CP_ORG, RO, "org" }, /* 18 */
514 { CP_REC, RO, "rec" }, /* 19 */
515 { CP_XMT, RO, "xleave" }, /* 20 */
516 { CP_REACH, RO, "reach" }, /* 21 */
517 { CP_UNREACH, RO, "unreach" }, /* 22 */
518 { CP_TIMER, RO, "timer" }, /* 23 */
519 { CP_DELAY, RO, "delay" }, /* 24 */
520 { CP_OFFSET, RO, "offset" }, /* 25 */
521 { CP_JITTER, RO, "jitter" }, /* 26 */
522 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
523 { CP_KEYID, RO, "keyid" }, /* 28 */
524 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
525 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
526 { CP_PMODE, RO, "pmode" }, /* 31 */
527 { CP_RECEIVED, RO, "received"}, /* 32 */
528 { CP_SENT, RO, "sent" }, /* 33 */
529 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
530 { CP_FLASH, RO, "flash" }, /* 35 */
531 { CP_TTL, RO, "ttl" }, /* 36 */
532 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
533 { CP_IN, RO, "in" }, /* 38 */
534 { CP_OUT, RO, "out" }, /* 39 */
535 { CP_RATE, RO, "headway" }, /* 40 */
536 { CP_BIAS, RO, "bias" }, /* 41 */
537 { CP_SRCHOST, RO, "srchost" }, /* 42 */
538 { CP_TIMEREC, RO, "timerec" }, /* 43 */
539 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
540 { CP_BADAUTH, RO, "badauth" }, /* 45 */
541 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
542 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
543 { CP_SELDISP, RO, "seldisp" }, /* 48 */
544 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
545 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
547 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
548 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
549 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
550 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
551 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
552 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
553 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
554 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
556 { 0, EOV, "" } /* 50/58 */
561 * Peer variables we print by default
563 static const u_char def_peer_var[] = {
612 * Clock variable list
614 static const struct ctl_var clock_var[] = {
615 { 0, PADDING, "" }, /* 0 */
616 { CC_TYPE, RO, "type" }, /* 1 */
617 { CC_TIMECODE, RO, "timecode" }, /* 2 */
618 { CC_POLL, RO, "poll" }, /* 3 */
619 { CC_NOREPLY, RO, "noreply" }, /* 4 */
620 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
621 { CC_BADDATA, RO, "baddata" }, /* 6 */
622 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
623 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
624 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
625 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
626 { CC_FLAGS, RO, "flags" }, /* 11 */
627 { CC_DEVICE, RO, "device" }, /* 12 */
628 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
629 { 0, EOV, "" } /* 14 */
634 * Clock variables printed by default
636 static const u_char def_clock_var[] = {
638 CC_TYPE, /* won't be output if device = known */
654 * MRU string constants shared by send_mru_entry() and read_mru_list().
656 static const char addr_fmt[] = "addr.%d";
657 static const char last_fmt[] = "last.%d";
660 * System and processor definitions.
664 # define STR_SYSTEM "UNIX"
666 # ifndef STR_PROCESSOR
667 # define STR_PROCESSOR "unknown"
670 static const char str_system[] = STR_SYSTEM;
671 static const char str_processor[] = STR_PROCESSOR;
673 # include <sys/utsname.h>
674 static struct utsname utsnamebuf;
675 #endif /* HAVE_UNAME */
678 * Trap structures. We only allow a few of these, and send a copy of
679 * each async message to each live one. Traps time out after an hour, it
680 * is up to the trap receipient to keep resetting it to avoid being
684 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
688 * Type bits, for ctlsettrap() call.
690 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
691 #define TRAP_TYPE_PRIO 1 /* priority trap */
692 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
696 * List relating reference clock types to control message time sources.
697 * Index by the reference clock type. This list will only be used iff
698 * the reference clock driver doesn't set peer->sstclktype to something
699 * different than CTL_SST_TS_UNSPEC.
702 static const u_char clocktypes[] = {
703 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
704 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
705 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
706 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
707 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
708 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
709 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
710 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
711 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
712 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
713 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
714 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
715 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
716 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
717 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
718 CTL_SST_TS_NTP, /* not used (15) */
719 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
720 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
721 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
722 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
723 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
724 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
725 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
726 CTL_SST_TS_NTP, /* not used (23) */
727 CTL_SST_TS_NTP, /* not used (24) */
728 CTL_SST_TS_NTP, /* not used (25) */
729 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
730 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
731 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
732 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
733 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
734 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
735 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
736 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
737 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
738 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
739 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
740 CTL_SST_TS_LF, /* REFCLK_FG (37) */
741 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
742 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
743 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
744 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
745 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
746 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
747 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
748 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
749 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
751 #endif /* REFCLOCK */
755 * Keyid used for authenticating write requests.
757 keyid_t ctl_auth_keyid;
760 * We keep track of the last error reported by the system internally
762 static u_char ctl_sys_last_event;
763 static u_char ctl_sys_num_events;
767 * Statistic counters to keep track of requests and responses.
769 u_long ctltimereset; /* time stats reset */
770 u_long numctlreq; /* number of requests we've received */
771 u_long numctlbadpkts; /* number of bad control packets */
772 u_long numctlresponses; /* number of resp packets sent with data */
773 u_long numctlfrags; /* number of fragments sent */
774 u_long numctlerrors; /* number of error responses sent */
775 u_long numctltooshort; /* number of too short input packets */
776 u_long numctlinputresp; /* number of responses on input */
777 u_long numctlinputfrag; /* number of fragments on input */
778 u_long numctlinputerr; /* number of input pkts with err bit set */
779 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
780 u_long numctlbadversion; /* number of input pkts with unknown version */
781 u_long numctldatatooshort; /* data too short for count */
782 u_long numctlbadop; /* bad op code found in packet */
783 u_long numasyncmsgs; /* number of async messages we've sent */
786 * Response packet used by these routines. Also some state information
787 * so that we can handle packet formatting within a common set of
788 * subroutines. Note we try to enter data in place whenever possible,
789 * but the need to set the more bit correctly means we occasionally
790 * use the extra buffer and copy.
792 static struct ntp_control rpkt;
793 static u_char res_version;
794 static u_char res_opcode;
795 static associd_t res_associd;
796 static u_short res_frags; /* datagrams in this response */
797 static int res_offset; /* offset of payload in response */
798 static u_char * datapt;
799 static u_char * dataend;
800 static int datalinelen;
801 static int datasent; /* flag to avoid initial ", " */
802 static int datanotbinflag;
803 static sockaddr_u *rmt_addr;
804 static struct interface *lcl_inter;
806 static u_char res_authenticate;
807 static u_char res_authokay;
808 static keyid_t res_keyid;
810 #define MAXDATALINELEN (72)
812 static u_char res_async; /* sending async trap response? */
815 * Pointers for saving state when decoding request packets
821 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
825 * init_control - initialize request data
834 #endif /* HAVE_UNAME */
839 ctl_sys_last_event = EVNT_UNSPEC;
840 ctl_sys_num_events = 0;
843 for (i = 0; i < COUNTOF(ctl_traps); i++)
844 ctl_traps[i].tr_flags = 0;
849 * ctl_error - send an error response for the current request
859 DPRINTF(3, ("sending control error %u\n", errcode));
862 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
863 * have already been filled in.
865 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
866 (res_opcode & CTL_OP_MASK);
867 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
871 * send packet and bump counters
873 if (res_authenticate && sys_authenticate) {
874 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
876 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
877 CTL_HEADER_LEN + maclen);
879 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
884 is_safe_filename(const char * name)
886 /* We need a strict validation of filenames we should write: The
887 * daemon might run with special permissions and is remote
888 * controllable, so we better take care what we allow as file
891 * The first character must be digit or a letter from the ASCII
892 * base plane or a '_' ([_A-Za-z0-9]), the following characters
893 * must be from [-._+A-Za-z0-9].
895 * We do not trust the character classification much here: Since
896 * the NTP protocol makes no provisions for UTF-8 or local code
897 * pages, we strictly require the 7bit ASCII code page.
899 * The following table is a packed bit field of 128 two-bit
900 * groups. The LSB in each group tells us if a character is
901 * acceptable at the first position, the MSB if the character is
902 * accepted at any other position.
904 * This does not ensure that the file name is syntactically
905 * correct (multiple dots will not work with VMS...) but it will
906 * exclude potential globbing bombs and directory traversal. It
907 * also rules out drive selection. (For systems that have this
908 * notion, like Windows or VMS.)
910 static const uint32_t chclass[8] = {
911 0x00000000, 0x00000000,
912 0x28800000, 0x000FFFFF,
913 0xFFFFFFFC, 0xC03FFFFF,
914 0xFFFFFFFC, 0x003FFFFF
917 u_int widx, bidx, mask;
922 while (0 != (widx = (u_char)*name++)) {
923 bidx = (widx & 15) << 1;
925 if (widx >= sizeof(chclass))
927 if (0 == ((chclass[widx] >> bidx) & mask))
936 * save_config - Implements ntpq -c "saveconfig <filename>"
937 * Writes current configuration including any runtime
938 * changes by ntpq's :config or config-from-file
940 * Note: There should be no buffer overflow or truncation in the
941 * processing of file names -- both cause security problems. This is bit
942 * painful to code but essential here.
946 struct recvbuf *rbufp,
950 /* block directory traversal by searching for characters that
951 * indicate directory components in a file path.
953 * Conceptually we should be searching for DIRSEP in filename,
954 * however Windows actually recognizes both forward and
955 * backslashes as equivalent directory separators at the API
956 * level. On POSIX systems we could allow '\\' but such
957 * filenames are tricky to manipulate from a shell, so just
958 * reject both types of slashes on all platforms.
960 /* TALOS-CAN-0062: block directory traversal for VMS, too */
961 static const char * illegal_in_filename =
963 ":[]" /* do not allow drive and path components here */
964 #elif defined(SYS_WINNT)
965 ":\\/" /* path and drive separators */
967 "\\/" /* separator and critical char for POSIX */
972 static const char savedconfig_eq[] = "savedconfig=";
974 /* Build a safe open mode from the available mode flags. We want
975 * to create a new file and write it in text mode (when
976 * applicable -- only Windows does this...)
978 static const int openmode = O_CREAT | O_TRUNC | O_WRONLY
979 # if defined(O_EXCL) /* posix, vms */
981 # elif defined(_O_EXCL) /* windows is alway very special... */
984 # if defined(_O_TEXT) /* windows, again */
992 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
1000 if (RES_NOMODIFY & restrict_mask) {
1001 ctl_printf("%s", "saveconfig prohibited by restrict ... nomodify");
1005 "saveconfig from %s rejected due to nomodify restriction",
1006 stoa(&rbufp->recv_srcadr));
1012 if (NULL == saveconfigdir) {
1013 ctl_printf("%s", "saveconfig prohibited, no saveconfigdir configured");
1017 "saveconfig from %s rejected, no saveconfigdir",
1018 stoa(&rbufp->recv_srcadr));
1022 /* The length checking stuff gets serious. Do not assume a NUL
1023 * byte can be found, but if so, use it to calculate the needed
1024 * buffer size. If the available buffer is too short, bail out;
1025 * likewise if there is no file spec. (The latter will not
1026 * happen when using NTPQ, but there are other ways to craft a
1029 reqlen = (size_t)(reqend - reqpt);
1031 char * nulpos = (char*)memchr(reqpt, 0, reqlen);
1033 reqlen = (size_t)(nulpos - reqpt);
1037 if (reqlen >= sizeof(filespec)) {
1038 ctl_printf("saveconfig exceeded maximum raw name length (%u)",
1039 (u_int)sizeof(filespec));
1042 "saveconfig exceeded maximum raw name length from %s",
1043 stoa(&rbufp->recv_srcadr));
1047 /* copy data directly as we exactly know the size */
1048 memcpy(filespec, reqpt, reqlen);
1049 filespec[reqlen] = '\0';
1052 * allow timestamping of the saved config filename with
1053 * strftime() format such as:
1054 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
1055 * XXX: Nice feature, but not too safe.
1056 * YYY: The check for permitted characters in file names should
1057 * weed out the worst. Let's hope 'strftime()' does not
1058 * develop pathological problems.
1061 if (0 == strftime(filename, sizeof(filename), filespec,
1065 * If we arrive here, 'strftime()' balked; most likely
1066 * the buffer was too short. (Or it encounterd an empty
1067 * format, or just a format that expands to an empty
1068 * string.) We try to use the original name, though this
1069 * is very likely to fail later if there are format
1070 * specs in the string. Note that truncation cannot
1071 * happen here as long as both buffers have the same
1074 strlcpy(filename, filespec, sizeof(filename));
1078 * Check the file name for sanity. This might/will rule out file
1079 * names that would be legal but problematic, and it blocks
1080 * directory traversal.
1082 if (!is_safe_filename(filename)) {
1083 ctl_printf("saveconfig rejects unsafe file name '%s'",
1087 "saveconfig rejects unsafe file name from %s",
1088 stoa(&rbufp->recv_srcadr));
1093 * XXX: This next test may not be needed with is_safe_filename()
1096 /* block directory/drive traversal */
1097 /* TALOS-CAN-0062: block directory traversal for VMS, too */
1098 if (NULL != strpbrk(filename, illegal_in_filename)) {
1099 snprintf(reply, sizeof(reply),
1100 "saveconfig does not allow directory in filename");
1101 ctl_putdata(reply, strlen(reply), 0);
1104 "saveconfig rejects unsafe file name from %s",
1105 stoa(&rbufp->recv_srcadr));
1109 /* concatenation of directory and path can cause another
1112 prc = snprintf(fullpath, sizeof(fullpath), "%s%s",
1113 saveconfigdir, filename);
1114 if (prc < 0 || prc >= sizeof(fullpath)) {
1115 ctl_printf("saveconfig exceeded maximum path length (%u)",
1116 (u_int)sizeof(fullpath));
1119 "saveconfig exceeded maximum path length from %s",
1120 stoa(&rbufp->recv_srcadr));
1124 fd = open(fullpath, openmode, S_IRUSR | S_IWUSR);
1128 fptr = fdopen(fd, "w");
1130 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
1131 ctl_printf("Unable to save configuration to file '%s': %m",
1134 "saveconfig %s from %s failed", filename,
1135 stoa(&rbufp->recv_srcadr));
1137 ctl_printf("Configuration saved to '%s'", filename);
1139 "Configuration saved to '%s' (requested by %s)",
1140 fullpath, stoa(&rbufp->recv_srcadr));
1142 * save the output filename in system variable
1143 * savedconfig, retrieved with:
1144 * ntpq -c "rv 0 savedconfig"
1145 * Note: the way 'savedconfig' is defined makes overflow
1146 * checks unnecessary here.
1148 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
1149 savedconfig_eq, filename);
1150 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1155 #else /* !SAVECONFIG follows */
1157 "saveconfig unavailable, configured with --disable-saveconfig");
1164 * process_control - process an incoming control message
1168 struct recvbuf *rbufp,
1172 struct ntp_control *pkt;
1175 const struct ctl_proc *cc;
1180 DPRINTF(3, ("in process_control()\n"));
1183 * Save the addresses for error responses
1186 rmt_addr = &rbufp->recv_srcadr;
1187 lcl_inter = rbufp->dstadr;
1188 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1191 * If the length is less than required for the header, or
1192 * it is a response or a fragment, ignore this.
1194 if (rbufp->recv_length < (int)CTL_HEADER_LEN
1195 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1196 || pkt->offset != 0) {
1197 DPRINTF(1, ("invalid format in control packet\n"));
1198 if (rbufp->recv_length < (int)CTL_HEADER_LEN)
1200 if (CTL_RESPONSE & pkt->r_m_e_op)
1202 if (CTL_MORE & pkt->r_m_e_op)
1204 if (CTL_ERROR & pkt->r_m_e_op)
1206 if (pkt->offset != 0)
1210 res_version = PKT_VERSION(pkt->li_vn_mode);
1211 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1212 DPRINTF(1, ("unknown version %d in control packet\n",
1219 * Pull enough data from the packet to make intelligent
1222 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1224 res_opcode = pkt->r_m_e_op;
1225 rpkt.sequence = pkt->sequence;
1226 rpkt.associd = pkt->associd;
1230 res_associd = htons(pkt->associd);
1232 res_authenticate = FALSE;
1234 res_authokay = FALSE;
1235 req_count = (int)ntohs(pkt->count);
1236 datanotbinflag = FALSE;
1239 datapt = rpkt.u.data;
1240 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1242 if ((rbufp->recv_length & 0x3) != 0)
1243 DPRINTF(3, ("Control packet length %d unrounded\n",
1244 rbufp->recv_length));
1247 * We're set up now. Make sure we've got at least enough
1248 * incoming data space to match the count.
1250 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1251 if (req_data < req_count || rbufp->recv_length & 0x3) {
1252 ctl_error(CERR_BADFMT);
1253 numctldatatooshort++;
1257 properlen = req_count + CTL_HEADER_LEN;
1258 /* round up proper len to a 8 octet boundary */
1260 properlen = (properlen + 7) & ~7;
1261 maclen = rbufp->recv_length - properlen;
1262 if ((rbufp->recv_length & 3) == 0 &&
1263 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1265 res_authenticate = TRUE;
1266 pkid = (void *)((char *)pkt + properlen);
1267 res_keyid = ntohl(*pkid);
1268 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1269 rbufp->recv_length, properlen, res_keyid,
1272 if (!authistrusted(res_keyid))
1273 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1274 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1275 rbufp->recv_length - maclen,
1277 res_authokay = TRUE;
1278 DPRINTF(3, ("authenticated okay\n"));
1281 DPRINTF(3, ("authentication failed\n"));
1286 * Set up translate pointers
1288 reqpt = (char *)pkt->u.data;
1289 reqend = reqpt + req_count;
1292 * Look for the opcode processor
1294 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1295 if (cc->control_code == res_opcode) {
1296 DPRINTF(3, ("opcode %d, found command handler\n",
1298 if (cc->flags == AUTH
1300 || res_keyid != ctl_auth_keyid)) {
1301 ctl_error(CERR_PERMISSION);
1304 (cc->handler)(rbufp, restrict_mask);
1310 * Can't find this one, return an error.
1313 ctl_error(CERR_BADOP);
1319 * ctlpeerstatus - return a status word for this peer
1323 register struct peer *p
1329 if (FLAG_CONFIG & p->flags)
1330 status |= CTL_PST_CONFIG;
1332 status |= CTL_PST_AUTHENABLE;
1333 if (FLAG_AUTHENTIC & p->flags)
1334 status |= CTL_PST_AUTHENTIC;
1336 status |= CTL_PST_REACH;
1337 if (MDF_TXONLY_MASK & p->cast_flags)
1338 status |= CTL_PST_BCAST;
1340 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1345 * ctlclkstatus - return a status word for this clock
1350 struct refclockstat *pcs
1353 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1359 * ctlsysstatus - return the system status word
1364 register u_char this_clock;
1366 this_clock = CTL_SST_TS_UNSPEC;
1368 if (sys_peer != NULL) {
1369 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1370 this_clock = sys_peer->sstclktype;
1371 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1372 this_clock = clocktypes[sys_peer->refclktype];
1374 #else /* REFCLOCK */
1376 this_clock = CTL_SST_TS_NTP;
1377 #endif /* REFCLOCK */
1378 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1379 ctl_sys_last_event);
1384 * ctl_flushpkt - write out the current packet and prepare
1385 * another if necessary.
1399 dlen = datapt - rpkt.u.data;
1400 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1402 * Big hack, output a trailing \r\n
1408 sendlen = dlen + CTL_HEADER_LEN;
1411 * Pad to a multiple of 32 bits
1413 while (sendlen & 0x3) {
1419 * Fill in the packet with the current info
1421 rpkt.r_m_e_op = CTL_RESPONSE | more |
1422 (res_opcode & CTL_OP_MASK);
1423 rpkt.count = htons((u_short)dlen);
1424 rpkt.offset = htons((u_short)res_offset);
1426 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1427 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1431 ctl_traps[i].tr_version,
1434 htons(ctl_traps[i].tr_sequence);
1435 sendpkt(&ctl_traps[i].tr_addr,
1436 ctl_traps[i].tr_localaddr, -4,
1437 (struct pkt *)&rpkt, sendlen);
1439 ctl_traps[i].tr_sequence++;
1444 if (res_authenticate && sys_authenticate) {
1447 * If we are going to authenticate, then there
1448 * is an additional requirement that the MAC
1449 * begin on a 64 bit boundary.
1451 while (totlen & 7) {
1455 keyid = htonl(res_keyid);
1456 memcpy(datapt, &keyid, sizeof(keyid));
1457 maclen = authencrypt(res_keyid,
1458 (u_int32 *)&rpkt, totlen);
1459 sendpkt(rmt_addr, lcl_inter, -5,
1460 (struct pkt *)&rpkt, totlen + maclen);
1462 sendpkt(rmt_addr, lcl_inter, -6,
1463 (struct pkt *)&rpkt, sendlen);
1472 * Set us up for another go around.
1476 datapt = rpkt.u.data;
1481 * ctl_putdata - write data into the packet, fragmenting and starting
1482 * another if this one is full.
1488 int bin /* set to 1 when data is binary */
1492 unsigned int currentlen;
1496 datanotbinflag = TRUE;
1501 if ((dlen + datalinelen + 1) >= MAXDATALINELEN) {
1513 * Save room for trailing junk
1515 while (dlen + overhead + datapt > dataend) {
1517 * Not enough room in this one, flush it out.
1519 currentlen = MIN(dlen, (unsigned int)(dataend - datapt));
1521 memcpy(datapt, dp, currentlen);
1523 datapt += currentlen;
1526 datalinelen += currentlen;
1528 ctl_flushpkt(CTL_MORE);
1531 memcpy(datapt, dp, dlen);
1533 datalinelen += dlen;
1539 * ctl_putstr - write a tagged string into the response packet
1544 * len is the data length excluding the NUL terminator,
1545 * as in ctl_putstr("var", "value", strlen("value"));
1559 memcpy(buffer, tag, tl);
1562 INSIST(tl + 3 + len <= sizeof(buffer));
1565 memcpy(cp, data, len);
1569 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1574 * ctl_putunqstr - write a tagged string into the response packet
1579 * len is the data length excluding the NUL terminator.
1580 * data must not contain a comma or whitespace.
1594 memcpy(buffer, tag, tl);
1597 INSIST(tl + 1 + len <= sizeof(buffer));
1599 memcpy(cp, data, len);
1602 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1607 * ctl_putdblf - write a tagged, signed double into the response packet
1626 INSIST((size_t)(cp - buffer) < sizeof(buffer));
1627 snprintf(cp, sizeof(buffer) - (cp - buffer), use_f ? "%.*f" : "%.*g",
1630 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1634 * ctl_putuint - write a tagged unsigned integer into the response
1643 register const char *cq;
1652 INSIST((cp - buffer) < (int)sizeof(buffer));
1653 snprintf(cp, sizeof(buffer) - (cp - buffer), "%lu", uval);
1655 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1659 * ctl_putcal - write a decoded calendar data into the response
1664 const struct calendar *pcal
1670 numch = snprintf(buffer, sizeof(buffer),
1671 "%s=%04d%02d%02d%02d%02d",
1679 INSIST(numch < sizeof(buffer));
1680 ctl_putdata(buffer, numch, 0);
1686 * ctl_putfs - write a decoded filestamp into the response
1695 register const char *cq;
1697 struct tm *tm = NULL;
1706 fstamp = uval - JAN_1970;
1707 tm = gmtime(&fstamp);
1710 INSIST((cp - buffer) < (int)sizeof(buffer));
1711 snprintf(cp, sizeof(buffer) - (cp - buffer),
1712 "%04d%02d%02d%02d%02d", tm->tm_year + 1900,
1713 tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);
1715 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1720 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1730 register const char *cq;
1739 INSIST((cp - buffer) < (int)sizeof(buffer));
1740 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%lx", uval);
1742 ctl_putdata(buffer,(unsigned)( cp - buffer ), 0);
1747 * ctl_putint - write a tagged signed integer into the response
1756 register const char *cq;
1765 INSIST((cp - buffer) < (int)sizeof(buffer));
1766 snprintf(cp, sizeof(buffer) - (cp - buffer), "%ld", ival);
1768 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1773 * ctl_putts - write a tagged timestamp, in hex, into the response
1782 register const char *cq;
1791 INSIST((size_t)(cp - buffer) < sizeof(buffer));
1792 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%08x.%08x",
1793 (u_int)ts->l_ui, (u_int)ts->l_uf);
1795 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1800 * ctl_putadr - write an IP address into the response
1810 register const char *cq;
1820 cq = numtoa(addr32);
1823 INSIST((cp - buffer) < (int)sizeof(buffer));
1824 snprintf(cp, sizeof(buffer) - (cp - buffer), "%s", cq);
1826 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1831 * ctl_putrefid - send a u_int32 refid as printable text
1847 oplim = output + sizeof(output);
1848 while (optr < oplim && '\0' != *tag)
1854 if (!(optr < oplim))
1856 iptr = (char *)&refid;
1857 iplim = iptr + sizeof(refid);
1858 for ( ; optr < oplim && iptr < iplim && '\0' != *iptr;
1860 if (isprint((int)*iptr))
1864 if (!(optr <= oplim))
1866 ctl_putdata(output, (u_int)(optr - output), FALSE);
1871 * ctl_putarray - write a tagged eight element double array into the response
1881 register const char *cq;
1894 INSIST((cp - buffer) < (int)sizeof(buffer));
1895 snprintf(cp, sizeof(buffer) - (cp - buffer),
1896 " %.2f", arr[i] * 1e3);
1898 } while (i != start);
1899 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1903 * ctl_printf - put a formatted string into the data buffer
1911 static const char * ellipsis = "[...]";
1917 rc = vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, va);
1919 if (rc < 0 || rc >= sizeof(fmtbuf))
1920 strcpy(fmtbuf + sizeof(fmtbuf) - strlen(ellipsis) - 1,
1922 ctl_putdata(fmtbuf, strlen(fmtbuf), 0);
1927 * ctl_putsys - output a system variable
1941 struct cert_info *cp;
1942 #endif /* AUTOKEY */
1944 static struct timex ntx;
1945 static u_long ntp_adjtime_time;
1947 static const double to_ms =
1949 1.0e-6; /* nsec to msec */
1951 1.0e-3; /* usec to msec */
1955 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1957 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1958 current_time != ntp_adjtime_time) {
1960 if (ntp_adjtime(&ntx) < 0)
1961 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1963 ntp_adjtime_time = current_time;
1965 #endif /* KERNEL_PLL */
1970 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1974 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1978 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1982 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1986 case CS_ROOTDISPERSION:
1987 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1988 sys_rootdisp * 1e3);
1992 if (sys_stratum > 1 && sys_stratum < STRATUM_UNSPEC)
1993 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1995 ctl_putrefid(sys_var[varid].text, sys_refid);
1999 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
2003 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
2007 if (sys_peer == NULL)
2008 ctl_putuint(sys_var[CS_PEERID].text, 0);
2010 ctl_putuint(sys_var[CS_PEERID].text,
2015 if (sys_peer != NULL && sys_peer->dstadr != NULL)
2016 ss = sptoa(&sys_peer->srcadr);
2019 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
2023 u = (sys_peer != NULL)
2026 ctl_putuint(sys_var[CS_PEERMODE].text, u);
2030 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
2034 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
2038 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
2042 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
2047 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
2052 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
2053 sizeof(str_processor) - 1);
2055 ctl_putstr(sys_var[CS_PROCESSOR].text,
2056 utsnamebuf.machine, strlen(utsnamebuf.machine));
2057 #endif /* HAVE_UNAME */
2062 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
2063 sizeof(str_system) - 1);
2065 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
2066 utsnamebuf.release);
2067 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
2068 #endif /* HAVE_UNAME */
2072 ctl_putstr(sys_var[CS_VERSION].text, Version,
2077 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
2083 char buf[CTL_MAX_DATA_LEN];
2084 //buffPointer, firstElementPointer, buffEndPointer
2085 char *buffp, *buffend;
2089 const struct ctl_var *k;
2092 buffend = buf + sizeof(buf);
2093 if (buffp + strlen(sys_var[CS_VARLIST].text) + 4 > buffend)
2094 break; /* really long var name */
2096 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
2097 buffp += strlen(buffp);
2098 firstVarName = TRUE;
2099 for (k = sys_var; !(k->flags & EOV); k++) {
2100 if (k->flags & PADDING)
2102 len = strlen(k->text);
2103 if (buffp + len + 1 >= buffend)
2108 firstVarName = FALSE;
2109 memcpy(buffp, k->text, len);
2113 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
2114 if (k->flags & PADDING)
2116 if (NULL == k->text)
2118 ss1 = strchr(k->text, '=');
2120 len = strlen(k->text);
2122 len = ss1 - k->text;
2123 if (buffp + len + 1 >= buffend)
2127 firstVarName = FALSE;
2129 memcpy(buffp, k->text,(unsigned)len);
2132 if (buffp + 2 >= buffend)
2138 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
2144 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
2149 leap_signature_t lsig;
2150 leapsec_getsig(&lsig);
2152 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
2158 leap_signature_t lsig;
2159 leapsec_getsig(&lsig);
2161 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2166 case CS_LEAPSMEARINTV:
2167 if (leap_smear_intv > 0)
2168 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2171 case CS_LEAPSMEAROFFS:
2172 if (leap_smear_intv > 0)
2173 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2174 leap_smear.doffset * 1e3);
2176 #endif /* LEAP_SMEAR */
2179 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2182 case CS_MRU_ENABLED:
2183 ctl_puthex(sys_var[varid].text, mon_enabled);
2187 ctl_putuint(sys_var[varid].text, mru_entries);
2191 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2195 ctl_putuint(sys_var[varid].text, u);
2198 case CS_MRU_DEEPEST:
2199 ctl_putuint(sys_var[varid].text, mru_peakentries);
2202 case CS_MRU_MINDEPTH:
2203 ctl_putuint(sys_var[varid].text, mru_mindepth);
2207 ctl_putint(sys_var[varid].text, mru_maxage);
2210 case CS_MRU_MAXDEPTH:
2211 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2215 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2219 ctl_putuint(sys_var[varid].text, u);
2223 ctl_putuint(sys_var[varid].text, current_time);
2227 ctl_putuint(sys_var[varid].text,
2228 current_time - sys_stattime);
2231 case CS_SS_RECEIVED:
2232 ctl_putuint(sys_var[varid].text, sys_received);
2236 ctl_putuint(sys_var[varid].text, sys_newversion);
2240 ctl_putuint(sys_var[varid].text, sys_oldversion);
2243 case CS_SS_BADFORMAT:
2244 ctl_putuint(sys_var[varid].text, sys_badlength);
2248 ctl_putuint(sys_var[varid].text, sys_badauth);
2251 case CS_SS_DECLINED:
2252 ctl_putuint(sys_var[varid].text, sys_declined);
2255 case CS_SS_RESTRICTED:
2256 ctl_putuint(sys_var[varid].text, sys_restricted);
2260 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2264 ctl_putuint(sys_var[varid].text, sys_kodsent);
2267 case CS_SS_PROCESSED:
2268 ctl_putuint(sys_var[varid].text, sys_processed);
2272 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2276 LFPTOD(&sys_authdelay, dtemp);
2277 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2281 ctl_putuint(sys_var[varid].text, authnumkeys);
2285 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2288 case CS_AUTHKLOOKUPS:
2289 ctl_putuint(sys_var[varid].text, authkeylookups);
2292 case CS_AUTHKNOTFOUND:
2293 ctl_putuint(sys_var[varid].text, authkeynotfound);
2296 case CS_AUTHKUNCACHED:
2297 ctl_putuint(sys_var[varid].text, authkeyuncached);
2300 case CS_AUTHKEXPIRED:
2301 ctl_putuint(sys_var[varid].text, authkeyexpired);
2304 case CS_AUTHENCRYPTS:
2305 ctl_putuint(sys_var[varid].text, authencryptions);
2308 case CS_AUTHDECRYPTS:
2309 ctl_putuint(sys_var[varid].text, authdecryptions);
2313 ctl_putuint(sys_var[varid].text,
2314 current_time - auth_timereset);
2318 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2319 * unavailable, otherwise calls putfunc with args.
2322 # define CTL_IF_KERNLOOP(putfunc, args) \
2323 ctl_putint(sys_var[varid].text, 0)
2325 # define CTL_IF_KERNLOOP(putfunc, args) \
2330 * CTL_IF_KERNPPS() puts a zero if either the kernel
2331 * loop is unavailable, or kernel hard PPS is not
2332 * active, otherwise calls putfunc with args.
2335 # define CTL_IF_KERNPPS(putfunc, args) \
2336 ctl_putint(sys_var[varid].text, 0)
2338 # define CTL_IF_KERNPPS(putfunc, args) \
2339 if (0 == ntx.shift) \
2340 ctl_putint(sys_var[varid].text, 0); \
2342 putfunc args /* no trailing ; */
2348 (sys_var[varid].text, 0, -1, to_ms * ntx.offset)
2355 (sys_var[varid].text, ntx.freq)
2362 (sys_var[varid].text, 0, 6,
2363 to_ms * ntx.maxerror)
2370 (sys_var[varid].text, 0, 6,
2371 to_ms * ntx.esterror)
2379 ss = k_st_flags(ntx.status);
2381 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2384 case CS_K_TIMECONST:
2387 (sys_var[varid].text, ntx.constant)
2391 case CS_K_PRECISION:
2394 (sys_var[varid].text, 0, 6,
2395 to_ms * ntx.precision)
2402 (sys_var[varid].text, ntx.tolerance)
2409 (sys_var[varid].text, ntx.ppsfreq)
2413 case CS_K_PPS_STABIL:
2416 (sys_var[varid].text, ntx.stabil)
2420 case CS_K_PPS_JITTER:
2423 (sys_var[varid].text, to_ms * ntx.jitter)
2427 case CS_K_PPS_CALIBDUR:
2430 (sys_var[varid].text, 1 << ntx.shift)
2434 case CS_K_PPS_CALIBS:
2437 (sys_var[varid].text, ntx.calcnt)
2441 case CS_K_PPS_CALIBERRS:
2444 (sys_var[varid].text, ntx.errcnt)
2448 case CS_K_PPS_JITEXC:
2451 (sys_var[varid].text, ntx.jitcnt)
2455 case CS_K_PPS_STBEXC:
2458 (sys_var[varid].text, ntx.stbcnt)
2462 case CS_IOSTATS_RESET:
2463 ctl_putuint(sys_var[varid].text,
2464 current_time - io_timereset);
2468 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2472 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2476 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2479 case CS_RBUF_LOWATER:
2480 ctl_putuint(sys_var[varid].text, lowater_additions());
2484 ctl_putuint(sys_var[varid].text, packets_dropped);
2488 ctl_putuint(sys_var[varid].text, packets_ignored);
2491 case CS_IO_RECEIVED:
2492 ctl_putuint(sys_var[varid].text, packets_received);
2496 ctl_putuint(sys_var[varid].text, packets_sent);
2499 case CS_IO_SENDFAILED:
2500 ctl_putuint(sys_var[varid].text, packets_notsent);
2504 ctl_putuint(sys_var[varid].text, handler_calls);
2507 case CS_IO_GOODWAKEUPS:
2508 ctl_putuint(sys_var[varid].text, handler_pkts);
2511 case CS_TIMERSTATS_RESET:
2512 ctl_putuint(sys_var[varid].text,
2513 current_time - timer_timereset);
2516 case CS_TIMER_OVERRUNS:
2517 ctl_putuint(sys_var[varid].text, alarm_overflow);
2521 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2525 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2527 case CS_WANDER_THRESH:
2528 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2533 ctl_puthex(sys_var[CS_FLAGS].text,
2539 strlcpy(str, OBJ_nid2ln(crypto_nid),
2541 ctl_putstr(sys_var[CS_DIGEST].text, str,
2550 dp = EVP_get_digestbynid(crypto_flags >> 16);
2551 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2553 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2559 if (hostval.ptr != NULL)
2560 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2561 strlen(hostval.ptr));
2565 if (sys_ident != NULL)
2566 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2571 for (cp = cinfo; cp != NULL; cp = cp->link) {
2572 snprintf(str, sizeof(str), "%s %s 0x%x",
2573 cp->subject, cp->issuer, cp->flags);
2574 ctl_putstr(sys_var[CS_CERTIF].text, str,
2576 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2581 if (hostval.tstamp != 0)
2582 ctl_putfs(sys_var[CS_PUBLIC].text,
2583 ntohl(hostval.tstamp));
2585 #endif /* AUTOKEY */
2594 * ctl_putpeer - output a peer variable
2602 char buf[CTL_MAX_DATA_LEN];
2607 const struct ctl_var *k;
2612 #endif /* AUTOKEY */
2617 ctl_putuint(peer_var[id].text,
2618 !(FLAG_PREEMPT & p->flags));
2622 ctl_putuint(peer_var[id].text, !(p->keyid));
2626 ctl_putuint(peer_var[id].text,
2627 !!(FLAG_AUTHENTIC & p->flags));
2631 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2635 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2639 if (p->hostname != NULL)
2640 ctl_putstr(peer_var[id].text, p->hostname,
2641 strlen(p->hostname));
2645 ctl_putadr(peer_var[id].text, 0,
2652 ctl_putuint(peer_var[id].text,
2654 ? SRCPORT(&p->dstadr->sin)
2660 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2665 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2669 ctl_putuint(peer_var[id].text, p->throttle);
2673 ctl_putuint(peer_var[id].text, p->leap);
2677 ctl_putuint(peer_var[id].text, p->hmode);
2681 ctl_putuint(peer_var[id].text, p->stratum);
2685 ctl_putuint(peer_var[id].text, p->ppoll);
2689 ctl_putuint(peer_var[id].text, p->hpoll);
2693 ctl_putint(peer_var[id].text, p->precision);
2697 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2700 case CP_ROOTDISPERSION:
2701 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2706 if (p->flags & FLAG_REFCLOCK) {
2707 ctl_putrefid(peer_var[id].text, p->refid);
2711 if (p->stratum > 1 && p->stratum < STRATUM_UNSPEC)
2712 ctl_putadr(peer_var[id].text, p->refid,
2715 ctl_putrefid(peer_var[id].text, p->refid);
2719 ctl_putts(peer_var[id].text, &p->reftime);
2723 ctl_putts(peer_var[id].text, &p->aorg);
2727 ctl_putts(peer_var[id].text, &p->dst);
2732 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2737 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2741 ctl_puthex(peer_var[id].text, p->reach);
2745 ctl_puthex(peer_var[id].text, p->flash);
2750 if (p->flags & FLAG_REFCLOCK) {
2751 ctl_putuint(peer_var[id].text, p->ttl);
2755 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2756 ctl_putint(peer_var[id].text,
2761 ctl_putuint(peer_var[id].text, p->unreach);
2765 ctl_putuint(peer_var[id].text,
2766 p->nextdate - current_time);
2770 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2774 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2778 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2782 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2786 if (p->keyid > NTP_MAXKEY)
2787 ctl_puthex(peer_var[id].text, p->keyid);
2789 ctl_putuint(peer_var[id].text, p->keyid);
2793 ctl_putarray(peer_var[id].text, p->filter_delay,
2798 ctl_putarray(peer_var[id].text, p->filter_offset,
2803 ctl_putarray(peer_var[id].text, p->filter_disp,
2808 ctl_putuint(peer_var[id].text, p->pmode);
2812 ctl_putuint(peer_var[id].text, p->received);
2816 ctl_putuint(peer_var[id].text, p->sent);
2821 be = buf + sizeof(buf);
2822 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2823 break; /* really long var name */
2825 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2828 for (k = peer_var; !(EOV & k->flags); k++) {
2829 if (PADDING & k->flags)
2831 i = strlen(k->text);
2832 if (s + i + 1 >= be)
2836 memcpy(s, k->text, i);
2842 ctl_putdata(buf, (u_int)(s - buf), 0);
2847 ctl_putuint(peer_var[id].text,
2848 current_time - p->timereceived);
2852 ctl_putuint(peer_var[id].text,
2853 current_time - p->timereachable);
2857 ctl_putuint(peer_var[id].text, p->badauth);
2861 ctl_putuint(peer_var[id].text, p->bogusorg);
2865 ctl_putuint(peer_var[id].text, p->oldpkt);
2869 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2873 ctl_putuint(peer_var[id].text, p->selbroken);
2877 ctl_putuint(peer_var[id].text, p->status);
2882 ctl_puthex(peer_var[id].text, p->crypto);
2887 dp = EVP_get_digestbynid(p->crypto >> 16);
2888 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2889 ctl_putstr(peer_var[id].text, str, strlen(str));
2894 if (p->subject != NULL)
2895 ctl_putstr(peer_var[id].text, p->subject,
2896 strlen(p->subject));
2899 case CP_VALID: /* not used */
2903 if (NULL == (ap = p->recval.ptr))
2906 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2907 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2908 ctl_putfs(peer_var[CP_INITTSP].text,
2909 ntohl(p->recval.tstamp));
2913 if (p->ident != NULL)
2914 ctl_putstr(peer_var[id].text, p->ident,
2919 #endif /* AUTOKEY */
2926 * ctl_putclock - output clock variables
2931 struct refclockstat *pcs,
2935 char buf[CTL_MAX_DATA_LEN];
2939 const struct ctl_var *k;
2944 if (mustput || pcs->clockdesc == NULL
2945 || *(pcs->clockdesc) == '\0') {
2946 ctl_putuint(clock_var[id].text, pcs->type);
2950 ctl_putstr(clock_var[id].text,
2952 (unsigned)pcs->lencode);
2956 ctl_putuint(clock_var[id].text, pcs->polls);
2960 ctl_putuint(clock_var[id].text,
2965 ctl_putuint(clock_var[id].text,
2970 ctl_putuint(clock_var[id].text,
2975 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2976 ctl_putdbl(clock_var[id].text,
2977 pcs->fudgetime1 * 1e3);
2981 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2982 ctl_putdbl(clock_var[id].text,
2983 pcs->fudgetime2 * 1e3);
2987 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2988 ctl_putint(clock_var[id].text,
2993 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2994 if (pcs->fudgeval1 > 1)
2995 ctl_putadr(clock_var[id].text,
2996 pcs->fudgeval2, NULL);
2998 ctl_putrefid(clock_var[id].text,
3004 ctl_putuint(clock_var[id].text, pcs->flags);
3008 if (pcs->clockdesc == NULL ||
3009 *(pcs->clockdesc) == '\0') {
3011 ctl_putstr(clock_var[id].text,
3014 ctl_putstr(clock_var[id].text,
3016 strlen(pcs->clockdesc));
3022 be = buf + sizeof(buf);
3023 if (strlen(clock_var[CC_VARLIST].text) + 4 >
3025 break; /* really long var name */
3027 snprintf(s, sizeof(buf), "%s=\"",
3028 clock_var[CC_VARLIST].text);
3032 for (k = clock_var; !(EOV & k->flags); k++) {
3033 if (PADDING & k->flags)
3036 i = strlen(k->text);
3037 if (s + i + 1 >= be)
3042 memcpy(s, k->text, i);
3046 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
3047 if (PADDING & k->flags)
3054 while (*ss && *ss != '=')
3057 if (s + i + 1 >= be)
3062 memcpy(s, k->text, (unsigned)i);
3071 ctl_putdata(buf, (unsigned)(s - buf), 0);
3080 * ctl_getitem - get the next data item from the incoming packet
3082 static const struct ctl_var *
3084 const struct ctl_var *var_list,
3088 static const struct ctl_var eol = { 0, EOV, NULL };
3089 static char buf[128];
3090 static u_long quiet_until;
3091 const struct ctl_var *v;
3097 * Delete leading commas and white space
3099 while (reqpt < reqend && (*reqpt == ',' ||
3100 isspace((unsigned char)*reqpt)))
3102 if (reqpt >= reqend)
3105 if (NULL == var_list)
3109 * Look for a first character match on the tag. If we find
3110 * one, see if it is a full match.
3113 for (v = var_list; !(EOV & v->flags); v++) {
3114 if (!(PADDING & v->flags) && *cp == *(v->text)) {
3116 while ('\0' != *pch && '=' != *pch && cp < reqend
3121 if ('\0' == *pch || '=' == *pch) {
3122 while (cp < reqend && isspace((u_char)*cp))
3124 if (cp == reqend || ',' == *cp) {
3135 while (cp < reqend && isspace((u_char)*cp))
3137 while (cp < reqend && *cp != ',') {
3139 if ((size_t)(tp - buf) >= sizeof(buf)) {
3140 ctl_error(CERR_BADFMT);
3143 if (quiet_until <= current_time) {
3144 quiet_until = current_time + 300;
3145 msyslog(LOG_WARNING,
3146 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)", stoa(rmt_addr), SRCPORT(rmt_addr));
3154 while (tp >= buf && isspace((u_char)*tp))
3169 * control_unspec - response to an unspecified op-code
3174 struct recvbuf *rbufp,
3181 * What is an appropriate response to an unspecified op-code?
3182 * I return no errors and no data, unless a specified assocation
3186 peer = findpeerbyassoc(res_associd);
3188 ctl_error(CERR_BADASSOC);
3191 rpkt.status = htons(ctlpeerstatus(peer));
3193 rpkt.status = htons(ctlsysstatus());
3199 * read_status - return either a list of associd's, or a particular
3205 struct recvbuf *rbufp,
3212 /* a_st holds association ID, status pairs alternating */
3213 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3217 printf("read_status: ID %d\n", res_associd);
3220 * Two choices here. If the specified association ID is
3221 * zero we return all known assocation ID's. Otherwise
3222 * we return a bunch of stuff about the particular peer.
3225 peer = findpeerbyassoc(res_associd);
3227 ctl_error(CERR_BADASSOC);
3230 rpkt.status = htons(ctlpeerstatus(peer));
3232 peer->num_events = 0;
3234 * For now, output everything we know about the
3235 * peer. May be more selective later.
3237 for (cp = def_peer_var; *cp != 0; cp++)
3238 ctl_putpeer((int)*cp, peer);
3243 rpkt.status = htons(ctlsysstatus());
3244 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3245 a_st[n++] = htons(peer->associd);
3246 a_st[n++] = htons(ctlpeerstatus(peer));
3247 /* two entries each loop iteration, so n + 1 */
3248 if (n + 1 >= COUNTOF(a_st)) {
3249 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3255 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3261 * read_peervars - half of read_variables() implementation
3266 const struct ctl_var *v;
3271 u_char wants[CP_MAXCODE + 1];
3275 * Wants info for a particular peer. See if we know
3278 peer = findpeerbyassoc(res_associd);
3280 ctl_error(CERR_BADASSOC);
3283 rpkt.status = htons(ctlpeerstatus(peer));
3285 peer->num_events = 0;
3288 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3289 if (v->flags & EOV) {
3290 ctl_error(CERR_UNKNOWNVAR);
3293 INSIST(v->code < COUNTOF(wants));
3298 for (i = 1; i < COUNTOF(wants); i++)
3300 ctl_putpeer(i, peer);
3302 for (cp = def_peer_var; *cp != 0; cp++)
3303 ctl_putpeer((int)*cp, peer);
3309 * read_sysvars - half of read_variables() implementation
3314 const struct ctl_var *v;
3325 * Wants system variables. Figure out which he wants
3326 * and give them to him.
3328 rpkt.status = htons(ctlsysstatus());
3330 ctl_sys_num_events = 0;
3331 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3332 wants = emalloc_zero(wants_count);
3334 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3335 if (!(EOV & v->flags)) {
3336 INSIST(v->code < wants_count);
3340 v = ctl_getitem(ext_sys_var, &valuep);
3342 if (EOV & v->flags) {
3343 ctl_error(CERR_UNKNOWNVAR);
3347 n = v->code + CS_MAXCODE + 1;
3348 INSIST(n < wants_count);
3354 for (n = 1; n <= CS_MAXCODE; n++)
3357 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3358 if (wants[n + CS_MAXCODE + 1]) {
3359 pch = ext_sys_var[n].text;
3360 ctl_putdata(pch, strlen(pch), 0);
3363 for (cs = def_sys_var; *cs != 0; cs++)
3364 ctl_putsys((int)*cs);
3365 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3366 if (DEF & kv->flags)
3367 ctl_putdata(kv->text, strlen(kv->text),
3376 * read_variables - return the variables the caller asks for
3381 struct recvbuf *rbufp,
3393 * write_variables - write into variables. We only allow leap bit
3399 struct recvbuf *rbufp,
3403 const struct ctl_var *v;
3414 * If he's trying to write into a peer tell him no way
3416 if (res_associd != 0) {
3417 ctl_error(CERR_PERMISSION);
3424 rpkt.status = htons(ctlsysstatus());
3427 * Look through the variables. Dump out at the first sign of
3430 while ((v = ctl_getitem(sys_var, &valuep)) != 0) {
3432 if (v->flags & EOV) {
3433 if ((v = ctl_getitem(ext_sys_var, &valuep)) !=
3435 if (v->flags & EOV) {
3436 ctl_error(CERR_UNKNOWNVAR);
3444 if (!(v->flags & CAN_WRITE)) {
3445 ctl_error(CERR_PERMISSION);
3448 if (!ext_var && (*valuep == '\0' || !atoint(valuep,
3450 ctl_error(CERR_BADFMT);
3453 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) {
3454 ctl_error(CERR_BADVALUE);
3459 octets = strlen(v->text) + strlen(valuep) + 2;
3460 vareqv = emalloc(octets);
3463 while (*t && *t != '=')
3466 memcpy(tt, valuep, 1 + strlen(valuep));
3467 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3470 ctl_error(CERR_UNSPEC); /* really */
3476 * If we got anything, do it. xxx nothing to do ***
3479 if (leapind != ~0 || leapwarn != ~0) {
3480 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3481 ctl_error(CERR_PERMISSION);
3491 * configure() processes ntpq :config/config-from-file, allowing
3492 * generic runtime reconfiguration.
3494 static void configure(
3495 struct recvbuf *rbufp,
3502 /* I haven't yet implemented changes to an existing association.
3503 * Hence check if the association id is 0
3505 if (res_associd != 0) {
3506 ctl_error(CERR_BADVALUE);
3510 if (RES_NOMODIFY & restrict_mask) {
3511 snprintf(remote_config.err_msg,
3512 sizeof(remote_config.err_msg),
3513 "runtime configuration prohibited by restrict ... nomodify");
3514 ctl_putdata(remote_config.err_msg,
3515 strlen(remote_config.err_msg), 0);
3519 "runtime config from %s rejected due to nomodify restriction",
3520 stoa(&rbufp->recv_srcadr));
3525 /* Initialize the remote config buffer */
3526 data_count = remoteconfig_cmdlength(reqpt, reqend);
3528 if (data_count > sizeof(remote_config.buffer) - 2) {
3529 snprintf(remote_config.err_msg,
3530 sizeof(remote_config.err_msg),
3531 "runtime configuration failed: request too long");
3532 ctl_putdata(remote_config.err_msg,
3533 strlen(remote_config.err_msg), 0);
3536 "runtime config from %s rejected: request too long",
3537 stoa(&rbufp->recv_srcadr));
3540 /* Bug 2853 -- check if all characters were acceptable */
3541 if (data_count != (size_t)(reqend - reqpt)) {
3542 snprintf(remote_config.err_msg,
3543 sizeof(remote_config.err_msg),
3544 "runtime configuration failed: request contains an unprintable character");
3545 ctl_putdata(remote_config.err_msg,
3546 strlen(remote_config.err_msg), 0);
3549 "runtime config from %s rejected: request contains an unprintable character: %0x",
3550 stoa(&rbufp->recv_srcadr),
3555 memcpy(remote_config.buffer, reqpt, data_count);
3556 /* The buffer has no trailing linefeed or NUL right now. For
3557 * logging, we do not want a newline, so we do that first after
3558 * adding the necessary NUL byte.
3560 remote_config.buffer[data_count] = '\0';
3561 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3562 remote_config.buffer));
3563 msyslog(LOG_NOTICE, "%s config: %s",
3564 stoa(&rbufp->recv_srcadr),
3565 remote_config.buffer);
3567 /* Now we have to make sure there is a NL/NUL sequence at the
3568 * end of the buffer before we parse it.
3570 remote_config.buffer[data_count++] = '\n';
3571 remote_config.buffer[data_count] = '\0';
3572 remote_config.pos = 0;
3573 remote_config.err_pos = 0;
3574 remote_config.no_errors = 0;
3575 config_remotely(&rbufp->recv_srcadr);
3578 * Check if errors were reported. If not, output 'Config
3579 * Succeeded'. Else output the error count. It would be nice
3580 * to output any parser error messages.
3582 if (0 == remote_config.no_errors) {
3583 retval = snprintf(remote_config.err_msg,
3584 sizeof(remote_config.err_msg),
3585 "Config Succeeded");
3587 remote_config.err_pos += retval;
3590 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3593 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3595 if (remote_config.no_errors > 0)
3596 msyslog(LOG_NOTICE, "%d error in %s config",
3597 remote_config.no_errors,
3598 stoa(&rbufp->recv_srcadr));
3603 * derive_nonce - generate client-address-specific nonce value
3604 * associated with a given timestamp.
3606 static u_int32 derive_nonce(
3612 static u_int32 salt[4];
3613 static u_long last_salt_update;
3615 u_char digest[EVP_MAX_MD_SIZE];
3621 while (!salt[0] || current_time - last_salt_update >= 3600) {
3622 salt[0] = ntp_random();
3623 salt[1] = ntp_random();
3624 salt[2] = ntp_random();
3625 salt[3] = ntp_random();
3626 last_salt_update = current_time;
3629 EVP_DigestInit(&ctx, EVP_get_digestbynid(NID_md5));
3630 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3631 EVP_DigestUpdate(&ctx, &ts_i, sizeof(ts_i));
3632 EVP_DigestUpdate(&ctx, &ts_f, sizeof(ts_f));
3634 EVP_DigestUpdate(&ctx, &SOCK_ADDR4(addr),
3635 sizeof(SOCK_ADDR4(addr)));
3637 EVP_DigestUpdate(&ctx, &SOCK_ADDR6(addr),
3638 sizeof(SOCK_ADDR6(addr)));
3639 EVP_DigestUpdate(&ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3640 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3641 EVP_DigestFinal(&ctx, d.digest, &len);
3648 * generate_nonce - generate client-address-specific nonce string.
3650 static void generate_nonce(
3651 struct recvbuf * rbufp,
3658 derived = derive_nonce(&rbufp->recv_srcadr,
3659 rbufp->recv_time.l_ui,
3660 rbufp->recv_time.l_uf);
3661 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3662 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3667 * validate_nonce - validate client-address-specific nonce string.
3669 * Returns TRUE if the local calculation of the nonce matches the
3670 * client-provided value and the timestamp is recent enough.
3672 static int validate_nonce(
3673 const char * pnonce,
3674 struct recvbuf * rbufp
3684 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3687 ts.l_ui = (u_int32)ts_i;
3688 ts.l_uf = (u_int32)ts_f;
3689 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3690 get_systime(&now_delta);
3691 L_SUB(&now_delta, &ts);
3693 return (supposed == derived && now_delta.l_ui < 16);
3698 * send_random_tag_value - send a randomly-generated three character
3699 * tag prefix, a '.', an index, a '=' and a
3700 * random integer value.
3702 * To try to force clients to ignore unrecognized tags in mrulist,
3703 * reslist, and ifstats responses, the first and last rows are spiced
3704 * with randomly-generated tag names with correct .# index. Make it
3705 * three characters knowing that none of the currently-used subscripted
3706 * tags have that length, avoiding the need to test for
3710 send_random_tag_value(
3717 noise = rand() ^ (rand() << 16);
3718 buf[0] = 'a' + noise % 26;
3720 buf[1] = 'a' + noise % 26;
3722 buf[2] = 'a' + noise % 26;
3725 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3726 ctl_putuint(buf, noise);
3731 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3733 * To keep clients honest about not depending on the order of values,
3734 * and thereby avoid being locked into ugly workarounds to maintain
3735 * backward compatibility later as new fields are added to the response,
3736 * the order is random.
3744 const char first_fmt[] = "first.%d";
3745 const char ct_fmt[] = "ct.%d";
3746 const char mv_fmt[] = "mv.%d";
3747 const char rs_fmt[] = "rs.%d";
3749 u_char sent[6]; /* 6 tag=value pairs */
3755 remaining = COUNTOF(sent);
3757 noise = (u_int32)(rand() ^ (rand() << 16));
3758 while (remaining > 0) {
3759 which = (noise & 7) % COUNTOF(sent);
3762 which = (which + 1) % COUNTOF(sent);
3767 snprintf(tag, sizeof(tag), addr_fmt, count);
3768 pch = sptoa(&mon->rmtadr);
3769 ctl_putunqstr(tag, pch, strlen(pch));
3773 snprintf(tag, sizeof(tag), last_fmt, count);
3774 ctl_putts(tag, &mon->last);
3778 snprintf(tag, sizeof(tag), first_fmt, count);
3779 ctl_putts(tag, &mon->first);
3783 snprintf(tag, sizeof(tag), ct_fmt, count);
3784 ctl_putint(tag, mon->count);
3788 snprintf(tag, sizeof(tag), mv_fmt, count);
3789 ctl_putuint(tag, mon->vn_mode);
3793 snprintf(tag, sizeof(tag), rs_fmt, count);
3794 ctl_puthex(tag, mon->flags);
3804 * read_mru_list - supports ntpq's mrulist command.
3806 * The challenge here is to match ntpdc's monlist functionality without
3807 * being limited to hundreds of entries returned total, and without
3808 * requiring state on the server. If state were required, ntpq's
3809 * mrulist command would require authentication.
3811 * The approach was suggested by Ry Jones. A finite and variable number
3812 * of entries are retrieved per request, to avoid having responses with
3813 * such large numbers of packets that socket buffers are overflowed and
3814 * packets lost. The entries are retrieved oldest-first, taking into
3815 * account that the MRU list will be changing between each request. We
3816 * can expect to see duplicate entries for addresses updated in the MRU
3817 * list during the fetch operation. In the end, the client can assemble
3818 * a close approximation of the MRU list at the point in time the last
3819 * response was sent by ntpd. The only difference is it may be longer,
3820 * containing some number of oldest entries which have since been
3821 * reclaimed. If necessary, the protocol could be extended to zap those
3822 * from the client snapshot at the end, but so far that doesn't seem
3825 * To accomodate the changing MRU list, the starting point for requests
3826 * after the first request is supplied as a series of last seen
3827 * timestamps and associated addresses, the newest ones the client has
3828 * received. As long as at least one of those entries hasn't been
3829 * bumped to the head of the MRU list, ntpd can pick up at that point.
3830 * Otherwise, the request is failed and it is up to ntpq to back up and
3831 * provide the next newest entry's timestamps and addresses, conceivably
3832 * backing up all the way to the starting point.
3835 * nonce= Regurgitated nonce retrieved by the client
3836 * previously using CTL_OP_REQ_NONCE, demonstrating
3837 * ability to receive traffic sent to its address.
3838 * frags= Limit on datagrams (fragments) in response. Used
3839 * by newer ntpq versions instead of limit= when
3840 * retrieving multiple entries.
3841 * limit= Limit on MRU entries returned. One of frags= or
3842 * limit= must be provided.
3843 * limit=1 is a special case: Instead of fetching
3844 * beginning with the supplied starting point's
3845 * newer neighbor, fetch the supplied entry, and
3846 * in that case the #.last timestamp can be zero.
3847 * This enables fetching a single entry by IP
3848 * address. When limit is not one and frags= is
3849 * provided, the fragment limit controls.
3850 * mincount= (decimal) Return entries with count >= mincount.
3851 * laddr= Return entries associated with the server's IP
3852 * address given. No port specification is needed,
3853 * and any supplied is ignored.
3854 * resall= 0x-prefixed hex restrict bits which must all be
3855 * lit for an MRU entry to be included.
3856 * Has precedence over any resany=.
3857 * resany= 0x-prefixed hex restrict bits, at least one of
3858 * which must be list for an MRU entry to be
3860 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3861 * which client previously received.
3862 * addr.0= text of newest entry's IP address and port,
3863 * IPv6 addresses in bracketed form: [::]:123
3864 * last.1= timestamp of 2nd newest entry client has.
3865 * addr.1= address of 2nd newest entry.
3868 * ntpq provides as many last/addr pairs as will fit in a single request
3869 * packet, except for the first request in a MRU fetch operation.
3871 * The response begins with a new nonce value to be used for any
3872 * followup request. Following the nonce is the next newer entry than
3873 * referred to by last.0 and addr.0, if the "0" entry has not been
3874 * bumped to the front. If it has, the first entry returned will be the
3875 * next entry newer than referred to by last.1 and addr.1, and so on.
3876 * If none of the referenced entries remain unchanged, the request fails
3877 * and ntpq backs up to the next earlier set of entries to resync.
3879 * Except for the first response, the response begins with confirmation
3880 * of the entry that precedes the first additional entry provided:
3882 * last.older= hex l_fp timestamp matching one of the input
3883 * .last timestamps, which entry now precedes the
3884 * response 0. entry in the MRU list.
3885 * addr.older= text of address corresponding to older.last.
3887 * And in any case, a successful response contains sets of values
3888 * comprising entries, with the oldest numbered 0 and incrementing from
3891 * addr.# text of IPv4 or IPv6 address and port
3892 * last.# hex l_fp timestamp of last receipt
3893 * first.# hex l_fp timestamp of first receipt
3894 * ct.# count of packets received
3895 * mv.# mode and version
3896 * rs.# restriction mask (RES_* bits)
3898 * Note the code currently assumes there are no valid three letter
3899 * tags sent with each row, and needs to be adjusted if that changes.
3901 * The client should accept the values in any order, and ignore .#
3902 * values which it does not understand, to allow a smooth path to
3903 * future changes without requiring a new opcode. Clients can rely
3904 * on all *.0 values preceding any *.1 values, that is all values for
3905 * a given index number are together in the response.
3907 * The end of the response list is noted with one or two tag=value
3908 * pairs. Unconditionally:
3910 * now= 0x-prefixed l_fp timestamp at the server marking
3911 * the end of the operation.
3913 * If any entries were returned, now= is followed by:
3915 * last.newest= hex l_fp identical to last.# of the prior
3918 static void read_mru_list(
3919 struct recvbuf *rbufp,
3923 const char nonce_text[] = "nonce";
3924 const char frags_text[] = "frags";
3925 const char limit_text[] = "limit";
3926 const char mincount_text[] = "mincount";
3927 const char resall_text[] = "resall";
3928 const char resany_text[] = "resany";
3929 const char maxlstint_text[] = "maxlstint";
3930 const char laddr_text[] = "laddr";
3931 const char resaxx_fmt[] = "0x%hx";
3939 struct interface * lcladr;
3944 sockaddr_u addr[COUNTOF(last)];
3946 struct ctl_var * in_parms;
3947 const struct ctl_var * v;
3956 mon_entry * prior_mon;
3959 if (RES_NOMRULIST & restrict_mask) {
3960 ctl_error(CERR_PERMISSION);
3963 "mrulist from %s rejected due to nomrulist restriction",
3964 stoa(&rbufp->recv_srcadr));
3969 * fill in_parms var list with all possible input parameters.
3972 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
3973 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
3974 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
3975 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
3976 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
3977 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
3978 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
3979 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
3980 for (i = 0; i < COUNTOF(last); i++) {
3981 snprintf(buf, sizeof(buf), last_fmt, (int)i);
3982 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3983 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
3984 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3987 /* decode input parms */
4000 while (NULL != (v = ctl_getitem(in_parms, &val)) &&
4001 !(EOV & v->flags)) {
4004 if (!strcmp(nonce_text, v->text)) {
4007 pnonce = estrdup(val);
4008 } else if (!strcmp(frags_text, v->text)) {
4009 sscanf(val, "%hu", &frags);
4010 } else if (!strcmp(limit_text, v->text)) {
4011 sscanf(val, "%u", &limit);
4012 } else if (!strcmp(mincount_text, v->text)) {
4013 if (1 != sscanf(val, "%d", &mincount) ||
4016 } else if (!strcmp(resall_text, v->text)) {
4017 sscanf(val, resaxx_fmt, &resall);
4018 } else if (!strcmp(resany_text, v->text)) {
4019 sscanf(val, resaxx_fmt, &resany);
4020 } else if (!strcmp(maxlstint_text, v->text)) {
4021 sscanf(val, "%u", &maxlstint);
4022 } else if (!strcmp(laddr_text, v->text)) {
4023 if (decodenetnum(val, &laddr))
4024 lcladr = getinterface(&laddr, 0);
4025 } else if (1 == sscanf(v->text, last_fmt, &si) &&
4026 (size_t)si < COUNTOF(last)) {
4027 if (2 == sscanf(val, "0x%08x.%08x", &ui, &uf)) {
4030 if (!SOCK_UNSPEC(&addr[si]) &&
4034 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
4035 (size_t)si < COUNTOF(addr)) {
4036 if (decodenetnum(val, &addr[si])
4037 && last[si].l_ui && last[si].l_uf &&
4042 free_varlist(in_parms);
4045 /* return no responses until the nonce is validated */
4049 nonce_valid = validate_nonce(pnonce, rbufp);
4054 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
4055 frags > MRU_FRAGS_LIMIT) {
4056 ctl_error(CERR_BADVALUE);
4061 * If either frags or limit is not given, use the max.
4063 if (0 != frags && 0 == limit)
4065 else if (0 != limit && 0 == frags)
4066 frags = MRU_FRAGS_LIMIT;
4069 * Find the starting point if one was provided.
4072 for (i = 0; i < (size_t)priors; i++) {
4073 hash = MON_HASH(&addr[i]);
4074 for (mon = mon_hash[hash];
4076 mon = mon->hash_next)
4077 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
4080 if (L_ISEQU(&mon->last, &last[i]))
4086 /* If a starting point was provided... */
4088 /* and none could be found unmodified... */
4090 /* tell ntpq to try again with older entries */
4091 ctl_error(CERR_UNKNOWNVAR);
4094 /* confirm the prior entry used as starting point */
4095 ctl_putts("last.older", &mon->last);
4096 pch = sptoa(&mon->rmtadr);
4097 ctl_putunqstr("addr.older", pch, strlen(pch));
4100 * Move on to the first entry the client doesn't have,
4101 * except in the special case of a limit of one. In
4102 * that case return the starting point entry.
4105 mon = PREV_DLIST(mon_mru_list, mon, mru);
4106 } else { /* start with the oldest */
4107 mon = TAIL_DLIST(mon_mru_list, mru);
4111 * send up to limit= entries in up to frags= datagrams
4114 generate_nonce(rbufp, buf, sizeof(buf));
4115 ctl_putunqstr("nonce", buf, strlen(buf));
4118 mon != NULL && res_frags < frags && count < limit;
4119 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
4121 if (mon->count < mincount)
4123 if (resall && resall != (resall & mon->flags))
4125 if (resany && !(resany & mon->flags))
4127 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
4130 if (lcladr != NULL && mon->lcladr != lcladr)
4133 send_mru_entry(mon, count);
4135 send_random_tag_value(0);
4141 * If this batch completes the MRU list, say so explicitly with
4142 * a now= l_fp timestamp.
4146 send_random_tag_value(count - 1);
4147 ctl_putts("now", &now);
4148 /* if any entries were returned confirm the last */
4149 if (prior_mon != NULL)
4150 ctl_putts("last.newest", &prior_mon->last);
4157 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
4159 * To keep clients honest about not depending on the order of values,
4160 * and thereby avoid being locked into ugly workarounds to maintain
4161 * backward compatibility later as new fields are added to the response,
4162 * the order is random.
4170 const char addr_fmtu[] = "addr.%u";
4171 const char bcast_fmt[] = "bcast.%u";
4172 const char en_fmt[] = "en.%u"; /* enabled */
4173 const char name_fmt[] = "name.%u";
4174 const char flags_fmt[] = "flags.%u";
4175 const char tl_fmt[] = "tl.%u"; /* ttl */
4176 const char mc_fmt[] = "mc.%u"; /* mcast count */
4177 const char rx_fmt[] = "rx.%u";
4178 const char tx_fmt[] = "tx.%u";
4179 const char txerr_fmt[] = "txerr.%u";
4180 const char pc_fmt[] = "pc.%u"; /* peer count */
4181 const char up_fmt[] = "up.%u"; /* uptime */
4183 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4190 remaining = COUNTOF(sent);
4194 while (remaining > 0) {
4195 if (noisebits < 4) {
4196 noise = rand() ^ (rand() << 16);
4199 which = (noise & 0xf) % COUNTOF(sent);
4204 which = (which + 1) % COUNTOF(sent);
4209 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4210 pch = sptoa(&la->sin);
4211 ctl_putunqstr(tag, pch, strlen(pch));
4215 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4216 if (INT_BCASTOPEN & la->flags)
4217 pch = sptoa(&la->bcast);
4220 ctl_putunqstr(tag, pch, strlen(pch));
4224 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4225 ctl_putint(tag, !la->ignore_packets);
4229 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4230 ctl_putstr(tag, la->name, strlen(la->name));
4234 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4235 ctl_puthex(tag, (u_int)la->flags);
4239 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4240 ctl_putint(tag, la->last_ttl);
4244 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4245 ctl_putint(tag, la->num_mcast);
4249 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4250 ctl_putint(tag, la->received);
4254 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4255 ctl_putint(tag, la->sent);
4259 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4260 ctl_putint(tag, la->notsent);
4264 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4265 ctl_putuint(tag, la->peercnt);
4269 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4270 ctl_putuint(tag, current_time - la->starttime);
4276 send_random_tag_value((int)ifnum);
4281 * read_ifstats - send statistics for each local address, exposed by
4286 struct recvbuf * rbufp
4293 * loop over [0..sys_ifnum] searching ep_list for each
4296 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4297 for (la = ep_list; la != NULL; la = la->elink)
4298 if (ifidx == la->ifnum)
4302 /* return stats for one local address */
4303 send_ifstats_entry(la, ifidx);
4309 sockaddrs_from_restrict_u(
4319 psaA->sa.sa_family = AF_INET;
4320 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4321 psaM->sa.sa_family = AF_INET;
4322 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4324 psaA->sa.sa_family = AF_INET6;
4325 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4326 sizeof(psaA->sa6.sin6_addr));
4327 psaM->sa.sa_family = AF_INET6;
4328 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4329 sizeof(psaA->sa6.sin6_addr));
4335 * Send a restrict entry in response to a "ntpq -c reslist" request.
4337 * To keep clients honest about not depending on the order of values,
4338 * and thereby avoid being locked into ugly workarounds to maintain
4339 * backward compatibility later as new fields are added to the response,
4340 * the order is random.
4343 send_restrict_entry(
4349 const char addr_fmtu[] = "addr.%u";
4350 const char mask_fmtu[] = "mask.%u";
4351 const char hits_fmt[] = "hits.%u";
4352 const char flags_fmt[] = "flags.%u";
4354 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4363 const char * match_str;
4364 const char * access_str;
4366 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4367 remaining = COUNTOF(sent);
4371 while (remaining > 0) {
4372 if (noisebits < 2) {
4373 noise = rand() ^ (rand() << 16);
4376 which = (noise & 0x3) % COUNTOF(sent);
4381 which = (which + 1) % COUNTOF(sent);
4386 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4388 ctl_putunqstr(tag, pch, strlen(pch));
4392 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4394 ctl_putunqstr(tag, pch, strlen(pch));
4398 snprintf(tag, sizeof(tag), hits_fmt, idx);
4399 ctl_putuint(tag, pres->count);
4403 snprintf(tag, sizeof(tag), flags_fmt, idx);
4404 match_str = res_match_flags(pres->mflags);
4405 access_str = res_access_flags(pres->flags);
4406 if ('\0' == match_str[0]) {
4410 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4411 match_str, access_str);
4414 ctl_putunqstr(tag, pch, strlen(pch));
4420 send_random_tag_value((int)idx);
4431 for ( ; pres != NULL; pres = pres->link) {
4432 send_restrict_entry(pres, ipv6, *pidx);
4439 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4442 read_addr_restrictions(
4443 struct recvbuf * rbufp
4449 send_restrict_list(restrictlist4, FALSE, &idx);
4450 send_restrict_list(restrictlist6, TRUE, &idx);
4456 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4460 struct recvbuf * rbufp,
4464 const char ifstats_s[] = "ifstats";
4465 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4466 const char addr_rst_s[] = "addr_restrictions";
4467 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4468 struct ntp_control * cpkt;
4469 u_short qdata_octets;
4472 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4473 * used only for ntpq -c ifstats. With the addition of reslist
4474 * the same opcode was generalized to retrieve ordered lists
4475 * which require authentication. The request data is empty or
4476 * contains "ifstats" (not null terminated) to retrieve local
4477 * addresses and associated stats. It is "addr_restrictions"
4478 * to retrieve the IPv4 then IPv6 remote address restrictions,
4479 * which are access control lists. Other request data return
4482 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4483 qdata_octets = ntohs(cpkt->count);
4484 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4485 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4486 read_ifstats(rbufp);
4489 if (a_r_chars == qdata_octets &&
4490 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4491 read_addr_restrictions(rbufp);
4494 ctl_error(CERR_UNKNOWNVAR);
4499 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4501 static void req_nonce(
4502 struct recvbuf * rbufp,
4508 generate_nonce(rbufp, buf, sizeof(buf));
4509 ctl_putunqstr("nonce", buf, strlen(buf));
4515 * read_clockstatus - return clock radio status
4520 struct recvbuf *rbufp,
4526 * If no refclock support, no data to return
4528 ctl_error(CERR_BADASSOC);
4530 const struct ctl_var * v;
4538 struct ctl_var * kv;
4539 struct refclockstat cs;
4541 if (res_associd != 0) {
4542 peer = findpeerbyassoc(res_associd);
4545 * Find a clock for this jerk. If the system peer
4546 * is a clock use it, else search peer_list for one.
4548 if (sys_peer != NULL && (FLAG_REFCLOCK &
4552 for (peer = peer_list;
4554 peer = peer->p_link)
4555 if (FLAG_REFCLOCK & peer->flags)
4558 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4559 ctl_error(CERR_BADASSOC);
4563 * If we got here we have a peer which is a clock. Get his
4567 refclock_control(&peer->srcadr, NULL, &cs);
4570 * Look for variables in the packet.
4572 rpkt.status = htons(ctlclkstatus(&cs));
4573 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4574 wants = emalloc_zero(wants_alloc);
4576 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4577 if (!(EOV & v->flags)) {
4578 wants[v->code] = TRUE;
4581 v = ctl_getitem(kv, &valuep);
4583 if (EOV & v->flags) {
4584 ctl_error(CERR_UNKNOWNVAR);
4586 free_varlist(cs.kv_list);
4589 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4595 for (i = 1; i <= CC_MAXCODE; i++)
4597 ctl_putclock(i, &cs, TRUE);
4599 for (i = 0; !(EOV & kv[i].flags); i++)
4600 if (wants[i + CC_MAXCODE + 1])
4601 ctl_putdata(kv[i].text,
4605 for (cc = def_clock_var; *cc != 0; cc++)
4606 ctl_putclock((int)*cc, &cs, FALSE);
4607 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4608 if (DEF & kv->flags)
4609 ctl_putdata(kv->text, strlen(kv->text),
4614 free_varlist(cs.kv_list);
4622 * write_clockstatus - we don't do this
4627 struct recvbuf *rbufp,
4631 ctl_error(CERR_PERMISSION);
4635 * Trap support from here on down. We send async trap messages when the
4636 * upper levels report trouble. Traps can by set either by control
4637 * messages or by configuration.
4640 * set_trap - set a trap in response to a control message
4644 struct recvbuf *rbufp,
4651 * See if this guy is allowed
4653 if (restrict_mask & RES_NOTRAP) {
4654 ctl_error(CERR_PERMISSION);
4659 * Determine his allowed trap type.
4661 traptype = TRAP_TYPE_PRIO;
4662 if (restrict_mask & RES_LPTRAP)
4663 traptype = TRAP_TYPE_NONPRIO;
4666 * Call ctlsettrap() to do the work. Return
4667 * an error if it can't assign the trap.
4669 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4671 ctl_error(CERR_NORESOURCE);
4677 * unset_trap - unset a trap in response to a control message
4681 struct recvbuf *rbufp,
4688 * We don't prevent anyone from removing his own trap unless the
4689 * trap is configured. Note we also must be aware of the
4690 * possibility that restriction flags were changed since this
4691 * guy last set his trap. Set the trap type based on this.
4693 traptype = TRAP_TYPE_PRIO;
4694 if (restrict_mask & RES_LPTRAP)
4695 traptype = TRAP_TYPE_NONPRIO;
4698 * Call ctlclrtrap() to clear this out.
4700 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4701 ctl_error(CERR_BADASSOC);
4707 * ctlsettrap - called to set a trap
4712 struct interface *linter,
4718 struct ctl_trap *tp;
4719 struct ctl_trap *tptouse;
4722 * See if we can find this trap. If so, we only need update
4723 * the flags and the time.
4725 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4728 case TRAP_TYPE_CONFIG:
4729 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4732 case TRAP_TYPE_PRIO:
4733 if (tp->tr_flags & TRAP_CONFIGURED)
4734 return (1); /* don't change anything */
4735 tp->tr_flags = TRAP_INUSE;
4738 case TRAP_TYPE_NONPRIO:
4739 if (tp->tr_flags & TRAP_CONFIGURED)
4740 return (1); /* don't change anything */
4741 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4744 tp->tr_settime = current_time;
4750 * First we heard of this guy. Try to find a trap structure
4751 * for him to use, clearing out lesser priority guys if we
4752 * have to. Clear out anyone who's expired while we're at it.
4755 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4757 if ((TRAP_INUSE & tp->tr_flags) &&
4758 !(TRAP_CONFIGURED & tp->tr_flags) &&
4759 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4763 if (!(TRAP_INUSE & tp->tr_flags)) {
4765 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4768 case TRAP_TYPE_CONFIG:
4769 if (tptouse == NULL) {
4773 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4774 !(TRAP_NONPRIO & tp->tr_flags))
4777 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4778 && (TRAP_NONPRIO & tp->tr_flags)) {
4782 if (tptouse->tr_origtime <
4787 case TRAP_TYPE_PRIO:
4788 if ( TRAP_NONPRIO & tp->tr_flags) {
4789 if (tptouse == NULL ||
4791 tptouse->tr_flags) &&
4792 tptouse->tr_origtime <
4798 case TRAP_TYPE_NONPRIO:
4805 * If we don't have room for him return an error.
4807 if (tptouse == NULL)
4811 * Set up this structure for him.
4813 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4814 tptouse->tr_count = tptouse->tr_resets = 0;
4815 tptouse->tr_sequence = 1;
4816 tptouse->tr_addr = *raddr;
4817 tptouse->tr_localaddr = linter;
4818 tptouse->tr_version = (u_char) version;
4819 tptouse->tr_flags = TRAP_INUSE;
4820 if (traptype == TRAP_TYPE_CONFIG)
4821 tptouse->tr_flags |= TRAP_CONFIGURED;
4822 else if (traptype == TRAP_TYPE_NONPRIO)
4823 tptouse->tr_flags |= TRAP_NONPRIO;
4830 * ctlclrtrap - called to clear a trap
4835 struct interface *linter,
4839 register struct ctl_trap *tp;
4841 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4844 if (tp->tr_flags & TRAP_CONFIGURED
4845 && traptype != TRAP_TYPE_CONFIG)
4855 * ctlfindtrap - find a trap given the remote and local addresses
4857 static struct ctl_trap *
4860 struct interface *linter
4865 for (n = 0; n < COUNTOF(ctl_traps); n++)
4866 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4867 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4868 && (linter == ctl_traps[n].tr_localaddr))
4869 return &ctl_traps[n];
4876 * report_event - report an event to the trappers
4880 int err, /* error code */
4881 struct peer *peer, /* peer structure pointer */
4882 const char *str /* protostats string */
4885 char statstr[NTP_MAXSTRLEN];
4890 * Report the error to the protostats file, system log and
4896 * Discard a system report if the number of reports of
4897 * the same type exceeds the maximum.
4899 if (ctl_sys_last_event != (u_char)err)
4900 ctl_sys_num_events= 0;
4901 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4904 ctl_sys_last_event = (u_char)err;
4905 ctl_sys_num_events++;
4906 snprintf(statstr, sizeof(statstr),
4907 "0.0.0.0 %04x %02x %s",
4908 ctlsysstatus(), err, eventstr(err));
4910 len = strlen(statstr);
4911 snprintf(statstr + len, sizeof(statstr) - len,
4915 msyslog(LOG_INFO, "%s", statstr);
4919 * Discard a peer report if the number of reports of
4920 * the same type exceeds the maximum for that peer.
4925 errlast = (u_char)err & ~PEER_EVENT;
4926 if (peer->last_event == errlast)
4927 peer->num_events = 0;
4928 if (peer->num_events >= CTL_PEER_MAXEVENTS)
4931 peer->last_event = errlast;
4933 if (ISREFCLOCKADR(&peer->srcadr))
4934 src = refnumtoa(&peer->srcadr);
4936 src = stoa(&peer->srcadr);
4938 snprintf(statstr, sizeof(statstr),
4939 "%s %04x %02x %s", src,
4940 ctlpeerstatus(peer), err, eventstr(err));
4942 len = strlen(statstr);
4943 snprintf(statstr + len, sizeof(statstr) - len,
4946 NLOG(NLOG_PEEREVENT)
4947 msyslog(LOG_INFO, "%s", statstr);
4949 record_proto_stats(statstr);
4952 printf("event at %lu %s\n", current_time, statstr);
4956 * If no trappers, return.
4958 if (num_ctl_traps <= 0)
4962 * Set up the outgoing packet variables
4964 res_opcode = CTL_OP_ASYNCMSG;
4967 res_authenticate = FALSE;
4968 datapt = rpkt.u.data;
4969 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
4970 if (!(err & PEER_EVENT)) {
4972 rpkt.status = htons(ctlsysstatus());
4974 /* Include the core system variables and the list. */
4975 for (i = 1; i <= CS_VARLIST; i++)
4978 INSIST(peer != NULL);
4979 rpkt.associd = htons(peer->associd);
4980 rpkt.status = htons(ctlpeerstatus(peer));
4982 /* Dump it all. Later, maybe less. */
4983 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
4984 ctl_putpeer(i, peer);
4987 * for clock exception events: add clock variables to
4988 * reflect info on exception
4990 if (err == PEVNT_CLOCK) {
4991 struct refclockstat cs;
4995 refclock_control(&peer->srcadr, NULL, &cs);
4997 ctl_puthex("refclockstatus",
5000 for (i = 1; i <= CC_MAXCODE; i++)
5001 ctl_putclock(i, &cs, FALSE);
5002 for (kv = cs.kv_list;
5003 kv != NULL && !(EOV & kv->flags);
5005 if (DEF & kv->flags)
5006 ctl_putdata(kv->text,
5009 free_varlist(cs.kv_list);
5011 #endif /* REFCLOCK */
5015 * We're done, return.
5022 * mprintf_event - printf-style varargs variant of report_event()
5026 int evcode, /* event code */
5027 struct peer * p, /* may be NULL */
5028 const char * fmt, /* msnprintf format */
5037 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
5039 report_event(evcode, p, msg);
5046 * ctl_clr_stats - clear stat counters
5051 ctltimereset = current_time;
5054 numctlresponses = 0;
5059 numctlinputresp = 0;
5060 numctlinputfrag = 0;
5062 numctlbadoffset = 0;
5063 numctlbadversion = 0;
5064 numctldatatooshort = 0;
5071 const struct ctl_var *k
5080 while (!(EOV & (k++)->flags))
5083 ENSURE(c <= USHRT_MAX);
5090 struct ctl_var **kv,
5100 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
5102 buf = emalloc(size);
5107 k[c + 1].text = NULL;
5108 k[c + 1].flags = EOV;
5116 struct ctl_var **kv,
5127 if (NULL == data || !size)
5132 while (!(EOV & k->flags)) {
5133 if (NULL == k->text) {
5135 memcpy(td, data, size);
5142 while (*t != '=' && *s == *t) {
5146 if (*s == *t && ((*t == '=') || !*t)) {
5147 td = erealloc((void *)(intptr_t)k->text, size);
5148 memcpy(td, data, size);
5157 td = add_var(kv, size, def);
5158 memcpy(td, data, size);
5169 set_var(&ext_sys_var, data, size, def);
5174 * get_ext_sys_var() retrieves the value of a user-defined variable or
5175 * NULL if the variable has not been setvar'd.
5178 get_ext_sys_var(const char *tag)
5186 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5187 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5188 if ('=' == v->text[c]) {
5189 val = v->text + c + 1;
5191 } else if ('\0' == v->text[c]) {
5209 for (k = kv; !(k->flags & EOV); k++)
5210 free((void *)(intptr_t)k->text);