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 =
1915 1.0e-6; /* nsec to msec */
1917 1.0e-3; /* usec to msec */
1921 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1923 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1924 current_time != ntp_adjtime_time) {
1926 if (ntp_adjtime(&ntx) < 0)
1927 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1929 ntp_adjtime_time = current_time;
1931 #endif /* KERNEL_PLL */
1936 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1940 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1944 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1948 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1952 case CS_ROOTDISPERSION:
1953 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1954 sys_rootdisp * 1e3);
1958 if (REFID_ISTEXT(sys_stratum))
1959 ctl_putrefid(sys_var[varid].text, sys_refid);
1961 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1965 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1969 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
1973 if (sys_peer == NULL)
1974 ctl_putuint(sys_var[CS_PEERID].text, 0);
1976 ctl_putuint(sys_var[CS_PEERID].text,
1981 if (sys_peer != NULL && sys_peer->dstadr != NULL)
1982 ss = sptoa(&sys_peer->srcadr);
1985 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
1989 u = (sys_peer != NULL)
1992 ctl_putuint(sys_var[CS_PEERMODE].text, u);
1996 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
2000 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
2004 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
2008 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
2013 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
2018 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
2019 sizeof(str_processor) - 1);
2021 ctl_putstr(sys_var[CS_PROCESSOR].text,
2022 utsnamebuf.machine, strlen(utsnamebuf.machine));
2023 #endif /* HAVE_UNAME */
2028 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
2029 sizeof(str_system) - 1);
2031 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
2032 utsnamebuf.release);
2033 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
2034 #endif /* HAVE_UNAME */
2038 ctl_putstr(sys_var[CS_VERSION].text, Version,
2043 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
2049 char buf[CTL_MAX_DATA_LEN];
2050 //buffPointer, firstElementPointer, buffEndPointer
2051 char *buffp, *buffend;
2055 const struct ctl_var *k;
2058 buffend = buf + sizeof(buf);
2059 if (strlen(sys_var[CS_VARLIST].text) > (sizeof(buf) - 4))
2060 break; /* really long var name */
2062 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
2063 buffp += strlen(buffp);
2064 firstVarName = TRUE;
2065 for (k = sys_var; !(k->flags & EOV); k++) {
2066 if (k->flags & PADDING)
2068 len = strlen(k->text);
2069 if (len + 1 >= buffend - buffp)
2074 firstVarName = FALSE;
2075 memcpy(buffp, k->text, len);
2079 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
2080 if (k->flags & PADDING)
2082 if (NULL == k->text)
2084 ss1 = strchr(k->text, '=');
2086 len = strlen(k->text);
2088 len = ss1 - k->text;
2089 if (len + 1 >= buffend - buffp)
2093 firstVarName = FALSE;
2095 memcpy(buffp, k->text,(unsigned)len);
2098 if (2 >= buffend - buffp)
2104 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
2110 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
2115 leap_signature_t lsig;
2116 leapsec_getsig(&lsig);
2118 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
2124 leap_signature_t lsig;
2125 leapsec_getsig(&lsig);
2127 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2132 case CS_LEAPSMEARINTV:
2133 if (leap_smear_intv > 0)
2134 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2137 case CS_LEAPSMEAROFFS:
2138 if (leap_smear_intv > 0)
2139 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2140 leap_smear.doffset * 1e3);
2142 #endif /* LEAP_SMEAR */
2145 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2148 case CS_MRU_ENABLED:
2149 ctl_puthex(sys_var[varid].text, mon_enabled);
2153 ctl_putuint(sys_var[varid].text, mru_entries);
2157 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2161 ctl_putuint(sys_var[varid].text, u);
2164 case CS_MRU_DEEPEST:
2165 ctl_putuint(sys_var[varid].text, mru_peakentries);
2168 case CS_MRU_MINDEPTH:
2169 ctl_putuint(sys_var[varid].text, mru_mindepth);
2173 ctl_putint(sys_var[varid].text, mru_maxage);
2176 case CS_MRU_MAXDEPTH:
2177 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2181 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2185 ctl_putuint(sys_var[varid].text, u);
2189 ctl_putuint(sys_var[varid].text, current_time);
2193 ctl_putuint(sys_var[varid].text,
2194 current_time - sys_stattime);
2197 case CS_SS_RECEIVED:
2198 ctl_putuint(sys_var[varid].text, sys_received);
2202 ctl_putuint(sys_var[varid].text, sys_newversion);
2206 ctl_putuint(sys_var[varid].text, sys_oldversion);
2209 case CS_SS_BADFORMAT:
2210 ctl_putuint(sys_var[varid].text, sys_badlength);
2214 ctl_putuint(sys_var[varid].text, sys_badauth);
2217 case CS_SS_DECLINED:
2218 ctl_putuint(sys_var[varid].text, sys_declined);
2221 case CS_SS_RESTRICTED:
2222 ctl_putuint(sys_var[varid].text, sys_restricted);
2226 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2230 ctl_putuint(sys_var[varid].text, sys_lamport);
2233 case CS_SS_TSROUNDING:
2234 ctl_putuint(sys_var[varid].text, sys_tsrounding);
2238 ctl_putuint(sys_var[varid].text, sys_kodsent);
2241 case CS_SS_PROCESSED:
2242 ctl_putuint(sys_var[varid].text, sys_processed);
2246 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2250 LFPTOD(&sys_authdelay, dtemp);
2251 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2255 ctl_putuint(sys_var[varid].text, authnumkeys);
2259 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2262 case CS_AUTHKLOOKUPS:
2263 ctl_putuint(sys_var[varid].text, authkeylookups);
2266 case CS_AUTHKNOTFOUND:
2267 ctl_putuint(sys_var[varid].text, authkeynotfound);
2270 case CS_AUTHKUNCACHED:
2271 ctl_putuint(sys_var[varid].text, authkeyuncached);
2274 case CS_AUTHKEXPIRED:
2275 ctl_putuint(sys_var[varid].text, authkeyexpired);
2278 case CS_AUTHENCRYPTS:
2279 ctl_putuint(sys_var[varid].text, authencryptions);
2282 case CS_AUTHDECRYPTS:
2283 ctl_putuint(sys_var[varid].text, authdecryptions);
2287 ctl_putuint(sys_var[varid].text,
2288 current_time - auth_timereset);
2292 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2293 * unavailable, otherwise calls putfunc with args.
2296 # define CTL_IF_KERNLOOP(putfunc, args) \
2297 ctl_putint(sys_var[varid].text, 0)
2299 # define CTL_IF_KERNLOOP(putfunc, args) \
2304 * CTL_IF_KERNPPS() puts a zero if either the kernel
2305 * loop is unavailable, or kernel hard PPS is not
2306 * active, otherwise calls putfunc with args.
2309 # define CTL_IF_KERNPPS(putfunc, args) \
2310 ctl_putint(sys_var[varid].text, 0)
2312 # define CTL_IF_KERNPPS(putfunc, args) \
2313 if (0 == ntx.shift) \
2314 ctl_putint(sys_var[varid].text, 0); \
2316 putfunc args /* no trailing ; */
2322 (sys_var[varid].text, 0, -1, to_ms * ntx.offset)
2329 (sys_var[varid].text, ntx.freq)
2336 (sys_var[varid].text, 0, 6,
2337 to_ms * ntx.maxerror)
2344 (sys_var[varid].text, 0, 6,
2345 to_ms * ntx.esterror)
2353 ss = k_st_flags(ntx.status);
2355 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2358 case CS_K_TIMECONST:
2361 (sys_var[varid].text, ntx.constant)
2365 case CS_K_PRECISION:
2368 (sys_var[varid].text, 0, 6,
2369 to_ms * ntx.precision)
2376 (sys_var[varid].text, ntx.tolerance)
2383 (sys_var[varid].text, ntx.ppsfreq)
2387 case CS_K_PPS_STABIL:
2390 (sys_var[varid].text, ntx.stabil)
2394 case CS_K_PPS_JITTER:
2397 (sys_var[varid].text, to_ms * ntx.jitter)
2401 case CS_K_PPS_CALIBDUR:
2404 (sys_var[varid].text, 1 << ntx.shift)
2408 case CS_K_PPS_CALIBS:
2411 (sys_var[varid].text, ntx.calcnt)
2415 case CS_K_PPS_CALIBERRS:
2418 (sys_var[varid].text, ntx.errcnt)
2422 case CS_K_PPS_JITEXC:
2425 (sys_var[varid].text, ntx.jitcnt)
2429 case CS_K_PPS_STBEXC:
2432 (sys_var[varid].text, ntx.stbcnt)
2436 case CS_IOSTATS_RESET:
2437 ctl_putuint(sys_var[varid].text,
2438 current_time - io_timereset);
2442 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2446 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2450 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2453 case CS_RBUF_LOWATER:
2454 ctl_putuint(sys_var[varid].text, lowater_additions());
2458 ctl_putuint(sys_var[varid].text, packets_dropped);
2462 ctl_putuint(sys_var[varid].text, packets_ignored);
2465 case CS_IO_RECEIVED:
2466 ctl_putuint(sys_var[varid].text, packets_received);
2470 ctl_putuint(sys_var[varid].text, packets_sent);
2473 case CS_IO_SENDFAILED:
2474 ctl_putuint(sys_var[varid].text, packets_notsent);
2478 ctl_putuint(sys_var[varid].text, handler_calls);
2481 case CS_IO_GOODWAKEUPS:
2482 ctl_putuint(sys_var[varid].text, handler_pkts);
2485 case CS_TIMERSTATS_RESET:
2486 ctl_putuint(sys_var[varid].text,
2487 current_time - timer_timereset);
2490 case CS_TIMER_OVERRUNS:
2491 ctl_putuint(sys_var[varid].text, alarm_overflow);
2495 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2499 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2501 case CS_WANDER_THRESH:
2502 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2507 ctl_puthex(sys_var[CS_FLAGS].text,
2513 strlcpy(str, OBJ_nid2ln(crypto_nid),
2515 ctl_putstr(sys_var[CS_DIGEST].text, str,
2524 dp = EVP_get_digestbynid(crypto_flags >> 16);
2525 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2527 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2533 if (hostval.ptr != NULL)
2534 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2535 strlen(hostval.ptr));
2539 if (sys_ident != NULL)
2540 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2545 for (cp = cinfo; cp != NULL; cp = cp->link) {
2546 snprintf(str, sizeof(str), "%s %s 0x%x",
2547 cp->subject, cp->issuer, cp->flags);
2548 ctl_putstr(sys_var[CS_CERTIF].text, str,
2550 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2555 if (hostval.tstamp != 0)
2556 ctl_putfs(sys_var[CS_PUBLIC].text,
2557 ntohl(hostval.tstamp));
2559 #endif /* AUTOKEY */
2568 * ctl_putpeer - output a peer variable
2576 char buf[CTL_MAX_DATA_LEN];
2581 const struct ctl_var *k;
2586 #endif /* AUTOKEY */
2591 ctl_putuint(peer_var[id].text,
2592 !(FLAG_PREEMPT & p->flags));
2596 ctl_putuint(peer_var[id].text, !(p->keyid));
2600 ctl_putuint(peer_var[id].text,
2601 !!(FLAG_AUTHENTIC & p->flags));
2605 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2609 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2613 if (p->hostname != NULL)
2614 ctl_putstr(peer_var[id].text, p->hostname,
2615 strlen(p->hostname));
2619 ctl_putadr(peer_var[id].text, 0,
2626 ctl_putuint(peer_var[id].text,
2628 ? SRCPORT(&p->dstadr->sin)
2634 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2639 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2643 ctl_putuint(peer_var[id].text, p->throttle);
2647 ctl_putuint(peer_var[id].text, p->leap);
2651 ctl_putuint(peer_var[id].text, p->hmode);
2655 ctl_putuint(peer_var[id].text, p->stratum);
2659 ctl_putuint(peer_var[id].text, p->ppoll);
2663 ctl_putuint(peer_var[id].text, p->hpoll);
2667 ctl_putint(peer_var[id].text, p->precision);
2671 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2674 case CP_ROOTDISPERSION:
2675 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2680 if (p->flags & FLAG_REFCLOCK) {
2681 ctl_putrefid(peer_var[id].text, p->refid);
2685 if (REFID_ISTEXT(p->stratum))
2686 ctl_putrefid(peer_var[id].text, p->refid);
2688 ctl_putadr(peer_var[id].text, p->refid, NULL);
2692 ctl_putts(peer_var[id].text, &p->reftime);
2696 ctl_putts(peer_var[id].text, &p->aorg);
2700 ctl_putts(peer_var[id].text, &p->dst);
2705 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2710 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2714 ctl_puthex(peer_var[id].text, p->reach);
2718 ctl_puthex(peer_var[id].text, p->flash);
2723 if (p->flags & FLAG_REFCLOCK) {
2724 ctl_putuint(peer_var[id].text, p->ttl);
2728 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2729 ctl_putint(peer_var[id].text,
2734 ctl_putuint(peer_var[id].text, p->unreach);
2738 ctl_putuint(peer_var[id].text,
2739 p->nextdate - current_time);
2743 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2747 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2751 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2755 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2759 if (p->keyid > NTP_MAXKEY)
2760 ctl_puthex(peer_var[id].text, p->keyid);
2762 ctl_putuint(peer_var[id].text, p->keyid);
2766 ctl_putarray(peer_var[id].text, p->filter_delay,
2771 ctl_putarray(peer_var[id].text, p->filter_offset,
2776 ctl_putarray(peer_var[id].text, p->filter_disp,
2781 ctl_putuint(peer_var[id].text, p->pmode);
2785 ctl_putuint(peer_var[id].text, p->received);
2789 ctl_putuint(peer_var[id].text, p->sent);
2794 be = buf + sizeof(buf);
2795 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2796 break; /* really long var name */
2798 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2801 for (k = peer_var; !(EOV & k->flags); k++) {
2802 if (PADDING & k->flags)
2804 i = strlen(k->text);
2805 if (s + i + 1 >= be)
2809 memcpy(s, k->text, i);
2815 ctl_putdata(buf, (u_int)(s - buf), 0);
2820 ctl_putuint(peer_var[id].text,
2821 current_time - p->timereceived);
2825 ctl_putuint(peer_var[id].text,
2826 current_time - p->timereachable);
2830 ctl_putuint(peer_var[id].text, p->badauth);
2834 ctl_putuint(peer_var[id].text, p->bogusorg);
2838 ctl_putuint(peer_var[id].text, p->oldpkt);
2842 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2846 ctl_putuint(peer_var[id].text, p->selbroken);
2850 ctl_putuint(peer_var[id].text, p->status);
2855 ctl_puthex(peer_var[id].text, p->crypto);
2860 dp = EVP_get_digestbynid(p->crypto >> 16);
2861 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2862 ctl_putstr(peer_var[id].text, str, strlen(str));
2867 if (p->subject != NULL)
2868 ctl_putstr(peer_var[id].text, p->subject,
2869 strlen(p->subject));
2872 case CP_VALID: /* not used */
2876 if (NULL == (ap = p->recval.ptr))
2879 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2880 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2881 ctl_putfs(peer_var[CP_INITTSP].text,
2882 ntohl(p->recval.tstamp));
2886 if (p->ident != NULL)
2887 ctl_putstr(peer_var[id].text, p->ident,
2892 #endif /* AUTOKEY */
2899 * ctl_putclock - output clock variables
2904 struct refclockstat *pcs,
2908 char buf[CTL_MAX_DATA_LEN];
2912 const struct ctl_var *k;
2917 if (mustput || pcs->clockdesc == NULL
2918 || *(pcs->clockdesc) == '\0') {
2919 ctl_putuint(clock_var[id].text, pcs->type);
2923 ctl_putstr(clock_var[id].text,
2925 (unsigned)pcs->lencode);
2929 ctl_putuint(clock_var[id].text, pcs->polls);
2933 ctl_putuint(clock_var[id].text,
2938 ctl_putuint(clock_var[id].text,
2943 ctl_putuint(clock_var[id].text,
2948 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2949 ctl_putdbl(clock_var[id].text,
2950 pcs->fudgetime1 * 1e3);
2954 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2955 ctl_putdbl(clock_var[id].text,
2956 pcs->fudgetime2 * 1e3);
2960 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2961 ctl_putint(clock_var[id].text,
2966 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) {
2967 if (pcs->fudgeval1 > 1)
2968 ctl_putadr(clock_var[id].text,
2969 pcs->fudgeval2, NULL);
2971 ctl_putrefid(clock_var[id].text,
2977 ctl_putuint(clock_var[id].text, pcs->flags);
2981 if (pcs->clockdesc == NULL ||
2982 *(pcs->clockdesc) == '\0') {
2984 ctl_putstr(clock_var[id].text,
2987 ctl_putstr(clock_var[id].text,
2989 strlen(pcs->clockdesc));
2995 be = buf + sizeof(buf);
2996 if (strlen(clock_var[CC_VARLIST].text) + 4 >
2998 break; /* really long var name */
3000 snprintf(s, sizeof(buf), "%s=\"",
3001 clock_var[CC_VARLIST].text);
3005 for (k = clock_var; !(EOV & k->flags); k++) {
3006 if (PADDING & k->flags)
3009 i = strlen(k->text);
3010 if (s + i + 1 >= be)
3015 memcpy(s, k->text, i);
3019 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
3020 if (PADDING & k->flags)
3027 while (*ss && *ss != '=')
3030 if (s + i + 1 >= be)
3035 memcpy(s, k->text, (unsigned)i);
3044 ctl_putdata(buf, (unsigned)(s - buf), 0);
3053 * ctl_getitem - get the next data item from the incoming packet
3055 static const struct ctl_var *
3057 const struct ctl_var *var_list,
3061 /* [Bug 3008] First check the packet data sanity, then search
3062 * the key. This improves the consistency of result values: If
3063 * the result is NULL once, it will never be EOV again for this
3064 * packet; If it's EOV, it will never be NULL again until the
3065 * variable is found and processed in a given 'var_list'. (That
3066 * is, a result is returned that is neither NULL nor EOV).
3068 static const struct ctl_var eol = { 0, EOV, NULL };
3069 static char buf[128];
3070 static u_long quiet_until;
3071 const struct ctl_var *v;
3076 * Part One: Validate the packet state
3079 /* Delete leading commas and white space */
3080 while (reqpt < reqend && (*reqpt == ',' ||
3081 isspace((unsigned char)*reqpt)))
3083 if (reqpt >= reqend)
3086 /* Scan the string in the packet until we hit comma or
3087 * EoB. Register position of first '=' on the fly. */
3088 for (tp = NULL, cp = reqpt; cp != reqend; ++cp) {
3089 if (*cp == '=' && tp == NULL)
3095 /* Process payload, if any. */
3098 /* eventually strip white space from argument. */
3099 const char *plhead = tp + 1; /* skip the '=' */
3100 const char *pltail = cp;
3103 while (plhead != pltail && isspace((u_char)plhead[0]))
3105 while (plhead != pltail && isspace((u_char)pltail[-1]))
3108 /* check payload size, terminate packet on overflow */
3109 plsize = (size_t)(pltail - plhead);
3110 if (plsize >= sizeof(buf))
3113 /* copy data, NUL terminate, and set result data ptr */
3114 memcpy(buf, plhead, plsize);
3118 /* no payload, current end --> current name termination */
3124 * Now we're sure that the packet data itself is sane. Scan the
3125 * list now. Make sure a NULL list is properly treated by
3126 * returning a synthetic End-Of-Values record. We must not
3127 * return NULL pointers after this point, or the behaviour would
3128 * become inconsistent if called several times with different
3129 * variable lists after an EoV was returned. (Such a behavior
3130 * actually caused Bug 3008.)
3133 if (NULL == var_list)
3136 for (v = var_list; !(EOV & v->flags); ++v)
3137 if (!(PADDING & v->flags)) {
3138 /* Check if the var name matches the buffer. The
3139 * name is bracketed by [reqpt..tp] and not NUL
3140 * terminated, and it contains no '=' char. The
3141 * lookup value IS NUL-terminated but might
3142 * include a '='... We have to look out for
3145 const char *sp1 = reqpt;
3146 const char *sp2 = v->text;
3148 /* [Bug 3412] do not compare past NUL byte in name */
3150 && ('\0' != *sp2) && (*sp1 == *sp2)) {
3154 if (sp1 == tp && (*sp2 == '\0' || *sp2 == '='))
3158 /* See if we have found a valid entry or not. If found, advance
3159 * the request pointer for the next round; if not, clear the
3160 * data pointer so we have no dangling garbage here.
3165 reqpt = cp + (cp != reqend);
3169 /*TODO? somehow indicate this packet was bad, apart from syslog? */
3172 if (quiet_until <= current_time) {
3173 quiet_until = current_time + 300;
3174 msyslog(LOG_WARNING,
3175 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)",
3176 stoa(rmt_addr), SRCPORT(rmt_addr));
3178 reqpt = reqend; /* never again for this packet! */
3184 * control_unspec - response to an unspecified op-code
3189 struct recvbuf *rbufp,
3196 * What is an appropriate response to an unspecified op-code?
3197 * I return no errors and no data, unless a specified assocation
3201 peer = findpeerbyassoc(res_associd);
3203 ctl_error(CERR_BADASSOC);
3206 rpkt.status = htons(ctlpeerstatus(peer));
3208 rpkt.status = htons(ctlsysstatus());
3214 * read_status - return either a list of associd's, or a particular
3220 struct recvbuf *rbufp,
3227 /* a_st holds association ID, status pairs alternating */
3228 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3232 printf("read_status: ID %d\n", res_associd);
3235 * Two choices here. If the specified association ID is
3236 * zero we return all known assocation ID's. Otherwise
3237 * we return a bunch of stuff about the particular peer.
3240 peer = findpeerbyassoc(res_associd);
3242 ctl_error(CERR_BADASSOC);
3245 rpkt.status = htons(ctlpeerstatus(peer));
3247 peer->num_events = 0;
3249 * For now, output everything we know about the
3250 * peer. May be more selective later.
3252 for (cp = def_peer_var; *cp != 0; cp++)
3253 ctl_putpeer((int)*cp, peer);
3258 rpkt.status = htons(ctlsysstatus());
3259 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3260 a_st[n++] = htons(peer->associd);
3261 a_st[n++] = htons(ctlpeerstatus(peer));
3262 /* two entries each loop iteration, so n + 1 */
3263 if (n + 1 >= COUNTOF(a_st)) {
3264 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3270 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3276 * read_peervars - half of read_variables() implementation
3281 const struct ctl_var *v;
3286 u_char wants[CP_MAXCODE + 1];
3290 * Wants info for a particular peer. See if we know
3293 peer = findpeerbyassoc(res_associd);
3295 ctl_error(CERR_BADASSOC);
3298 rpkt.status = htons(ctlpeerstatus(peer));
3300 peer->num_events = 0;
3303 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3304 if (v->flags & EOV) {
3305 ctl_error(CERR_UNKNOWNVAR);
3308 INSIST(v->code < COUNTOF(wants));
3313 for (i = 1; i < COUNTOF(wants); i++)
3315 ctl_putpeer(i, peer);
3317 for (cp = def_peer_var; *cp != 0; cp++)
3318 ctl_putpeer((int)*cp, peer);
3324 * read_sysvars - half of read_variables() implementation
3329 const struct ctl_var *v;
3340 * Wants system variables. Figure out which he wants
3341 * and give them to him.
3343 rpkt.status = htons(ctlsysstatus());
3345 ctl_sys_num_events = 0;
3346 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3347 wants = emalloc_zero(wants_count);
3349 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3350 if (!(EOV & v->flags)) {
3351 INSIST(v->code < wants_count);
3355 v = ctl_getitem(ext_sys_var, &valuep);
3357 ctl_error(CERR_BADVALUE);
3361 if (EOV & v->flags) {
3362 ctl_error(CERR_UNKNOWNVAR);
3366 n = v->code + CS_MAXCODE + 1;
3367 INSIST(n < wants_count);
3373 for (n = 1; n <= CS_MAXCODE; n++)
3376 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3377 if (wants[n + CS_MAXCODE + 1]) {
3378 pch = ext_sys_var[n].text;
3379 ctl_putdata(pch, strlen(pch), 0);
3382 for (cs = def_sys_var; *cs != 0; cs++)
3383 ctl_putsys((int)*cs);
3384 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3385 if (DEF & kv->flags)
3386 ctl_putdata(kv->text, strlen(kv->text),
3395 * read_variables - return the variables the caller asks for
3400 struct recvbuf *rbufp,
3412 * write_variables - write into variables. We only allow leap bit
3418 struct recvbuf *rbufp,
3422 const struct ctl_var *v;
3433 * If he's trying to write into a peer tell him no way
3435 if (res_associd != 0) {
3436 ctl_error(CERR_PERMISSION);
3443 rpkt.status = htons(ctlsysstatus());
3446 * Look through the variables. Dump out at the first sign of
3449 while ((v = ctl_getitem(sys_var, &valuep)) != 0) {
3451 if (v->flags & EOV) {
3452 if ((v = ctl_getitem(ext_sys_var, &valuep)) !=
3454 if (v->flags & EOV) {
3455 ctl_error(CERR_UNKNOWNVAR);
3463 if (!(v->flags & CAN_WRITE)) {
3464 ctl_error(CERR_PERMISSION);
3467 if (!ext_var && (*valuep == '\0' || !atoint(valuep,
3469 ctl_error(CERR_BADFMT);
3472 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) {
3473 ctl_error(CERR_BADVALUE);
3478 octets = strlen(v->text) + strlen(valuep) + 2;
3479 vareqv = emalloc(octets);
3482 while (*t && *t != '=')
3485 memcpy(tt, valuep, 1 + strlen(valuep));
3486 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3489 ctl_error(CERR_UNSPEC); /* really */
3495 * If we got anything, do it. xxx nothing to do ***
3498 if (leapind != ~0 || leapwarn != ~0) {
3499 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3500 ctl_error(CERR_PERMISSION);
3510 * configure() processes ntpq :config/config-from-file, allowing
3511 * generic runtime reconfiguration.
3513 static void configure(
3514 struct recvbuf *rbufp,
3521 /* I haven't yet implemented changes to an existing association.
3522 * Hence check if the association id is 0
3524 if (res_associd != 0) {
3525 ctl_error(CERR_BADVALUE);
3529 if (RES_NOMODIFY & restrict_mask) {
3530 snprintf(remote_config.err_msg,
3531 sizeof(remote_config.err_msg),
3532 "runtime configuration prohibited by restrict ... nomodify");
3533 ctl_putdata(remote_config.err_msg,
3534 strlen(remote_config.err_msg), 0);
3538 "runtime config from %s rejected due to nomodify restriction",
3539 stoa(&rbufp->recv_srcadr));
3544 /* Initialize the remote config buffer */
3545 data_count = remoteconfig_cmdlength(reqpt, reqend);
3547 if (data_count > sizeof(remote_config.buffer) - 2) {
3548 snprintf(remote_config.err_msg,
3549 sizeof(remote_config.err_msg),
3550 "runtime configuration failed: request too long");
3551 ctl_putdata(remote_config.err_msg,
3552 strlen(remote_config.err_msg), 0);
3555 "runtime config from %s rejected: request too long",
3556 stoa(&rbufp->recv_srcadr));
3559 /* Bug 2853 -- check if all characters were acceptable */
3560 if (data_count != (size_t)(reqend - reqpt)) {
3561 snprintf(remote_config.err_msg,
3562 sizeof(remote_config.err_msg),
3563 "runtime configuration failed: request contains an unprintable character");
3564 ctl_putdata(remote_config.err_msg,
3565 strlen(remote_config.err_msg), 0);
3568 "runtime config from %s rejected: request contains an unprintable character: %0x",
3569 stoa(&rbufp->recv_srcadr),
3574 memcpy(remote_config.buffer, reqpt, data_count);
3575 /* The buffer has no trailing linefeed or NUL right now. For
3576 * logging, we do not want a newline, so we do that first after
3577 * adding the necessary NUL byte.
3579 remote_config.buffer[data_count] = '\0';
3580 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3581 remote_config.buffer));
3582 msyslog(LOG_NOTICE, "%s config: %s",
3583 stoa(&rbufp->recv_srcadr),
3584 remote_config.buffer);
3586 /* Now we have to make sure there is a NL/NUL sequence at the
3587 * end of the buffer before we parse it.
3589 remote_config.buffer[data_count++] = '\n';
3590 remote_config.buffer[data_count] = '\0';
3591 remote_config.pos = 0;
3592 remote_config.err_pos = 0;
3593 remote_config.no_errors = 0;
3594 config_remotely(&rbufp->recv_srcadr);
3597 * Check if errors were reported. If not, output 'Config
3598 * Succeeded'. Else output the error count. It would be nice
3599 * to output any parser error messages.
3601 if (0 == remote_config.no_errors) {
3602 retval = snprintf(remote_config.err_msg,
3603 sizeof(remote_config.err_msg),
3604 "Config Succeeded");
3606 remote_config.err_pos += retval;
3609 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3612 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3614 if (remote_config.no_errors > 0)
3615 msyslog(LOG_NOTICE, "%d error in %s config",
3616 remote_config.no_errors,
3617 stoa(&rbufp->recv_srcadr));
3622 * derive_nonce - generate client-address-specific nonce value
3623 * associated with a given timestamp.
3625 static u_int32 derive_nonce(
3631 static u_int32 salt[4];
3632 static u_long last_salt_update;
3634 u_char digest[EVP_MAX_MD_SIZE];
3640 while (!salt[0] || current_time - last_salt_update >= 3600) {
3641 salt[0] = ntp_random();
3642 salt[1] = ntp_random();
3643 salt[2] = ntp_random();
3644 salt[3] = ntp_random();
3645 last_salt_update = current_time;
3648 ctx = EVP_MD_CTX_new();
3649 # if defined(OPENSSL) && defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW)
3650 /* [Bug 3457] set flags and don't kill them again */
3651 EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
3652 EVP_DigestInit_ex(ctx, EVP_get_digestbynid(NID_md5), NULL);
3654 EVP_DigestInit(ctx, EVP_get_digestbynid(NID_md5));
3656 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3657 EVP_DigestUpdate(ctx, &ts_i, sizeof(ts_i));
3658 EVP_DigestUpdate(ctx, &ts_f, sizeof(ts_f));
3660 EVP_DigestUpdate(ctx, &SOCK_ADDR4(addr),
3661 sizeof(SOCK_ADDR4(addr)));
3663 EVP_DigestUpdate(ctx, &SOCK_ADDR6(addr),
3664 sizeof(SOCK_ADDR6(addr)));
3665 EVP_DigestUpdate(ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3666 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3667 EVP_DigestFinal(ctx, d.digest, &len);
3668 EVP_MD_CTX_free(ctx);
3675 * generate_nonce - generate client-address-specific nonce string.
3677 static void generate_nonce(
3678 struct recvbuf * rbufp,
3685 derived = derive_nonce(&rbufp->recv_srcadr,
3686 rbufp->recv_time.l_ui,
3687 rbufp->recv_time.l_uf);
3688 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3689 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3694 * validate_nonce - validate client-address-specific nonce string.
3696 * Returns TRUE if the local calculation of the nonce matches the
3697 * client-provided value and the timestamp is recent enough.
3699 static int validate_nonce(
3700 const char * pnonce,
3701 struct recvbuf * rbufp
3711 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3714 ts.l_ui = (u_int32)ts_i;
3715 ts.l_uf = (u_int32)ts_f;
3716 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3717 get_systime(&now_delta);
3718 L_SUB(&now_delta, &ts);
3720 return (supposed == derived && now_delta.l_ui < 16);
3725 * send_random_tag_value - send a randomly-generated three character
3726 * tag prefix, a '.', an index, a '=' and a
3727 * random integer value.
3729 * To try to force clients to ignore unrecognized tags in mrulist,
3730 * reslist, and ifstats responses, the first and last rows are spiced
3731 * with randomly-generated tag names with correct .# index. Make it
3732 * three characters knowing that none of the currently-used subscripted
3733 * tags have that length, avoiding the need to test for
3737 send_random_tag_value(
3744 noise = rand() ^ (rand() << 16);
3745 buf[0] = 'a' + noise % 26;
3747 buf[1] = 'a' + noise % 26;
3749 buf[2] = 'a' + noise % 26;
3752 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3753 ctl_putuint(buf, noise);
3758 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3760 * To keep clients honest about not depending on the order of values,
3761 * and thereby avoid being locked into ugly workarounds to maintain
3762 * backward compatibility later as new fields are added to the response,
3763 * the order is random.
3771 const char first_fmt[] = "first.%d";
3772 const char ct_fmt[] = "ct.%d";
3773 const char mv_fmt[] = "mv.%d";
3774 const char rs_fmt[] = "rs.%d";
3776 u_char sent[6]; /* 6 tag=value pairs */
3782 remaining = COUNTOF(sent);
3784 noise = (u_int32)(rand() ^ (rand() << 16));
3785 while (remaining > 0) {
3786 which = (noise & 7) % COUNTOF(sent);
3789 which = (which + 1) % COUNTOF(sent);
3794 snprintf(tag, sizeof(tag), addr_fmt, count);
3795 pch = sptoa(&mon->rmtadr);
3796 ctl_putunqstr(tag, pch, strlen(pch));
3800 snprintf(tag, sizeof(tag), last_fmt, count);
3801 ctl_putts(tag, &mon->last);
3805 snprintf(tag, sizeof(tag), first_fmt, count);
3806 ctl_putts(tag, &mon->first);
3810 snprintf(tag, sizeof(tag), ct_fmt, count);
3811 ctl_putint(tag, mon->count);
3815 snprintf(tag, sizeof(tag), mv_fmt, count);
3816 ctl_putuint(tag, mon->vn_mode);
3820 snprintf(tag, sizeof(tag), rs_fmt, count);
3821 ctl_puthex(tag, mon->flags);
3831 * read_mru_list - supports ntpq's mrulist command.
3833 * The challenge here is to match ntpdc's monlist functionality without
3834 * being limited to hundreds of entries returned total, and without
3835 * requiring state on the server. If state were required, ntpq's
3836 * mrulist command would require authentication.
3838 * The approach was suggested by Ry Jones. A finite and variable number
3839 * of entries are retrieved per request, to avoid having responses with
3840 * such large numbers of packets that socket buffers are overflowed and
3841 * packets lost. The entries are retrieved oldest-first, taking into
3842 * account that the MRU list will be changing between each request. We
3843 * can expect to see duplicate entries for addresses updated in the MRU
3844 * list during the fetch operation. In the end, the client can assemble
3845 * a close approximation of the MRU list at the point in time the last
3846 * response was sent by ntpd. The only difference is it may be longer,
3847 * containing some number of oldest entries which have since been
3848 * reclaimed. If necessary, the protocol could be extended to zap those
3849 * from the client snapshot at the end, but so far that doesn't seem
3852 * To accomodate the changing MRU list, the starting point for requests
3853 * after the first request is supplied as a series of last seen
3854 * timestamps and associated addresses, the newest ones the client has
3855 * received. As long as at least one of those entries hasn't been
3856 * bumped to the head of the MRU list, ntpd can pick up at that point.
3857 * Otherwise, the request is failed and it is up to ntpq to back up and
3858 * provide the next newest entry's timestamps and addresses, conceivably
3859 * backing up all the way to the starting point.
3862 * nonce= Regurgitated nonce retrieved by the client
3863 * previously using CTL_OP_REQ_NONCE, demonstrating
3864 * ability to receive traffic sent to its address.
3865 * frags= Limit on datagrams (fragments) in response. Used
3866 * by newer ntpq versions instead of limit= when
3867 * retrieving multiple entries.
3868 * limit= Limit on MRU entries returned. One of frags= or
3869 * limit= must be provided.
3870 * limit=1 is a special case: Instead of fetching
3871 * beginning with the supplied starting point's
3872 * newer neighbor, fetch the supplied entry, and
3873 * in that case the #.last timestamp can be zero.
3874 * This enables fetching a single entry by IP
3875 * address. When limit is not one and frags= is
3876 * provided, the fragment limit controls.
3877 * mincount= (decimal) Return entries with count >= mincount.
3878 * laddr= Return entries associated with the server's IP
3879 * address given. No port specification is needed,
3880 * and any supplied is ignored.
3881 * resall= 0x-prefixed hex restrict bits which must all be
3882 * lit for an MRU entry to be included.
3883 * Has precedence over any resany=.
3884 * resany= 0x-prefixed hex restrict bits, at least one of
3885 * which must be list for an MRU entry to be
3887 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3888 * which client previously received.
3889 * addr.0= text of newest entry's IP address and port,
3890 * IPv6 addresses in bracketed form: [::]:123
3891 * last.1= timestamp of 2nd newest entry client has.
3892 * addr.1= address of 2nd newest entry.
3895 * ntpq provides as many last/addr pairs as will fit in a single request
3896 * packet, except for the first request in a MRU fetch operation.
3898 * The response begins with a new nonce value to be used for any
3899 * followup request. Following the nonce is the next newer entry than
3900 * referred to by last.0 and addr.0, if the "0" entry has not been
3901 * bumped to the front. If it has, the first entry returned will be the
3902 * next entry newer than referred to by last.1 and addr.1, and so on.
3903 * If none of the referenced entries remain unchanged, the request fails
3904 * and ntpq backs up to the next earlier set of entries to resync.
3906 * Except for the first response, the response begins with confirmation
3907 * of the entry that precedes the first additional entry provided:
3909 * last.older= hex l_fp timestamp matching one of the input
3910 * .last timestamps, which entry now precedes the
3911 * response 0. entry in the MRU list.
3912 * addr.older= text of address corresponding to older.last.
3914 * And in any case, a successful response contains sets of values
3915 * comprising entries, with the oldest numbered 0 and incrementing from
3918 * addr.# text of IPv4 or IPv6 address and port
3919 * last.# hex l_fp timestamp of last receipt
3920 * first.# hex l_fp timestamp of first receipt
3921 * ct.# count of packets received
3922 * mv.# mode and version
3923 * rs.# restriction mask (RES_* bits)
3925 * Note the code currently assumes there are no valid three letter
3926 * tags sent with each row, and needs to be adjusted if that changes.
3928 * The client should accept the values in any order, and ignore .#
3929 * values which it does not understand, to allow a smooth path to
3930 * future changes without requiring a new opcode. Clients can rely
3931 * on all *.0 values preceding any *.1 values, that is all values for
3932 * a given index number are together in the response.
3934 * The end of the response list is noted with one or two tag=value
3935 * pairs. Unconditionally:
3937 * now= 0x-prefixed l_fp timestamp at the server marking
3938 * the end of the operation.
3940 * If any entries were returned, now= is followed by:
3942 * last.newest= hex l_fp identical to last.# of the prior
3945 static void read_mru_list(
3946 struct recvbuf *rbufp,
3950 static const char nulltxt[1] = { '\0' };
3951 static const char nonce_text[] = "nonce";
3952 static const char frags_text[] = "frags";
3953 static const char limit_text[] = "limit";
3954 static const char mincount_text[] = "mincount";
3955 static const char resall_text[] = "resall";
3956 static const char resany_text[] = "resany";
3957 static const char maxlstint_text[] = "maxlstint";
3958 static const char laddr_text[] = "laddr";
3959 static const char resaxx_fmt[] = "0x%hx";
3968 struct interface * lcladr;
3973 sockaddr_u addr[COUNTOF(last)];
3975 struct ctl_var * in_parms;
3976 const struct ctl_var * v;
3985 mon_entry * prior_mon;
3988 if (RES_NOMRULIST & restrict_mask) {
3989 ctl_error(CERR_PERMISSION);
3992 "mrulist from %s rejected due to nomrulist restriction",
3993 stoa(&rbufp->recv_srcadr));
3998 * fill in_parms var list with all possible input parameters.
4001 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
4002 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
4003 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
4004 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
4005 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
4006 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
4007 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
4008 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
4009 for (i = 0; i < COUNTOF(last); i++) {
4010 snprintf(buf, sizeof(buf), last_fmt, (int)i);
4011 set_var(&in_parms, buf, strlen(buf) + 1, 0);
4012 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
4013 set_var(&in_parms, buf, strlen(buf) + 1, 0);
4016 /* decode input parms */
4029 /* have to go through '(void*)' to drop 'const' property from pointer.
4030 * ctl_getitem()' needs some cleanup, too.... perlinger@ntp.org
4032 while (NULL != (v = ctl_getitem(in_parms, (void*)&val)) &&
4033 !(EOV & v->flags)) {
4039 if (!strcmp(nonce_text, v->text)) {
4041 pnonce = (*val) ? estrdup(val) : NULL;
4042 } else if (!strcmp(frags_text, v->text)) {
4043 if (1 != sscanf(val, "%hu", &frags))
4045 } else if (!strcmp(limit_text, v->text)) {
4046 if (1 != sscanf(val, "%u", &limit))
4048 } else if (!strcmp(mincount_text, v->text)) {
4049 if (1 != sscanf(val, "%d", &mincount))
4053 } else if (!strcmp(resall_text, v->text)) {
4054 if (1 != sscanf(val, resaxx_fmt, &resall))
4056 } else if (!strcmp(resany_text, v->text)) {
4057 if (1 != sscanf(val, resaxx_fmt, &resany))
4059 } else if (!strcmp(maxlstint_text, v->text)) {
4060 if (1 != sscanf(val, "%u", &maxlstint))
4062 } else if (!strcmp(laddr_text, v->text)) {
4063 if (!decodenetnum(val, &laddr))
4065 lcladr = getinterface(&laddr, 0);
4066 } else if (1 == sscanf(v->text, last_fmt, &si) &&
4067 (size_t)si < COUNTOF(last)) {
4068 if (2 != sscanf(val, "0x%08x.%08x", &ui, &uf))
4072 if (!SOCK_UNSPEC(&addr[si]) && si == priors)
4074 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
4075 (size_t)si < COUNTOF(addr)) {
4076 if (!decodenetnum(val, &addr[si]))
4078 if (last[si].l_ui && last[si].l_uf && si == priors)
4081 DPRINTF(1, ("read_mru_list: invalid key item: '%s' (ignored)\n",
4086 DPRINTF(1, ("read_mru_list: invalid param for '%s': '%s' (bailing)\n",
4093 free_varlist(in_parms);
4096 /* return no responses until the nonce is validated */
4100 nonce_valid = validate_nonce(pnonce, rbufp);
4105 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
4106 frags > MRU_FRAGS_LIMIT) {
4107 ctl_error(CERR_BADVALUE);
4112 * If either frags or limit is not given, use the max.
4114 if (0 != frags && 0 == limit)
4116 else if (0 != limit && 0 == frags)
4117 frags = MRU_FRAGS_LIMIT;
4120 * Find the starting point if one was provided.
4123 for (i = 0; i < (size_t)priors; i++) {
4124 hash = MON_HASH(&addr[i]);
4125 for (mon = mon_hash[hash];
4127 mon = mon->hash_next)
4128 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
4131 if (L_ISEQU(&mon->last, &last[i]))
4137 /* If a starting point was provided... */
4139 /* and none could be found unmodified... */
4141 /* tell ntpq to try again with older entries */
4142 ctl_error(CERR_UNKNOWNVAR);
4145 /* confirm the prior entry used as starting point */
4146 ctl_putts("last.older", &mon->last);
4147 pch = sptoa(&mon->rmtadr);
4148 ctl_putunqstr("addr.older", pch, strlen(pch));
4151 * Move on to the first entry the client doesn't have,
4152 * except in the special case of a limit of one. In
4153 * that case return the starting point entry.
4156 mon = PREV_DLIST(mon_mru_list, mon, mru);
4157 } else { /* start with the oldest */
4158 mon = TAIL_DLIST(mon_mru_list, mru);
4162 * send up to limit= entries in up to frags= datagrams
4165 generate_nonce(rbufp, buf, sizeof(buf));
4166 ctl_putunqstr("nonce", buf, strlen(buf));
4169 mon != NULL && res_frags < frags && count < limit;
4170 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
4172 if (mon->count < mincount)
4174 if (resall && resall != (resall & mon->flags))
4176 if (resany && !(resany & mon->flags))
4178 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
4181 if (lcladr != NULL && mon->lcladr != lcladr)
4184 send_mru_entry(mon, count);
4186 send_random_tag_value(0);
4192 * If this batch completes the MRU list, say so explicitly with
4193 * a now= l_fp timestamp.
4197 send_random_tag_value(count - 1);
4198 ctl_putts("now", &now);
4199 /* if any entries were returned confirm the last */
4200 if (prior_mon != NULL)
4201 ctl_putts("last.newest", &prior_mon->last);
4208 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
4210 * To keep clients honest about not depending on the order of values,
4211 * and thereby avoid being locked into ugly workarounds to maintain
4212 * backward compatibility later as new fields are added to the response,
4213 * the order is random.
4221 const char addr_fmtu[] = "addr.%u";
4222 const char bcast_fmt[] = "bcast.%u";
4223 const char en_fmt[] = "en.%u"; /* enabled */
4224 const char name_fmt[] = "name.%u";
4225 const char flags_fmt[] = "flags.%u";
4226 const char tl_fmt[] = "tl.%u"; /* ttl */
4227 const char mc_fmt[] = "mc.%u"; /* mcast count */
4228 const char rx_fmt[] = "rx.%u";
4229 const char tx_fmt[] = "tx.%u";
4230 const char txerr_fmt[] = "txerr.%u";
4231 const char pc_fmt[] = "pc.%u"; /* peer count */
4232 const char up_fmt[] = "up.%u"; /* uptime */
4234 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4241 remaining = COUNTOF(sent);
4245 while (remaining > 0) {
4246 if (noisebits < 4) {
4247 noise = rand() ^ (rand() << 16);
4250 which = (noise & 0xf) % COUNTOF(sent);
4255 which = (which + 1) % COUNTOF(sent);
4260 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4261 pch = sptoa(&la->sin);
4262 ctl_putunqstr(tag, pch, strlen(pch));
4266 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4267 if (INT_BCASTOPEN & la->flags)
4268 pch = sptoa(&la->bcast);
4271 ctl_putunqstr(tag, pch, strlen(pch));
4275 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4276 ctl_putint(tag, !la->ignore_packets);
4280 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4281 ctl_putstr(tag, la->name, strlen(la->name));
4285 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4286 ctl_puthex(tag, (u_int)la->flags);
4290 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4291 ctl_putint(tag, la->last_ttl);
4295 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4296 ctl_putint(tag, la->num_mcast);
4300 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4301 ctl_putint(tag, la->received);
4305 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4306 ctl_putint(tag, la->sent);
4310 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4311 ctl_putint(tag, la->notsent);
4315 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4316 ctl_putuint(tag, la->peercnt);
4320 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4321 ctl_putuint(tag, current_time - la->starttime);
4327 send_random_tag_value((int)ifnum);
4332 * read_ifstats - send statistics for each local address, exposed by
4337 struct recvbuf * rbufp
4344 * loop over [0..sys_ifnum] searching ep_list for each
4347 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4348 for (la = ep_list; la != NULL; la = la->elink)
4349 if (ifidx == la->ifnum)
4353 /* return stats for one local address */
4354 send_ifstats_entry(la, ifidx);
4360 sockaddrs_from_restrict_u(
4370 psaA->sa.sa_family = AF_INET;
4371 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4372 psaM->sa.sa_family = AF_INET;
4373 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4375 psaA->sa.sa_family = AF_INET6;
4376 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4377 sizeof(psaA->sa6.sin6_addr));
4378 psaM->sa.sa_family = AF_INET6;
4379 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4380 sizeof(psaA->sa6.sin6_addr));
4386 * Send a restrict entry in response to a "ntpq -c reslist" request.
4388 * To keep clients honest about not depending on the order of values,
4389 * and thereby avoid being locked into ugly workarounds to maintain
4390 * backward compatibility later as new fields are added to the response,
4391 * the order is random.
4394 send_restrict_entry(
4400 const char addr_fmtu[] = "addr.%u";
4401 const char mask_fmtu[] = "mask.%u";
4402 const char hits_fmt[] = "hits.%u";
4403 const char flags_fmt[] = "flags.%u";
4405 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4414 const char * match_str;
4415 const char * access_str;
4417 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4418 remaining = COUNTOF(sent);
4422 while (remaining > 0) {
4423 if (noisebits < 2) {
4424 noise = rand() ^ (rand() << 16);
4427 which = (noise & 0x3) % COUNTOF(sent);
4432 which = (which + 1) % COUNTOF(sent);
4434 /* XXX: Numbers? Really? */
4438 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4440 ctl_putunqstr(tag, pch, strlen(pch));
4444 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4446 ctl_putunqstr(tag, pch, strlen(pch));
4450 snprintf(tag, sizeof(tag), hits_fmt, idx);
4451 ctl_putuint(tag, pres->count);
4455 snprintf(tag, sizeof(tag), flags_fmt, idx);
4456 match_str = res_match_flags(pres->mflags);
4457 access_str = res_access_flags(pres->rflags);
4458 if ('\0' == match_str[0]) {
4462 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4463 match_str, access_str);
4466 ctl_putunqstr(tag, pch, strlen(pch));
4472 send_random_tag_value((int)idx);
4483 for ( ; pres != NULL; pres = pres->link) {
4484 send_restrict_entry(pres, ipv6, *pidx);
4491 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4494 read_addr_restrictions(
4495 struct recvbuf * rbufp
4501 send_restrict_list(restrictlist4, FALSE, &idx);
4502 send_restrict_list(restrictlist6, TRUE, &idx);
4508 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4512 struct recvbuf * rbufp,
4516 const char ifstats_s[] = "ifstats";
4517 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4518 const char addr_rst_s[] = "addr_restrictions";
4519 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4520 struct ntp_control * cpkt;
4521 u_short qdata_octets;
4524 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4525 * used only for ntpq -c ifstats. With the addition of reslist
4526 * the same opcode was generalized to retrieve ordered lists
4527 * which require authentication. The request data is empty or
4528 * contains "ifstats" (not null terminated) to retrieve local
4529 * addresses and associated stats. It is "addr_restrictions"
4530 * to retrieve the IPv4 then IPv6 remote address restrictions,
4531 * which are access control lists. Other request data return
4534 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4535 qdata_octets = ntohs(cpkt->count);
4536 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4537 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4538 read_ifstats(rbufp);
4541 if (a_r_chars == qdata_octets &&
4542 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4543 read_addr_restrictions(rbufp);
4546 ctl_error(CERR_UNKNOWNVAR);
4551 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4553 static void req_nonce(
4554 struct recvbuf * rbufp,
4560 generate_nonce(rbufp, buf, sizeof(buf));
4561 ctl_putunqstr("nonce", buf, strlen(buf));
4567 * read_clockstatus - return clock radio status
4572 struct recvbuf *rbufp,
4578 * If no refclock support, no data to return
4580 ctl_error(CERR_BADASSOC);
4582 const struct ctl_var * v;
4590 struct ctl_var * kv;
4591 struct refclockstat cs;
4593 if (res_associd != 0) {
4594 peer = findpeerbyassoc(res_associd);
4597 * Find a clock for this jerk. If the system peer
4598 * is a clock use it, else search peer_list for one.
4600 if (sys_peer != NULL && (FLAG_REFCLOCK &
4604 for (peer = peer_list;
4606 peer = peer->p_link)
4607 if (FLAG_REFCLOCK & peer->flags)
4610 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4611 ctl_error(CERR_BADASSOC);
4615 * If we got here we have a peer which is a clock. Get his
4619 refclock_control(&peer->srcadr, NULL, &cs);
4622 * Look for variables in the packet.
4624 rpkt.status = htons(ctlclkstatus(&cs));
4625 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4626 wants = emalloc_zero(wants_alloc);
4628 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4629 if (!(EOV & v->flags)) {
4630 wants[v->code] = TRUE;
4633 v = ctl_getitem(kv, &valuep);
4635 ctl_error(CERR_BADVALUE);
4637 free_varlist(cs.kv_list);
4640 if (EOV & v->flags) {
4641 ctl_error(CERR_UNKNOWNVAR);
4643 free_varlist(cs.kv_list);
4646 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4652 for (i = 1; i <= CC_MAXCODE; i++)
4654 ctl_putclock(i, &cs, TRUE);
4656 for (i = 0; !(EOV & kv[i].flags); i++)
4657 if (wants[i + CC_MAXCODE + 1])
4658 ctl_putdata(kv[i].text,
4662 for (cc = def_clock_var; *cc != 0; cc++)
4663 ctl_putclock((int)*cc, &cs, FALSE);
4664 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4665 if (DEF & kv->flags)
4666 ctl_putdata(kv->text, strlen(kv->text),
4671 free_varlist(cs.kv_list);
4679 * write_clockstatus - we don't do this
4684 struct recvbuf *rbufp,
4688 ctl_error(CERR_PERMISSION);
4692 * Trap support from here on down. We send async trap messages when the
4693 * upper levels report trouble. Traps can by set either by control
4694 * messages or by configuration.
4697 * set_trap - set a trap in response to a control message
4701 struct recvbuf *rbufp,
4708 * See if this guy is allowed
4710 if (restrict_mask & RES_NOTRAP) {
4711 ctl_error(CERR_PERMISSION);
4716 * Determine his allowed trap type.
4718 traptype = TRAP_TYPE_PRIO;
4719 if (restrict_mask & RES_LPTRAP)
4720 traptype = TRAP_TYPE_NONPRIO;
4723 * Call ctlsettrap() to do the work. Return
4724 * an error if it can't assign the trap.
4726 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4728 ctl_error(CERR_NORESOURCE);
4734 * unset_trap - unset a trap in response to a control message
4738 struct recvbuf *rbufp,
4745 * We don't prevent anyone from removing his own trap unless the
4746 * trap is configured. Note we also must be aware of the
4747 * possibility that restriction flags were changed since this
4748 * guy last set his trap. Set the trap type based on this.
4750 traptype = TRAP_TYPE_PRIO;
4751 if (restrict_mask & RES_LPTRAP)
4752 traptype = TRAP_TYPE_NONPRIO;
4755 * Call ctlclrtrap() to clear this out.
4757 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4758 ctl_error(CERR_BADASSOC);
4764 * ctlsettrap - called to set a trap
4769 struct interface *linter,
4775 struct ctl_trap *tp;
4776 struct ctl_trap *tptouse;
4779 * See if we can find this trap. If so, we only need update
4780 * the flags and the time.
4782 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4785 case TRAP_TYPE_CONFIG:
4786 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4789 case TRAP_TYPE_PRIO:
4790 if (tp->tr_flags & TRAP_CONFIGURED)
4791 return (1); /* don't change anything */
4792 tp->tr_flags = TRAP_INUSE;
4795 case TRAP_TYPE_NONPRIO:
4796 if (tp->tr_flags & TRAP_CONFIGURED)
4797 return (1); /* don't change anything */
4798 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4801 tp->tr_settime = current_time;
4807 * First we heard of this guy. Try to find a trap structure
4808 * for him to use, clearing out lesser priority guys if we
4809 * have to. Clear out anyone who's expired while we're at it.
4812 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4814 if ((TRAP_INUSE & tp->tr_flags) &&
4815 !(TRAP_CONFIGURED & tp->tr_flags) &&
4816 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4820 if (!(TRAP_INUSE & tp->tr_flags)) {
4822 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4825 case TRAP_TYPE_CONFIG:
4826 if (tptouse == NULL) {
4830 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4831 !(TRAP_NONPRIO & tp->tr_flags))
4834 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4835 && (TRAP_NONPRIO & tp->tr_flags)) {
4839 if (tptouse->tr_origtime <
4844 case TRAP_TYPE_PRIO:
4845 if ( TRAP_NONPRIO & tp->tr_flags) {
4846 if (tptouse == NULL ||
4848 tptouse->tr_flags) &&
4849 tptouse->tr_origtime <
4855 case TRAP_TYPE_NONPRIO:
4862 * If we don't have room for him return an error.
4864 if (tptouse == NULL)
4868 * Set up this structure for him.
4870 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4871 tptouse->tr_count = tptouse->tr_resets = 0;
4872 tptouse->tr_sequence = 1;
4873 tptouse->tr_addr = *raddr;
4874 tptouse->tr_localaddr = linter;
4875 tptouse->tr_version = (u_char) version;
4876 tptouse->tr_flags = TRAP_INUSE;
4877 if (traptype == TRAP_TYPE_CONFIG)
4878 tptouse->tr_flags |= TRAP_CONFIGURED;
4879 else if (traptype == TRAP_TYPE_NONPRIO)
4880 tptouse->tr_flags |= TRAP_NONPRIO;
4887 * ctlclrtrap - called to clear a trap
4892 struct interface *linter,
4896 register struct ctl_trap *tp;
4898 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4901 if (tp->tr_flags & TRAP_CONFIGURED
4902 && traptype != TRAP_TYPE_CONFIG)
4912 * ctlfindtrap - find a trap given the remote and local addresses
4914 static struct ctl_trap *
4917 struct interface *linter
4922 for (n = 0; n < COUNTOF(ctl_traps); n++)
4923 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4924 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4925 && (linter == ctl_traps[n].tr_localaddr))
4926 return &ctl_traps[n];
4933 * report_event - report an event to the trappers
4937 int err, /* error code */
4938 struct peer *peer, /* peer structure pointer */
4939 const char *str /* protostats string */
4942 char statstr[NTP_MAXSTRLEN];
4947 * Report the error to the protostats file, system log and
4953 * Discard a system report if the number of reports of
4954 * the same type exceeds the maximum.
4956 if (ctl_sys_last_event != (u_char)err)
4957 ctl_sys_num_events= 0;
4958 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4961 ctl_sys_last_event = (u_char)err;
4962 ctl_sys_num_events++;
4963 snprintf(statstr, sizeof(statstr),
4964 "0.0.0.0 %04x %02x %s",
4965 ctlsysstatus(), err, eventstr(err));
4967 len = strlen(statstr);
4968 snprintf(statstr + len, sizeof(statstr) - len,
4972 msyslog(LOG_INFO, "%s", statstr);
4976 * Discard a peer report if the number of reports of
4977 * the same type exceeds the maximum for that peer.
4982 errlast = (u_char)err & ~PEER_EVENT;
4983 if (peer->last_event != errlast)
4984 peer->num_events = 0;
4985 if (peer->num_events >= CTL_PEER_MAXEVENTS)
4988 peer->last_event = errlast;
4990 if (ISREFCLOCKADR(&peer->srcadr))
4991 src = refnumtoa(&peer->srcadr);
4993 src = stoa(&peer->srcadr);
4995 snprintf(statstr, sizeof(statstr),
4996 "%s %04x %02x %s", src,
4997 ctlpeerstatus(peer), err, eventstr(err));
4999 len = strlen(statstr);
5000 snprintf(statstr + len, sizeof(statstr) - len,
5003 NLOG(NLOG_PEEREVENT)
5004 msyslog(LOG_INFO, "%s", statstr);
5006 record_proto_stats(statstr);
5009 printf("event at %lu %s\n", current_time, statstr);
5013 * If no trappers, return.
5015 if (num_ctl_traps <= 0)
5019 * Peer Events should be associated with a peer -- hence the
5020 * name. But there are instances where this function is called
5021 * *without* a valid peer. This happens e.g. with an unsolicited
5022 * CryptoNAK, or when a leap second alarm is going off while
5023 * currently without a system peer.
5025 * The most sensible approach to this seems to bail out here if
5026 * this happens. Avoiding to call this function would also
5027 * bypass the log reporting in the first part of this function,
5028 * and this is probably not the best of all options.
5029 * -*-perlinger@ntp.org-*-
5031 if ((err & PEER_EVENT) && !peer)
5035 * Set up the outgoing packet variables
5037 res_opcode = CTL_OP_ASYNCMSG;
5040 res_authenticate = FALSE;
5041 datapt = rpkt.u.data;
5042 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
5043 if (!(err & PEER_EVENT)) {
5045 rpkt.status = htons(ctlsysstatus());
5047 /* Include the core system variables and the list. */
5048 for (i = 1; i <= CS_VARLIST; i++)
5050 } else if (NULL != peer) { /* paranoia -- skip output */
5051 rpkt.associd = htons(peer->associd);
5052 rpkt.status = htons(ctlpeerstatus(peer));
5054 /* Dump it all. Later, maybe less. */
5055 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
5056 ctl_putpeer(i, peer);
5059 * for clock exception events: add clock variables to
5060 * reflect info on exception
5062 if (err == PEVNT_CLOCK) {
5063 struct refclockstat cs;
5067 refclock_control(&peer->srcadr, NULL, &cs);
5069 ctl_puthex("refclockstatus",
5072 for (i = 1; i <= CC_MAXCODE; i++)
5073 ctl_putclock(i, &cs, FALSE);
5074 for (kv = cs.kv_list;
5075 kv != NULL && !(EOV & kv->flags);
5077 if (DEF & kv->flags)
5078 ctl_putdata(kv->text,
5081 free_varlist(cs.kv_list);
5083 # endif /* REFCLOCK */
5087 * We're done, return.
5094 * mprintf_event - printf-style varargs variant of report_event()
5098 int evcode, /* event code */
5099 struct peer * p, /* may be NULL */
5100 const char * fmt, /* msnprintf format */
5109 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
5111 report_event(evcode, p, msg);
5118 * ctl_clr_stats - clear stat counters
5123 ctltimereset = current_time;
5126 numctlresponses = 0;
5131 numctlinputresp = 0;
5132 numctlinputfrag = 0;
5134 numctlbadoffset = 0;
5135 numctlbadversion = 0;
5136 numctldatatooshort = 0;
5143 const struct ctl_var *k
5152 while (!(EOV & (k++)->flags))
5155 ENSURE(c <= USHRT_MAX);
5162 struct ctl_var **kv,
5172 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
5174 buf = emalloc(size);
5179 k[c + 1].text = NULL;
5180 k[c + 1].flags = EOV;
5188 struct ctl_var **kv,
5199 if (NULL == data || !size)
5204 while (!(EOV & k->flags)) {
5205 if (NULL == k->text) {
5207 memcpy(td, data, size);
5214 while (*t != '=' && *s == *t) {
5218 if (*s == *t && ((*t == '=') || !*t)) {
5219 td = erealloc((void *)(intptr_t)k->text, size);
5220 memcpy(td, data, size);
5229 td = add_var(kv, size, def);
5230 memcpy(td, data, size);
5241 set_var(&ext_sys_var, data, size, def);
5246 * get_ext_sys_var() retrieves the value of a user-defined variable or
5247 * NULL if the variable has not been setvar'd.
5250 get_ext_sys_var(const char *tag)
5258 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5259 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5260 if ('=' == v->text[c]) {
5261 val = v->text + c + 1;
5263 } else if ('\0' == v->text[c]) {
5281 for (k = kv; !(k->flags & EOV); k++)
5282 free((void *)(intptr_t)k->text);