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"
37 * Structure to hold request procedure information
41 short control_code; /* defined request code */
42 #define NO_REQUEST (-1)
43 u_short flags; /* flags word */
44 /* Only one flag. Authentication required or not. */
47 void (*handler) (struct recvbuf *, int); /* handle request */
52 * Request processing routines
54 static void ctl_error (u_char);
56 static u_short ctlclkstatus (struct refclockstat *);
58 static void ctl_flushpkt (u_char);
59 static void ctl_putdata (const char *, unsigned int, int);
60 static void ctl_putstr (const char *, const char *, size_t);
61 static void ctl_putdblf (const char *, int, int, double);
62 #define ctl_putdbl(tag, d) ctl_putdblf(tag, 1, 3, d)
63 #define ctl_putdbl6(tag, d) ctl_putdblf(tag, 1, 6, d)
64 #define ctl_putsfp(tag, sfp) ctl_putdblf(tag, 0, -1, \
66 static void ctl_putuint (const char *, u_long);
67 static void ctl_puthex (const char *, u_long);
68 static void ctl_putint (const char *, long);
69 static void ctl_putts (const char *, l_fp *);
70 static void ctl_putadr (const char *, u_int32,
72 static void ctl_putrefid (const char *, u_int32);
73 static void ctl_putarray (const char *, double *, int);
74 static void ctl_putsys (int);
75 static void ctl_putpeer (int, struct peer *);
76 static void ctl_putfs (const char *, tstamp_t);
77 static void ctl_printf (const char *, ...) NTP_PRINTF(1, 2);
79 static void ctl_putclock (int, struct refclockstat *, int);
81 static const struct ctl_var *ctl_getitem(const struct ctl_var *,
83 static u_short count_var (const struct ctl_var *);
84 static void control_unspec (struct recvbuf *, int);
85 static void read_status (struct recvbuf *, int);
86 static void read_sysvars (void);
87 static void read_peervars (void);
88 static void read_variables (struct recvbuf *, int);
89 static void write_variables (struct recvbuf *, int);
90 static void read_clockstatus(struct recvbuf *, int);
91 static void write_clockstatus(struct recvbuf *, int);
92 static void set_trap (struct recvbuf *, int);
93 static void save_config (struct recvbuf *, int);
94 static void configure (struct recvbuf *, int);
95 static void send_mru_entry (mon_entry *, int);
96 static void send_random_tag_value(int);
97 static void read_mru_list (struct recvbuf *, int);
98 static void send_ifstats_entry(endpt *, u_int);
99 static void read_ifstats (struct recvbuf *);
100 static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *,
102 static void send_restrict_entry(restrict_u *, int, u_int);
103 static void send_restrict_list(restrict_u *, int, u_int *);
104 static void read_addr_restrictions(struct recvbuf *);
105 static void read_ordlist (struct recvbuf *, int);
106 static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32);
107 static void generate_nonce (struct recvbuf *, char *, size_t);
108 static int validate_nonce (const char *, struct recvbuf *);
109 static void req_nonce (struct recvbuf *, int);
110 static void unset_trap (struct recvbuf *, int);
111 static struct ctl_trap *ctlfindtrap(sockaddr_u *,
114 int/*BOOL*/ is_safe_filename(const char * name);
116 static const struct ctl_proc control_codes[] = {
117 { CTL_OP_UNSPEC, NOAUTH, control_unspec },
118 { CTL_OP_READSTAT, NOAUTH, read_status },
119 { CTL_OP_READVAR, NOAUTH, read_variables },
120 { CTL_OP_WRITEVAR, AUTH, write_variables },
121 { CTL_OP_READCLOCK, NOAUTH, read_clockstatus },
122 { CTL_OP_WRITECLOCK, AUTH, write_clockstatus },
123 { CTL_OP_SETTRAP, AUTH, set_trap },
124 { CTL_OP_CONFIGURE, AUTH, configure },
125 { CTL_OP_SAVECONFIG, AUTH, save_config },
126 { CTL_OP_READ_MRU, NOAUTH, read_mru_list },
127 { CTL_OP_READ_ORDLIST_A, AUTH, read_ordlist },
128 { CTL_OP_REQ_NONCE, NOAUTH, req_nonce },
129 { CTL_OP_UNSETTRAP, AUTH, unset_trap },
130 { NO_REQUEST, 0, NULL }
134 * System variables we understand
138 #define CS_PRECISION 3
139 #define CS_ROOTDELAY 4
140 #define CS_ROOTDISPERSION 5
150 #define CS_PROCESSOR 15
152 #define CS_VERSION 17
154 #define CS_VARLIST 19
156 #define CS_LEAPTAB 21
157 #define CS_LEAPEND 22
159 #define CS_MRU_ENABLED 24
160 #define CS_MRU_DEPTH 25
161 #define CS_MRU_DEEPEST 26
162 #define CS_MRU_MINDEPTH 27
163 #define CS_MRU_MAXAGE 28
164 #define CS_MRU_MAXDEPTH 29
165 #define CS_MRU_MEM 30
166 #define CS_MRU_MAXMEM 31
167 #define CS_SS_UPTIME 32
168 #define CS_SS_RESET 33
169 #define CS_SS_RECEIVED 34
170 #define CS_SS_THISVER 35
171 #define CS_SS_OLDVER 36
172 #define CS_SS_BADFORMAT 37
173 #define CS_SS_BADAUTH 38
174 #define CS_SS_DECLINED 39
175 #define CS_SS_RESTRICTED 40
176 #define CS_SS_LIMITED 41
177 #define CS_SS_KODSENT 42
178 #define CS_SS_PROCESSED 43
179 #define CS_PEERADR 44
180 #define CS_PEERMODE 45
181 #define CS_BCASTDELAY 46
182 #define CS_AUTHDELAY 47
183 #define CS_AUTHKEYS 48
184 #define CS_AUTHFREEK 49
185 #define CS_AUTHKLOOKUPS 50
186 #define CS_AUTHKNOTFOUND 51
187 #define CS_AUTHKUNCACHED 52
188 #define CS_AUTHKEXPIRED 53
189 #define CS_AUTHENCRYPTS 54
190 #define CS_AUTHDECRYPTS 55
191 #define CS_AUTHRESET 56
192 #define CS_K_OFFSET 57
194 #define CS_K_MAXERR 59
195 #define CS_K_ESTERR 60
196 #define CS_K_STFLAGS 61
197 #define CS_K_TIMECONST 62
198 #define CS_K_PRECISION 63
199 #define CS_K_FREQTOL 64
200 #define CS_K_PPS_FREQ 65
201 #define CS_K_PPS_STABIL 66
202 #define CS_K_PPS_JITTER 67
203 #define CS_K_PPS_CALIBDUR 68
204 #define CS_K_PPS_CALIBS 69
205 #define CS_K_PPS_CALIBERRS 70
206 #define CS_K_PPS_JITEXC 71
207 #define CS_K_PPS_STBEXC 72
208 #define CS_KERN_FIRST CS_K_OFFSET
209 #define CS_KERN_LAST CS_K_PPS_STBEXC
210 #define CS_IOSTATS_RESET 73
211 #define CS_TOTAL_RBUF 74
212 #define CS_FREE_RBUF 75
213 #define CS_USED_RBUF 76
214 #define CS_RBUF_LOWATER 77
215 #define CS_IO_DROPPED 78
216 #define CS_IO_IGNORED 79
217 #define CS_IO_RECEIVED 80
218 #define CS_IO_SENT 81
219 #define CS_IO_SENDFAILED 82
220 #define CS_IO_WAKEUPS 83
221 #define CS_IO_GOODWAKEUPS 84
222 #define CS_TIMERSTATS_RESET 85
223 #define CS_TIMER_OVERRUNS 86
224 #define CS_TIMER_XMTS 87
226 #define CS_WANDER_THRESH 89
227 #define CS_LEAPSMEARINTV 90
228 #define CS_LEAPSMEAROFFS 91
229 #define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS
231 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
232 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
233 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
234 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
235 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
236 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
237 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
238 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
239 #define CS_MAXCODE CS_DIGEST
240 #else /* !AUTOKEY follows */
241 #define CS_MAXCODE CS_MAX_NOAUTOKEY
242 #endif /* !AUTOKEY */
245 * Peer variables we understand
248 #define CP_AUTHENABLE 2
249 #define CP_AUTHENTIC 3
256 #define CP_STRATUM 10
259 #define CP_PRECISION 13
260 #define CP_ROOTDELAY 14
261 #define CP_ROOTDISPERSION 15
263 #define CP_REFTIME 17
268 #define CP_UNREACH 22
273 #define CP_DISPERSION 27
275 #define CP_FILTDELAY 29
276 #define CP_FILTOFFSET 30
278 #define CP_RECEIVED 32
280 #define CP_FILTERROR 34
283 #define CP_VARLIST 37
288 #define CP_SRCHOST 42
289 #define CP_TIMEREC 43
290 #define CP_TIMEREACH 44
291 #define CP_BADAUTH 45
292 #define CP_BOGUSORG 46
294 #define CP_SELDISP 48
295 #define CP_SELBROKEN 49
296 #define CP_CANDIDATE 50
297 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
299 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
300 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
301 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
302 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
303 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
304 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
305 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
306 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
307 #define CP_MAXCODE CP_IDENT
308 #else /* !AUTOKEY follows */
309 #define CP_MAXCODE CP_MAX_NOAUTOKEY
310 #endif /* !AUTOKEY */
313 * Clock variables we understand
316 #define CC_TIMECODE 2
319 #define CC_BADFORMAT 5
321 #define CC_FUDGETIME1 7
322 #define CC_FUDGETIME2 8
323 #define CC_FUDGEVAL1 9
324 #define CC_FUDGEVAL2 10
327 #define CC_VARLIST 13
328 #define CC_MAXCODE CC_VARLIST
331 * System variable values. The array can be indexed by the variable
332 * index to find the textual name.
334 static const struct ctl_var sys_var[] = {
335 { 0, PADDING, "" }, /* 0 */
336 { CS_LEAP, RW, "leap" }, /* 1 */
337 { CS_STRATUM, RO, "stratum" }, /* 2 */
338 { CS_PRECISION, RO, "precision" }, /* 3 */
339 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
340 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
341 { CS_REFID, RO, "refid" }, /* 6 */
342 { CS_REFTIME, RO, "reftime" }, /* 7 */
343 { CS_POLL, RO, "tc" }, /* 8 */
344 { CS_PEERID, RO, "peer" }, /* 9 */
345 { CS_OFFSET, RO, "offset" }, /* 10 */
346 { CS_DRIFT, RO, "frequency" }, /* 11 */
347 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
348 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
349 { CS_CLOCK, RO, "clock" }, /* 14 */
350 { CS_PROCESSOR, RO, "processor" }, /* 15 */
351 { CS_SYSTEM, RO, "system" }, /* 16 */
352 { CS_VERSION, RO, "version" }, /* 17 */
353 { CS_STABIL, RO, "clk_wander" }, /* 18 */
354 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
355 { CS_TAI, RO, "tai" }, /* 20 */
356 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
357 { CS_LEAPEND, RO, "expire" }, /* 22 */
358 { CS_RATE, RO, "mintc" }, /* 23 */
359 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
360 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
361 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
362 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
363 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
364 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
365 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
366 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
367 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
368 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
369 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
370 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
371 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
372 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
373 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
374 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
375 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
376 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
377 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
378 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
379 { CS_PEERADR, RO, "peeradr" }, /* 44 */
380 { CS_PEERMODE, RO, "peermode" }, /* 45 */
381 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 46 */
382 { CS_AUTHDELAY, RO, "authdelay" }, /* 47 */
383 { CS_AUTHKEYS, RO, "authkeys" }, /* 48 */
384 { CS_AUTHFREEK, RO, "authfreek" }, /* 49 */
385 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 50 */
386 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 51 */
387 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 52 */
388 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 53 */
389 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 54 */
390 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 55 */
391 { CS_AUTHRESET, RO, "authreset" }, /* 56 */
392 { CS_K_OFFSET, RO, "koffset" }, /* 57 */
393 { CS_K_FREQ, RO, "kfreq" }, /* 58 */
394 { CS_K_MAXERR, RO, "kmaxerr" }, /* 59 */
395 { CS_K_ESTERR, RO, "kesterr" }, /* 60 */
396 { CS_K_STFLAGS, RO, "kstflags" }, /* 61 */
397 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 62 */
398 { CS_K_PRECISION, RO, "kprecis" }, /* 63 */
399 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 64 */
400 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 65 */
401 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 66 */
402 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 67 */
403 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 68 */
404 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 69 */
405 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 70 */
406 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 71 */
407 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 72 */
408 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 73 */
409 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 74 */
410 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 75 */
411 { CS_USED_RBUF, RO, "used_rbuf" }, /* 76 */
412 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 77 */
413 { CS_IO_DROPPED, RO, "io_dropped" }, /* 78 */
414 { CS_IO_IGNORED, RO, "io_ignored" }, /* 79 */
415 { CS_IO_RECEIVED, RO, "io_received" }, /* 80 */
416 { CS_IO_SENT, RO, "io_sent" }, /* 81 */
417 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 82 */
418 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 83 */
419 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 84 */
420 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 85 */
421 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 86 */
422 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 87 */
423 { CS_FUZZ, RO, "fuzz" }, /* 88 */
424 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 89 */
426 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 90 */
427 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 91 */
430 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
431 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
432 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
433 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
434 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
435 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
436 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
437 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
439 { 0, EOV, "" } /* 87/95 */
442 static struct ctl_var *ext_sys_var = NULL;
445 * System variables we print by default (in fuzzball order,
448 static const u_char def_sys_var[] = {
489 static const struct ctl_var peer_var[] = {
490 { 0, PADDING, "" }, /* 0 */
491 { CP_CONFIG, RO, "config" }, /* 1 */
492 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
493 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
494 { CP_SRCADR, RO, "srcadr" }, /* 4 */
495 { CP_SRCPORT, RO, "srcport" }, /* 5 */
496 { CP_DSTADR, RO, "dstadr" }, /* 6 */
497 { CP_DSTPORT, RO, "dstport" }, /* 7 */
498 { CP_LEAP, RO, "leap" }, /* 8 */
499 { CP_HMODE, RO, "hmode" }, /* 9 */
500 { CP_STRATUM, RO, "stratum" }, /* 10 */
501 { CP_PPOLL, RO, "ppoll" }, /* 11 */
502 { CP_HPOLL, RO, "hpoll" }, /* 12 */
503 { CP_PRECISION, RO, "precision" }, /* 13 */
504 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
505 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
506 { CP_REFID, RO, "refid" }, /* 16 */
507 { CP_REFTIME, RO, "reftime" }, /* 17 */
508 { CP_ORG, RO, "org" }, /* 18 */
509 { CP_REC, RO, "rec" }, /* 19 */
510 { CP_XMT, RO, "xleave" }, /* 20 */
511 { CP_REACH, RO, "reach" }, /* 21 */
512 { CP_UNREACH, RO, "unreach" }, /* 22 */
513 { CP_TIMER, RO, "timer" }, /* 23 */
514 { CP_DELAY, RO, "delay" }, /* 24 */
515 { CP_OFFSET, RO, "offset" }, /* 25 */
516 { CP_JITTER, RO, "jitter" }, /* 26 */
517 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
518 { CP_KEYID, RO, "keyid" }, /* 28 */
519 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
520 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
521 { CP_PMODE, RO, "pmode" }, /* 31 */
522 { CP_RECEIVED, RO, "received"}, /* 32 */
523 { CP_SENT, RO, "sent" }, /* 33 */
524 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
525 { CP_FLASH, RO, "flash" }, /* 35 */
526 { CP_TTL, RO, "ttl" }, /* 36 */
527 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
528 { CP_IN, RO, "in" }, /* 38 */
529 { CP_OUT, RO, "out" }, /* 39 */
530 { CP_RATE, RO, "headway" }, /* 40 */
531 { CP_BIAS, RO, "bias" }, /* 41 */
532 { CP_SRCHOST, RO, "srchost" }, /* 42 */
533 { CP_TIMEREC, RO, "timerec" }, /* 43 */
534 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
535 { CP_BADAUTH, RO, "badauth" }, /* 45 */
536 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
537 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
538 { CP_SELDISP, RO, "seldisp" }, /* 48 */
539 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
540 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
542 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
543 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
544 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
545 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
546 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
547 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
548 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
549 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
551 { 0, EOV, "" } /* 50/58 */
556 * Peer variables we print by default
558 static const u_char def_peer_var[] = {
607 * Clock variable list
609 static const struct ctl_var clock_var[] = {
610 { 0, PADDING, "" }, /* 0 */
611 { CC_TYPE, RO, "type" }, /* 1 */
612 { CC_TIMECODE, RO, "timecode" }, /* 2 */
613 { CC_POLL, RO, "poll" }, /* 3 */
614 { CC_NOREPLY, RO, "noreply" }, /* 4 */
615 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
616 { CC_BADDATA, RO, "baddata" }, /* 6 */
617 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
618 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
619 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
620 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
621 { CC_FLAGS, RO, "flags" }, /* 11 */
622 { CC_DEVICE, RO, "device" }, /* 12 */
623 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
624 { 0, EOV, "" } /* 14 */
629 * Clock variables printed by default
631 static const u_char def_clock_var[] = {
633 CC_TYPE, /* won't be output if device = known */
649 * MRU string constants shared by send_mru_entry() and read_mru_list().
651 static const char addr_fmt[] = "addr.%d";
652 static const char last_fmt[] = "last.%d";
655 * System and processor definitions.
659 # define STR_SYSTEM "UNIX"
661 # ifndef STR_PROCESSOR
662 # define STR_PROCESSOR "unknown"
665 static const char str_system[] = STR_SYSTEM;
666 static const char str_processor[] = STR_PROCESSOR;
668 # include <sys/utsname.h>
669 static struct utsname utsnamebuf;
670 #endif /* HAVE_UNAME */
673 * Trap structures. We only allow a few of these, and send a copy of
674 * each async message to each live one. Traps time out after an hour, it
675 * is up to the trap receipient to keep resetting it to avoid being
679 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
683 * Type bits, for ctlsettrap() call.
685 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
686 #define TRAP_TYPE_PRIO 1 /* priority trap */
687 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
691 * List relating reference clock types to control message time sources.
692 * Index by the reference clock type. This list will only be used iff
693 * the reference clock driver doesn't set peer->sstclktype to something
694 * different than CTL_SST_TS_UNSPEC.
697 static const u_char clocktypes[] = {
698 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
699 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
700 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
701 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
702 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
703 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
704 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
705 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
706 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
707 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
708 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
709 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
710 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
711 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
712 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
713 CTL_SST_TS_NTP, /* not used (15) */
714 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
715 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
716 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
717 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
718 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
719 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
720 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
721 CTL_SST_TS_NTP, /* not used (23) */
722 CTL_SST_TS_NTP, /* not used (24) */
723 CTL_SST_TS_NTP, /* not used (25) */
724 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
725 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
726 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
727 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
728 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
729 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
730 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
731 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
732 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
733 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
734 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
735 CTL_SST_TS_LF, /* REFCLK_FG (37) */
736 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
737 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
738 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
739 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
740 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
741 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
742 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
743 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
744 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
746 #endif /* REFCLOCK */
750 * Keyid used for authenticating write requests.
752 keyid_t ctl_auth_keyid;
755 * We keep track of the last error reported by the system internally
757 static u_char ctl_sys_last_event;
758 static u_char ctl_sys_num_events;
762 * Statistic counters to keep track of requests and responses.
764 u_long ctltimereset; /* time stats reset */
765 u_long numctlreq; /* number of requests we've received */
766 u_long numctlbadpkts; /* number of bad control packets */
767 u_long numctlresponses; /* number of resp packets sent with data */
768 u_long numctlfrags; /* number of fragments sent */
769 u_long numctlerrors; /* number of error responses sent */
770 u_long numctltooshort; /* number of too short input packets */
771 u_long numctlinputresp; /* number of responses on input */
772 u_long numctlinputfrag; /* number of fragments on input */
773 u_long numctlinputerr; /* number of input pkts with err bit set */
774 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
775 u_long numctlbadversion; /* number of input pkts with unknown version */
776 u_long numctldatatooshort; /* data too short for count */
777 u_long numctlbadop; /* bad op code found in packet */
778 u_long numasyncmsgs; /* number of async messages we've sent */
781 * Response packet used by these routines. Also some state information
782 * so that we can handle packet formatting within a common set of
783 * subroutines. Note we try to enter data in place whenever possible,
784 * but the need to set the more bit correctly means we occasionally
785 * use the extra buffer and copy.
787 static struct ntp_control rpkt;
788 static u_char res_version;
789 static u_char res_opcode;
790 static associd_t res_associd;
791 static u_short res_frags; /* datagrams in this response */
792 static int res_offset; /* offset of payload in response */
793 static u_char * datapt;
794 static u_char * dataend;
795 static int datalinelen;
796 static int datasent; /* flag to avoid initial ", " */
797 static int datanotbinflag;
798 static sockaddr_u *rmt_addr;
799 static struct interface *lcl_inter;
801 static u_char res_authenticate;
802 static u_char res_authokay;
803 static keyid_t res_keyid;
805 #define MAXDATALINELEN (72)
807 static u_char res_async; /* sending async trap response? */
810 * Pointers for saving state when decoding request packets
816 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
820 * init_control - initialize request data
829 #endif /* HAVE_UNAME */
834 ctl_sys_last_event = EVNT_UNSPEC;
835 ctl_sys_num_events = 0;
838 for (i = 0; i < COUNTOF(ctl_traps); i++)
839 ctl_traps[i].tr_flags = 0;
844 * ctl_error - send an error response for the current request
854 DPRINTF(3, ("sending control error %u\n", errcode));
857 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
858 * have already been filled in.
860 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
861 (res_opcode & CTL_OP_MASK);
862 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
866 * send packet and bump counters
868 if (res_authenticate && sys_authenticate) {
869 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
871 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
872 CTL_HEADER_LEN + maclen);
874 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
879 is_safe_filename(const char * name)
881 /* We need a strict validation of filenames we should write: The
882 * daemon might run with special permissions and is remote
883 * controllable, so we better take care what we allow as file
886 * The first character must be digit or a letter from the ASCII
887 * base plane or a '_' ([_A-Za-z0-9]), the following characters
888 * must be from [-._+A-Za-z0-9].
890 * We do not trust the character classification much here: Since
891 * the NTP protocol makes no provisions for UTF-8 or local code
892 * pages, we strictly require the 7bit ASCII code page.
894 * The following table is a packed bit field of 128 two-bit
895 * groups. The LSB in each group tells us if a character is
896 * acceptable at the first position, the MSB if the character is
897 * accepted at any other position.
899 * This does not ensure that the file name is syntactically
900 * correct (multiple dots will not work with VMS...) but it will
901 * exclude potential globbing bombs and directory traversal. It
902 * also rules out drive selection. (For systems that have this
903 * notion, like Windows or VMS.)
905 static const uint32_t chclass[8] = {
906 0x00000000, 0x00000000,
907 0x28800000, 0x000FFFFF,
908 0xFFFFFFFC, 0xC03FFFFF,
909 0xFFFFFFFC, 0x003FFFFF
912 u_int widx, bidx, mask;
913 if ( ! (name && *name))
917 while (0 != (widx = (u_char)*name++)) {
918 bidx = (widx & 15) << 1;
920 if (widx >= sizeof(chclass)/sizeof(chclass[0]))
922 if (0 == ((chclass[widx] >> bidx) & mask))
931 * save_config - Implements ntpq -c "saveconfig <filename>"
932 * Writes current configuration including any runtime
933 * changes by ntpq's :config or config-from-file
935 * Note: There should be no buffer overflow or truncation in the
936 * processing of file names -- both cause security problems. This is bit
937 * painful to code but essential here.
941 struct recvbuf *rbufp,
945 /* block directory traversal by searching for characters that
946 * indicate directory components in a file path.
948 * Conceptually we should be searching for DIRSEP in filename,
949 * however Windows actually recognizes both forward and
950 * backslashes as equivalent directory separators at the API
951 * level. On POSIX systems we could allow '\\' but such
952 * filenames are tricky to manipulate from a shell, so just
953 * reject both types of slashes on all platforms.
955 /* TALOS-CAN-0062: block directory traversal for VMS, too */
956 static const char * illegal_in_filename =
958 ":[]" /* do not allow drive and path components here */
959 #elif defined(SYS_WINNT)
960 ":\\/" /* path and drive separators */
962 "\\/" /* separator and critical char for POSIX */
967 static const char savedconfig_eq[] = "savedconfig=";
969 /* Build a safe open mode from the available mode flags. We want
970 * to create a new file and write it in text mode (when
971 * applicable -- only Windows does this...)
973 static const int openmode = O_CREAT | O_TRUNC | O_WRONLY
974 # if defined(O_EXCL) /* posix, vms */
976 # elif defined(_O_EXCL) /* windows is alway very special... */
979 # if defined(_O_TEXT) /* windows, again */
987 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
995 if (RES_NOMODIFY & restrict_mask) {
996 ctl_printf("%s", "saveconfig prohibited by restrict ... nomodify");
1000 "saveconfig from %s rejected due to nomodify restriction",
1001 stoa(&rbufp->recv_srcadr));
1007 if (NULL == saveconfigdir) {
1008 ctl_printf("%s", "saveconfig prohibited, no saveconfigdir configured");
1012 "saveconfig from %s rejected, no saveconfigdir",
1013 stoa(&rbufp->recv_srcadr));
1017 /* The length checking stuff gets serious. Do not assume a NUL
1018 * byte can be found, but if so, use it to calculate the needed
1019 * buffer size. If the available buffer is too short, bail out;
1020 * likewise if there is no file spec. (The latter will not
1021 * happen when using NTPQ, but there are other ways to craft a
1024 reqlen = (size_t)(reqend - reqpt);
1026 char * nulpos = (char*)memchr(reqpt, 0, reqlen);
1028 reqlen = (size_t)(nulpos - reqpt);
1032 if (reqlen >= sizeof(filespec)) {
1033 ctl_printf("saveconfig exceeded maximum raw name length (%u)",
1034 (u_int)sizeof(filespec));
1037 "saveconfig exceeded maximum raw name length from %s",
1038 stoa(&rbufp->recv_srcadr));
1042 /* copy data directly as we exactly know the size */
1043 memcpy(filespec, reqpt, reqlen);
1044 filespec[reqlen] = '\0';
1047 * allow timestamping of the saved config filename with
1048 * strftime() format such as:
1049 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
1050 * XXX: Nice feature, but not too safe.
1051 * YYY: The check for permitted characters in file names should
1052 * weed out the worst. Let's hope 'strftime()' does not
1053 * develop pathological problems.
1056 if (0 == strftime(filename, sizeof(filename), filespec,
1060 * If we arrive here, 'strftime()' balked; most likely
1061 * the buffer was too short. (Or it encounterd an empty
1062 * format, or just a format that expands to an empty
1063 * string.) We try to use the original name, though this
1064 * is very likely to fail later if there are format
1065 * specs in the string. Note that truncation cannot
1066 * happen here as long as both buffers have the same
1069 strlcpy(filename, filespec, sizeof(filename));
1073 * Check the file name for sanity. This might/will rule out file
1074 * names that would be legal but problematic, and it blocks
1075 * directory traversal.
1077 if (!is_safe_filename(filename)) {
1078 ctl_printf("saveconfig rejects unsafe file name '%s'",
1082 "saveconfig rejects unsafe file name from %s",
1083 stoa(&rbufp->recv_srcadr));
1088 * XXX: This next test may not be needed with is_safe_filename()
1091 /* block directory/drive traversal */
1092 /* TALOS-CAN-0062: block directory traversal for VMS, too */
1093 if (NULL != strpbrk(filename, illegal_in_filename)) {
1094 snprintf(reply, sizeof(reply),
1095 "saveconfig does not allow directory in filename");
1096 ctl_putdata(reply, strlen(reply), 0);
1099 "saveconfig rejects unsafe file name from %s",
1100 stoa(&rbufp->recv_srcadr));
1104 /* concatenation of directory and path can cause another
1107 prc = snprintf(fullpath, sizeof(fullpath), "%s%s",
1108 saveconfigdir, filename);
1109 if (prc < 0 || prc >= sizeof(fullpath)) {
1110 ctl_printf("saveconfig exceeded maximum path length (%u)",
1111 (u_int)sizeof(fullpath));
1114 "saveconfig exceeded maximum path length from %s",
1115 stoa(&rbufp->recv_srcadr));
1119 fd = open(fullpath, openmode, S_IRUSR | S_IWUSR);
1123 fptr = fdopen(fd, "w");
1125 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
1126 ctl_printf("Unable to save configuration to file '%s': %m",
1129 "saveconfig %s from %s failed", filename,
1130 stoa(&rbufp->recv_srcadr));
1132 ctl_printf("Configuration saved to '%s'", filename);
1134 "Configuration saved to '%s' (requested by %s)",
1135 fullpath, stoa(&rbufp->recv_srcadr));
1137 * save the output filename in system variable
1138 * savedconfig, retrieved with:
1139 * ntpq -c "rv 0 savedconfig"
1140 * Note: the way 'savedconfig' is defined makes overflow
1141 * checks unnecessary here.
1143 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
1144 savedconfig_eq, filename);
1145 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1150 #else /* !SAVECONFIG follows */
1152 "saveconfig unavailable, configured with --disable-saveconfig");
1159 * process_control - process an incoming control message
1163 struct recvbuf *rbufp,
1167 struct ntp_control *pkt;
1170 const struct ctl_proc *cc;
1175 DPRINTF(3, ("in process_control()\n"));
1178 * Save the addresses for error responses
1181 rmt_addr = &rbufp->recv_srcadr;
1182 lcl_inter = rbufp->dstadr;
1183 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1186 * If the length is less than required for the header, or
1187 * it is a response or a fragment, ignore this.
1189 if (rbufp->recv_length < (int)CTL_HEADER_LEN
1190 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1191 || pkt->offset != 0) {
1192 DPRINTF(1, ("invalid format in control packet\n"));
1193 if (rbufp->recv_length < (int)CTL_HEADER_LEN)
1195 if (CTL_RESPONSE & pkt->r_m_e_op)
1197 if (CTL_MORE & pkt->r_m_e_op)
1199 if (CTL_ERROR & pkt->r_m_e_op)
1201 if (pkt->offset != 0)
1205 res_version = PKT_VERSION(pkt->li_vn_mode);
1206 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1207 DPRINTF(1, ("unknown version %d in control packet\n",
1214 * Pull enough data from the packet to make intelligent
1217 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1219 res_opcode = pkt->r_m_e_op;
1220 rpkt.sequence = pkt->sequence;
1221 rpkt.associd = pkt->associd;
1225 res_associd = htons(pkt->associd);
1227 res_authenticate = FALSE;
1229 res_authokay = FALSE;
1230 req_count = (int)ntohs(pkt->count);
1231 datanotbinflag = FALSE;
1234 datapt = rpkt.u.data;
1235 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1237 if ((rbufp->recv_length & 0x3) != 0)
1238 DPRINTF(3, ("Control packet length %d unrounded\n",
1239 rbufp->recv_length));
1242 * We're set up now. Make sure we've got at least enough
1243 * incoming data space to match the count.
1245 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1246 if (req_data < req_count || rbufp->recv_length & 0x3) {
1247 ctl_error(CERR_BADFMT);
1248 numctldatatooshort++;
1252 properlen = req_count + CTL_HEADER_LEN;
1253 /* round up proper len to a 8 octet boundary */
1255 properlen = (properlen + 7) & ~7;
1256 maclen = rbufp->recv_length - properlen;
1257 if ((rbufp->recv_length & 3) == 0 &&
1258 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1260 res_authenticate = TRUE;
1261 pkid = (void *)((char *)pkt + properlen);
1262 res_keyid = ntohl(*pkid);
1263 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1264 rbufp->recv_length, properlen, res_keyid,
1267 if (!authistrusted(res_keyid))
1268 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1269 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1270 rbufp->recv_length - maclen,
1272 res_authokay = TRUE;
1273 DPRINTF(3, ("authenticated okay\n"));
1276 DPRINTF(3, ("authentication failed\n"));
1281 * Set up translate pointers
1283 reqpt = (char *)pkt->u.data;
1284 reqend = reqpt + req_count;
1287 * Look for the opcode processor
1289 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1290 if (cc->control_code == res_opcode) {
1291 DPRINTF(3, ("opcode %d, found command handler\n",
1293 if (cc->flags == AUTH
1295 || res_keyid != ctl_auth_keyid)) {
1296 ctl_error(CERR_PERMISSION);
1299 (cc->handler)(rbufp, restrict_mask);
1305 * Can't find this one, return an error.
1308 ctl_error(CERR_BADOP);
1314 * ctlpeerstatus - return a status word for this peer
1318 register struct peer *p
1324 if (FLAG_CONFIG & p->flags)
1325 status |= CTL_PST_CONFIG;
1327 status |= CTL_PST_AUTHENABLE;
1328 if (FLAG_AUTHENTIC & p->flags)
1329 status |= CTL_PST_AUTHENTIC;
1331 status |= CTL_PST_REACH;
1332 if (MDF_TXONLY_MASK & p->cast_flags)
1333 status |= CTL_PST_BCAST;
1335 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1340 * ctlclkstatus - return a status word for this clock
1345 struct refclockstat *pcs
1348 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1354 * ctlsysstatus - return the system status word
1359 register u_char this_clock;
1361 this_clock = CTL_SST_TS_UNSPEC;
1363 if (sys_peer != NULL) {
1364 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1365 this_clock = sys_peer->sstclktype;
1366 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1367 this_clock = clocktypes[sys_peer->refclktype];
1369 #else /* REFCLOCK */
1371 this_clock = CTL_SST_TS_NTP;
1372 #endif /* REFCLOCK */
1373 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1374 ctl_sys_last_event);
1379 * ctl_flushpkt - write out the current packet and prepare
1380 * another if necessary.
1394 dlen = datapt - rpkt.u.data;
1395 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1397 * Big hack, output a trailing \r\n
1403 sendlen = dlen + CTL_HEADER_LEN;
1406 * Pad to a multiple of 32 bits
1408 while (sendlen & 0x3) {
1414 * Fill in the packet with the current info
1416 rpkt.r_m_e_op = CTL_RESPONSE | more |
1417 (res_opcode & CTL_OP_MASK);
1418 rpkt.count = htons((u_short)dlen);
1419 rpkt.offset = htons((u_short)res_offset);
1421 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1422 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1426 ctl_traps[i].tr_version,
1429 htons(ctl_traps[i].tr_sequence);
1430 sendpkt(&ctl_traps[i].tr_addr,
1431 ctl_traps[i].tr_localaddr, -4,
1432 (struct pkt *)&rpkt, sendlen);
1434 ctl_traps[i].tr_sequence++;
1439 if (res_authenticate && sys_authenticate) {
1442 * If we are going to authenticate, then there
1443 * is an additional requirement that the MAC
1444 * begin on a 64 bit boundary.
1446 while (totlen & 7) {
1450 keyid = htonl(res_keyid);
1451 memcpy(datapt, &keyid, sizeof(keyid));
1452 maclen = authencrypt(res_keyid,
1453 (u_int32 *)&rpkt, totlen);
1454 sendpkt(rmt_addr, lcl_inter, -5,
1455 (struct pkt *)&rpkt, totlen + maclen);
1457 sendpkt(rmt_addr, lcl_inter, -6,
1458 (struct pkt *)&rpkt, sendlen);
1467 * Set us up for another go around.
1471 datapt = rpkt.u.data;
1476 * ctl_putdata - write data into the packet, fragmenting and starting
1477 * another if this one is full.
1483 int bin /* set to 1 when data is binary */
1487 unsigned int currentlen;
1491 datanotbinflag = TRUE;
1496 if ((dlen + datalinelen + 1) >= MAXDATALINELEN) {
1508 * Save room for trailing junk
1510 while (dlen + overhead + datapt > dataend) {
1512 * Not enough room in this one, flush it out.
1514 currentlen = MIN(dlen, (unsigned int)(dataend - datapt));
1516 memcpy(datapt, dp, currentlen);
1518 datapt += currentlen;
1521 datalinelen += currentlen;
1523 ctl_flushpkt(CTL_MORE);
1526 memcpy(datapt, dp, dlen);
1528 datalinelen += dlen;
1534 * ctl_putstr - write a tagged string into the response packet
1539 * len is the data length excluding the NUL terminator,
1540 * as in ctl_putstr("var", "value", strlen("value"));
1552 INSIST(len < sizeof(buffer));
1554 rc = snprintf(buffer, sizeof(buffer), "%s=\"%.*s\"", tag, (int)len, data);
1556 rc = snprintf(buffer, sizeof(buffer), "%s", tag);
1557 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1558 ctl_putdata(buffer, (u_int)rc, 0);
1563 * ctl_putunqstr - write a tagged string into the response packet
1568 * len is the data length excluding the NUL terminator.
1569 * data must not contain a comma or whitespace.
1581 INSIST(len < sizeof(buffer));
1583 rc = snprintf(buffer, sizeof(buffer), "%s=%.*s", tag, (int)len, data);
1585 rc = snprintf(buffer, sizeof(buffer), "%s", tag);
1586 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1587 ctl_putdata(buffer, (u_int)rc, 0);
1592 * ctl_putdblf - write a tagged, signed double into the response packet
1605 rc = snprintf(buffer, sizeof(buffer),
1606 (use_f ? "%s=%.*f" : "%s=%.*g"),
1608 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1609 ctl_putdata(buffer, (u_int)rc, 0);
1613 * ctl_putuint - write a tagged unsigned integer into the response
1624 rc = snprintf(buffer, sizeof(buffer), "%s=%lu", tag, uval);
1625 INSIST(rc >= 0 && rc < sizeof(buffer));
1626 ctl_putdata(buffer, (u_int)rc, 0);
1630 * ctl_putcal - write a decoded calendar data into the response.
1631 * only used with AUTOKEY currently, so compiled conditional
1637 const struct calendar *pcal
1643 rc = snprintf(buffer, sizeof(buffer),
1644 "%s=%04d%02d%02d%02d%02d",
1646 pcal->year, pcal->month, pcal->monthday,
1647 pcal->hour, pcal->minute
1649 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1650 ctl_putdata(buffer, (u_int)rc, 0);
1655 * ctl_putfs - write a decoded filestamp into the response
1664 struct tm *tm = NULL;
1668 fstamp = (time_t)uval - JAN_1970;
1669 tm = gmtime(&fstamp);
1673 rc = snprintf(buffer, sizeof(buffer),
1674 "%s=%04d%02d%02d%02d%02d",
1676 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1677 tm->tm_hour, tm->tm_min);
1678 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1679 ctl_putdata(buffer, (u_int)rc, 0);
1684 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1696 rc = snprintf(buffer, sizeof(buffer), "%s=0x%lx", tag, uval);
1697 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1698 ctl_putdata(buffer, (u_int)rc, 0);
1703 * ctl_putint - write a tagged signed integer into the response
1714 rc = snprintf(buffer, sizeof(buffer), "%s=%ld", tag, ival);
1715 INSIST(rc >= 0 && rc < sizeof(buffer));
1716 ctl_putdata(buffer, (u_int)rc, 0);
1721 * ctl_putts - write a tagged timestamp, in hex, into the response
1732 rc = snprintf(buffer, sizeof(buffer),
1734 tag, (u_long)ts->l_ui, (u_long)ts->l_uf);
1735 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1736 ctl_putdata(buffer, (u_int)rc, 0);
1741 * ctl_putadr - write an IP address into the response
1755 cq = numtoa(addr32);
1758 rc = snprintf(buffer, sizeof(buffer), "%s=%s", tag, cq);
1759 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1760 ctl_putdata(buffer, (u_int)rc, 0);
1765 * ctl_putrefid - send a u_int32 refid as printable text
1778 uint8_t b[sizeof(uint32_t)];
1782 for (i = 0; i < sizeof(bytes.b); ++i)
1783 if (bytes.b[i] && !isprint(bytes.b[i]))
1785 rc = snprintf(buffer, sizeof(buffer), "%s=%.*s",
1786 tag, (int)sizeof(bytes.b), bytes.b);
1787 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1788 ctl_putdata(buffer, (u_int)rc, FALSE);
1793 * ctl_putarray - write a tagged eight element double array into the response
1807 ep = buffer + sizeof(buffer);
1809 rc = snprintf(cp, (size_t)(ep - cp), "%s=", tag);
1810 INSIST(rc >= 0 && rc < (ep - cp));
1818 rc = snprintf(cp, (size_t)(ep - cp), " %.2f", arr[i] * 1e3);
1819 INSIST(rc >= 0 && rc < (ep - cp));
1821 } while (i != start);
1822 ctl_putdata(buffer, (u_int)(cp - buffer), 0);
1826 * ctl_printf - put a formatted string into the data buffer
1834 static const char * ellipsis = "[...]";
1840 rc = vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, va);
1842 if (rc < 0 || rc >= sizeof(fmtbuf))
1843 strcpy(fmtbuf + sizeof(fmtbuf) - strlen(ellipsis) - 1,
1845 ctl_putdata(fmtbuf, strlen(fmtbuf), 0);
1850 * ctl_putsys - output a system variable
1864 struct cert_info *cp;
1865 #endif /* AUTOKEY */
1867 static struct timex ntx;
1868 static u_long ntp_adjtime_time;
1870 static const double to_ms =
1872 1.0e-6; /* nsec to msec */
1874 1.0e-3; /* usec to msec */
1878 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1880 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1881 current_time != ntp_adjtime_time) {
1883 if (ntp_adjtime(&ntx) < 0)
1884 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1886 ntp_adjtime_time = current_time;
1888 #endif /* KERNEL_PLL */
1893 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1897 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1901 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1905 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1909 case CS_ROOTDISPERSION:
1910 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1911 sys_rootdisp * 1e3);
1915 if (sys_stratum > 1 && sys_stratum < STRATUM_UNSPEC)
1916 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1918 ctl_putrefid(sys_var[varid].text, sys_refid);
1922 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1926 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
1930 if (sys_peer == NULL)
1931 ctl_putuint(sys_var[CS_PEERID].text, 0);
1933 ctl_putuint(sys_var[CS_PEERID].text,
1938 if (sys_peer != NULL && sys_peer->dstadr != NULL)
1939 ss = sptoa(&sys_peer->srcadr);
1942 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
1946 u = (sys_peer != NULL)
1949 ctl_putuint(sys_var[CS_PEERMODE].text, u);
1953 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
1957 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
1961 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
1965 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
1970 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
1975 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
1976 sizeof(str_processor) - 1);
1978 ctl_putstr(sys_var[CS_PROCESSOR].text,
1979 utsnamebuf.machine, strlen(utsnamebuf.machine));
1980 #endif /* HAVE_UNAME */
1985 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
1986 sizeof(str_system) - 1);
1988 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
1989 utsnamebuf.release);
1990 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
1991 #endif /* HAVE_UNAME */
1995 ctl_putstr(sys_var[CS_VERSION].text, Version,
2000 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
2006 char buf[CTL_MAX_DATA_LEN];
2007 //buffPointer, firstElementPointer, buffEndPointer
2008 char *buffp, *buffend;
2012 const struct ctl_var *k;
2015 buffend = buf + sizeof(buf);
2016 if (strlen(sys_var[CS_VARLIST].text) > (sizeof(buf) - 4))
2017 break; /* really long var name */
2019 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
2020 buffp += strlen(buffp);
2021 firstVarName = TRUE;
2022 for (k = sys_var; !(k->flags & EOV); k++) {
2023 if (k->flags & PADDING)
2025 len = strlen(k->text);
2026 if (len + 1 >= buffend - buffp)
2031 firstVarName = FALSE;
2032 memcpy(buffp, k->text, len);
2036 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
2037 if (k->flags & PADDING)
2039 if (NULL == k->text)
2041 ss1 = strchr(k->text, '=');
2043 len = strlen(k->text);
2045 len = ss1 - k->text;
2046 if (len + 1 >= buffend - buffp)
2050 firstVarName = FALSE;
2052 memcpy(buffp, k->text,(unsigned)len);
2055 if (2 >= buffend - buffp)
2061 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
2067 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
2072 leap_signature_t lsig;
2073 leapsec_getsig(&lsig);
2075 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
2081 leap_signature_t lsig;
2082 leapsec_getsig(&lsig);
2084 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2089 case CS_LEAPSMEARINTV:
2090 if (leap_smear_intv > 0)
2091 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2094 case CS_LEAPSMEAROFFS:
2095 if (leap_smear_intv > 0)
2096 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2097 leap_smear.doffset * 1e3);
2099 #endif /* LEAP_SMEAR */
2102 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2105 case CS_MRU_ENABLED:
2106 ctl_puthex(sys_var[varid].text, mon_enabled);
2110 ctl_putuint(sys_var[varid].text, mru_entries);
2114 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2118 ctl_putuint(sys_var[varid].text, u);
2121 case CS_MRU_DEEPEST:
2122 ctl_putuint(sys_var[varid].text, mru_peakentries);
2125 case CS_MRU_MINDEPTH:
2126 ctl_putuint(sys_var[varid].text, mru_mindepth);
2130 ctl_putint(sys_var[varid].text, mru_maxage);
2133 case CS_MRU_MAXDEPTH:
2134 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2138 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2142 ctl_putuint(sys_var[varid].text, u);
2146 ctl_putuint(sys_var[varid].text, current_time);
2150 ctl_putuint(sys_var[varid].text,
2151 current_time - sys_stattime);
2154 case CS_SS_RECEIVED:
2155 ctl_putuint(sys_var[varid].text, sys_received);
2159 ctl_putuint(sys_var[varid].text, sys_newversion);
2163 ctl_putuint(sys_var[varid].text, sys_oldversion);
2166 case CS_SS_BADFORMAT:
2167 ctl_putuint(sys_var[varid].text, sys_badlength);
2171 ctl_putuint(sys_var[varid].text, sys_badauth);
2174 case CS_SS_DECLINED:
2175 ctl_putuint(sys_var[varid].text, sys_declined);
2178 case CS_SS_RESTRICTED:
2179 ctl_putuint(sys_var[varid].text, sys_restricted);
2183 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2187 ctl_putuint(sys_var[varid].text, sys_kodsent);
2190 case CS_SS_PROCESSED:
2191 ctl_putuint(sys_var[varid].text, sys_processed);
2195 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2199 LFPTOD(&sys_authdelay, dtemp);
2200 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2204 ctl_putuint(sys_var[varid].text, authnumkeys);
2208 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2211 case CS_AUTHKLOOKUPS:
2212 ctl_putuint(sys_var[varid].text, authkeylookups);
2215 case CS_AUTHKNOTFOUND:
2216 ctl_putuint(sys_var[varid].text, authkeynotfound);
2219 case CS_AUTHKUNCACHED:
2220 ctl_putuint(sys_var[varid].text, authkeyuncached);
2223 case CS_AUTHKEXPIRED:
2224 ctl_putuint(sys_var[varid].text, authkeyexpired);
2227 case CS_AUTHENCRYPTS:
2228 ctl_putuint(sys_var[varid].text, authencryptions);
2231 case CS_AUTHDECRYPTS:
2232 ctl_putuint(sys_var[varid].text, authdecryptions);
2236 ctl_putuint(sys_var[varid].text,
2237 current_time - auth_timereset);
2241 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2242 * unavailable, otherwise calls putfunc with args.
2245 # define CTL_IF_KERNLOOP(putfunc, args) \
2246 ctl_putint(sys_var[varid].text, 0)
2248 # define CTL_IF_KERNLOOP(putfunc, args) \
2253 * CTL_IF_KERNPPS() puts a zero if either the kernel
2254 * loop is unavailable, or kernel hard PPS is not
2255 * active, otherwise calls putfunc with args.
2258 # define CTL_IF_KERNPPS(putfunc, args) \
2259 ctl_putint(sys_var[varid].text, 0)
2261 # define CTL_IF_KERNPPS(putfunc, args) \
2262 if (0 == ntx.shift) \
2263 ctl_putint(sys_var[varid].text, 0); \
2265 putfunc args /* no trailing ; */
2271 (sys_var[varid].text, 0, -1, to_ms * ntx.offset)
2278 (sys_var[varid].text, ntx.freq)
2285 (sys_var[varid].text, 0, 6,
2286 to_ms * ntx.maxerror)
2293 (sys_var[varid].text, 0, 6,
2294 to_ms * ntx.esterror)
2302 ss = k_st_flags(ntx.status);
2304 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2307 case CS_K_TIMECONST:
2310 (sys_var[varid].text, ntx.constant)
2314 case CS_K_PRECISION:
2317 (sys_var[varid].text, 0, 6,
2318 to_ms * ntx.precision)
2325 (sys_var[varid].text, ntx.tolerance)
2332 (sys_var[varid].text, ntx.ppsfreq)
2336 case CS_K_PPS_STABIL:
2339 (sys_var[varid].text, ntx.stabil)
2343 case CS_K_PPS_JITTER:
2346 (sys_var[varid].text, to_ms * ntx.jitter)
2350 case CS_K_PPS_CALIBDUR:
2353 (sys_var[varid].text, 1 << ntx.shift)
2357 case CS_K_PPS_CALIBS:
2360 (sys_var[varid].text, ntx.calcnt)
2364 case CS_K_PPS_CALIBERRS:
2367 (sys_var[varid].text, ntx.errcnt)
2371 case CS_K_PPS_JITEXC:
2374 (sys_var[varid].text, ntx.jitcnt)
2378 case CS_K_PPS_STBEXC:
2381 (sys_var[varid].text, ntx.stbcnt)
2385 case CS_IOSTATS_RESET:
2386 ctl_putuint(sys_var[varid].text,
2387 current_time - io_timereset);
2391 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2395 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2399 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2402 case CS_RBUF_LOWATER:
2403 ctl_putuint(sys_var[varid].text, lowater_additions());
2407 ctl_putuint(sys_var[varid].text, packets_dropped);
2411 ctl_putuint(sys_var[varid].text, packets_ignored);
2414 case CS_IO_RECEIVED:
2415 ctl_putuint(sys_var[varid].text, packets_received);
2419 ctl_putuint(sys_var[varid].text, packets_sent);
2422 case CS_IO_SENDFAILED:
2423 ctl_putuint(sys_var[varid].text, packets_notsent);
2427 ctl_putuint(sys_var[varid].text, handler_calls);
2430 case CS_IO_GOODWAKEUPS:
2431 ctl_putuint(sys_var[varid].text, handler_pkts);
2434 case CS_TIMERSTATS_RESET:
2435 ctl_putuint(sys_var[varid].text,
2436 current_time - timer_timereset);
2439 case CS_TIMER_OVERRUNS:
2440 ctl_putuint(sys_var[varid].text, alarm_overflow);
2444 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2448 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2450 case CS_WANDER_THRESH:
2451 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2456 ctl_puthex(sys_var[CS_FLAGS].text,
2462 strlcpy(str, OBJ_nid2ln(crypto_nid),
2464 ctl_putstr(sys_var[CS_DIGEST].text, str,
2473 dp = EVP_get_digestbynid(crypto_flags >> 16);
2474 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2476 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2482 if (hostval.ptr != NULL)
2483 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2484 strlen(hostval.ptr));
2488 if (sys_ident != NULL)
2489 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2494 for (cp = cinfo; cp != NULL; cp = cp->link) {
2495 snprintf(str, sizeof(str), "%s %s 0x%x",
2496 cp->subject, cp->issuer, cp->flags);
2497 ctl_putstr(sys_var[CS_CERTIF].text, str,
2499 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2504 if (hostval.tstamp != 0)
2505 ctl_putfs(sys_var[CS_PUBLIC].text,
2506 ntohl(hostval.tstamp));
2508 #endif /* AUTOKEY */
2517 * ctl_putpeer - output a peer variable
2525 char buf[CTL_MAX_DATA_LEN];
2530 const struct ctl_var *k;
2535 #endif /* AUTOKEY */
2540 ctl_putuint(peer_var[id].text,
2541 !(FLAG_PREEMPT & p->flags));
2545 ctl_putuint(peer_var[id].text, !(p->keyid));
2549 ctl_putuint(peer_var[id].text,
2550 !!(FLAG_AUTHENTIC & p->flags));
2554 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2558 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2562 if (p->hostname != NULL)
2563 ctl_putstr(peer_var[id].text, p->hostname,
2564 strlen(p->hostname));
2568 ctl_putadr(peer_var[id].text, 0,
2575 ctl_putuint(peer_var[id].text,
2577 ? SRCPORT(&p->dstadr->sin)
2583 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2588 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2592 ctl_putuint(peer_var[id].text, p->throttle);
2596 ctl_putuint(peer_var[id].text, p->leap);
2600 ctl_putuint(peer_var[id].text, p->hmode);
2604 ctl_putuint(peer_var[id].text, p->stratum);
2608 ctl_putuint(peer_var[id].text, p->ppoll);
2612 ctl_putuint(peer_var[id].text, p->hpoll);
2616 ctl_putint(peer_var[id].text, p->precision);
2620 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2623 case CP_ROOTDISPERSION:
2624 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2629 if (p->flags & FLAG_REFCLOCK) {
2630 ctl_putrefid(peer_var[id].text, p->refid);
2634 if (p->stratum > 1 && p->stratum < STRATUM_UNSPEC)
2635 ctl_putadr(peer_var[id].text, p->refid,
2638 ctl_putrefid(peer_var[id].text, p->refid);
2642 ctl_putts(peer_var[id].text, &p->reftime);
2646 ctl_putts(peer_var[id].text, &p->aorg);
2650 ctl_putts(peer_var[id].text, &p->dst);
2655 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2660 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2664 ctl_puthex(peer_var[id].text, p->reach);
2668 ctl_puthex(peer_var[id].text, p->flash);
2673 if (p->flags & FLAG_REFCLOCK) {
2674 ctl_putuint(peer_var[id].text, p->ttl);
2678 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2679 ctl_putint(peer_var[id].text,
2684 ctl_putuint(peer_var[id].text, p->unreach);
2688 ctl_putuint(peer_var[id].text,
2689 p->nextdate - current_time);
2693 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2697 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2701 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2705 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2709 if (p->keyid > NTP_MAXKEY)
2710 ctl_puthex(peer_var[id].text, p->keyid);
2712 ctl_putuint(peer_var[id].text, p->keyid);
2716 ctl_putarray(peer_var[id].text, p->filter_delay,
2721 ctl_putarray(peer_var[id].text, p->filter_offset,
2726 ctl_putarray(peer_var[id].text, p->filter_disp,
2731 ctl_putuint(peer_var[id].text, p->pmode);
2735 ctl_putuint(peer_var[id].text, p->received);
2739 ctl_putuint(peer_var[id].text, p->sent);
2744 be = buf + sizeof(buf);
2745 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2746 break; /* really long var name */
2748 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2751 for (k = peer_var; !(EOV & k->flags); k++) {
2752 if (PADDING & k->flags)
2754 i = strlen(k->text);
2755 if (s + i + 1 >= be)
2759 memcpy(s, k->text, i);
2765 ctl_putdata(buf, (u_int)(s - buf), 0);
2770 ctl_putuint(peer_var[id].text,
2771 current_time - p->timereceived);
2775 ctl_putuint(peer_var[id].text,
2776 current_time - p->timereachable);
2780 ctl_putuint(peer_var[id].text, p->badauth);
2784 ctl_putuint(peer_var[id].text, p->bogusorg);
2788 ctl_putuint(peer_var[id].text, p->oldpkt);
2792 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2796 ctl_putuint(peer_var[id].text, p->selbroken);
2800 ctl_putuint(peer_var[id].text, p->status);
2805 ctl_puthex(peer_var[id].text, p->crypto);
2810 dp = EVP_get_digestbynid(p->crypto >> 16);
2811 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2812 ctl_putstr(peer_var[id].text, str, strlen(str));
2817 if (p->subject != NULL)
2818 ctl_putstr(peer_var[id].text, p->subject,
2819 strlen(p->subject));
2822 case CP_VALID: /* not used */
2826 if (NULL == (ap = p->recval.ptr))
2829 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2830 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2831 ctl_putfs(peer_var[CP_INITTSP].text,
2832 ntohl(p->recval.tstamp));
2836 if (p->ident != NULL)
2837 ctl_putstr(peer_var[id].text, p->ident,
2842 #endif /* AUTOKEY */
2849 * ctl_putclock - output clock variables
2854 struct refclockstat *pcs,
2858 char buf[CTL_MAX_DATA_LEN];
2862 const struct ctl_var *k;
2867 if (mustput || pcs->clockdesc == NULL
2868 || *(pcs->clockdesc) == '\0') {
2869 ctl_putuint(clock_var[id].text, pcs->type);
2873 ctl_putstr(clock_var[id].text,
2875 (unsigned)pcs->lencode);
2879 ctl_putuint(clock_var[id].text, pcs->polls);
2883 ctl_putuint(clock_var[id].text,
2888 ctl_putuint(clock_var[id].text,
2893 ctl_putuint(clock_var[id].text,
2898 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2899 ctl_putdbl(clock_var[id].text,
2900 pcs->fudgetime1 * 1e3);
2904 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2905 ctl_putdbl(clock_var[id].text,
2906 pcs->fudgetime2 * 1e3);
2910 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2911 ctl_putint(clock_var[id].text,
2916 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2917 if (pcs->fudgeval1 > 1)
2918 ctl_putadr(clock_var[id].text,
2919 pcs->fudgeval2, NULL);
2921 ctl_putrefid(clock_var[id].text,
2927 ctl_putuint(clock_var[id].text, pcs->flags);
2931 if (pcs->clockdesc == NULL ||
2932 *(pcs->clockdesc) == '\0') {
2934 ctl_putstr(clock_var[id].text,
2937 ctl_putstr(clock_var[id].text,
2939 strlen(pcs->clockdesc));
2945 be = buf + sizeof(buf);
2946 if (strlen(clock_var[CC_VARLIST].text) + 4 >
2948 break; /* really long var name */
2950 snprintf(s, sizeof(buf), "%s=\"",
2951 clock_var[CC_VARLIST].text);
2955 for (k = clock_var; !(EOV & k->flags); k++) {
2956 if (PADDING & k->flags)
2959 i = strlen(k->text);
2960 if (s + i + 1 >= be)
2965 memcpy(s, k->text, i);
2969 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
2970 if (PADDING & k->flags)
2977 while (*ss && *ss != '=')
2980 if (s + i + 1 >= be)
2985 memcpy(s, k->text, (unsigned)i);
2994 ctl_putdata(buf, (unsigned)(s - buf), 0);
3003 * ctl_getitem - get the next data item from the incoming packet
3005 static const struct ctl_var *
3007 const struct ctl_var *var_list,
3011 /* [Bug 3008] First check the packet data sanity, then search
3012 * the key. This improves the consistency of result values: If
3013 * the result is NULL once, it will never be EOV again for this
3014 * packet; If it's EOV, it will never be NULL again until the
3015 * variable is found and processed in a given 'var_list'. (That
3016 * is, a result is returned that is neither NULL nor EOV).
3018 static const struct ctl_var eol = { 0, EOV, NULL };
3019 static char buf[128];
3020 static u_long quiet_until;
3021 const struct ctl_var *v;
3026 * Part One: Validate the packet state
3029 /* Delete leading commas and white space */
3030 while (reqpt < reqend && (*reqpt == ',' ||
3031 isspace((unsigned char)*reqpt)))
3033 if (reqpt >= reqend)
3036 /* Scan the string in the packet until we hit comma or
3037 * EoB. Register position of first '=' on the fly. */
3038 for (tp = NULL, cp = reqpt; cp != reqend; ++cp) {
3039 if (*cp == '=' && tp == NULL)
3045 /* Process payload, if any. */
3048 /* eventually strip white space from argument. */
3049 const char *plhead = tp + 1; /* skip the '=' */
3050 const char *pltail = cp;
3053 while (plhead != pltail && isspace((u_char)plhead[0]))
3055 while (plhead != pltail && isspace((u_char)pltail[-1]))
3058 /* check payload size, terminate packet on overflow */
3059 plsize = (size_t)(pltail - plhead);
3060 if (plsize >= sizeof(buf))
3063 /* copy data, NUL terminate, and set result data ptr */
3064 memcpy(buf, plhead, plsize);
3068 /* no payload, current end --> current name termination */
3074 * Now we're sure that the packet data itself is sane. Scan the
3075 * list now. Make sure a NULL list is properly treated by
3076 * returning a synthetic End-Of-Values record. We must not
3077 * return NULL pointers after this point, or the behaviour would
3078 * become inconsistent if called several times with different
3079 * variable lists after an EoV was returned. (Such a behavior
3080 * actually caused Bug 3008.)
3083 if (NULL == var_list)
3086 for (v = var_list; !(EOV & v->flags); ++v)
3087 if (!(PADDING & v->flags)) {
3088 /* Check if the var name matches the buffer. The
3089 * name is bracketed by [reqpt..tp] and not NUL
3090 * terminated, and it contains no '=' char. The
3091 * lookup value IS NUL-terminated but might
3092 * include a '='... We have to look out for
3095 const char *sp1 = reqpt;
3096 const char *sp2 = v->text;
3098 while ((sp1 != tp) && (*sp1 == *sp2)) {
3102 if (sp1 == tp && (*sp2 == '\0' || *sp2 == '='))
3106 /* See if we have found a valid entry or not. If found, advance
3107 * the request pointer for the next round; if not, clear the
3108 * data pointer so we have no dangling garbage here.
3113 reqpt = cp + (cp != reqend);
3117 /*TODO? somehow indicate this packet was bad, apart from syslog? */
3120 if (quiet_until <= current_time) {
3121 quiet_until = current_time + 300;
3122 msyslog(LOG_WARNING,
3123 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)",
3124 stoa(rmt_addr), SRCPORT(rmt_addr));
3126 reqpt = reqend; /* never again for this packet! */
3132 * control_unspec - response to an unspecified op-code
3137 struct recvbuf *rbufp,
3144 * What is an appropriate response to an unspecified op-code?
3145 * I return no errors and no data, unless a specified assocation
3149 peer = findpeerbyassoc(res_associd);
3151 ctl_error(CERR_BADASSOC);
3154 rpkt.status = htons(ctlpeerstatus(peer));
3156 rpkt.status = htons(ctlsysstatus());
3162 * read_status - return either a list of associd's, or a particular
3168 struct recvbuf *rbufp,
3175 /* a_st holds association ID, status pairs alternating */
3176 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3180 printf("read_status: ID %d\n", res_associd);
3183 * Two choices here. If the specified association ID is
3184 * zero we return all known assocation ID's. Otherwise
3185 * we return a bunch of stuff about the particular peer.
3188 peer = findpeerbyassoc(res_associd);
3190 ctl_error(CERR_BADASSOC);
3193 rpkt.status = htons(ctlpeerstatus(peer));
3195 peer->num_events = 0;
3197 * For now, output everything we know about the
3198 * peer. May be more selective later.
3200 for (cp = def_peer_var; *cp != 0; cp++)
3201 ctl_putpeer((int)*cp, peer);
3206 rpkt.status = htons(ctlsysstatus());
3207 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3208 a_st[n++] = htons(peer->associd);
3209 a_st[n++] = htons(ctlpeerstatus(peer));
3210 /* two entries each loop iteration, so n + 1 */
3211 if (n + 1 >= COUNTOF(a_st)) {
3212 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3218 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3224 * read_peervars - half of read_variables() implementation
3229 const struct ctl_var *v;
3234 u_char wants[CP_MAXCODE + 1];
3238 * Wants info for a particular peer. See if we know
3241 peer = findpeerbyassoc(res_associd);
3243 ctl_error(CERR_BADASSOC);
3246 rpkt.status = htons(ctlpeerstatus(peer));
3248 peer->num_events = 0;
3251 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3252 if (v->flags & EOV) {
3253 ctl_error(CERR_UNKNOWNVAR);
3256 INSIST(v->code < COUNTOF(wants));
3261 for (i = 1; i < COUNTOF(wants); i++)
3263 ctl_putpeer(i, peer);
3265 for (cp = def_peer_var; *cp != 0; cp++)
3266 ctl_putpeer((int)*cp, peer);
3272 * read_sysvars - half of read_variables() implementation
3277 const struct ctl_var *v;
3288 * Wants system variables. Figure out which he wants
3289 * and give them to him.
3291 rpkt.status = htons(ctlsysstatus());
3293 ctl_sys_num_events = 0;
3294 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3295 wants = emalloc_zero(wants_count);
3297 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3298 if (!(EOV & v->flags)) {
3299 INSIST(v->code < wants_count);
3303 v = ctl_getitem(ext_sys_var, &valuep);
3305 ctl_error(CERR_BADVALUE);
3309 if (EOV & v->flags) {
3310 ctl_error(CERR_UNKNOWNVAR);
3314 n = v->code + CS_MAXCODE + 1;
3315 INSIST(n < wants_count);
3321 for (n = 1; n <= CS_MAXCODE; n++)
3324 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3325 if (wants[n + CS_MAXCODE + 1]) {
3326 pch = ext_sys_var[n].text;
3327 ctl_putdata(pch, strlen(pch), 0);
3330 for (cs = def_sys_var; *cs != 0; cs++)
3331 ctl_putsys((int)*cs);
3332 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3333 if (DEF & kv->flags)
3334 ctl_putdata(kv->text, strlen(kv->text),
3343 * read_variables - return the variables the caller asks for
3348 struct recvbuf *rbufp,
3360 * write_variables - write into variables. We only allow leap bit
3366 struct recvbuf *rbufp,
3370 const struct ctl_var *v;
3381 * If he's trying to write into a peer tell him no way
3383 if (res_associd != 0) {
3384 ctl_error(CERR_PERMISSION);
3391 rpkt.status = htons(ctlsysstatus());
3394 * Look through the variables. Dump out at the first sign of
3397 while ((v = ctl_getitem(sys_var, &valuep)) != 0) {
3399 if (v->flags & EOV) {
3400 if ((v = ctl_getitem(ext_sys_var, &valuep)) !=
3402 if (v->flags & EOV) {
3403 ctl_error(CERR_UNKNOWNVAR);
3411 if (!(v->flags & CAN_WRITE)) {
3412 ctl_error(CERR_PERMISSION);
3415 if (!ext_var && (*valuep == '\0' || !atoint(valuep,
3417 ctl_error(CERR_BADFMT);
3420 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) {
3421 ctl_error(CERR_BADVALUE);
3426 octets = strlen(v->text) + strlen(valuep) + 2;
3427 vareqv = emalloc(octets);
3430 while (*t && *t != '=')
3433 memcpy(tt, valuep, 1 + strlen(valuep));
3434 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3437 ctl_error(CERR_UNSPEC); /* really */
3443 * If we got anything, do it. xxx nothing to do ***
3446 if (leapind != ~0 || leapwarn != ~0) {
3447 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3448 ctl_error(CERR_PERMISSION);
3458 * configure() processes ntpq :config/config-from-file, allowing
3459 * generic runtime reconfiguration.
3461 static void configure(
3462 struct recvbuf *rbufp,
3469 /* I haven't yet implemented changes to an existing association.
3470 * Hence check if the association id is 0
3472 if (res_associd != 0) {
3473 ctl_error(CERR_BADVALUE);
3477 if (RES_NOMODIFY & restrict_mask) {
3478 snprintf(remote_config.err_msg,
3479 sizeof(remote_config.err_msg),
3480 "runtime configuration prohibited by restrict ... nomodify");
3481 ctl_putdata(remote_config.err_msg,
3482 strlen(remote_config.err_msg), 0);
3486 "runtime config from %s rejected due to nomodify restriction",
3487 stoa(&rbufp->recv_srcadr));
3492 /* Initialize the remote config buffer */
3493 data_count = remoteconfig_cmdlength(reqpt, reqend);
3495 if (data_count > sizeof(remote_config.buffer) - 2) {
3496 snprintf(remote_config.err_msg,
3497 sizeof(remote_config.err_msg),
3498 "runtime configuration failed: request too long");
3499 ctl_putdata(remote_config.err_msg,
3500 strlen(remote_config.err_msg), 0);
3503 "runtime config from %s rejected: request too long",
3504 stoa(&rbufp->recv_srcadr));
3507 /* Bug 2853 -- check if all characters were acceptable */
3508 if (data_count != (size_t)(reqend - reqpt)) {
3509 snprintf(remote_config.err_msg,
3510 sizeof(remote_config.err_msg),
3511 "runtime configuration failed: request contains an unprintable character");
3512 ctl_putdata(remote_config.err_msg,
3513 strlen(remote_config.err_msg), 0);
3516 "runtime config from %s rejected: request contains an unprintable character: %0x",
3517 stoa(&rbufp->recv_srcadr),
3522 memcpy(remote_config.buffer, reqpt, data_count);
3523 /* The buffer has no trailing linefeed or NUL right now. For
3524 * logging, we do not want a newline, so we do that first after
3525 * adding the necessary NUL byte.
3527 remote_config.buffer[data_count] = '\0';
3528 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3529 remote_config.buffer));
3530 msyslog(LOG_NOTICE, "%s config: %s",
3531 stoa(&rbufp->recv_srcadr),
3532 remote_config.buffer);
3534 /* Now we have to make sure there is a NL/NUL sequence at the
3535 * end of the buffer before we parse it.
3537 remote_config.buffer[data_count++] = '\n';
3538 remote_config.buffer[data_count] = '\0';
3539 remote_config.pos = 0;
3540 remote_config.err_pos = 0;
3541 remote_config.no_errors = 0;
3542 config_remotely(&rbufp->recv_srcadr);
3545 * Check if errors were reported. If not, output 'Config
3546 * Succeeded'. Else output the error count. It would be nice
3547 * to output any parser error messages.
3549 if (0 == remote_config.no_errors) {
3550 retval = snprintf(remote_config.err_msg,
3551 sizeof(remote_config.err_msg),
3552 "Config Succeeded");
3554 remote_config.err_pos += retval;
3557 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3560 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3562 if (remote_config.no_errors > 0)
3563 msyslog(LOG_NOTICE, "%d error in %s config",
3564 remote_config.no_errors,
3565 stoa(&rbufp->recv_srcadr));
3570 * derive_nonce - generate client-address-specific nonce value
3571 * associated with a given timestamp.
3573 static u_int32 derive_nonce(
3579 static u_int32 salt[4];
3580 static u_long last_salt_update;
3582 u_char digest[EVP_MAX_MD_SIZE];
3588 while (!salt[0] || current_time - last_salt_update >= 3600) {
3589 salt[0] = ntp_random();
3590 salt[1] = ntp_random();
3591 salt[2] = ntp_random();
3592 salt[3] = ntp_random();
3593 last_salt_update = current_time;
3596 ctx = EVP_MD_CTX_new();
3597 EVP_DigestInit(ctx, EVP_get_digestbynid(NID_md5));
3598 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3599 EVP_DigestUpdate(ctx, &ts_i, sizeof(ts_i));
3600 EVP_DigestUpdate(ctx, &ts_f, sizeof(ts_f));
3602 EVP_DigestUpdate(ctx, &SOCK_ADDR4(addr),
3603 sizeof(SOCK_ADDR4(addr)));
3605 EVP_DigestUpdate(ctx, &SOCK_ADDR6(addr),
3606 sizeof(SOCK_ADDR6(addr)));
3607 EVP_DigestUpdate(ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3608 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3609 EVP_DigestFinal(ctx, d.digest, &len);
3610 EVP_MD_CTX_free(ctx);
3617 * generate_nonce - generate client-address-specific nonce string.
3619 static void generate_nonce(
3620 struct recvbuf * rbufp,
3627 derived = derive_nonce(&rbufp->recv_srcadr,
3628 rbufp->recv_time.l_ui,
3629 rbufp->recv_time.l_uf);
3630 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3631 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3636 * validate_nonce - validate client-address-specific nonce string.
3638 * Returns TRUE if the local calculation of the nonce matches the
3639 * client-provided value and the timestamp is recent enough.
3641 static int validate_nonce(
3642 const char * pnonce,
3643 struct recvbuf * rbufp
3653 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3656 ts.l_ui = (u_int32)ts_i;
3657 ts.l_uf = (u_int32)ts_f;
3658 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3659 get_systime(&now_delta);
3660 L_SUB(&now_delta, &ts);
3662 return (supposed == derived && now_delta.l_ui < 16);
3667 * send_random_tag_value - send a randomly-generated three character
3668 * tag prefix, a '.', an index, a '=' and a
3669 * random integer value.
3671 * To try to force clients to ignore unrecognized tags in mrulist,
3672 * reslist, and ifstats responses, the first and last rows are spiced
3673 * with randomly-generated tag names with correct .# index. Make it
3674 * three characters knowing that none of the currently-used subscripted
3675 * tags have that length, avoiding the need to test for
3679 send_random_tag_value(
3686 noise = rand() ^ (rand() << 16);
3687 buf[0] = 'a' + noise % 26;
3689 buf[1] = 'a' + noise % 26;
3691 buf[2] = 'a' + noise % 26;
3694 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3695 ctl_putuint(buf, noise);
3700 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3702 * To keep clients honest about not depending on the order of values,
3703 * and thereby avoid being locked into ugly workarounds to maintain
3704 * backward compatibility later as new fields are added to the response,
3705 * the order is random.
3713 const char first_fmt[] = "first.%d";
3714 const char ct_fmt[] = "ct.%d";
3715 const char mv_fmt[] = "mv.%d";
3716 const char rs_fmt[] = "rs.%d";
3718 u_char sent[6]; /* 6 tag=value pairs */
3724 remaining = COUNTOF(sent);
3726 noise = (u_int32)(rand() ^ (rand() << 16));
3727 while (remaining > 0) {
3728 which = (noise & 7) % COUNTOF(sent);
3731 which = (which + 1) % COUNTOF(sent);
3736 snprintf(tag, sizeof(tag), addr_fmt, count);
3737 pch = sptoa(&mon->rmtadr);
3738 ctl_putunqstr(tag, pch, strlen(pch));
3742 snprintf(tag, sizeof(tag), last_fmt, count);
3743 ctl_putts(tag, &mon->last);
3747 snprintf(tag, sizeof(tag), first_fmt, count);
3748 ctl_putts(tag, &mon->first);
3752 snprintf(tag, sizeof(tag), ct_fmt, count);
3753 ctl_putint(tag, mon->count);
3757 snprintf(tag, sizeof(tag), mv_fmt, count);
3758 ctl_putuint(tag, mon->vn_mode);
3762 snprintf(tag, sizeof(tag), rs_fmt, count);
3763 ctl_puthex(tag, mon->flags);
3773 * read_mru_list - supports ntpq's mrulist command.
3775 * The challenge here is to match ntpdc's monlist functionality without
3776 * being limited to hundreds of entries returned total, and without
3777 * requiring state on the server. If state were required, ntpq's
3778 * mrulist command would require authentication.
3780 * The approach was suggested by Ry Jones. A finite and variable number
3781 * of entries are retrieved per request, to avoid having responses with
3782 * such large numbers of packets that socket buffers are overflowed and
3783 * packets lost. The entries are retrieved oldest-first, taking into
3784 * account that the MRU list will be changing between each request. We
3785 * can expect to see duplicate entries for addresses updated in the MRU
3786 * list during the fetch operation. In the end, the client can assemble
3787 * a close approximation of the MRU list at the point in time the last
3788 * response was sent by ntpd. The only difference is it may be longer,
3789 * containing some number of oldest entries which have since been
3790 * reclaimed. If necessary, the protocol could be extended to zap those
3791 * from the client snapshot at the end, but so far that doesn't seem
3794 * To accomodate the changing MRU list, the starting point for requests
3795 * after the first request is supplied as a series of last seen
3796 * timestamps and associated addresses, the newest ones the client has
3797 * received. As long as at least one of those entries hasn't been
3798 * bumped to the head of the MRU list, ntpd can pick up at that point.
3799 * Otherwise, the request is failed and it is up to ntpq to back up and
3800 * provide the next newest entry's timestamps and addresses, conceivably
3801 * backing up all the way to the starting point.
3804 * nonce= Regurgitated nonce retrieved by the client
3805 * previously using CTL_OP_REQ_NONCE, demonstrating
3806 * ability to receive traffic sent to its address.
3807 * frags= Limit on datagrams (fragments) in response. Used
3808 * by newer ntpq versions instead of limit= when
3809 * retrieving multiple entries.
3810 * limit= Limit on MRU entries returned. One of frags= or
3811 * limit= must be provided.
3812 * limit=1 is a special case: Instead of fetching
3813 * beginning with the supplied starting point's
3814 * newer neighbor, fetch the supplied entry, and
3815 * in that case the #.last timestamp can be zero.
3816 * This enables fetching a single entry by IP
3817 * address. When limit is not one and frags= is
3818 * provided, the fragment limit controls.
3819 * mincount= (decimal) Return entries with count >= mincount.
3820 * laddr= Return entries associated with the server's IP
3821 * address given. No port specification is needed,
3822 * and any supplied is ignored.
3823 * resall= 0x-prefixed hex restrict bits which must all be
3824 * lit for an MRU entry to be included.
3825 * Has precedence over any resany=.
3826 * resany= 0x-prefixed hex restrict bits, at least one of
3827 * which must be list for an MRU entry to be
3829 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3830 * which client previously received.
3831 * addr.0= text of newest entry's IP address and port,
3832 * IPv6 addresses in bracketed form: [::]:123
3833 * last.1= timestamp of 2nd newest entry client has.
3834 * addr.1= address of 2nd newest entry.
3837 * ntpq provides as many last/addr pairs as will fit in a single request
3838 * packet, except for the first request in a MRU fetch operation.
3840 * The response begins with a new nonce value to be used for any
3841 * followup request. Following the nonce is the next newer entry than
3842 * referred to by last.0 and addr.0, if the "0" entry has not been
3843 * bumped to the front. If it has, the first entry returned will be the
3844 * next entry newer than referred to by last.1 and addr.1, and so on.
3845 * If none of the referenced entries remain unchanged, the request fails
3846 * and ntpq backs up to the next earlier set of entries to resync.
3848 * Except for the first response, the response begins with confirmation
3849 * of the entry that precedes the first additional entry provided:
3851 * last.older= hex l_fp timestamp matching one of the input
3852 * .last timestamps, which entry now precedes the
3853 * response 0. entry in the MRU list.
3854 * addr.older= text of address corresponding to older.last.
3856 * And in any case, a successful response contains sets of values
3857 * comprising entries, with the oldest numbered 0 and incrementing from
3860 * addr.# text of IPv4 or IPv6 address and port
3861 * last.# hex l_fp timestamp of last receipt
3862 * first.# hex l_fp timestamp of first receipt
3863 * ct.# count of packets received
3864 * mv.# mode and version
3865 * rs.# restriction mask (RES_* bits)
3867 * Note the code currently assumes there are no valid three letter
3868 * tags sent with each row, and needs to be adjusted if that changes.
3870 * The client should accept the values in any order, and ignore .#
3871 * values which it does not understand, to allow a smooth path to
3872 * future changes without requiring a new opcode. Clients can rely
3873 * on all *.0 values preceding any *.1 values, that is all values for
3874 * a given index number are together in the response.
3876 * The end of the response list is noted with one or two tag=value
3877 * pairs. Unconditionally:
3879 * now= 0x-prefixed l_fp timestamp at the server marking
3880 * the end of the operation.
3882 * If any entries were returned, now= is followed by:
3884 * last.newest= hex l_fp identical to last.# of the prior
3887 static void read_mru_list(
3888 struct recvbuf *rbufp,
3892 static const char nulltxt[1] = { '\0' };
3893 static const char nonce_text[] = "nonce";
3894 static const char frags_text[] = "frags";
3895 static const char limit_text[] = "limit";
3896 static const char mincount_text[] = "mincount";
3897 static const char resall_text[] = "resall";
3898 static const char resany_text[] = "resany";
3899 static const char maxlstint_text[] = "maxlstint";
3900 static const char laddr_text[] = "laddr";
3901 static const char resaxx_fmt[] = "0x%hx";
3910 struct interface * lcladr;
3915 sockaddr_u addr[COUNTOF(last)];
3917 struct ctl_var * in_parms;
3918 const struct ctl_var * v;
3927 mon_entry * prior_mon;
3930 if (RES_NOMRULIST & restrict_mask) {
3931 ctl_error(CERR_PERMISSION);
3934 "mrulist from %s rejected due to nomrulist restriction",
3935 stoa(&rbufp->recv_srcadr));
3940 * fill in_parms var list with all possible input parameters.
3943 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
3944 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
3945 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
3946 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
3947 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
3948 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
3949 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
3950 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
3951 for (i = 0; i < COUNTOF(last); i++) {
3952 snprintf(buf, sizeof(buf), last_fmt, (int)i);
3953 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3954 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
3955 set_var(&in_parms, buf, strlen(buf) + 1, 0);
3958 /* decode input parms */
3971 /* have to go through '(void*)' to drop 'const' property from pointer.
3972 * ctl_getitem()' needs some cleanup, too.... perlinger@ntp.org
3974 while (NULL != (v = ctl_getitem(in_parms, (void*)&val)) &&
3975 !(EOV & v->flags)) {
3981 if (!strcmp(nonce_text, v->text)) {
3983 pnonce = (*val) ? estrdup(val) : NULL;
3984 } else if (!strcmp(frags_text, v->text)) {
3985 if (1 != sscanf(val, "%hu", &frags))
3987 } else if (!strcmp(limit_text, v->text)) {
3988 if (1 != sscanf(val, "%u", &limit))
3990 } else if (!strcmp(mincount_text, v->text)) {
3991 if (1 != sscanf(val, "%d", &mincount))
3995 } else if (!strcmp(resall_text, v->text)) {
3996 if (1 != sscanf(val, resaxx_fmt, &resall))
3998 } else if (!strcmp(resany_text, v->text)) {
3999 if (1 != sscanf(val, resaxx_fmt, &resany))
4001 } else if (!strcmp(maxlstint_text, v->text)) {
4002 if (1 != sscanf(val, "%u", &maxlstint))
4004 } else if (!strcmp(laddr_text, v->text)) {
4005 if (!decodenetnum(val, &laddr))
4007 lcladr = getinterface(&laddr, 0);
4008 } else if (1 == sscanf(v->text, last_fmt, &si) &&
4009 (size_t)si < COUNTOF(last)) {
4010 if (2 != sscanf(val, "0x%08x.%08x", &ui, &uf))
4014 if (!SOCK_UNSPEC(&addr[si]) && si == priors)
4016 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
4017 (size_t)si < COUNTOF(addr)) {
4018 if (!decodenetnum(val, &addr[si]))
4020 if (last[si].l_ui && last[si].l_uf && si == priors)
4023 DPRINTF(1, ("read_mru_list: invalid key item: '%s' (ignored)\n",
4028 DPRINTF(1, ("read_mru_list: invalid param for '%s': '%s' (bailing)\n",
4035 free_varlist(in_parms);
4038 /* return no responses until the nonce is validated */
4042 nonce_valid = validate_nonce(pnonce, rbufp);
4047 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
4048 frags > MRU_FRAGS_LIMIT) {
4049 ctl_error(CERR_BADVALUE);
4054 * If either frags or limit is not given, use the max.
4056 if (0 != frags && 0 == limit)
4058 else if (0 != limit && 0 == frags)
4059 frags = MRU_FRAGS_LIMIT;
4062 * Find the starting point if one was provided.
4065 for (i = 0; i < (size_t)priors; i++) {
4066 hash = MON_HASH(&addr[i]);
4067 for (mon = mon_hash[hash];
4069 mon = mon->hash_next)
4070 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
4073 if (L_ISEQU(&mon->last, &last[i]))
4079 /* If a starting point was provided... */
4081 /* and none could be found unmodified... */
4083 /* tell ntpq to try again with older entries */
4084 ctl_error(CERR_UNKNOWNVAR);
4087 /* confirm the prior entry used as starting point */
4088 ctl_putts("last.older", &mon->last);
4089 pch = sptoa(&mon->rmtadr);
4090 ctl_putunqstr("addr.older", pch, strlen(pch));
4093 * Move on to the first entry the client doesn't have,
4094 * except in the special case of a limit of one. In
4095 * that case return the starting point entry.
4098 mon = PREV_DLIST(mon_mru_list, mon, mru);
4099 } else { /* start with the oldest */
4100 mon = TAIL_DLIST(mon_mru_list, mru);
4104 * send up to limit= entries in up to frags= datagrams
4107 generate_nonce(rbufp, buf, sizeof(buf));
4108 ctl_putunqstr("nonce", buf, strlen(buf));
4111 mon != NULL && res_frags < frags && count < limit;
4112 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
4114 if (mon->count < mincount)
4116 if (resall && resall != (resall & mon->flags))
4118 if (resany && !(resany & mon->flags))
4120 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
4123 if (lcladr != NULL && mon->lcladr != lcladr)
4126 send_mru_entry(mon, count);
4128 send_random_tag_value(0);
4134 * If this batch completes the MRU list, say so explicitly with
4135 * a now= l_fp timestamp.
4139 send_random_tag_value(count - 1);
4140 ctl_putts("now", &now);
4141 /* if any entries were returned confirm the last */
4142 if (prior_mon != NULL)
4143 ctl_putts("last.newest", &prior_mon->last);
4150 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
4152 * To keep clients honest about not depending on the order of values,
4153 * and thereby avoid being locked into ugly workarounds to maintain
4154 * backward compatibility later as new fields are added to the response,
4155 * the order is random.
4163 const char addr_fmtu[] = "addr.%u";
4164 const char bcast_fmt[] = "bcast.%u";
4165 const char en_fmt[] = "en.%u"; /* enabled */
4166 const char name_fmt[] = "name.%u";
4167 const char flags_fmt[] = "flags.%u";
4168 const char tl_fmt[] = "tl.%u"; /* ttl */
4169 const char mc_fmt[] = "mc.%u"; /* mcast count */
4170 const char rx_fmt[] = "rx.%u";
4171 const char tx_fmt[] = "tx.%u";
4172 const char txerr_fmt[] = "txerr.%u";
4173 const char pc_fmt[] = "pc.%u"; /* peer count */
4174 const char up_fmt[] = "up.%u"; /* uptime */
4176 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4183 remaining = COUNTOF(sent);
4187 while (remaining > 0) {
4188 if (noisebits < 4) {
4189 noise = rand() ^ (rand() << 16);
4192 which = (noise & 0xf) % COUNTOF(sent);
4197 which = (which + 1) % COUNTOF(sent);
4202 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4203 pch = sptoa(&la->sin);
4204 ctl_putunqstr(tag, pch, strlen(pch));
4208 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4209 if (INT_BCASTOPEN & la->flags)
4210 pch = sptoa(&la->bcast);
4213 ctl_putunqstr(tag, pch, strlen(pch));
4217 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4218 ctl_putint(tag, !la->ignore_packets);
4222 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4223 ctl_putstr(tag, la->name, strlen(la->name));
4227 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4228 ctl_puthex(tag, (u_int)la->flags);
4232 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4233 ctl_putint(tag, la->last_ttl);
4237 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4238 ctl_putint(tag, la->num_mcast);
4242 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4243 ctl_putint(tag, la->received);
4247 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4248 ctl_putint(tag, la->sent);
4252 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4253 ctl_putint(tag, la->notsent);
4257 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4258 ctl_putuint(tag, la->peercnt);
4262 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4263 ctl_putuint(tag, current_time - la->starttime);
4269 send_random_tag_value((int)ifnum);
4274 * read_ifstats - send statistics for each local address, exposed by
4279 struct recvbuf * rbufp
4286 * loop over [0..sys_ifnum] searching ep_list for each
4289 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4290 for (la = ep_list; la != NULL; la = la->elink)
4291 if (ifidx == la->ifnum)
4295 /* return stats for one local address */
4296 send_ifstats_entry(la, ifidx);
4302 sockaddrs_from_restrict_u(
4312 psaA->sa.sa_family = AF_INET;
4313 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4314 psaM->sa.sa_family = AF_INET;
4315 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4317 psaA->sa.sa_family = AF_INET6;
4318 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4319 sizeof(psaA->sa6.sin6_addr));
4320 psaM->sa.sa_family = AF_INET6;
4321 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4322 sizeof(psaA->sa6.sin6_addr));
4328 * Send a restrict entry in response to a "ntpq -c reslist" request.
4330 * To keep clients honest about not depending on the order of values,
4331 * and thereby avoid being locked into ugly workarounds to maintain
4332 * backward compatibility later as new fields are added to the response,
4333 * the order is random.
4336 send_restrict_entry(
4342 const char addr_fmtu[] = "addr.%u";
4343 const char mask_fmtu[] = "mask.%u";
4344 const char hits_fmt[] = "hits.%u";
4345 const char flags_fmt[] = "flags.%u";
4347 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4356 const char * match_str;
4357 const char * access_str;
4359 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4360 remaining = COUNTOF(sent);
4364 while (remaining > 0) {
4365 if (noisebits < 2) {
4366 noise = rand() ^ (rand() << 16);
4369 which = (noise & 0x3) % COUNTOF(sent);
4374 which = (which + 1) % COUNTOF(sent);
4379 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4381 ctl_putunqstr(tag, pch, strlen(pch));
4385 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4387 ctl_putunqstr(tag, pch, strlen(pch));
4391 snprintf(tag, sizeof(tag), hits_fmt, idx);
4392 ctl_putuint(tag, pres->count);
4396 snprintf(tag, sizeof(tag), flags_fmt, idx);
4397 match_str = res_match_flags(pres->mflags);
4398 access_str = res_access_flags(pres->flags);
4399 if ('\0' == match_str[0]) {
4403 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4404 match_str, access_str);
4407 ctl_putunqstr(tag, pch, strlen(pch));
4413 send_random_tag_value((int)idx);
4424 for ( ; pres != NULL; pres = pres->link) {
4425 send_restrict_entry(pres, ipv6, *pidx);
4432 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4435 read_addr_restrictions(
4436 struct recvbuf * rbufp
4442 send_restrict_list(restrictlist4, FALSE, &idx);
4443 send_restrict_list(restrictlist6, TRUE, &idx);
4449 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4453 struct recvbuf * rbufp,
4457 const char ifstats_s[] = "ifstats";
4458 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4459 const char addr_rst_s[] = "addr_restrictions";
4460 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4461 struct ntp_control * cpkt;
4462 u_short qdata_octets;
4465 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4466 * used only for ntpq -c ifstats. With the addition of reslist
4467 * the same opcode was generalized to retrieve ordered lists
4468 * which require authentication. The request data is empty or
4469 * contains "ifstats" (not null terminated) to retrieve local
4470 * addresses and associated stats. It is "addr_restrictions"
4471 * to retrieve the IPv4 then IPv6 remote address restrictions,
4472 * which are access control lists. Other request data return
4475 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4476 qdata_octets = ntohs(cpkt->count);
4477 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4478 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4479 read_ifstats(rbufp);
4482 if (a_r_chars == qdata_octets &&
4483 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4484 read_addr_restrictions(rbufp);
4487 ctl_error(CERR_UNKNOWNVAR);
4492 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4494 static void req_nonce(
4495 struct recvbuf * rbufp,
4501 generate_nonce(rbufp, buf, sizeof(buf));
4502 ctl_putunqstr("nonce", buf, strlen(buf));
4508 * read_clockstatus - return clock radio status
4513 struct recvbuf *rbufp,
4519 * If no refclock support, no data to return
4521 ctl_error(CERR_BADASSOC);
4523 const struct ctl_var * v;
4531 struct ctl_var * kv;
4532 struct refclockstat cs;
4534 if (res_associd != 0) {
4535 peer = findpeerbyassoc(res_associd);
4538 * Find a clock for this jerk. If the system peer
4539 * is a clock use it, else search peer_list for one.
4541 if (sys_peer != NULL && (FLAG_REFCLOCK &
4545 for (peer = peer_list;
4547 peer = peer->p_link)
4548 if (FLAG_REFCLOCK & peer->flags)
4551 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4552 ctl_error(CERR_BADASSOC);
4556 * If we got here we have a peer which is a clock. Get his
4560 refclock_control(&peer->srcadr, NULL, &cs);
4563 * Look for variables in the packet.
4565 rpkt.status = htons(ctlclkstatus(&cs));
4566 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4567 wants = emalloc_zero(wants_alloc);
4569 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4570 if (!(EOV & v->flags)) {
4571 wants[v->code] = TRUE;
4574 v = ctl_getitem(kv, &valuep);
4576 ctl_error(CERR_BADVALUE);
4578 free_varlist(cs.kv_list);
4581 if (EOV & v->flags) {
4582 ctl_error(CERR_UNKNOWNVAR);
4584 free_varlist(cs.kv_list);
4587 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4593 for (i = 1; i <= CC_MAXCODE; i++)
4595 ctl_putclock(i, &cs, TRUE);
4597 for (i = 0; !(EOV & kv[i].flags); i++)
4598 if (wants[i + CC_MAXCODE + 1])
4599 ctl_putdata(kv[i].text,
4603 for (cc = def_clock_var; *cc != 0; cc++)
4604 ctl_putclock((int)*cc, &cs, FALSE);
4605 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4606 if (DEF & kv->flags)
4607 ctl_putdata(kv->text, strlen(kv->text),
4612 free_varlist(cs.kv_list);
4620 * write_clockstatus - we don't do this
4625 struct recvbuf *rbufp,
4629 ctl_error(CERR_PERMISSION);
4633 * Trap support from here on down. We send async trap messages when the
4634 * upper levels report trouble. Traps can by set either by control
4635 * messages or by configuration.
4638 * set_trap - set a trap in response to a control message
4642 struct recvbuf *rbufp,
4649 * See if this guy is allowed
4651 if (restrict_mask & RES_NOTRAP) {
4652 ctl_error(CERR_PERMISSION);
4657 * Determine his allowed trap type.
4659 traptype = TRAP_TYPE_PRIO;
4660 if (restrict_mask & RES_LPTRAP)
4661 traptype = TRAP_TYPE_NONPRIO;
4664 * Call ctlsettrap() to do the work. Return
4665 * an error if it can't assign the trap.
4667 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4669 ctl_error(CERR_NORESOURCE);
4675 * unset_trap - unset a trap in response to a control message
4679 struct recvbuf *rbufp,
4686 * We don't prevent anyone from removing his own trap unless the
4687 * trap is configured. Note we also must be aware of the
4688 * possibility that restriction flags were changed since this
4689 * guy last set his trap. Set the trap type based on this.
4691 traptype = TRAP_TYPE_PRIO;
4692 if (restrict_mask & RES_LPTRAP)
4693 traptype = TRAP_TYPE_NONPRIO;
4696 * Call ctlclrtrap() to clear this out.
4698 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4699 ctl_error(CERR_BADASSOC);
4705 * ctlsettrap - called to set a trap
4710 struct interface *linter,
4716 struct ctl_trap *tp;
4717 struct ctl_trap *tptouse;
4720 * See if we can find this trap. If so, we only need update
4721 * the flags and the time.
4723 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4726 case TRAP_TYPE_CONFIG:
4727 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4730 case TRAP_TYPE_PRIO:
4731 if (tp->tr_flags & TRAP_CONFIGURED)
4732 return (1); /* don't change anything */
4733 tp->tr_flags = TRAP_INUSE;
4736 case TRAP_TYPE_NONPRIO:
4737 if (tp->tr_flags & TRAP_CONFIGURED)
4738 return (1); /* don't change anything */
4739 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4742 tp->tr_settime = current_time;
4748 * First we heard of this guy. Try to find a trap structure
4749 * for him to use, clearing out lesser priority guys if we
4750 * have to. Clear out anyone who's expired while we're at it.
4753 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4755 if ((TRAP_INUSE & tp->tr_flags) &&
4756 !(TRAP_CONFIGURED & tp->tr_flags) &&
4757 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4761 if (!(TRAP_INUSE & tp->tr_flags)) {
4763 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4766 case TRAP_TYPE_CONFIG:
4767 if (tptouse == NULL) {
4771 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4772 !(TRAP_NONPRIO & tp->tr_flags))
4775 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4776 && (TRAP_NONPRIO & tp->tr_flags)) {
4780 if (tptouse->tr_origtime <
4785 case TRAP_TYPE_PRIO:
4786 if ( TRAP_NONPRIO & tp->tr_flags) {
4787 if (tptouse == NULL ||
4789 tptouse->tr_flags) &&
4790 tptouse->tr_origtime <
4796 case TRAP_TYPE_NONPRIO:
4803 * If we don't have room for him return an error.
4805 if (tptouse == NULL)
4809 * Set up this structure for him.
4811 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4812 tptouse->tr_count = tptouse->tr_resets = 0;
4813 tptouse->tr_sequence = 1;
4814 tptouse->tr_addr = *raddr;
4815 tptouse->tr_localaddr = linter;
4816 tptouse->tr_version = (u_char) version;
4817 tptouse->tr_flags = TRAP_INUSE;
4818 if (traptype == TRAP_TYPE_CONFIG)
4819 tptouse->tr_flags |= TRAP_CONFIGURED;
4820 else if (traptype == TRAP_TYPE_NONPRIO)
4821 tptouse->tr_flags |= TRAP_NONPRIO;
4828 * ctlclrtrap - called to clear a trap
4833 struct interface *linter,
4837 register struct ctl_trap *tp;
4839 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4842 if (tp->tr_flags & TRAP_CONFIGURED
4843 && traptype != TRAP_TYPE_CONFIG)
4853 * ctlfindtrap - find a trap given the remote and local addresses
4855 static struct ctl_trap *
4858 struct interface *linter
4863 for (n = 0; n < COUNTOF(ctl_traps); n++)
4864 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4865 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4866 && (linter == ctl_traps[n].tr_localaddr))
4867 return &ctl_traps[n];
4874 * report_event - report an event to the trappers
4878 int err, /* error code */
4879 struct peer *peer, /* peer structure pointer */
4880 const char *str /* protostats string */
4883 char statstr[NTP_MAXSTRLEN];
4888 * Report the error to the protostats file, system log and
4894 * Discard a system report if the number of reports of
4895 * the same type exceeds the maximum.
4897 if (ctl_sys_last_event != (u_char)err)
4898 ctl_sys_num_events= 0;
4899 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4902 ctl_sys_last_event = (u_char)err;
4903 ctl_sys_num_events++;
4904 snprintf(statstr, sizeof(statstr),
4905 "0.0.0.0 %04x %02x %s",
4906 ctlsysstatus(), err, eventstr(err));
4908 len = strlen(statstr);
4909 snprintf(statstr + len, sizeof(statstr) - len,
4913 msyslog(LOG_INFO, "%s", statstr);
4917 * Discard a peer report if the number of reports of
4918 * the same type exceeds the maximum for that peer.
4923 errlast = (u_char)err & ~PEER_EVENT;
4924 if (peer->last_event != errlast)
4925 peer->num_events = 0;
4926 if (peer->num_events >= CTL_PEER_MAXEVENTS)
4929 peer->last_event = errlast;
4931 if (ISREFCLOCKADR(&peer->srcadr))
4932 src = refnumtoa(&peer->srcadr);
4934 src = stoa(&peer->srcadr);
4936 snprintf(statstr, sizeof(statstr),
4937 "%s %04x %02x %s", src,
4938 ctlpeerstatus(peer), err, eventstr(err));
4940 len = strlen(statstr);
4941 snprintf(statstr + len, sizeof(statstr) - len,
4944 NLOG(NLOG_PEEREVENT)
4945 msyslog(LOG_INFO, "%s", statstr);
4947 record_proto_stats(statstr);
4950 printf("event at %lu %s\n", current_time, statstr);
4954 * If no trappers, return.
4956 if (num_ctl_traps <= 0)
4960 * Peer Events should be associated with a peer -- hence the
4961 * name. But there are instances where this function is called
4962 * *without* a valid peer. This happens e.g. with an unsolicited
4963 * CryptoNAK, or when a leap second alarm is going off while
4964 * currently without a system peer.
4966 * The most sensible approach to this seems to bail out here if
4967 * this happens. Avoiding to call this function would also
4968 * bypass the log reporting in the first part of this function,
4969 * and this is probably not the best of all options.
4970 * -*-perlinger@ntp.org-*-
4972 if ((err & PEER_EVENT) && !peer)
4976 * Set up the outgoing packet variables
4978 res_opcode = CTL_OP_ASYNCMSG;
4981 res_authenticate = FALSE;
4982 datapt = rpkt.u.data;
4983 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
4984 if (!(err & PEER_EVENT)) {
4986 rpkt.status = htons(ctlsysstatus());
4988 /* Include the core system variables and the list. */
4989 for (i = 1; i <= CS_VARLIST; i++)
4991 } else if (NULL != peer) { /* paranoia -- skip output */
4992 rpkt.associd = htons(peer->associd);
4993 rpkt.status = htons(ctlpeerstatus(peer));
4995 /* Dump it all. Later, maybe less. */
4996 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
4997 ctl_putpeer(i, peer);
5000 * for clock exception events: add clock variables to
5001 * reflect info on exception
5003 if (err == PEVNT_CLOCK) {
5004 struct refclockstat cs;
5008 refclock_control(&peer->srcadr, NULL, &cs);
5010 ctl_puthex("refclockstatus",
5013 for (i = 1; i <= CC_MAXCODE; i++)
5014 ctl_putclock(i, &cs, FALSE);
5015 for (kv = cs.kv_list;
5016 kv != NULL && !(EOV & kv->flags);
5018 if (DEF & kv->flags)
5019 ctl_putdata(kv->text,
5022 free_varlist(cs.kv_list);
5024 # endif /* REFCLOCK */
5028 * We're done, return.
5035 * mprintf_event - printf-style varargs variant of report_event()
5039 int evcode, /* event code */
5040 struct peer * p, /* may be NULL */
5041 const char * fmt, /* msnprintf format */
5050 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
5052 report_event(evcode, p, msg);
5059 * ctl_clr_stats - clear stat counters
5064 ctltimereset = current_time;
5067 numctlresponses = 0;
5072 numctlinputresp = 0;
5073 numctlinputfrag = 0;
5075 numctlbadoffset = 0;
5076 numctlbadversion = 0;
5077 numctldatatooshort = 0;
5084 const struct ctl_var *k
5093 while (!(EOV & (k++)->flags))
5096 ENSURE(c <= USHRT_MAX);
5103 struct ctl_var **kv,
5113 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
5115 buf = emalloc(size);
5120 k[c + 1].text = NULL;
5121 k[c + 1].flags = EOV;
5129 struct ctl_var **kv,
5140 if (NULL == data || !size)
5145 while (!(EOV & k->flags)) {
5146 if (NULL == k->text) {
5148 memcpy(td, data, size);
5155 while (*t != '=' && *s == *t) {
5159 if (*s == *t && ((*t == '=') || !*t)) {
5160 td = erealloc((void *)(intptr_t)k->text, size);
5161 memcpy(td, data, size);
5170 td = add_var(kv, size, def);
5171 memcpy(td, data, size);
5182 set_var(&ext_sys_var, data, size, def);
5187 * get_ext_sys_var() retrieves the value of a user-defined variable or
5188 * NULL if the variable has not been setvar'd.
5191 get_ext_sys_var(const char *tag)
5199 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5200 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5201 if ('=' == v->text[c]) {
5202 val = v->text + c + 1;
5204 } else if ('\0' == v->text[c]) {
5222 for (k = kv; !(k->flags & EOV); k++)
5223 free((void *)(intptr_t)k->text);