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_SS_LAMPORT 44
180 #define CS_SS_TSROUNDING 45
181 #define CS_PEERADR 46
182 #define CS_PEERMODE 47
183 #define CS_BCASTDELAY 48
184 #define CS_AUTHDELAY 49
185 #define CS_AUTHKEYS 50
186 #define CS_AUTHFREEK 51
187 #define CS_AUTHKLOOKUPS 52
188 #define CS_AUTHKNOTFOUND 53
189 #define CS_AUTHKUNCACHED 54
190 #define CS_AUTHKEXPIRED 55
191 #define CS_AUTHENCRYPTS 56
192 #define CS_AUTHDECRYPTS 57
193 #define CS_AUTHRESET 58
194 #define CS_K_OFFSET 59
196 #define CS_K_MAXERR 61
197 #define CS_K_ESTERR 62
198 #define CS_K_STFLAGS 63
199 #define CS_K_TIMECONST 64
200 #define CS_K_PRECISION 65
201 #define CS_K_FREQTOL 66
202 #define CS_K_PPS_FREQ 67
203 #define CS_K_PPS_STABIL 68
204 #define CS_K_PPS_JITTER 69
205 #define CS_K_PPS_CALIBDUR 70
206 #define CS_K_PPS_CALIBS 71
207 #define CS_K_PPS_CALIBERRS 72
208 #define CS_K_PPS_JITEXC 73
209 #define CS_K_PPS_STBEXC 74
210 #define CS_KERN_FIRST CS_K_OFFSET
211 #define CS_KERN_LAST CS_K_PPS_STBEXC
212 #define CS_IOSTATS_RESET 75
213 #define CS_TOTAL_RBUF 76
214 #define CS_FREE_RBUF 77
215 #define CS_USED_RBUF 78
216 #define CS_RBUF_LOWATER 79
217 #define CS_IO_DROPPED 80
218 #define CS_IO_IGNORED 81
219 #define CS_IO_RECEIVED 82
220 #define CS_IO_SENT 83
221 #define CS_IO_SENDFAILED 84
222 #define CS_IO_WAKEUPS 85
223 #define CS_IO_GOODWAKEUPS 86
224 #define CS_TIMERSTATS_RESET 87
225 #define CS_TIMER_OVERRUNS 88
226 #define CS_TIMER_XMTS 89
228 #define CS_WANDER_THRESH 91
229 #define CS_LEAPSMEARINTV 92
230 #define CS_LEAPSMEAROFFS 93
231 #define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS
233 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
234 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
235 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
236 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
237 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
238 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
239 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
240 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
241 #define CS_MAXCODE CS_DIGEST
242 #else /* !AUTOKEY follows */
243 #define CS_MAXCODE CS_MAX_NOAUTOKEY
244 #endif /* !AUTOKEY */
247 * Peer variables we understand
250 #define CP_AUTHENABLE 2
251 #define CP_AUTHENTIC 3
258 #define CP_STRATUM 10
261 #define CP_PRECISION 13
262 #define CP_ROOTDELAY 14
263 #define CP_ROOTDISPERSION 15
265 #define CP_REFTIME 17
270 #define CP_UNREACH 22
275 #define CP_DISPERSION 27
277 #define CP_FILTDELAY 29
278 #define CP_FILTOFFSET 30
280 #define CP_RECEIVED 32
282 #define CP_FILTERROR 34
285 #define CP_VARLIST 37
290 #define CP_SRCHOST 42
291 #define CP_TIMEREC 43
292 #define CP_TIMEREACH 44
293 #define CP_BADAUTH 45
294 #define CP_BOGUSORG 46
296 #define CP_SELDISP 48
297 #define CP_SELBROKEN 49
298 #define CP_CANDIDATE 50
299 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
301 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
302 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
303 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
304 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
305 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
306 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
307 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
308 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
309 #define CP_MAXCODE CP_IDENT
310 #else /* !AUTOKEY follows */
311 #define CP_MAXCODE CP_MAX_NOAUTOKEY
312 #endif /* !AUTOKEY */
315 * Clock variables we understand
318 #define CC_TIMECODE 2
321 #define CC_BADFORMAT 5
323 #define CC_FUDGETIME1 7
324 #define CC_FUDGETIME2 8
325 #define CC_FUDGEVAL1 9
326 #define CC_FUDGEVAL2 10
329 #define CC_VARLIST 13
330 #define CC_MAXCODE CC_VARLIST
333 * System variable values. The array can be indexed by the variable
334 * index to find the textual name.
336 static const struct ctl_var sys_var[] = {
337 { 0, PADDING, "" }, /* 0 */
338 { CS_LEAP, RW, "leap" }, /* 1 */
339 { CS_STRATUM, RO, "stratum" }, /* 2 */
340 { CS_PRECISION, RO, "precision" }, /* 3 */
341 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
342 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
343 { CS_REFID, RO, "refid" }, /* 6 */
344 { CS_REFTIME, RO, "reftime" }, /* 7 */
345 { CS_POLL, RO, "tc" }, /* 8 */
346 { CS_PEERID, RO, "peer" }, /* 9 */
347 { CS_OFFSET, RO, "offset" }, /* 10 */
348 { CS_DRIFT, RO, "frequency" }, /* 11 */
349 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
350 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
351 { CS_CLOCK, RO, "clock" }, /* 14 */
352 { CS_PROCESSOR, RO, "processor" }, /* 15 */
353 { CS_SYSTEM, RO, "system" }, /* 16 */
354 { CS_VERSION, RO, "version" }, /* 17 */
355 { CS_STABIL, RO, "clk_wander" }, /* 18 */
356 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
357 { CS_TAI, RO, "tai" }, /* 20 */
358 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
359 { CS_LEAPEND, RO, "expire" }, /* 22 */
360 { CS_RATE, RO, "mintc" }, /* 23 */
361 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
362 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
363 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
364 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
365 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
366 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
367 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
368 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
369 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
370 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
371 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
372 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
373 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
374 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
375 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
376 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
377 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
378 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
379 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
380 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
381 { CS_SS_LAMPORT, RO, "ss_lamport" }, /* 44 */
382 { CS_SS_TSROUNDING, RO, "ss_tsrounding" }, /* 45 */
383 { CS_PEERADR, RO, "peeradr" }, /* 46 */
384 { CS_PEERMODE, RO, "peermode" }, /* 47 */
385 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 48 */
386 { CS_AUTHDELAY, RO, "authdelay" }, /* 49 */
387 { CS_AUTHKEYS, RO, "authkeys" }, /* 50 */
388 { CS_AUTHFREEK, RO, "authfreek" }, /* 51 */
389 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 52 */
390 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 53 */
391 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 54 */
392 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 55 */
393 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 56 */
394 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 57 */
395 { CS_AUTHRESET, RO, "authreset" }, /* 58 */
396 { CS_K_OFFSET, RO, "koffset" }, /* 59 */
397 { CS_K_FREQ, RO, "kfreq" }, /* 60 */
398 { CS_K_MAXERR, RO, "kmaxerr" }, /* 61 */
399 { CS_K_ESTERR, RO, "kesterr" }, /* 62 */
400 { CS_K_STFLAGS, RO, "kstflags" }, /* 63 */
401 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 64 */
402 { CS_K_PRECISION, RO, "kprecis" }, /* 65 */
403 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 66 */
404 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 67 */
405 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 68 */
406 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 69 */
407 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 70 */
408 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 71 */
409 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 72 */
410 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 73 */
411 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 74 */
412 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 75 */
413 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 76 */
414 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 77 */
415 { CS_USED_RBUF, RO, "used_rbuf" }, /* 78 */
416 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 79 */
417 { CS_IO_DROPPED, RO, "io_dropped" }, /* 80 */
418 { CS_IO_IGNORED, RO, "io_ignored" }, /* 81 */
419 { CS_IO_RECEIVED, RO, "io_received" }, /* 82 */
420 { CS_IO_SENT, RO, "io_sent" }, /* 83 */
421 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 84 */
422 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 85 */
423 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 86 */
424 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 87 */
425 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 88 */
426 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 89 */
427 { CS_FUZZ, RO, "fuzz" }, /* 90 */
428 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 91 */
430 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 92 */
431 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 93 */
434 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
435 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
436 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
437 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
438 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
439 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
440 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
441 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
443 { 0, EOV, "" } /* 94/102 */
446 static struct ctl_var *ext_sys_var = NULL;
449 * System variables we print by default (in fuzzball order,
452 static const u_char def_sys_var[] = {
493 static const struct ctl_var peer_var[] = {
494 { 0, PADDING, "" }, /* 0 */
495 { CP_CONFIG, RO, "config" }, /* 1 */
496 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
497 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
498 { CP_SRCADR, RO, "srcadr" }, /* 4 */
499 { CP_SRCPORT, RO, "srcport" }, /* 5 */
500 { CP_DSTADR, RO, "dstadr" }, /* 6 */
501 { CP_DSTPORT, RO, "dstport" }, /* 7 */
502 { CP_LEAP, RO, "leap" }, /* 8 */
503 { CP_HMODE, RO, "hmode" }, /* 9 */
504 { CP_STRATUM, RO, "stratum" }, /* 10 */
505 { CP_PPOLL, RO, "ppoll" }, /* 11 */
506 { CP_HPOLL, RO, "hpoll" }, /* 12 */
507 { CP_PRECISION, RO, "precision" }, /* 13 */
508 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
509 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
510 { CP_REFID, RO, "refid" }, /* 16 */
511 { CP_REFTIME, RO, "reftime" }, /* 17 */
512 { CP_ORG, RO, "org" }, /* 18 */
513 { CP_REC, RO, "rec" }, /* 19 */
514 { CP_XMT, RO, "xleave" }, /* 20 */
515 { CP_REACH, RO, "reach" }, /* 21 */
516 { CP_UNREACH, RO, "unreach" }, /* 22 */
517 { CP_TIMER, RO, "timer" }, /* 23 */
518 { CP_DELAY, RO, "delay" }, /* 24 */
519 { CP_OFFSET, RO, "offset" }, /* 25 */
520 { CP_JITTER, RO, "jitter" }, /* 26 */
521 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
522 { CP_KEYID, RO, "keyid" }, /* 28 */
523 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
524 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
525 { CP_PMODE, RO, "pmode" }, /* 31 */
526 { CP_RECEIVED, RO, "received"}, /* 32 */
527 { CP_SENT, RO, "sent" }, /* 33 */
528 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
529 { CP_FLASH, RO, "flash" }, /* 35 */
530 { CP_TTL, RO, "ttl" }, /* 36 */
531 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
532 { CP_IN, RO, "in" }, /* 38 */
533 { CP_OUT, RO, "out" }, /* 39 */
534 { CP_RATE, RO, "headway" }, /* 40 */
535 { CP_BIAS, RO, "bias" }, /* 41 */
536 { CP_SRCHOST, RO, "srchost" }, /* 42 */
537 { CP_TIMEREC, RO, "timerec" }, /* 43 */
538 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
539 { CP_BADAUTH, RO, "badauth" }, /* 45 */
540 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
541 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
542 { CP_SELDISP, RO, "seldisp" }, /* 48 */
543 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
544 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
546 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
547 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
548 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
549 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
550 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
551 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
552 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
553 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
555 { 0, EOV, "" } /* 50/58 */
560 * Peer variables we print by default
562 static const u_char def_peer_var[] = {
611 * Clock variable list
613 static const struct ctl_var clock_var[] = {
614 { 0, PADDING, "" }, /* 0 */
615 { CC_TYPE, RO, "type" }, /* 1 */
616 { CC_TIMECODE, RO, "timecode" }, /* 2 */
617 { CC_POLL, RO, "poll" }, /* 3 */
618 { CC_NOREPLY, RO, "noreply" }, /* 4 */
619 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
620 { CC_BADDATA, RO, "baddata" }, /* 6 */
621 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
622 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
623 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
624 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
625 { CC_FLAGS, RO, "flags" }, /* 11 */
626 { CC_DEVICE, RO, "device" }, /* 12 */
627 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
628 { 0, EOV, "" } /* 14 */
633 * Clock variables printed by default
635 static const u_char def_clock_var[] = {
637 CC_TYPE, /* won't be output if device = known */
653 * MRU string constants shared by send_mru_entry() and read_mru_list().
655 static const char addr_fmt[] = "addr.%d";
656 static const char last_fmt[] = "last.%d";
659 * System and processor definitions.
663 # define STR_SYSTEM "UNIX"
665 # ifndef STR_PROCESSOR
666 # define STR_PROCESSOR "unknown"
669 static const char str_system[] = STR_SYSTEM;
670 static const char str_processor[] = STR_PROCESSOR;
672 # include <sys/utsname.h>
673 static struct utsname utsnamebuf;
674 #endif /* HAVE_UNAME */
677 * Trap structures. We only allow a few of these, and send a copy of
678 * each async message to each live one. Traps time out after an hour, it
679 * is up to the trap receipient to keep resetting it to avoid being
683 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
687 * Type bits, for ctlsettrap() call.
689 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
690 #define TRAP_TYPE_PRIO 1 /* priority trap */
691 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
695 * List relating reference clock types to control message time sources.
696 * Index by the reference clock type. This list will only be used iff
697 * the reference clock driver doesn't set peer->sstclktype to something
698 * different than CTL_SST_TS_UNSPEC.
701 static const u_char clocktypes[] = {
702 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
703 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
704 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
705 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
706 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
707 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
708 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
709 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
710 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
711 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
712 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
713 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
714 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
715 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
716 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
717 CTL_SST_TS_NTP, /* not used (15) */
718 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
719 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
720 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
721 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
722 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
723 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
724 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
725 CTL_SST_TS_NTP, /* not used (23) */
726 CTL_SST_TS_NTP, /* not used (24) */
727 CTL_SST_TS_NTP, /* not used (25) */
728 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
729 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
730 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
731 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
732 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
733 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
734 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
735 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
736 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
737 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
738 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
739 CTL_SST_TS_LF, /* REFCLK_FG (37) */
740 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
741 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
742 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
743 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
744 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
745 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
746 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
747 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
748 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
750 #endif /* REFCLOCK */
754 * Keyid used for authenticating write requests.
756 keyid_t ctl_auth_keyid;
759 * We keep track of the last error reported by the system internally
761 static u_char ctl_sys_last_event;
762 static u_char ctl_sys_num_events;
766 * Statistic counters to keep track of requests and responses.
768 u_long ctltimereset; /* time stats reset */
769 u_long numctlreq; /* number of requests we've received */
770 u_long numctlbadpkts; /* number of bad control packets */
771 u_long numctlresponses; /* number of resp packets sent with data */
772 u_long numctlfrags; /* number of fragments sent */
773 u_long numctlerrors; /* number of error responses sent */
774 u_long numctltooshort; /* number of too short input packets */
775 u_long numctlinputresp; /* number of responses on input */
776 u_long numctlinputfrag; /* number of fragments on input */
777 u_long numctlinputerr; /* number of input pkts with err bit set */
778 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
779 u_long numctlbadversion; /* number of input pkts with unknown version */
780 u_long numctldatatooshort; /* data too short for count */
781 u_long numctlbadop; /* bad op code found in packet */
782 u_long numasyncmsgs; /* number of async messages we've sent */
785 * Response packet used by these routines. Also some state information
786 * so that we can handle packet formatting within a common set of
787 * subroutines. Note we try to enter data in place whenever possible,
788 * but the need to set the more bit correctly means we occasionally
789 * use the extra buffer and copy.
791 static struct ntp_control rpkt;
792 static u_char res_version;
793 static u_char res_opcode;
794 static associd_t res_associd;
795 static u_short res_frags; /* datagrams in this response */
796 static int res_offset; /* offset of payload in response */
797 static u_char * datapt;
798 static u_char * dataend;
799 static int datalinelen;
800 static int datasent; /* flag to avoid initial ", " */
801 static int datanotbinflag;
802 static sockaddr_u *rmt_addr;
803 static struct interface *lcl_inter;
805 static u_char res_authenticate;
806 static u_char res_authokay;
807 static keyid_t res_keyid;
809 #define MAXDATALINELEN (72)
811 static u_char res_async; /* sending async trap response? */
814 * Pointers for saving state when decoding request packets
820 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
824 * init_control - initialize request data
833 #endif /* HAVE_UNAME */
838 ctl_sys_last_event = EVNT_UNSPEC;
839 ctl_sys_num_events = 0;
842 for (i = 0; i < COUNTOF(ctl_traps); i++)
843 ctl_traps[i].tr_flags = 0;
848 * ctl_error - send an error response for the current request
858 DPRINTF(3, ("sending control error %u\n", errcode));
861 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
862 * have already been filled in.
864 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
865 (res_opcode & CTL_OP_MASK);
866 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
870 * send packet and bump counters
872 if (res_authenticate && sys_authenticate) {
873 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
875 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
876 CTL_HEADER_LEN + maclen);
878 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
883 is_safe_filename(const char * name)
885 /* We need a strict validation of filenames we should write: The
886 * daemon might run with special permissions and is remote
887 * controllable, so we better take care what we allow as file
890 * The first character must be digit or a letter from the ASCII
891 * base plane or a '_' ([_A-Za-z0-9]), the following characters
892 * must be from [-._+A-Za-z0-9].
894 * We do not trust the character classification much here: Since
895 * the NTP protocol makes no provisions for UTF-8 or local code
896 * pages, we strictly require the 7bit ASCII code page.
898 * The following table is a packed bit field of 128 two-bit
899 * groups. The LSB in each group tells us if a character is
900 * acceptable at the first position, the MSB if the character is
901 * accepted at any other position.
903 * This does not ensure that the file name is syntactically
904 * correct (multiple dots will not work with VMS...) but it will
905 * exclude potential globbing bombs and directory traversal. It
906 * also rules out drive selection. (For systems that have this
907 * notion, like Windows or VMS.)
909 static const uint32_t chclass[8] = {
910 0x00000000, 0x00000000,
911 0x28800000, 0x000FFFFF,
912 0xFFFFFFFC, 0xC03FFFFF,
913 0xFFFFFFFC, 0x003FFFFF
916 u_int widx, bidx, mask;
917 if ( ! (name && *name))
921 while (0 != (widx = (u_char)*name++)) {
922 bidx = (widx & 15) << 1;
924 if (widx >= sizeof(chclass)/sizeof(chclass[0]))
926 if (0 == ((chclass[widx] >> bidx) & mask))
935 * save_config - Implements ntpq -c "saveconfig <filename>"
936 * Writes current configuration including any runtime
937 * changes by ntpq's :config or config-from-file
939 * Note: There should be no buffer overflow or truncation in the
940 * processing of file names -- both cause security problems. This is bit
941 * painful to code but essential here.
945 struct recvbuf *rbufp,
949 /* block directory traversal by searching for characters that
950 * indicate directory components in a file path.
952 * Conceptually we should be searching for DIRSEP in filename,
953 * however Windows actually recognizes both forward and
954 * backslashes as equivalent directory separators at the API
955 * level. On POSIX systems we could allow '\\' but such
956 * filenames are tricky to manipulate from a shell, so just
957 * reject both types of slashes on all platforms.
959 /* TALOS-CAN-0062: block directory traversal for VMS, too */
960 static const char * illegal_in_filename =
962 ":[]" /* do not allow drive and path components here */
963 #elif defined(SYS_WINNT)
964 ":\\/" /* path and drive separators */
966 "\\/" /* separator and critical char for POSIX */
971 static const char savedconfig_eq[] = "savedconfig=";
973 /* Build a safe open mode from the available mode flags. We want
974 * to create a new file and write it in text mode (when
975 * applicable -- only Windows does this...)
977 static const int openmode = O_CREAT | O_TRUNC | O_WRONLY
978 # if defined(O_EXCL) /* posix, vms */
980 # elif defined(_O_EXCL) /* windows is alway very special... */
983 # if defined(_O_TEXT) /* windows, again */
991 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
999 if (RES_NOMODIFY & restrict_mask) {
1000 ctl_printf("%s", "saveconfig prohibited by restrict ... nomodify");
1004 "saveconfig from %s rejected due to nomodify restriction",
1005 stoa(&rbufp->recv_srcadr));
1011 if (NULL == saveconfigdir) {
1012 ctl_printf("%s", "saveconfig prohibited, no saveconfigdir configured");
1016 "saveconfig from %s rejected, no saveconfigdir",
1017 stoa(&rbufp->recv_srcadr));
1021 /* The length checking stuff gets serious. Do not assume a NUL
1022 * byte can be found, but if so, use it to calculate the needed
1023 * buffer size. If the available buffer is too short, bail out;
1024 * likewise if there is no file spec. (The latter will not
1025 * happen when using NTPQ, but there are other ways to craft a
1028 reqlen = (size_t)(reqend - reqpt);
1030 char * nulpos = (char*)memchr(reqpt, 0, reqlen);
1032 reqlen = (size_t)(nulpos - reqpt);
1036 if (reqlen >= sizeof(filespec)) {
1037 ctl_printf("saveconfig exceeded maximum raw name length (%u)",
1038 (u_int)sizeof(filespec));
1041 "saveconfig exceeded maximum raw name length from %s",
1042 stoa(&rbufp->recv_srcadr));
1046 /* copy data directly as we exactly know the size */
1047 memcpy(filespec, reqpt, reqlen);
1048 filespec[reqlen] = '\0';
1051 * allow timestamping of the saved config filename with
1052 * strftime() format such as:
1053 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
1054 * XXX: Nice feature, but not too safe.
1055 * YYY: The check for permitted characters in file names should
1056 * weed out the worst. Let's hope 'strftime()' does not
1057 * develop pathological problems.
1060 if (0 == strftime(filename, sizeof(filename), filespec,
1064 * If we arrive here, 'strftime()' balked; most likely
1065 * the buffer was too short. (Or it encounterd an empty
1066 * format, or just a format that expands to an empty
1067 * string.) We try to use the original name, though this
1068 * is very likely to fail later if there are format
1069 * specs in the string. Note that truncation cannot
1070 * happen here as long as both buffers have the same
1073 strlcpy(filename, filespec, sizeof(filename));
1077 * Check the file name for sanity. This might/will rule out file
1078 * names that would be legal but problematic, and it blocks
1079 * directory traversal.
1081 if (!is_safe_filename(filename)) {
1082 ctl_printf("saveconfig rejects unsafe file name '%s'",
1086 "saveconfig rejects unsafe file name from %s",
1087 stoa(&rbufp->recv_srcadr));
1092 * XXX: This next test may not be needed with is_safe_filename()
1095 /* block directory/drive traversal */
1096 /* TALOS-CAN-0062: block directory traversal for VMS, too */
1097 if (NULL != strpbrk(filename, illegal_in_filename)) {
1098 snprintf(reply, sizeof(reply),
1099 "saveconfig does not allow directory in filename");
1100 ctl_putdata(reply, strlen(reply), 0);
1103 "saveconfig rejects unsafe file name from %s",
1104 stoa(&rbufp->recv_srcadr));
1108 /* concatenation of directory and path can cause another
1111 prc = snprintf(fullpath, sizeof(fullpath), "%s%s",
1112 saveconfigdir, filename);
1113 if (prc < 0 || (size_t)prc >= sizeof(fullpath)) {
1114 ctl_printf("saveconfig exceeded maximum path length (%u)",
1115 (u_int)sizeof(fullpath));
1118 "saveconfig exceeded maximum path length from %s",
1119 stoa(&rbufp->recv_srcadr));
1123 fd = open(fullpath, openmode, S_IRUSR | S_IWUSR);
1127 fptr = fdopen(fd, "w");
1129 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
1130 ctl_printf("Unable to save configuration to file '%s': %s",
1131 filename, strerror(errno));
1133 "saveconfig %s from %s failed", filename,
1134 stoa(&rbufp->recv_srcadr));
1136 ctl_printf("Configuration saved to '%s'", filename);
1138 "Configuration saved to '%s' (requested by %s)",
1139 fullpath, stoa(&rbufp->recv_srcadr));
1141 * save the output filename in system variable
1142 * savedconfig, retrieved with:
1143 * ntpq -c "rv 0 savedconfig"
1144 * Note: the way 'savedconfig' is defined makes overflow
1145 * checks unnecessary here.
1147 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
1148 savedconfig_eq, filename);
1149 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1154 #else /* !SAVECONFIG follows */
1156 "saveconfig unavailable, configured with --disable-saveconfig");
1163 * process_control - process an incoming control message
1167 struct recvbuf *rbufp,
1171 struct ntp_control *pkt;
1174 const struct ctl_proc *cc;
1179 DPRINTF(3, ("in process_control()\n"));
1182 * Save the addresses for error responses
1185 rmt_addr = &rbufp->recv_srcadr;
1186 lcl_inter = rbufp->dstadr;
1187 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1190 * If the length is less than required for the header, or
1191 * it is a response or a fragment, ignore this.
1193 if (rbufp->recv_length < (int)CTL_HEADER_LEN
1194 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1195 || pkt->offset != 0) {
1196 DPRINTF(1, ("invalid format in control packet\n"));
1197 if (rbufp->recv_length < (int)CTL_HEADER_LEN)
1199 if (CTL_RESPONSE & pkt->r_m_e_op)
1201 if (CTL_MORE & pkt->r_m_e_op)
1203 if (CTL_ERROR & pkt->r_m_e_op)
1205 if (pkt->offset != 0)
1209 res_version = PKT_VERSION(pkt->li_vn_mode);
1210 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1211 DPRINTF(1, ("unknown version %d in control packet\n",
1218 * Pull enough data from the packet to make intelligent
1221 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1223 res_opcode = pkt->r_m_e_op;
1224 rpkt.sequence = pkt->sequence;
1225 rpkt.associd = pkt->associd;
1229 res_associd = htons(pkt->associd);
1231 res_authenticate = FALSE;
1233 res_authokay = FALSE;
1234 req_count = (int)ntohs(pkt->count);
1235 datanotbinflag = FALSE;
1238 datapt = rpkt.u.data;
1239 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1241 if ((rbufp->recv_length & 0x3) != 0)
1242 DPRINTF(3, ("Control packet length %d unrounded\n",
1243 rbufp->recv_length));
1246 * We're set up now. Make sure we've got at least enough
1247 * incoming data space to match the count.
1249 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1250 if (req_data < req_count || rbufp->recv_length & 0x3) {
1251 ctl_error(CERR_BADFMT);
1252 numctldatatooshort++;
1256 properlen = req_count + CTL_HEADER_LEN;
1257 /* round up proper len to a 8 octet boundary */
1259 properlen = (properlen + 7) & ~7;
1260 maclen = rbufp->recv_length - properlen;
1261 if ((rbufp->recv_length & 3) == 0 &&
1262 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1264 res_authenticate = TRUE;
1265 pkid = (void *)((char *)pkt + properlen);
1266 res_keyid = ntohl(*pkid);
1267 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1268 rbufp->recv_length, properlen, res_keyid,
1271 if (!authistrustedip(res_keyid, &rbufp->recv_srcadr))
1272 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1273 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1274 rbufp->recv_length - maclen,
1276 res_authokay = TRUE;
1277 DPRINTF(3, ("authenticated okay\n"));
1280 DPRINTF(3, ("authentication failed\n"));
1285 * Set up translate pointers
1287 reqpt = (char *)pkt->u.data;
1288 reqend = reqpt + req_count;
1291 * Look for the opcode processor
1293 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1294 if (cc->control_code == res_opcode) {
1295 DPRINTF(3, ("opcode %d, found command handler\n",
1297 if (cc->flags == AUTH
1299 || res_keyid != ctl_auth_keyid)) {
1300 ctl_error(CERR_PERMISSION);
1303 (cc->handler)(rbufp, restrict_mask);
1309 * Can't find this one, return an error.
1312 ctl_error(CERR_BADOP);
1318 * ctlpeerstatus - return a status word for this peer
1322 register struct peer *p
1328 if (FLAG_CONFIG & p->flags)
1329 status |= CTL_PST_CONFIG;
1331 status |= CTL_PST_AUTHENABLE;
1332 if (FLAG_AUTHENTIC & p->flags)
1333 status |= CTL_PST_AUTHENTIC;
1335 status |= CTL_PST_REACH;
1336 if (MDF_TXONLY_MASK & p->cast_flags)
1337 status |= CTL_PST_BCAST;
1339 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1344 * ctlclkstatus - return a status word for this clock
1349 struct refclockstat *pcs
1352 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1358 * ctlsysstatus - return the system status word
1363 register u_char this_clock;
1365 this_clock = CTL_SST_TS_UNSPEC;
1367 if (sys_peer != NULL) {
1368 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1369 this_clock = sys_peer->sstclktype;
1370 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1371 this_clock = clocktypes[sys_peer->refclktype];
1373 #else /* REFCLOCK */
1375 this_clock = CTL_SST_TS_NTP;
1376 #endif /* REFCLOCK */
1377 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1378 ctl_sys_last_event);
1383 * ctl_flushpkt - write out the current packet and prepare
1384 * another if necessary.
1398 dlen = datapt - rpkt.u.data;
1399 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1401 * Big hack, output a trailing \r\n
1407 sendlen = dlen + CTL_HEADER_LEN;
1410 * Pad to a multiple of 32 bits
1412 while (sendlen & 0x3) {
1418 * Fill in the packet with the current info
1420 rpkt.r_m_e_op = CTL_RESPONSE | more |
1421 (res_opcode & CTL_OP_MASK);
1422 rpkt.count = htons((u_short)dlen);
1423 rpkt.offset = htons((u_short)res_offset);
1425 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1426 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1430 ctl_traps[i].tr_version,
1433 htons(ctl_traps[i].tr_sequence);
1434 sendpkt(&ctl_traps[i].tr_addr,
1435 ctl_traps[i].tr_localaddr, -4,
1436 (struct pkt *)&rpkt, sendlen);
1438 ctl_traps[i].tr_sequence++;
1443 if (res_authenticate && sys_authenticate) {
1446 * If we are going to authenticate, then there
1447 * is an additional requirement that the MAC
1448 * begin on a 64 bit boundary.
1450 while (totlen & 7) {
1454 keyid = htonl(res_keyid);
1455 memcpy(datapt, &keyid, sizeof(keyid));
1456 maclen = authencrypt(res_keyid,
1457 (u_int32 *)&rpkt, totlen);
1458 sendpkt(rmt_addr, lcl_inter, -5,
1459 (struct pkt *)&rpkt, totlen + maclen);
1461 sendpkt(rmt_addr, lcl_inter, -6,
1462 (struct pkt *)&rpkt, sendlen);
1471 * Set us up for another go around.
1475 datapt = rpkt.u.data;
1479 /* --------------------------------------------------------------------
1480 * block transfer API -- stream string/data fragments into xmit buffer
1481 * without additional copying
1484 /* buffer descriptor: address & size of fragment
1485 * 'buf' may only be NULL when 'len' is zero!
1492 /* put ctl data in a gather-style operation */
1495 const CtlMemBufT * argv,
1497 int/*BOOL*/ bin /* set to 1 when data is binary */
1500 const char * src_ptr;
1501 size_t src_len, cur_len, add_len, argi;
1503 /* text / binary preprocessing, possibly create new linefeed */
1507 datanotbinflag = TRUE;
1514 /* sum up total length */
1515 for (argi = 0, src_len = 0; argi < argc; ++argi)
1516 src_len += argv[argi].len;
1517 /* possibly start a new line, assume no size_t overflow */
1518 if ((src_len + datalinelen + 1) >= MAXDATALINELEN) {
1529 /* now stream out all buffers */
1530 for (argi = 0; argi < argc; ++argi) {
1531 src_ptr = argv[argi].buf;
1532 src_len = argv[argi].len;
1534 if ( ! (src_ptr && src_len))
1537 cur_len = (size_t)(dataend - datapt);
1538 while ((src_len + add_len) > cur_len) {
1539 /* Not enough room in this one, flush it out. */
1540 if (src_len < cur_len)
1543 memcpy(datapt, src_ptr, cur_len);
1545 datalinelen += cur_len;
1550 ctl_flushpkt(CTL_MORE);
1551 cur_len = (size_t)(dataend - datapt);
1554 memcpy(datapt, src_ptr, src_len);
1556 datalinelen += src_len;
1563 * ctl_putdata - write data into the packet, fragmenting and starting
1564 * another if this one is full.
1570 int bin /* set to 1 when data is binary */
1577 ctl_putdata_ex(args, 1, bin);
1581 * ctl_putstr - write a tagged string into the response packet
1586 * len is the data length excluding the NUL terminator,
1587 * as in ctl_putstr("var", "value", strlen("value"));
1599 args[0].len = strlen(tag);
1601 args[1].buf = "=\"";
1607 ctl_putdata_ex(args, 4, FALSE);
1609 args[1].buf = "=\"\"";
1611 ctl_putdata_ex(args, 2, FALSE);
1617 * ctl_putunqstr - write a tagged string into the response packet
1622 * len is the data length excluding the NUL terminator.
1623 * data must not contain a comma or whitespace.
1635 args[0].len = strlen(tag);
1641 ctl_putdata_ex(args, 3, FALSE);
1643 ctl_putdata_ex(args, 2, FALSE);
1649 * ctl_putdblf - write a tagged, signed double into the response packet
1662 rc = snprintf(buffer, sizeof(buffer),
1663 (use_f ? "%.*f" : "%.*g"),
1665 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1666 ctl_putunqstr(tag, buffer, rc);
1670 * ctl_putuint - write a tagged unsigned integer into the response
1678 char buffer[24]; /* needs to fit for 64 bits! */
1681 rc = snprintf(buffer, sizeof(buffer), "%lu", uval);
1682 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1683 ctl_putunqstr(tag, buffer, rc);
1687 * ctl_putcal - write a decoded calendar data into the response.
1688 * only used with AUTOKEY currently, so compiled conditional
1694 const struct calendar *pcal
1700 rc = snprintf(buffer, sizeof(buffer),
1701 "%04d%02d%02d%02d%02d",
1702 pcal->year, pcal->month, pcal->monthday,
1703 pcal->hour, pcal->minute
1705 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1706 ctl_putunqstr(tag, buffer, rc);
1711 * ctl_putfs - write a decoded filestamp into the response
1722 time_t fstamp = (time_t)uval - JAN_1970;
1723 struct tm *tm = gmtime(&fstamp);
1728 rc = snprintf(buffer, sizeof(buffer),
1729 "%04d%02d%02d%02d%02d",
1730 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1731 tm->tm_hour, tm->tm_min);
1732 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1733 ctl_putunqstr(tag, buffer, rc);
1738 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1747 char buffer[24]; /* must fit 64bit int! */
1750 rc = snprintf(buffer, sizeof(buffer), "0x%lx", uval);
1751 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1752 ctl_putunqstr(tag, buffer, rc);
1757 * ctl_putint - write a tagged signed integer into the response
1765 char buffer[24]; /*must fit 64bit int */
1768 rc = snprintf(buffer, sizeof(buffer), "%ld", ival);
1769 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1770 ctl_putunqstr(tag, buffer, rc);
1775 * ctl_putts - write a tagged timestamp, in hex, into the response
1786 rc = snprintf(buffer, sizeof(buffer),
1788 (u_long)ts->l_ui, (u_long)ts->l_uf);
1789 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1790 ctl_putunqstr(tag, buffer, rc);
1795 * ctl_putadr - write an IP address into the response
1807 cq = numtoa(addr32);
1810 ctl_putunqstr(tag, cq, strlen(cq));
1815 * ctl_putrefid - send a u_int32 refid as printable text
1827 uint8_t b[sizeof(uint32_t)];
1831 for (nc = 0; nc < sizeof(bytes.b) && bytes.b[nc]; ++nc)
1832 if ( !isprint(bytes.b[nc])
1833 || isspace(bytes.b[nc])
1834 || bytes.b[nc] == ',' )
1836 ctl_putunqstr(tag, (const char*)bytes.b, nc);
1841 * ctl_putarray - write a tagged eight element double array into the response
1855 ep = buffer + sizeof(buffer);
1861 rc = snprintf(cp, (size_t)(ep - cp), " %.2f", arr[i] * 1e3);
1862 INSIST(rc >= 0 && (size_t)rc < (size_t)(ep - cp));
1864 } while (i != start);
1865 ctl_putunqstr(tag, buffer, (size_t)(cp - buffer));
1869 * ctl_printf - put a formatted string into the data buffer
1877 static const char * ellipsis = "[...]";
1883 rc = vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, va);
1885 if (rc < 0 || (size_t)rc >= sizeof(fmtbuf))
1886 strcpy(fmtbuf + sizeof(fmtbuf) - strlen(ellipsis) - 1,
1888 ctl_putdata(fmtbuf, strlen(fmtbuf), 0);
1893 * ctl_putsys - output a system variable
1907 struct cert_info *cp;
1908 #endif /* AUTOKEY */
1910 static struct timex ntx;
1911 static u_long ntp_adjtime_time;
1913 static const double to_ms_usec =
1914 1.0e-3; /* usec to msec */
1915 static const double to_ms_nusec =
1917 1.0e-6; /* nsec to msec */
1923 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1925 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1926 current_time != ntp_adjtime_time) {
1928 if (ntp_adjtime(&ntx) < 0)
1929 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1931 ntp_adjtime_time = current_time;
1933 #endif /* KERNEL_PLL */
1938 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1942 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1946 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1950 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1954 case CS_ROOTDISPERSION:
1955 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1956 sys_rootdisp * 1e3);
1960 if (REFID_ISTEXT(sys_stratum))
1961 ctl_putrefid(sys_var[varid].text, sys_refid);
1963 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1967 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1971 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
1975 if (sys_peer == NULL)
1976 ctl_putuint(sys_var[CS_PEERID].text, 0);
1978 ctl_putuint(sys_var[CS_PEERID].text,
1983 if (sys_peer != NULL && sys_peer->dstadr != NULL)
1984 ss = sptoa(&sys_peer->srcadr);
1987 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
1991 u = (sys_peer != NULL)
1994 ctl_putuint(sys_var[CS_PEERMODE].text, u);
1998 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
2002 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
2006 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
2010 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
2015 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
2020 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
2021 sizeof(str_processor) - 1);
2023 ctl_putstr(sys_var[CS_PROCESSOR].text,
2024 utsnamebuf.machine, strlen(utsnamebuf.machine));
2025 #endif /* HAVE_UNAME */
2030 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
2031 sizeof(str_system) - 1);
2033 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
2034 utsnamebuf.release);
2035 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
2036 #endif /* HAVE_UNAME */
2040 ctl_putstr(sys_var[CS_VERSION].text, Version,
2045 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
2051 char buf[CTL_MAX_DATA_LEN];
2052 //buffPointer, firstElementPointer, buffEndPointer
2053 char *buffp, *buffend;
2057 const struct ctl_var *k;
2060 buffend = buf + sizeof(buf);
2061 if (strlen(sys_var[CS_VARLIST].text) > (sizeof(buf) - 4))
2062 break; /* really long var name */
2064 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
2065 buffp += strlen(buffp);
2066 firstVarName = TRUE;
2067 for (k = sys_var; !(k->flags & EOV); k++) {
2068 if (k->flags & PADDING)
2070 len = strlen(k->text);
2071 if (len + 1 >= buffend - buffp)
2076 firstVarName = FALSE;
2077 memcpy(buffp, k->text, len);
2081 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
2082 if (k->flags & PADDING)
2084 if (NULL == k->text)
2086 ss1 = strchr(k->text, '=');
2088 len = strlen(k->text);
2090 len = ss1 - k->text;
2091 if (len + 1 >= buffend - buffp)
2095 firstVarName = FALSE;
2097 memcpy(buffp, k->text,(unsigned)len);
2100 if (2 >= buffend - buffp)
2106 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
2112 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
2117 leap_signature_t lsig;
2118 leapsec_getsig(&lsig);
2120 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
2126 leap_signature_t lsig;
2127 leapsec_getsig(&lsig);
2129 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2134 case CS_LEAPSMEARINTV:
2135 if (leap_smear_intv > 0)
2136 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2139 case CS_LEAPSMEAROFFS:
2140 if (leap_smear_intv > 0)
2141 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2142 leap_smear.doffset * 1e3);
2144 #endif /* LEAP_SMEAR */
2147 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2150 case CS_MRU_ENABLED:
2151 ctl_puthex(sys_var[varid].text, mon_enabled);
2155 ctl_putuint(sys_var[varid].text, mru_entries);
2159 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2163 ctl_putuint(sys_var[varid].text, u);
2166 case CS_MRU_DEEPEST:
2167 ctl_putuint(sys_var[varid].text, mru_peakentries);
2170 case CS_MRU_MINDEPTH:
2171 ctl_putuint(sys_var[varid].text, mru_mindepth);
2175 ctl_putint(sys_var[varid].text, mru_maxage);
2178 case CS_MRU_MAXDEPTH:
2179 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2183 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2187 ctl_putuint(sys_var[varid].text, u);
2191 ctl_putuint(sys_var[varid].text, current_time);
2195 ctl_putuint(sys_var[varid].text,
2196 current_time - sys_stattime);
2199 case CS_SS_RECEIVED:
2200 ctl_putuint(sys_var[varid].text, sys_received);
2204 ctl_putuint(sys_var[varid].text, sys_newversion);
2208 ctl_putuint(sys_var[varid].text, sys_oldversion);
2211 case CS_SS_BADFORMAT:
2212 ctl_putuint(sys_var[varid].text, sys_badlength);
2216 ctl_putuint(sys_var[varid].text, sys_badauth);
2219 case CS_SS_DECLINED:
2220 ctl_putuint(sys_var[varid].text, sys_declined);
2223 case CS_SS_RESTRICTED:
2224 ctl_putuint(sys_var[varid].text, sys_restricted);
2228 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2232 ctl_putuint(sys_var[varid].text, sys_lamport);
2235 case CS_SS_TSROUNDING:
2236 ctl_putuint(sys_var[varid].text, sys_tsrounding);
2240 ctl_putuint(sys_var[varid].text, sys_kodsent);
2243 case CS_SS_PROCESSED:
2244 ctl_putuint(sys_var[varid].text, sys_processed);
2248 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2252 LFPTOD(&sys_authdelay, dtemp);
2253 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2257 ctl_putuint(sys_var[varid].text, authnumkeys);
2261 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2264 case CS_AUTHKLOOKUPS:
2265 ctl_putuint(sys_var[varid].text, authkeylookups);
2268 case CS_AUTHKNOTFOUND:
2269 ctl_putuint(sys_var[varid].text, authkeynotfound);
2272 case CS_AUTHKUNCACHED:
2273 ctl_putuint(sys_var[varid].text, authkeyuncached);
2276 case CS_AUTHKEXPIRED:
2277 ctl_putuint(sys_var[varid].text, authkeyexpired);
2280 case CS_AUTHENCRYPTS:
2281 ctl_putuint(sys_var[varid].text, authencryptions);
2284 case CS_AUTHDECRYPTS:
2285 ctl_putuint(sys_var[varid].text, authdecryptions);
2289 ctl_putuint(sys_var[varid].text,
2290 current_time - auth_timereset);
2294 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2295 * unavailable, otherwise calls putfunc with args.
2298 # define CTL_IF_KERNLOOP(putfunc, args) \
2299 ctl_putint(sys_var[varid].text, 0)
2301 # define CTL_IF_KERNLOOP(putfunc, args) \
2306 * CTL_IF_KERNPPS() puts a zero if either the kernel
2307 * loop is unavailable, or kernel hard PPS is not
2308 * active, otherwise calls putfunc with args.
2311 # define CTL_IF_KERNPPS(putfunc, args) \
2312 ctl_putint(sys_var[varid].text, 0)
2314 # define CTL_IF_KERNPPS(putfunc, args) \
2315 if (0 == ntx.shift) \
2316 ctl_putint(sys_var[varid].text, 0); \
2318 putfunc args /* no trailing ; */
2324 (sys_var[varid].text, 0, -1, to_ms_nusec * ntx.offset)
2331 (sys_var[varid].text, ntx.freq)
2338 (sys_var[varid].text, 0, 6,
2339 to_ms_usec * ntx.maxerror)
2346 (sys_var[varid].text, 0, 6,
2347 to_ms_usec * ntx.esterror)
2355 ss = k_st_flags(ntx.status);
2357 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2360 case CS_K_TIMECONST:
2363 (sys_var[varid].text, ntx.constant)
2367 case CS_K_PRECISION:
2370 (sys_var[varid].text, 0, 6,
2371 to_ms_usec * ntx.precision)
2378 (sys_var[varid].text, ntx.tolerance)
2385 (sys_var[varid].text, ntx.ppsfreq)
2389 case CS_K_PPS_STABIL:
2392 (sys_var[varid].text, ntx.stabil)
2396 case CS_K_PPS_JITTER:
2399 (sys_var[varid].text, to_ms_nusec * ntx.jitter)
2403 case CS_K_PPS_CALIBDUR:
2406 (sys_var[varid].text, 1 << ntx.shift)
2410 case CS_K_PPS_CALIBS:
2413 (sys_var[varid].text, ntx.calcnt)
2417 case CS_K_PPS_CALIBERRS:
2420 (sys_var[varid].text, ntx.errcnt)
2424 case CS_K_PPS_JITEXC:
2427 (sys_var[varid].text, ntx.jitcnt)
2431 case CS_K_PPS_STBEXC:
2434 (sys_var[varid].text, ntx.stbcnt)
2438 case CS_IOSTATS_RESET:
2439 ctl_putuint(sys_var[varid].text,
2440 current_time - io_timereset);
2444 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2448 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2452 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2455 case CS_RBUF_LOWATER:
2456 ctl_putuint(sys_var[varid].text, lowater_additions());
2460 ctl_putuint(sys_var[varid].text, packets_dropped);
2464 ctl_putuint(sys_var[varid].text, packets_ignored);
2467 case CS_IO_RECEIVED:
2468 ctl_putuint(sys_var[varid].text, packets_received);
2472 ctl_putuint(sys_var[varid].text, packets_sent);
2475 case CS_IO_SENDFAILED:
2476 ctl_putuint(sys_var[varid].text, packets_notsent);
2480 ctl_putuint(sys_var[varid].text, handler_calls);
2483 case CS_IO_GOODWAKEUPS:
2484 ctl_putuint(sys_var[varid].text, handler_pkts);
2487 case CS_TIMERSTATS_RESET:
2488 ctl_putuint(sys_var[varid].text,
2489 current_time - timer_timereset);
2492 case CS_TIMER_OVERRUNS:
2493 ctl_putuint(sys_var[varid].text, alarm_overflow);
2497 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2501 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2503 case CS_WANDER_THRESH:
2504 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2509 ctl_puthex(sys_var[CS_FLAGS].text,
2515 strlcpy(str, OBJ_nid2ln(crypto_nid),
2517 ctl_putstr(sys_var[CS_DIGEST].text, str,
2526 dp = EVP_get_digestbynid(crypto_flags >> 16);
2527 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2529 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2535 if (hostval.ptr != NULL)
2536 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2537 strlen(hostval.ptr));
2541 if (sys_ident != NULL)
2542 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2547 for (cp = cinfo; cp != NULL; cp = cp->link) {
2548 snprintf(str, sizeof(str), "%s %s 0x%x",
2549 cp->subject, cp->issuer, cp->flags);
2550 ctl_putstr(sys_var[CS_CERTIF].text, str,
2552 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2557 if (hostval.tstamp != 0)
2558 ctl_putfs(sys_var[CS_PUBLIC].text,
2559 ntohl(hostval.tstamp));
2561 #endif /* AUTOKEY */
2570 * ctl_putpeer - output a peer variable
2578 char buf[CTL_MAX_DATA_LEN];
2583 const struct ctl_var *k;
2588 #endif /* AUTOKEY */
2593 ctl_putuint(peer_var[id].text,
2594 !(FLAG_PREEMPT & p->flags));
2598 ctl_putuint(peer_var[id].text, !(p->keyid));
2602 ctl_putuint(peer_var[id].text,
2603 !!(FLAG_AUTHENTIC & p->flags));
2607 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2611 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2615 if (p->hostname != NULL)
2616 ctl_putstr(peer_var[id].text, p->hostname,
2617 strlen(p->hostname));
2621 ctl_putadr(peer_var[id].text, 0,
2628 ctl_putuint(peer_var[id].text,
2630 ? SRCPORT(&p->dstadr->sin)
2636 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2641 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2645 ctl_putuint(peer_var[id].text, p->throttle);
2649 ctl_putuint(peer_var[id].text, p->leap);
2653 ctl_putuint(peer_var[id].text, p->hmode);
2657 ctl_putuint(peer_var[id].text, p->stratum);
2661 ctl_putuint(peer_var[id].text, p->ppoll);
2665 ctl_putuint(peer_var[id].text, p->hpoll);
2669 ctl_putint(peer_var[id].text, p->precision);
2673 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2676 case CP_ROOTDISPERSION:
2677 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2682 if (p->flags & FLAG_REFCLOCK) {
2683 ctl_putrefid(peer_var[id].text, p->refid);
2687 if (REFID_ISTEXT(p->stratum))
2688 ctl_putrefid(peer_var[id].text, p->refid);
2690 ctl_putadr(peer_var[id].text, p->refid, NULL);
2694 ctl_putts(peer_var[id].text, &p->reftime);
2698 ctl_putts(peer_var[id].text, &p->aorg);
2702 ctl_putts(peer_var[id].text, &p->dst);
2707 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2712 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2716 ctl_puthex(peer_var[id].text, p->reach);
2720 ctl_puthex(peer_var[id].text, p->flash);
2725 if (p->flags & FLAG_REFCLOCK) {
2726 ctl_putuint(peer_var[id].text, p->ttl);
2730 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2731 ctl_putint(peer_var[id].text,
2736 ctl_putuint(peer_var[id].text, p->unreach);
2740 ctl_putuint(peer_var[id].text,
2741 p->nextdate - current_time);
2745 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2749 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2753 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2757 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2761 if (p->keyid > NTP_MAXKEY)
2762 ctl_puthex(peer_var[id].text, p->keyid);
2764 ctl_putuint(peer_var[id].text, p->keyid);
2768 ctl_putarray(peer_var[id].text, p->filter_delay,
2773 ctl_putarray(peer_var[id].text, p->filter_offset,
2778 ctl_putarray(peer_var[id].text, p->filter_disp,
2783 ctl_putuint(peer_var[id].text, p->pmode);
2787 ctl_putuint(peer_var[id].text, p->received);
2791 ctl_putuint(peer_var[id].text, p->sent);
2796 be = buf + sizeof(buf);
2797 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2798 break; /* really long var name */
2800 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2803 for (k = peer_var; !(EOV & k->flags); k++) {
2804 if (PADDING & k->flags)
2806 i = strlen(k->text);
2807 if (s + i + 1 >= be)
2811 memcpy(s, k->text, i);
2817 ctl_putdata(buf, (u_int)(s - buf), 0);
2822 ctl_putuint(peer_var[id].text,
2823 current_time - p->timereceived);
2827 ctl_putuint(peer_var[id].text,
2828 current_time - p->timereachable);
2832 ctl_putuint(peer_var[id].text, p->badauth);
2836 ctl_putuint(peer_var[id].text, p->bogusorg);
2840 ctl_putuint(peer_var[id].text, p->oldpkt);
2844 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2848 ctl_putuint(peer_var[id].text, p->selbroken);
2852 ctl_putuint(peer_var[id].text, p->status);
2857 ctl_puthex(peer_var[id].text, p->crypto);
2862 dp = EVP_get_digestbynid(p->crypto >> 16);
2863 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2864 ctl_putstr(peer_var[id].text, str, strlen(str));
2869 if (p->subject != NULL)
2870 ctl_putstr(peer_var[id].text, p->subject,
2871 strlen(p->subject));
2874 case CP_VALID: /* not used */
2878 if (NULL == (ap = p->recval.ptr))
2881 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2882 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2883 ctl_putfs(peer_var[CP_INITTSP].text,
2884 ntohl(p->recval.tstamp));
2888 if (p->ident != NULL)
2889 ctl_putstr(peer_var[id].text, p->ident,
2894 #endif /* AUTOKEY */
2901 * ctl_putclock - output clock variables
2906 struct refclockstat *pcs,
2910 char buf[CTL_MAX_DATA_LEN];
2914 const struct ctl_var *k;
2919 if (mustput || pcs->clockdesc == NULL
2920 || *(pcs->clockdesc) == '\0') {
2921 ctl_putuint(clock_var[id].text, pcs->type);
2925 ctl_putstr(clock_var[id].text,
2927 (unsigned)pcs->lencode);
2931 ctl_putuint(clock_var[id].text, pcs->polls);
2935 ctl_putuint(clock_var[id].text,
2940 ctl_putuint(clock_var[id].text,
2945 ctl_putuint(clock_var[id].text,
2950 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2951 ctl_putdbl(clock_var[id].text,
2952 pcs->fudgetime1 * 1e3);
2956 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2957 ctl_putdbl(clock_var[id].text,
2958 pcs->fudgetime2 * 1e3);
2962 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2963 ctl_putint(clock_var[id].text,
2968 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2969 if (pcs->fudgeval1 > 1)
2970 ctl_putadr(clock_var[id].text,
2971 pcs->fudgeval2, NULL);
2973 ctl_putrefid(clock_var[id].text,
2979 ctl_putuint(clock_var[id].text, pcs->flags);
2983 if (pcs->clockdesc == NULL ||
2984 *(pcs->clockdesc) == '\0') {
2986 ctl_putstr(clock_var[id].text,
2989 ctl_putstr(clock_var[id].text,
2991 strlen(pcs->clockdesc));
2997 be = buf + sizeof(buf);
2998 if (strlen(clock_var[CC_VARLIST].text) + 4 >
3000 break; /* really long var name */
3002 snprintf(s, sizeof(buf), "%s=\"",
3003 clock_var[CC_VARLIST].text);
3007 for (k = clock_var; !(EOV & k->flags); k++) {
3008 if (PADDING & k->flags)
3011 i = strlen(k->text);
3012 if (s + i + 1 >= be)
3017 memcpy(s, k->text, i);
3021 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
3022 if (PADDING & k->flags)
3029 while (*ss && *ss != '=')
3032 if (s + i + 1 >= be)
3037 memcpy(s, k->text, (unsigned)i);
3046 ctl_putdata(buf, (unsigned)(s - buf), 0);
3055 * ctl_getitem - get the next data item from the incoming packet
3057 static const struct ctl_var *
3059 const struct ctl_var *var_list,
3063 /* [Bug 3008] First check the packet data sanity, then search
3064 * the key. This improves the consistency of result values: If
3065 * the result is NULL once, it will never be EOV again for this
3066 * packet; If it's EOV, it will never be NULL again until the
3067 * variable is found and processed in a given 'var_list'. (That
3068 * is, a result is returned that is neither NULL nor EOV).
3070 static const struct ctl_var eol = { 0, EOV, NULL };
3071 static char buf[128];
3072 static u_long quiet_until;
3073 const struct ctl_var *v;
3078 * Part One: Validate the packet state
3081 /* Delete leading commas and white space */
3082 while (reqpt < reqend && (*reqpt == ',' ||
3083 isspace((unsigned char)*reqpt)))
3085 if (reqpt >= reqend)
3088 /* Scan the string in the packet until we hit comma or
3089 * EoB. Register position of first '=' on the fly. */
3090 for (tp = NULL, cp = reqpt; cp != reqend; ++cp) {
3091 if (*cp == '=' && tp == NULL)
3097 /* Process payload, if any. */
3100 /* eventually strip white space from argument. */
3101 const char *plhead = tp + 1; /* skip the '=' */
3102 const char *pltail = cp;
3105 while (plhead != pltail && isspace((u_char)plhead[0]))
3107 while (plhead != pltail && isspace((u_char)pltail[-1]))
3110 /* check payload size, terminate packet on overflow */
3111 plsize = (size_t)(pltail - plhead);
3112 if (plsize >= sizeof(buf))
3115 /* copy data, NUL terminate, and set result data ptr */
3116 memcpy(buf, plhead, plsize);
3120 /* no payload, current end --> current name termination */
3126 * Now we're sure that the packet data itself is sane. Scan the
3127 * list now. Make sure a NULL list is properly treated by
3128 * returning a synthetic End-Of-Values record. We must not
3129 * return NULL pointers after this point, or the behaviour would
3130 * become inconsistent if called several times with different
3131 * variable lists after an EoV was returned. (Such a behavior
3132 * actually caused Bug 3008.)
3135 if (NULL == var_list)
3138 for (v = var_list; !(EOV & v->flags); ++v)
3139 if (!(PADDING & v->flags)) {
3140 /* Check if the var name matches the buffer. The
3141 * name is bracketed by [reqpt..tp] and not NUL
3142 * terminated, and it contains no '=' char. The
3143 * lookup value IS NUL-terminated but might
3144 * include a '='... We have to look out for
3147 const char *sp1 = reqpt;
3148 const char *sp2 = v->text;
3150 /* [Bug 3412] do not compare past NUL byte in name */
3152 && ('\0' != *sp2) && (*sp1 == *sp2)) {
3156 if (sp1 == tp && (*sp2 == '\0' || *sp2 == '='))
3160 /* See if we have found a valid entry or not. If found, advance
3161 * the request pointer for the next round; if not, clear the
3162 * data pointer so we have no dangling garbage here.
3167 reqpt = cp + (cp != reqend);
3171 /*TODO? somehow indicate this packet was bad, apart from syslog? */
3174 if (quiet_until <= current_time) {
3175 quiet_until = current_time + 300;
3176 msyslog(LOG_WARNING,
3177 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)",
3178 stoa(rmt_addr), SRCPORT(rmt_addr));
3180 reqpt = reqend; /* never again for this packet! */
3186 * control_unspec - response to an unspecified op-code
3191 struct recvbuf *rbufp,
3198 * What is an appropriate response to an unspecified op-code?
3199 * I return no errors and no data, unless a specified assocation
3203 peer = findpeerbyassoc(res_associd);
3205 ctl_error(CERR_BADASSOC);
3208 rpkt.status = htons(ctlpeerstatus(peer));
3210 rpkt.status = htons(ctlsysstatus());
3216 * read_status - return either a list of associd's, or a particular
3222 struct recvbuf *rbufp,
3229 /* a_st holds association ID, status pairs alternating */
3230 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3234 printf("read_status: ID %d\n", res_associd);
3237 * Two choices here. If the specified association ID is
3238 * zero we return all known assocation ID's. Otherwise
3239 * we return a bunch of stuff about the particular peer.
3242 peer = findpeerbyassoc(res_associd);
3244 ctl_error(CERR_BADASSOC);
3247 rpkt.status = htons(ctlpeerstatus(peer));
3249 peer->num_events = 0;
3251 * For now, output everything we know about the
3252 * peer. May be more selective later.
3254 for (cp = def_peer_var; *cp != 0; cp++)
3255 ctl_putpeer((int)*cp, peer);
3260 rpkt.status = htons(ctlsysstatus());
3261 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3262 a_st[n++] = htons(peer->associd);
3263 a_st[n++] = htons(ctlpeerstatus(peer));
3264 /* two entries each loop iteration, so n + 1 */
3265 if (n + 1 >= COUNTOF(a_st)) {
3266 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3272 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3278 * read_peervars - half of read_variables() implementation
3283 const struct ctl_var *v;
3288 u_char wants[CP_MAXCODE + 1];
3292 * Wants info for a particular peer. See if we know
3295 peer = findpeerbyassoc(res_associd);
3297 ctl_error(CERR_BADASSOC);
3300 rpkt.status = htons(ctlpeerstatus(peer));
3302 peer->num_events = 0;
3305 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3306 if (v->flags & EOV) {
3307 ctl_error(CERR_UNKNOWNVAR);
3310 INSIST(v->code < COUNTOF(wants));
3315 for (i = 1; i < COUNTOF(wants); i++)
3317 ctl_putpeer(i, peer);
3319 for (cp = def_peer_var; *cp != 0; cp++)
3320 ctl_putpeer((int)*cp, peer);
3326 * read_sysvars - half of read_variables() implementation
3331 const struct ctl_var *v;
3342 * Wants system variables. Figure out which he wants
3343 * and give them to him.
3345 rpkt.status = htons(ctlsysstatus());
3347 ctl_sys_num_events = 0;
3348 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3349 wants = emalloc_zero(wants_count);
3351 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3352 if (!(EOV & v->flags)) {
3353 INSIST(v->code < wants_count);
3357 v = ctl_getitem(ext_sys_var, &valuep);
3359 ctl_error(CERR_BADVALUE);
3363 if (EOV & v->flags) {
3364 ctl_error(CERR_UNKNOWNVAR);
3368 n = v->code + CS_MAXCODE + 1;
3369 INSIST(n < wants_count);
3375 for (n = 1; n <= CS_MAXCODE; n++)
3378 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3379 if (wants[n + CS_MAXCODE + 1]) {
3380 pch = ext_sys_var[n].text;
3381 ctl_putdata(pch, strlen(pch), 0);
3384 for (cs = def_sys_var; *cs != 0; cs++)
3385 ctl_putsys((int)*cs);
3386 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3387 if (DEF & kv->flags)
3388 ctl_putdata(kv->text, strlen(kv->text),
3397 * read_variables - return the variables the caller asks for
3402 struct recvbuf *rbufp,
3414 * write_variables - write into variables. We only allow leap bit
3420 struct recvbuf *rbufp,
3424 const struct ctl_var *v;
3435 * If he's trying to write into a peer tell him no way
3437 if (res_associd != 0) {
3438 ctl_error(CERR_PERMISSION);
3445 rpkt.status = htons(ctlsysstatus());
3448 * Look through the variables. Dump out at the first sign of
3451 while ((v = ctl_getitem(sys_var, &valuep)) != NULL) {
3453 if (v->flags & EOV) {
3454 v = ctl_getitem(ext_sys_var, &valuep);
3456 if (v->flags & EOV) {
3457 ctl_error(CERR_UNKNOWNVAR);
3465 if (!(v->flags & CAN_WRITE)) {
3466 ctl_error(CERR_PERMISSION);
3469 /* [bug 3565] writing makes sense only if we *have* a
3470 * value in the packet!
3472 if (valuep == NULL) {
3473 ctl_error(CERR_BADFMT);
3477 if ( !(*valuep && atoint(valuep, &val))) {
3478 ctl_error(CERR_BADFMT);
3481 if ((val & ~LEAP_NOTINSYNC) != 0) {
3482 ctl_error(CERR_BADVALUE);
3488 octets = strlen(v->text) + strlen(valuep) + 2;
3489 vareqv = emalloc(octets);
3492 while (*t && *t != '=')
3495 memcpy(tt, valuep, 1 + strlen(valuep));
3496 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3499 ctl_error(CERR_UNSPEC); /* really */
3505 * If we got anything, do it. xxx nothing to do ***
3508 if (leapind != ~0 || leapwarn != ~0) {
3509 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3510 ctl_error(CERR_PERMISSION);
3520 * configure() processes ntpq :config/config-from-file, allowing
3521 * generic runtime reconfiguration.
3523 static void configure(
3524 struct recvbuf *rbufp,
3531 /* I haven't yet implemented changes to an existing association.
3532 * Hence check if the association id is 0
3534 if (res_associd != 0) {
3535 ctl_error(CERR_BADVALUE);
3539 if (RES_NOMODIFY & restrict_mask) {
3540 snprintf(remote_config.err_msg,
3541 sizeof(remote_config.err_msg),
3542 "runtime configuration prohibited by restrict ... nomodify");
3543 ctl_putdata(remote_config.err_msg,
3544 strlen(remote_config.err_msg), 0);
3548 "runtime config from %s rejected due to nomodify restriction",
3549 stoa(&rbufp->recv_srcadr));
3554 /* Initialize the remote config buffer */
3555 data_count = remoteconfig_cmdlength(reqpt, reqend);
3557 if (data_count > sizeof(remote_config.buffer) - 2) {
3558 snprintf(remote_config.err_msg,
3559 sizeof(remote_config.err_msg),
3560 "runtime configuration failed: request too long");
3561 ctl_putdata(remote_config.err_msg,
3562 strlen(remote_config.err_msg), 0);
3565 "runtime config from %s rejected: request too long",
3566 stoa(&rbufp->recv_srcadr));
3569 /* Bug 2853 -- check if all characters were acceptable */
3570 if (data_count != (size_t)(reqend - reqpt)) {
3571 snprintf(remote_config.err_msg,
3572 sizeof(remote_config.err_msg),
3573 "runtime configuration failed: request contains an unprintable character");
3574 ctl_putdata(remote_config.err_msg,
3575 strlen(remote_config.err_msg), 0);
3578 "runtime config from %s rejected: request contains an unprintable character: %0x",
3579 stoa(&rbufp->recv_srcadr),
3584 memcpy(remote_config.buffer, reqpt, data_count);
3585 /* The buffer has no trailing linefeed or NUL right now. For
3586 * logging, we do not want a newline, so we do that first after
3587 * adding the necessary NUL byte.
3589 remote_config.buffer[data_count] = '\0';
3590 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3591 remote_config.buffer));
3592 msyslog(LOG_NOTICE, "%s config: %s",
3593 stoa(&rbufp->recv_srcadr),
3594 remote_config.buffer);
3596 /* Now we have to make sure there is a NL/NUL sequence at the
3597 * end of the buffer before we parse it.
3599 remote_config.buffer[data_count++] = '\n';
3600 remote_config.buffer[data_count] = '\0';
3601 remote_config.pos = 0;
3602 remote_config.err_pos = 0;
3603 remote_config.no_errors = 0;
3604 config_remotely(&rbufp->recv_srcadr);
3607 * Check if errors were reported. If not, output 'Config
3608 * Succeeded'. Else output the error count. It would be nice
3609 * to output any parser error messages.
3611 if (0 == remote_config.no_errors) {
3612 retval = snprintf(remote_config.err_msg,
3613 sizeof(remote_config.err_msg),
3614 "Config Succeeded");
3616 remote_config.err_pos += retval;
3619 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3622 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3624 if (remote_config.no_errors > 0)
3625 msyslog(LOG_NOTICE, "%d error in %s config",
3626 remote_config.no_errors,
3627 stoa(&rbufp->recv_srcadr));
3632 * derive_nonce - generate client-address-specific nonce value
3633 * associated with a given timestamp.
3635 static u_int32 derive_nonce(
3641 static u_int32 salt[4];
3642 static u_long last_salt_update;
3644 u_char digest[EVP_MAX_MD_SIZE];
3650 while (!salt[0] || current_time - last_salt_update >= 3600) {
3651 salt[0] = ntp_random();
3652 salt[1] = ntp_random();
3653 salt[2] = ntp_random();
3654 salt[3] = ntp_random();
3655 last_salt_update = current_time;
3658 ctx = EVP_MD_CTX_new();
3659 # if defined(OPENSSL) && defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW)
3660 /* [Bug 3457] set flags and don't kill them again */
3661 EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
3662 EVP_DigestInit_ex(ctx, EVP_get_digestbynid(NID_md5), NULL);
3664 EVP_DigestInit(ctx, EVP_get_digestbynid(NID_md5));
3666 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3667 EVP_DigestUpdate(ctx, &ts_i, sizeof(ts_i));
3668 EVP_DigestUpdate(ctx, &ts_f, sizeof(ts_f));
3670 EVP_DigestUpdate(ctx, &SOCK_ADDR4(addr),
3671 sizeof(SOCK_ADDR4(addr)));
3673 EVP_DigestUpdate(ctx, &SOCK_ADDR6(addr),
3674 sizeof(SOCK_ADDR6(addr)));
3675 EVP_DigestUpdate(ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3676 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3677 EVP_DigestFinal(ctx, d.digest, &len);
3678 EVP_MD_CTX_free(ctx);
3685 * generate_nonce - generate client-address-specific nonce string.
3687 static void generate_nonce(
3688 struct recvbuf * rbufp,
3695 derived = derive_nonce(&rbufp->recv_srcadr,
3696 rbufp->recv_time.l_ui,
3697 rbufp->recv_time.l_uf);
3698 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3699 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3704 * validate_nonce - validate client-address-specific nonce string.
3706 * Returns TRUE if the local calculation of the nonce matches the
3707 * client-provided value and the timestamp is recent enough.
3709 static int validate_nonce(
3710 const char * pnonce,
3711 struct recvbuf * rbufp
3721 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3724 ts.l_ui = (u_int32)ts_i;
3725 ts.l_uf = (u_int32)ts_f;
3726 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3727 get_systime(&now_delta);
3728 L_SUB(&now_delta, &ts);
3730 return (supposed == derived && now_delta.l_ui < 16);
3735 * send_random_tag_value - send a randomly-generated three character
3736 * tag prefix, a '.', an index, a '=' and a
3737 * random integer value.
3739 * To try to force clients to ignore unrecognized tags in mrulist,
3740 * reslist, and ifstats responses, the first and last rows are spiced
3741 * with randomly-generated tag names with correct .# index. Make it
3742 * three characters knowing that none of the currently-used subscripted
3743 * tags have that length, avoiding the need to test for
3747 send_random_tag_value(
3754 noise = rand() ^ (rand() << 16);
3755 buf[0] = 'a' + noise % 26;
3757 buf[1] = 'a' + noise % 26;
3759 buf[2] = 'a' + noise % 26;
3762 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3763 ctl_putuint(buf, noise);
3768 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3770 * To keep clients honest about not depending on the order of values,
3771 * and thereby avoid being locked into ugly workarounds to maintain
3772 * backward compatibility later as new fields are added to the response,
3773 * the order is random.
3781 const char first_fmt[] = "first.%d";
3782 const char ct_fmt[] = "ct.%d";
3783 const char mv_fmt[] = "mv.%d";
3784 const char rs_fmt[] = "rs.%d";
3786 u_char sent[6]; /* 6 tag=value pairs */
3792 remaining = COUNTOF(sent);
3794 noise = (u_int32)(rand() ^ (rand() << 16));
3795 while (remaining > 0) {
3796 which = (noise & 7) % COUNTOF(sent);
3799 which = (which + 1) % COUNTOF(sent);
3804 snprintf(tag, sizeof(tag), addr_fmt, count);
3805 pch = sptoa(&mon->rmtadr);
3806 ctl_putunqstr(tag, pch, strlen(pch));
3810 snprintf(tag, sizeof(tag), last_fmt, count);
3811 ctl_putts(tag, &mon->last);
3815 snprintf(tag, sizeof(tag), first_fmt, count);
3816 ctl_putts(tag, &mon->first);
3820 snprintf(tag, sizeof(tag), ct_fmt, count);
3821 ctl_putint(tag, mon->count);
3825 snprintf(tag, sizeof(tag), mv_fmt, count);
3826 ctl_putuint(tag, mon->vn_mode);
3830 snprintf(tag, sizeof(tag), rs_fmt, count);
3831 ctl_puthex(tag, mon->flags);
3841 * read_mru_list - supports ntpq's mrulist command.
3843 * The challenge here is to match ntpdc's monlist functionality without
3844 * being limited to hundreds of entries returned total, and without
3845 * requiring state on the server. If state were required, ntpq's
3846 * mrulist command would require authentication.
3848 * The approach was suggested by Ry Jones. A finite and variable number
3849 * of entries are retrieved per request, to avoid having responses with
3850 * such large numbers of packets that socket buffers are overflowed and
3851 * packets lost. The entries are retrieved oldest-first, taking into
3852 * account that the MRU list will be changing between each request. We
3853 * can expect to see duplicate entries for addresses updated in the MRU
3854 * list during the fetch operation. In the end, the client can assemble
3855 * a close approximation of the MRU list at the point in time the last
3856 * response was sent by ntpd. The only difference is it may be longer,
3857 * containing some number of oldest entries which have since been
3858 * reclaimed. If necessary, the protocol could be extended to zap those
3859 * from the client snapshot at the end, but so far that doesn't seem
3862 * To accomodate the changing MRU list, the starting point for requests
3863 * after the first request is supplied as a series of last seen
3864 * timestamps and associated addresses, the newest ones the client has
3865 * received. As long as at least one of those entries hasn't been
3866 * bumped to the head of the MRU list, ntpd can pick up at that point.
3867 * Otherwise, the request is failed and it is up to ntpq to back up and
3868 * provide the next newest entry's timestamps and addresses, conceivably
3869 * backing up all the way to the starting point.
3872 * nonce= Regurgitated nonce retrieved by the client
3873 * previously using CTL_OP_REQ_NONCE, demonstrating
3874 * ability to receive traffic sent to its address.
3875 * frags= Limit on datagrams (fragments) in response. Used
3876 * by newer ntpq versions instead of limit= when
3877 * retrieving multiple entries.
3878 * limit= Limit on MRU entries returned. One of frags= or
3879 * limit= must be provided.
3880 * limit=1 is a special case: Instead of fetching
3881 * beginning with the supplied starting point's
3882 * newer neighbor, fetch the supplied entry, and
3883 * in that case the #.last timestamp can be zero.
3884 * This enables fetching a single entry by IP
3885 * address. When limit is not one and frags= is
3886 * provided, the fragment limit controls.
3887 * mincount= (decimal) Return entries with count >= mincount.
3888 * laddr= Return entries associated with the server's IP
3889 * address given. No port specification is needed,
3890 * and any supplied is ignored.
3891 * resall= 0x-prefixed hex restrict bits which must all be
3892 * lit for an MRU entry to be included.
3893 * Has precedence over any resany=.
3894 * resany= 0x-prefixed hex restrict bits, at least one of
3895 * which must be list for an MRU entry to be
3897 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3898 * which client previously received.
3899 * addr.0= text of newest entry's IP address and port,
3900 * IPv6 addresses in bracketed form: [::]:123
3901 * last.1= timestamp of 2nd newest entry client has.
3902 * addr.1= address of 2nd newest entry.
3905 * ntpq provides as many last/addr pairs as will fit in a single request
3906 * packet, except for the first request in a MRU fetch operation.
3908 * The response begins with a new nonce value to be used for any
3909 * followup request. Following the nonce is the next newer entry than
3910 * referred to by last.0 and addr.0, if the "0" entry has not been
3911 * bumped to the front. If it has, the first entry returned will be the
3912 * next entry newer than referred to by last.1 and addr.1, and so on.
3913 * If none of the referenced entries remain unchanged, the request fails
3914 * and ntpq backs up to the next earlier set of entries to resync.
3916 * Except for the first response, the response begins with confirmation
3917 * of the entry that precedes the first additional entry provided:
3919 * last.older= hex l_fp timestamp matching one of the input
3920 * .last timestamps, which entry now precedes the
3921 * response 0. entry in the MRU list.
3922 * addr.older= text of address corresponding to older.last.
3924 * And in any case, a successful response contains sets of values
3925 * comprising entries, with the oldest numbered 0 and incrementing from
3928 * addr.# text of IPv4 or IPv6 address and port
3929 * last.# hex l_fp timestamp of last receipt
3930 * first.# hex l_fp timestamp of first receipt
3931 * ct.# count of packets received
3932 * mv.# mode and version
3933 * rs.# restriction mask (RES_* bits)
3935 * Note the code currently assumes there are no valid three letter
3936 * tags sent with each row, and needs to be adjusted if that changes.
3938 * The client should accept the values in any order, and ignore .#
3939 * values which it does not understand, to allow a smooth path to
3940 * future changes without requiring a new opcode. Clients can rely
3941 * on all *.0 values preceding any *.1 values, that is all values for
3942 * a given index number are together in the response.
3944 * The end of the response list is noted with one or two tag=value
3945 * pairs. Unconditionally:
3947 * now= 0x-prefixed l_fp timestamp at the server marking
3948 * the end of the operation.
3950 * If any entries were returned, now= is followed by:
3952 * last.newest= hex l_fp identical to last.# of the prior
3955 static void read_mru_list(
3956 struct recvbuf *rbufp,
3960 static const char nulltxt[1] = { '\0' };
3961 static const char nonce_text[] = "nonce";
3962 static const char frags_text[] = "frags";
3963 static const char limit_text[] = "limit";
3964 static const char mincount_text[] = "mincount";
3965 static const char resall_text[] = "resall";
3966 static const char resany_text[] = "resany";
3967 static const char maxlstint_text[] = "maxlstint";
3968 static const char laddr_text[] = "laddr";
3969 static const char resaxx_fmt[] = "0x%hx";
3978 struct interface * lcladr;
3983 sockaddr_u addr[COUNTOF(last)];
3985 struct ctl_var * in_parms;
3986 const struct ctl_var * v;
3995 mon_entry * prior_mon;
3998 if (RES_NOMRULIST & restrict_mask) {
3999 ctl_error(CERR_PERMISSION);
4002 "mrulist from %s rejected due to nomrulist restriction",
4003 stoa(&rbufp->recv_srcadr));
4008 * fill in_parms var list with all possible input parameters.
4011 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
4012 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
4013 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
4014 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
4015 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
4016 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
4017 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
4018 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
4019 for (i = 0; i < COUNTOF(last); i++) {
4020 snprintf(buf, sizeof(buf), last_fmt, (int)i);
4021 set_var(&in_parms, buf, strlen(buf) + 1, 0);
4022 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
4023 set_var(&in_parms, buf, strlen(buf) + 1, 0);
4026 /* decode input parms */
4039 /* have to go through '(void*)' to drop 'const' property from pointer.
4040 * ctl_getitem()' needs some cleanup, too.... perlinger@ntp.org
4042 while (NULL != (v = ctl_getitem(in_parms, (void*)&val)) &&
4043 !(EOV & v->flags)) {
4049 if (!strcmp(nonce_text, v->text)) {
4051 pnonce = (*val) ? estrdup(val) : NULL;
4052 } else if (!strcmp(frags_text, v->text)) {
4053 if (1 != sscanf(val, "%hu", &frags))
4055 } else if (!strcmp(limit_text, v->text)) {
4056 if (1 != sscanf(val, "%u", &limit))
4058 } else if (!strcmp(mincount_text, v->text)) {
4059 if (1 != sscanf(val, "%d", &mincount))
4063 } else if (!strcmp(resall_text, v->text)) {
4064 if (1 != sscanf(val, resaxx_fmt, &resall))
4066 } else if (!strcmp(resany_text, v->text)) {
4067 if (1 != sscanf(val, resaxx_fmt, &resany))
4069 } else if (!strcmp(maxlstint_text, v->text)) {
4070 if (1 != sscanf(val, "%u", &maxlstint))
4072 } else if (!strcmp(laddr_text, v->text)) {
4073 if (!decodenetnum(val, &laddr))
4075 lcladr = getinterface(&laddr, 0);
4076 } else if (1 == sscanf(v->text, last_fmt, &si) &&
4077 (size_t)si < COUNTOF(last)) {
4078 if (2 != sscanf(val, "0x%08x.%08x", &ui, &uf))
4082 if (!SOCK_UNSPEC(&addr[si]) && si == priors)
4084 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
4085 (size_t)si < COUNTOF(addr)) {
4086 if (!decodenetnum(val, &addr[si]))
4088 if (last[si].l_ui && last[si].l_uf && si == priors)
4091 DPRINTF(1, ("read_mru_list: invalid key item: '%s' (ignored)\n",
4096 DPRINTF(1, ("read_mru_list: invalid param for '%s': '%s' (bailing)\n",
4103 free_varlist(in_parms);
4106 /* return no responses until the nonce is validated */
4110 nonce_valid = validate_nonce(pnonce, rbufp);
4115 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
4116 frags > MRU_FRAGS_LIMIT) {
4117 ctl_error(CERR_BADVALUE);
4122 * If either frags or limit is not given, use the max.
4124 if (0 != frags && 0 == limit)
4126 else if (0 != limit && 0 == frags)
4127 frags = MRU_FRAGS_LIMIT;
4130 * Find the starting point if one was provided.
4133 for (i = 0; i < (size_t)priors; i++) {
4134 hash = MON_HASH(&addr[i]);
4135 for (mon = mon_hash[hash];
4137 mon = mon->hash_next)
4138 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
4141 if (L_ISEQU(&mon->last, &last[i]))
4147 /* If a starting point was provided... */
4149 /* and none could be found unmodified... */
4151 /* tell ntpq to try again with older entries */
4152 ctl_error(CERR_UNKNOWNVAR);
4155 /* confirm the prior entry used as starting point */
4156 ctl_putts("last.older", &mon->last);
4157 pch = sptoa(&mon->rmtadr);
4158 ctl_putunqstr("addr.older", pch, strlen(pch));
4161 * Move on to the first entry the client doesn't have,
4162 * except in the special case of a limit of one. In
4163 * that case return the starting point entry.
4166 mon = PREV_DLIST(mon_mru_list, mon, mru);
4167 } else { /* start with the oldest */
4168 mon = TAIL_DLIST(mon_mru_list, mru);
4172 * send up to limit= entries in up to frags= datagrams
4175 generate_nonce(rbufp, buf, sizeof(buf));
4176 ctl_putunqstr("nonce", buf, strlen(buf));
4179 mon != NULL && res_frags < frags && count < limit;
4180 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
4182 if (mon->count < mincount)
4184 if (resall && resall != (resall & mon->flags))
4186 if (resany && !(resany & mon->flags))
4188 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
4191 if (lcladr != NULL && mon->lcladr != lcladr)
4194 send_mru_entry(mon, count);
4196 send_random_tag_value(0);
4202 * If this batch completes the MRU list, say so explicitly with
4203 * a now= l_fp timestamp.
4207 send_random_tag_value(count - 1);
4208 ctl_putts("now", &now);
4209 /* if any entries were returned confirm the last */
4210 if (prior_mon != NULL)
4211 ctl_putts("last.newest", &prior_mon->last);
4218 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
4220 * To keep clients honest about not depending on the order of values,
4221 * and thereby avoid being locked into ugly workarounds to maintain
4222 * backward compatibility later as new fields are added to the response,
4223 * the order is random.
4231 const char addr_fmtu[] = "addr.%u";
4232 const char bcast_fmt[] = "bcast.%u";
4233 const char en_fmt[] = "en.%u"; /* enabled */
4234 const char name_fmt[] = "name.%u";
4235 const char flags_fmt[] = "flags.%u";
4236 const char tl_fmt[] = "tl.%u"; /* ttl */
4237 const char mc_fmt[] = "mc.%u"; /* mcast count */
4238 const char rx_fmt[] = "rx.%u";
4239 const char tx_fmt[] = "tx.%u";
4240 const char txerr_fmt[] = "txerr.%u";
4241 const char pc_fmt[] = "pc.%u"; /* peer count */
4242 const char up_fmt[] = "up.%u"; /* uptime */
4244 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4251 remaining = COUNTOF(sent);
4255 while (remaining > 0) {
4256 if (noisebits < 4) {
4257 noise = rand() ^ (rand() << 16);
4260 which = (noise & 0xf) % COUNTOF(sent);
4265 which = (which + 1) % COUNTOF(sent);
4270 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4271 pch = sptoa(&la->sin);
4272 ctl_putunqstr(tag, pch, strlen(pch));
4276 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4277 if (INT_BCASTOPEN & la->flags)
4278 pch = sptoa(&la->bcast);
4281 ctl_putunqstr(tag, pch, strlen(pch));
4285 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4286 ctl_putint(tag, !la->ignore_packets);
4290 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4291 ctl_putstr(tag, la->name, strlen(la->name));
4295 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4296 ctl_puthex(tag, (u_int)la->flags);
4300 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4301 ctl_putint(tag, la->last_ttl);
4305 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4306 ctl_putint(tag, la->num_mcast);
4310 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4311 ctl_putint(tag, la->received);
4315 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4316 ctl_putint(tag, la->sent);
4320 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4321 ctl_putint(tag, la->notsent);
4325 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4326 ctl_putuint(tag, la->peercnt);
4330 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4331 ctl_putuint(tag, current_time - la->starttime);
4337 send_random_tag_value((int)ifnum);
4342 * read_ifstats - send statistics for each local address, exposed by
4347 struct recvbuf * rbufp
4354 * loop over [0..sys_ifnum] searching ep_list for each
4357 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4358 for (la = ep_list; la != NULL; la = la->elink)
4359 if (ifidx == la->ifnum)
4363 /* return stats for one local address */
4364 send_ifstats_entry(la, ifidx);
4370 sockaddrs_from_restrict_u(
4380 psaA->sa.sa_family = AF_INET;
4381 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4382 psaM->sa.sa_family = AF_INET;
4383 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4385 psaA->sa.sa_family = AF_INET6;
4386 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4387 sizeof(psaA->sa6.sin6_addr));
4388 psaM->sa.sa_family = AF_INET6;
4389 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4390 sizeof(psaA->sa6.sin6_addr));
4396 * Send a restrict entry in response to a "ntpq -c reslist" request.
4398 * To keep clients honest about not depending on the order of values,
4399 * and thereby avoid being locked into ugly workarounds to maintain
4400 * backward compatibility later as new fields are added to the response,
4401 * the order is random.
4404 send_restrict_entry(
4410 const char addr_fmtu[] = "addr.%u";
4411 const char mask_fmtu[] = "mask.%u";
4412 const char hits_fmt[] = "hits.%u";
4413 const char flags_fmt[] = "flags.%u";
4415 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4424 const char * match_str;
4425 const char * access_str;
4427 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4428 remaining = COUNTOF(sent);
4432 while (remaining > 0) {
4433 if (noisebits < 2) {
4434 noise = rand() ^ (rand() << 16);
4437 which = (noise & 0x3) % COUNTOF(sent);
4442 which = (which + 1) % COUNTOF(sent);
4444 /* XXX: Numbers? Really? */
4448 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4450 ctl_putunqstr(tag, pch, strlen(pch));
4454 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4456 ctl_putunqstr(tag, pch, strlen(pch));
4460 snprintf(tag, sizeof(tag), hits_fmt, idx);
4461 ctl_putuint(tag, pres->count);
4465 snprintf(tag, sizeof(tag), flags_fmt, idx);
4466 match_str = res_match_flags(pres->mflags);
4467 access_str = res_access_flags(pres->rflags);
4468 if ('\0' == match_str[0]) {
4472 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4473 match_str, access_str);
4476 ctl_putunqstr(tag, pch, strlen(pch));
4482 send_random_tag_value((int)idx);
4493 for ( ; pres != NULL; pres = pres->link) {
4494 send_restrict_entry(pres, ipv6, *pidx);
4501 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4504 read_addr_restrictions(
4505 struct recvbuf * rbufp
4511 send_restrict_list(restrictlist4, FALSE, &idx);
4512 send_restrict_list(restrictlist6, TRUE, &idx);
4518 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4522 struct recvbuf * rbufp,
4526 const char ifstats_s[] = "ifstats";
4527 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4528 const char addr_rst_s[] = "addr_restrictions";
4529 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4530 struct ntp_control * cpkt;
4531 u_short qdata_octets;
4534 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4535 * used only for ntpq -c ifstats. With the addition of reslist
4536 * the same opcode was generalized to retrieve ordered lists
4537 * which require authentication. The request data is empty or
4538 * contains "ifstats" (not null terminated) to retrieve local
4539 * addresses and associated stats. It is "addr_restrictions"
4540 * to retrieve the IPv4 then IPv6 remote address restrictions,
4541 * which are access control lists. Other request data return
4544 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4545 qdata_octets = ntohs(cpkt->count);
4546 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4547 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4548 read_ifstats(rbufp);
4551 if (a_r_chars == qdata_octets &&
4552 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4553 read_addr_restrictions(rbufp);
4556 ctl_error(CERR_UNKNOWNVAR);
4561 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4563 static void req_nonce(
4564 struct recvbuf * rbufp,
4570 generate_nonce(rbufp, buf, sizeof(buf));
4571 ctl_putunqstr("nonce", buf, strlen(buf));
4577 * read_clockstatus - return clock radio status
4582 struct recvbuf *rbufp,
4588 * If no refclock support, no data to return
4590 ctl_error(CERR_BADASSOC);
4592 const struct ctl_var * v;
4600 struct ctl_var * kv;
4601 struct refclockstat cs;
4603 if (res_associd != 0) {
4604 peer = findpeerbyassoc(res_associd);
4607 * Find a clock for this jerk. If the system peer
4608 * is a clock use it, else search peer_list for one.
4610 if (sys_peer != NULL && (FLAG_REFCLOCK &
4614 for (peer = peer_list;
4616 peer = peer->p_link)
4617 if (FLAG_REFCLOCK & peer->flags)
4620 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4621 ctl_error(CERR_BADASSOC);
4625 * If we got here we have a peer which is a clock. Get his
4629 refclock_control(&peer->srcadr, NULL, &cs);
4632 * Look for variables in the packet.
4634 rpkt.status = htons(ctlclkstatus(&cs));
4635 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4636 wants = emalloc_zero(wants_alloc);
4638 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4639 if (!(EOV & v->flags)) {
4640 wants[v->code] = TRUE;
4643 v = ctl_getitem(kv, &valuep);
4645 ctl_error(CERR_BADVALUE);
4647 free_varlist(cs.kv_list);
4650 if (EOV & v->flags) {
4651 ctl_error(CERR_UNKNOWNVAR);
4653 free_varlist(cs.kv_list);
4656 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4662 for (i = 1; i <= CC_MAXCODE; i++)
4664 ctl_putclock(i, &cs, TRUE);
4666 for (i = 0; !(EOV & kv[i].flags); i++)
4667 if (wants[i + CC_MAXCODE + 1])
4668 ctl_putdata(kv[i].text,
4672 for (cc = def_clock_var; *cc != 0; cc++)
4673 ctl_putclock((int)*cc, &cs, FALSE);
4674 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4675 if (DEF & kv->flags)
4676 ctl_putdata(kv->text, strlen(kv->text),
4681 free_varlist(cs.kv_list);
4689 * write_clockstatus - we don't do this
4694 struct recvbuf *rbufp,
4698 ctl_error(CERR_PERMISSION);
4702 * Trap support from here on down. We send async trap messages when the
4703 * upper levels report trouble. Traps can by set either by control
4704 * messages or by configuration.
4707 * set_trap - set a trap in response to a control message
4711 struct recvbuf *rbufp,
4718 * See if this guy is allowed
4720 if (restrict_mask & RES_NOTRAP) {
4721 ctl_error(CERR_PERMISSION);
4726 * Determine his allowed trap type.
4728 traptype = TRAP_TYPE_PRIO;
4729 if (restrict_mask & RES_LPTRAP)
4730 traptype = TRAP_TYPE_NONPRIO;
4733 * Call ctlsettrap() to do the work. Return
4734 * an error if it can't assign the trap.
4736 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4738 ctl_error(CERR_NORESOURCE);
4744 * unset_trap - unset a trap in response to a control message
4748 struct recvbuf *rbufp,
4755 * We don't prevent anyone from removing his own trap unless the
4756 * trap is configured. Note we also must be aware of the
4757 * possibility that restriction flags were changed since this
4758 * guy last set his trap. Set the trap type based on this.
4760 traptype = TRAP_TYPE_PRIO;
4761 if (restrict_mask & RES_LPTRAP)
4762 traptype = TRAP_TYPE_NONPRIO;
4765 * Call ctlclrtrap() to clear this out.
4767 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4768 ctl_error(CERR_BADASSOC);
4774 * ctlsettrap - called to set a trap
4779 struct interface *linter,
4785 struct ctl_trap *tp;
4786 struct ctl_trap *tptouse;
4789 * See if we can find this trap. If so, we only need update
4790 * the flags and the time.
4792 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4795 case TRAP_TYPE_CONFIG:
4796 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4799 case TRAP_TYPE_PRIO:
4800 if (tp->tr_flags & TRAP_CONFIGURED)
4801 return (1); /* don't change anything */
4802 tp->tr_flags = TRAP_INUSE;
4805 case TRAP_TYPE_NONPRIO:
4806 if (tp->tr_flags & TRAP_CONFIGURED)
4807 return (1); /* don't change anything */
4808 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4811 tp->tr_settime = current_time;
4817 * First we heard of this guy. Try to find a trap structure
4818 * for him to use, clearing out lesser priority guys if we
4819 * have to. Clear out anyone who's expired while we're at it.
4822 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4824 if ((TRAP_INUSE & tp->tr_flags) &&
4825 !(TRAP_CONFIGURED & tp->tr_flags) &&
4826 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4830 if (!(TRAP_INUSE & tp->tr_flags)) {
4832 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4835 case TRAP_TYPE_CONFIG:
4836 if (tptouse == NULL) {
4840 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4841 !(TRAP_NONPRIO & tp->tr_flags))
4844 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4845 && (TRAP_NONPRIO & tp->tr_flags)) {
4849 if (tptouse->tr_origtime <
4854 case TRAP_TYPE_PRIO:
4855 if ( TRAP_NONPRIO & tp->tr_flags) {
4856 if (tptouse == NULL ||
4858 tptouse->tr_flags) &&
4859 tptouse->tr_origtime <
4865 case TRAP_TYPE_NONPRIO:
4872 * If we don't have room for him return an error.
4874 if (tptouse == NULL)
4878 * Set up this structure for him.
4880 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4881 tptouse->tr_count = tptouse->tr_resets = 0;
4882 tptouse->tr_sequence = 1;
4883 tptouse->tr_addr = *raddr;
4884 tptouse->tr_localaddr = linter;
4885 tptouse->tr_version = (u_char) version;
4886 tptouse->tr_flags = TRAP_INUSE;
4887 if (traptype == TRAP_TYPE_CONFIG)
4888 tptouse->tr_flags |= TRAP_CONFIGURED;
4889 else if (traptype == TRAP_TYPE_NONPRIO)
4890 tptouse->tr_flags |= TRAP_NONPRIO;
4897 * ctlclrtrap - called to clear a trap
4902 struct interface *linter,
4906 register struct ctl_trap *tp;
4908 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4911 if (tp->tr_flags & TRAP_CONFIGURED
4912 && traptype != TRAP_TYPE_CONFIG)
4922 * ctlfindtrap - find a trap given the remote and local addresses
4924 static struct ctl_trap *
4927 struct interface *linter
4932 for (n = 0; n < COUNTOF(ctl_traps); n++)
4933 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4934 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4935 && (linter == ctl_traps[n].tr_localaddr))
4936 return &ctl_traps[n];
4943 * report_event - report an event to the trappers
4947 int err, /* error code */
4948 struct peer *peer, /* peer structure pointer */
4949 const char *str /* protostats string */
4952 char statstr[NTP_MAXSTRLEN];
4957 * Report the error to the protostats file, system log and
4963 * Discard a system report if the number of reports of
4964 * the same type exceeds the maximum.
4966 if (ctl_sys_last_event != (u_char)err)
4967 ctl_sys_num_events= 0;
4968 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4971 ctl_sys_last_event = (u_char)err;
4972 ctl_sys_num_events++;
4973 snprintf(statstr, sizeof(statstr),
4974 "0.0.0.0 %04x %02x %s",
4975 ctlsysstatus(), err, eventstr(err));
4977 len = strlen(statstr);
4978 snprintf(statstr + len, sizeof(statstr) - len,
4982 msyslog(LOG_INFO, "%s", statstr);
4986 * Discard a peer report if the number of reports of
4987 * the same type exceeds the maximum for that peer.
4992 errlast = (u_char)err & ~PEER_EVENT;
4993 if (peer->last_event != errlast)
4994 peer->num_events = 0;
4995 if (peer->num_events >= CTL_PEER_MAXEVENTS)
4998 peer->last_event = errlast;
5000 if (ISREFCLOCKADR(&peer->srcadr))
5001 src = refnumtoa(&peer->srcadr);
5003 src = stoa(&peer->srcadr);
5005 snprintf(statstr, sizeof(statstr),
5006 "%s %04x %02x %s", src,
5007 ctlpeerstatus(peer), err, eventstr(err));
5009 len = strlen(statstr);
5010 snprintf(statstr + len, sizeof(statstr) - len,
5013 NLOG(NLOG_PEEREVENT)
5014 msyslog(LOG_INFO, "%s", statstr);
5016 record_proto_stats(statstr);
5019 printf("event at %lu %s\n", current_time, statstr);
5023 * If no trappers, return.
5025 if (num_ctl_traps <= 0)
5029 * Peer Events should be associated with a peer -- hence the
5030 * name. But there are instances where this function is called
5031 * *without* a valid peer. This happens e.g. with an unsolicited
5032 * CryptoNAK, or when a leap second alarm is going off while
5033 * currently without a system peer.
5035 * The most sensible approach to this seems to bail out here if
5036 * this happens. Avoiding to call this function would also
5037 * bypass the log reporting in the first part of this function,
5038 * and this is probably not the best of all options.
5039 * -*-perlinger@ntp.org-*-
5041 if ((err & PEER_EVENT) && !peer)
5045 * Set up the outgoing packet variables
5047 res_opcode = CTL_OP_ASYNCMSG;
5050 res_authenticate = FALSE;
5051 datapt = rpkt.u.data;
5052 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
5053 if (!(err & PEER_EVENT)) {
5055 rpkt.status = htons(ctlsysstatus());
5057 /* Include the core system variables and the list. */
5058 for (i = 1; i <= CS_VARLIST; i++)
5060 } else if (NULL != peer) { /* paranoia -- skip output */
5061 rpkt.associd = htons(peer->associd);
5062 rpkt.status = htons(ctlpeerstatus(peer));
5064 /* Dump it all. Later, maybe less. */
5065 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
5066 ctl_putpeer(i, peer);
5069 * for clock exception events: add clock variables to
5070 * reflect info on exception
5072 if (err == PEVNT_CLOCK) {
5073 struct refclockstat cs;
5077 refclock_control(&peer->srcadr, NULL, &cs);
5079 ctl_puthex("refclockstatus",
5082 for (i = 1; i <= CC_MAXCODE; i++)
5083 ctl_putclock(i, &cs, FALSE);
5084 for (kv = cs.kv_list;
5085 kv != NULL && !(EOV & kv->flags);
5087 if (DEF & kv->flags)
5088 ctl_putdata(kv->text,
5091 free_varlist(cs.kv_list);
5093 # endif /* REFCLOCK */
5097 * We're done, return.
5104 * mprintf_event - printf-style varargs variant of report_event()
5108 int evcode, /* event code */
5109 struct peer * p, /* may be NULL */
5110 const char * fmt, /* msnprintf format */
5119 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
5121 report_event(evcode, p, msg);
5128 * ctl_clr_stats - clear stat counters
5133 ctltimereset = current_time;
5136 numctlresponses = 0;
5141 numctlinputresp = 0;
5142 numctlinputfrag = 0;
5144 numctlbadoffset = 0;
5145 numctlbadversion = 0;
5146 numctldatatooshort = 0;
5153 const struct ctl_var *k
5162 while (!(EOV & (k++)->flags))
5165 ENSURE(c <= USHRT_MAX);
5172 struct ctl_var **kv,
5182 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
5184 buf = emalloc(size);
5189 k[c + 1].text = NULL;
5190 k[c + 1].flags = EOV;
5198 struct ctl_var **kv,
5209 if (NULL == data || !size)
5214 while (!(EOV & k->flags)) {
5215 if (NULL == k->text) {
5217 memcpy(td, data, size);
5224 while (*t != '=' && *s == *t) {
5228 if (*s == *t && ((*t == '=') || !*t)) {
5229 td = erealloc((void *)(intptr_t)k->text, size);
5230 memcpy(td, data, size);
5239 td = add_var(kv, size, def);
5240 memcpy(td, data, size);
5251 set_var(&ext_sys_var, data, size, def);
5256 * get_ext_sys_var() retrieves the value of a user-defined variable or
5257 * NULL if the variable has not been setvar'd.
5260 get_ext_sys_var(const char *tag)
5268 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5269 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5270 if ('=' == v->text[c]) {
5271 val = v->text + c + 1;
5273 } else if ('\0' == v->text[c]) {
5291 for (k = kv; !(k->flags & EOV); k++)
5292 free((void *)(intptr_t)k->text);