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"
36 #include "libssl_compat.h"
39 * Structure to hold request procedure information
43 short control_code; /* defined request code */
44 #define NO_REQUEST (-1)
45 u_short flags; /* flags word */
46 /* Only one flag. Authentication required or not. */
49 void (*handler) (struct recvbuf *, int); /* handle request */
54 * Request processing routines
56 static void ctl_error (u_char);
58 static u_short ctlclkstatus (struct refclockstat *);
60 static void ctl_flushpkt (u_char);
61 static void ctl_putdata (const char *, unsigned int, int);
62 static void ctl_putstr (const char *, const char *, size_t);
63 static void ctl_putdblf (const char *, int, int, double);
64 #define ctl_putdbl(tag, d) ctl_putdblf(tag, 1, 3, d)
65 #define ctl_putdbl6(tag, d) ctl_putdblf(tag, 1, 6, d)
66 #define ctl_putsfp(tag, sfp) ctl_putdblf(tag, 0, -1, \
68 static void ctl_putuint (const char *, u_long);
69 static void ctl_puthex (const char *, u_long);
70 static void ctl_putint (const char *, long);
71 static void ctl_putts (const char *, l_fp *);
72 static void ctl_putadr (const char *, u_int32,
74 static void ctl_putrefid (const char *, u_int32);
75 static void ctl_putarray (const char *, double *, int);
76 static void ctl_putsys (int);
77 static void ctl_putpeer (int, struct peer *);
78 static void ctl_putfs (const char *, tstamp_t);
79 static void ctl_printf (const char *, ...) NTP_PRINTF(1, 2);
81 static void ctl_putclock (int, struct refclockstat *, int);
83 static const struct ctl_var *ctl_getitem(const struct ctl_var *,
85 static u_short count_var (const struct ctl_var *);
86 static void control_unspec (struct recvbuf *, int);
87 static void read_status (struct recvbuf *, int);
88 static void read_sysvars (void);
89 static void read_peervars (void);
90 static void read_variables (struct recvbuf *, int);
91 static void write_variables (struct recvbuf *, int);
92 static void read_clockstatus(struct recvbuf *, int);
93 static void write_clockstatus(struct recvbuf *, int);
94 static void set_trap (struct recvbuf *, int);
95 static void save_config (struct recvbuf *, int);
96 static void configure (struct recvbuf *, int);
97 static void send_mru_entry (mon_entry *, int);
98 static void send_random_tag_value(int);
99 static void read_mru_list (struct recvbuf *, int);
100 static void send_ifstats_entry(endpt *, u_int);
101 static void read_ifstats (struct recvbuf *);
102 static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *,
104 static void send_restrict_entry(restrict_u *, int, u_int);
105 static void send_restrict_list(restrict_u *, int, u_int *);
106 static void read_addr_restrictions(struct recvbuf *);
107 static void read_ordlist (struct recvbuf *, int);
108 static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32);
109 static void generate_nonce (struct recvbuf *, char *, size_t);
110 static int validate_nonce (const char *, struct recvbuf *);
111 static void req_nonce (struct recvbuf *, int);
112 static void unset_trap (struct recvbuf *, int);
113 static struct ctl_trap *ctlfindtrap(sockaddr_u *,
116 int/*BOOL*/ is_safe_filename(const char * name);
118 static const struct ctl_proc control_codes[] = {
119 { CTL_OP_UNSPEC, NOAUTH, control_unspec },
120 { CTL_OP_READSTAT, NOAUTH, read_status },
121 { CTL_OP_READVAR, NOAUTH, read_variables },
122 { CTL_OP_WRITEVAR, AUTH, write_variables },
123 { CTL_OP_READCLOCK, NOAUTH, read_clockstatus },
124 { CTL_OP_WRITECLOCK, AUTH, write_clockstatus },
125 { CTL_OP_SETTRAP, AUTH, set_trap },
126 { CTL_OP_CONFIGURE, AUTH, configure },
127 { CTL_OP_SAVECONFIG, AUTH, save_config },
128 { CTL_OP_READ_MRU, NOAUTH, read_mru_list },
129 { CTL_OP_READ_ORDLIST_A, AUTH, read_ordlist },
130 { CTL_OP_REQ_NONCE, NOAUTH, req_nonce },
131 { CTL_OP_UNSETTRAP, AUTH, unset_trap },
132 { NO_REQUEST, 0, NULL }
136 * System variables we understand
140 #define CS_PRECISION 3
141 #define CS_ROOTDELAY 4
142 #define CS_ROOTDISPERSION 5
152 #define CS_PROCESSOR 15
154 #define CS_VERSION 17
156 #define CS_VARLIST 19
158 #define CS_LEAPTAB 21
159 #define CS_LEAPEND 22
161 #define CS_MRU_ENABLED 24
162 #define CS_MRU_DEPTH 25
163 #define CS_MRU_DEEPEST 26
164 #define CS_MRU_MINDEPTH 27
165 #define CS_MRU_MAXAGE 28
166 #define CS_MRU_MAXDEPTH 29
167 #define CS_MRU_MEM 30
168 #define CS_MRU_MAXMEM 31
169 #define CS_SS_UPTIME 32
170 #define CS_SS_RESET 33
171 #define CS_SS_RECEIVED 34
172 #define CS_SS_THISVER 35
173 #define CS_SS_OLDVER 36
174 #define CS_SS_BADFORMAT 37
175 #define CS_SS_BADAUTH 38
176 #define CS_SS_DECLINED 39
177 #define CS_SS_RESTRICTED 40
178 #define CS_SS_LIMITED 41
179 #define CS_SS_KODSENT 42
180 #define CS_SS_PROCESSED 43
181 #define CS_PEERADR 44
182 #define CS_PEERMODE 45
183 #define CS_BCASTDELAY 46
184 #define CS_AUTHDELAY 47
185 #define CS_AUTHKEYS 48
186 #define CS_AUTHFREEK 49
187 #define CS_AUTHKLOOKUPS 50
188 #define CS_AUTHKNOTFOUND 51
189 #define CS_AUTHKUNCACHED 52
190 #define CS_AUTHKEXPIRED 53
191 #define CS_AUTHENCRYPTS 54
192 #define CS_AUTHDECRYPTS 55
193 #define CS_AUTHRESET 56
194 #define CS_K_OFFSET 57
196 #define CS_K_MAXERR 59
197 #define CS_K_ESTERR 60
198 #define CS_K_STFLAGS 61
199 #define CS_K_TIMECONST 62
200 #define CS_K_PRECISION 63
201 #define CS_K_FREQTOL 64
202 #define CS_K_PPS_FREQ 65
203 #define CS_K_PPS_STABIL 66
204 #define CS_K_PPS_JITTER 67
205 #define CS_K_PPS_CALIBDUR 68
206 #define CS_K_PPS_CALIBS 69
207 #define CS_K_PPS_CALIBERRS 70
208 #define CS_K_PPS_JITEXC 71
209 #define CS_K_PPS_STBEXC 72
210 #define CS_KERN_FIRST CS_K_OFFSET
211 #define CS_KERN_LAST CS_K_PPS_STBEXC
212 #define CS_IOSTATS_RESET 73
213 #define CS_TOTAL_RBUF 74
214 #define CS_FREE_RBUF 75
215 #define CS_USED_RBUF 76
216 #define CS_RBUF_LOWATER 77
217 #define CS_IO_DROPPED 78
218 #define CS_IO_IGNORED 79
219 #define CS_IO_RECEIVED 80
220 #define CS_IO_SENT 81
221 #define CS_IO_SENDFAILED 82
222 #define CS_IO_WAKEUPS 83
223 #define CS_IO_GOODWAKEUPS 84
224 #define CS_TIMERSTATS_RESET 85
225 #define CS_TIMER_OVERRUNS 86
226 #define CS_TIMER_XMTS 87
228 #define CS_WANDER_THRESH 89
229 #define CS_LEAPSMEARINTV 90
230 #define CS_LEAPSMEAROFFS 91
231 #define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS
233 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
234 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
235 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
236 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
237 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
238 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
239 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
240 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
241 #define CS_MAXCODE CS_DIGEST
242 #else /* !AUTOKEY follows */
243 #define CS_MAXCODE CS_MAX_NOAUTOKEY
244 #endif /* !AUTOKEY */
247 * Peer variables we understand
250 #define CP_AUTHENABLE 2
251 #define CP_AUTHENTIC 3
258 #define CP_STRATUM 10
261 #define CP_PRECISION 13
262 #define CP_ROOTDELAY 14
263 #define CP_ROOTDISPERSION 15
265 #define CP_REFTIME 17
270 #define CP_UNREACH 22
275 #define CP_DISPERSION 27
277 #define CP_FILTDELAY 29
278 #define CP_FILTOFFSET 30
280 #define CP_RECEIVED 32
282 #define CP_FILTERROR 34
285 #define CP_VARLIST 37
290 #define CP_SRCHOST 42
291 #define CP_TIMEREC 43
292 #define CP_TIMEREACH 44
293 #define CP_BADAUTH 45
294 #define CP_BOGUSORG 46
296 #define CP_SELDISP 48
297 #define CP_SELBROKEN 49
298 #define CP_CANDIDATE 50
299 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
301 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
302 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
303 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
304 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
305 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
306 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
307 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
308 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
309 #define CP_MAXCODE CP_IDENT
310 #else /* !AUTOKEY follows */
311 #define CP_MAXCODE CP_MAX_NOAUTOKEY
312 #endif /* !AUTOKEY */
315 * Clock variables we understand
318 #define CC_TIMECODE 2
321 #define CC_BADFORMAT 5
323 #define CC_FUDGETIME1 7
324 #define CC_FUDGETIME2 8
325 #define CC_FUDGEVAL1 9
326 #define CC_FUDGEVAL2 10
329 #define CC_VARLIST 13
330 #define CC_MAXCODE CC_VARLIST
333 * System variable values. The array can be indexed by the variable
334 * index to find the textual name.
336 static const struct ctl_var sys_var[] = {
337 { 0, PADDING, "" }, /* 0 */
338 { CS_LEAP, RW, "leap" }, /* 1 */
339 { CS_STRATUM, RO, "stratum" }, /* 2 */
340 { CS_PRECISION, RO, "precision" }, /* 3 */
341 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
342 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
343 { CS_REFID, RO, "refid" }, /* 6 */
344 { CS_REFTIME, RO, "reftime" }, /* 7 */
345 { CS_POLL, RO, "tc" }, /* 8 */
346 { CS_PEERID, RO, "peer" }, /* 9 */
347 { CS_OFFSET, RO, "offset" }, /* 10 */
348 { CS_DRIFT, RO, "frequency" }, /* 11 */
349 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
350 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
351 { CS_CLOCK, RO, "clock" }, /* 14 */
352 { CS_PROCESSOR, RO, "processor" }, /* 15 */
353 { CS_SYSTEM, RO, "system" }, /* 16 */
354 { CS_VERSION, RO, "version" }, /* 17 */
355 { CS_STABIL, RO, "clk_wander" }, /* 18 */
356 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
357 { CS_TAI, RO, "tai" }, /* 20 */
358 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
359 { CS_LEAPEND, RO, "expire" }, /* 22 */
360 { CS_RATE, RO, "mintc" }, /* 23 */
361 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
362 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
363 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
364 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
365 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
366 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
367 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
368 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
369 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
370 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
371 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
372 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
373 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
374 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
375 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
376 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
377 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
378 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
379 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
380 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
381 { CS_PEERADR, RO, "peeradr" }, /* 44 */
382 { CS_PEERMODE, RO, "peermode" }, /* 45 */
383 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 46 */
384 { CS_AUTHDELAY, RO, "authdelay" }, /* 47 */
385 { CS_AUTHKEYS, RO, "authkeys" }, /* 48 */
386 { CS_AUTHFREEK, RO, "authfreek" }, /* 49 */
387 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 50 */
388 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 51 */
389 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 52 */
390 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 53 */
391 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 54 */
392 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 55 */
393 { CS_AUTHRESET, RO, "authreset" }, /* 56 */
394 { CS_K_OFFSET, RO, "koffset" }, /* 57 */
395 { CS_K_FREQ, RO, "kfreq" }, /* 58 */
396 { CS_K_MAXERR, RO, "kmaxerr" }, /* 59 */
397 { CS_K_ESTERR, RO, "kesterr" }, /* 60 */
398 { CS_K_STFLAGS, RO, "kstflags" }, /* 61 */
399 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 62 */
400 { CS_K_PRECISION, RO, "kprecis" }, /* 63 */
401 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 64 */
402 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 65 */
403 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 66 */
404 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 67 */
405 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 68 */
406 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 69 */
407 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 70 */
408 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 71 */
409 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 72 */
410 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 73 */
411 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 74 */
412 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 75 */
413 { CS_USED_RBUF, RO, "used_rbuf" }, /* 76 */
414 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 77 */
415 { CS_IO_DROPPED, RO, "io_dropped" }, /* 78 */
416 { CS_IO_IGNORED, RO, "io_ignored" }, /* 79 */
417 { CS_IO_RECEIVED, RO, "io_received" }, /* 80 */
418 { CS_IO_SENT, RO, "io_sent" }, /* 81 */
419 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 82 */
420 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 83 */
421 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 84 */
422 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 85 */
423 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 86 */
424 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 87 */
425 { CS_FUZZ, RO, "fuzz" }, /* 88 */
426 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 89 */
428 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 90 */
429 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 91 */
432 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
433 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
434 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
435 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
436 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
437 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
438 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
439 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
441 { 0, EOV, "" } /* 87/95 */
444 static struct ctl_var *ext_sys_var = NULL;
447 * System variables we print by default (in fuzzball order,
450 static const u_char def_sys_var[] = {
491 static const struct ctl_var peer_var[] = {
492 { 0, PADDING, "" }, /* 0 */
493 { CP_CONFIG, RO, "config" }, /* 1 */
494 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
495 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
496 { CP_SRCADR, RO, "srcadr" }, /* 4 */
497 { CP_SRCPORT, RO, "srcport" }, /* 5 */
498 { CP_DSTADR, RO, "dstadr" }, /* 6 */
499 { CP_DSTPORT, RO, "dstport" }, /* 7 */
500 { CP_LEAP, RO, "leap" }, /* 8 */
501 { CP_HMODE, RO, "hmode" }, /* 9 */
502 { CP_STRATUM, RO, "stratum" }, /* 10 */
503 { CP_PPOLL, RO, "ppoll" }, /* 11 */
504 { CP_HPOLL, RO, "hpoll" }, /* 12 */
505 { CP_PRECISION, RO, "precision" }, /* 13 */
506 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
507 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
508 { CP_REFID, RO, "refid" }, /* 16 */
509 { CP_REFTIME, RO, "reftime" }, /* 17 */
510 { CP_ORG, RO, "org" }, /* 18 */
511 { CP_REC, RO, "rec" }, /* 19 */
512 { CP_XMT, RO, "xleave" }, /* 20 */
513 { CP_REACH, RO, "reach" }, /* 21 */
514 { CP_UNREACH, RO, "unreach" }, /* 22 */
515 { CP_TIMER, RO, "timer" }, /* 23 */
516 { CP_DELAY, RO, "delay" }, /* 24 */
517 { CP_OFFSET, RO, "offset" }, /* 25 */
518 { CP_JITTER, RO, "jitter" }, /* 26 */
519 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
520 { CP_KEYID, RO, "keyid" }, /* 28 */
521 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
522 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
523 { CP_PMODE, RO, "pmode" }, /* 31 */
524 { CP_RECEIVED, RO, "received"}, /* 32 */
525 { CP_SENT, RO, "sent" }, /* 33 */
526 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
527 { CP_FLASH, RO, "flash" }, /* 35 */
528 { CP_TTL, RO, "ttl" }, /* 36 */
529 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
530 { CP_IN, RO, "in" }, /* 38 */
531 { CP_OUT, RO, "out" }, /* 39 */
532 { CP_RATE, RO, "headway" }, /* 40 */
533 { CP_BIAS, RO, "bias" }, /* 41 */
534 { CP_SRCHOST, RO, "srchost" }, /* 42 */
535 { CP_TIMEREC, RO, "timerec" }, /* 43 */
536 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
537 { CP_BADAUTH, RO, "badauth" }, /* 45 */
538 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
539 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
540 { CP_SELDISP, RO, "seldisp" }, /* 48 */
541 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
542 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
544 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
545 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
546 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
547 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
548 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
549 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
550 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
551 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
553 { 0, EOV, "" } /* 50/58 */
558 * Peer variables we print by default
560 static const u_char def_peer_var[] = {
609 * Clock variable list
611 static const struct ctl_var clock_var[] = {
612 { 0, PADDING, "" }, /* 0 */
613 { CC_TYPE, RO, "type" }, /* 1 */
614 { CC_TIMECODE, RO, "timecode" }, /* 2 */
615 { CC_POLL, RO, "poll" }, /* 3 */
616 { CC_NOREPLY, RO, "noreply" }, /* 4 */
617 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
618 { CC_BADDATA, RO, "baddata" }, /* 6 */
619 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
620 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
621 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
622 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
623 { CC_FLAGS, RO, "flags" }, /* 11 */
624 { CC_DEVICE, RO, "device" }, /* 12 */
625 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
626 { 0, EOV, "" } /* 14 */
631 * Clock variables printed by default
633 static const u_char def_clock_var[] = {
635 CC_TYPE, /* won't be output if device = known */
651 * MRU string constants shared by send_mru_entry() and read_mru_list().
653 static const char addr_fmt[] = "addr.%d";
654 static const char last_fmt[] = "last.%d";
657 * System and processor definitions.
661 # define STR_SYSTEM "UNIX"
663 # ifndef STR_PROCESSOR
664 # define STR_PROCESSOR "unknown"
667 static const char str_system[] = STR_SYSTEM;
668 static const char str_processor[] = STR_PROCESSOR;
670 # include <sys/utsname.h>
671 static struct utsname utsnamebuf;
672 #endif /* HAVE_UNAME */
675 * Trap structures. We only allow a few of these, and send a copy of
676 * each async message to each live one. Traps time out after an hour, it
677 * is up to the trap receipient to keep resetting it to avoid being
681 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
685 * Type bits, for ctlsettrap() call.
687 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
688 #define TRAP_TYPE_PRIO 1 /* priority trap */
689 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
693 * List relating reference clock types to control message time sources.
694 * Index by the reference clock type. This list will only be used iff
695 * the reference clock driver doesn't set peer->sstclktype to something
696 * different than CTL_SST_TS_UNSPEC.
699 static const u_char clocktypes[] = {
700 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
701 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
702 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
703 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
704 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
705 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
706 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
707 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
708 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
709 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
710 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
711 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
712 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
713 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
714 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
715 CTL_SST_TS_NTP, /* not used (15) */
716 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
717 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
718 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
719 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
720 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
721 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
722 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
723 CTL_SST_TS_NTP, /* not used (23) */
724 CTL_SST_TS_NTP, /* not used (24) */
725 CTL_SST_TS_NTP, /* not used (25) */
726 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
727 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
728 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
729 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
730 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
731 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
732 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
733 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
734 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
735 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
736 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
737 CTL_SST_TS_LF, /* REFCLK_FG (37) */
738 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
739 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
740 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
741 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
742 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
743 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
744 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
745 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
746 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
748 #endif /* REFCLOCK */
752 * Keyid used for authenticating write requests.
754 keyid_t ctl_auth_keyid;
757 * We keep track of the last error reported by the system internally
759 static u_char ctl_sys_last_event;
760 static u_char ctl_sys_num_events;
764 * Statistic counters to keep track of requests and responses.
766 u_long ctltimereset; /* time stats reset */
767 u_long numctlreq; /* number of requests we've received */
768 u_long numctlbadpkts; /* number of bad control packets */
769 u_long numctlresponses; /* number of resp packets sent with data */
770 u_long numctlfrags; /* number of fragments sent */
771 u_long numctlerrors; /* number of error responses sent */
772 u_long numctltooshort; /* number of too short input packets */
773 u_long numctlinputresp; /* number of responses on input */
774 u_long numctlinputfrag; /* number of fragments on input */
775 u_long numctlinputerr; /* number of input pkts with err bit set */
776 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
777 u_long numctlbadversion; /* number of input pkts with unknown version */
778 u_long numctldatatooshort; /* data too short for count */
779 u_long numctlbadop; /* bad op code found in packet */
780 u_long numasyncmsgs; /* number of async messages we've sent */
783 * Response packet used by these routines. Also some state information
784 * so that we can handle packet formatting within a common set of
785 * subroutines. Note we try to enter data in place whenever possible,
786 * but the need to set the more bit correctly means we occasionally
787 * use the extra buffer and copy.
789 static struct ntp_control rpkt;
790 static u_char res_version;
791 static u_char res_opcode;
792 static associd_t res_associd;
793 static u_short res_frags; /* datagrams in this response */
794 static int res_offset; /* offset of payload in response */
795 static u_char * datapt;
796 static u_char * dataend;
797 static int datalinelen;
798 static int datasent; /* flag to avoid initial ", " */
799 static int datanotbinflag;
800 static sockaddr_u *rmt_addr;
801 static struct interface *lcl_inter;
803 static u_char res_authenticate;
804 static u_char res_authokay;
805 static keyid_t res_keyid;
807 #define MAXDATALINELEN (72)
809 static u_char res_async; /* sending async trap response? */
812 * Pointers for saving state when decoding request packets
818 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
822 * init_control - initialize request data
831 #endif /* HAVE_UNAME */
836 ctl_sys_last_event = EVNT_UNSPEC;
837 ctl_sys_num_events = 0;
840 for (i = 0; i < COUNTOF(ctl_traps); i++)
841 ctl_traps[i].tr_flags = 0;
846 * ctl_error - send an error response for the current request
856 DPRINTF(3, ("sending control error %u\n", errcode));
859 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
860 * have already been filled in.
862 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
863 (res_opcode & CTL_OP_MASK);
864 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
868 * send packet and bump counters
870 if (res_authenticate && sys_authenticate) {
871 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
873 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
874 CTL_HEADER_LEN + maclen);
876 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
881 is_safe_filename(const char * name)
883 /* We need a strict validation of filenames we should write: The
884 * daemon might run with special permissions and is remote
885 * controllable, so we better take care what we allow as file
888 * The first character must be digit or a letter from the ASCII
889 * base plane or a '_' ([_A-Za-z0-9]), the following characters
890 * must be from [-._+A-Za-z0-9].
892 * We do not trust the character classification much here: Since
893 * the NTP protocol makes no provisions for UTF-8 or local code
894 * pages, we strictly require the 7bit ASCII code page.
896 * The following table is a packed bit field of 128 two-bit
897 * groups. The LSB in each group tells us if a character is
898 * acceptable at the first position, the MSB if the character is
899 * accepted at any other position.
901 * This does not ensure that the file name is syntactically
902 * correct (multiple dots will not work with VMS...) but it will
903 * exclude potential globbing bombs and directory traversal. It
904 * also rules out drive selection. (For systems that have this
905 * notion, like Windows or VMS.)
907 static const uint32_t chclass[8] = {
908 0x00000000, 0x00000000,
909 0x28800000, 0x000FFFFF,
910 0xFFFFFFFC, 0xC03FFFFF,
911 0xFFFFFFFC, 0x003FFFFF
914 u_int widx, bidx, mask;
915 if ( ! (name && *name))
919 while (0 != (widx = (u_char)*name++)) {
920 bidx = (widx & 15) << 1;
922 if (widx >= sizeof(chclass)/sizeof(chclass[0]))
924 if (0 == ((chclass[widx] >> bidx) & mask))
933 * save_config - Implements ntpq -c "saveconfig <filename>"
934 * Writes current configuration including any runtime
935 * changes by ntpq's :config or config-from-file
937 * Note: There should be no buffer overflow or truncation in the
938 * processing of file names -- both cause security problems. This is bit
939 * painful to code but essential here.
943 struct recvbuf *rbufp,
947 /* block directory traversal by searching for characters that
948 * indicate directory components in a file path.
950 * Conceptually we should be searching for DIRSEP in filename,
951 * however Windows actually recognizes both forward and
952 * backslashes as equivalent directory separators at the API
953 * level. On POSIX systems we could allow '\\' but such
954 * filenames are tricky to manipulate from a shell, so just
955 * reject both types of slashes on all platforms.
957 /* TALOS-CAN-0062: block directory traversal for VMS, too */
958 static const char * illegal_in_filename =
960 ":[]" /* do not allow drive and path components here */
961 #elif defined(SYS_WINNT)
962 ":\\/" /* path and drive separators */
964 "\\/" /* separator and critical char for POSIX */
969 static const char savedconfig_eq[] = "savedconfig=";
971 /* Build a safe open mode from the available mode flags. We want
972 * to create a new file and write it in text mode (when
973 * applicable -- only Windows does this...)
975 static const int openmode = O_CREAT | O_TRUNC | O_WRONLY
976 # if defined(O_EXCL) /* posix, vms */
978 # elif defined(_O_EXCL) /* windows is alway very special... */
981 # if defined(_O_TEXT) /* windows, again */
989 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
997 if (RES_NOMODIFY & restrict_mask) {
998 ctl_printf("%s", "saveconfig prohibited by restrict ... nomodify");
1002 "saveconfig from %s rejected due to nomodify restriction",
1003 stoa(&rbufp->recv_srcadr));
1009 if (NULL == saveconfigdir) {
1010 ctl_printf("%s", "saveconfig prohibited, no saveconfigdir configured");
1014 "saveconfig from %s rejected, no saveconfigdir",
1015 stoa(&rbufp->recv_srcadr));
1019 /* The length checking stuff gets serious. Do not assume a NUL
1020 * byte can be found, but if so, use it to calculate the needed
1021 * buffer size. If the available buffer is too short, bail out;
1022 * likewise if there is no file spec. (The latter will not
1023 * happen when using NTPQ, but there are other ways to craft a
1026 reqlen = (size_t)(reqend - reqpt);
1028 char * nulpos = (char*)memchr(reqpt, 0, reqlen);
1030 reqlen = (size_t)(nulpos - reqpt);
1034 if (reqlen >= sizeof(filespec)) {
1035 ctl_printf("saveconfig exceeded maximum raw name length (%u)",
1036 (u_int)sizeof(filespec));
1039 "saveconfig exceeded maximum raw name length from %s",
1040 stoa(&rbufp->recv_srcadr));
1044 /* copy data directly as we exactly know the size */
1045 memcpy(filespec, reqpt, reqlen);
1046 filespec[reqlen] = '\0';
1049 * allow timestamping of the saved config filename with
1050 * strftime() format such as:
1051 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
1052 * XXX: Nice feature, but not too safe.
1053 * YYY: The check for permitted characters in file names should
1054 * weed out the worst. Let's hope 'strftime()' does not
1055 * develop pathological problems.
1058 if (0 == strftime(filename, sizeof(filename), filespec,
1062 * If we arrive here, 'strftime()' balked; most likely
1063 * the buffer was too short. (Or it encounterd an empty
1064 * format, or just a format that expands to an empty
1065 * string.) We try to use the original name, though this
1066 * is very likely to fail later if there are format
1067 * specs in the string. Note that truncation cannot
1068 * happen here as long as both buffers have the same
1071 strlcpy(filename, filespec, sizeof(filename));
1075 * Check the file name for sanity. This might/will rule out file
1076 * names that would be legal but problematic, and it blocks
1077 * directory traversal.
1079 if (!is_safe_filename(filename)) {
1080 ctl_printf("saveconfig rejects unsafe file name '%s'",
1084 "saveconfig rejects unsafe file name from %s",
1085 stoa(&rbufp->recv_srcadr));
1090 * XXX: This next test may not be needed with is_safe_filename()
1093 /* block directory/drive traversal */
1094 /* TALOS-CAN-0062: block directory traversal for VMS, too */
1095 if (NULL != strpbrk(filename, illegal_in_filename)) {
1096 snprintf(reply, sizeof(reply),
1097 "saveconfig does not allow directory in filename");
1098 ctl_putdata(reply, strlen(reply), 0);
1101 "saveconfig rejects unsafe file name from %s",
1102 stoa(&rbufp->recv_srcadr));
1106 /* concatenation of directory and path can cause another
1109 prc = snprintf(fullpath, sizeof(fullpath), "%s%s",
1110 saveconfigdir, filename);
1111 if (prc < 0 || prc >= sizeof(fullpath)) {
1112 ctl_printf("saveconfig exceeded maximum path length (%u)",
1113 (u_int)sizeof(fullpath));
1116 "saveconfig exceeded maximum path length from %s",
1117 stoa(&rbufp->recv_srcadr));
1121 fd = open(fullpath, openmode, S_IRUSR | S_IWUSR);
1125 fptr = fdopen(fd, "w");
1127 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
1128 ctl_printf("Unable to save configuration to file '%s': %m",
1131 "saveconfig %s from %s failed", filename,
1132 stoa(&rbufp->recv_srcadr));
1134 ctl_printf("Configuration saved to '%s'", filename);
1136 "Configuration saved to '%s' (requested by %s)",
1137 fullpath, stoa(&rbufp->recv_srcadr));
1139 * save the output filename in system variable
1140 * savedconfig, retrieved with:
1141 * ntpq -c "rv 0 savedconfig"
1142 * Note: the way 'savedconfig' is defined makes overflow
1143 * checks unnecessary here.
1145 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
1146 savedconfig_eq, filename);
1147 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1152 #else /* !SAVECONFIG follows */
1154 "saveconfig unavailable, configured with --disable-saveconfig");
1161 * process_control - process an incoming control message
1165 struct recvbuf *rbufp,
1169 struct ntp_control *pkt;
1172 const struct ctl_proc *cc;
1177 DPRINTF(3, ("in process_control()\n"));
1180 * Save the addresses for error responses
1183 rmt_addr = &rbufp->recv_srcadr;
1184 lcl_inter = rbufp->dstadr;
1185 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1188 * If the length is less than required for the header, or
1189 * it is a response or a fragment, ignore this.
1191 if (rbufp->recv_length < (int)CTL_HEADER_LEN
1192 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1193 || pkt->offset != 0) {
1194 DPRINTF(1, ("invalid format in control packet\n"));
1195 if (rbufp->recv_length < (int)CTL_HEADER_LEN)
1197 if (CTL_RESPONSE & pkt->r_m_e_op)
1199 if (CTL_MORE & pkt->r_m_e_op)
1201 if (CTL_ERROR & pkt->r_m_e_op)
1203 if (pkt->offset != 0)
1207 res_version = PKT_VERSION(pkt->li_vn_mode);
1208 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1209 DPRINTF(1, ("unknown version %d in control packet\n",
1216 * Pull enough data from the packet to make intelligent
1219 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1221 res_opcode = pkt->r_m_e_op;
1222 rpkt.sequence = pkt->sequence;
1223 rpkt.associd = pkt->associd;
1227 res_associd = htons(pkt->associd);
1229 res_authenticate = FALSE;
1231 res_authokay = FALSE;
1232 req_count = (int)ntohs(pkt->count);
1233 datanotbinflag = FALSE;
1236 datapt = rpkt.u.data;
1237 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1239 if ((rbufp->recv_length & 0x3) != 0)
1240 DPRINTF(3, ("Control packet length %d unrounded\n",
1241 rbufp->recv_length));
1244 * We're set up now. Make sure we've got at least enough
1245 * incoming data space to match the count.
1247 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1248 if (req_data < req_count || rbufp->recv_length & 0x3) {
1249 ctl_error(CERR_BADFMT);
1250 numctldatatooshort++;
1254 properlen = req_count + CTL_HEADER_LEN;
1255 /* round up proper len to a 8 octet boundary */
1257 properlen = (properlen + 7) & ~7;
1258 maclen = rbufp->recv_length - properlen;
1259 if ((rbufp->recv_length & 3) == 0 &&
1260 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1262 res_authenticate = TRUE;
1263 pkid = (void *)((char *)pkt + properlen);
1264 res_keyid = ntohl(*pkid);
1265 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1266 rbufp->recv_length, properlen, res_keyid,
1269 if (!authistrusted(res_keyid))
1270 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1271 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1272 rbufp->recv_length - maclen,
1274 res_authokay = TRUE;
1275 DPRINTF(3, ("authenticated okay\n"));
1278 DPRINTF(3, ("authentication failed\n"));
1283 * Set up translate pointers
1285 reqpt = (char *)pkt->u.data;
1286 reqend = reqpt + req_count;
1289 * Look for the opcode processor
1291 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1292 if (cc->control_code == res_opcode) {
1293 DPRINTF(3, ("opcode %d, found command handler\n",
1295 if (cc->flags == AUTH
1297 || res_keyid != ctl_auth_keyid)) {
1298 ctl_error(CERR_PERMISSION);
1301 (cc->handler)(rbufp, restrict_mask);
1307 * Can't find this one, return an error.
1310 ctl_error(CERR_BADOP);
1316 * ctlpeerstatus - return a status word for this peer
1320 register struct peer *p
1326 if (FLAG_CONFIG & p->flags)
1327 status |= CTL_PST_CONFIG;
1329 status |= CTL_PST_AUTHENABLE;
1330 if (FLAG_AUTHENTIC & p->flags)
1331 status |= CTL_PST_AUTHENTIC;
1333 status |= CTL_PST_REACH;
1334 if (MDF_TXONLY_MASK & p->cast_flags)
1335 status |= CTL_PST_BCAST;
1337 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1342 * ctlclkstatus - return a status word for this clock
1347 struct refclockstat *pcs
1350 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1356 * ctlsysstatus - return the system status word
1361 register u_char this_clock;
1363 this_clock = CTL_SST_TS_UNSPEC;
1365 if (sys_peer != NULL) {
1366 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1367 this_clock = sys_peer->sstclktype;
1368 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1369 this_clock = clocktypes[sys_peer->refclktype];
1371 #else /* REFCLOCK */
1373 this_clock = CTL_SST_TS_NTP;
1374 #endif /* REFCLOCK */
1375 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1376 ctl_sys_last_event);
1381 * ctl_flushpkt - write out the current packet and prepare
1382 * another if necessary.
1396 dlen = datapt - rpkt.u.data;
1397 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1399 * Big hack, output a trailing \r\n
1405 sendlen = dlen + CTL_HEADER_LEN;
1408 * Pad to a multiple of 32 bits
1410 while (sendlen & 0x3) {
1416 * Fill in the packet with the current info
1418 rpkt.r_m_e_op = CTL_RESPONSE | more |
1419 (res_opcode & CTL_OP_MASK);
1420 rpkt.count = htons((u_short)dlen);
1421 rpkt.offset = htons((u_short)res_offset);
1423 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1424 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1428 ctl_traps[i].tr_version,
1431 htons(ctl_traps[i].tr_sequence);
1432 sendpkt(&ctl_traps[i].tr_addr,
1433 ctl_traps[i].tr_localaddr, -4,
1434 (struct pkt *)&rpkt, sendlen);
1436 ctl_traps[i].tr_sequence++;
1441 if (res_authenticate && sys_authenticate) {
1444 * If we are going to authenticate, then there
1445 * is an additional requirement that the MAC
1446 * begin on a 64 bit boundary.
1448 while (totlen & 7) {
1452 keyid = htonl(res_keyid);
1453 memcpy(datapt, &keyid, sizeof(keyid));
1454 maclen = authencrypt(res_keyid,
1455 (u_int32 *)&rpkt, totlen);
1456 sendpkt(rmt_addr, lcl_inter, -5,
1457 (struct pkt *)&rpkt, totlen + maclen);
1459 sendpkt(rmt_addr, lcl_inter, -6,
1460 (struct pkt *)&rpkt, sendlen);
1469 * Set us up for another go around.
1473 datapt = rpkt.u.data;
1478 * ctl_putdata - write data into the packet, fragmenting and starting
1479 * another if this one is full.
1485 int bin /* set to 1 when data is binary */
1489 unsigned int currentlen;
1493 datanotbinflag = TRUE;
1498 if ((dlen + datalinelen + 1) >= MAXDATALINELEN) {
1510 * Save room for trailing junk
1512 while (dlen + overhead + datapt > dataend) {
1514 * Not enough room in this one, flush it out.
1516 currentlen = MIN(dlen, (unsigned int)(dataend - datapt));
1518 memcpy(datapt, dp, currentlen);
1520 datapt += currentlen;
1523 datalinelen += currentlen;
1525 ctl_flushpkt(CTL_MORE);
1528 memcpy(datapt, dp, dlen);
1530 datalinelen += dlen;
1536 * ctl_putstr - write a tagged string into the response packet
1541 * len is the data length excluding the NUL terminator,
1542 * as in ctl_putstr("var", "value", strlen("value"));
1556 memcpy(buffer, tag, tl);
1559 INSIST(tl + 3 + len <= sizeof(buffer));
1562 memcpy(cp, data, len);
1566 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1571 * ctl_putunqstr - write a tagged string into the response packet
1576 * len is the data length excluding the NUL terminator.
1577 * data must not contain a comma or whitespace.
1591 memcpy(buffer, tag, tl);
1594 INSIST(tl + 1 + len <= sizeof(buffer));
1596 memcpy(cp, data, len);
1599 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1604 * ctl_putdblf - write a tagged, signed double into the response packet
1623 INSIST((size_t)(cp - buffer) < sizeof(buffer));
1624 snprintf(cp, sizeof(buffer) - (cp - buffer), use_f ? "%.*f" : "%.*g",
1627 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1631 * ctl_putuint - write a tagged unsigned integer into the response
1640 register const char *cq;
1649 INSIST((cp - buffer) < (int)sizeof(buffer));
1650 snprintf(cp, sizeof(buffer) - (cp - buffer), "%lu", uval);
1652 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1656 * ctl_putcal - write a decoded calendar data into the response
1661 const struct calendar *pcal
1667 numch = snprintf(buffer, sizeof(buffer),
1668 "%s=%04d%02d%02d%02d%02d",
1676 INSIST(numch < sizeof(buffer));
1677 ctl_putdata(buffer, numch, 0);
1683 * ctl_putfs - write a decoded filestamp into the response
1692 register const char *cq;
1694 struct tm *tm = NULL;
1703 fstamp = uval - JAN_1970;
1704 tm = gmtime(&fstamp);
1707 INSIST((cp - buffer) < (int)sizeof(buffer));
1708 snprintf(cp, sizeof(buffer) - (cp - buffer),
1709 "%04d%02d%02d%02d%02d", tm->tm_year + 1900,
1710 tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);
1712 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1717 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1727 register const char *cq;
1736 INSIST((cp - buffer) < (int)sizeof(buffer));
1737 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%lx", uval);
1739 ctl_putdata(buffer,(unsigned)( cp - buffer ), 0);
1744 * ctl_putint - write a tagged signed integer into the response
1753 register const char *cq;
1762 INSIST((cp - buffer) < (int)sizeof(buffer));
1763 snprintf(cp, sizeof(buffer) - (cp - buffer), "%ld", ival);
1765 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1770 * ctl_putts - write a tagged timestamp, in hex, into the response
1779 register const char *cq;
1788 INSIST((size_t)(cp - buffer) < sizeof(buffer));
1789 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%08x.%08x",
1790 (u_int)ts->l_ui, (u_int)ts->l_uf);
1792 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0);
1797 * ctl_putadr - write an IP address into the response
1807 register const char *cq;
1817 cq = numtoa(addr32);
1820 INSIST((cp - buffer) < (int)sizeof(buffer));
1821 snprintf(cp, sizeof(buffer) - (cp - buffer), "%s", cq);
1823 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1828 * ctl_putrefid - send a u_int32 refid as printable text
1844 oplim = output + sizeof(output);
1845 while (optr < oplim && '\0' != *tag)
1851 if (!(optr < oplim))
1853 iptr = (char *)&refid;
1854 iplim = iptr + sizeof(refid);
1855 for ( ; optr < oplim && iptr < iplim && '\0' != *iptr;
1857 if (isprint((int)*iptr))
1861 if (!(optr <= oplim))
1863 ctl_putdata(output, (u_int)(optr - output), FALSE);
1868 * ctl_putarray - write a tagged eight element double array into the response
1878 register const char *cq;
1891 INSIST((cp - buffer) < (int)sizeof(buffer));
1892 snprintf(cp, sizeof(buffer) - (cp - buffer),
1893 " %.2f", arr[i] * 1e3);
1895 } while (i != start);
1896 ctl_putdata(buffer, (unsigned)(cp - buffer), 0);
1900 * ctl_printf - put a formatted string into the data buffer
1908 static const char * ellipsis = "[...]";
1914 rc = vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, va);
1916 if (rc < 0 || rc >= sizeof(fmtbuf))
1917 strcpy(fmtbuf + sizeof(fmtbuf) - strlen(ellipsis) - 1,
1919 ctl_putdata(fmtbuf, strlen(fmtbuf), 0);
1924 * ctl_putsys - output a system variable
1938 struct cert_info *cp;
1939 #endif /* AUTOKEY */
1941 static struct timex ntx;
1942 static u_long ntp_adjtime_time;
1944 static const double to_ms =
1946 1.0e-6; /* nsec to msec */
1948 1.0e-3; /* usec to msec */
1952 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1954 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1955 current_time != ntp_adjtime_time) {
1957 if (ntp_adjtime(&ntx) < 0)
1958 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1960 ntp_adjtime_time = current_time;
1962 #endif /* KERNEL_PLL */
1967 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1971 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1975 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1979 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1983 case CS_ROOTDISPERSION:
1984 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1985 sys_rootdisp * 1e3);
1989 if (sys_stratum > 1 && sys_stratum < STRATUM_UNSPEC)
1990 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1992 ctl_putrefid(sys_var[varid].text, sys_refid);
1996 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
2000 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
2004 if (sys_peer == NULL)
2005 ctl_putuint(sys_var[CS_PEERID].text, 0);
2007 ctl_putuint(sys_var[CS_PEERID].text,
2012 if (sys_peer != NULL && sys_peer->dstadr != NULL)
2013 ss = sptoa(&sys_peer->srcadr);
2016 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
2020 u = (sys_peer != NULL)
2023 ctl_putuint(sys_var[CS_PEERMODE].text, u);
2027 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
2031 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
2035 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
2039 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
2044 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
2049 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
2050 sizeof(str_processor) - 1);
2052 ctl_putstr(sys_var[CS_PROCESSOR].text,
2053 utsnamebuf.machine, strlen(utsnamebuf.machine));
2054 #endif /* HAVE_UNAME */
2059 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
2060 sizeof(str_system) - 1);
2062 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
2063 utsnamebuf.release);
2064 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
2065 #endif /* HAVE_UNAME */
2069 ctl_putstr(sys_var[CS_VERSION].text, Version,
2074 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
2080 char buf[CTL_MAX_DATA_LEN];
2081 //buffPointer, firstElementPointer, buffEndPointer
2082 char *buffp, *buffend;
2086 const struct ctl_var *k;
2089 buffend = buf + sizeof(buf);
2090 if (buffp + strlen(sys_var[CS_VARLIST].text) + 4 > buffend)
2091 break; /* really long var name */
2093 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
2094 buffp += strlen(buffp);
2095 firstVarName = TRUE;
2096 for (k = sys_var; !(k->flags & EOV); k++) {
2097 if (k->flags & PADDING)
2099 len = strlen(k->text);
2100 if (buffp + len + 1 >= buffend)
2105 firstVarName = FALSE;
2106 memcpy(buffp, k->text, len);
2110 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
2111 if (k->flags & PADDING)
2113 if (NULL == k->text)
2115 ss1 = strchr(k->text, '=');
2117 len = strlen(k->text);
2119 len = ss1 - k->text;
2120 if (buffp + len + 1 >= buffend)
2124 firstVarName = FALSE;
2126 memcpy(buffp, k->text,(unsigned)len);
2129 if (buffp + 2 >= buffend)
2135 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
2141 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
2146 leap_signature_t lsig;
2147 leapsec_getsig(&lsig);
2149 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
2155 leap_signature_t lsig;
2156 leapsec_getsig(&lsig);
2158 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2163 case CS_LEAPSMEARINTV:
2164 if (leap_smear_intv > 0)
2165 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2168 case CS_LEAPSMEAROFFS:
2169 if (leap_smear_intv > 0)
2170 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2171 leap_smear.doffset * 1e3);
2173 #endif /* LEAP_SMEAR */
2176 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2179 case CS_MRU_ENABLED:
2180 ctl_puthex(sys_var[varid].text, mon_enabled);
2184 ctl_putuint(sys_var[varid].text, mru_entries);
2188 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2192 ctl_putuint(sys_var[varid].text, u);
2195 case CS_MRU_DEEPEST:
2196 ctl_putuint(sys_var[varid].text, mru_peakentries);
2199 case CS_MRU_MINDEPTH:
2200 ctl_putuint(sys_var[varid].text, mru_mindepth);
2204 ctl_putint(sys_var[varid].text, mru_maxage);
2207 case CS_MRU_MAXDEPTH:
2208 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2212 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2216 ctl_putuint(sys_var[varid].text, u);
2220 ctl_putuint(sys_var[varid].text, current_time);
2224 ctl_putuint(sys_var[varid].text,
2225 current_time - sys_stattime);
2228 case CS_SS_RECEIVED:
2229 ctl_putuint(sys_var[varid].text, sys_received);
2233 ctl_putuint(sys_var[varid].text, sys_newversion);
2237 ctl_putuint(sys_var[varid].text, sys_oldversion);
2240 case CS_SS_BADFORMAT:
2241 ctl_putuint(sys_var[varid].text, sys_badlength);
2245 ctl_putuint(sys_var[varid].text, sys_badauth);
2248 case CS_SS_DECLINED:
2249 ctl_putuint(sys_var[varid].text, sys_declined);
2252 case CS_SS_RESTRICTED:
2253 ctl_putuint(sys_var[varid].text, sys_restricted);
2257 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2261 ctl_putuint(sys_var[varid].text, sys_kodsent);
2264 case CS_SS_PROCESSED:
2265 ctl_putuint(sys_var[varid].text, sys_processed);
2269 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2273 LFPTOD(&sys_authdelay, dtemp);
2274 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2278 ctl_putuint(sys_var[varid].text, authnumkeys);
2282 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2285 case CS_AUTHKLOOKUPS:
2286 ctl_putuint(sys_var[varid].text, authkeylookups);
2289 case CS_AUTHKNOTFOUND:
2290 ctl_putuint(sys_var[varid].text, authkeynotfound);
2293 case CS_AUTHKUNCACHED:
2294 ctl_putuint(sys_var[varid].text, authkeyuncached);
2297 case CS_AUTHKEXPIRED:
2298 ctl_putuint(sys_var[varid].text, authkeyexpired);
2301 case CS_AUTHENCRYPTS:
2302 ctl_putuint(sys_var[varid].text, authencryptions);
2305 case CS_AUTHDECRYPTS:
2306 ctl_putuint(sys_var[varid].text, authdecryptions);
2310 ctl_putuint(sys_var[varid].text,
2311 current_time - auth_timereset);
2315 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2316 * unavailable, otherwise calls putfunc with args.
2319 # define CTL_IF_KERNLOOP(putfunc, args) \
2320 ctl_putint(sys_var[varid].text, 0)
2322 # define CTL_IF_KERNLOOP(putfunc, args) \
2327 * CTL_IF_KERNPPS() puts a zero if either the kernel
2328 * loop is unavailable, or kernel hard PPS is not
2329 * active, otherwise calls putfunc with args.
2332 # define CTL_IF_KERNPPS(putfunc, args) \
2333 ctl_putint(sys_var[varid].text, 0)
2335 # define CTL_IF_KERNPPS(putfunc, args) \
2336 if (0 == ntx.shift) \
2337 ctl_putint(sys_var[varid].text, 0); \
2339 putfunc args /* no trailing ; */
2345 (sys_var[varid].text, 0, -1, to_ms * ntx.offset)
2352 (sys_var[varid].text, ntx.freq)
2359 (sys_var[varid].text, 0, 6,
2360 to_ms * ntx.maxerror)
2367 (sys_var[varid].text, 0, 6,
2368 to_ms * ntx.esterror)
2376 ss = k_st_flags(ntx.status);
2378 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2381 case CS_K_TIMECONST:
2384 (sys_var[varid].text, ntx.constant)
2388 case CS_K_PRECISION:
2391 (sys_var[varid].text, 0, 6,
2392 to_ms * ntx.precision)
2399 (sys_var[varid].text, ntx.tolerance)
2406 (sys_var[varid].text, ntx.ppsfreq)
2410 case CS_K_PPS_STABIL:
2413 (sys_var[varid].text, ntx.stabil)
2417 case CS_K_PPS_JITTER:
2420 (sys_var[varid].text, to_ms * ntx.jitter)
2424 case CS_K_PPS_CALIBDUR:
2427 (sys_var[varid].text, 1 << ntx.shift)
2431 case CS_K_PPS_CALIBS:
2434 (sys_var[varid].text, ntx.calcnt)
2438 case CS_K_PPS_CALIBERRS:
2441 (sys_var[varid].text, ntx.errcnt)
2445 case CS_K_PPS_JITEXC:
2448 (sys_var[varid].text, ntx.jitcnt)
2452 case CS_K_PPS_STBEXC:
2455 (sys_var[varid].text, ntx.stbcnt)
2459 case CS_IOSTATS_RESET:
2460 ctl_putuint(sys_var[varid].text,
2461 current_time - io_timereset);
2465 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2469 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2473 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2476 case CS_RBUF_LOWATER:
2477 ctl_putuint(sys_var[varid].text, lowater_additions());
2481 ctl_putuint(sys_var[varid].text, packets_dropped);
2485 ctl_putuint(sys_var[varid].text, packets_ignored);
2488 case CS_IO_RECEIVED:
2489 ctl_putuint(sys_var[varid].text, packets_received);
2493 ctl_putuint(sys_var[varid].text, packets_sent);
2496 case CS_IO_SENDFAILED:
2497 ctl_putuint(sys_var[varid].text, packets_notsent);
2501 ctl_putuint(sys_var[varid].text, handler_calls);
2504 case CS_IO_GOODWAKEUPS:
2505 ctl_putuint(sys_var[varid].text, handler_pkts);
2508 case CS_TIMERSTATS_RESET:
2509 ctl_putuint(sys_var[varid].text,
2510 current_time - timer_timereset);
2513 case CS_TIMER_OVERRUNS:
2514 ctl_putuint(sys_var[varid].text, alarm_overflow);
2518 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2522 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2524 case CS_WANDER_THRESH:
2525 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2530 ctl_puthex(sys_var[CS_FLAGS].text,
2536 strlcpy(str, OBJ_nid2ln(crypto_nid),
2538 ctl_putstr(sys_var[CS_DIGEST].text, str,
2547 dp = EVP_get_digestbynid(crypto_flags >> 16);
2548 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2550 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2556 if (hostval.ptr != NULL)
2557 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2558 strlen(hostval.ptr));
2562 if (sys_ident != NULL)
2563 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2568 for (cp = cinfo; cp != NULL; cp = cp->link) {
2569 snprintf(str, sizeof(str), "%s %s 0x%x",
2570 cp->subject, cp->issuer, cp->flags);
2571 ctl_putstr(sys_var[CS_CERTIF].text, str,
2573 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2578 if (hostval.tstamp != 0)
2579 ctl_putfs(sys_var[CS_PUBLIC].text,
2580 ntohl(hostval.tstamp));
2582 #endif /* AUTOKEY */
2591 * ctl_putpeer - output a peer variable
2599 char buf[CTL_MAX_DATA_LEN];
2604 const struct ctl_var *k;
2609 #endif /* AUTOKEY */
2614 ctl_putuint(peer_var[id].text,
2615 !(FLAG_PREEMPT & p->flags));
2619 ctl_putuint(peer_var[id].text, !(p->keyid));
2623 ctl_putuint(peer_var[id].text,
2624 !!(FLAG_AUTHENTIC & p->flags));
2628 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2632 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2636 if (p->hostname != NULL)
2637 ctl_putstr(peer_var[id].text, p->hostname,
2638 strlen(p->hostname));
2642 ctl_putadr(peer_var[id].text, 0,
2649 ctl_putuint(peer_var[id].text,
2651 ? SRCPORT(&p->dstadr->sin)
2657 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2662 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2666 ctl_putuint(peer_var[id].text, p->throttle);
2670 ctl_putuint(peer_var[id].text, p->leap);
2674 ctl_putuint(peer_var[id].text, p->hmode);
2678 ctl_putuint(peer_var[id].text, p->stratum);
2682 ctl_putuint(peer_var[id].text, p->ppoll);
2686 ctl_putuint(peer_var[id].text, p->hpoll);
2690 ctl_putint(peer_var[id].text, p->precision);
2694 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2697 case CP_ROOTDISPERSION:
2698 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2703 if (p->flags & FLAG_REFCLOCK) {
2704 ctl_putrefid(peer_var[id].text, p->refid);
2708 if (p->stratum > 1 && p->stratum < STRATUM_UNSPEC)
2709 ctl_putadr(peer_var[id].text, p->refid,
2712 ctl_putrefid(peer_var[id].text, p->refid);
2716 ctl_putts(peer_var[id].text, &p->reftime);
2720 ctl_putts(peer_var[id].text, &p->aorg);
2724 ctl_putts(peer_var[id].text, &p->dst);
2729 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2734 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2738 ctl_puthex(peer_var[id].text, p->reach);
2742 ctl_puthex(peer_var[id].text, p->flash);
2747 if (p->flags & FLAG_REFCLOCK) {
2748 ctl_putuint(peer_var[id].text, p->ttl);
2752 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2753 ctl_putint(peer_var[id].text,
2758 ctl_putuint(peer_var[id].text, p->unreach);
2762 ctl_putuint(peer_var[id].text,
2763 p->nextdate - current_time);
2767 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2771 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2775 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2779 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2783 if (p->keyid > NTP_MAXKEY)
2784 ctl_puthex(peer_var[id].text, p->keyid);
2786 ctl_putuint(peer_var[id].text, p->keyid);
2790 ctl_putarray(peer_var[id].text, p->filter_delay,
2795 ctl_putarray(peer_var[id].text, p->filter_offset,
2800 ctl_putarray(peer_var[id].text, p->filter_disp,
2805 ctl_putuint(peer_var[id].text, p->pmode);
2809 ctl_putuint(peer_var[id].text, p->received);
2813 ctl_putuint(peer_var[id].text, p->sent);
2818 be = buf + sizeof(buf);
2819 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2820 break; /* really long var name */
2822 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2825 for (k = peer_var; !(EOV & k->flags); k++) {
2826 if (PADDING & k->flags)
2828 i = strlen(k->text);
2829 if (s + i + 1 >= be)
2833 memcpy(s, k->text, i);
2839 ctl_putdata(buf, (u_int)(s - buf), 0);
2844 ctl_putuint(peer_var[id].text,
2845 current_time - p->timereceived);
2849 ctl_putuint(peer_var[id].text,
2850 current_time - p->timereachable);
2854 ctl_putuint(peer_var[id].text, p->badauth);
2858 ctl_putuint(peer_var[id].text, p->bogusorg);
2862 ctl_putuint(peer_var[id].text, p->oldpkt);
2866 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2870 ctl_putuint(peer_var[id].text, p->selbroken);
2874 ctl_putuint(peer_var[id].text, p->status);
2879 ctl_puthex(peer_var[id].text, p->crypto);
2884 dp = EVP_get_digestbynid(p->crypto >> 16);
2885 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2886 ctl_putstr(peer_var[id].text, str, strlen(str));
2891 if (p->subject != NULL)
2892 ctl_putstr(peer_var[id].text, p->subject,
2893 strlen(p->subject));
2896 case CP_VALID: /* not used */
2900 if (NULL == (ap = p->recval.ptr))
2903 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2904 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2905 ctl_putfs(peer_var[CP_INITTSP].text,
2906 ntohl(p->recval.tstamp));
2910 if (p->ident != NULL)
2911 ctl_putstr(peer_var[id].text, p->ident,
2916 #endif /* AUTOKEY */
2923 * ctl_putclock - output clock variables
2928 struct refclockstat *pcs,
2932 char buf[CTL_MAX_DATA_LEN];
2936 const struct ctl_var *k;
2941 if (mustput || pcs->clockdesc == NULL
2942 || *(pcs->clockdesc) == '\0') {
2943 ctl_putuint(clock_var[id].text, pcs->type);
2947 ctl_putstr(clock_var[id].text,
2949 (unsigned)pcs->lencode);
2953 ctl_putuint(clock_var[id].text, pcs->polls);
2957 ctl_putuint(clock_var[id].text,
2962 ctl_putuint(clock_var[id].text,
2967 ctl_putuint(clock_var[id].text,
2972 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2973 ctl_putdbl(clock_var[id].text,
2974 pcs->fudgetime1 * 1e3);
2978 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2979 ctl_putdbl(clock_var[id].text,
2980 pcs->fudgetime2 * 1e3);
2984 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2985 ctl_putint(clock_var[id].text,
2990 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2991 if (pcs->fudgeval1 > 1)
2992 ctl_putadr(clock_var[id].text,
2993 pcs->fudgeval2, NULL);
2995 ctl_putrefid(clock_var[id].text,
3001 ctl_putuint(clock_var[id].text, pcs->flags);
3005 if (pcs->clockdesc == NULL ||
3006 *(pcs->clockdesc) == '\0') {
3008 ctl_putstr(clock_var[id].text,
3011 ctl_putstr(clock_var[id].text,
3013 strlen(pcs->clockdesc));
3019 be = buf + sizeof(buf);
3020 if (strlen(clock_var[CC_VARLIST].text) + 4 >
3022 break; /* really long var name */
3024 snprintf(s, sizeof(buf), "%s=\"",
3025 clock_var[CC_VARLIST].text);
3029 for (k = clock_var; !(EOV & k->flags); k++) {
3030 if (PADDING & k->flags)
3033 i = strlen(k->text);
3034 if (s + i + 1 >= be)
3039 memcpy(s, k->text, i);
3043 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
3044 if (PADDING & k->flags)
3051 while (*ss && *ss != '=')
3054 if (s + i + 1 >= be)
3059 memcpy(s, k->text, (unsigned)i);
3068 ctl_putdata(buf, (unsigned)(s - buf), 0);
3077 * ctl_getitem - get the next data item from the incoming packet
3079 static const struct ctl_var *
3081 const struct ctl_var *var_list,
3085 /* [Bug 3008] First check the packet data sanity, then search
3086 * the key. This improves the consistency of result values: If
3087 * the result is NULL once, it will never be EOV again for this
3088 * packet; If it's EOV, it will never be NULL again until the
3089 * variable is found and processed in a given 'var_list'. (That
3090 * is, a result is returned that is neither NULL nor EOV).
3092 static const struct ctl_var eol = { 0, EOV, NULL };
3093 static char buf[128];
3094 static u_long quiet_until;
3095 const struct ctl_var *v;
3100 * Part One: Validate the packet state
3103 /* Delete leading commas and white space */
3104 while (reqpt < reqend && (*reqpt == ',' ||
3105 isspace((unsigned char)*reqpt)))
3107 if (reqpt >= reqend)
3110 /* Scan the string in the packet until we hit comma or
3111 * EoB. Register position of first '=' on the fly. */
3112 for (tp = NULL, cp = reqpt; cp != reqend; ++cp) {
3113 if (*cp == '=' && tp == NULL)
3119 /* Process payload, if any. */
3122 /* eventually strip white space from argument. */
3123 const char *plhead = tp + 1; /* skip the '=' */
3124 const char *pltail = cp;
3127 while (plhead != pltail && isspace((u_char)plhead[0]))
3129 while (plhead != pltail && isspace((u_char)pltail[-1]))
3132 /* check payload size, terminate packet on overflow */
3133 plsize = (size_t)(pltail - plhead);
3134 if (plsize >= sizeof(buf))
3137 /* copy data, NUL terminate, and set result data ptr */
3138 memcpy(buf, plhead, plsize);
3142 /* no payload, current end --> current name termination */
3148 * Now we're sure that the packet data itself is sane. Scan the
3149 * list now. Make sure a NULL list is properly treated by
3150 * returning a synthetic End-Of-Values record. We must not
3151 * return NULL pointers after this point, or the behaviour would
3152 * become inconsistent if called several times with different
3153 * variable lists after an EoV was returned. (Such a behavior
3154 * actually caused Bug 3008.)
3157 if (NULL == var_list)
3160 for (v = var_list; !(EOV & v->flags); ++v)
3161 if (!(PADDING & v->flags)) {
3162 /* Check if the var name matches the buffer. The
3163 * name is bracketed by [reqpt..tp] and not NUL
3164 * terminated, and it contains no '=' char. The
3165 * lookup value IS NUL-terminated but might
3166 * include a '='... We have to look out for
3169 const char *sp1 = reqpt;
3170 const char *sp2 = v->text;
3172 while ((sp1 != tp) && (*sp1 == *sp2)) {
3176 if (sp1 == tp && (*sp2 == '\0' || *sp2 == '='))
3180 /* See if we have found a valid entry or not. If found, advance
3181 * the request pointer for the next round; if not, clear the
3182 * data pointer so we have no dangling garbage here.
3187 reqpt = cp + (cp != reqend);
3191 /*TODO? somehow indicate this packet was bad, apart from syslog? */
3194 if (quiet_until <= current_time) {
3195 quiet_until = current_time + 300;
3196 msyslog(LOG_WARNING,
3197 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)",
3198 stoa(rmt_addr), SRCPORT(rmt_addr));
3200 reqpt = reqend; /* never again for this packet! */
3206 * control_unspec - response to an unspecified op-code
3211 struct recvbuf *rbufp,
3218 * What is an appropriate response to an unspecified op-code?
3219 * I return no errors and no data, unless a specified assocation
3223 peer = findpeerbyassoc(res_associd);
3225 ctl_error(CERR_BADASSOC);
3228 rpkt.status = htons(ctlpeerstatus(peer));
3230 rpkt.status = htons(ctlsysstatus());
3236 * read_status - return either a list of associd's, or a particular
3242 struct recvbuf *rbufp,
3249 /* a_st holds association ID, status pairs alternating */
3250 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3254 printf("read_status: ID %d\n", res_associd);
3257 * Two choices here. If the specified association ID is
3258 * zero we return all known assocation ID's. Otherwise
3259 * we return a bunch of stuff about the particular peer.
3262 peer = findpeerbyassoc(res_associd);
3264 ctl_error(CERR_BADASSOC);
3267 rpkt.status = htons(ctlpeerstatus(peer));
3269 peer->num_events = 0;
3271 * For now, output everything we know about the
3272 * peer. May be more selective later.
3274 for (cp = def_peer_var; *cp != 0; cp++)
3275 ctl_putpeer((int)*cp, peer);
3280 rpkt.status = htons(ctlsysstatus());
3281 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3282 a_st[n++] = htons(peer->associd);
3283 a_st[n++] = htons(ctlpeerstatus(peer));
3284 /* two entries each loop iteration, so n + 1 */
3285 if (n + 1 >= COUNTOF(a_st)) {
3286 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3292 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3298 * read_peervars - half of read_variables() implementation
3303 const struct ctl_var *v;
3308 u_char wants[CP_MAXCODE + 1];
3312 * Wants info for a particular peer. See if we know
3315 peer = findpeerbyassoc(res_associd);
3317 ctl_error(CERR_BADASSOC);
3320 rpkt.status = htons(ctlpeerstatus(peer));
3322 peer->num_events = 0;
3325 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3326 if (v->flags & EOV) {
3327 ctl_error(CERR_UNKNOWNVAR);
3330 INSIST(v->code < COUNTOF(wants));
3335 for (i = 1; i < COUNTOF(wants); i++)
3337 ctl_putpeer(i, peer);
3339 for (cp = def_peer_var; *cp != 0; cp++)
3340 ctl_putpeer((int)*cp, peer);
3346 * read_sysvars - half of read_variables() implementation
3351 const struct ctl_var *v;
3362 * Wants system variables. Figure out which he wants
3363 * and give them to him.
3365 rpkt.status = htons(ctlsysstatus());
3367 ctl_sys_num_events = 0;
3368 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3369 wants = emalloc_zero(wants_count);
3371 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3372 if (!(EOV & v->flags)) {
3373 INSIST(v->code < wants_count);
3377 v = ctl_getitem(ext_sys_var, &valuep);
3379 ctl_error(CERR_BADVALUE);
3383 if (EOV & v->flags) {
3384 ctl_error(CERR_UNKNOWNVAR);
3388 n = v->code + CS_MAXCODE + 1;
3389 INSIST(n < wants_count);
3395 for (n = 1; n <= CS_MAXCODE; n++)
3398 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3399 if (wants[n + CS_MAXCODE + 1]) {
3400 pch = ext_sys_var[n].text;
3401 ctl_putdata(pch, strlen(pch), 0);
3404 for (cs = def_sys_var; *cs != 0; cs++)
3405 ctl_putsys((int)*cs);
3406 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3407 if (DEF & kv->flags)
3408 ctl_putdata(kv->text, strlen(kv->text),
3417 * read_variables - return the variables the caller asks for
3422 struct recvbuf *rbufp,
3434 * write_variables - write into variables. We only allow leap bit
3440 struct recvbuf *rbufp,
3444 const struct ctl_var *v;
3455 * If he's trying to write into a peer tell him no way
3457 if (res_associd != 0) {
3458 ctl_error(CERR_PERMISSION);
3465 rpkt.status = htons(ctlsysstatus());
3468 * Look through the variables. Dump out at the first sign of
3471 while ((v = ctl_getitem(sys_var, &valuep)) != 0) {
3473 if (v->flags & EOV) {
3474 if ((v = ctl_getitem(ext_sys_var, &valuep)) !=
3476 if (v->flags & EOV) {
3477 ctl_error(CERR_UNKNOWNVAR);
3485 if (!(v->flags & CAN_WRITE)) {
3486 ctl_error(CERR_PERMISSION);
3489 if (!ext_var && (*valuep == '\0' || !atoint(valuep,
3491 ctl_error(CERR_BADFMT);
3494 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) {
3495 ctl_error(CERR_BADVALUE);
3500 octets = strlen(v->text) + strlen(valuep) + 2;
3501 vareqv = emalloc(octets);
3504 while (*t && *t != '=')
3507 memcpy(tt, valuep, 1 + strlen(valuep));
3508 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3511 ctl_error(CERR_UNSPEC); /* really */
3517 * If we got anything, do it. xxx nothing to do ***
3520 if (leapind != ~0 || leapwarn != ~0) {
3521 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3522 ctl_error(CERR_PERMISSION);
3532 * configure() processes ntpq :config/config-from-file, allowing
3533 * generic runtime reconfiguration.
3535 static void configure(
3536 struct recvbuf *rbufp,
3543 /* I haven't yet implemented changes to an existing association.
3544 * Hence check if the association id is 0
3546 if (res_associd != 0) {
3547 ctl_error(CERR_BADVALUE);
3551 if (RES_NOMODIFY & restrict_mask) {
3552 snprintf(remote_config.err_msg,
3553 sizeof(remote_config.err_msg),
3554 "runtime configuration prohibited by restrict ... nomodify");
3555 ctl_putdata(remote_config.err_msg,
3556 strlen(remote_config.err_msg), 0);
3560 "runtime config from %s rejected due to nomodify restriction",
3561 stoa(&rbufp->recv_srcadr));
3566 /* Initialize the remote config buffer */
3567 data_count = remoteconfig_cmdlength(reqpt, reqend);
3569 if (data_count > sizeof(remote_config.buffer) - 2) {
3570 snprintf(remote_config.err_msg,
3571 sizeof(remote_config.err_msg),
3572 "runtime configuration failed: request too long");
3573 ctl_putdata(remote_config.err_msg,
3574 strlen(remote_config.err_msg), 0);
3577 "runtime config from %s rejected: request too long",
3578 stoa(&rbufp->recv_srcadr));
3581 /* Bug 2853 -- check if all characters were acceptable */
3582 if (data_count != (size_t)(reqend - reqpt)) {
3583 snprintf(remote_config.err_msg,
3584 sizeof(remote_config.err_msg),
3585 "runtime configuration failed: request contains an unprintable character");
3586 ctl_putdata(remote_config.err_msg,
3587 strlen(remote_config.err_msg), 0);
3590 "runtime config from %s rejected: request contains an unprintable character: %0x",
3591 stoa(&rbufp->recv_srcadr),
3596 memcpy(remote_config.buffer, reqpt, data_count);
3597 /* The buffer has no trailing linefeed or NUL right now. For
3598 * logging, we do not want a newline, so we do that first after
3599 * adding the necessary NUL byte.
3601 remote_config.buffer[data_count] = '\0';
3602 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3603 remote_config.buffer));
3604 msyslog(LOG_NOTICE, "%s config: %s",
3605 stoa(&rbufp->recv_srcadr),
3606 remote_config.buffer);
3608 /* Now we have to make sure there is a NL/NUL sequence at the
3609 * end of the buffer before we parse it.
3611 remote_config.buffer[data_count++] = '\n';
3612 remote_config.buffer[data_count] = '\0';
3613 remote_config.pos = 0;
3614 remote_config.err_pos = 0;
3615 remote_config.no_errors = 0;
3616 config_remotely(&rbufp->recv_srcadr);
3619 * Check if errors were reported. If not, output 'Config
3620 * Succeeded'. Else output the error count. It would be nice
3621 * to output any parser error messages.
3623 if (0 == remote_config.no_errors) {
3624 retval = snprintf(remote_config.err_msg,
3625 sizeof(remote_config.err_msg),
3626 "Config Succeeded");
3628 remote_config.err_pos += retval;
3631 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3634 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3636 if (remote_config.no_errors > 0)
3637 msyslog(LOG_NOTICE, "%d error in %s config",
3638 remote_config.no_errors,
3639 stoa(&rbufp->recv_srcadr));
3644 * derive_nonce - generate client-address-specific nonce value
3645 * associated with a given timestamp.
3647 static u_int32 derive_nonce(
3653 static u_int32 salt[4];
3654 static u_long last_salt_update;
3656 u_char digest[EVP_MAX_MD_SIZE];
3662 while (!salt[0] || current_time - last_salt_update >= 3600) {
3663 salt[0] = ntp_random();
3664 salt[1] = ntp_random();
3665 salt[2] = ntp_random();
3666 salt[3] = ntp_random();
3667 last_salt_update = current_time;
3670 ctx = EVP_MD_CTX_new();
3671 EVP_DigestInit(ctx, EVP_get_digestbynid(NID_md5));
3672 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3673 EVP_DigestUpdate(ctx, &ts_i, sizeof(ts_i));
3674 EVP_DigestUpdate(ctx, &ts_f, sizeof(ts_f));
3676 EVP_DigestUpdate(ctx, &SOCK_ADDR4(addr),
3677 sizeof(SOCK_ADDR4(addr)));
3679 EVP_DigestUpdate(ctx, &SOCK_ADDR6(addr),
3680 sizeof(SOCK_ADDR6(addr)));
3681 EVP_DigestUpdate(ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3682 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3683 EVP_DigestFinal(ctx, d.digest, &len);
3684 EVP_MD_CTX_free(ctx);
3691 * generate_nonce - generate client-address-specific nonce string.
3693 static void generate_nonce(
3694 struct recvbuf * rbufp,
3701 derived = derive_nonce(&rbufp->recv_srcadr,
3702 rbufp->recv_time.l_ui,
3703 rbufp->recv_time.l_uf);
3704 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3705 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3710 * validate_nonce - validate client-address-specific nonce string.
3712 * Returns TRUE if the local calculation of the nonce matches the
3713 * client-provided value and the timestamp is recent enough.
3715 static int validate_nonce(
3716 const char * pnonce,
3717 struct recvbuf * rbufp
3727 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3730 ts.l_ui = (u_int32)ts_i;
3731 ts.l_uf = (u_int32)ts_f;
3732 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3733 get_systime(&now_delta);
3734 L_SUB(&now_delta, &ts);
3736 return (supposed == derived && now_delta.l_ui < 16);
3741 * send_random_tag_value - send a randomly-generated three character
3742 * tag prefix, a '.', an index, a '=' and a
3743 * random integer value.
3745 * To try to force clients to ignore unrecognized tags in mrulist,
3746 * reslist, and ifstats responses, the first and last rows are spiced
3747 * with randomly-generated tag names with correct .# index. Make it
3748 * three characters knowing that none of the currently-used subscripted
3749 * tags have that length, avoiding the need to test for
3753 send_random_tag_value(
3760 noise = rand() ^ (rand() << 16);
3761 buf[0] = 'a' + noise % 26;
3763 buf[1] = 'a' + noise % 26;
3765 buf[2] = 'a' + noise % 26;
3768 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3769 ctl_putuint(buf, noise);
3774 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3776 * To keep clients honest about not depending on the order of values,
3777 * and thereby avoid being locked into ugly workarounds to maintain
3778 * backward compatibility later as new fields are added to the response,
3779 * the order is random.
3787 const char first_fmt[] = "first.%d";
3788 const char ct_fmt[] = "ct.%d";
3789 const char mv_fmt[] = "mv.%d";
3790 const char rs_fmt[] = "rs.%d";
3792 u_char sent[6]; /* 6 tag=value pairs */
3798 remaining = COUNTOF(sent);
3800 noise = (u_int32)(rand() ^ (rand() << 16));
3801 while (remaining > 0) {
3802 which = (noise & 7) % COUNTOF(sent);
3805 which = (which + 1) % COUNTOF(sent);
3810 snprintf(tag, sizeof(tag), addr_fmt, count);
3811 pch = sptoa(&mon->rmtadr);
3812 ctl_putunqstr(tag, pch, strlen(pch));
3816 snprintf(tag, sizeof(tag), last_fmt, count);
3817 ctl_putts(tag, &mon->last);
3821 snprintf(tag, sizeof(tag), first_fmt, count);
3822 ctl_putts(tag, &mon->first);
3826 snprintf(tag, sizeof(tag), ct_fmt, count);
3827 ctl_putint(tag, mon->count);
3831 snprintf(tag, sizeof(tag), mv_fmt, count);
3832 ctl_putuint(tag, mon->vn_mode);
3836 snprintf(tag, sizeof(tag), rs_fmt, count);
3837 ctl_puthex(tag, mon->flags);
3847 * read_mru_list - supports ntpq's mrulist command.
3849 * The challenge here is to match ntpdc's monlist functionality without
3850 * being limited to hundreds of entries returned total, and without
3851 * requiring state on the server. If state were required, ntpq's
3852 * mrulist command would require authentication.
3854 * The approach was suggested by Ry Jones. A finite and variable number
3855 * of entries are retrieved per request, to avoid having responses with
3856 * such large numbers of packets that socket buffers are overflowed and
3857 * packets lost. The entries are retrieved oldest-first, taking into
3858 * account that the MRU list will be changing between each request. We
3859 * can expect to see duplicate entries for addresses updated in the MRU
3860 * list during the fetch operation. In the end, the client can assemble
3861 * a close approximation of the MRU list at the point in time the last
3862 * response was sent by ntpd. The only difference is it may be longer,
3863 * containing some number of oldest entries which have since been
3864 * reclaimed. If necessary, the protocol could be extended to zap those
3865 * from the client snapshot at the end, but so far that doesn't seem
3868 * To accomodate the changing MRU list, the starting point for requests
3869 * after the first request is supplied as a series of last seen
3870 * timestamps and associated addresses, the newest ones the client has
3871 * received. As long as at least one of those entries hasn't been
3872 * bumped to the head of the MRU list, ntpd can pick up at that point.
3873 * Otherwise, the request is failed and it is up to ntpq to back up and
3874 * provide the next newest entry's timestamps and addresses, conceivably
3875 * backing up all the way to the starting point.
3878 * nonce= Regurgitated nonce retrieved by the client
3879 * previously using CTL_OP_REQ_NONCE, demonstrating
3880 * ability to receive traffic sent to its address.
3881 * frags= Limit on datagrams (fragments) in response. Used
3882 * by newer ntpq versions instead of limit= when
3883 * retrieving multiple entries.
3884 * limit= Limit on MRU entries returned. One of frags= or
3885 * limit= must be provided.
3886 * limit=1 is a special case: Instead of fetching
3887 * beginning with the supplied starting point's
3888 * newer neighbor, fetch the supplied entry, and
3889 * in that case the #.last timestamp can be zero.
3890 * This enables fetching a single entry by IP
3891 * address. When limit is not one and frags= is
3892 * provided, the fragment limit controls.
3893 * mincount= (decimal) Return entries with count >= mincount.
3894 * laddr= Return entries associated with the server's IP
3895 * address given. No port specification is needed,
3896 * and any supplied is ignored.
3897 * resall= 0x-prefixed hex restrict bits which must all be
3898 * lit for an MRU entry to be included.
3899 * Has precedence over any resany=.
3900 * resany= 0x-prefixed hex restrict bits, at least one of
3901 * which must be list for an MRU entry to be
3903 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3904 * which client previously received.
3905 * addr.0= text of newest entry's IP address and port,
3906 * IPv6 addresses in bracketed form: [::]:123
3907 * last.1= timestamp of 2nd newest entry client has.
3908 * addr.1= address of 2nd newest entry.
3911 * ntpq provides as many last/addr pairs as will fit in a single request
3912 * packet, except for the first request in a MRU fetch operation.
3914 * The response begins with a new nonce value to be used for any
3915 * followup request. Following the nonce is the next newer entry than
3916 * referred to by last.0 and addr.0, if the "0" entry has not been
3917 * bumped to the front. If it has, the first entry returned will be the
3918 * next entry newer than referred to by last.1 and addr.1, and so on.
3919 * If none of the referenced entries remain unchanged, the request fails
3920 * and ntpq backs up to the next earlier set of entries to resync.
3922 * Except for the first response, the response begins with confirmation
3923 * of the entry that precedes the first additional entry provided:
3925 * last.older= hex l_fp timestamp matching one of the input
3926 * .last timestamps, which entry now precedes the
3927 * response 0. entry in the MRU list.
3928 * addr.older= text of address corresponding to older.last.
3930 * And in any case, a successful response contains sets of values
3931 * comprising entries, with the oldest numbered 0 and incrementing from
3934 * addr.# text of IPv4 or IPv6 address and port
3935 * last.# hex l_fp timestamp of last receipt
3936 * first.# hex l_fp timestamp of first receipt
3937 * ct.# count of packets received
3938 * mv.# mode and version
3939 * rs.# restriction mask (RES_* bits)
3941 * Note the code currently assumes there are no valid three letter
3942 * tags sent with each row, and needs to be adjusted if that changes.
3944 * The client should accept the values in any order, and ignore .#
3945 * values which it does not understand, to allow a smooth path to
3946 * future changes without requiring a new opcode. Clients can rely
3947 * on all *.0 values preceding any *.1 values, that is all values for
3948 * a given index number are together in the response.
3950 * The end of the response list is noted with one or two tag=value
3951 * pairs. Unconditionally:
3953 * now= 0x-prefixed l_fp timestamp at the server marking
3954 * the end of the operation.
3956 * If any entries were returned, now= is followed by:
3958 * last.newest= hex l_fp identical to last.# of the prior
3961 static void read_mru_list(
3962 struct recvbuf *rbufp,
3966 static const char nulltxt[1] = { '\0' };
3967 static const char nonce_text[] = "nonce";
3968 static const char frags_text[] = "frags";
3969 static const char limit_text[] = "limit";
3970 static const char mincount_text[] = "mincount";
3971 static const char resall_text[] = "resall";
3972 static const char resany_text[] = "resany";
3973 static const char maxlstint_text[] = "maxlstint";
3974 static const char laddr_text[] = "laddr";
3975 static const char resaxx_fmt[] = "0x%hx";
3984 struct interface * lcladr;
3989 sockaddr_u addr[COUNTOF(last)];
3991 struct ctl_var * in_parms;
3992 const struct ctl_var * v;
4001 mon_entry * prior_mon;
4004 if (RES_NOMRULIST & restrict_mask) {
4005 ctl_error(CERR_PERMISSION);
4008 "mrulist from %s rejected due to nomrulist restriction",
4009 stoa(&rbufp->recv_srcadr));
4014 * fill in_parms var list with all possible input parameters.
4017 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
4018 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
4019 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
4020 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
4021 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
4022 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
4023 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
4024 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
4025 for (i = 0; i < COUNTOF(last); i++) {
4026 snprintf(buf, sizeof(buf), last_fmt, (int)i);
4027 set_var(&in_parms, buf, strlen(buf) + 1, 0);
4028 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
4029 set_var(&in_parms, buf, strlen(buf) + 1, 0);
4032 /* decode input parms */
4045 /* have to go through '(void*)' to drop 'const' property from pointer.
4046 * ctl_getitem()' needs some cleanup, too.... perlinger@ntp.org
4048 while (NULL != (v = ctl_getitem(in_parms, (void*)&val)) &&
4049 !(EOV & v->flags)) {
4055 if (!strcmp(nonce_text, v->text)) {
4057 pnonce = (*val) ? estrdup(val) : NULL;
4058 } else if (!strcmp(frags_text, v->text)) {
4059 if (1 != sscanf(val, "%hu", &frags))
4061 } else if (!strcmp(limit_text, v->text)) {
4062 if (1 != sscanf(val, "%u", &limit))
4064 } else if (!strcmp(mincount_text, v->text)) {
4065 if (1 != sscanf(val, "%d", &mincount))
4069 } else if (!strcmp(resall_text, v->text)) {
4070 if (1 != sscanf(val, resaxx_fmt, &resall))
4072 } else if (!strcmp(resany_text, v->text)) {
4073 if (1 != sscanf(val, resaxx_fmt, &resany))
4075 } else if (!strcmp(maxlstint_text, v->text)) {
4076 if (1 != sscanf(val, "%u", &maxlstint))
4078 } else if (!strcmp(laddr_text, v->text)) {
4079 if (!decodenetnum(val, &laddr))
4081 lcladr = getinterface(&laddr, 0);
4082 } else if (1 == sscanf(v->text, last_fmt, &si) &&
4083 (size_t)si < COUNTOF(last)) {
4084 if (2 != sscanf(val, "0x%08x.%08x", &ui, &uf))
4088 if (!SOCK_UNSPEC(&addr[si]) && si == priors)
4090 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
4091 (size_t)si < COUNTOF(addr)) {
4092 if (!decodenetnum(val, &addr[si]))
4094 if (last[si].l_ui && last[si].l_uf && si == priors)
4097 DPRINTF(1, ("read_mru_list: invalid key item: '%s' (ignored)\n",
4102 DPRINTF(1, ("read_mru_list: invalid param for '%s': '%s' (bailing)\n",
4109 free_varlist(in_parms);
4112 /* return no responses until the nonce is validated */
4116 nonce_valid = validate_nonce(pnonce, rbufp);
4121 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
4122 frags > MRU_FRAGS_LIMIT) {
4123 ctl_error(CERR_BADVALUE);
4128 * If either frags or limit is not given, use the max.
4130 if (0 != frags && 0 == limit)
4132 else if (0 != limit && 0 == frags)
4133 frags = MRU_FRAGS_LIMIT;
4136 * Find the starting point if one was provided.
4139 for (i = 0; i < (size_t)priors; i++) {
4140 hash = MON_HASH(&addr[i]);
4141 for (mon = mon_hash[hash];
4143 mon = mon->hash_next)
4144 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
4147 if (L_ISEQU(&mon->last, &last[i]))
4153 /* If a starting point was provided... */
4155 /* and none could be found unmodified... */
4157 /* tell ntpq to try again with older entries */
4158 ctl_error(CERR_UNKNOWNVAR);
4161 /* confirm the prior entry used as starting point */
4162 ctl_putts("last.older", &mon->last);
4163 pch = sptoa(&mon->rmtadr);
4164 ctl_putunqstr("addr.older", pch, strlen(pch));
4167 * Move on to the first entry the client doesn't have,
4168 * except in the special case of a limit of one. In
4169 * that case return the starting point entry.
4172 mon = PREV_DLIST(mon_mru_list, mon, mru);
4173 } else { /* start with the oldest */
4174 mon = TAIL_DLIST(mon_mru_list, mru);
4178 * send up to limit= entries in up to frags= datagrams
4181 generate_nonce(rbufp, buf, sizeof(buf));
4182 ctl_putunqstr("nonce", buf, strlen(buf));
4185 mon != NULL && res_frags < frags && count < limit;
4186 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
4188 if (mon->count < mincount)
4190 if (resall && resall != (resall & mon->flags))
4192 if (resany && !(resany & mon->flags))
4194 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
4197 if (lcladr != NULL && mon->lcladr != lcladr)
4200 send_mru_entry(mon, count);
4202 send_random_tag_value(0);
4208 * If this batch completes the MRU list, say so explicitly with
4209 * a now= l_fp timestamp.
4213 send_random_tag_value(count - 1);
4214 ctl_putts("now", &now);
4215 /* if any entries were returned confirm the last */
4216 if (prior_mon != NULL)
4217 ctl_putts("last.newest", &prior_mon->last);
4224 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
4226 * To keep clients honest about not depending on the order of values,
4227 * and thereby avoid being locked into ugly workarounds to maintain
4228 * backward compatibility later as new fields are added to the response,
4229 * the order is random.
4237 const char addr_fmtu[] = "addr.%u";
4238 const char bcast_fmt[] = "bcast.%u";
4239 const char en_fmt[] = "en.%u"; /* enabled */
4240 const char name_fmt[] = "name.%u";
4241 const char flags_fmt[] = "flags.%u";
4242 const char tl_fmt[] = "tl.%u"; /* ttl */
4243 const char mc_fmt[] = "mc.%u"; /* mcast count */
4244 const char rx_fmt[] = "rx.%u";
4245 const char tx_fmt[] = "tx.%u";
4246 const char txerr_fmt[] = "txerr.%u";
4247 const char pc_fmt[] = "pc.%u"; /* peer count */
4248 const char up_fmt[] = "up.%u"; /* uptime */
4250 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4257 remaining = COUNTOF(sent);
4261 while (remaining > 0) {
4262 if (noisebits < 4) {
4263 noise = rand() ^ (rand() << 16);
4266 which = (noise & 0xf) % COUNTOF(sent);
4271 which = (which + 1) % COUNTOF(sent);
4276 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4277 pch = sptoa(&la->sin);
4278 ctl_putunqstr(tag, pch, strlen(pch));
4282 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4283 if (INT_BCASTOPEN & la->flags)
4284 pch = sptoa(&la->bcast);
4287 ctl_putunqstr(tag, pch, strlen(pch));
4291 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4292 ctl_putint(tag, !la->ignore_packets);
4296 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4297 ctl_putstr(tag, la->name, strlen(la->name));
4301 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4302 ctl_puthex(tag, (u_int)la->flags);
4306 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4307 ctl_putint(tag, la->last_ttl);
4311 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4312 ctl_putint(tag, la->num_mcast);
4316 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4317 ctl_putint(tag, la->received);
4321 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4322 ctl_putint(tag, la->sent);
4326 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4327 ctl_putint(tag, la->notsent);
4331 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4332 ctl_putuint(tag, la->peercnt);
4336 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4337 ctl_putuint(tag, current_time - la->starttime);
4343 send_random_tag_value((int)ifnum);
4348 * read_ifstats - send statistics for each local address, exposed by
4353 struct recvbuf * rbufp
4360 * loop over [0..sys_ifnum] searching ep_list for each
4363 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4364 for (la = ep_list; la != NULL; la = la->elink)
4365 if (ifidx == la->ifnum)
4369 /* return stats for one local address */
4370 send_ifstats_entry(la, ifidx);
4376 sockaddrs_from_restrict_u(
4386 psaA->sa.sa_family = AF_INET;
4387 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4388 psaM->sa.sa_family = AF_INET;
4389 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4391 psaA->sa.sa_family = AF_INET6;
4392 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4393 sizeof(psaA->sa6.sin6_addr));
4394 psaM->sa.sa_family = AF_INET6;
4395 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4396 sizeof(psaA->sa6.sin6_addr));
4402 * Send a restrict entry in response to a "ntpq -c reslist" request.
4404 * To keep clients honest about not depending on the order of values,
4405 * and thereby avoid being locked into ugly workarounds to maintain
4406 * backward compatibility later as new fields are added to the response,
4407 * the order is random.
4410 send_restrict_entry(
4416 const char addr_fmtu[] = "addr.%u";
4417 const char mask_fmtu[] = "mask.%u";
4418 const char hits_fmt[] = "hits.%u";
4419 const char flags_fmt[] = "flags.%u";
4421 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4430 const char * match_str;
4431 const char * access_str;
4433 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4434 remaining = COUNTOF(sent);
4438 while (remaining > 0) {
4439 if (noisebits < 2) {
4440 noise = rand() ^ (rand() << 16);
4443 which = (noise & 0x3) % COUNTOF(sent);
4448 which = (which + 1) % COUNTOF(sent);
4453 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4455 ctl_putunqstr(tag, pch, strlen(pch));
4459 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4461 ctl_putunqstr(tag, pch, strlen(pch));
4465 snprintf(tag, sizeof(tag), hits_fmt, idx);
4466 ctl_putuint(tag, pres->count);
4470 snprintf(tag, sizeof(tag), flags_fmt, idx);
4471 match_str = res_match_flags(pres->mflags);
4472 access_str = res_access_flags(pres->flags);
4473 if ('\0' == match_str[0]) {
4477 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4478 match_str, access_str);
4481 ctl_putunqstr(tag, pch, strlen(pch));
4487 send_random_tag_value((int)idx);
4498 for ( ; pres != NULL; pres = pres->link) {
4499 send_restrict_entry(pres, ipv6, *pidx);
4506 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4509 read_addr_restrictions(
4510 struct recvbuf * rbufp
4516 send_restrict_list(restrictlist4, FALSE, &idx);
4517 send_restrict_list(restrictlist6, TRUE, &idx);
4523 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4527 struct recvbuf * rbufp,
4531 const char ifstats_s[] = "ifstats";
4532 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4533 const char addr_rst_s[] = "addr_restrictions";
4534 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4535 struct ntp_control * cpkt;
4536 u_short qdata_octets;
4539 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4540 * used only for ntpq -c ifstats. With the addition of reslist
4541 * the same opcode was generalized to retrieve ordered lists
4542 * which require authentication. The request data is empty or
4543 * contains "ifstats" (not null terminated) to retrieve local
4544 * addresses and associated stats. It is "addr_restrictions"
4545 * to retrieve the IPv4 then IPv6 remote address restrictions,
4546 * which are access control lists. Other request data return
4549 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4550 qdata_octets = ntohs(cpkt->count);
4551 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4552 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4553 read_ifstats(rbufp);
4556 if (a_r_chars == qdata_octets &&
4557 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4558 read_addr_restrictions(rbufp);
4561 ctl_error(CERR_UNKNOWNVAR);
4566 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4568 static void req_nonce(
4569 struct recvbuf * rbufp,
4575 generate_nonce(rbufp, buf, sizeof(buf));
4576 ctl_putunqstr("nonce", buf, strlen(buf));
4582 * read_clockstatus - return clock radio status
4587 struct recvbuf *rbufp,
4593 * If no refclock support, no data to return
4595 ctl_error(CERR_BADASSOC);
4597 const struct ctl_var * v;
4605 struct ctl_var * kv;
4606 struct refclockstat cs;
4608 if (res_associd != 0) {
4609 peer = findpeerbyassoc(res_associd);
4612 * Find a clock for this jerk. If the system peer
4613 * is a clock use it, else search peer_list for one.
4615 if (sys_peer != NULL && (FLAG_REFCLOCK &
4619 for (peer = peer_list;
4621 peer = peer->p_link)
4622 if (FLAG_REFCLOCK & peer->flags)
4625 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4626 ctl_error(CERR_BADASSOC);
4630 * If we got here we have a peer which is a clock. Get his
4634 refclock_control(&peer->srcadr, NULL, &cs);
4637 * Look for variables in the packet.
4639 rpkt.status = htons(ctlclkstatus(&cs));
4640 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4641 wants = emalloc_zero(wants_alloc);
4643 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4644 if (!(EOV & v->flags)) {
4645 wants[v->code] = TRUE;
4648 v = ctl_getitem(kv, &valuep);
4650 ctl_error(CERR_BADVALUE);
4652 free_varlist(cs.kv_list);
4655 if (EOV & v->flags) {
4656 ctl_error(CERR_UNKNOWNVAR);
4658 free_varlist(cs.kv_list);
4661 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4667 for (i = 1; i <= CC_MAXCODE; i++)
4669 ctl_putclock(i, &cs, TRUE);
4671 for (i = 0; !(EOV & kv[i].flags); i++)
4672 if (wants[i + CC_MAXCODE + 1])
4673 ctl_putdata(kv[i].text,
4677 for (cc = def_clock_var; *cc != 0; cc++)
4678 ctl_putclock((int)*cc, &cs, FALSE);
4679 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4680 if (DEF & kv->flags)
4681 ctl_putdata(kv->text, strlen(kv->text),
4686 free_varlist(cs.kv_list);
4694 * write_clockstatus - we don't do this
4699 struct recvbuf *rbufp,
4703 ctl_error(CERR_PERMISSION);
4707 * Trap support from here on down. We send async trap messages when the
4708 * upper levels report trouble. Traps can by set either by control
4709 * messages or by configuration.
4712 * set_trap - set a trap in response to a control message
4716 struct recvbuf *rbufp,
4723 * See if this guy is allowed
4725 if (restrict_mask & RES_NOTRAP) {
4726 ctl_error(CERR_PERMISSION);
4731 * Determine his allowed trap type.
4733 traptype = TRAP_TYPE_PRIO;
4734 if (restrict_mask & RES_LPTRAP)
4735 traptype = TRAP_TYPE_NONPRIO;
4738 * Call ctlsettrap() to do the work. Return
4739 * an error if it can't assign the trap.
4741 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4743 ctl_error(CERR_NORESOURCE);
4749 * unset_trap - unset a trap in response to a control message
4753 struct recvbuf *rbufp,
4760 * We don't prevent anyone from removing his own trap unless the
4761 * trap is configured. Note we also must be aware of the
4762 * possibility that restriction flags were changed since this
4763 * guy last set his trap. Set the trap type based on this.
4765 traptype = TRAP_TYPE_PRIO;
4766 if (restrict_mask & RES_LPTRAP)
4767 traptype = TRAP_TYPE_NONPRIO;
4770 * Call ctlclrtrap() to clear this out.
4772 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4773 ctl_error(CERR_BADASSOC);
4779 * ctlsettrap - called to set a trap
4784 struct interface *linter,
4790 struct ctl_trap *tp;
4791 struct ctl_trap *tptouse;
4794 * See if we can find this trap. If so, we only need update
4795 * the flags and the time.
4797 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4800 case TRAP_TYPE_CONFIG:
4801 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4804 case TRAP_TYPE_PRIO:
4805 if (tp->tr_flags & TRAP_CONFIGURED)
4806 return (1); /* don't change anything */
4807 tp->tr_flags = TRAP_INUSE;
4810 case TRAP_TYPE_NONPRIO:
4811 if (tp->tr_flags & TRAP_CONFIGURED)
4812 return (1); /* don't change anything */
4813 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4816 tp->tr_settime = current_time;
4822 * First we heard of this guy. Try to find a trap structure
4823 * for him to use, clearing out lesser priority guys if we
4824 * have to. Clear out anyone who's expired while we're at it.
4827 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4829 if ((TRAP_INUSE & tp->tr_flags) &&
4830 !(TRAP_CONFIGURED & tp->tr_flags) &&
4831 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4835 if (!(TRAP_INUSE & tp->tr_flags)) {
4837 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4840 case TRAP_TYPE_CONFIG:
4841 if (tptouse == NULL) {
4845 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4846 !(TRAP_NONPRIO & tp->tr_flags))
4849 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4850 && (TRAP_NONPRIO & tp->tr_flags)) {
4854 if (tptouse->tr_origtime <
4859 case TRAP_TYPE_PRIO:
4860 if ( TRAP_NONPRIO & tp->tr_flags) {
4861 if (tptouse == NULL ||
4863 tptouse->tr_flags) &&
4864 tptouse->tr_origtime <
4870 case TRAP_TYPE_NONPRIO:
4877 * If we don't have room for him return an error.
4879 if (tptouse == NULL)
4883 * Set up this structure for him.
4885 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4886 tptouse->tr_count = tptouse->tr_resets = 0;
4887 tptouse->tr_sequence = 1;
4888 tptouse->tr_addr = *raddr;
4889 tptouse->tr_localaddr = linter;
4890 tptouse->tr_version = (u_char) version;
4891 tptouse->tr_flags = TRAP_INUSE;
4892 if (traptype == TRAP_TYPE_CONFIG)
4893 tptouse->tr_flags |= TRAP_CONFIGURED;
4894 else if (traptype == TRAP_TYPE_NONPRIO)
4895 tptouse->tr_flags |= TRAP_NONPRIO;
4902 * ctlclrtrap - called to clear a trap
4907 struct interface *linter,
4911 register struct ctl_trap *tp;
4913 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4916 if (tp->tr_flags & TRAP_CONFIGURED
4917 && traptype != TRAP_TYPE_CONFIG)
4927 * ctlfindtrap - find a trap given the remote and local addresses
4929 static struct ctl_trap *
4932 struct interface *linter
4937 for (n = 0; n < COUNTOF(ctl_traps); n++)
4938 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4939 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4940 && (linter == ctl_traps[n].tr_localaddr))
4941 return &ctl_traps[n];
4948 * report_event - report an event to the trappers
4952 int err, /* error code */
4953 struct peer *peer, /* peer structure pointer */
4954 const char *str /* protostats string */
4957 char statstr[NTP_MAXSTRLEN];
4962 * Report the error to the protostats file, system log and
4968 * Discard a system report if the number of reports of
4969 * the same type exceeds the maximum.
4971 if (ctl_sys_last_event != (u_char)err)
4972 ctl_sys_num_events= 0;
4973 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4976 ctl_sys_last_event = (u_char)err;
4977 ctl_sys_num_events++;
4978 snprintf(statstr, sizeof(statstr),
4979 "0.0.0.0 %04x %02x %s",
4980 ctlsysstatus(), err, eventstr(err));
4982 len = strlen(statstr);
4983 snprintf(statstr + len, sizeof(statstr) - len,
4987 msyslog(LOG_INFO, "%s", statstr);
4991 * Discard a peer report if the number of reports of
4992 * the same type exceeds the maximum for that peer.
4997 errlast = (u_char)err & ~PEER_EVENT;
4998 if (peer->last_event == errlast)
4999 peer->num_events = 0;
5000 if (peer->num_events >= CTL_PEER_MAXEVENTS)
5003 peer->last_event = errlast;
5005 if (ISREFCLOCKADR(&peer->srcadr))
5006 src = refnumtoa(&peer->srcadr);
5008 src = stoa(&peer->srcadr);
5010 snprintf(statstr, sizeof(statstr),
5011 "%s %04x %02x %s", src,
5012 ctlpeerstatus(peer), err, eventstr(err));
5014 len = strlen(statstr);
5015 snprintf(statstr + len, sizeof(statstr) - len,
5018 NLOG(NLOG_PEEREVENT)
5019 msyslog(LOG_INFO, "%s", statstr);
5021 record_proto_stats(statstr);
5024 printf("event at %lu %s\n", current_time, statstr);
5028 * If no trappers, return.
5030 if (num_ctl_traps <= 0)
5034 * Peer Events should be associated with a peer -- hence the
5035 * name. But there are instances where this function is called
5036 * *without* a valid peer. This happens e.g. with an unsolicited
5037 * CryptoNAK, or when a leap second alarm is going off while
5038 * currently without a system peer.
5040 * The most sensible approach to this seems to bail out here if
5041 * this happens. Avoiding to call this function would also
5042 * bypass the log reporting in the first part of this function,
5043 * and this is probably not the best of all options.
5044 * -*-perlinger@ntp.org-*-
5046 if ((err & PEER_EVENT) && !peer)
5050 * Set up the outgoing packet variables
5052 res_opcode = CTL_OP_ASYNCMSG;
5055 res_authenticate = FALSE;
5056 datapt = rpkt.u.data;
5057 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
5058 if (!(err & PEER_EVENT)) {
5060 rpkt.status = htons(ctlsysstatus());
5062 /* Include the core system variables and the list. */
5063 for (i = 1; i <= CS_VARLIST; i++)
5065 } else if (NULL != peer) { /* paranoia -- skip output */
5066 rpkt.associd = htons(peer->associd);
5067 rpkt.status = htons(ctlpeerstatus(peer));
5069 /* Dump it all. Later, maybe less. */
5070 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
5071 ctl_putpeer(i, peer);
5074 * for clock exception events: add clock variables to
5075 * reflect info on exception
5077 if (err == PEVNT_CLOCK) {
5078 struct refclockstat cs;
5082 refclock_control(&peer->srcadr, NULL, &cs);
5084 ctl_puthex("refclockstatus",
5087 for (i = 1; i <= CC_MAXCODE; i++)
5088 ctl_putclock(i, &cs, FALSE);
5089 for (kv = cs.kv_list;
5090 kv != NULL && !(EOV & kv->flags);
5092 if (DEF & kv->flags)
5093 ctl_putdata(kv->text,
5096 free_varlist(cs.kv_list);
5098 # endif /* REFCLOCK */
5102 * We're done, return.
5109 * mprintf_event - printf-style varargs variant of report_event()
5113 int evcode, /* event code */
5114 struct peer * p, /* may be NULL */
5115 const char * fmt, /* msnprintf format */
5124 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
5126 report_event(evcode, p, msg);
5133 * ctl_clr_stats - clear stat counters
5138 ctltimereset = current_time;
5141 numctlresponses = 0;
5146 numctlinputresp = 0;
5147 numctlinputfrag = 0;
5149 numctlbadoffset = 0;
5150 numctlbadversion = 0;
5151 numctldatatooshort = 0;
5158 const struct ctl_var *k
5167 while (!(EOV & (k++)->flags))
5170 ENSURE(c <= USHRT_MAX);
5177 struct ctl_var **kv,
5187 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
5189 buf = emalloc(size);
5194 k[c + 1].text = NULL;
5195 k[c + 1].flags = EOV;
5203 struct ctl_var **kv,
5214 if (NULL == data || !size)
5219 while (!(EOV & k->flags)) {
5220 if (NULL == k->text) {
5222 memcpy(td, data, size);
5229 while (*t != '=' && *s == *t) {
5233 if (*s == *t && ((*t == '=') || !*t)) {
5234 td = erealloc((void *)(intptr_t)k->text, size);
5235 memcpy(td, data, size);
5244 td = add_var(kv, size, def);
5245 memcpy(td, data, size);
5256 set_var(&ext_sys_var, data, size, def);
5261 * get_ext_sys_var() retrieves the value of a user-defined variable or
5262 * NULL if the variable has not been setvar'd.
5265 get_ext_sys_var(const char *tag)
5273 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5274 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5275 if ('=' == v->text[c]) {
5276 val = v->text + c + 1;
5278 } else if ('\0' == v->text[c]) {
5296 for (k = kv; !(k->flags & EOV); k++)
5297 free((void *)(intptr_t)k->text);