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"
33 #include <rc_cmdlength.h>
35 # include "ntp_syscall.h"
39 * Structure to hold request procedure information
43 short control_code; /* defined request code */
44 #define NO_REQUEST (-1)
45 u_short flags; /* flags word */
46 /* Only one flag. Authentication required or not. */
49 void (*handler) (struct recvbuf *, int); /* handle request */
54 * Request processing routines
56 static void ctl_error (u_char);
58 static u_short ctlclkstatus (struct refclockstat *);
60 static void ctl_flushpkt (u_char);
61 static void ctl_putdata (const char *, unsigned int, int);
62 static void ctl_putstr (const char *, const char *, size_t);
63 static void ctl_putdblf (const char *, int, int, double);
64 #define ctl_putdbl(tag, d) ctl_putdblf(tag, 1, 3, d)
65 #define ctl_putdbl6(tag, d) ctl_putdblf(tag, 1, 6, d)
66 #define ctl_putsfp(tag, sfp) ctl_putdblf(tag, 0, -1, \
68 static void ctl_putuint (const char *, u_long);
69 static void ctl_puthex (const char *, u_long);
70 static void ctl_putint (const char *, long);
71 static void ctl_putts (const char *, l_fp *);
72 static void ctl_putadr (const char *, u_int32,
74 static void ctl_putrefid (const char *, u_int32);
75 static void ctl_putarray (const char *, double *, int);
76 static void ctl_putsys (int);
77 static void ctl_putpeer (int, struct peer *);
78 static void ctl_putfs (const char *, tstamp_t);
79 static void ctl_printf (const char *, ...) NTP_PRINTF(1, 2);
81 static void ctl_putclock (int, struct refclockstat *, int);
83 static const struct ctl_var *ctl_getitem(const struct ctl_var *,
85 static u_short count_var (const struct ctl_var *);
86 static void control_unspec (struct recvbuf *, int);
87 static void read_status (struct recvbuf *, int);
88 static void read_sysvars (void);
89 static void read_peervars (void);
90 static void read_variables (struct recvbuf *, int);
91 static void write_variables (struct recvbuf *, int);
92 static void read_clockstatus(struct recvbuf *, int);
93 static void write_clockstatus(struct recvbuf *, int);
94 static void set_trap (struct recvbuf *, int);
95 static void save_config (struct recvbuf *, int);
96 static void configure (struct recvbuf *, int);
97 static void send_mru_entry (mon_entry *, int);
98 static void send_random_tag_value(int);
99 static void read_mru_list (struct recvbuf *, int);
100 static void send_ifstats_entry(endpt *, u_int);
101 static void read_ifstats (struct recvbuf *);
102 static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *,
104 static void send_restrict_entry(restrict_u *, int, u_int);
105 static void send_restrict_list(restrict_u *, int, u_int *);
106 static void read_addr_restrictions(struct recvbuf *);
107 static void read_ordlist (struct recvbuf *, int);
108 static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32);
109 static void generate_nonce (struct recvbuf *, char *, size_t);
110 static int validate_nonce (const char *, struct recvbuf *);
111 static void req_nonce (struct recvbuf *, int);
112 static void unset_trap (struct recvbuf *, int);
113 static struct ctl_trap *ctlfindtrap(sockaddr_u *,
116 int/*BOOL*/ is_safe_filename(const char * name);
118 static const struct ctl_proc control_codes[] = {
119 { CTL_OP_UNSPEC, NOAUTH, control_unspec },
120 { CTL_OP_READSTAT, NOAUTH, read_status },
121 { CTL_OP_READVAR, NOAUTH, read_variables },
122 { CTL_OP_WRITEVAR, AUTH, write_variables },
123 { CTL_OP_READCLOCK, NOAUTH, read_clockstatus },
124 { CTL_OP_WRITECLOCK, AUTH, write_clockstatus },
125 { CTL_OP_SETTRAP, AUTH, set_trap },
126 { CTL_OP_CONFIGURE, AUTH, configure },
127 { CTL_OP_SAVECONFIG, AUTH, save_config },
128 { CTL_OP_READ_MRU, NOAUTH, read_mru_list },
129 { CTL_OP_READ_ORDLIST_A, AUTH, read_ordlist },
130 { CTL_OP_REQ_NONCE, NOAUTH, req_nonce },
131 { CTL_OP_UNSETTRAP, AUTH, unset_trap },
132 { NO_REQUEST, 0, NULL }
136 * System variables we understand
140 #define CS_PRECISION 3
141 #define CS_ROOTDELAY 4
142 #define CS_ROOTDISPERSION 5
152 #define CS_PROCESSOR 15
154 #define CS_VERSION 17
156 #define CS_VARLIST 19
158 #define CS_LEAPTAB 21
159 #define CS_LEAPEND 22
161 #define CS_MRU_ENABLED 24
162 #define CS_MRU_DEPTH 25
163 #define CS_MRU_DEEPEST 26
164 #define CS_MRU_MINDEPTH 27
165 #define CS_MRU_MAXAGE 28
166 #define CS_MRU_MAXDEPTH 29
167 #define CS_MRU_MEM 30
168 #define CS_MRU_MAXMEM 31
169 #define CS_SS_UPTIME 32
170 #define CS_SS_RESET 33
171 #define CS_SS_RECEIVED 34
172 #define CS_SS_THISVER 35
173 #define CS_SS_OLDVER 36
174 #define CS_SS_BADFORMAT 37
175 #define CS_SS_BADAUTH 38
176 #define CS_SS_DECLINED 39
177 #define CS_SS_RESTRICTED 40
178 #define CS_SS_LIMITED 41
179 #define CS_SS_KODSENT 42
180 #define CS_SS_PROCESSED 43
181 #define CS_SS_LAMPORT 44
182 #define CS_SS_TSROUNDING 45
183 #define CS_PEERADR 46
184 #define CS_PEERMODE 47
185 #define CS_BCASTDELAY 48
186 #define CS_AUTHDELAY 49
187 #define CS_AUTHKEYS 50
188 #define CS_AUTHFREEK 51
189 #define CS_AUTHKLOOKUPS 52
190 #define CS_AUTHKNOTFOUND 53
191 #define CS_AUTHKUNCACHED 54
192 #define CS_AUTHKEXPIRED 55
193 #define CS_AUTHENCRYPTS 56
194 #define CS_AUTHDECRYPTS 57
195 #define CS_AUTHRESET 58
196 #define CS_K_OFFSET 59
198 #define CS_K_MAXERR 61
199 #define CS_K_ESTERR 62
200 #define CS_K_STFLAGS 63
201 #define CS_K_TIMECONST 64
202 #define CS_K_PRECISION 65
203 #define CS_K_FREQTOL 66
204 #define CS_K_PPS_FREQ 67
205 #define CS_K_PPS_STABIL 68
206 #define CS_K_PPS_JITTER 69
207 #define CS_K_PPS_CALIBDUR 70
208 #define CS_K_PPS_CALIBS 71
209 #define CS_K_PPS_CALIBERRS 72
210 #define CS_K_PPS_JITEXC 73
211 #define CS_K_PPS_STBEXC 74
212 #define CS_KERN_FIRST CS_K_OFFSET
213 #define CS_KERN_LAST CS_K_PPS_STBEXC
214 #define CS_IOSTATS_RESET 75
215 #define CS_TOTAL_RBUF 76
216 #define CS_FREE_RBUF 77
217 #define CS_USED_RBUF 78
218 #define CS_RBUF_LOWATER 79
219 #define CS_IO_DROPPED 80
220 #define CS_IO_IGNORED 81
221 #define CS_IO_RECEIVED 82
222 #define CS_IO_SENT 83
223 #define CS_IO_SENDFAILED 84
224 #define CS_IO_WAKEUPS 85
225 #define CS_IO_GOODWAKEUPS 86
226 #define CS_TIMERSTATS_RESET 87
227 #define CS_TIMER_OVERRUNS 88
228 #define CS_TIMER_XMTS 89
230 #define CS_WANDER_THRESH 91
231 #define CS_LEAPSMEARINTV 92
232 #define CS_LEAPSMEAROFFS 93
233 #define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS
235 #define CS_FLAGS (1 + CS_MAX_NOAUTOKEY)
236 #define CS_HOST (2 + CS_MAX_NOAUTOKEY)
237 #define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY)
238 #define CS_CERTIF (4 + CS_MAX_NOAUTOKEY)
239 #define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY)
240 #define CS_REVTIME (6 + CS_MAX_NOAUTOKEY)
241 #define CS_IDENT (7 + CS_MAX_NOAUTOKEY)
242 #define CS_DIGEST (8 + CS_MAX_NOAUTOKEY)
243 #define CS_MAXCODE CS_DIGEST
244 #else /* !AUTOKEY follows */
245 #define CS_MAXCODE CS_MAX_NOAUTOKEY
246 #endif /* !AUTOKEY */
249 * Peer variables we understand
252 #define CP_AUTHENABLE 2
253 #define CP_AUTHENTIC 3
260 #define CP_STRATUM 10
263 #define CP_PRECISION 13
264 #define CP_ROOTDELAY 14
265 #define CP_ROOTDISPERSION 15
267 #define CP_REFTIME 17
272 #define CP_UNREACH 22
277 #define CP_DISPERSION 27
279 #define CP_FILTDELAY 29
280 #define CP_FILTOFFSET 30
282 #define CP_RECEIVED 32
284 #define CP_FILTERROR 34
287 #define CP_VARLIST 37
292 #define CP_SRCHOST 42
293 #define CP_TIMEREC 43
294 #define CP_TIMEREACH 44
295 #define CP_BADAUTH 45
296 #define CP_BOGUSORG 46
298 #define CP_SELDISP 48
299 #define CP_SELBROKEN 49
300 #define CP_CANDIDATE 50
301 #define CP_MAX_NOAUTOKEY CP_CANDIDATE
303 #define CP_FLAGS (1 + CP_MAX_NOAUTOKEY)
304 #define CP_HOST (2 + CP_MAX_NOAUTOKEY)
305 #define CP_VALID (3 + CP_MAX_NOAUTOKEY)
306 #define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY)
307 #define CP_INITKEY (5 + CP_MAX_NOAUTOKEY)
308 #define CP_INITTSP (6 + CP_MAX_NOAUTOKEY)
309 #define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY)
310 #define CP_IDENT (8 + CP_MAX_NOAUTOKEY)
311 #define CP_MAXCODE CP_IDENT
312 #else /* !AUTOKEY follows */
313 #define CP_MAXCODE CP_MAX_NOAUTOKEY
314 #endif /* !AUTOKEY */
317 * Clock variables we understand
320 #define CC_TIMECODE 2
323 #define CC_BADFORMAT 5
325 #define CC_FUDGETIME1 7
326 #define CC_FUDGETIME2 8
327 #define CC_FUDGEVAL1 9
328 #define CC_FUDGEVAL2 10
331 #define CC_VARLIST 13
332 #define CC_FUDGEMINJIT 14
333 #define CC_MAXCODE CC_FUDGEMINJIT
336 * System variable values. The array can be indexed by the variable
337 * index to find the textual name.
339 static const struct ctl_var sys_var[] = {
340 { 0, PADDING, "" }, /* 0 */
341 { CS_LEAP, RW, "leap" }, /* 1 */
342 { CS_STRATUM, RO, "stratum" }, /* 2 */
343 { CS_PRECISION, RO, "precision" }, /* 3 */
344 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */
345 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */
346 { CS_REFID, RO, "refid" }, /* 6 */
347 { CS_REFTIME, RO, "reftime" }, /* 7 */
348 { CS_POLL, RO, "tc" }, /* 8 */
349 { CS_PEERID, RO, "peer" }, /* 9 */
350 { CS_OFFSET, RO, "offset" }, /* 10 */
351 { CS_DRIFT, RO, "frequency" }, /* 11 */
352 { CS_JITTER, RO, "sys_jitter" }, /* 12 */
353 { CS_ERROR, RO, "clk_jitter" }, /* 13 */
354 { CS_CLOCK, RO, "clock" }, /* 14 */
355 { CS_PROCESSOR, RO, "processor" }, /* 15 */
356 { CS_SYSTEM, RO, "system" }, /* 16 */
357 { CS_VERSION, RO, "version" }, /* 17 */
358 { CS_STABIL, RO, "clk_wander" }, /* 18 */
359 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */
360 { CS_TAI, RO, "tai" }, /* 20 */
361 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */
362 { CS_LEAPEND, RO, "expire" }, /* 22 */
363 { CS_RATE, RO, "mintc" }, /* 23 */
364 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */
365 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */
366 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */
367 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */
368 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */
369 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */
370 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */
371 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */
372 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */
373 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */
374 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */
375 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */
376 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */
377 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */
378 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */
379 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */
380 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */
381 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */
382 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */
383 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */
384 { CS_SS_LAMPORT, RO, "ss_lamport" }, /* 44 */
385 { CS_SS_TSROUNDING, RO, "ss_tsrounding" }, /* 45 */
386 { CS_PEERADR, RO, "peeradr" }, /* 46 */
387 { CS_PEERMODE, RO, "peermode" }, /* 47 */
388 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 48 */
389 { CS_AUTHDELAY, RO, "authdelay" }, /* 49 */
390 { CS_AUTHKEYS, RO, "authkeys" }, /* 50 */
391 { CS_AUTHFREEK, RO, "authfreek" }, /* 51 */
392 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 52 */
393 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 53 */
394 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 54 */
395 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 55 */
396 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 56 */
397 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 57 */
398 { CS_AUTHRESET, RO, "authreset" }, /* 58 */
399 { CS_K_OFFSET, RO, "koffset" }, /* 59 */
400 { CS_K_FREQ, RO, "kfreq" }, /* 60 */
401 { CS_K_MAXERR, RO, "kmaxerr" }, /* 61 */
402 { CS_K_ESTERR, RO, "kesterr" }, /* 62 */
403 { CS_K_STFLAGS, RO, "kstflags" }, /* 63 */
404 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 64 */
405 { CS_K_PRECISION, RO, "kprecis" }, /* 65 */
406 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 66 */
407 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 67 */
408 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 68 */
409 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 69 */
410 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 70 */
411 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 71 */
412 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 72 */
413 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 73 */
414 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 74 */
415 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 75 */
416 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 76 */
417 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 77 */
418 { CS_USED_RBUF, RO, "used_rbuf" }, /* 78 */
419 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 79 */
420 { CS_IO_DROPPED, RO, "io_dropped" }, /* 80 */
421 { CS_IO_IGNORED, RO, "io_ignored" }, /* 81 */
422 { CS_IO_RECEIVED, RO, "io_received" }, /* 82 */
423 { CS_IO_SENT, RO, "io_sent" }, /* 83 */
424 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 84 */
425 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 85 */
426 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 86 */
427 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 87 */
428 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 88 */
429 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 89 */
430 { CS_FUZZ, RO, "fuzz" }, /* 90 */
431 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 91 */
433 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 92 */
434 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 93 */
437 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */
438 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */
439 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */
440 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */
441 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */
442 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */
443 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */
444 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */
446 { 0, EOV, "" } /* 94/102 */
449 static struct ctl_var *ext_sys_var = NULL;
452 * System variables we print by default (in fuzzball order,
455 static const u_char def_sys_var[] = {
496 static const struct ctl_var peer_var[] = {
497 { 0, PADDING, "" }, /* 0 */
498 { CP_CONFIG, RO, "config" }, /* 1 */
499 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */
500 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */
501 { CP_SRCADR, RO, "srcadr" }, /* 4 */
502 { CP_SRCPORT, RO, "srcport" }, /* 5 */
503 { CP_DSTADR, RO, "dstadr" }, /* 6 */
504 { CP_DSTPORT, RO, "dstport" }, /* 7 */
505 { CP_LEAP, RO, "leap" }, /* 8 */
506 { CP_HMODE, RO, "hmode" }, /* 9 */
507 { CP_STRATUM, RO, "stratum" }, /* 10 */
508 { CP_PPOLL, RO, "ppoll" }, /* 11 */
509 { CP_HPOLL, RO, "hpoll" }, /* 12 */
510 { CP_PRECISION, RO, "precision" }, /* 13 */
511 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */
512 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */
513 { CP_REFID, RO, "refid" }, /* 16 */
514 { CP_REFTIME, RO, "reftime" }, /* 17 */
515 { CP_ORG, RO, "org" }, /* 18 */
516 { CP_REC, RO, "rec" }, /* 19 */
517 { CP_XMT, RO, "xleave" }, /* 20 */
518 { CP_REACH, RO, "reach" }, /* 21 */
519 { CP_UNREACH, RO, "unreach" }, /* 22 */
520 { CP_TIMER, RO, "timer" }, /* 23 */
521 { CP_DELAY, RO, "delay" }, /* 24 */
522 { CP_OFFSET, RO, "offset" }, /* 25 */
523 { CP_JITTER, RO, "jitter" }, /* 26 */
524 { CP_DISPERSION, RO, "dispersion" }, /* 27 */
525 { CP_KEYID, RO, "keyid" }, /* 28 */
526 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */
527 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */
528 { CP_PMODE, RO, "pmode" }, /* 31 */
529 { CP_RECEIVED, RO, "received"}, /* 32 */
530 { CP_SENT, RO, "sent" }, /* 33 */
531 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */
532 { CP_FLASH, RO, "flash" }, /* 35 */
533 { CP_TTL, RO, "ttl" }, /* 36 */
534 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */
535 { CP_IN, RO, "in" }, /* 38 */
536 { CP_OUT, RO, "out" }, /* 39 */
537 { CP_RATE, RO, "headway" }, /* 40 */
538 { CP_BIAS, RO, "bias" }, /* 41 */
539 { CP_SRCHOST, RO, "srchost" }, /* 42 */
540 { CP_TIMEREC, RO, "timerec" }, /* 43 */
541 { CP_TIMEREACH, RO, "timereach" }, /* 44 */
542 { CP_BADAUTH, RO, "badauth" }, /* 45 */
543 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */
544 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */
545 { CP_SELDISP, RO, "seldisp" }, /* 48 */
546 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */
547 { CP_CANDIDATE, RO, "candidate" }, /* 50 */
549 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */
550 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */
551 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */
552 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */
553 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */
554 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */
555 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */
556 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */
558 { 0, EOV, "" } /* 50/58 */
563 * Peer variables we print by default
565 static const u_char def_peer_var[] = {
614 * Clock variable list
616 static const struct ctl_var clock_var[] = {
617 { 0, PADDING, "" }, /* 0 */
618 { CC_TYPE, RO, "type" }, /* 1 */
619 { CC_TIMECODE, RO, "timecode" }, /* 2 */
620 { CC_POLL, RO, "poll" }, /* 3 */
621 { CC_NOREPLY, RO, "noreply" }, /* 4 */
622 { CC_BADFORMAT, RO, "badformat" }, /* 5 */
623 { CC_BADDATA, RO, "baddata" }, /* 6 */
624 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */
625 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */
626 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */
627 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */
628 { CC_FLAGS, RO, "flags" }, /* 11 */
629 { CC_DEVICE, RO, "device" }, /* 12 */
630 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */
631 { CC_FUDGEMINJIT, RO, "minjitter" }, /* 14 */
632 { 0, EOV, "" } /* 15 */
637 * Clock variables printed by default
639 static const u_char def_clock_var[] = {
641 CC_TYPE, /* won't be output if device = known */
658 * MRU string constants shared by send_mru_entry() and read_mru_list().
660 static const char addr_fmt[] = "addr.%d";
661 static const char last_fmt[] = "last.%d";
664 * System and processor definitions.
668 # define STR_SYSTEM "UNIX"
670 # ifndef STR_PROCESSOR
671 # define STR_PROCESSOR "unknown"
674 static const char str_system[] = STR_SYSTEM;
675 static const char str_processor[] = STR_PROCESSOR;
677 # include <sys/utsname.h>
678 static struct utsname utsnamebuf;
679 #endif /* HAVE_UNAME */
682 * Trap structures. We only allow a few of these, and send a copy of
683 * each async message to each live one. Traps time out after an hour, it
684 * is up to the trap receipient to keep resetting it to avoid being
688 struct ctl_trap ctl_traps[CTL_MAXTRAPS];
692 * Type bits, for ctlsettrap() call.
694 #define TRAP_TYPE_CONFIG 0 /* used by configuration code */
695 #define TRAP_TYPE_PRIO 1 /* priority trap */
696 #define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */
700 * List relating reference clock types to control message time sources.
701 * Index by the reference clock type. This list will only be used iff
702 * the reference clock driver doesn't set peer->sstclktype to something
703 * different than CTL_SST_TS_UNSPEC.
706 static const u_char clocktypes[] = {
707 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */
708 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */
709 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */
710 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */
711 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */
712 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */
713 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */
714 CTL_SST_TS_HF, /* REFCLK_CHU (7) */
715 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */
716 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */
717 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */
718 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */
719 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */
720 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */
721 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */
722 CTL_SST_TS_NTP, /* not used (15) */
723 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */
724 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */
725 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */
726 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */
727 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */
728 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */
729 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */
730 CTL_SST_TS_NTP, /* not used (23) */
731 CTL_SST_TS_NTP, /* not used (24) */
732 CTL_SST_TS_NTP, /* not used (25) */
733 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */
734 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */
735 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */
736 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */
737 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */
738 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */
739 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */
740 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */
741 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */
742 CTL_SST_TS_LF, /* REFCLK_PCF (35) */
743 CTL_SST_TS_HF, /* REFCLK_WWV (36) */
744 CTL_SST_TS_LF, /* REFCLK_FG (37) */
745 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */
746 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */
747 CTL_SST_TS_LF, /* REFCLK_JJY (40) */
748 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */
749 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */
750 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */
751 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */
752 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */
753 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */
755 #endif /* REFCLOCK */
759 * Keyid used for authenticating write requests.
761 keyid_t ctl_auth_keyid;
764 * We keep track of the last error reported by the system internally
766 static u_char ctl_sys_last_event;
767 static u_char ctl_sys_num_events;
771 * Statistic counters to keep track of requests and responses.
773 u_long ctltimereset; /* time stats reset */
774 u_long numctlreq; /* number of requests we've received */
775 u_long numctlbadpkts; /* number of bad control packets */
776 u_long numctlresponses; /* number of resp packets sent with data */
777 u_long numctlfrags; /* number of fragments sent */
778 u_long numctlerrors; /* number of error responses sent */
779 u_long numctltooshort; /* number of too short input packets */
780 u_long numctlinputresp; /* number of responses on input */
781 u_long numctlinputfrag; /* number of fragments on input */
782 u_long numctlinputerr; /* number of input pkts with err bit set */
783 u_long numctlbadoffset; /* number of input pkts with nonzero offset */
784 u_long numctlbadversion; /* number of input pkts with unknown version */
785 u_long numctldatatooshort; /* data too short for count */
786 u_long numctlbadop; /* bad op code found in packet */
787 u_long numasyncmsgs; /* number of async messages we've sent */
790 * Response packet used by these routines. Also some state information
791 * so that we can handle packet formatting within a common set of
792 * subroutines. Note we try to enter data in place whenever possible,
793 * but the need to set the more bit correctly means we occasionally
794 * use the extra buffer and copy.
796 static struct ntp_control rpkt;
797 static u_char res_version;
798 static u_char res_opcode;
799 static associd_t res_associd;
800 static u_short res_frags; /* datagrams in this response */
801 static int res_offset; /* offset of payload in response */
802 static u_char * datapt;
803 static u_char * dataend;
804 static int datalinelen;
805 static int datasent; /* flag to avoid initial ", " */
806 static int datanotbinflag;
807 static sockaddr_u *rmt_addr;
808 static struct interface *lcl_inter;
810 static u_char res_authenticate;
811 static u_char res_authokay;
812 static keyid_t res_keyid;
814 #define MAXDATALINELEN (72)
816 static u_char res_async; /* sending async trap response? */
819 * Pointers for saving state when decoding request packets
825 #define MIN(a, b) (((a) <= (b)) ? (a) : (b))
829 * init_control - initialize request data
838 #endif /* HAVE_UNAME */
843 ctl_sys_last_event = EVNT_UNSPEC;
844 ctl_sys_num_events = 0;
847 for (i = 0; i < COUNTOF(ctl_traps); i++)
848 ctl_traps[i].tr_flags = 0;
853 * ctl_error - send an error response for the current request
863 DPRINTF(3, ("sending control error %u\n", errcode));
866 * Fill in the fields. We assume rpkt.sequence and rpkt.associd
867 * have already been filled in.
869 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR |
870 (res_opcode & CTL_OP_MASK);
871 rpkt.status = htons((u_short)(errcode << 8) & 0xff00);
875 * send packet and bump counters
877 if (res_authenticate && sys_authenticate) {
878 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt,
880 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt,
881 CTL_HEADER_LEN + maclen);
883 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt,
888 is_safe_filename(const char * name)
890 /* We need a strict validation of filenames we should write: The
891 * daemon might run with special permissions and is remote
892 * controllable, so we better take care what we allow as file
895 * The first character must be digit or a letter from the ASCII
896 * base plane or a '_' ([_A-Za-z0-9]), the following characters
897 * must be from [-._+A-Za-z0-9].
899 * We do not trust the character classification much here: Since
900 * the NTP protocol makes no provisions for UTF-8 or local code
901 * pages, we strictly require the 7bit ASCII code page.
903 * The following table is a packed bit field of 128 two-bit
904 * groups. The LSB in each group tells us if a character is
905 * acceptable at the first position, the MSB if the character is
906 * accepted at any other position.
908 * This does not ensure that the file name is syntactically
909 * correct (multiple dots will not work with VMS...) but it will
910 * exclude potential globbing bombs and directory traversal. It
911 * also rules out drive selection. (For systems that have this
912 * notion, like Windows or VMS.)
914 static const uint32_t chclass[8] = {
915 0x00000000, 0x00000000,
916 0x28800000, 0x000FFFFF,
917 0xFFFFFFFC, 0xC03FFFFF,
918 0xFFFFFFFC, 0x003FFFFF
921 u_int widx, bidx, mask;
922 if ( ! (name && *name))
926 while (0 != (widx = (u_char)*name++)) {
927 bidx = (widx & 15) << 1;
929 if (widx >= sizeof(chclass)/sizeof(chclass[0]))
931 if (0 == ((chclass[widx] >> bidx) & mask))
940 * save_config - Implements ntpq -c "saveconfig <filename>"
941 * Writes current configuration including any runtime
942 * changes by ntpq's :config or config-from-file
944 * Note: There should be no buffer overflow or truncation in the
945 * processing of file names -- both cause security problems. This is bit
946 * painful to code but essential here.
950 struct recvbuf *rbufp,
954 /* block directory traversal by searching for characters that
955 * indicate directory components in a file path.
957 * Conceptually we should be searching for DIRSEP in filename,
958 * however Windows actually recognizes both forward and
959 * backslashes as equivalent directory separators at the API
960 * level. On POSIX systems we could allow '\\' but such
961 * filenames are tricky to manipulate from a shell, so just
962 * reject both types of slashes on all platforms.
964 /* TALOS-CAN-0062: block directory traversal for VMS, too */
965 static const char * illegal_in_filename =
967 ":[]" /* do not allow drive and path components here */
968 #elif defined(SYS_WINNT)
969 ":\\/" /* path and drive separators */
971 "\\/" /* separator and critical char for POSIX */
976 static const char savedconfig_eq[] = "savedconfig=";
978 /* Build a safe open mode from the available mode flags. We want
979 * to create a new file and write it in text mode (when
980 * applicable -- only Windows does this...)
982 static const int openmode = O_CREAT | O_TRUNC | O_WRONLY
983 # if defined(O_EXCL) /* posix, vms */
985 # elif defined(_O_EXCL) /* windows is alway very special... */
988 # if defined(_O_TEXT) /* windows, again */
996 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)];
1004 if (RES_NOMODIFY & restrict_mask) {
1005 ctl_printf("%s", "saveconfig prohibited by restrict ... nomodify");
1009 "saveconfig from %s rejected due to nomodify restriction",
1010 stoa(&rbufp->recv_srcadr));
1016 if (NULL == saveconfigdir) {
1017 ctl_printf("%s", "saveconfig prohibited, no saveconfigdir configured");
1021 "saveconfig from %s rejected, no saveconfigdir",
1022 stoa(&rbufp->recv_srcadr));
1026 /* The length checking stuff gets serious. Do not assume a NUL
1027 * byte can be found, but if so, use it to calculate the needed
1028 * buffer size. If the available buffer is too short, bail out;
1029 * likewise if there is no file spec. (The latter will not
1030 * happen when using NTPQ, but there are other ways to craft a
1033 reqlen = (size_t)(reqend - reqpt);
1035 char * nulpos = (char*)memchr(reqpt, 0, reqlen);
1037 reqlen = (size_t)(nulpos - reqpt);
1041 if (reqlen >= sizeof(filespec)) {
1042 ctl_printf("saveconfig exceeded maximum raw name length (%u)",
1043 (u_int)sizeof(filespec));
1046 "saveconfig exceeded maximum raw name length from %s",
1047 stoa(&rbufp->recv_srcadr));
1051 /* copy data directly as we exactly know the size */
1052 memcpy(filespec, reqpt, reqlen);
1053 filespec[reqlen] = '\0';
1056 * allow timestamping of the saved config filename with
1057 * strftime() format such as:
1058 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf"
1059 * XXX: Nice feature, but not too safe.
1060 * YYY: The check for permitted characters in file names should
1061 * weed out the worst. Let's hope 'strftime()' does not
1062 * develop pathological problems.
1065 if (0 == strftime(filename, sizeof(filename), filespec,
1069 * If we arrive here, 'strftime()' balked; most likely
1070 * the buffer was too short. (Or it encounterd an empty
1071 * format, or just a format that expands to an empty
1072 * string.) We try to use the original name, though this
1073 * is very likely to fail later if there are format
1074 * specs in the string. Note that truncation cannot
1075 * happen here as long as both buffers have the same
1078 strlcpy(filename, filespec, sizeof(filename));
1082 * Check the file name for sanity. This might/will rule out file
1083 * names that would be legal but problematic, and it blocks
1084 * directory traversal.
1086 if (!is_safe_filename(filename)) {
1087 ctl_printf("saveconfig rejects unsafe file name '%s'",
1091 "saveconfig rejects unsafe file name from %s",
1092 stoa(&rbufp->recv_srcadr));
1097 * XXX: This next test may not be needed with is_safe_filename()
1100 /* block directory/drive traversal */
1101 /* TALOS-CAN-0062: block directory traversal for VMS, too */
1102 if (NULL != strpbrk(filename, illegal_in_filename)) {
1103 snprintf(reply, sizeof(reply),
1104 "saveconfig does not allow directory in filename");
1105 ctl_putdata(reply, strlen(reply), 0);
1108 "saveconfig rejects unsafe file name from %s",
1109 stoa(&rbufp->recv_srcadr));
1113 /* concatenation of directory and path can cause another
1116 prc = snprintf(fullpath, sizeof(fullpath), "%s%s",
1117 saveconfigdir, filename);
1118 if (prc < 0 || (size_t)prc >= sizeof(fullpath)) {
1119 ctl_printf("saveconfig exceeded maximum path length (%u)",
1120 (u_int)sizeof(fullpath));
1123 "saveconfig exceeded maximum path length from %s",
1124 stoa(&rbufp->recv_srcadr));
1128 fd = open(fullpath, openmode, S_IRUSR | S_IWUSR);
1132 fptr = fdopen(fd, "w");
1134 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) {
1135 ctl_printf("Unable to save configuration to file '%s': %s",
1136 filename, strerror(errno));
1138 "saveconfig %s from %s failed", filename,
1139 stoa(&rbufp->recv_srcadr));
1141 ctl_printf("Configuration saved to '%s'", filename);
1143 "Configuration saved to '%s' (requested by %s)",
1144 fullpath, stoa(&rbufp->recv_srcadr));
1146 * save the output filename in system variable
1147 * savedconfig, retrieved with:
1148 * ntpq -c "rv 0 savedconfig"
1149 * Note: the way 'savedconfig' is defined makes overflow
1150 * checks unnecessary here.
1152 snprintf(savedconfig, sizeof(savedconfig), "%s%s",
1153 savedconfig_eq, filename);
1154 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO);
1159 #else /* !SAVECONFIG follows */
1161 "saveconfig unavailable, configured with --disable-saveconfig");
1168 * process_control - process an incoming control message
1172 struct recvbuf *rbufp,
1176 struct ntp_control *pkt;
1179 const struct ctl_proc *cc;
1184 DPRINTF(3, ("in process_control()\n"));
1187 * Save the addresses for error responses
1190 rmt_addr = &rbufp->recv_srcadr;
1191 lcl_inter = rbufp->dstadr;
1192 pkt = (struct ntp_control *)&rbufp->recv_pkt;
1195 * If the length is less than required for the header,
1198 if (rbufp->recv_length < (int)CTL_HEADER_LEN) {
1199 DPRINTF(1, ("Short control packet\n"));
1205 * If this packet is a response or a fragment, ignore it.
1207 if ( (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op
1208 || pkt->offset != 0) {
1209 DPRINTF(1, ("invalid format in control packet\n"));
1210 if (CTL_RESPONSE & pkt->r_m_e_op)
1212 if (CTL_MORE & pkt->r_m_e_op)
1214 if (CTL_ERROR & pkt->r_m_e_op)
1216 if (pkt->offset != 0)
1221 res_version = PKT_VERSION(pkt->li_vn_mode);
1222 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) {
1223 DPRINTF(1, ("unknown version %d in control packet\n",
1230 * Pull enough data from the packet to make intelligent
1233 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version,
1235 res_opcode = pkt->r_m_e_op;
1236 rpkt.sequence = pkt->sequence;
1237 rpkt.associd = pkt->associd;
1241 res_associd = htons(pkt->associd);
1243 res_authenticate = FALSE;
1245 res_authokay = FALSE;
1246 req_count = (int)ntohs(pkt->count);
1247 datanotbinflag = FALSE;
1250 datapt = rpkt.u.data;
1251 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
1253 if ((rbufp->recv_length & 0x3) != 0)
1254 DPRINTF(3, ("Control packet length %d unrounded\n",
1255 rbufp->recv_length));
1258 * We're set up now. Make sure we've got at least enough
1259 * incoming data space to match the count.
1261 req_data = rbufp->recv_length - CTL_HEADER_LEN;
1262 if (req_data < req_count || rbufp->recv_length & 0x3) {
1263 ctl_error(CERR_BADFMT);
1264 numctldatatooshort++;
1268 properlen = req_count + CTL_HEADER_LEN;
1269 /* round up proper len to a 8 octet boundary */
1271 properlen = (properlen + 7) & ~7;
1272 maclen = rbufp->recv_length - properlen;
1273 if ((rbufp->recv_length & 3) == 0 &&
1274 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN &&
1276 res_authenticate = TRUE;
1277 pkid = (void *)((char *)pkt + properlen);
1278 res_keyid = ntohl(*pkid);
1279 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n",
1280 rbufp->recv_length, properlen, res_keyid,
1283 if (!authistrustedip(res_keyid, &rbufp->recv_srcadr))
1284 DPRINTF(3, ("invalid keyid %08x\n", res_keyid));
1285 else if (authdecrypt(res_keyid, (u_int32 *)pkt,
1286 rbufp->recv_length - maclen,
1288 res_authokay = TRUE;
1289 DPRINTF(3, ("authenticated okay\n"));
1292 DPRINTF(3, ("authentication failed\n"));
1297 * Set up translate pointers
1299 reqpt = (char *)pkt->u.data;
1300 reqend = reqpt + req_count;
1303 * Look for the opcode processor
1305 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) {
1306 if (cc->control_code == res_opcode) {
1307 DPRINTF(3, ("opcode %d, found command handler\n",
1309 if (cc->flags == AUTH
1311 || res_keyid != ctl_auth_keyid)) {
1312 ctl_error(CERR_PERMISSION);
1315 (cc->handler)(rbufp, restrict_mask);
1321 * Can't find this one, return an error.
1324 ctl_error(CERR_BADOP);
1330 * ctlpeerstatus - return a status word for this peer
1334 register struct peer *p
1340 if (FLAG_CONFIG & p->flags)
1341 status |= CTL_PST_CONFIG;
1343 status |= CTL_PST_AUTHENABLE;
1344 if (FLAG_AUTHENTIC & p->flags)
1345 status |= CTL_PST_AUTHENTIC;
1347 status |= CTL_PST_REACH;
1348 if (MDF_TXONLY_MASK & p->cast_flags)
1349 status |= CTL_PST_BCAST;
1351 return CTL_PEER_STATUS(status, p->num_events, p->last_event);
1356 * ctlclkstatus - return a status word for this clock
1361 struct refclockstat *pcs
1364 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus);
1370 * ctlsysstatus - return the system status word
1375 register u_char this_clock;
1377 this_clock = CTL_SST_TS_UNSPEC;
1379 if (sys_peer != NULL) {
1380 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype)
1381 this_clock = sys_peer->sstclktype;
1382 else if (sys_peer->refclktype < COUNTOF(clocktypes))
1383 this_clock = clocktypes[sys_peer->refclktype];
1385 #else /* REFCLOCK */
1387 this_clock = CTL_SST_TS_NTP;
1388 #endif /* REFCLOCK */
1389 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events,
1390 ctl_sys_last_event);
1395 * ctl_flushpkt - write out the current packet and prepare
1396 * another if necessary.
1410 dlen = datapt - rpkt.u.data;
1411 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) {
1413 * Big hack, output a trailing \r\n
1419 sendlen = dlen + CTL_HEADER_LEN;
1422 * Pad to a multiple of 32 bits
1424 while (sendlen & 0x3) {
1430 * Fill in the packet with the current info
1432 rpkt.r_m_e_op = CTL_RESPONSE | more |
1433 (res_opcode & CTL_OP_MASK);
1434 rpkt.count = htons((u_short)dlen);
1435 rpkt.offset = htons((u_short)res_offset);
1437 for (i = 0; i < COUNTOF(ctl_traps); i++) {
1438 if (TRAP_INUSE & ctl_traps[i].tr_flags) {
1442 ctl_traps[i].tr_version,
1445 htons(ctl_traps[i].tr_sequence);
1446 sendpkt(&ctl_traps[i].tr_addr,
1447 ctl_traps[i].tr_localaddr, -4,
1448 (struct pkt *)&rpkt, sendlen);
1450 ctl_traps[i].tr_sequence++;
1455 if (res_authenticate && sys_authenticate) {
1458 * If we are going to authenticate, then there
1459 * is an additional requirement that the MAC
1460 * begin on a 64 bit boundary.
1462 while (totlen & 7) {
1466 keyid = htonl(res_keyid);
1467 memcpy(datapt, &keyid, sizeof(keyid));
1468 maclen = authencrypt(res_keyid,
1469 (u_int32 *)&rpkt, totlen);
1470 sendpkt(rmt_addr, lcl_inter, -5,
1471 (struct pkt *)&rpkt, totlen + maclen);
1473 sendpkt(rmt_addr, lcl_inter, -6,
1474 (struct pkt *)&rpkt, sendlen);
1483 * Set us up for another go around.
1487 datapt = rpkt.u.data;
1491 /* --------------------------------------------------------------------
1492 * block transfer API -- stream string/data fragments into xmit buffer
1493 * without additional copying
1496 /* buffer descriptor: address & size of fragment
1497 * 'buf' may only be NULL when 'len' is zero!
1504 /* put ctl data in a gather-style operation */
1507 const CtlMemBufT * argv,
1509 int/*BOOL*/ bin /* set to 1 when data is binary */
1512 const char * src_ptr;
1513 size_t src_len, cur_len, add_len, argi;
1515 /* text / binary preprocessing, possibly create new linefeed */
1519 datanotbinflag = TRUE;
1526 /* sum up total length */
1527 for (argi = 0, src_len = 0; argi < argc; ++argi)
1528 src_len += argv[argi].len;
1529 /* possibly start a new line, assume no size_t overflow */
1530 if ((src_len + datalinelen + 1) >= MAXDATALINELEN) {
1541 /* now stream out all buffers */
1542 for (argi = 0; argi < argc; ++argi) {
1543 src_ptr = argv[argi].buf;
1544 src_len = argv[argi].len;
1546 if ( ! (src_ptr && src_len))
1549 cur_len = (size_t)(dataend - datapt);
1550 while ((src_len + add_len) > cur_len) {
1551 /* Not enough room in this one, flush it out. */
1552 if (src_len < cur_len)
1555 memcpy(datapt, src_ptr, cur_len);
1557 datalinelen += cur_len;
1562 ctl_flushpkt(CTL_MORE);
1563 cur_len = (size_t)(dataend - datapt);
1566 memcpy(datapt, src_ptr, src_len);
1568 datalinelen += src_len;
1575 * ctl_putdata - write data into the packet, fragmenting and starting
1576 * another if this one is full.
1582 int bin /* set to 1 when data is binary */
1589 ctl_putdata_ex(args, 1, bin);
1593 * ctl_putstr - write a tagged string into the response packet
1598 * len is the data length excluding the NUL terminator,
1599 * as in ctl_putstr("var", "value", strlen("value"));
1611 args[0].len = strlen(tag);
1613 args[1].buf = "=\"";
1619 ctl_putdata_ex(args, 4, FALSE);
1621 args[1].buf = "=\"\"";
1623 ctl_putdata_ex(args, 2, FALSE);
1629 * ctl_putunqstr - write a tagged string into the response packet
1634 * len is the data length excluding the NUL terminator.
1635 * data must not contain a comma or whitespace.
1647 args[0].len = strlen(tag);
1653 ctl_putdata_ex(args, 3, FALSE);
1655 ctl_putdata_ex(args, 2, FALSE);
1661 * ctl_putdblf - write a tagged, signed double into the response packet
1674 rc = snprintf(buffer, sizeof(buffer),
1675 (use_f ? "%.*f" : "%.*g"),
1677 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1678 ctl_putunqstr(tag, buffer, rc);
1682 * ctl_putuint - write a tagged unsigned integer into the response
1690 char buffer[24]; /* needs to fit for 64 bits! */
1693 rc = snprintf(buffer, sizeof(buffer), "%lu", uval);
1694 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1695 ctl_putunqstr(tag, buffer, rc);
1699 * ctl_putcal - write a decoded calendar data into the response.
1700 * only used with AUTOKEY currently, so compiled conditional
1706 const struct calendar *pcal
1712 rc = snprintf(buffer, sizeof(buffer),
1713 "%04d%02d%02d%02d%02d",
1714 pcal->year, pcal->month, pcal->monthday,
1715 pcal->hour, pcal->minute
1717 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1718 ctl_putunqstr(tag, buffer, rc);
1723 * ctl_putfs - write a decoded filestamp into the response
1734 time_t fstamp = (time_t)uval - JAN_1970;
1735 struct tm *tm = gmtime(&fstamp);
1740 rc = snprintf(buffer, sizeof(buffer),
1741 "%04d%02d%02d%02d%02d",
1742 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1743 tm->tm_hour, tm->tm_min);
1744 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1745 ctl_putunqstr(tag, buffer, rc);
1750 * ctl_puthex - write a tagged unsigned integer, in hex, into the
1759 char buffer[24]; /* must fit 64bit int! */
1762 rc = snprintf(buffer, sizeof(buffer), "0x%lx", uval);
1763 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1764 ctl_putunqstr(tag, buffer, rc);
1769 * ctl_putint - write a tagged signed integer into the response
1777 char buffer[24]; /*must fit 64bit int */
1780 rc = snprintf(buffer, sizeof(buffer), "%ld", ival);
1781 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1782 ctl_putunqstr(tag, buffer, rc);
1787 * ctl_putts - write a tagged timestamp, in hex, into the response
1798 rc = snprintf(buffer, sizeof(buffer),
1800 (u_long)ts->l_ui, (u_long)ts->l_uf);
1801 INSIST(rc >= 0 && (size_t)rc < sizeof(buffer));
1802 ctl_putunqstr(tag, buffer, rc);
1807 * ctl_putadr - write an IP address into the response
1819 cq = numtoa(addr32);
1822 ctl_putunqstr(tag, cq, strlen(cq));
1827 * ctl_putrefid - send a u_int32 refid as printable text
1839 uint8_t b[sizeof(uint32_t)];
1843 for (nc = 0; nc < sizeof(bytes.b) && bytes.b[nc]; ++nc)
1844 if ( !isprint(bytes.b[nc])
1845 || isspace(bytes.b[nc])
1846 || bytes.b[nc] == ',' )
1848 ctl_putunqstr(tag, (const char*)bytes.b, nc);
1853 * ctl_putarray - write a tagged eight element double array into the response
1867 ep = buffer + sizeof(buffer);
1873 rc = snprintf(cp, (size_t)(ep - cp), " %.2f", arr[i] * 1e3);
1874 INSIST(rc >= 0 && (size_t)rc < (size_t)(ep - cp));
1876 } while (i != start);
1877 ctl_putunqstr(tag, buffer, (size_t)(cp - buffer));
1881 * ctl_printf - put a formatted string into the data buffer
1889 static const char * ellipsis = "[...]";
1895 rc = vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, va);
1897 if (rc < 0 || (size_t)rc >= sizeof(fmtbuf))
1898 strcpy(fmtbuf + sizeof(fmtbuf) - strlen(ellipsis) - 1,
1900 ctl_putdata(fmtbuf, strlen(fmtbuf), 0);
1905 * ctl_putsys - output a system variable
1919 struct cert_info *cp;
1920 #endif /* AUTOKEY */
1922 static struct timex ntx;
1923 static u_long ntp_adjtime_time;
1926 * CS_K_* variables depend on up-to-date output of ntp_adjtime()
1928 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST &&
1929 current_time != ntp_adjtime_time) {
1931 if (ntp_adjtime(&ntx) < 0)
1932 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m");
1934 ntp_adjtime_time = current_time;
1936 #endif /* KERNEL_PLL */
1941 ctl_putuint(sys_var[CS_LEAP].text, sys_leap);
1945 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum);
1949 ctl_putint(sys_var[CS_PRECISION].text, sys_precision);
1953 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay *
1957 case CS_ROOTDISPERSION:
1958 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text,
1959 sys_rootdisp * 1e3);
1963 if (REFID_ISTEXT(sys_stratum))
1964 ctl_putrefid(sys_var[varid].text, sys_refid);
1966 ctl_putadr(sys_var[varid].text, sys_refid, NULL);
1970 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime);
1974 ctl_putuint(sys_var[CS_POLL].text, sys_poll);
1978 if (sys_peer == NULL)
1979 ctl_putuint(sys_var[CS_PEERID].text, 0);
1981 ctl_putuint(sys_var[CS_PEERID].text,
1986 if (sys_peer != NULL && sys_peer->dstadr != NULL)
1987 ss = sptoa(&sys_peer->srcadr);
1990 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss));
1994 u = (sys_peer != NULL)
1997 ctl_putuint(sys_var[CS_PEERMODE].text, u);
2001 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3);
2005 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6);
2009 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3);
2013 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3);
2018 ctl_putts(sys_var[CS_CLOCK].text, &tmp);
2023 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor,
2024 sizeof(str_processor) - 1);
2026 ctl_putstr(sys_var[CS_PROCESSOR].text,
2027 utsnamebuf.machine, strlen(utsnamebuf.machine));
2028 #endif /* HAVE_UNAME */
2033 ctl_putstr(sys_var[CS_SYSTEM].text, str_system,
2034 sizeof(str_system) - 1);
2036 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname,
2037 utsnamebuf.release);
2038 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str));
2039 #endif /* HAVE_UNAME */
2043 ctl_putstr(sys_var[CS_VERSION].text, Version,
2048 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability *
2054 char buf[CTL_MAX_DATA_LEN];
2055 //buffPointer, firstElementPointer, buffEndPointer
2056 char *buffp, *buffend;
2060 const struct ctl_var *k;
2063 buffend = buf + sizeof(buf);
2064 if (strlen(sys_var[CS_VARLIST].text) > (sizeof(buf) - 4))
2065 break; /* really long var name */
2067 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text);
2068 buffp += strlen(buffp);
2069 firstVarName = TRUE;
2070 for (k = sys_var; !(k->flags & EOV); k++) {
2071 if (k->flags & PADDING)
2073 len = strlen(k->text);
2074 if (len + 1 >= buffend - buffp)
2079 firstVarName = FALSE;
2080 memcpy(buffp, k->text, len);
2084 for (k = ext_sys_var; k && !(k->flags & EOV); k++) {
2085 if (k->flags & PADDING)
2087 if (NULL == k->text)
2089 ss1 = strchr(k->text, '=');
2091 len = strlen(k->text);
2093 len = ss1 - k->text;
2094 if (len + 1 >= buffend - buffp)
2098 firstVarName = FALSE;
2100 memcpy(buffp, k->text,(unsigned)len);
2103 if (2 >= buffend - buffp)
2109 ctl_putdata(buf, (unsigned)( buffp - buf ), 0);
2115 ctl_putuint(sys_var[CS_TAI].text, sys_tai);
2120 leap_signature_t lsig;
2121 leapsec_getsig(&lsig);
2123 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime);
2129 leap_signature_t lsig;
2130 leapsec_getsig(&lsig);
2132 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime);
2137 case CS_LEAPSMEARINTV:
2138 if (leap_smear_intv > 0)
2139 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv);
2142 case CS_LEAPSMEAROFFS:
2143 if (leap_smear_intv > 0)
2144 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text,
2145 leap_smear.doffset * 1e3);
2147 #endif /* LEAP_SMEAR */
2150 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll);
2153 case CS_MRU_ENABLED:
2154 ctl_puthex(sys_var[varid].text, mon_enabled);
2158 ctl_putuint(sys_var[varid].text, mru_entries);
2162 kb = mru_entries * (sizeof(mon_entry) / 1024.);
2166 ctl_putuint(sys_var[varid].text, u);
2169 case CS_MRU_DEEPEST:
2170 ctl_putuint(sys_var[varid].text, mru_peakentries);
2173 case CS_MRU_MINDEPTH:
2174 ctl_putuint(sys_var[varid].text, mru_mindepth);
2178 ctl_putint(sys_var[varid].text, mru_maxage);
2181 case CS_MRU_MAXDEPTH:
2182 ctl_putuint(sys_var[varid].text, mru_maxdepth);
2186 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.);
2190 ctl_putuint(sys_var[varid].text, u);
2194 ctl_putuint(sys_var[varid].text, current_time);
2198 ctl_putuint(sys_var[varid].text,
2199 current_time - sys_stattime);
2202 case CS_SS_RECEIVED:
2203 ctl_putuint(sys_var[varid].text, sys_received);
2207 ctl_putuint(sys_var[varid].text, sys_newversion);
2211 ctl_putuint(sys_var[varid].text, sys_oldversion);
2214 case CS_SS_BADFORMAT:
2215 ctl_putuint(sys_var[varid].text, sys_badlength);
2219 ctl_putuint(sys_var[varid].text, sys_badauth);
2222 case CS_SS_DECLINED:
2223 ctl_putuint(sys_var[varid].text, sys_declined);
2226 case CS_SS_RESTRICTED:
2227 ctl_putuint(sys_var[varid].text, sys_restricted);
2231 ctl_putuint(sys_var[varid].text, sys_limitrejected);
2235 ctl_putuint(sys_var[varid].text, sys_lamport);
2238 case CS_SS_TSROUNDING:
2239 ctl_putuint(sys_var[varid].text, sys_tsrounding);
2243 ctl_putuint(sys_var[varid].text, sys_kodsent);
2246 case CS_SS_PROCESSED:
2247 ctl_putuint(sys_var[varid].text, sys_processed);
2251 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3);
2255 LFPTOD(&sys_authdelay, dtemp);
2256 ctl_putdbl(sys_var[varid].text, dtemp * 1e3);
2260 ctl_putuint(sys_var[varid].text, authnumkeys);
2264 ctl_putuint(sys_var[varid].text, authnumfreekeys);
2267 case CS_AUTHKLOOKUPS:
2268 ctl_putuint(sys_var[varid].text, authkeylookups);
2271 case CS_AUTHKNOTFOUND:
2272 ctl_putuint(sys_var[varid].text, authkeynotfound);
2275 case CS_AUTHKUNCACHED:
2276 ctl_putuint(sys_var[varid].text, authkeyuncached);
2279 case CS_AUTHKEXPIRED:
2280 ctl_putuint(sys_var[varid].text, authkeyexpired);
2283 case CS_AUTHENCRYPTS:
2284 ctl_putuint(sys_var[varid].text, authencryptions);
2287 case CS_AUTHDECRYPTS:
2288 ctl_putuint(sys_var[varid].text, authdecryptions);
2292 ctl_putuint(sys_var[varid].text,
2293 current_time - auth_timereset);
2297 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is
2298 * unavailable, otherwise calls putfunc with args.
2301 # define CTL_IF_KERNLOOP(putfunc, args) \
2302 ctl_putint(sys_var[varid].text, 0)
2304 # define CTL_IF_KERNLOOP(putfunc, args) \
2309 * CTL_IF_KERNPPS() puts a zero if either the kernel
2310 * loop is unavailable, or kernel hard PPS is not
2311 * active, otherwise calls putfunc with args.
2314 # define CTL_IF_KERNPPS(putfunc, args) \
2315 ctl_putint(sys_var[varid].text, 0)
2317 # define CTL_IF_KERNPPS(putfunc, args) \
2318 if (0 == ntx.shift) \
2319 ctl_putint(sys_var[varid].text, 0); \
2321 putfunc args /* no trailing ; */
2327 (sys_var[varid].text, 0, -1,
2328 1000 * dbl_from_var_long(ntx.offset, ntx.status))
2335 (sys_var[varid].text, ntx.freq)
2342 (sys_var[varid].text, 0, 6,
2343 1000 * dbl_from_usec_long(ntx.maxerror))
2350 (sys_var[varid].text, 0, 6,
2351 1000 * dbl_from_usec_long(ntx.esterror))
2359 ss = k_st_flags(ntx.status);
2361 ctl_putstr(sys_var[varid].text, ss, strlen(ss));
2364 case CS_K_TIMECONST:
2367 (sys_var[varid].text, ntx.constant)
2371 case CS_K_PRECISION:
2374 (sys_var[varid].text, 0, 6,
2375 1000 * dbl_from_var_long(ntx.precision, ntx.status))
2382 (sys_var[varid].text, ntx.tolerance)
2389 (sys_var[varid].text, ntx.ppsfreq)
2393 case CS_K_PPS_STABIL:
2396 (sys_var[varid].text, ntx.stabil)
2400 case CS_K_PPS_JITTER:
2403 (sys_var[varid].text,
2404 1000 * dbl_from_var_long(ntx.jitter, ntx.status))
2408 case CS_K_PPS_CALIBDUR:
2411 (sys_var[varid].text, 1 << ntx.shift)
2415 case CS_K_PPS_CALIBS:
2418 (sys_var[varid].text, ntx.calcnt)
2422 case CS_K_PPS_CALIBERRS:
2425 (sys_var[varid].text, ntx.errcnt)
2429 case CS_K_PPS_JITEXC:
2432 (sys_var[varid].text, ntx.jitcnt)
2436 case CS_K_PPS_STBEXC:
2439 (sys_var[varid].text, ntx.stbcnt)
2443 case CS_IOSTATS_RESET:
2444 ctl_putuint(sys_var[varid].text,
2445 current_time - io_timereset);
2449 ctl_putuint(sys_var[varid].text, total_recvbuffs());
2453 ctl_putuint(sys_var[varid].text, free_recvbuffs());
2457 ctl_putuint(sys_var[varid].text, full_recvbuffs());
2460 case CS_RBUF_LOWATER:
2461 ctl_putuint(sys_var[varid].text, lowater_additions());
2465 ctl_putuint(sys_var[varid].text, packets_dropped);
2469 ctl_putuint(sys_var[varid].text, packets_ignored);
2472 case CS_IO_RECEIVED:
2473 ctl_putuint(sys_var[varid].text, packets_received);
2477 ctl_putuint(sys_var[varid].text, packets_sent);
2480 case CS_IO_SENDFAILED:
2481 ctl_putuint(sys_var[varid].text, packets_notsent);
2485 ctl_putuint(sys_var[varid].text, handler_calls);
2488 case CS_IO_GOODWAKEUPS:
2489 ctl_putuint(sys_var[varid].text, handler_pkts);
2492 case CS_TIMERSTATS_RESET:
2493 ctl_putuint(sys_var[varid].text,
2494 current_time - timer_timereset);
2497 case CS_TIMER_OVERRUNS:
2498 ctl_putuint(sys_var[varid].text, alarm_overflow);
2502 ctl_putuint(sys_var[varid].text, timer_xmtcalls);
2506 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3);
2508 case CS_WANDER_THRESH:
2509 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6);
2514 ctl_puthex(sys_var[CS_FLAGS].text,
2520 strlcpy(str, OBJ_nid2ln(crypto_nid),
2522 ctl_putstr(sys_var[CS_DIGEST].text, str,
2531 dp = EVP_get_digestbynid(crypto_flags >> 16);
2532 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)),
2534 ctl_putstr(sys_var[CS_SIGNATURE].text, str,
2540 if (hostval.ptr != NULL)
2541 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr,
2542 strlen(hostval.ptr));
2546 if (sys_ident != NULL)
2547 ctl_putstr(sys_var[CS_IDENT].text, sys_ident,
2552 for (cp = cinfo; cp != NULL; cp = cp->link) {
2553 snprintf(str, sizeof(str), "%s %s 0x%x",
2554 cp->subject, cp->issuer, cp->flags);
2555 ctl_putstr(sys_var[CS_CERTIF].text, str,
2557 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last));
2562 if (hostval.tstamp != 0)
2563 ctl_putfs(sys_var[CS_PUBLIC].text,
2564 ntohl(hostval.tstamp));
2566 #endif /* AUTOKEY */
2575 * ctl_putpeer - output a peer variable
2583 char buf[CTL_MAX_DATA_LEN];
2588 const struct ctl_var *k;
2593 #endif /* AUTOKEY */
2598 ctl_putuint(peer_var[id].text,
2599 !(FLAG_PREEMPT & p->flags));
2603 ctl_putuint(peer_var[id].text, !(p->keyid));
2607 ctl_putuint(peer_var[id].text,
2608 !!(FLAG_AUTHENTIC & p->flags));
2612 ctl_putadr(peer_var[id].text, 0, &p->srcadr);
2616 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr));
2620 if (p->hostname != NULL)
2621 ctl_putstr(peer_var[id].text, p->hostname,
2622 strlen(p->hostname));
2626 ctl_putadr(peer_var[id].text, 0,
2633 ctl_putuint(peer_var[id].text,
2635 ? SRCPORT(&p->dstadr->sin)
2641 ctl_putdbl(peer_var[id].text, p->r21 / 1e3);
2646 ctl_putdbl(peer_var[id].text, p->r34 / 1e3);
2650 ctl_putuint(peer_var[id].text, p->throttle);
2654 ctl_putuint(peer_var[id].text, p->leap);
2658 ctl_putuint(peer_var[id].text, p->hmode);
2662 ctl_putuint(peer_var[id].text, p->stratum);
2666 ctl_putuint(peer_var[id].text, p->ppoll);
2670 ctl_putuint(peer_var[id].text, p->hpoll);
2674 ctl_putint(peer_var[id].text, p->precision);
2678 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3);
2681 case CP_ROOTDISPERSION:
2682 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3);
2687 if (p->flags & FLAG_REFCLOCK) {
2688 ctl_putrefid(peer_var[id].text, p->refid);
2692 if (REFID_ISTEXT(p->stratum))
2693 ctl_putrefid(peer_var[id].text, p->refid);
2695 ctl_putadr(peer_var[id].text, p->refid, NULL);
2699 ctl_putts(peer_var[id].text, &p->reftime);
2703 ctl_putts(peer_var[id].text, &p->aorg);
2707 ctl_putts(peer_var[id].text, &p->dst);
2712 ctl_putdbl(peer_var[id].text, p->xleave * 1e3);
2717 ctl_putdbl(peer_var[id].text, p->bias * 1e3);
2721 ctl_puthex(peer_var[id].text, p->reach);
2725 ctl_puthex(peer_var[id].text, p->flash);
2730 if (p->flags & FLAG_REFCLOCK) {
2731 ctl_putuint(peer_var[id].text, p->ttl);
2735 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl))
2736 ctl_putint(peer_var[id].text,
2741 ctl_putuint(peer_var[id].text, p->unreach);
2745 ctl_putuint(peer_var[id].text,
2746 p->nextdate - current_time);
2750 ctl_putdbl(peer_var[id].text, p->delay * 1e3);
2754 ctl_putdbl(peer_var[id].text, p->offset * 1e3);
2758 ctl_putdbl(peer_var[id].text, p->jitter * 1e3);
2762 ctl_putdbl(peer_var[id].text, p->disp * 1e3);
2766 if (p->keyid > NTP_MAXKEY)
2767 ctl_puthex(peer_var[id].text, p->keyid);
2769 ctl_putuint(peer_var[id].text, p->keyid);
2773 ctl_putarray(peer_var[id].text, p->filter_delay,
2778 ctl_putarray(peer_var[id].text, p->filter_offset,
2783 ctl_putarray(peer_var[id].text, p->filter_disp,
2788 ctl_putuint(peer_var[id].text, p->pmode);
2792 ctl_putuint(peer_var[id].text, p->received);
2796 ctl_putuint(peer_var[id].text, p->sent);
2801 be = buf + sizeof(buf);
2802 if (strlen(peer_var[id].text) + 4 > sizeof(buf))
2803 break; /* really long var name */
2805 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text);
2808 for (k = peer_var; !(EOV & k->flags); k++) {
2809 if (PADDING & k->flags)
2811 i = strlen(k->text);
2812 if (s + i + 1 >= be)
2816 memcpy(s, k->text, i);
2822 ctl_putdata(buf, (u_int)(s - buf), 0);
2827 ctl_putuint(peer_var[id].text,
2828 current_time - p->timereceived);
2832 ctl_putuint(peer_var[id].text,
2833 current_time - p->timereachable);
2837 ctl_putuint(peer_var[id].text, p->badauth);
2841 ctl_putuint(peer_var[id].text, p->bogusorg);
2845 ctl_putuint(peer_var[id].text, p->oldpkt);
2849 ctl_putuint(peer_var[id].text, p->seldisptoolarge);
2853 ctl_putuint(peer_var[id].text, p->selbroken);
2857 ctl_putuint(peer_var[id].text, p->status);
2862 ctl_puthex(peer_var[id].text, p->crypto);
2867 dp = EVP_get_digestbynid(p->crypto >> 16);
2868 str = OBJ_nid2ln(EVP_MD_pkey_type(dp));
2869 ctl_putstr(peer_var[id].text, str, strlen(str));
2874 if (p->subject != NULL)
2875 ctl_putstr(peer_var[id].text, p->subject,
2876 strlen(p->subject));
2879 case CP_VALID: /* not used */
2883 if (NULL == (ap = p->recval.ptr))
2886 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq);
2887 ctl_puthex(peer_var[CP_INITKEY].text, ap->key);
2888 ctl_putfs(peer_var[CP_INITTSP].text,
2889 ntohl(p->recval.tstamp));
2893 if (p->ident != NULL)
2894 ctl_putstr(peer_var[id].text, p->ident,
2899 #endif /* AUTOKEY */
2906 * ctl_putclock - output clock variables
2911 struct refclockstat *pcs,
2915 char buf[CTL_MAX_DATA_LEN];
2919 const struct ctl_var *k;
2924 if (mustput || pcs->clockdesc == NULL
2925 || *(pcs->clockdesc) == '\0') {
2926 ctl_putuint(clock_var[id].text, pcs->type);
2930 ctl_putstr(clock_var[id].text,
2932 (unsigned)pcs->lencode);
2936 ctl_putuint(clock_var[id].text, pcs->polls);
2940 ctl_putuint(clock_var[id].text,
2945 ctl_putuint(clock_var[id].text,
2950 ctl_putuint(clock_var[id].text,
2955 if (mustput || (pcs->haveflags & CLK_HAVETIME1))
2956 ctl_putdbl(clock_var[id].text,
2957 pcs->fudgetime1 * 1e3);
2961 if (mustput || (pcs->haveflags & CLK_HAVETIME2))
2962 ctl_putdbl(clock_var[id].text,
2963 pcs->fudgetime2 * 1e3);
2967 if (mustput || (pcs->haveflags & CLK_HAVEVAL1))
2968 ctl_putint(clock_var[id].text,
2973 /* RefID of clocks are always text even if stratum is fudged */
2974 if (mustput || (pcs->haveflags & CLK_HAVEVAL2))
2975 ctl_putrefid(clock_var[id].text, pcs->fudgeval2);
2979 ctl_putuint(clock_var[id].text, pcs->flags);
2983 if (pcs->clockdesc == NULL ||
2984 *(pcs->clockdesc) == '\0') {
2986 ctl_putstr(clock_var[id].text,
2989 ctl_putstr(clock_var[id].text,
2991 strlen(pcs->clockdesc));
2997 be = buf + sizeof(buf);
2998 if (strlen(clock_var[CC_VARLIST].text) + 4 >
3000 break; /* really long var name */
3002 snprintf(s, sizeof(buf), "%s=\"",
3003 clock_var[CC_VARLIST].text);
3007 for (k = clock_var; !(EOV & k->flags); k++) {
3008 if (PADDING & k->flags)
3011 i = strlen(k->text);
3012 if (s + i + 1 >= be)
3017 memcpy(s, k->text, i);
3021 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) {
3022 if (PADDING & k->flags)
3029 while (*ss && *ss != '=')
3032 if (s + i + 1 >= be)
3037 memcpy(s, k->text, (unsigned)i);
3046 ctl_putdata(buf, (unsigned)(s - buf), 0);
3049 case CC_FUDGEMINJIT:
3050 if (mustput || (pcs->haveflags & CLK_HAVEMINJIT))
3051 ctl_putdbl(clock_var[id].text,
3052 pcs->fudgeminjitter * 1e3);
3065 * ctl_getitem - get the next data item from the incoming packet
3067 static const struct ctl_var *
3069 const struct ctl_var *var_list,
3073 /* [Bug 3008] First check the packet data sanity, then search
3074 * the key. This improves the consistency of result values: If
3075 * the result is NULL once, it will never be EOV again for this
3076 * packet; If it's EOV, it will never be NULL again until the
3077 * variable is found and processed in a given 'var_list'. (That
3078 * is, a result is returned that is neither NULL nor EOV).
3080 static const struct ctl_var eol = { 0, EOV, NULL };
3081 static char buf[128];
3082 static u_long quiet_until;
3083 const struct ctl_var *v;
3088 * Part One: Validate the packet state
3091 /* Delete leading commas and white space */
3092 while (reqpt < reqend && (*reqpt == ',' ||
3093 isspace((unsigned char)*reqpt)))
3095 if (reqpt >= reqend)
3098 /* Scan the string in the packet until we hit comma or
3099 * EoB. Register position of first '=' on the fly. */
3100 for (tp = NULL, cp = reqpt; cp != reqend; ++cp) {
3101 if (*cp == '=' && tp == NULL)
3107 /* Process payload, if any. */
3110 /* eventually strip white space from argument. */
3111 const char *plhead = tp + 1; /* skip the '=' */
3112 const char *pltail = cp;
3115 while (plhead != pltail && isspace((u_char)plhead[0]))
3117 while (plhead != pltail && isspace((u_char)pltail[-1]))
3120 /* check payload size, terminate packet on overflow */
3121 plsize = (size_t)(pltail - plhead);
3122 if (plsize >= sizeof(buf))
3125 /* copy data, NUL terminate, and set result data ptr */
3126 memcpy(buf, plhead, plsize);
3130 /* no payload, current end --> current name termination */
3136 * Now we're sure that the packet data itself is sane. Scan the
3137 * list now. Make sure a NULL list is properly treated by
3138 * returning a synthetic End-Of-Values record. We must not
3139 * return NULL pointers after this point, or the behaviour would
3140 * become inconsistent if called several times with different
3141 * variable lists after an EoV was returned. (Such a behavior
3142 * actually caused Bug 3008.)
3145 if (NULL == var_list)
3148 for (v = var_list; !(EOV & v->flags); ++v)
3149 if (!(PADDING & v->flags)) {
3150 /* Check if the var name matches the buffer. The
3151 * name is bracketed by [reqpt..tp] and not NUL
3152 * terminated, and it contains no '=' char. The
3153 * lookup value IS NUL-terminated but might
3154 * include a '='... We have to look out for
3157 const char *sp1 = reqpt;
3158 const char *sp2 = v->text;
3160 /* [Bug 3412] do not compare past NUL byte in name */
3162 && ('\0' != *sp2) && (*sp1 == *sp2)) {
3166 if (sp1 == tp && (*sp2 == '\0' || *sp2 == '='))
3170 /* See if we have found a valid entry or not. If found, advance
3171 * the request pointer for the next round; if not, clear the
3172 * data pointer so we have no dangling garbage here.
3177 reqpt = cp + (cp != reqend);
3181 /*TODO? somehow indicate this packet was bad, apart from syslog? */
3184 if (quiet_until <= current_time) {
3185 quiet_until = current_time + 300;
3186 msyslog(LOG_WARNING,
3187 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)",
3188 stoa(rmt_addr), SRCPORT(rmt_addr));
3190 reqpt = reqend; /* never again for this packet! */
3196 * control_unspec - response to an unspecified op-code
3201 struct recvbuf *rbufp,
3208 * What is an appropriate response to an unspecified op-code?
3209 * I return no errors and no data, unless a specified assocation
3213 peer = findpeerbyassoc(res_associd);
3215 ctl_error(CERR_BADASSOC);
3218 rpkt.status = htons(ctlpeerstatus(peer));
3220 rpkt.status = htons(ctlsysstatus());
3226 * read_status - return either a list of associd's, or a particular
3232 struct recvbuf *rbufp,
3239 /* a_st holds association ID, status pairs alternating */
3240 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)];
3244 printf("read_status: ID %d\n", res_associd);
3247 * Two choices here. If the specified association ID is
3248 * zero we return all known assocation ID's. Otherwise
3249 * we return a bunch of stuff about the particular peer.
3252 peer = findpeerbyassoc(res_associd);
3254 ctl_error(CERR_BADASSOC);
3257 rpkt.status = htons(ctlpeerstatus(peer));
3259 peer->num_events = 0;
3261 * For now, output everything we know about the
3262 * peer. May be more selective later.
3264 for (cp = def_peer_var; *cp != 0; cp++)
3265 ctl_putpeer((int)*cp, peer);
3270 rpkt.status = htons(ctlsysstatus());
3271 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3272 a_st[n++] = htons(peer->associd);
3273 a_st[n++] = htons(ctlpeerstatus(peer));
3274 /* two entries each loop iteration, so n + 1 */
3275 if (n + 1 >= COUNTOF(a_st)) {
3276 ctl_putdata((void *)a_st, n * sizeof(a_st[0]),
3282 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1);
3288 * read_peervars - half of read_variables() implementation
3293 const struct ctl_var *v;
3298 u_char wants[CP_MAXCODE + 1];
3302 * Wants info for a particular peer. See if we know
3305 peer = findpeerbyassoc(res_associd);
3307 ctl_error(CERR_BADASSOC);
3310 rpkt.status = htons(ctlpeerstatus(peer));
3312 peer->num_events = 0;
3315 while (NULL != (v = ctl_getitem(peer_var, &valuep))) {
3316 if (v->flags & EOV) {
3317 ctl_error(CERR_UNKNOWNVAR);
3320 INSIST(v->code < COUNTOF(wants));
3325 for (i = 1; i < COUNTOF(wants); i++)
3327 ctl_putpeer(i, peer);
3329 for (cp = def_peer_var; *cp != 0; cp++)
3330 ctl_putpeer((int)*cp, peer);
3336 * read_sysvars - half of read_variables() implementation
3341 const struct ctl_var *v;
3352 * Wants system variables. Figure out which he wants
3353 * and give them to him.
3355 rpkt.status = htons(ctlsysstatus());
3357 ctl_sys_num_events = 0;
3358 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var);
3359 wants = emalloc_zero(wants_count);
3361 while (NULL != (v = ctl_getitem(sys_var, &valuep))) {
3362 if (!(EOV & v->flags)) {
3363 INSIST(v->code < wants_count);
3367 v = ctl_getitem(ext_sys_var, &valuep);
3369 ctl_error(CERR_BADVALUE);
3373 if (EOV & v->flags) {
3374 ctl_error(CERR_UNKNOWNVAR);
3378 n = v->code + CS_MAXCODE + 1;
3379 INSIST(n < wants_count);
3385 for (n = 1; n <= CS_MAXCODE; n++)
3388 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++)
3389 if (wants[n + CS_MAXCODE + 1]) {
3390 pch = ext_sys_var[n].text;
3391 ctl_putdata(pch, strlen(pch), 0);
3394 for (cs = def_sys_var; *cs != 0; cs++)
3395 ctl_putsys((int)*cs);
3396 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++)
3397 if (DEF & kv->flags)
3398 ctl_putdata(kv->text, strlen(kv->text),
3407 * read_variables - return the variables the caller asks for
3412 struct recvbuf *rbufp,
3424 * write_variables - write into variables. We only allow leap bit
3430 struct recvbuf *rbufp,
3434 const struct ctl_var *v;
3445 * If he's trying to write into a peer tell him no way
3447 if (res_associd != 0) {
3448 ctl_error(CERR_PERMISSION);
3455 rpkt.status = htons(ctlsysstatus());
3458 * Look through the variables. Dump out at the first sign of
3461 while ((v = ctl_getitem(sys_var, &valuep)) != NULL) {
3463 if (v->flags & EOV) {
3464 v = ctl_getitem(ext_sys_var, &valuep);
3466 if (v->flags & EOV) {
3467 ctl_error(CERR_UNKNOWNVAR);
3475 if (!(v->flags & CAN_WRITE)) {
3476 ctl_error(CERR_PERMISSION);
3479 /* [bug 3565] writing makes sense only if we *have* a
3480 * value in the packet!
3482 if (valuep == NULL) {
3483 ctl_error(CERR_BADFMT);
3487 if ( !(*valuep && atoint(valuep, &val))) {
3488 ctl_error(CERR_BADFMT);
3491 if ((val & ~LEAP_NOTINSYNC) != 0) {
3492 ctl_error(CERR_BADVALUE);
3498 octets = strlen(v->text) + strlen(valuep) + 2;
3499 vareqv = emalloc(octets);
3502 while (*t && *t != '=')
3505 memcpy(tt, valuep, 1 + strlen(valuep));
3506 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags);
3509 ctl_error(CERR_UNSPEC); /* really */
3515 * If we got anything, do it. xxx nothing to do ***
3518 if (leapind != ~0 || leapwarn != ~0) {
3519 if (!leap_setleap((int)leapind, (int)leapwarn)) {
3520 ctl_error(CERR_PERMISSION);
3530 * configure() processes ntpq :config/config-from-file, allowing
3531 * generic runtime reconfiguration.
3533 static void configure(
3534 struct recvbuf *rbufp,
3541 /* I haven't yet implemented changes to an existing association.
3542 * Hence check if the association id is 0
3544 if (res_associd != 0) {
3545 ctl_error(CERR_BADVALUE);
3549 if (RES_NOMODIFY & restrict_mask) {
3550 snprintf(remote_config.err_msg,
3551 sizeof(remote_config.err_msg),
3552 "runtime configuration prohibited by restrict ... nomodify");
3553 ctl_putdata(remote_config.err_msg,
3554 strlen(remote_config.err_msg), 0);
3558 "runtime config from %s rejected due to nomodify restriction",
3559 stoa(&rbufp->recv_srcadr));
3564 /* Initialize the remote config buffer */
3565 data_count = remoteconfig_cmdlength(reqpt, reqend);
3567 if (data_count > sizeof(remote_config.buffer) - 2) {
3568 snprintf(remote_config.err_msg,
3569 sizeof(remote_config.err_msg),
3570 "runtime configuration failed: request too long");
3571 ctl_putdata(remote_config.err_msg,
3572 strlen(remote_config.err_msg), 0);
3575 "runtime config from %s rejected: request too long",
3576 stoa(&rbufp->recv_srcadr));
3579 /* Bug 2853 -- check if all characters were acceptable */
3580 if (data_count != (size_t)(reqend - reqpt)) {
3581 snprintf(remote_config.err_msg,
3582 sizeof(remote_config.err_msg),
3583 "runtime configuration failed: request contains an unprintable character");
3584 ctl_putdata(remote_config.err_msg,
3585 strlen(remote_config.err_msg), 0);
3588 "runtime config from %s rejected: request contains an unprintable character: %0x",
3589 stoa(&rbufp->recv_srcadr),
3594 memcpy(remote_config.buffer, reqpt, data_count);
3595 /* The buffer has no trailing linefeed or NUL right now. For
3596 * logging, we do not want a newline, so we do that first after
3597 * adding the necessary NUL byte.
3599 remote_config.buffer[data_count] = '\0';
3600 DPRINTF(1, ("Got Remote Configuration Command: %s\n",
3601 remote_config.buffer));
3602 msyslog(LOG_NOTICE, "%s config: %s",
3603 stoa(&rbufp->recv_srcadr),
3604 remote_config.buffer);
3606 /* Now we have to make sure there is a NL/NUL sequence at the
3607 * end of the buffer before we parse it.
3609 remote_config.buffer[data_count++] = '\n';
3610 remote_config.buffer[data_count] = '\0';
3611 remote_config.pos = 0;
3612 remote_config.err_pos = 0;
3613 remote_config.no_errors = 0;
3614 config_remotely(&rbufp->recv_srcadr);
3617 * Check if errors were reported. If not, output 'Config
3618 * Succeeded'. Else output the error count. It would be nice
3619 * to output any parser error messages.
3621 if (0 == remote_config.no_errors) {
3622 retval = snprintf(remote_config.err_msg,
3623 sizeof(remote_config.err_msg),
3624 "Config Succeeded");
3626 remote_config.err_pos += retval;
3629 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0);
3632 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg));
3634 if (remote_config.no_errors > 0)
3635 msyslog(LOG_NOTICE, "%d error in %s config",
3636 remote_config.no_errors,
3637 stoa(&rbufp->recv_srcadr));
3642 * derive_nonce - generate client-address-specific nonce value
3643 * associated with a given timestamp.
3645 static u_int32 derive_nonce(
3651 static u_int32 salt[4];
3652 static u_long last_salt_update;
3654 u_char digest[EVP_MAX_MD_SIZE];
3660 while (!salt[0] || current_time - last_salt_update >= 3600) {
3661 salt[0] = ntp_random();
3662 salt[1] = ntp_random();
3663 salt[2] = ntp_random();
3664 salt[3] = ntp_random();
3665 last_salt_update = current_time;
3668 ctx = EVP_MD_CTX_new();
3669 # if defined(OPENSSL) && defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW)
3670 /* [Bug 3457] set flags and don't kill them again */
3671 EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
3672 EVP_DigestInit_ex(ctx, EVP_get_digestbynid(NID_md5), NULL);
3674 EVP_DigestInit(ctx, EVP_get_digestbynid(NID_md5));
3676 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3677 EVP_DigestUpdate(ctx, &ts_i, sizeof(ts_i));
3678 EVP_DigestUpdate(ctx, &ts_f, sizeof(ts_f));
3680 EVP_DigestUpdate(ctx, &SOCK_ADDR4(addr),
3681 sizeof(SOCK_ADDR4(addr)));
3683 EVP_DigestUpdate(ctx, &SOCK_ADDR6(addr),
3684 sizeof(SOCK_ADDR6(addr)));
3685 EVP_DigestUpdate(ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr)));
3686 EVP_DigestUpdate(ctx, salt, sizeof(salt));
3687 EVP_DigestFinal(ctx, d.digest, &len);
3688 EVP_MD_CTX_free(ctx);
3695 * generate_nonce - generate client-address-specific nonce string.
3697 static void generate_nonce(
3698 struct recvbuf * rbufp,
3705 derived = derive_nonce(&rbufp->recv_srcadr,
3706 rbufp->recv_time.l_ui,
3707 rbufp->recv_time.l_uf);
3708 snprintf(nonce, nonce_octets, "%08x%08x%08x",
3709 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived);
3714 * validate_nonce - validate client-address-specific nonce string.
3716 * Returns TRUE if the local calculation of the nonce matches the
3717 * client-provided value and the timestamp is recent enough.
3719 static int validate_nonce(
3720 const char * pnonce,
3721 struct recvbuf * rbufp
3731 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed))
3734 ts.l_ui = (u_int32)ts_i;
3735 ts.l_uf = (u_int32)ts_f;
3736 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf);
3737 get_systime(&now_delta);
3738 L_SUB(&now_delta, &ts);
3740 return (supposed == derived && now_delta.l_ui < 16);
3745 * send_random_tag_value - send a randomly-generated three character
3746 * tag prefix, a '.', an index, a '=' and a
3747 * random integer value.
3749 * To try to force clients to ignore unrecognized tags in mrulist,
3750 * reslist, and ifstats responses, the first and last rows are spiced
3751 * with randomly-generated tag names with correct .# index. Make it
3752 * three characters knowing that none of the currently-used subscripted
3753 * tags have that length, avoiding the need to test for
3757 send_random_tag_value(
3764 noise = rand() ^ (rand() << 16);
3765 buf[0] = 'a' + noise % 26;
3767 buf[1] = 'a' + noise % 26;
3769 buf[2] = 'a' + noise % 26;
3772 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx);
3773 ctl_putuint(buf, noise);
3778 * Send a MRU list entry in response to a "ntpq -c mrulist" operation.
3780 * To keep clients honest about not depending on the order of values,
3781 * and thereby avoid being locked into ugly workarounds to maintain
3782 * backward compatibility later as new fields are added to the response,
3783 * the order is random.
3791 const char first_fmt[] = "first.%d";
3792 const char ct_fmt[] = "ct.%d";
3793 const char mv_fmt[] = "mv.%d";
3794 const char rs_fmt[] = "rs.%d";
3796 u_char sent[6]; /* 6 tag=value pairs */
3802 remaining = COUNTOF(sent);
3804 noise = (u_int32)(rand() ^ (rand() << 16));
3805 while (remaining > 0) {
3806 which = (noise & 7) % COUNTOF(sent);
3809 which = (which + 1) % COUNTOF(sent);
3814 snprintf(tag, sizeof(tag), addr_fmt, count);
3815 pch = sptoa(&mon->rmtadr);
3816 ctl_putunqstr(tag, pch, strlen(pch));
3820 snprintf(tag, sizeof(tag), last_fmt, count);
3821 ctl_putts(tag, &mon->last);
3825 snprintf(tag, sizeof(tag), first_fmt, count);
3826 ctl_putts(tag, &mon->first);
3830 snprintf(tag, sizeof(tag), ct_fmt, count);
3831 ctl_putint(tag, mon->count);
3835 snprintf(tag, sizeof(tag), mv_fmt, count);
3836 ctl_putuint(tag, mon->vn_mode);
3840 snprintf(tag, sizeof(tag), rs_fmt, count);
3841 ctl_puthex(tag, mon->flags);
3851 * read_mru_list - supports ntpq's mrulist command.
3853 * The challenge here is to match ntpdc's monlist functionality without
3854 * being limited to hundreds of entries returned total, and without
3855 * requiring state on the server. If state were required, ntpq's
3856 * mrulist command would require authentication.
3858 * The approach was suggested by Ry Jones. A finite and variable number
3859 * of entries are retrieved per request, to avoid having responses with
3860 * such large numbers of packets that socket buffers are overflowed and
3861 * packets lost. The entries are retrieved oldest-first, taking into
3862 * account that the MRU list will be changing between each request. We
3863 * can expect to see duplicate entries for addresses updated in the MRU
3864 * list during the fetch operation. In the end, the client can assemble
3865 * a close approximation of the MRU list at the point in time the last
3866 * response was sent by ntpd. The only difference is it may be longer,
3867 * containing some number of oldest entries which have since been
3868 * reclaimed. If necessary, the protocol could be extended to zap those
3869 * from the client snapshot at the end, but so far that doesn't seem
3872 * To accomodate the changing MRU list, the starting point for requests
3873 * after the first request is supplied as a series of last seen
3874 * timestamps and associated addresses, the newest ones the client has
3875 * received. As long as at least one of those entries hasn't been
3876 * bumped to the head of the MRU list, ntpd can pick up at that point.
3877 * Otherwise, the request is failed and it is up to ntpq to back up and
3878 * provide the next newest entry's timestamps and addresses, conceivably
3879 * backing up all the way to the starting point.
3882 * nonce= Regurgitated nonce retrieved by the client
3883 * previously using CTL_OP_REQ_NONCE, demonstrating
3884 * ability to receive traffic sent to its address.
3885 * frags= Limit on datagrams (fragments) in response. Used
3886 * by newer ntpq versions instead of limit= when
3887 * retrieving multiple entries.
3888 * limit= Limit on MRU entries returned. One of frags= or
3889 * limit= must be provided.
3890 * limit=1 is a special case: Instead of fetching
3891 * beginning with the supplied starting point's
3892 * newer neighbor, fetch the supplied entry, and
3893 * in that case the #.last timestamp can be zero.
3894 * This enables fetching a single entry by IP
3895 * address. When limit is not one and frags= is
3896 * provided, the fragment limit controls.
3897 * mincount= (decimal) Return entries with count >= mincount.
3898 * laddr= Return entries associated with the server's IP
3899 * address given. No port specification is needed,
3900 * and any supplied is ignored.
3901 * resall= 0x-prefixed hex restrict bits which must all be
3902 * lit for an MRU entry to be included.
3903 * Has precedence over any resany=.
3904 * resany= 0x-prefixed hex restrict bits, at least one of
3905 * which must be list for an MRU entry to be
3907 * last.0= 0x-prefixed hex l_fp timestamp of newest entry
3908 * which client previously received.
3909 * addr.0= text of newest entry's IP address and port,
3910 * IPv6 addresses in bracketed form: [::]:123
3911 * last.1= timestamp of 2nd newest entry client has.
3912 * addr.1= address of 2nd newest entry.
3915 * ntpq provides as many last/addr pairs as will fit in a single request
3916 * packet, except for the first request in a MRU fetch operation.
3918 * The response begins with a new nonce value to be used for any
3919 * followup request. Following the nonce is the next newer entry than
3920 * referred to by last.0 and addr.0, if the "0" entry has not been
3921 * bumped to the front. If it has, the first entry returned will be the
3922 * next entry newer than referred to by last.1 and addr.1, and so on.
3923 * If none of the referenced entries remain unchanged, the request fails
3924 * and ntpq backs up to the next earlier set of entries to resync.
3926 * Except for the first response, the response begins with confirmation
3927 * of the entry that precedes the first additional entry provided:
3929 * last.older= hex l_fp timestamp matching one of the input
3930 * .last timestamps, which entry now precedes the
3931 * response 0. entry in the MRU list.
3932 * addr.older= text of address corresponding to older.last.
3934 * And in any case, a successful response contains sets of values
3935 * comprising entries, with the oldest numbered 0 and incrementing from
3938 * addr.# text of IPv4 or IPv6 address and port
3939 * last.# hex l_fp timestamp of last receipt
3940 * first.# hex l_fp timestamp of first receipt
3941 * ct.# count of packets received
3942 * mv.# mode and version
3943 * rs.# restriction mask (RES_* bits)
3945 * Note the code currently assumes there are no valid three letter
3946 * tags sent with each row, and needs to be adjusted if that changes.
3948 * The client should accept the values in any order, and ignore .#
3949 * values which it does not understand, to allow a smooth path to
3950 * future changes without requiring a new opcode. Clients can rely
3951 * on all *.0 values preceding any *.1 values, that is all values for
3952 * a given index number are together in the response.
3954 * The end of the response list is noted with one or two tag=value
3955 * pairs. Unconditionally:
3957 * now= 0x-prefixed l_fp timestamp at the server marking
3958 * the end of the operation.
3960 * If any entries were returned, now= is followed by:
3962 * last.newest= hex l_fp identical to last.# of the prior
3965 static void read_mru_list(
3966 struct recvbuf *rbufp,
3970 static const char nulltxt[1] = { '\0' };
3971 static const char nonce_text[] = "nonce";
3972 static const char frags_text[] = "frags";
3973 static const char limit_text[] = "limit";
3974 static const char mincount_text[] = "mincount";
3975 static const char resall_text[] = "resall";
3976 static const char resany_text[] = "resany";
3977 static const char maxlstint_text[] = "maxlstint";
3978 static const char laddr_text[] = "laddr";
3979 static const char resaxx_fmt[] = "0x%hx";
3988 struct interface * lcladr;
3993 sockaddr_u addr[COUNTOF(last)];
3995 struct ctl_var * in_parms;
3996 const struct ctl_var * v;
4005 mon_entry * prior_mon;
4008 if (RES_NOMRULIST & restrict_mask) {
4009 ctl_error(CERR_PERMISSION);
4012 "mrulist from %s rejected due to nomrulist restriction",
4013 stoa(&rbufp->recv_srcadr));
4018 * fill in_parms var list with all possible input parameters.
4021 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0);
4022 set_var(&in_parms, frags_text, sizeof(frags_text), 0);
4023 set_var(&in_parms, limit_text, sizeof(limit_text), 0);
4024 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0);
4025 set_var(&in_parms, resall_text, sizeof(resall_text), 0);
4026 set_var(&in_parms, resany_text, sizeof(resany_text), 0);
4027 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0);
4028 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0);
4029 for (i = 0; i < COUNTOF(last); i++) {
4030 snprintf(buf, sizeof(buf), last_fmt, (int)i);
4031 set_var(&in_parms, buf, strlen(buf) + 1, 0);
4032 snprintf(buf, sizeof(buf), addr_fmt, (int)i);
4033 set_var(&in_parms, buf, strlen(buf) + 1, 0);
4036 /* decode input parms */
4049 /* have to go through '(void*)' to drop 'const' property from pointer.
4050 * ctl_getitem()' needs some cleanup, too.... perlinger@ntp.org
4052 while (NULL != (v = ctl_getitem(in_parms, (void*)&val)) &&
4053 !(EOV & v->flags)) {
4059 if (!strcmp(nonce_text, v->text)) {
4061 pnonce = (*val) ? estrdup(val) : NULL;
4062 } else if (!strcmp(frags_text, v->text)) {
4063 if (1 != sscanf(val, "%hu", &frags))
4065 } else if (!strcmp(limit_text, v->text)) {
4066 if (1 != sscanf(val, "%u", &limit))
4068 } else if (!strcmp(mincount_text, v->text)) {
4069 if (1 != sscanf(val, "%d", &mincount))
4073 } else if (!strcmp(resall_text, v->text)) {
4074 if (1 != sscanf(val, resaxx_fmt, &resall))
4076 } else if (!strcmp(resany_text, v->text)) {
4077 if (1 != sscanf(val, resaxx_fmt, &resany))
4079 } else if (!strcmp(maxlstint_text, v->text)) {
4080 if (1 != sscanf(val, "%u", &maxlstint))
4082 } else if (!strcmp(laddr_text, v->text)) {
4083 if (!decodenetnum(val, &laddr))
4085 lcladr = getinterface(&laddr, 0);
4086 } else if (1 == sscanf(v->text, last_fmt, &si) &&
4087 (size_t)si < COUNTOF(last)) {
4088 if (2 != sscanf(val, "0x%08x.%08x", &ui, &uf))
4092 if (!SOCK_UNSPEC(&addr[si]) && si == priors)
4094 } else if (1 == sscanf(v->text, addr_fmt, &si) &&
4095 (size_t)si < COUNTOF(addr)) {
4096 if (!decodenetnum(val, &addr[si]))
4098 if (last[si].l_ui && last[si].l_uf && si == priors)
4101 DPRINTF(1, ("read_mru_list: invalid key item: '%s' (ignored)\n",
4106 DPRINTF(1, ("read_mru_list: invalid param for '%s': '%s' (bailing)\n",
4113 free_varlist(in_parms);
4116 /* return no responses until the nonce is validated */
4120 nonce_valid = validate_nonce(pnonce, rbufp);
4125 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) ||
4126 frags > MRU_FRAGS_LIMIT) {
4127 ctl_error(CERR_BADVALUE);
4132 * If either frags or limit is not given, use the max.
4134 if (0 != frags && 0 == limit)
4136 else if (0 != limit && 0 == frags)
4137 frags = MRU_FRAGS_LIMIT;
4140 * Find the starting point if one was provided.
4143 for (i = 0; i < (size_t)priors; i++) {
4144 hash = MON_HASH(&addr[i]);
4145 for (mon = mon_hash[hash];
4147 mon = mon->hash_next)
4148 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i]))
4151 if (L_ISEQU(&mon->last, &last[i]))
4157 /* If a starting point was provided... */
4159 /* and none could be found unmodified... */
4161 /* tell ntpq to try again with older entries */
4162 ctl_error(CERR_UNKNOWNVAR);
4165 /* confirm the prior entry used as starting point */
4166 ctl_putts("last.older", &mon->last);
4167 pch = sptoa(&mon->rmtadr);
4168 ctl_putunqstr("addr.older", pch, strlen(pch));
4171 * Move on to the first entry the client doesn't have,
4172 * except in the special case of a limit of one. In
4173 * that case return the starting point entry.
4176 mon = PREV_DLIST(mon_mru_list, mon, mru);
4177 } else { /* start with the oldest */
4178 mon = TAIL_DLIST(mon_mru_list, mru);
4182 * send up to limit= entries in up to frags= datagrams
4185 generate_nonce(rbufp, buf, sizeof(buf));
4186 ctl_putunqstr("nonce", buf, strlen(buf));
4189 mon != NULL && res_frags < frags && count < limit;
4190 mon = PREV_DLIST(mon_mru_list, mon, mru)) {
4192 if (mon->count < mincount)
4194 if (resall && resall != (resall & mon->flags))
4196 if (resany && !(resany & mon->flags))
4198 if (maxlstint > 0 && now.l_ui - mon->last.l_ui >
4201 if (lcladr != NULL && mon->lcladr != lcladr)
4204 send_mru_entry(mon, count);
4206 send_random_tag_value(0);
4212 * If this batch completes the MRU list, say so explicitly with
4213 * a now= l_fp timestamp.
4217 send_random_tag_value(count - 1);
4218 ctl_putts("now", &now);
4219 /* if any entries were returned confirm the last */
4220 if (prior_mon != NULL)
4221 ctl_putts("last.newest", &prior_mon->last);
4228 * Send a ifstats entry in response to a "ntpq -c ifstats" request.
4230 * To keep clients honest about not depending on the order of values,
4231 * and thereby avoid being locked into ugly workarounds to maintain
4232 * backward compatibility later as new fields are added to the response,
4233 * the order is random.
4241 const char addr_fmtu[] = "addr.%u";
4242 const char bcast_fmt[] = "bcast.%u";
4243 const char en_fmt[] = "en.%u"; /* enabled */
4244 const char name_fmt[] = "name.%u";
4245 const char flags_fmt[] = "flags.%u";
4246 const char tl_fmt[] = "tl.%u"; /* ttl */
4247 const char mc_fmt[] = "mc.%u"; /* mcast count */
4248 const char rx_fmt[] = "rx.%u";
4249 const char tx_fmt[] = "tx.%u";
4250 const char txerr_fmt[] = "txerr.%u";
4251 const char pc_fmt[] = "pc.%u"; /* peer count */
4252 const char up_fmt[] = "up.%u"; /* uptime */
4254 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */
4261 remaining = COUNTOF(sent);
4265 while (remaining > 0) {
4266 if (noisebits < 4) {
4267 noise = rand() ^ (rand() << 16);
4270 which = (noise & 0xf) % COUNTOF(sent);
4275 which = (which + 1) % COUNTOF(sent);
4280 snprintf(tag, sizeof(tag), addr_fmtu, ifnum);
4281 pch = sptoa(&la->sin);
4282 ctl_putunqstr(tag, pch, strlen(pch));
4286 snprintf(tag, sizeof(tag), bcast_fmt, ifnum);
4287 if (INT_BCASTOPEN & la->flags)
4288 pch = sptoa(&la->bcast);
4291 ctl_putunqstr(tag, pch, strlen(pch));
4295 snprintf(tag, sizeof(tag), en_fmt, ifnum);
4296 ctl_putint(tag, !la->ignore_packets);
4300 snprintf(tag, sizeof(tag), name_fmt, ifnum);
4301 ctl_putstr(tag, la->name, strlen(la->name));
4305 snprintf(tag, sizeof(tag), flags_fmt, ifnum);
4306 ctl_puthex(tag, (u_int)la->flags);
4310 snprintf(tag, sizeof(tag), tl_fmt, ifnum);
4311 ctl_putint(tag, la->last_ttl);
4315 snprintf(tag, sizeof(tag), mc_fmt, ifnum);
4316 ctl_putint(tag, la->num_mcast);
4320 snprintf(tag, sizeof(tag), rx_fmt, ifnum);
4321 ctl_putint(tag, la->received);
4325 snprintf(tag, sizeof(tag), tx_fmt, ifnum);
4326 ctl_putint(tag, la->sent);
4330 snprintf(tag, sizeof(tag), txerr_fmt, ifnum);
4331 ctl_putint(tag, la->notsent);
4335 snprintf(tag, sizeof(tag), pc_fmt, ifnum);
4336 ctl_putuint(tag, la->peercnt);
4340 snprintf(tag, sizeof(tag), up_fmt, ifnum);
4341 ctl_putuint(tag, current_time - la->starttime);
4347 send_random_tag_value((int)ifnum);
4352 * read_ifstats - send statistics for each local address, exposed by
4357 struct recvbuf * rbufp
4364 * loop over [0..sys_ifnum] searching ep_list for each
4367 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) {
4368 for (la = ep_list; la != NULL; la = la->elink)
4369 if (ifidx == la->ifnum)
4373 /* return stats for one local address */
4374 send_ifstats_entry(la, ifidx);
4380 sockaddrs_from_restrict_u(
4390 psaA->sa.sa_family = AF_INET;
4391 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr);
4392 psaM->sa.sa_family = AF_INET;
4393 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask);
4395 psaA->sa.sa_family = AF_INET6;
4396 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr,
4397 sizeof(psaA->sa6.sin6_addr));
4398 psaM->sa.sa_family = AF_INET6;
4399 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask,
4400 sizeof(psaA->sa6.sin6_addr));
4406 * Send a restrict entry in response to a "ntpq -c reslist" request.
4408 * To keep clients honest about not depending on the order of values,
4409 * and thereby avoid being locked into ugly workarounds to maintain
4410 * backward compatibility later as new fields are added to the response,
4411 * the order is random.
4414 send_restrict_entry(
4420 const char addr_fmtu[] = "addr.%u";
4421 const char mask_fmtu[] = "mask.%u";
4422 const char hits_fmt[] = "hits.%u";
4423 const char flags_fmt[] = "flags.%u";
4425 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */
4434 const char * match_str;
4435 const char * access_str;
4437 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6);
4438 remaining = COUNTOF(sent);
4442 while (remaining > 0) {
4443 if (noisebits < 2) {
4444 noise = rand() ^ (rand() << 16);
4447 which = (noise & 0x3) % COUNTOF(sent);
4452 which = (which + 1) % COUNTOF(sent);
4454 /* XXX: Numbers? Really? */
4458 snprintf(tag, sizeof(tag), addr_fmtu, idx);
4460 ctl_putunqstr(tag, pch, strlen(pch));
4464 snprintf(tag, sizeof(tag), mask_fmtu, idx);
4466 ctl_putunqstr(tag, pch, strlen(pch));
4470 snprintf(tag, sizeof(tag), hits_fmt, idx);
4471 ctl_putuint(tag, pres->count);
4475 snprintf(tag, sizeof(tag), flags_fmt, idx);
4476 match_str = res_match_flags(pres->mflags);
4477 access_str = res_access_flags(pres->rflags);
4478 if ('\0' == match_str[0]) {
4482 snprintf(buf, LIB_BUFLENGTH, "%s %s",
4483 match_str, access_str);
4486 ctl_putunqstr(tag, pch, strlen(pch));
4492 send_random_tag_value((int)idx);
4503 for ( ; pres != NULL; pres = pres->link) {
4504 send_restrict_entry(pres, ipv6, *pidx);
4511 * read_addr_restrictions - returns IPv4 and IPv6 access control lists
4514 read_addr_restrictions(
4515 struct recvbuf * rbufp
4521 send_restrict_list(restrictlist4, FALSE, &idx);
4522 send_restrict_list(restrictlist6, TRUE, &idx);
4528 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist
4532 struct recvbuf * rbufp,
4536 const char ifstats_s[] = "ifstats";
4537 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1;
4538 const char addr_rst_s[] = "addr_restrictions";
4539 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1;
4540 struct ntp_control * cpkt;
4541 u_short qdata_octets;
4544 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and
4545 * used only for ntpq -c ifstats. With the addition of reslist
4546 * the same opcode was generalized to retrieve ordered lists
4547 * which require authentication. The request data is empty or
4548 * contains "ifstats" (not null terminated) to retrieve local
4549 * addresses and associated stats. It is "addr_restrictions"
4550 * to retrieve the IPv4 then IPv6 remote address restrictions,
4551 * which are access control lists. Other request data return
4554 cpkt = (struct ntp_control *)&rbufp->recv_pkt;
4555 qdata_octets = ntohs(cpkt->count);
4556 if (0 == qdata_octets || (ifstats_chars == qdata_octets &&
4557 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) {
4558 read_ifstats(rbufp);
4561 if (a_r_chars == qdata_octets &&
4562 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) {
4563 read_addr_restrictions(rbufp);
4566 ctl_error(CERR_UNKNOWNVAR);
4571 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite.
4573 static void req_nonce(
4574 struct recvbuf * rbufp,
4580 generate_nonce(rbufp, buf, sizeof(buf));
4581 ctl_putunqstr("nonce", buf, strlen(buf));
4587 * read_clockstatus - return clock radio status
4592 struct recvbuf *rbufp,
4598 * If no refclock support, no data to return
4600 ctl_error(CERR_BADASSOC);
4602 const struct ctl_var * v;
4610 struct ctl_var * kv;
4611 struct refclockstat cs;
4613 if (res_associd != 0) {
4614 peer = findpeerbyassoc(res_associd);
4617 * Find a clock for this jerk. If the system peer
4618 * is a clock use it, else search peer_list for one.
4620 if (sys_peer != NULL && (FLAG_REFCLOCK &
4624 for (peer = peer_list;
4626 peer = peer->p_link)
4627 if (FLAG_REFCLOCK & peer->flags)
4630 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) {
4631 ctl_error(CERR_BADASSOC);
4635 * If we got here we have a peer which is a clock. Get his
4639 refclock_control(&peer->srcadr, NULL, &cs);
4642 * Look for variables in the packet.
4644 rpkt.status = htons(ctlclkstatus(&cs));
4645 wants_alloc = CC_MAXCODE + 1 + count_var(kv);
4646 wants = emalloc_zero(wants_alloc);
4648 while (NULL != (v = ctl_getitem(clock_var, &valuep))) {
4649 if (!(EOV & v->flags)) {
4650 wants[v->code] = TRUE;
4653 v = ctl_getitem(kv, &valuep);
4655 ctl_error(CERR_BADVALUE);
4657 free_varlist(cs.kv_list);
4660 if (EOV & v->flags) {
4661 ctl_error(CERR_UNKNOWNVAR);
4663 free_varlist(cs.kv_list);
4666 wants[CC_MAXCODE + 1 + v->code] = TRUE;
4672 for (i = 1; i <= CC_MAXCODE; i++)
4674 ctl_putclock(i, &cs, TRUE);
4676 for (i = 0; !(EOV & kv[i].flags); i++)
4677 if (wants[i + CC_MAXCODE + 1])
4678 ctl_putdata(kv[i].text,
4682 for (cc = def_clock_var; *cc != 0; cc++)
4683 ctl_putclock((int)*cc, &cs, FALSE);
4684 for ( ; kv != NULL && !(EOV & kv->flags); kv++)
4685 if (DEF & kv->flags)
4686 ctl_putdata(kv->text, strlen(kv->text),
4691 free_varlist(cs.kv_list);
4699 * write_clockstatus - we don't do this
4704 struct recvbuf *rbufp,
4708 ctl_error(CERR_PERMISSION);
4712 * Trap support from here on down. We send async trap messages when the
4713 * upper levels report trouble. Traps can by set either by control
4714 * messages or by configuration.
4717 * set_trap - set a trap in response to a control message
4721 struct recvbuf *rbufp,
4728 * See if this guy is allowed
4730 if (restrict_mask & RES_NOTRAP) {
4731 ctl_error(CERR_PERMISSION);
4736 * Determine his allowed trap type.
4738 traptype = TRAP_TYPE_PRIO;
4739 if (restrict_mask & RES_LPTRAP)
4740 traptype = TRAP_TYPE_NONPRIO;
4743 * Call ctlsettrap() to do the work. Return
4744 * an error if it can't assign the trap.
4746 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype,
4748 ctl_error(CERR_NORESOURCE);
4754 * unset_trap - unset a trap in response to a control message
4758 struct recvbuf *rbufp,
4765 * We don't prevent anyone from removing his own trap unless the
4766 * trap is configured. Note we also must be aware of the
4767 * possibility that restriction flags were changed since this
4768 * guy last set his trap. Set the trap type based on this.
4770 traptype = TRAP_TYPE_PRIO;
4771 if (restrict_mask & RES_LPTRAP)
4772 traptype = TRAP_TYPE_NONPRIO;
4775 * Call ctlclrtrap() to clear this out.
4777 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype))
4778 ctl_error(CERR_BADASSOC);
4784 * ctlsettrap - called to set a trap
4789 struct interface *linter,
4795 struct ctl_trap *tp;
4796 struct ctl_trap *tptouse;
4799 * See if we can find this trap. If so, we only need update
4800 * the flags and the time.
4802 if ((tp = ctlfindtrap(raddr, linter)) != NULL) {
4805 case TRAP_TYPE_CONFIG:
4806 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED;
4809 case TRAP_TYPE_PRIO:
4810 if (tp->tr_flags & TRAP_CONFIGURED)
4811 return (1); /* don't change anything */
4812 tp->tr_flags = TRAP_INUSE;
4815 case TRAP_TYPE_NONPRIO:
4816 if (tp->tr_flags & TRAP_CONFIGURED)
4817 return (1); /* don't change anything */
4818 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO;
4821 tp->tr_settime = current_time;
4827 * First we heard of this guy. Try to find a trap structure
4828 * for him to use, clearing out lesser priority guys if we
4829 * have to. Clear out anyone who's expired while we're at it.
4832 for (n = 0; n < COUNTOF(ctl_traps); n++) {
4834 if ((TRAP_INUSE & tp->tr_flags) &&
4835 !(TRAP_CONFIGURED & tp->tr_flags) &&
4836 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) {
4840 if (!(TRAP_INUSE & tp->tr_flags)) {
4842 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) {
4845 case TRAP_TYPE_CONFIG:
4846 if (tptouse == NULL) {
4850 if ((TRAP_NONPRIO & tptouse->tr_flags) &&
4851 !(TRAP_NONPRIO & tp->tr_flags))
4854 if (!(TRAP_NONPRIO & tptouse->tr_flags)
4855 && (TRAP_NONPRIO & tp->tr_flags)) {
4859 if (tptouse->tr_origtime <
4864 case TRAP_TYPE_PRIO:
4865 if ( TRAP_NONPRIO & tp->tr_flags) {
4866 if (tptouse == NULL ||
4868 tptouse->tr_flags) &&
4869 tptouse->tr_origtime <
4875 case TRAP_TYPE_NONPRIO:
4882 * If we don't have room for him return an error.
4884 if (tptouse == NULL)
4888 * Set up this structure for him.
4890 tptouse->tr_settime = tptouse->tr_origtime = current_time;
4891 tptouse->tr_count = tptouse->tr_resets = 0;
4892 tptouse->tr_sequence = 1;
4893 tptouse->tr_addr = *raddr;
4894 tptouse->tr_localaddr = linter;
4895 tptouse->tr_version = (u_char) version;
4896 tptouse->tr_flags = TRAP_INUSE;
4897 if (traptype == TRAP_TYPE_CONFIG)
4898 tptouse->tr_flags |= TRAP_CONFIGURED;
4899 else if (traptype == TRAP_TYPE_NONPRIO)
4900 tptouse->tr_flags |= TRAP_NONPRIO;
4907 * ctlclrtrap - called to clear a trap
4912 struct interface *linter,
4916 register struct ctl_trap *tp;
4918 if ((tp = ctlfindtrap(raddr, linter)) == NULL)
4921 if (tp->tr_flags & TRAP_CONFIGURED
4922 && traptype != TRAP_TYPE_CONFIG)
4932 * ctlfindtrap - find a trap given the remote and local addresses
4934 static struct ctl_trap *
4937 struct interface *linter
4942 for (n = 0; n < COUNTOF(ctl_traps); n++)
4943 if ((ctl_traps[n].tr_flags & TRAP_INUSE)
4944 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr)
4945 && (linter == ctl_traps[n].tr_localaddr))
4946 return &ctl_traps[n];
4953 * report_event - report an event to the trappers
4957 int err, /* error code */
4958 struct peer *peer, /* peer structure pointer */
4959 const char *str /* protostats string */
4962 char statstr[NTP_MAXSTRLEN];
4967 * Report the error to the protostats file, system log and
4973 * Discard a system report if the number of reports of
4974 * the same type exceeds the maximum.
4976 if (ctl_sys_last_event != (u_char)err)
4977 ctl_sys_num_events= 0;
4978 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS)
4981 ctl_sys_last_event = (u_char)err;
4982 ctl_sys_num_events++;
4983 snprintf(statstr, sizeof(statstr),
4984 "0.0.0.0 %04x %02x %s",
4985 ctlsysstatus(), err, eventstr(err));
4987 len = strlen(statstr);
4988 snprintf(statstr + len, sizeof(statstr) - len,
4992 msyslog(LOG_INFO, "%s", statstr);
4996 * Discard a peer report if the number of reports of
4997 * the same type exceeds the maximum for that peer.
5002 errlast = (u_char)err & ~PEER_EVENT;
5003 if (peer->last_event != errlast)
5004 peer->num_events = 0;
5005 if (peer->num_events >= CTL_PEER_MAXEVENTS)
5008 peer->last_event = errlast;
5010 if (ISREFCLOCKADR(&peer->srcadr))
5011 src = refnumtoa(&peer->srcadr);
5013 src = stoa(&peer->srcadr);
5015 snprintf(statstr, sizeof(statstr),
5016 "%s %04x %02x %s", src,
5017 ctlpeerstatus(peer), err, eventstr(err));
5019 len = strlen(statstr);
5020 snprintf(statstr + len, sizeof(statstr) - len,
5023 NLOG(NLOG_PEEREVENT)
5024 msyslog(LOG_INFO, "%s", statstr);
5026 record_proto_stats(statstr);
5029 printf("event at %lu %s\n", current_time, statstr);
5033 * If no trappers, return.
5035 if (num_ctl_traps <= 0)
5039 * Peer Events should be associated with a peer -- hence the
5040 * name. But there are instances where this function is called
5041 * *without* a valid peer. This happens e.g. with an unsolicited
5042 * CryptoNAK, or when a leap second alarm is going off while
5043 * currently without a system peer.
5045 * The most sensible approach to this seems to bail out here if
5046 * this happens. Avoiding to call this function would also
5047 * bypass the log reporting in the first part of this function,
5048 * and this is probably not the best of all options.
5049 * -*-perlinger@ntp.org-*-
5051 if ((err & PEER_EVENT) && !peer)
5055 * Set up the outgoing packet variables
5057 res_opcode = CTL_OP_ASYNCMSG;
5060 res_authenticate = FALSE;
5061 datapt = rpkt.u.data;
5062 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN];
5063 if (!(err & PEER_EVENT)) {
5065 rpkt.status = htons(ctlsysstatus());
5067 /* Include the core system variables and the list. */
5068 for (i = 1; i <= CS_VARLIST; i++)
5070 } else if (NULL != peer) { /* paranoia -- skip output */
5071 rpkt.associd = htons(peer->associd);
5072 rpkt.status = htons(ctlpeerstatus(peer));
5074 /* Dump it all. Later, maybe less. */
5075 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++)
5076 ctl_putpeer(i, peer);
5079 * for clock exception events: add clock variables to
5080 * reflect info on exception
5082 if (err == PEVNT_CLOCK) {
5083 struct refclockstat cs;
5087 refclock_control(&peer->srcadr, NULL, &cs);
5089 ctl_puthex("refclockstatus",
5092 for (i = 1; i <= CC_MAXCODE; i++)
5093 ctl_putclock(i, &cs, FALSE);
5094 for (kv = cs.kv_list;
5095 kv != NULL && !(EOV & kv->flags);
5097 if (DEF & kv->flags)
5098 ctl_putdata(kv->text,
5101 free_varlist(cs.kv_list);
5103 # endif /* REFCLOCK */
5107 * We're done, return.
5114 * mprintf_event - printf-style varargs variant of report_event()
5118 int evcode, /* event code */
5119 struct peer * p, /* may be NULL */
5120 const char * fmt, /* msnprintf format */
5129 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
5131 report_event(evcode, p, msg);
5138 * ctl_clr_stats - clear stat counters
5143 ctltimereset = current_time;
5146 numctlresponses = 0;
5151 numctlinputresp = 0;
5152 numctlinputfrag = 0;
5154 numctlbadoffset = 0;
5155 numctlbadversion = 0;
5156 numctldatatooshort = 0;
5163 const struct ctl_var *k
5172 while (!(EOV & (k++)->flags))
5175 ENSURE(c <= USHRT_MAX);
5182 struct ctl_var **kv,
5192 *kv = erealloc(*kv, (c + 2) * sizeof(**kv));
5194 buf = emalloc(size);
5199 k[c + 1].text = NULL;
5200 k[c + 1].flags = EOV;
5208 struct ctl_var **kv,
5219 if (NULL == data || !size)
5224 while (!(EOV & k->flags)) {
5225 if (NULL == k->text) {
5227 memcpy(td, data, size);
5234 while (*t != '=' && *s == *t) {
5238 if (*s == *t && ((*t == '=') || !*t)) {
5239 td = erealloc((void *)(intptr_t)k->text, size);
5240 memcpy(td, data, size);
5249 td = add_var(kv, size, def);
5250 memcpy(td, data, size);
5261 set_var(&ext_sys_var, data, size, def);
5266 * get_ext_sys_var() retrieves the value of a user-defined variable or
5267 * NULL if the variable has not been setvar'd.
5270 get_ext_sys_var(const char *tag)
5278 for (v = ext_sys_var; !(EOV & v->flags); v++) {
5279 if (NULL != v->text && !memcmp(tag, v->text, c)) {
5280 if ('=' == v->text[c]) {
5281 val = v->text + c + 1;
5283 } else if ('\0' == v->text[c]) {
5301 for (k = kv; !(k->flags & EOV); k++)
5302 free((void *)(intptr_t)k->text);