2 * ntp_control.c - respond to mode 6 control messages and send async
3 * traps. Provides service to ntpq and others.
14 #ifdef HAVE_NETINET_IN_H
15 # include <netinet/in.h>
17 #include <arpa/inet.h>
21 #include "ntp_refclock.h"
22 #include "ntp_control.h"
23 #include "ntp_unixtime.h"
24 #include "ntp_stdlib.h"
25 #include "ntp_config.h"
26 #include "ntp_crypto.h"
27 #include "ntp_assert.h"
28 #include "ntp_leapsec.h"
29 #include "ntp_md5.h" /* provides OpenSSL digest API */
30 #include "lib_strbuf.h"
31 #include <rc_cmdlength.h>
33 # include "ntp_syscall.h"
38 * Structure to hold request procedure information
42 short control_code; /* defined request code */
43 #define NO_REQUEST (-1)
44 u_short flags; /* flags word */
45 /* Only one flag. Authentication required or not. */
48 void (*handler) (struct recvbuf *, int); /* handle request */
53 * Request processing routines
55 static void ctl_error (u_char);
57 static u_short ctlclkstatus (struct refclockstat *);
59 static void ctl_flushpkt (u_char);
60 static void ctl_putdata (const char *, unsigned int, int);
61 static void ctl_putstr (const char *, const char *, size_t);
62 static void ctl_putdblf (const char *, int, int, double);
63 #define ctl_putdbl(tag, d) ctl_putdblf(tag, 1, 3, d)
64 #define ctl_putdbl6(tag, d) ctl_putdblf(tag, 1, 6, d)
65 #define ctl_putsfp(tag, sfp) ctl_putdblf(tag, 0, -1, \
67 static void ctl_putuint (const char *, u_long);
68 static void ctl_puthex (const char *, u_long);
69 static void ctl_putint (const char *, long);
70 static void ctl_putts (const char *, l_fp *);
71 static void ctl_putadr (const char *, u_int32,
73 static void ctl_putrefid (const char *, u_int32);
74 static void ctl_putarray (const char *, double *, int);
75 static void ctl_putsys (int);
76 static void ctl_putpeer (int, struct peer *);
77 static void ctl_putfs (const char *, tstamp_t);
78 static void ctl_printf (const char *, ...) NTP_PRINTF(1, 2);
80 static void ctl_putclock (int, struct refclockstat *, int);
82 static const struct ctl_var *ctl_getitem(const struct ctl_var *,
84 static u_short count_var (const struct ctl_var *);
85 static void control_unspec (struct recvbuf *, int);
86 static void read_status (struct recvbuf *, int);
87 static void read_sysvars (void);
88 static void read_peervars (void);
89 static void read_variables (struct recvbuf *, int);
90 static void write_variables (struct recvbuf *, int);
91 static void read_clockstatus(struct recvbuf *, int);
92 static void write_clockstatus(struct recvbuf *, int);
93 static void set_trap (struct recvbuf *, int);
94 static void save_config (struct recvbuf *, int);
95 static void configure (struct recvbuf *, int);
96 static void send_mru_entry (mon_entry *, int);
97 static void send_random_tag_value(int);
98 static void read_mru_list (struct recvbuf *, int);
99 static void send_ifstats_entry(endpt *, u_int);
100 static void read_ifstats (struct recvbuf *);
101 static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *,
103 static void send_restrict_entry(restrict_u *, int, u_int);
104 static void send_restrict_list(restrict_u *, int, u_int *);
105 static void read_addr_restrictions(struct recvbuf *);
106 static void read_ordlist (struct recvbuf *, int);
107 static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32);
108 static void generate_nonce (struct recvbuf *, char *, size_t);
109 static int validate_nonce (const char *, struct recvbuf *);
110 static void req_nonce (struct recvbuf *, int);
111 static void unset_trap (struct recvbuf *, int);
112 static struct ctl_trap *ctlfindtrap(sockaddr_u *,
115 int/*BOOL*/ is_safe_filename(const char * name);
117 static const struct ctl_proc control_codes[] = {
118 { CTL_OP_UNSPEC, NOAUTH, control_unspec },
119 { CTL_OP_READSTAT, NOAUTH, read_status },
120 { CTL_OP_READVAR, NOAUTH, read_variables },
121 { CTL_OP_WRITEVAR, AUTH, write_variables },
122 { CTL_OP_READCLOCK, NOAUTH, read_clockstatus },
123 { CTL_OP_WRITECLOCK, NOAUTH, write_clockstatus },
124 { CTL_OP_SETTRAP, NOAUTH, set_trap },
125 { CTL_OP_CONFIGURE, AUTH, configure },
126 { CTL_OP_SAVECONFIG, AUTH, save_config },
127 { CTL_OP_READ_MRU, NOAUTH, read_mru_list },
128 { CTL_OP_READ_ORDLIST_A, AUTH, read_ordlist },
129 { CTL_OP_REQ_NONCE, NOAUTH, req_nonce },
130 { CTL_OP_UNSETTRAP, NOAUTH, unset_trap },
131 { NO_REQUEST, 0, NULL }
135 * System variables we understand
139 #define CS_PRECISION 3
140 #define CS_ROOTDELAY 4
141 #define CS_ROOTDISPERSION 5
151 #define CS_PROCESSOR 15
153 #define CS_VERSION 17
155 #define CS_VARLIST 19
157 #define CS_LEAPTAB 21
158 #define CS_LEAPEND 22
160 #define CS_MRU_ENABLED 24
161 #define CS_MRU_DEPTH 25
162 #define CS_MRU_DEEPEST 26
163 #define CS_MRU_MINDEPTH 27
164 #define CS_MRU_MAXAGE 28
165 #define CS_MRU_MAXDEPTH 29
166 #define CS_MRU_MEM 30
167 #define CS_MRU_MAXMEM 31
168 #define CS_SS_UPTIME 32
169 #define CS_SS_RESET 33
170 #define CS_SS_RECEIVED 34
171 #define CS_SS_THISVER 35
172 #define CS_SS_OLDVER 36
173 #define CS_SS_BADFORMAT 37
174 #define CS_SS_BADAUTH 38
175 #define CS_SS_DECLINED 39
176 #define CS_SS_RESTRICTED 40
177 #define CS_SS_LIMITED 41
178 #define CS_SS_KODSENT 42
179 #define CS_SS_PROCESSED 43
180 #define CS_PEERADR 44
181 #define CS_PEERMODE 45
182 #define CS_BCASTDELAY 46
183 #define CS_AUTHDELAY 47
184 #define CS_AUTHKEYS 48
185 #define CS_AUTHFREEK 49
186 #define CS_AUTHKLOOKUPS 50
187 #define CS_AUTHKNOTFOUND 51
188 #define CS_AUTHKUNCACHED 52
189 #define CS_AUTHKEXPIRED 53
190 #define CS_AUTHENCRYPTS 54
191 #define CS_AUTHDECRYPTS 55
192 #define CS_AUTHRESET 56
193 #define CS_K_OFFSET 57
195 #define CS_K_MAXERR 59
196 #define CS_K_ESTERR 60
197 #define CS_K_STFLAGS 61
198 #define CS_K_TIMECONST 62
199 #define CS_K_PRECISION 63
200 #define CS_K_FREQTOL 64
201 #define CS_K_PPS_FREQ 65
202 #define CS_K_PPS_STABIL 66
203 #define CS_K_PPS_JITTER 67
204 #define CS_K_PPS_CALIBDUR 68
205 #define CS_K_PPS_CALIBS 69
206 #define CS_K_PPS_CALIBERRS 70
207 #define CS_K_PPS_JITEXC 71
208 #define CS_K_PPS_STBEXC 72
209 #define CS_KERN_FIRST CS_K_OFFSET
210 #define CS_KERN_LAST CS_K_PPS_STBEXC
211 #define CS_IOSTATS_RESET 73
212 #define CS_TOTAL_RBUF 74
213 #define CS_FREE_RBUF 75
214 #define CS_USED_RBUF 76
215 #define CS_RBUF_LOWATER 77
216 #define CS_IO_DROPPED 78
217 #define CS_IO_IGNORED 79
218 #define CS_IO_RECEIVED 80
219 #define CS_IO_SENT 81
220 #define CS_IO_SENDFAILED 82
221 #define CS_IO_WAKEUPS 83
222 #define CS_IO_GOODWAKEUPS 84
223 #define CS_TIMERSTATS_RESET 85
224 #define CS_TIMER_OVERRUNS 86
225 #define CS_TIMER_XMTS 87
227 #define CS_WANDER_THRESH 89
228 #define CS_LEAPSMEARINTV 90
229 #define CS_LEAPSMEAROFFS 91
230 #define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS
232 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
233 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
234 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
235 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
236 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
237 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
238 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
239 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
240 #define CS_MAXCODE CS_DIGEST
241 #else /* !AUTOKEY follows */
242 #define CS_MAXCODE CS_MAX_NOAUTOKEY
243 #endif /* !AUTOKEY */
246 * Peer variables we understand
249 #define CP_AUTHENABLE 2
250 #define CP_AUTHENTIC 3
257 #define CP_STRATUM 10
260 #define CP_PRECISION 13
261 #define CP_ROOTDELAY 14
262 #define CP_ROOTDISPERSION 15
264 #define CP_REFTIME 17
269 #define CP_UNREACH 22
274 #define CP_DISPERSION 27
276 #define CP_FILTDELAY 29
277 #define CP_FILTOFFSET 30
279 #define CP_RECEIVED 32
281 #define CP_FILTERROR 34
284 #define CP_VARLIST 37
289 #define CP_SRCHOST 42
290 #define CP_TIMEREC 43
291 #define CP_TIMEREACH 44
292 #define CP_BADAUTH 45
293 #define CP_BOGUSORG 46
295 #define CP_SELDISP 48
296 #define CP_SELBROKEN 49
297 #define CP_CANDIDATE 50
298 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
300 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
301 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
302 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
303 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
304 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
305 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
306 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
307 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
308 #define CP_MAXCODE CP_IDENT
309 #else /* !AUTOKEY follows */
310 #define CP_MAXCODE CP_MAX_NOAUTOKEY
311 #endif /* !AUTOKEY */
314 * Clock variables we understand
317 #define CC_TIMECODE 2
320 #define CC_BADFORMAT 5
322 #define CC_FUDGETIME1 7
323 #define CC_FUDGETIME2 8
324 #define CC_FUDGEVAL1 9
325 #define CC_FUDGEVAL2 10
328 #define CC_VARLIST 13
329 #define CC_MAXCODE CC_VARLIST
332 * System variable values. The array can be indexed by the variable
333 * index to find the textual name.
335 static const struct ctl_var sys_var[] = {
336 { 0, PADDING, "" }, /* 0 */
337 { CS_LEAP, RW, "leap" }, /* 1 */
338 { CS_STRATUM, RO, "stratum" }, /* 2 */
339 { CS_PRECISION, RO, "precision" }, /* 3 */
340 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
341 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
342 { CS_REFID, RO, "refid" }, /* 6 */
343 { CS_REFTIME, RO, "reftime" }, /* 7 */
344 { CS_POLL, RO, "tc" }, /* 8 */
345 { CS_PEERID, RO, "peer" }, /* 9 */
346 { CS_OFFSET, RO, "offset" }, /* 10 */
347 { CS_DRIFT, RO, "frequency" }, /* 11 */
348 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
349 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
350 { CS_CLOCK, RO, "clock" }, /* 14 */
351 { CS_PROCESSOR, RO, "processor" }, /* 15 */
352 { CS_SYSTEM, RO, "system" }, /* 16 */
353 { CS_VERSION, RO, "version" }, /* 17 */
354 { CS_STABIL, RO, "clk_wander" }, /* 18 */
355 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
356 { CS_TAI, RO, "tai" }, /* 20 */
357 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
358 { CS_LEAPEND, RO, "expire" }, /* 22 */
359 { CS_RATE, RO, "mintc" }, /* 23 */
360 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
361 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
362 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
363 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
364 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
365 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
366 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
367 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
368 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
369 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
370 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
371 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
372 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
373 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
374 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
375 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
376 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
377 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
378 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
379 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
380 { CS_PEERADR, RO, "peeradr" }, /* 44 */
381 { CS_PEERMODE, RO, "peermode" }, /* 45 */
382 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 46 */
383 { CS_AUTHDELAY, RO, "authdelay" }, /* 47 */
384 { CS_AUTHKEYS, RO, "authkeys" }, /* 48 */
385 { CS_AUTHFREEK, RO, "authfreek" }, /* 49 */
386 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 50 */
387 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 51 */
388 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 52 */
389 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 53 */
390 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 54 */
391 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 55 */
392 { CS_AUTHRESET, RO, "authreset" }, /* 56 */
393 { CS_K_OFFSET, RO, "koffset" }, /* 57 */
394 { CS_K_FREQ, RO, "kfreq" }, /* 58 */
395 { CS_K_MAXERR, RO, "kmaxerr" }, /* 59 */
396 { CS_K_ESTERR, RO, "kesterr" }, /* 60 */
397 { CS_K_STFLAGS, RO, "kstflags" }, /* 61 */
398 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 62 */
399 { CS_K_PRECISION, RO, "kprecis" }, /* 63 */
400 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 64 */
401 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 65 */
402 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 66 */
403 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 67 */
404 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 68 */
405 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 69 */
406 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 70 */
407 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 71 */
408 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 72 */
409 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 73 */
410 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 74 */
411 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 75 */
412 { CS_USED_RBUF, RO, "used_rbuf" }, /* 76 */
413 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 77 */
414 { CS_IO_DROPPED, RO, "io_dropped" }, /* 78 */
415 { CS_IO_IGNORED, RO, "io_ignored" }, /* 79 */
416 { CS_IO_RECEIVED, RO, "io_received" }, /* 80 */
417 { CS_IO_SENT, RO, "io_sent" }, /* 81 */
418 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 82 */
419 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 83 */
420 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 84 */
421 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 85 */
422 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 86 */
423 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 87 */
424 { CS_FUZZ, RO, "fuzz" }, /* 88 */
425 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 89 */
427 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 90 */
428 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 91 */
431 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
432 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
433 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
434 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
435 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
436 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
437 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
438 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
440 { 0, EOV, "" } /* 87/95 */
443 static struct ctl_var *ext_sys_var = NULL;
446 * System variables we print by default (in fuzzball order,
449 static const u_char def_sys_var[] = {
490 static const struct ctl_var peer_var[] = {
491 { 0, PADDING, "" }, /* 0 */
492 { CP_CONFIG, RO, "config" }, /* 1 */
493 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
494 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
495 { CP_SRCADR, RO, "srcadr" }, /* 4 */
496 { CP_SRCPORT, RO, "srcport" }, /* 5 */
497 { CP_DSTADR, RO, "dstadr" }, /* 6 */
498 { CP_DSTPORT, RO, "dstport" }, /* 7 */
499 { CP_LEAP, RO, "leap" }, /* 8 */
500 { CP_HMODE, RO, "hmode" }, /* 9 */
501 { CP_STRATUM, RO, "stratum" }, /* 10 */
502 { CP_PPOLL, RO, "ppoll" }, /* 11 */
503 { CP_HPOLL, RO, "hpoll" }, /* 12 */
504 { CP_PRECISION, RO, "precision" }, /* 13 */
505 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
506 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
507 { CP_REFID, RO, "refid" }, /* 16 */
508 { CP_REFTIME, RO, "reftime" }, /* 17 */
509 { CP_ORG, RO, "org" }, /* 18 */
510 { CP_REC, RO, "rec" }, /* 19 */
511 { CP_XMT, RO, "xleave" }, /* 20 */
512 { CP_REACH, RO, "reach" }, /* 21 */
513 { CP_UNREACH, RO, "unreach" }, /* 22 */
514 { CP_TIMER, RO, "timer" }, /* 23 */
515 { CP_DELAY, RO, "delay" }, /* 24 */
516 { CP_OFFSET, RO, "offset" }, /* 25 */
517 { CP_JITTER, RO, "jitter" }, /* 26 */
518 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
519 { CP_KEYID, RO, "keyid" }, /* 28 */
520 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
521 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
522 { CP_PMODE, RO, "pmode" }, /* 31 */
523 { CP_RECEIVED, RO, "received"}, /* 32 */
524 { CP_SENT, RO, "sent" }, /* 33 */
525 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
526 { CP_FLASH, RO, "flash" }, /* 35 */
527 { CP_TTL, RO, "ttl" }, /* 36 */
528 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
529 { CP_IN, RO, "in" }, /* 38 */
530 { CP_OUT, RO, "out" }, /* 39 */
531 { CP_RATE, RO, "headway" }, /* 40 */
532 { CP_BIAS, RO, "bias" }, /* 41 */
533 { CP_SRCHOST, RO, "srchost" }, /* 42 */
534 { CP_TIMEREC, RO, "timerec" }, /* 43 */
535 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
536 { CP_BADAUTH, RO, "badauth" }, /* 45 */
537 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
538 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
539 { CP_SELDISP, RO, "seldisp" }, /* 48 */
540 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
541 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
543 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
544 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
545 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
546 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
547 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
548 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
549 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
550 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
552 { 0, EOV, "" } /* 50/58 */
557 * Peer variables we print by default
559 static const u_char def_peer_var[] = {
608 * Clock variable list
610 static const struct ctl_var clock_var[] = {
611 { 0, PADDING, "" }, /* 0 */
612 { CC_TYPE, RO, "type" }, /* 1 */
613 { CC_TIMECODE, RO, "timecode" }, /* 2 */
614 { CC_POLL, RO, "poll" }, /* 3 */
615 { CC_NOREPLY, RO, "noreply" }, /* 4 */
616 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
617 { CC_BADDATA, RO, "baddata" }, /* 6 */
618 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
619 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
620 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
621 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
622 { CC_FLAGS, RO, "flags" }, /* 11 */
623 { CC_DEVICE, RO, "device" }, /* 12 */
624 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
625 { 0, EOV, "" } /* 14 */
630 * Clock variables printed by default
632 static const u_char def_clock_var[] = {
634 CC_TYPE, /* won't be output if device = known */
650 * MRU string constants shared by send_mru_entry() and read_mru_list().
652 static const char addr_fmt[] = "addr.%d";
653 static const char last_fmt[] = "last.%d";
656 * System and processor definitions.
660 # define STR_SYSTEM "UNIX"
662 # ifndef STR_PROCESSOR
663 # define STR_PROCESSOR "unknown"
666 static const char str_system[] = STR_SYSTEM;
667 static const char str_processor[] = STR_PROCESSOR;
669 # include <sys/utsname.h>
670 static struct utsname utsnamebuf;
671 #endif /* HAVE_UNAME */
674 * Trap structures. We only allow a few of these, and send a copy of
675 * each async message to each live one. Traps time out after an hour, it
676 * is up to the trap receipient to keep resetting it to avoid being
680 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
684 * Type bits, for ctlsettrap() call.
686 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
687 #define TRAP_TYPE_PRIO 1 /* priority trap */
688 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
692 * List relating reference clock types to control message time sources.
693 * Index by the reference clock type. This list will only be used iff
694 * the reference clock driver doesn't set peer->sstclktype to something
695 * different than CTL_SST_TS_UNSPEC.
698 static const u_char clocktypes[] = {
699 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
700 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
701 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
702 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
703 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
704 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
705 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
706 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
707 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
708 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
709 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
710 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
711 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
712 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
713 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
714 CTL_SST_TS_NTP, /* not used (15) */
715 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
716 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
717 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
718 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
719 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
720 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
721 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
722 CTL_SST_TS_NTP, /* not used (23) */
723 CTL_SST_TS_NTP, /* not used (24) */
724 CTL_SST_TS_NTP, /* not used (25) */
725 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
726 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
727 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
728 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
729 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
730 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
731 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
732 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
733 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
734 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
735 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
736 CTL_SST_TS_LF, /* REFCLK_FG (37) */
737 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
738 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
739 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
740 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
741 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
742 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
743 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
744 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
745 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
747 #endif /* REFCLOCK */
751 * Keyid used for authenticating write requests.
753 keyid_t ctl_auth_keyid;
756 * We keep track of the last error reported by the system internally
758 static u_char ctl_sys_last_event;
759 static u_char ctl_sys_num_events;
763 * Statistic counters to keep track of requests and responses.
765 u_long ctltimereset; /* time stats reset */
766 u_long numctlreq; /* number of requests we've received */
767 u_long numctlbadpkts; /* number of bad control packets */
768 u_long numctlresponses; /* number of resp packets sent with data */
769 u_long numctlfrags; /* number of fragments sent */
770 u_long numctlerrors; /* number of error responses sent */
771 u_long numctltooshort; /* number of too short input packets */
772 u_long numctlinputresp; /* number of responses on input */
773 u_long numctlinputfrag; /* number of fragments on input */
774 u_long numctlinputerr; /* number of input pkts with err bit set */
775 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
776 u_long numctlbadversion; /* number of input pkts with unknown version */
777 u_long numctldatatooshort; /* data too short for count */
778 u_long numctlbadop; /* bad op code found in packet */
779 u_long numasyncmsgs; /* number of async messages we've sent */
782 * Response packet used by these routines. Also some state information
783 * so that we can handle packet formatting within a common set of
784 * subroutines. Note we try to enter data in place whenever possible,
785 * but the need to set the more bit correctly means we occasionally
786 * use the extra buffer and copy.
788 static struct ntp_control rpkt;
789 static u_char res_version;
790 static u_char res_opcode;
791 static associd_t res_associd;
792 static u_short res_frags; /* datagrams in this response */
793 static int res_offset; /* offset of payload in response */
794 static u_char * datapt;
795 static u_char * dataend;
796 static int datalinelen;
797 static int datasent; /* flag to avoid initial ", " */
798 static int datanotbinflag;
799 static sockaddr_u *rmt_addr;
800 static struct interface *lcl_inter;
802 static u_char res_authenticate;
803 static u_char res_authokay;
804 static keyid_t res_keyid;
806 #define MAXDATALINELEN (72)
808 static u_char res_async; /* sending async trap response? */
811 * Pointers for saving state when decoding request packets
817 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
821 * init_control - initialize request data
830 #endif /* HAVE_UNAME */
835 ctl_sys_last_event = EVNT_UNSPEC;
836 ctl_sys_num_events = 0;
839 for (i = 0; i < COUNTOF(ctl_traps); i++)
840 ctl_traps[i].tr_flags = 0;
845 * ctl_error - send an error response for the current request
855 DPRINTF(3, ("sending control error %u\n", errcode));
858 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
859 * have already been filled in.
861 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
862 (res_opcode & CTL_OP_MASK);
863 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
867 * send packet and bump counters
869 if (res_authenticate && sys_authenticate) {
870 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
872 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
873 CTL_HEADER_LEN + maclen);
875 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
880 is_safe_filename(const char * name)
882 /* We need a strict validation of filenames we should write: The
883 * daemon might run with special permissions and is remote
884 * controllable, so we better take care what we allow as file
887 * The first character must be digit or a letter from the ASCII
888 * base plane or a '_' ([_A-Za-z0-9]), the following characters
889 * must be from [-._+A-Za-z0-9].
891 * We do not trust the character classification much here: Since
892 * the NTP protocol makes no provisions for UTF-8 or local code
893 * pages, we strictly require the 7bit ASCII code page.
895 * The following table is a packed bit field of 128 two-bit
896 * groups. The LSB in each group tells us if a character is
897 * acceptable at the first position, the MSB if the character is
898 * accepted at any other position.
900 * This does not ensure that the file name is syntactically
901 * correct (multiple dots will not work with VMS...) but it will
902 * exclude potential globbing bombs and directory traversal. It
903 * also rules out drive selection. (For systems that have this
904 * notion, like Windows or VMS.)
906 static const uint32_t chclass[8] = {
907 0x00000000, 0x00000000,
908 0x28800000, 0x000FFFFF,
909 0xFFFFFFFC, 0xC03FFFFF,
910 0xFFFFFFFC, 0x003FFFFF
913 u_int widx, bidx, mask;
918 while (0 != (widx = (u_char)*name++)) {
919 bidx = (widx & 15) << 1;
921 if (widx >= sizeof(chclass))
923 if (0 == ((chclass[widx] >> bidx) & mask))
932 * save_config - Implements ntpq -c "saveconfig <filename>"
933 * Writes current configuration including any runtime
934 * changes by ntpq's :config or config-from-file
936 * Note: There should be no buffer overflow or truncation in the
937 * processing of file names -- both cause security problems. This is bit
938 * painful to code but essential here.
942 struct recvbuf *rbufp,
946 /* block directory traversal by searching for characters that
947 * indicate directory components in a file path.
949 * Conceptually we should be searching for DIRSEP in filename,
950 * however Windows actually recognizes both forward and
951 * backslashes as equivalent directory separators at the API
952 * level. On POSIX systems we could allow '\\' but such
953 * filenames are tricky to manipulate from a shell, so just
954 * reject both types of slashes on all platforms.
956 /* TALOS-CAN-0062: block directory traversal for VMS, too */
957 static const char * illegal_in_filename =
959 ":[]" /* do not allow drive and path components here */
960 #elif defined(SYS_WINNT)
961 ":\\/" /* path and drive separators */
963 "\\/" /* separator and critical char for POSIX */
968 static const char savedconfig_eq[] = "savedconfig=";
970 /* Build a safe open mode from the available mode flags. We want
971 * to create a new file and write it in text mode (when
972 * applicable -- only Windows does this...)
974 static const int openmode = O_CREAT | O_TRUNC | O_WRONLY
975 # if defined(O_EXCL) /* posix, vms */
977 # elif defined(_O_EXCL) /* windows is alway very special... */
980 # if defined(_O_TEXT) /* windows, again */
988 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
996 if (RES_NOMODIFY & restrict_mask) {
997 ctl_printf("%s", "saveconfig prohibited by restrict ... nomodify");
1001 "saveconfig from %s rejected due to nomodify restriction",
1002 stoa(&rbufp->recv_srcadr));
1008 if (NULL == saveconfigdir) {
1009 ctl_printf("%s", "saveconfig prohibited, no saveconfigdir configured");
1013 "saveconfig from %s rejected, no saveconfigdir",
1014 stoa(&rbufp->recv_srcadr));
1018 /* The length checking stuff gets serious. Do not assume a NUL
1019 * byte can be found, but if so, use it to calculate the needed
1020 * buffer size. If the available buffer is too short, bail out;
1021 * likewise if there is no file spec. (The latter will not
1022 * happen when using NTPQ, but there are other ways to craft a
1025 reqlen = (size_t)(reqend - reqpt);
1027 char * nulpos = (char*)memchr(reqpt, 0, reqlen);
1029 reqlen = (size_t)(nulpos - reqpt);
1033 if (reqlen >= sizeof(filespec)) {
1034 ctl_printf("saveconfig exceeded maximum raw name length (%u)",
1035 (u_int)sizeof(filespec));
1038 "saveconfig exceeded maximum raw name length from %s",
1039 stoa(&rbufp->recv_srcadr));
1043 /* copy data directly as we exactly know the size */
1044 memcpy(filespec, reqpt, reqlen);
1045 filespec[reqlen] = '\0';
1048 * allow timestamping of the saved config filename with
1049 * strftime() format such as:
1050 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
1051 * XXX: Nice feature, but not too safe.
1052 * YYY: The check for permitted characters in file names should
1053 * weed out the worst. Let's hope 'strftime()' does not
1054 * develop pathological problems.
1057 if (0 == strftime(filename, sizeof(filename), filespec,
1061 * If we arrive here, 'strftime()' balked; most likely
1062 * the buffer was too short. (Or it encounterd an empty
1063 * format, or just a format that expands to an empty
1064 * string.) We try to use the original name, though this
1065 * is very likely to fail later if there are format
1066 * specs in the string. Note that truncation cannot
1067 * happen here as long as both buffers have the same
1070 strlcpy(filename, filespec, sizeof(filename));
1074 * Check the file name for sanity. This might/will rule out file
1075 * names that would be legal but problematic, and it blocks
1076 * directory traversal.
1078 if (!is_safe_filename(filename)) {
1079 ctl_printf("saveconfig rejects unsafe file name '%s'",
1083 "saveconfig rejects unsafe file name from %s",
1084 stoa(&rbufp->recv_srcadr));
1089 * XXX: This next test may not be needed with is_safe_filename()
1092 /* block directory/drive traversal */
1093 /* TALOS-CAN-0062: block directory traversal for VMS, too */
1094 if (NULL != strpbrk(filename, illegal_in_filename)) {
1095 snprintf(reply, sizeof(reply),
1096 "saveconfig does not allow directory in filename");
1097 ctl_putdata(reply, strlen(reply), 0);
1100 "saveconfig rejects unsafe file name from %s",
1101 stoa(&rbufp->recv_srcadr));
1105 /* concatenation of directory and path can cause another
1108 prc = snprintf(fullpath, sizeof(fullpath), "%s%s",
1109 saveconfigdir, filename);
1110 if (prc < 0 || prc >= sizeof(fullpath)) {
1111 ctl_printf("saveconfig exceeded maximum path length (%u)",
1112 (u_int)sizeof(fullpath));
1115 "saveconfig exceeded maximum path length from %s",
1116 stoa(&rbufp->recv_srcadr));
1120 fd = open(fullpath, openmode, S_IRUSR | S_IWUSR);
1124 fptr = fdopen(fd, "w");
1126 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
1127 ctl_printf("Unable to save configuration to file '%s': %m",
1130 "saveconfig %s from %s failed", filename,
1131 stoa(&rbufp->recv_srcadr));
1133 ctl_printf("Configuration saved to '%s'", filename);
1135 "Configuration saved to '%s' (requested by %s)",
1136 fullpath, stoa(&rbufp->recv_srcadr));
1138 * save the output filename in system variable
1139 * savedconfig, retrieved with:
1140 * ntpq -c "rv 0 savedconfig"
1141 * Note: the way 'savedconfig' is defined makes overflow
1142 * checks unnecessary here.
1144 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
1145 savedconfig_eq, filename);
1146 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1151 #else /* !SAVECONFIG follows */
1153 "saveconfig unavailable, configured with --disable-saveconfig");
1160 * process_control - process an incoming control message
1164 struct recvbuf *rbufp,
1168 struct ntp_control *pkt;
1171 const struct ctl_proc *cc;
1176 DPRINTF(3, ("in process_control()\n"));
1179 * Save the addresses for error responses
1182 rmt_addr = &rbufp->recv_srcadr;
1183 lcl_inter = rbufp->dstadr;
1184 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1187 * If the length is less than required for the header, or
1188 * it is a response or a fragment, ignore this.
1190 if (rbufp->recv_length < (int)CTL_HEADER_LEN
1191 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1192 || pkt->offset != 0) {
1193 DPRINTF(1, ("invalid format in control packet\n"));
1194 if (rbufp->recv_length < (int)CTL_HEADER_LEN)
1196 if (CTL_RESPONSE & pkt->r_m_e_op)
1198 if (CTL_MORE & pkt->r_m_e_op)
1200 if (CTL_ERROR & pkt->r_m_e_op)
1202 if (pkt->offset != 0)
1206 res_version = PKT_VERSION(pkt->li_vn_mode);
1207 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1208 DPRINTF(1, ("unknown version %d in control packet\n",
1215 * Pull enough data from the packet to make intelligent
1218 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1220 res_opcode = pkt->r_m_e_op;
1221 rpkt.sequence = pkt->sequence;
1222 rpkt.associd = pkt->associd;
1226 res_associd = htons(pkt->associd);
1228 res_authenticate = FALSE;
1230 res_authokay = FALSE;
1231 req_count = (int)ntohs(pkt->count);
1232 datanotbinflag = FALSE;
1235 datapt = rpkt.u.data;
1236 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1238 if ((rbufp->recv_length & 0x3) != 0)
1239 DPRINTF(3, ("Control packet length %d unrounded\n",
1240 rbufp->recv_length));
1243 * We're set up now. Make sure we've got at least enough
1244 * incoming data space to match the count.
1246 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1247 if (req_data < req_count || rbufp->recv_length & 0x3) {
1248 ctl_error(CERR_BADFMT);
1249 numctldatatooshort++;
1253 properlen = req_count + CTL_HEADER_LEN;
1254 /* round up proper len to a 8 octet boundary */
1256 properlen = (properlen + 7) & ~7;
1257 maclen = rbufp->recv_length - properlen;
1258 if ((rbufp->recv_length & 3) == 0 &&
1259 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1261 res_authenticate = TRUE;
1262 pkid = (void *)((char *)pkt + properlen);
1263 res_keyid = ntohl(*pkid);
1264 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1265 rbufp->recv_length, properlen, res_keyid,
1268 if (!authistrusted(res_keyid))
1269 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1270 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1271 rbufp->recv_length - maclen,
1273 res_authokay = TRUE;
1274 DPRINTF(3, ("authenticated okay\n"));
1277 DPRINTF(3, ("authentication failed\n"));
1282 * Set up translate pointers
1284 reqpt = (char *)pkt->u.data;
1285 reqend = reqpt + req_count;
1288 * Look for the opcode processor
1290 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1291 if (cc->control_code == res_opcode) {
1292 DPRINTF(3, ("opcode %d, found command handler\n",
1294 if (cc->flags == AUTH
1296 || res_keyid != ctl_auth_keyid)) {
1297 ctl_error(CERR_PERMISSION);
1300 (cc->handler)(rbufp, restrict_mask);
1306 * Can't find this one, return an error.
1309 ctl_error(CERR_BADOP);
1315 * ctlpeerstatus - return a status word for this peer
1319 register struct peer *p
1325 if (FLAG_CONFIG & p->flags)
1326 status |= CTL_PST_CONFIG;
1328 status |= CTL_PST_AUTHENABLE;
1329 if (FLAG_AUTHENTIC & p->flags)
1330 status |= CTL_PST_AUTHENTIC;
1332 status |= CTL_PST_REACH;
1333 if (MDF_TXONLY_MASK & p->cast_flags)
1334 status |= CTL_PST_BCAST;
1336 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1341 * ctlclkstatus - return a status word for this clock
1346 struct refclockstat *pcs
1349 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1355 * ctlsysstatus - return the system status word
1360 register u_char this_clock;
1362 this_clock = CTL_SST_TS_UNSPEC;
1364 if (sys_peer != NULL) {
1365 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1366 this_clock = sys_peer->sstclktype;
1367 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1368 this_clock = clocktypes[sys_peer->refclktype];
1370 #else /* REFCLOCK */
1372 this_clock = CTL_SST_TS_NTP;
1373 #endif /* REFCLOCK */
1374 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1375 ctl_sys_last_event);
1380 * ctl_flushpkt - write out the current packet and prepare
1381 * another if necessary.
1395 dlen = datapt - rpkt.u.data;
1396 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1398 * Big hack, output a trailing \r\n
1404 sendlen = dlen + CTL_HEADER_LEN;
1407 * Pad to a multiple of 32 bits
1409 while (sendlen & 0x3) {
1415 * Fill in the packet with the current info
1417 rpkt.r_m_e_op = CTL_RESPONSE | more |
1418 (res_opcode & CTL_OP_MASK);
1419 rpkt.count = htons((u_short)dlen);
1420 rpkt.offset = htons((u_short)res_offset);
1422 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1423 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1427 ctl_traps[i].tr_version,
1430 htons(ctl_traps[i].tr_sequence);
1431 sendpkt(&ctl_traps[i].tr_addr,
1432 ctl_traps[i].tr_localaddr, -4,
1433 (struct pkt *)&rpkt, sendlen);
1435 ctl_traps[i].tr_sequence++;
1440 if (res_authenticate && sys_authenticate) {
1443 * If we are going to authenticate, then there
1444 * is an additional requirement that the MAC
1445 * begin on a 64 bit boundary.
1447 while (totlen & 7) {
1451 keyid = htonl(res_keyid);
1452 memcpy(datapt, &keyid, sizeof(keyid));
1453 maclen = authencrypt(res_keyid,
1454 (u_int32 *)&rpkt, totlen);
1455 sendpkt(rmt_addr, lcl_inter, -5,
1456 (struct pkt *)&rpkt, totlen + maclen);
1458 sendpkt(rmt_addr, lcl_inter, -6,
1459 (struct pkt *)&rpkt, sendlen);
1468 * Set us up for another go around.
1472 datapt = rpkt.u.data;
1477 * ctl_putdata - write data into the packet, fragmenting and starting
1478 * another if this one is full.
1484 int bin /* set to 1 when data is binary */
1488 unsigned int currentlen;
1492 datanotbinflag = TRUE;
1497 if ((dlen + datalinelen + 1) >= MAXDATALINELEN) {
1509 * Save room for trailing junk
1511 while (dlen + overhead + datapt > dataend) {
1513 * Not enough room in this one, flush it out.
1515 currentlen = MIN(dlen, (unsigned int)(dataend - datapt));
1517 memcpy(datapt, dp, currentlen);
1519 datapt += currentlen;
1522 datalinelen += currentlen;
1524 ctl_flushpkt(CTL_MORE);
1527 memcpy(datapt, dp, dlen);
1529 datalinelen += dlen;
1535 * ctl_putstr - write a tagged string into the response packet
1540 * len is the data length excluding the NUL terminator,
1541 * as in ctl_putstr("var", "value", strlen("value"));
1555 memcpy(buffer, tag, tl);
1558 INSIST(tl + 3 + len <= sizeof(buffer));
1561 memcpy(cp, data, len);
1565 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1570 * ctl_putunqstr - write a tagged string into the response packet
1575 * len is the data length excluding the NUL terminator.
1576 * data must not contain a comma or whitespace.
1590 memcpy(buffer, tag, tl);
1593 INSIST(tl + 1 + len <= sizeof(buffer));
1595 memcpy(cp, data, len);
1598 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1603 * ctl_putdblf - write a tagged, signed double into the response packet
1622 INSIST((size_t)(cp - buffer) < sizeof(buffer));
1623 snprintf(cp, sizeof(buffer) - (cp - buffer), use_f ? "%.*f" : "%.*g",
1626 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1630 * ctl_putuint - write a tagged unsigned integer into the response
1639 register const char *cq;
1648 INSIST((cp - buffer) < (int)sizeof(buffer));
1649 snprintf(cp, sizeof(buffer) - (cp - buffer), "%lu", uval);
1651 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1655 * ctl_putcal - write a decoded calendar data into the response
1660 const struct calendar *pcal
1666 numch = snprintf(buffer, sizeof(buffer),
1667 "%s=%04d%02d%02d%02d%02d",
1675 INSIST(numch < sizeof(buffer));
1676 ctl_putdata(buffer, numch, 0);
1682 * ctl_putfs - write a decoded filestamp into the response
1691 register const char *cq;
1693 struct tm *tm = NULL;
1702 fstamp = uval - JAN_1970;
1703 tm = gmtime(&fstamp);
1706 INSIST((cp - buffer) < (int)sizeof(buffer));
1707 snprintf(cp, sizeof(buffer) - (cp - buffer),
1708 "%04d%02d%02d%02d%02d", tm->tm_year + 1900,
1709 tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);
1711 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1716 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1726 register const char *cq;
1735 INSIST((cp - buffer) < (int)sizeof(buffer));
1736 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%lx", uval);
1738 ctl_putdata(buffer,(unsigned)( cp - buffer ), 0);
1743 * ctl_putint - write a tagged signed integer into the response
1752 register const char *cq;
1761 INSIST((cp - buffer) < (int)sizeof(buffer));
1762 snprintf(cp, sizeof(buffer) - (cp - buffer), "%ld", ival);
1764 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1769 * ctl_putts - write a tagged timestamp, in hex, into the response
1778 register const char *cq;
1787 INSIST((size_t)(cp - buffer) < sizeof(buffer));
1788 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%08x.%08x",
1789 (u_int)ts->l_ui, (u_int)ts->l_uf);
1791 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1796 * ctl_putadr - write an IP address into the response
1806 register const char *cq;
1816 cq = numtoa(addr32);
1819 INSIST((cp - buffer) < (int)sizeof(buffer));
1820 snprintf(cp, sizeof(buffer) - (cp - buffer), "%s", cq);
1822 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1827 * ctl_putrefid - send a u_int32 refid as printable text
1843 oplim = output + sizeof(output);
1844 while (optr < oplim && '\0' != *tag)
1850 if (!(optr < oplim))
1852 iptr = (char *)&refid;
1853 iplim = iptr + sizeof(refid);
1854 for ( ; optr < oplim && iptr < iplim && '\0' != *iptr;
1856 if (isprint((int)*iptr))
1860 if (!(optr <= oplim))
1862 ctl_putdata(output, (u_int)(optr - output), FALSE);
1867 * ctl_putarray - write a tagged eight element double array into the response
1877 register const char *cq;
1890 INSIST((cp - buffer) < (int)sizeof(buffer));
1891 snprintf(cp, sizeof(buffer) - (cp - buffer),
1892 " %.2f", arr[i] * 1e3);
1894 } while (i != start);
1895 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1899 * ctl_printf - put a formatted string into the data buffer
1907 static const char * ellipsis = "[...]";
1913 rc = vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, va);
1915 if (rc < 0 || rc >= sizeof(fmtbuf))
1916 strcpy(fmtbuf + sizeof(fmtbuf) - strlen(ellipsis) - 1,
1918 ctl_putdata(fmtbuf, strlen(fmtbuf), 0);
1923 * ctl_putsys - output a system variable
1937 struct cert_info *cp;
1938 #endif /* AUTOKEY */
1940 static struct timex ntx;
1941 static u_long ntp_adjtime_time;
1943 static const double to_ms =
1945 1.0e-6; /* nsec to msec */
1947 1.0e-3; /* usec to msec */
1951 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1953 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1954 current_time != ntp_adjtime_time) {
1956 if (ntp_adjtime(&ntx) < 0)
1957 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1959 ntp_adjtime_time = current_time;
1961 #endif /* KERNEL_PLL */
1966 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1970 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1974 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1978 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1982 case CS_ROOTDISPERSION:
1983 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1984 sys_rootdisp * 1e3);
1988 if (sys_stratum > 1 && sys_stratum < STRATUM_UNSPEC)
1989 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1991 ctl_putrefid(sys_var[varid].text, sys_refid);
1995 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1999 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
2003 if (sys_peer == NULL)
2004 ctl_putuint(sys_var[CS_PEERID].text, 0);
2006 ctl_putuint(sys_var[CS_PEERID].text,
2011 if (sys_peer != NULL && sys_peer->dstadr != NULL)
2012 ss = sptoa(&sys_peer->srcadr);
2015 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
2019 u = (sys_peer != NULL)
2022 ctl_putuint(sys_var[CS_PEERMODE].text, u);
2026 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
2030 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
2034 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
2038 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
2043 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
2048 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
2049 sizeof(str_processor) - 1);
2051 ctl_putstr(sys_var[CS_PROCESSOR].text,
2052 utsnamebuf.machine, strlen(utsnamebuf.machine));
2053 #endif /* HAVE_UNAME */
2058 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
2059 sizeof(str_system) - 1);
2061 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
2062 utsnamebuf.release);
2063 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
2064 #endif /* HAVE_UNAME */
2068 ctl_putstr(sys_var[CS_VERSION].text, Version,
2073 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
2079 char buf[CTL_MAX_DATA_LEN];
2080 //buffPointer, firstElementPointer, buffEndPointer
2081 char *buffp, *buffend;
2085 const struct ctl_var *k;
2088 buffend = buf + sizeof(buf);
2089 if (buffp + strlen(sys_var[CS_VARLIST].text) + 4 > buffend)
2090 break; /* really long var name */
2092 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
2093 buffp += strlen(buffp);
2094 firstVarName = TRUE;
2095 for (k = sys_var; !(k->flags & EOV); k++) {
2096 if (k->flags & PADDING)
2098 len = strlen(k->text);
2099 if (buffp + len + 1 >= buffend)
2104 firstVarName = FALSE;
2105 memcpy(buffp, k->text, len);
2109 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
2110 if (k->flags & PADDING)
2112 if (NULL == k->text)
2114 ss1 = strchr(k->text, '=');
2116 len = strlen(k->text);
2118 len = ss1 - k->text;
2119 if (buffp + len + 1 >= buffend)
2123 firstVarName = FALSE;
2125 memcpy(buffp, k->text,(unsigned)len);
2128 if (buffp + 2 >= buffend)
2134 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
2140 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
2145 leap_signature_t lsig;
2146 leapsec_getsig(&lsig);
2148 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
2154 leap_signature_t lsig;
2155 leapsec_getsig(&lsig);
2157 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2162 case CS_LEAPSMEARINTV:
2163 if (leap_smear_intv > 0)
2164 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2167 case CS_LEAPSMEAROFFS:
2168 if (leap_smear_intv > 0)
2169 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2170 leap_smear.doffset * 1e3);
2172 #endif /* LEAP_SMEAR */
2175 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2178 case CS_MRU_ENABLED:
2179 ctl_puthex(sys_var[varid].text, mon_enabled);
2183 ctl_putuint(sys_var[varid].text, mru_entries);
2187 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2191 ctl_putuint(sys_var[varid].text, u);
2194 case CS_MRU_DEEPEST:
2195 ctl_putuint(sys_var[varid].text, mru_peakentries);
2198 case CS_MRU_MINDEPTH:
2199 ctl_putuint(sys_var[varid].text, mru_mindepth);
2203 ctl_putint(sys_var[varid].text, mru_maxage);
2206 case CS_MRU_MAXDEPTH:
2207 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2211 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2215 ctl_putuint(sys_var[varid].text, u);
2219 ctl_putuint(sys_var[varid].text, current_time);
2223 ctl_putuint(sys_var[varid].text,
2224 current_time - sys_stattime);
2227 case CS_SS_RECEIVED:
2228 ctl_putuint(sys_var[varid].text, sys_received);
2232 ctl_putuint(sys_var[varid].text, sys_newversion);
2236 ctl_putuint(sys_var[varid].text, sys_oldversion);
2239 case CS_SS_BADFORMAT:
2240 ctl_putuint(sys_var[varid].text, sys_badlength);
2244 ctl_putuint(sys_var[varid].text, sys_badauth);
2247 case CS_SS_DECLINED:
2248 ctl_putuint(sys_var[varid].text, sys_declined);
2251 case CS_SS_RESTRICTED:
2252 ctl_putuint(sys_var[varid].text, sys_restricted);
2256 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2260 ctl_putuint(sys_var[varid].text, sys_kodsent);
2263 case CS_SS_PROCESSED:
2264 ctl_putuint(sys_var[varid].text, sys_processed);
2268 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2272 LFPTOD(&sys_authdelay, dtemp);
2273 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2277 ctl_putuint(sys_var[varid].text, authnumkeys);
2281 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2284 case CS_AUTHKLOOKUPS:
2285 ctl_putuint(sys_var[varid].text, authkeylookups);
2288 case CS_AUTHKNOTFOUND:
2289 ctl_putuint(sys_var[varid].text, authkeynotfound);
2292 case CS_AUTHKUNCACHED:
2293 ctl_putuint(sys_var[varid].text, authkeyuncached);
2296 case CS_AUTHKEXPIRED:
2297 ctl_putuint(sys_var[varid].text, authkeyexpired);
2300 case CS_AUTHENCRYPTS:
2301 ctl_putuint(sys_var[varid].text, authencryptions);
2304 case CS_AUTHDECRYPTS:
2305 ctl_putuint(sys_var[varid].text, authdecryptions);
2309 ctl_putuint(sys_var[varid].text,
2310 current_time - auth_timereset);
2314 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2315 * unavailable, otherwise calls putfunc with args.
2318 # define CTL_IF_KERNLOOP(putfunc, args) \
2319 ctl_putint(sys_var[varid].text, 0)
2321 # define CTL_IF_KERNLOOP(putfunc, args) \
2326 * CTL_IF_KERNPPS() puts a zero if either the kernel
2327 * loop is unavailable, or kernel hard PPS is not
2328 * active, otherwise calls putfunc with args.
2331 # define CTL_IF_KERNPPS(putfunc, args) \
2332 ctl_putint(sys_var[varid].text, 0)
2334 # define CTL_IF_KERNPPS(putfunc, args) \
2335 if (0 == ntx.shift) \
2336 ctl_putint(sys_var[varid].text, 0); \
2338 putfunc args /* no trailing ; */
2344 (sys_var[varid].text, 0, -1, to_ms * ntx.offset)
2351 (sys_var[varid].text, ntx.freq)
2358 (sys_var[varid].text, 0, 6,
2359 to_ms * ntx.maxerror)
2366 (sys_var[varid].text, 0, 6,
2367 to_ms * ntx.esterror)
2375 ss = k_st_flags(ntx.status);
2377 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2380 case CS_K_TIMECONST:
2383 (sys_var[varid].text, ntx.constant)
2387 case CS_K_PRECISION:
2390 (sys_var[varid].text, 0, 6,
2391 to_ms * ntx.precision)
2398 (sys_var[varid].text, ntx.tolerance)
2405 (sys_var[varid].text, ntx.ppsfreq)
2409 case CS_K_PPS_STABIL:
2412 (sys_var[varid].text, ntx.stabil)
2416 case CS_K_PPS_JITTER:
2419 (sys_var[varid].text, to_ms * ntx.jitter)
2423 case CS_K_PPS_CALIBDUR:
2426 (sys_var[varid].text, 1 << ntx.shift)
2430 case CS_K_PPS_CALIBS:
2433 (sys_var[varid].text, ntx.calcnt)
2437 case CS_K_PPS_CALIBERRS:
2440 (sys_var[varid].text, ntx.errcnt)
2444 case CS_K_PPS_JITEXC:
2447 (sys_var[varid].text, ntx.jitcnt)
2451 case CS_K_PPS_STBEXC:
2454 (sys_var[varid].text, ntx.stbcnt)
2458 case CS_IOSTATS_RESET:
2459 ctl_putuint(sys_var[varid].text,
2460 current_time - io_timereset);
2464 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2468 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2472 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2475 case CS_RBUF_LOWATER:
2476 ctl_putuint(sys_var[varid].text, lowater_additions());
2480 ctl_putuint(sys_var[varid].text, packets_dropped);
2484 ctl_putuint(sys_var[varid].text, packets_ignored);
2487 case CS_IO_RECEIVED:
2488 ctl_putuint(sys_var[varid].text, packets_received);
2492 ctl_putuint(sys_var[varid].text, packets_sent);
2495 case CS_IO_SENDFAILED:
2496 ctl_putuint(sys_var[varid].text, packets_notsent);
2500 ctl_putuint(sys_var[varid].text, handler_calls);
2503 case CS_IO_GOODWAKEUPS:
2504 ctl_putuint(sys_var[varid].text, handler_pkts);
2507 case CS_TIMERSTATS_RESET:
2508 ctl_putuint(sys_var[varid].text,
2509 current_time - timer_timereset);
2512 case CS_TIMER_OVERRUNS:
2513 ctl_putuint(sys_var[varid].text, alarm_overflow);
2517 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2521 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2523 case CS_WANDER_THRESH:
2524 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2529 ctl_puthex(sys_var[CS_FLAGS].text,
2535 strlcpy(str, OBJ_nid2ln(crypto_nid),
2537 ctl_putstr(sys_var[CS_DIGEST].text, str,
2546 dp = EVP_get_digestbynid(crypto_flags >> 16);
2547 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2549 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2555 if (hostval.ptr != NULL)
2556 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2557 strlen(hostval.ptr));
2561 if (sys_ident != NULL)
2562 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2567 for (cp = cinfo; cp != NULL; cp = cp->link) {
2568 snprintf(str, sizeof(str), "%s %s 0x%x",
2569 cp->subject, cp->issuer, cp->flags);
2570 ctl_putstr(sys_var[CS_CERTIF].text, str,
2572 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2577 if (hostval.tstamp != 0)
2578 ctl_putfs(sys_var[CS_PUBLIC].text,
2579 ntohl(hostval.tstamp));
2581 #endif /* AUTOKEY */
2590 * ctl_putpeer - output a peer variable
2598 char buf[CTL_MAX_DATA_LEN];
2603 const struct ctl_var *k;
2608 #endif /* AUTOKEY */
2613 ctl_putuint(peer_var[id].text,
2614 !(FLAG_PREEMPT & p->flags));
2618 ctl_putuint(peer_var[id].text, !(p->keyid));
2622 ctl_putuint(peer_var[id].text,
2623 !!(FLAG_AUTHENTIC & p->flags));
2627 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2631 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2635 if (p->hostname != NULL)
2636 ctl_putstr(peer_var[id].text, p->hostname,
2637 strlen(p->hostname));
2641 ctl_putadr(peer_var[id].text, 0,
2648 ctl_putuint(peer_var[id].text,
2650 ? SRCPORT(&p->dstadr->sin)
2656 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2661 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2665 ctl_putuint(peer_var[id].text, p->throttle);
2669 ctl_putuint(peer_var[id].text, p->leap);
2673 ctl_putuint(peer_var[id].text, p->hmode);
2677 ctl_putuint(peer_var[id].text, p->stratum);
2681 ctl_putuint(peer_var[id].text, p->ppoll);
2685 ctl_putuint(peer_var[id].text, p->hpoll);
2689 ctl_putint(peer_var[id].text, p->precision);
2693 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2696 case CP_ROOTDISPERSION:
2697 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2702 if (p->flags & FLAG_REFCLOCK) {
2703 ctl_putrefid(peer_var[id].text, p->refid);
2707 if (p->stratum > 1 && p->stratum < STRATUM_UNSPEC)
2708 ctl_putadr(peer_var[id].text, p->refid,
2711 ctl_putrefid(peer_var[id].text, p->refid);
2715 ctl_putts(peer_var[id].text, &p->reftime);
2719 ctl_putts(peer_var[id].text, &p->aorg);
2723 ctl_putts(peer_var[id].text, &p->dst);
2728 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2733 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2737 ctl_puthex(peer_var[id].text, p->reach);
2741 ctl_puthex(peer_var[id].text, p->flash);
2746 if (p->flags & FLAG_REFCLOCK) {
2747 ctl_putuint(peer_var[id].text, p->ttl);
2751 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2752 ctl_putint(peer_var[id].text,
2757 ctl_putuint(peer_var[id].text, p->unreach);
2761 ctl_putuint(peer_var[id].text,
2762 p->nextdate - current_time);
2766 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2770 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2774 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2778 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2782 if (p->keyid > NTP_MAXKEY)
2783 ctl_puthex(peer_var[id].text, p->keyid);
2785 ctl_putuint(peer_var[id].text, p->keyid);
2789 ctl_putarray(peer_var[id].text, p->filter_delay,
2794 ctl_putarray(peer_var[id].text, p->filter_offset,
2799 ctl_putarray(peer_var[id].text, p->filter_disp,
2804 ctl_putuint(peer_var[id].text, p->pmode);
2808 ctl_putuint(peer_var[id].text, p->received);
2812 ctl_putuint(peer_var[id].text, p->sent);
2817 be = buf + sizeof(buf);
2818 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2819 break; /* really long var name */
2821 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2824 for (k = peer_var; !(EOV & k->flags); k++) {
2825 if (PADDING & k->flags)
2827 i = strlen(k->text);
2828 if (s + i + 1 >= be)
2832 memcpy(s, k->text, i);
2838 ctl_putdata(buf, (u_int)(s - buf), 0);
2843 ctl_putuint(peer_var[id].text,
2844 current_time - p->timereceived);
2848 ctl_putuint(peer_var[id].text,
2849 current_time - p->timereachable);
2853 ctl_putuint(peer_var[id].text, p->badauth);
2857 ctl_putuint(peer_var[id].text, p->bogusorg);
2861 ctl_putuint(peer_var[id].text, p->oldpkt);
2865 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2869 ctl_putuint(peer_var[id].text, p->selbroken);
2873 ctl_putuint(peer_var[id].text, p->status);
2878 ctl_puthex(peer_var[id].text, p->crypto);
2883 dp = EVP_get_digestbynid(p->crypto >> 16);
2884 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2885 ctl_putstr(peer_var[id].text, str, strlen(str));
2890 if (p->subject != NULL)
2891 ctl_putstr(peer_var[id].text, p->subject,
2892 strlen(p->subject));
2895 case CP_VALID: /* not used */
2899 if (NULL == (ap = p->recval.ptr))
2902 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2903 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2904 ctl_putfs(peer_var[CP_INITTSP].text,
2905 ntohl(p->recval.tstamp));
2909 if (p->ident != NULL)
2910 ctl_putstr(peer_var[id].text, p->ident,
2915 #endif /* AUTOKEY */
2922 * ctl_putclock - output clock variables
2927 struct refclockstat *pcs,
2931 char buf[CTL_MAX_DATA_LEN];
2935 const struct ctl_var *k;
2940 if (mustput || pcs->clockdesc == NULL
2941 || *(pcs->clockdesc) == '\0') {
2942 ctl_putuint(clock_var[id].text, pcs->type);
2946 ctl_putstr(clock_var[id].text,
2948 (unsigned)pcs->lencode);
2952 ctl_putuint(clock_var[id].text, pcs->polls);
2956 ctl_putuint(clock_var[id].text,
2961 ctl_putuint(clock_var[id].text,
2966 ctl_putuint(clock_var[id].text,
2971 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2972 ctl_putdbl(clock_var[id].text,
2973 pcs->fudgetime1 * 1e3);
2977 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2978 ctl_putdbl(clock_var[id].text,
2979 pcs->fudgetime2 * 1e3);
2983 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2984 ctl_putint(clock_var[id].text,
2989 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2990 if (pcs->fudgeval1 > 1)
2991 ctl_putadr(clock_var[id].text,
2992 pcs->fudgeval2, NULL);
2994 ctl_putrefid(clock_var[id].text,
3000 ctl_putuint(clock_var[id].text, pcs->flags);
3004 if (pcs->clockdesc == NULL ||
3005 *(pcs->clockdesc) == '\0') {
3007 ctl_putstr(clock_var[id].text,
3010 ctl_putstr(clock_var[id].text,
3012 strlen(pcs->clockdesc));
3018 be = buf + sizeof(buf);
3019 if (strlen(clock_var[CC_VARLIST].text) + 4 >
3021 break; /* really long var name */
3023 snprintf(s, sizeof(buf), "%s=\"",
3024 clock_var[CC_VARLIST].text);
3028 for (k = clock_var; !(EOV & k->flags); k++) {
3029 if (PADDING & k->flags)
3032 i = strlen(k->text);
3033 if (s + i + 1 >= be)
3038 memcpy(s, k->text, i);
3042 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
3043 if (PADDING & k->flags)
3050 while (*ss && *ss != '=')
3053 if (s + i + 1 >= be)
3058 memcpy(s, k->text, (unsigned)i);
3067 ctl_putdata(buf, (unsigned)(s - buf), 0);
3076 * ctl_getitem - get the next data item from the incoming packet
3078 static const struct ctl_var *
3080 const struct ctl_var *var_list,
3084 static const struct ctl_var eol = { 0, EOV, NULL };
3085 static char buf[128];
3086 static u_long quiet_until;
3087 const struct ctl_var *v;
3093 * Delete leading commas and white space
3095 while (reqpt < reqend && (*reqpt == ',' ||
3096 isspace((unsigned char)*reqpt)))
3098 if (reqpt >= reqend)
3101 if (NULL == var_list)
3105 * Look for a first character match on the tag. If we find
3106 * one, see if it is a full match.
3109 for (v = var_list; !(EOV & v->flags); v++) {
3110 if (!(PADDING & v->flags) && *cp == *(v->text)) {
3112 while ('\0' != *pch && '=' != *pch && cp < reqend
3117 if ('\0' == *pch || '=' == *pch) {
3118 while (cp < reqend && isspace((u_char)*cp))
3120 if (cp == reqend || ',' == *cp) {
3131 while (cp < reqend && isspace((u_char)*cp))
3133 while (cp < reqend && *cp != ',') {
3135 if ((size_t)(tp - buf) >= sizeof(buf)) {
3136 ctl_error(CERR_BADFMT);
3139 if (quiet_until <= current_time) {
3140 quiet_until = current_time + 300;
3141 msyslog(LOG_WARNING,
3142 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)", stoa(rmt_addr), SRCPORT(rmt_addr));
3150 while (tp >= buf && isspace((u_char)*tp))
3165 * control_unspec - response to an unspecified op-code
3170 struct recvbuf *rbufp,
3177 * What is an appropriate response to an unspecified op-code?
3178 * I return no errors and no data, unless a specified assocation
3182 peer = findpeerbyassoc(res_associd);
3184 ctl_error(CERR_BADASSOC);
3187 rpkt.status = htons(ctlpeerstatus(peer));
3189 rpkt.status = htons(ctlsysstatus());
3195 * read_status - return either a list of associd's, or a particular
3201 struct recvbuf *rbufp,
3208 /* a_st holds association ID, status pairs alternating */
3209 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3213 printf("read_status: ID %d\n", res_associd);
3216 * Two choices here. If the specified association ID is
3217 * zero we return all known assocation ID's. Otherwise
3218 * we return a bunch of stuff about the particular peer.
3221 peer = findpeerbyassoc(res_associd);
3223 ctl_error(CERR_BADASSOC);
3226 rpkt.status = htons(ctlpeerstatus(peer));
3228 peer->num_events = 0;
3230 * For now, output everything we know about the
3231 * peer. May be more selective later.
3233 for (cp = def_peer_var; *cp != 0; cp++)
3234 ctl_putpeer((int)*cp, peer);
3239 rpkt.status = htons(ctlsysstatus());
3240 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3241 a_st[n++] = htons(peer->associd);
3242 a_st[n++] = htons(ctlpeerstatus(peer));
3243 /* two entries each loop iteration, so n + 1 */
3244 if (n + 1 >= COUNTOF(a_st)) {
3245 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3251 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3257 * read_peervars - half of read_variables() implementation
3262 const struct ctl_var *v;
3267 u_char wants[CP_MAXCODE + 1];
3271 * Wants info for a particular peer. See if we know
3274 peer = findpeerbyassoc(res_associd);
3276 ctl_error(CERR_BADASSOC);
3279 rpkt.status = htons(ctlpeerstatus(peer));
3281 peer->num_events = 0;
3284 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3285 if (v->flags & EOV) {
3286 ctl_error(CERR_UNKNOWNVAR);
3289 INSIST(v->code < COUNTOF(wants));
3294 for (i = 1; i < COUNTOF(wants); i++)
3296 ctl_putpeer(i, peer);
3298 for (cp = def_peer_var; *cp != 0; cp++)
3299 ctl_putpeer((int)*cp, peer);
3305 * read_sysvars - half of read_variables() implementation
3310 const struct ctl_var *v;
3321 * Wants system variables. Figure out which he wants
3322 * and give them to him.
3324 rpkt.status = htons(ctlsysstatus());
3326 ctl_sys_num_events = 0;
3327 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3328 wants = emalloc_zero(wants_count);
3330 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3331 if (!(EOV & v->flags)) {
3332 INSIST(v->code < wants_count);
3336 v = ctl_getitem(ext_sys_var, &valuep);
3338 if (EOV & v->flags) {
3339 ctl_error(CERR_UNKNOWNVAR);
3343 n = v->code + CS_MAXCODE + 1;
3344 INSIST(n < wants_count);
3350 for (n = 1; n <= CS_MAXCODE; n++)
3353 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3354 if (wants[n + CS_MAXCODE + 1]) {
3355 pch = ext_sys_var[n].text;
3356 ctl_putdata(pch, strlen(pch), 0);
3359 for (cs = def_sys_var; *cs != 0; cs++)
3360 ctl_putsys((int)*cs);
3361 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3362 if (DEF & kv->flags)
3363 ctl_putdata(kv->text, strlen(kv->text),
3372 * read_variables - return the variables the caller asks for
3377 struct recvbuf *rbufp,
3389 * write_variables - write into variables. We only allow leap bit
3395 struct recvbuf *rbufp,
3399 const struct ctl_var *v;
3410 * If he's trying to write into a peer tell him no way
3412 if (res_associd != 0) {
3413 ctl_error(CERR_PERMISSION);
3420 rpkt.status = htons(ctlsysstatus());
3423 * Look through the variables. Dump out at the first sign of
3426 while ((v = ctl_getitem(sys_var, &valuep)) != 0) {
3428 if (v->flags & EOV) {
3429 if ((v = ctl_getitem(ext_sys_var, &valuep)) !=
3431 if (v->flags & EOV) {
3432 ctl_error(CERR_UNKNOWNVAR);
3440 if (!(v->flags & CAN_WRITE)) {
3441 ctl_error(CERR_PERMISSION);
3444 if (!ext_var && (*valuep == '\0' || !atoint(valuep,
3446 ctl_error(CERR_BADFMT);
3449 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) {
3450 ctl_error(CERR_BADVALUE);
3455 octets = strlen(v->text) + strlen(valuep) + 2;
3456 vareqv = emalloc(octets);
3459 while (*t && *t != '=')
3462 memcpy(tt, valuep, 1 + strlen(valuep));
3463 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3466 ctl_error(CERR_UNSPEC); /* really */
3472 * If we got anything, do it. xxx nothing to do ***
3475 if (leapind != ~0 || leapwarn != ~0) {
3476 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3477 ctl_error(CERR_PERMISSION);
3487 * configure() processes ntpq :config/config-from-file, allowing
3488 * generic runtime reconfiguration.
3490 static void configure(
3491 struct recvbuf *rbufp,
3498 /* I haven't yet implemented changes to an existing association.
3499 * Hence check if the association id is 0
3501 if (res_associd != 0) {
3502 ctl_error(CERR_BADVALUE);
3506 if (RES_NOMODIFY & restrict_mask) {
3507 snprintf(remote_config.err_msg,
3508 sizeof(remote_config.err_msg),
3509 "runtime configuration prohibited by restrict ... nomodify");
3510 ctl_putdata(remote_config.err_msg,
3511 strlen(remote_config.err_msg), 0);
3515 "runtime config from %s rejected due to nomodify restriction",
3516 stoa(&rbufp->recv_srcadr));
3521 /* Initialize the remote config buffer */
3522 data_count = remoteconfig_cmdlength(reqpt, reqend);
3524 if (data_count > sizeof(remote_config.buffer) - 2) {
3525 snprintf(remote_config.err_msg,
3526 sizeof(remote_config.err_msg),
3527 "runtime configuration failed: request too long");
3528 ctl_putdata(remote_config.err_msg,
3529 strlen(remote_config.err_msg), 0);
3532 "runtime config from %s rejected: request too long",
3533 stoa(&rbufp->recv_srcadr));
3536 /* Bug 2853 -- check if all characters were acceptable */
3537 if (data_count != (size_t)(reqend - reqpt)) {
3538 snprintf(remote_config.err_msg,
3539 sizeof(remote_config.err_msg),
3540 "runtime configuration failed: request contains an unprintable character");
3541 ctl_putdata(remote_config.err_msg,
3542 strlen(remote_config.err_msg), 0);
3545 "runtime config from %s rejected: request contains an unprintable character: %0x",
3546 stoa(&rbufp->recv_srcadr),
3551 memcpy(remote_config.buffer, reqpt, data_count);
3552 /* The buffer has no trailing linefeed or NUL right now. For
3553 * logging, we do not want a newline, so we do that first after
3554 * adding the necessary NUL byte.
3556 remote_config.buffer[data_count] = '\0';
3557 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3558 remote_config.buffer));
3559 msyslog(LOG_NOTICE, "%s config: %s",
3560 stoa(&rbufp->recv_srcadr),
3561 remote_config.buffer);
3563 /* Now we have to make sure there is a NL/NUL sequence at the
3564 * end of the buffer before we parse it.
3566 remote_config.buffer[data_count++] = '\n';
3567 remote_config.buffer[data_count] = '\0';
3568 remote_config.pos = 0;
3569 remote_config.err_pos = 0;
3570 remote_config.no_errors = 0;
3571 config_remotely(&rbufp->recv_srcadr);
3574 * Check if errors were reported. If not, output 'Config
3575 * Succeeded'. Else output the error count. It would be nice
3576 * to output any parser error messages.
3578 if (0 == remote_config.no_errors) {
3579 retval = snprintf(remote_config.err_msg,
3580 sizeof(remote_config.err_msg),
3581 "Config Succeeded");
3583 remote_config.err_pos += retval;
3586 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3589 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3591 if (remote_config.no_errors > 0)
3592 msyslog(LOG_NOTICE, "%d error in %s config",
3593 remote_config.no_errors,
3594 stoa(&rbufp->recv_srcadr));
3599 * derive_nonce - generate client-address-specific nonce value
3600 * associated with a given timestamp.
3602 static u_int32 derive_nonce(
3608 static u_int32 salt[4];
3609 static u_long last_salt_update;
3611 u_char digest[EVP_MAX_MD_SIZE];
3617 while (!salt[0] || current_time - last_salt_update >= 3600) {
3618 salt[0] = ntp_random();
3619 salt[1] = ntp_random();
3620 salt[2] = ntp_random();
3621 salt[3] = ntp_random();
3622 last_salt_update = current_time;
3625 EVP_DigestInit(&ctx, EVP_get_digestbynid(NID_md5));
3626 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3627 EVP_DigestUpdate(&ctx, &ts_i, sizeof(ts_i));
3628 EVP_DigestUpdate(&ctx, &ts_f, sizeof(ts_f));
3630 EVP_DigestUpdate(&ctx, &SOCK_ADDR4(addr),
3631 sizeof(SOCK_ADDR4(addr)));
3633 EVP_DigestUpdate(&ctx, &SOCK_ADDR6(addr),
3634 sizeof(SOCK_ADDR6(addr)));
3635 EVP_DigestUpdate(&ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3636 EVP_DigestUpdate(&ctx, salt, sizeof(salt));
3637 EVP_DigestFinal(&ctx, d.digest, &len);
3644 * generate_nonce - generate client-address-specific nonce string.
3646 static void generate_nonce(
3647 struct recvbuf * rbufp,
3654 derived = derive_nonce(&rbufp->recv_srcadr,
3655 rbufp->recv_time.l_ui,
3656 rbufp->recv_time.l_uf);
3657 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3658 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3663 * validate_nonce - validate client-address-specific nonce string.
3665 * Returns TRUE if the local calculation of the nonce matches the
3666 * client-provided value and the timestamp is recent enough.
3668 static int validate_nonce(
3669 const char * pnonce,
3670 struct recvbuf * rbufp
3680 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3683 ts.l_ui = (u_int32)ts_i;
3684 ts.l_uf = (u_int32)ts_f;
3685 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3686 get_systime(&now_delta);
3687 L_SUB(&now_delta, &ts);
3689 return (supposed == derived && now_delta.l_ui < 16);
3694 * send_random_tag_value - send a randomly-generated three character
3695 * tag prefix, a '.', an index, a '=' and a
3696 * random integer value.
3698 * To try to force clients to ignore unrecognized tags in mrulist,
3699 * reslist, and ifstats responses, the first and last rows are spiced
3700 * with randomly-generated tag names with correct .# index. Make it
3701 * three characters knowing that none of the currently-used subscripted
3702 * tags have that length, avoiding the need to test for
3706 send_random_tag_value(
3713 noise = rand() ^ (rand() << 16);
3714 buf[0] = 'a' + noise % 26;
3716 buf[1] = 'a' + noise % 26;
3718 buf[2] = 'a' + noise % 26;
3721 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3722 ctl_putuint(buf, noise);
3727 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3729 * To keep clients honest about not depending on the order of values,
3730 * and thereby avoid being locked into ugly workarounds to maintain
3731 * backward compatibility later as new fields are added to the response,
3732 * the order is random.
3740 const char first_fmt[] = "first.%d";
3741 const char ct_fmt[] = "ct.%d";
3742 const char mv_fmt[] = "mv.%d";
3743 const char rs_fmt[] = "rs.%d";
3745 u_char sent[6]; /* 6 tag=value pairs */
3751 remaining = COUNTOF(sent);
3753 noise = (u_int32)(rand() ^ (rand() << 16));
3754 while (remaining > 0) {
3755 which = (noise & 7) % COUNTOF(sent);
3758 which = (which + 1) % COUNTOF(sent);
3763 snprintf(tag, sizeof(tag), addr_fmt, count);
3764 pch = sptoa(&mon->rmtadr);
3765 ctl_putunqstr(tag, pch, strlen(pch));
3769 snprintf(tag, sizeof(tag), last_fmt, count);
3770 ctl_putts(tag, &mon->last);
3774 snprintf(tag, sizeof(tag), first_fmt, count);
3775 ctl_putts(tag, &mon->first);
3779 snprintf(tag, sizeof(tag), ct_fmt, count);
3780 ctl_putint(tag, mon->count);
3784 snprintf(tag, sizeof(tag), mv_fmt, count);
3785 ctl_putuint(tag, mon->vn_mode);
3789 snprintf(tag, sizeof(tag), rs_fmt, count);
3790 ctl_puthex(tag, mon->flags);
3800 * read_mru_list - supports ntpq's mrulist command.
3802 * The challenge here is to match ntpdc's monlist functionality without
3803 * being limited to hundreds of entries returned total, and without
3804 * requiring state on the server. If state were required, ntpq's
3805 * mrulist command would require authentication.
3807 * The approach was suggested by Ry Jones. A finite and variable number
3808 * of entries are retrieved per request, to avoid having responses with
3809 * such large numbers of packets that socket buffers are overflowed and
3810 * packets lost. The entries are retrieved oldest-first, taking into
3811 * account that the MRU list will be changing between each request. We
3812 * can expect to see duplicate entries for addresses updated in the MRU
3813 * list during the fetch operation. In the end, the client can assemble
3814 * a close approximation of the MRU list at the point in time the last
3815 * response was sent by ntpd. The only difference is it may be longer,
3816 * containing some number of oldest entries which have since been
3817 * reclaimed. If necessary, the protocol could be extended to zap those
3818 * from the client snapshot at the end, but so far that doesn't seem
3821 * To accomodate the changing MRU list, the starting point for requests
3822 * after the first request is supplied as a series of last seen
3823 * timestamps and associated addresses, the newest ones the client has
3824 * received. As long as at least one of those entries hasn't been
3825 * bumped to the head of the MRU list, ntpd can pick up at that point.
3826 * Otherwise, the request is failed and it is up to ntpq to back up and
3827 * provide the next newest entry's timestamps and addresses, conceivably
3828 * backing up all the way to the starting point.
3831 * nonce= Regurgitated nonce retrieved by the client
3832 * previously using CTL_OP_REQ_NONCE, demonstrating
3833 * ability to receive traffic sent to its address.
3834 * frags= Limit on datagrams (fragments) in response. Used
3835 * by newer ntpq versions instead of limit= when
3836 * retrieving multiple entries.
3837 * limit= Limit on MRU entries returned. One of frags= or
3838 * limit= must be provided.
3839 * limit=1 is a special case: Instead of fetching
3840 * beginning with the supplied starting point's
3841 * newer neighbor, fetch the supplied entry, and
3842 * in that case the #.last timestamp can be zero.
3843 * This enables fetching a single entry by IP
3844 * address. When limit is not one and frags= is
3845 * provided, the fragment limit controls.
3846 * mincount= (decimal) Return entries with count >= mincount.
3847 * laddr= Return entries associated with the server's IP
3848 * address given. No port specification is needed,
3849 * and any supplied is ignored.
3850 * resall= 0x-prefixed hex restrict bits which must all be
3851 * lit for an MRU entry to be included.
3852 * Has precedence over any resany=.
3853 * resany= 0x-prefixed hex restrict bits, at least one of
3854 * which must be list for an MRU entry to be
3856 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3857 * which client previously received.
3858 * addr.0= text of newest entry's IP address and port,
3859 * IPv6 addresses in bracketed form: [::]:123
3860 * last.1= timestamp of 2nd newest entry client has.
3861 * addr.1= address of 2nd newest entry.
3864 * ntpq provides as many last/addr pairs as will fit in a single request
3865 * packet, except for the first request in a MRU fetch operation.
3867 * The response begins with a new nonce value to be used for any
3868 * followup request. Following the nonce is the next newer entry than
3869 * referred to by last.0 and addr.0, if the "0" entry has not been
3870 * bumped to the front. If it has, the first entry returned will be the
3871 * next entry newer than referred to by last.1 and addr.1, and so on.
3872 * If none of the referenced entries remain unchanged, the request fails
3873 * and ntpq backs up to the next earlier set of entries to resync.
3875 * Except for the first response, the response begins with confirmation
3876 * of the entry that precedes the first additional entry provided:
3878 * last.older= hex l_fp timestamp matching one of the input
3879 * .last timestamps, which entry now precedes the
3880 * response 0. entry in the MRU list.
3881 * addr.older= text of address corresponding to older.last.
3883 * And in any case, a successful response contains sets of values
3884 * comprising entries, with the oldest numbered 0 and incrementing from
3887 * addr.# text of IPv4 or IPv6 address and port
3888 * last.# hex l_fp timestamp of last receipt
3889 * first.# hex l_fp timestamp of first receipt
3890 * ct.# count of packets received
3891 * mv.# mode and version
3892 * rs.# restriction mask (RES_* bits)
3894 * Note the code currently assumes there are no valid three letter
3895 * tags sent with each row, and needs to be adjusted if that changes.
3897 * The client should accept the values in any order, and ignore .#
3898 * values which it does not understand, to allow a smooth path to
3899 * future changes without requiring a new opcode. Clients can rely
3900 * on all *.0 values preceding any *.1 values, that is all values for
3901 * a given index number are together in the response.
3903 * The end of the response list is noted with one or two tag=value
3904 * pairs. Unconditionally:
3906 * now= 0x-prefixed l_fp timestamp at the server marking
3907 * the end of the operation.
3909 * If any entries were returned, now= is followed by:
3911 * last.newest= hex l_fp identical to last.# of the prior
3914 static void read_mru_list(
3915 struct recvbuf *rbufp,
3919 const char nonce_text[] = "nonce";
3920 const char frags_text[] = "frags";
3921 const char limit_text[] = "limit";
3922 const char mincount_text[] = "mincount";
3923 const char resall_text[] = "resall";
3924 const char resany_text[] = "resany";
3925 const char maxlstint_text[] = "maxlstint";
3926 const char laddr_text[] = "laddr";
3927 const char resaxx_fmt[] = "0x%hx";
3935 struct interface * lcladr;
3940 sockaddr_u addr[COUNTOF(last)];
3942 struct ctl_var * in_parms;
3943 const struct ctl_var * v;
3952 mon_entry * prior_mon;
3955 if (RES_NOMRULIST & restrict_mask) {
3956 ctl_error(CERR_PERMISSION);
3959 "mrulist from %s rejected due to nomrulist restriction",
3960 stoa(&rbufp->recv_srcadr));
3965 * fill in_parms var list with all possible input parameters.
3968 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
3969 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
3970 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
3971 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
3972 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
3973 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
3974 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
3975 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
3976 for (i = 0; i < COUNTOF(last); i++) {
3977 snprintf(buf, sizeof(buf), last_fmt, (int)i);
3978 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3979 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
3980 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3983 /* decode input parms */
3996 while (NULL != (v = ctl_getitem(in_parms, &val)) &&
3997 !(EOV & v->flags)) {
4000 if (!strcmp(nonce_text, v->text)) {
4003 pnonce = estrdup(val);
4004 } else if (!strcmp(frags_text, v->text)) {
4005 sscanf(val, "%hu", &frags);
4006 } else if (!strcmp(limit_text, v->text)) {
4007 sscanf(val, "%u", &limit);
4008 } else if (!strcmp(mincount_text, v->text)) {
4009 if (1 != sscanf(val, "%d", &mincount) ||
4012 } else if (!strcmp(resall_text, v->text)) {
4013 sscanf(val, resaxx_fmt, &resall);
4014 } else if (!strcmp(resany_text, v->text)) {
4015 sscanf(val, resaxx_fmt, &resany);
4016 } else if (!strcmp(maxlstint_text, v->text)) {
4017 sscanf(val, "%u", &maxlstint);
4018 } else if (!strcmp(laddr_text, v->text)) {
4019 if (decodenetnum(val, &laddr))
4020 lcladr = getinterface(&laddr, 0);
4021 } else if (1 == sscanf(v->text, last_fmt, &si) &&
4022 (size_t)si < COUNTOF(last)) {
4023 if (2 == sscanf(val, "0x%08x.%08x", &ui, &uf)) {
4026 if (!SOCK_UNSPEC(&addr[si]) &&
4030 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
4031 (size_t)si < COUNTOF(addr)) {
4032 if (decodenetnum(val, &addr[si])
4033 && last[si].l_ui && last[si].l_uf &&
4038 free_varlist(in_parms);
4041 /* return no responses until the nonce is validated */
4045 nonce_valid = validate_nonce(pnonce, rbufp);
4050 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
4051 frags > MRU_FRAGS_LIMIT) {
4052 ctl_error(CERR_BADVALUE);
4057 * If either frags or limit is not given, use the max.
4059 if (0 != frags && 0 == limit)
4061 else if (0 != limit && 0 == frags)
4062 frags = MRU_FRAGS_LIMIT;
4065 * Find the starting point if one was provided.
4068 for (i = 0; i < (size_t)priors; i++) {
4069 hash = MON_HASH(&addr[i]);
4070 for (mon = mon_hash[hash];
4072 mon = mon->hash_next)
4073 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
4076 if (L_ISEQU(&mon->last, &last[i]))
4082 /* If a starting point was provided... */
4084 /* and none could be found unmodified... */
4086 /* tell ntpq to try again with older entries */
4087 ctl_error(CERR_UNKNOWNVAR);
4090 /* confirm the prior entry used as starting point */
4091 ctl_putts("last.older", &mon->last);
4092 pch = sptoa(&mon->rmtadr);
4093 ctl_putunqstr("addr.older", pch, strlen(pch));
4096 * Move on to the first entry the client doesn't have,
4097 * except in the special case of a limit of one. In
4098 * that case return the starting point entry.
4101 mon = PREV_DLIST(mon_mru_list, mon, mru);
4102 } else { /* start with the oldest */
4103 mon = TAIL_DLIST(mon_mru_list, mru);
4107 * send up to limit= entries in up to frags= datagrams
4110 generate_nonce(rbufp, buf, sizeof(buf));
4111 ctl_putunqstr("nonce", buf, strlen(buf));
4114 mon != NULL && res_frags < frags && count < limit;
4115 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
4117 if (mon->count < mincount)
4119 if (resall && resall != (resall & mon->flags))
4121 if (resany && !(resany & mon->flags))
4123 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
4126 if (lcladr != NULL && mon->lcladr != lcladr)
4129 send_mru_entry(mon, count);
4131 send_random_tag_value(0);
4137 * If this batch completes the MRU list, say so explicitly with
4138 * a now= l_fp timestamp.
4142 send_random_tag_value(count - 1);
4143 ctl_putts("now", &now);
4144 /* if any entries were returned confirm the last */
4145 if (prior_mon != NULL)
4146 ctl_putts("last.newest", &prior_mon->last);
4153 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
4155 * To keep clients honest about not depending on the order of values,
4156 * and thereby avoid being locked into ugly workarounds to maintain
4157 * backward compatibility later as new fields are added to the response,
4158 * the order is random.
4166 const char addr_fmtu[] = "addr.%u";
4167 const char bcast_fmt[] = "bcast.%u";
4168 const char en_fmt[] = "en.%u"; /* enabled */
4169 const char name_fmt[] = "name.%u";
4170 const char flags_fmt[] = "flags.%u";
4171 const char tl_fmt[] = "tl.%u"; /* ttl */
4172 const char mc_fmt[] = "mc.%u"; /* mcast count */
4173 const char rx_fmt[] = "rx.%u";
4174 const char tx_fmt[] = "tx.%u";
4175 const char txerr_fmt[] = "txerr.%u";
4176 const char pc_fmt[] = "pc.%u"; /* peer count */
4177 const char up_fmt[] = "up.%u"; /* uptime */
4179 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4186 remaining = COUNTOF(sent);
4190 while (remaining > 0) {
4191 if (noisebits < 4) {
4192 noise = rand() ^ (rand() << 16);
4195 which = (noise & 0xf) % COUNTOF(sent);
4200 which = (which + 1) % COUNTOF(sent);
4205 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4206 pch = sptoa(&la->sin);
4207 ctl_putunqstr(tag, pch, strlen(pch));
4211 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4212 if (INT_BCASTOPEN & la->flags)
4213 pch = sptoa(&la->bcast);
4216 ctl_putunqstr(tag, pch, strlen(pch));
4220 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4221 ctl_putint(tag, !la->ignore_packets);
4225 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4226 ctl_putstr(tag, la->name, strlen(la->name));
4230 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4231 ctl_puthex(tag, (u_int)la->flags);
4235 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4236 ctl_putint(tag, la->last_ttl);
4240 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4241 ctl_putint(tag, la->num_mcast);
4245 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4246 ctl_putint(tag, la->received);
4250 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4251 ctl_putint(tag, la->sent);
4255 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4256 ctl_putint(tag, la->notsent);
4260 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4261 ctl_putuint(tag, la->peercnt);
4265 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4266 ctl_putuint(tag, current_time - la->starttime);
4272 send_random_tag_value((int)ifnum);
4277 * read_ifstats - send statistics for each local address, exposed by
4282 struct recvbuf * rbufp
4289 * loop over [0..sys_ifnum] searching ep_list for each
4292 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4293 for (la = ep_list; la != NULL; la = la->elink)
4294 if (ifidx == la->ifnum)
4298 /* return stats for one local address */
4299 send_ifstats_entry(la, ifidx);
4305 sockaddrs_from_restrict_u(
4315 psaA->sa.sa_family = AF_INET;
4316 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4317 psaM->sa.sa_family = AF_INET;
4318 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4320 psaA->sa.sa_family = AF_INET6;
4321 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4322 sizeof(psaA->sa6.sin6_addr));
4323 psaM->sa.sa_family = AF_INET6;
4324 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4325 sizeof(psaA->sa6.sin6_addr));
4331 * Send a restrict entry in response to a "ntpq -c reslist" request.
4333 * To keep clients honest about not depending on the order of values,
4334 * and thereby avoid being locked into ugly workarounds to maintain
4335 * backward compatibility later as new fields are added to the response,
4336 * the order is random.
4339 send_restrict_entry(
4345 const char addr_fmtu[] = "addr.%u";
4346 const char mask_fmtu[] = "mask.%u";
4347 const char hits_fmt[] = "hits.%u";
4348 const char flags_fmt[] = "flags.%u";
4350 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4359 const char * match_str;
4360 const char * access_str;
4362 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4363 remaining = COUNTOF(sent);
4367 while (remaining > 0) {
4368 if (noisebits < 2) {
4369 noise = rand() ^ (rand() << 16);
4372 which = (noise & 0x3) % COUNTOF(sent);
4377 which = (which + 1) % COUNTOF(sent);
4382 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4384 ctl_putunqstr(tag, pch, strlen(pch));
4388 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4390 ctl_putunqstr(tag, pch, strlen(pch));
4394 snprintf(tag, sizeof(tag), hits_fmt, idx);
4395 ctl_putuint(tag, pres->count);
4399 snprintf(tag, sizeof(tag), flags_fmt, idx);
4400 match_str = res_match_flags(pres->mflags);
4401 access_str = res_access_flags(pres->flags);
4402 if ('\0' == match_str[0]) {
4406 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4407 match_str, access_str);
4410 ctl_putunqstr(tag, pch, strlen(pch));
4416 send_random_tag_value((int)idx);
4427 for ( ; pres != NULL; pres = pres->link) {
4428 send_restrict_entry(pres, ipv6, *pidx);
4435 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4438 read_addr_restrictions(
4439 struct recvbuf * rbufp
4445 send_restrict_list(restrictlist4, FALSE, &idx);
4446 send_restrict_list(restrictlist6, TRUE, &idx);
4452 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4456 struct recvbuf * rbufp,
4460 const char ifstats_s[] = "ifstats";
4461 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4462 const char addr_rst_s[] = "addr_restrictions";
4463 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4464 struct ntp_control * cpkt;
4465 u_short qdata_octets;
4468 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4469 * used only for ntpq -c ifstats. With the addition of reslist
4470 * the same opcode was generalized to retrieve ordered lists
4471 * which require authentication. The request data is empty or
4472 * contains "ifstats" (not null terminated) to retrieve local
4473 * addresses and associated stats. It is "addr_restrictions"
4474 * to retrieve the IPv4 then IPv6 remote address restrictions,
4475 * which are access control lists. Other request data return
4478 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4479 qdata_octets = ntohs(cpkt->count);
4480 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4481 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4482 read_ifstats(rbufp);
4485 if (a_r_chars == qdata_octets &&
4486 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4487 read_addr_restrictions(rbufp);
4490 ctl_error(CERR_UNKNOWNVAR);
4495 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4497 static void req_nonce(
4498 struct recvbuf * rbufp,
4504 generate_nonce(rbufp, buf, sizeof(buf));
4505 ctl_putunqstr("nonce", buf, strlen(buf));
4511 * read_clockstatus - return clock radio status
4516 struct recvbuf *rbufp,
4522 * If no refclock support, no data to return
4524 ctl_error(CERR_BADASSOC);
4526 const struct ctl_var * v;
4534 struct ctl_var * kv;
4535 struct refclockstat cs;
4537 if (res_associd != 0) {
4538 peer = findpeerbyassoc(res_associd);
4541 * Find a clock for this jerk. If the system peer
4542 * is a clock use it, else search peer_list for one.
4544 if (sys_peer != NULL && (FLAG_REFCLOCK &
4548 for (peer = peer_list;
4550 peer = peer->p_link)
4551 if (FLAG_REFCLOCK & peer->flags)
4554 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4555 ctl_error(CERR_BADASSOC);
4559 * If we got here we have a peer which is a clock. Get his
4563 refclock_control(&peer->srcadr, NULL, &cs);
4566 * Look for variables in the packet.
4568 rpkt.status = htons(ctlclkstatus(&cs));
4569 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4570 wants = emalloc_zero(wants_alloc);
4572 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4573 if (!(EOV & v->flags)) {
4574 wants[v->code] = TRUE;
4577 v = ctl_getitem(kv, &valuep);
4579 if (EOV & v->flags) {
4580 ctl_error(CERR_UNKNOWNVAR);
4582 free_varlist(cs.kv_list);
4585 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4591 for (i = 1; i <= CC_MAXCODE; i++)
4593 ctl_putclock(i, &cs, TRUE);
4595 for (i = 0; !(EOV & kv[i].flags); i++)
4596 if (wants[i + CC_MAXCODE + 1])
4597 ctl_putdata(kv[i].text,
4601 for (cc = def_clock_var; *cc != 0; cc++)
4602 ctl_putclock((int)*cc, &cs, FALSE);
4603 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4604 if (DEF & kv->flags)
4605 ctl_putdata(kv->text, strlen(kv->text),
4610 free_varlist(cs.kv_list);
4618 * write_clockstatus - we don't do this
4623 struct recvbuf *rbufp,
4627 ctl_error(CERR_PERMISSION);
4631 * Trap support from here on down. We send async trap messages when the
4632 * upper levels report trouble. Traps can by set either by control
4633 * messages or by configuration.
4636 * set_trap - set a trap in response to a control message
4640 struct recvbuf *rbufp,
4647 * See if this guy is allowed
4649 if (restrict_mask & RES_NOTRAP) {
4650 ctl_error(CERR_PERMISSION);
4655 * Determine his allowed trap type.
4657 traptype = TRAP_TYPE_PRIO;
4658 if (restrict_mask & RES_LPTRAP)
4659 traptype = TRAP_TYPE_NONPRIO;
4662 * Call ctlsettrap() to do the work. Return
4663 * an error if it can't assign the trap.
4665 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4667 ctl_error(CERR_NORESOURCE);
4673 * unset_trap - unset a trap in response to a control message
4677 struct recvbuf *rbufp,
4684 * We don't prevent anyone from removing his own trap unless the
4685 * trap is configured. Note we also must be aware of the
4686 * possibility that restriction flags were changed since this
4687 * guy last set his trap. Set the trap type based on this.
4689 traptype = TRAP_TYPE_PRIO;
4690 if (restrict_mask & RES_LPTRAP)
4691 traptype = TRAP_TYPE_NONPRIO;
4694 * Call ctlclrtrap() to clear this out.
4696 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4697 ctl_error(CERR_BADASSOC);
4703 * ctlsettrap - called to set a trap
4708 struct interface *linter,
4714 struct ctl_trap *tp;
4715 struct ctl_trap *tptouse;
4718 * See if we can find this trap. If so, we only need update
4719 * the flags and the time.
4721 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4724 case TRAP_TYPE_CONFIG:
4725 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4728 case TRAP_TYPE_PRIO:
4729 if (tp->tr_flags & TRAP_CONFIGURED)
4730 return (1); /* don't change anything */
4731 tp->tr_flags = TRAP_INUSE;
4734 case TRAP_TYPE_NONPRIO:
4735 if (tp->tr_flags & TRAP_CONFIGURED)
4736 return (1); /* don't change anything */
4737 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4740 tp->tr_settime = current_time;
4746 * First we heard of this guy. Try to find a trap structure
4747 * for him to use, clearing out lesser priority guys if we
4748 * have to. Clear out anyone who's expired while we're at it.
4751 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4753 if ((TRAP_INUSE & tp->tr_flags) &&
4754 !(TRAP_CONFIGURED & tp->tr_flags) &&
4755 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4759 if (!(TRAP_INUSE & tp->tr_flags)) {
4761 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4764 case TRAP_TYPE_CONFIG:
4765 if (tptouse == NULL) {
4769 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4770 !(TRAP_NONPRIO & tp->tr_flags))
4773 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4774 && (TRAP_NONPRIO & tp->tr_flags)) {
4778 if (tptouse->tr_origtime <
4783 case TRAP_TYPE_PRIO:
4784 if ( TRAP_NONPRIO & tp->tr_flags) {
4785 if (tptouse == NULL ||
4787 tptouse->tr_flags) &&
4788 tptouse->tr_origtime <
4794 case TRAP_TYPE_NONPRIO:
4801 * If we don't have room for him return an error.
4803 if (tptouse == NULL)
4807 * Set up this structure for him.
4809 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4810 tptouse->tr_count = tptouse->tr_resets = 0;
4811 tptouse->tr_sequence = 1;
4812 tptouse->tr_addr = *raddr;
4813 tptouse->tr_localaddr = linter;
4814 tptouse->tr_version = (u_char) version;
4815 tptouse->tr_flags = TRAP_INUSE;
4816 if (traptype == TRAP_TYPE_CONFIG)
4817 tptouse->tr_flags |= TRAP_CONFIGURED;
4818 else if (traptype == TRAP_TYPE_NONPRIO)
4819 tptouse->tr_flags |= TRAP_NONPRIO;
4826 * ctlclrtrap - called to clear a trap
4831 struct interface *linter,
4835 register struct ctl_trap *tp;
4837 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4840 if (tp->tr_flags & TRAP_CONFIGURED
4841 && traptype != TRAP_TYPE_CONFIG)
4851 * ctlfindtrap - find a trap given the remote and local addresses
4853 static struct ctl_trap *
4856 struct interface *linter
4861 for (n = 0; n < COUNTOF(ctl_traps); n++)
4862 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4863 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4864 && (linter == ctl_traps[n].tr_localaddr))
4865 return &ctl_traps[n];
4872 * report_event - report an event to the trappers
4876 int err, /* error code */
4877 struct peer *peer, /* peer structure pointer */
4878 const char *str /* protostats string */
4881 char statstr[NTP_MAXSTRLEN];
4886 * Report the error to the protostats file, system log and
4892 * Discard a system report if the number of reports of
4893 * the same type exceeds the maximum.
4895 if (ctl_sys_last_event != (u_char)err)
4896 ctl_sys_num_events= 0;
4897 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4900 ctl_sys_last_event = (u_char)err;
4901 ctl_sys_num_events++;
4902 snprintf(statstr, sizeof(statstr),
4903 "0.0.0.0 %04x %02x %s",
4904 ctlsysstatus(), err, eventstr(err));
4906 len = strlen(statstr);
4907 snprintf(statstr + len, sizeof(statstr) - len,
4911 msyslog(LOG_INFO, "%s", statstr);
4915 * Discard a peer report if the number of reports of
4916 * the same type exceeds the maximum for that peer.
4921 errlast = (u_char)err & ~PEER_EVENT;
4922 if (peer->last_event == errlast)
4923 peer->num_events = 0;
4924 if (peer->num_events >= CTL_PEER_MAXEVENTS)
4927 peer->last_event = errlast;
4929 if (ISREFCLOCKADR(&peer->srcadr))
4930 src = refnumtoa(&peer->srcadr);
4932 src = stoa(&peer->srcadr);
4934 snprintf(statstr, sizeof(statstr),
4935 "%s %04x %02x %s", src,
4936 ctlpeerstatus(peer), err, eventstr(err));
4938 len = strlen(statstr);
4939 snprintf(statstr + len, sizeof(statstr) - len,
4942 NLOG(NLOG_PEEREVENT)
4943 msyslog(LOG_INFO, "%s", statstr);
4945 record_proto_stats(statstr);
4948 printf("event at %lu %s\n", current_time, statstr);
4952 * If no trappers, return.
4954 if (num_ctl_traps <= 0)
4958 * Set up the outgoing packet variables
4960 res_opcode = CTL_OP_ASYNCMSG;
4963 res_authenticate = FALSE;
4964 datapt = rpkt.u.data;
4965 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
4966 if (!(err & PEER_EVENT)) {
4968 rpkt.status = htons(ctlsysstatus());
4970 /* Include the core system variables and the list. */
4971 for (i = 1; i <= CS_VARLIST; i++)
4974 INSIST(peer != NULL);
4975 rpkt.associd = htons(peer->associd);
4976 rpkt.status = htons(ctlpeerstatus(peer));
4978 /* Dump it all. Later, maybe less. */
4979 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
4980 ctl_putpeer(i, peer);
4983 * for clock exception events: add clock variables to
4984 * reflect info on exception
4986 if (err == PEVNT_CLOCK) {
4987 struct refclockstat cs;
4991 refclock_control(&peer->srcadr, NULL, &cs);
4993 ctl_puthex("refclockstatus",
4996 for (i = 1; i <= CC_MAXCODE; i++)
4997 ctl_putclock(i, &cs, FALSE);
4998 for (kv = cs.kv_list;
4999 kv != NULL && !(EOV & kv->flags);
5001 if (DEF & kv->flags)
5002 ctl_putdata(kv->text,
5005 free_varlist(cs.kv_list);
5007 #endif /* REFCLOCK */
5011 * We're done, return.
5018 * mprintf_event - printf-style varargs variant of report_event()
5022 int evcode, /* event code */
5023 struct peer * p, /* may be NULL */
5024 const char * fmt, /* msnprintf format */
5033 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
5035 report_event(evcode, p, msg);
5042 * ctl_clr_stats - clear stat counters
5047 ctltimereset = current_time;
5050 numctlresponses = 0;
5055 numctlinputresp = 0;
5056 numctlinputfrag = 0;
5058 numctlbadoffset = 0;
5059 numctlbadversion = 0;
5060 numctldatatooshort = 0;
5067 const struct ctl_var *k
5076 while (!(EOV & (k++)->flags))
5079 ENSURE(c <= USHRT_MAX);
5086 struct ctl_var **kv,
5096 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
5098 buf = emalloc(size);
5103 k[c + 1].text = NULL;
5104 k[c + 1].flags = EOV;
5112 struct ctl_var **kv,
5123 if (NULL == data || !size)
5128 while (!(EOV & k->flags)) {
5129 if (NULL == k->text) {
5131 memcpy(td, data, size);
5138 while (*t != '=' && *s == *t) {
5142 if (*s == *t && ((*t == '=') || !*t)) {
5143 td = erealloc((void *)(intptr_t)k->text, size);
5144 memcpy(td, data, size);
5153 td = add_var(kv, size, def);
5154 memcpy(td, data, size);
5165 set_var(&ext_sys_var, data, size, def);
5170 * get_ext_sys_var() retrieves the value of a user-defined variable or
5171 * NULL if the variable has not been setvar'd.
5174 get_ext_sys_var(const char *tag)
5182 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5183 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5184 if ('=' == v->text[c]) {
5185 val = v->text + c + 1;
5187 } else if ('\0' == v->text[c]) {
5205 for (k = kv; !(k->flags & EOV); k++)
5206 free((void *)(intptr_t)k->text);