ntp_control.c revision 309007
1/* 2 * ntp_control.c - respond to mode 6 control messages and send async 3 * traps. Provides service to ntpq and others. 4 */ 5 6#ifdef HAVE_CONFIG_H 7# include <config.h> 8#endif 9 10#include <stdio.h> 11#include <ctype.h> 12#include <signal.h> 13#include <sys/stat.h> 14#ifdef HAVE_NETINET_IN_H 15# include <netinet/in.h> 16#endif 17#include <arpa/inet.h> 18 19#include "ntpd.h" 20#include "ntp_io.h" 21#include "ntp_refclock.h" 22#include "ntp_control.h" 23#include "ntp_unixtime.h" 24#include "ntp_stdlib.h" 25#include "ntp_config.h" 26#include "ntp_crypto.h" 27#include "ntp_assert.h" 28#include "ntp_leapsec.h" 29#include "ntp_md5.h" /* provides OpenSSL digest API */ 30#include "lib_strbuf.h" 31#include <rc_cmdlength.h> 32#ifdef KERNEL_PLL 33# include "ntp_syscall.h" 34#endif 35 36#include "libssl_compat.h" 37 38/* 39 * Structure to hold request procedure information 40 */ 41 42struct ctl_proc { 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. */ 47#define NOAUTH 0 48#define AUTH 1 49 void (*handler) (struct recvbuf *, int); /* handle request */ 50}; 51 52 53/* 54 * Request processing routines 55 */ 56static void ctl_error (u_char); 57#ifdef REFCLOCK 58static u_short ctlclkstatus (struct refclockstat *); 59#endif 60static void ctl_flushpkt (u_char); 61static void ctl_putdata (const char *, unsigned int, int); 62static void ctl_putstr (const char *, const char *, size_t); 63static 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, \ 67 FPTOD(sfp)) 68static void ctl_putuint (const char *, u_long); 69static void ctl_puthex (const char *, u_long); 70static void ctl_putint (const char *, long); 71static void ctl_putts (const char *, l_fp *); 72static void ctl_putadr (const char *, u_int32, 73 sockaddr_u *); 74static void ctl_putrefid (const char *, u_int32); 75static void ctl_putarray (const char *, double *, int); 76static void ctl_putsys (int); 77static void ctl_putpeer (int, struct peer *); 78static void ctl_putfs (const char *, tstamp_t); 79static void ctl_printf (const char *, ...) NTP_PRINTF(1, 2); 80#ifdef REFCLOCK 81static void ctl_putclock (int, struct refclockstat *, int); 82#endif /* REFCLOCK */ 83static const struct ctl_var *ctl_getitem(const struct ctl_var *, 84 char **); 85static u_short count_var (const struct ctl_var *); 86static void control_unspec (struct recvbuf *, int); 87static void read_status (struct recvbuf *, int); 88static void read_sysvars (void); 89static void read_peervars (void); 90static void read_variables (struct recvbuf *, int); 91static void write_variables (struct recvbuf *, int); 92static void read_clockstatus(struct recvbuf *, int); 93static void write_clockstatus(struct recvbuf *, int); 94static void set_trap (struct recvbuf *, int); 95static void save_config (struct recvbuf *, int); 96static void configure (struct recvbuf *, int); 97static void send_mru_entry (mon_entry *, int); 98static void send_random_tag_value(int); 99static void read_mru_list (struct recvbuf *, int); 100static void send_ifstats_entry(endpt *, u_int); 101static void read_ifstats (struct recvbuf *); 102static void sockaddrs_from_restrict_u(sockaddr_u *, sockaddr_u *, 103 restrict_u *, int); 104static void send_restrict_entry(restrict_u *, int, u_int); 105static void send_restrict_list(restrict_u *, int, u_int *); 106static void read_addr_restrictions(struct recvbuf *); 107static void read_ordlist (struct recvbuf *, int); 108static u_int32 derive_nonce (sockaddr_u *, u_int32, u_int32); 109static void generate_nonce (struct recvbuf *, char *, size_t); 110static int validate_nonce (const char *, struct recvbuf *); 111static void req_nonce (struct recvbuf *, int); 112static void unset_trap (struct recvbuf *, int); 113static struct ctl_trap *ctlfindtrap(sockaddr_u *, 114 struct interface *); 115 116int/*BOOL*/ is_safe_filename(const char * name); 117 118static 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 } 133}; 134 135/* 136 * System variables we understand 137 */ 138#define CS_LEAP 1 139#define CS_STRATUM 2 140#define CS_PRECISION 3 141#define CS_ROOTDELAY 4 142#define CS_ROOTDISPERSION 5 143#define CS_REFID 6 144#define CS_REFTIME 7 145#define CS_POLL 8 146#define CS_PEERID 9 147#define CS_OFFSET 10 148#define CS_DRIFT 11 149#define CS_JITTER 12 150#define CS_ERROR 13 151#define CS_CLOCK 14 152#define CS_PROCESSOR 15 153#define CS_SYSTEM 16 154#define CS_VERSION 17 155#define CS_STABIL 18 156#define CS_VARLIST 19 157#define CS_TAI 20 158#define CS_LEAPTAB 21 159#define CS_LEAPEND 22 160#define CS_RATE 23 161#define CS_MRU_ENABLED 24 162#define CS_MRU_DEPTH 25 163#define CS_MRU_DEEPEST 26 164#define CS_MRU_MINDEPTH 27 165#define CS_MRU_MAXAGE 28 166#define CS_MRU_MAXDEPTH 29 167#define CS_MRU_MEM 30 168#define CS_MRU_MAXMEM 31 169#define CS_SS_UPTIME 32 170#define CS_SS_RESET 33 171#define CS_SS_RECEIVED 34 172#define CS_SS_THISVER 35 173#define CS_SS_OLDVER 36 174#define CS_SS_BADFORMAT 37 175#define CS_SS_BADAUTH 38 176#define CS_SS_DECLINED 39 177#define CS_SS_RESTRICTED 40 178#define CS_SS_LIMITED 41 179#define CS_SS_KODSENT 42 180#define CS_SS_PROCESSED 43 181#define CS_PEERADR 44 182#define CS_PEERMODE 45 183#define CS_BCASTDELAY 46 184#define CS_AUTHDELAY 47 185#define CS_AUTHKEYS 48 186#define CS_AUTHFREEK 49 187#define CS_AUTHKLOOKUPS 50 188#define CS_AUTHKNOTFOUND 51 189#define CS_AUTHKUNCACHED 52 190#define CS_AUTHKEXPIRED 53 191#define CS_AUTHENCRYPTS 54 192#define CS_AUTHDECRYPTS 55 193#define CS_AUTHRESET 56 194#define CS_K_OFFSET 57 195#define CS_K_FREQ 58 196#define CS_K_MAXERR 59 197#define CS_K_ESTERR 60 198#define CS_K_STFLAGS 61 199#define CS_K_TIMECONST 62 200#define CS_K_PRECISION 63 201#define CS_K_FREQTOL 64 202#define CS_K_PPS_FREQ 65 203#define CS_K_PPS_STABIL 66 204#define CS_K_PPS_JITTER 67 205#define CS_K_PPS_CALIBDUR 68 206#define CS_K_PPS_CALIBS 69 207#define CS_K_PPS_CALIBERRS 70 208#define CS_K_PPS_JITEXC 71 209#define CS_K_PPS_STBEXC 72 210#define CS_KERN_FIRST CS_K_OFFSET 211#define CS_KERN_LAST CS_K_PPS_STBEXC 212#define CS_IOSTATS_RESET 73 213#define CS_TOTAL_RBUF 74 214#define CS_FREE_RBUF 75 215#define CS_USED_RBUF 76 216#define CS_RBUF_LOWATER 77 217#define CS_IO_DROPPED 78 218#define CS_IO_IGNORED 79 219#define CS_IO_RECEIVED 80 220#define CS_IO_SENT 81 221#define CS_IO_SENDFAILED 82 222#define CS_IO_WAKEUPS 83 223#define CS_IO_GOODWAKEUPS 84 224#define CS_TIMERSTATS_RESET 85 225#define CS_TIMER_OVERRUNS 86 226#define CS_TIMER_XMTS 87 227#define CS_FUZZ 88 228#define CS_WANDER_THRESH 89 229#define CS_LEAPSMEARINTV 90 230#define CS_LEAPSMEAROFFS 91 231#define CS_MAX_NOAUTOKEY CS_LEAPSMEAROFFS 232#ifdef AUTOKEY 233#define CS_FLAGS (1 + CS_MAX_NOAUTOKEY) 234#define CS_HOST (2 + CS_MAX_NOAUTOKEY) 235#define CS_PUBLIC (3 + CS_MAX_NOAUTOKEY) 236#define CS_CERTIF (4 + CS_MAX_NOAUTOKEY) 237#define CS_SIGNATURE (5 + CS_MAX_NOAUTOKEY) 238#define CS_REVTIME (6 + CS_MAX_NOAUTOKEY) 239#define CS_IDENT (7 + CS_MAX_NOAUTOKEY) 240#define CS_DIGEST (8 + CS_MAX_NOAUTOKEY) 241#define CS_MAXCODE CS_DIGEST 242#else /* !AUTOKEY follows */ 243#define CS_MAXCODE CS_MAX_NOAUTOKEY 244#endif /* !AUTOKEY */ 245 246/* 247 * Peer variables we understand 248 */ 249#define CP_CONFIG 1 250#define CP_AUTHENABLE 2 251#define CP_AUTHENTIC 3 252#define CP_SRCADR 4 253#define CP_SRCPORT 5 254#define CP_DSTADR 6 255#define CP_DSTPORT 7 256#define CP_LEAP 8 257#define CP_HMODE 9 258#define CP_STRATUM 10 259#define CP_PPOLL 11 260#define CP_HPOLL 12 261#define CP_PRECISION 13 262#define CP_ROOTDELAY 14 263#define CP_ROOTDISPERSION 15 264#define CP_REFID 16 265#define CP_REFTIME 17 266#define CP_ORG 18 267#define CP_REC 19 268#define CP_XMT 20 269#define CP_REACH 21 270#define CP_UNREACH 22 271#define CP_TIMER 23 272#define CP_DELAY 24 273#define CP_OFFSET 25 274#define CP_JITTER 26 275#define CP_DISPERSION 27 276#define CP_KEYID 28 277#define CP_FILTDELAY 29 278#define CP_FILTOFFSET 30 279#define CP_PMODE 31 280#define CP_RECEIVED 32 281#define CP_SENT 33 282#define CP_FILTERROR 34 283#define CP_FLASH 35 284#define CP_TTL 36 285#define CP_VARLIST 37 286#define CP_IN 38 287#define CP_OUT 39 288#define CP_RATE 40 289#define CP_BIAS 41 290#define CP_SRCHOST 42 291#define CP_TIMEREC 43 292#define CP_TIMEREACH 44 293#define CP_BADAUTH 45 294#define CP_BOGUSORG 46 295#define CP_OLDPKT 47 296#define CP_SELDISP 48 297#define CP_SELBROKEN 49 298#define CP_CANDIDATE 50 299#define CP_MAX_NOAUTOKEY CP_CANDIDATE 300#ifdef AUTOKEY 301#define CP_FLAGS (1 + CP_MAX_NOAUTOKEY) 302#define CP_HOST (2 + CP_MAX_NOAUTOKEY) 303#define CP_VALID (3 + CP_MAX_NOAUTOKEY) 304#define CP_INITSEQ (4 + CP_MAX_NOAUTOKEY) 305#define CP_INITKEY (5 + CP_MAX_NOAUTOKEY) 306#define CP_INITTSP (6 + CP_MAX_NOAUTOKEY) 307#define CP_SIGNATURE (7 + CP_MAX_NOAUTOKEY) 308#define CP_IDENT (8 + CP_MAX_NOAUTOKEY) 309#define CP_MAXCODE CP_IDENT 310#else /* !AUTOKEY follows */ 311#define CP_MAXCODE CP_MAX_NOAUTOKEY 312#endif /* !AUTOKEY */ 313 314/* 315 * Clock variables we understand 316 */ 317#define CC_TYPE 1 318#define CC_TIMECODE 2 319#define CC_POLL 3 320#define CC_NOREPLY 4 321#define CC_BADFORMAT 5 322#define CC_BADDATA 6 323#define CC_FUDGETIME1 7 324#define CC_FUDGETIME2 8 325#define CC_FUDGEVAL1 9 326#define CC_FUDGEVAL2 10 327#define CC_FLAGS 11 328#define CC_DEVICE 12 329#define CC_VARLIST 13 330#define CC_MAXCODE CC_VARLIST 331 332/* 333 * System variable values. The array can be indexed by the variable 334 * index to find the textual name. 335 */ 336static const struct ctl_var sys_var[] = { 337 { 0, PADDING, "" }, /* 0 */ 338 { CS_LEAP, RW, "leap" }, /* 1 */ 339 { CS_STRATUM, RO, "stratum" }, /* 2 */ 340 { CS_PRECISION, RO, "precision" }, /* 3 */ 341 { CS_ROOTDELAY, RO, "rootdelay" }, /* 4 */ 342 { CS_ROOTDISPERSION, RO, "rootdisp" }, /* 5 */ 343 { CS_REFID, RO, "refid" }, /* 6 */ 344 { CS_REFTIME, RO, "reftime" }, /* 7 */ 345 { CS_POLL, RO, "tc" }, /* 8 */ 346 { CS_PEERID, RO, "peer" }, /* 9 */ 347 { CS_OFFSET, RO, "offset" }, /* 10 */ 348 { CS_DRIFT, RO, "frequency" }, /* 11 */ 349 { CS_JITTER, RO, "sys_jitter" }, /* 12 */ 350 { CS_ERROR, RO, "clk_jitter" }, /* 13 */ 351 { CS_CLOCK, RO, "clock" }, /* 14 */ 352 { CS_PROCESSOR, RO, "processor" }, /* 15 */ 353 { CS_SYSTEM, RO, "system" }, /* 16 */ 354 { CS_VERSION, RO, "version" }, /* 17 */ 355 { CS_STABIL, RO, "clk_wander" }, /* 18 */ 356 { CS_VARLIST, RO, "sys_var_list" }, /* 19 */ 357 { CS_TAI, RO, "tai" }, /* 20 */ 358 { CS_LEAPTAB, RO, "leapsec" }, /* 21 */ 359 { CS_LEAPEND, RO, "expire" }, /* 22 */ 360 { CS_RATE, RO, "mintc" }, /* 23 */ 361 { CS_MRU_ENABLED, RO, "mru_enabled" }, /* 24 */ 362 { CS_MRU_DEPTH, RO, "mru_depth" }, /* 25 */ 363 { CS_MRU_DEEPEST, RO, "mru_deepest" }, /* 26 */ 364 { CS_MRU_MINDEPTH, RO, "mru_mindepth" }, /* 27 */ 365 { CS_MRU_MAXAGE, RO, "mru_maxage" }, /* 28 */ 366 { CS_MRU_MAXDEPTH, RO, "mru_maxdepth" }, /* 29 */ 367 { CS_MRU_MEM, RO, "mru_mem" }, /* 30 */ 368 { CS_MRU_MAXMEM, RO, "mru_maxmem" }, /* 31 */ 369 { CS_SS_UPTIME, RO, "ss_uptime" }, /* 32 */ 370 { CS_SS_RESET, RO, "ss_reset" }, /* 33 */ 371 { CS_SS_RECEIVED, RO, "ss_received" }, /* 34 */ 372 { CS_SS_THISVER, RO, "ss_thisver" }, /* 35 */ 373 { CS_SS_OLDVER, RO, "ss_oldver" }, /* 36 */ 374 { CS_SS_BADFORMAT, RO, "ss_badformat" }, /* 37 */ 375 { CS_SS_BADAUTH, RO, "ss_badauth" }, /* 38 */ 376 { CS_SS_DECLINED, RO, "ss_declined" }, /* 39 */ 377 { CS_SS_RESTRICTED, RO, "ss_restricted" }, /* 40 */ 378 { CS_SS_LIMITED, RO, "ss_limited" }, /* 41 */ 379 { CS_SS_KODSENT, RO, "ss_kodsent" }, /* 42 */ 380 { CS_SS_PROCESSED, RO, "ss_processed" }, /* 43 */ 381 { CS_PEERADR, RO, "peeradr" }, /* 44 */ 382 { CS_PEERMODE, RO, "peermode" }, /* 45 */ 383 { CS_BCASTDELAY, RO, "bcastdelay" }, /* 46 */ 384 { CS_AUTHDELAY, RO, "authdelay" }, /* 47 */ 385 { CS_AUTHKEYS, RO, "authkeys" }, /* 48 */ 386 { CS_AUTHFREEK, RO, "authfreek" }, /* 49 */ 387 { CS_AUTHKLOOKUPS, RO, "authklookups" }, /* 50 */ 388 { CS_AUTHKNOTFOUND, RO, "authknotfound" }, /* 51 */ 389 { CS_AUTHKUNCACHED, RO, "authkuncached" }, /* 52 */ 390 { CS_AUTHKEXPIRED, RO, "authkexpired" }, /* 53 */ 391 { CS_AUTHENCRYPTS, RO, "authencrypts" }, /* 54 */ 392 { CS_AUTHDECRYPTS, RO, "authdecrypts" }, /* 55 */ 393 { CS_AUTHRESET, RO, "authreset" }, /* 56 */ 394 { CS_K_OFFSET, RO, "koffset" }, /* 57 */ 395 { CS_K_FREQ, RO, "kfreq" }, /* 58 */ 396 { CS_K_MAXERR, RO, "kmaxerr" }, /* 59 */ 397 { CS_K_ESTERR, RO, "kesterr" }, /* 60 */ 398 { CS_K_STFLAGS, RO, "kstflags" }, /* 61 */ 399 { CS_K_TIMECONST, RO, "ktimeconst" }, /* 62 */ 400 { CS_K_PRECISION, RO, "kprecis" }, /* 63 */ 401 { CS_K_FREQTOL, RO, "kfreqtol" }, /* 64 */ 402 { CS_K_PPS_FREQ, RO, "kppsfreq" }, /* 65 */ 403 { CS_K_PPS_STABIL, RO, "kppsstab" }, /* 66 */ 404 { CS_K_PPS_JITTER, RO, "kppsjitter" }, /* 67 */ 405 { CS_K_PPS_CALIBDUR, RO, "kppscalibdur" }, /* 68 */ 406 { CS_K_PPS_CALIBS, RO, "kppscalibs" }, /* 69 */ 407 { CS_K_PPS_CALIBERRS, RO, "kppscaliberrs" }, /* 70 */ 408 { CS_K_PPS_JITEXC, RO, "kppsjitexc" }, /* 71 */ 409 { CS_K_PPS_STBEXC, RO, "kppsstbexc" }, /* 72 */ 410 { CS_IOSTATS_RESET, RO, "iostats_reset" }, /* 73 */ 411 { CS_TOTAL_RBUF, RO, "total_rbuf" }, /* 74 */ 412 { CS_FREE_RBUF, RO, "free_rbuf" }, /* 75 */ 413 { CS_USED_RBUF, RO, "used_rbuf" }, /* 76 */ 414 { CS_RBUF_LOWATER, RO, "rbuf_lowater" }, /* 77 */ 415 { CS_IO_DROPPED, RO, "io_dropped" }, /* 78 */ 416 { CS_IO_IGNORED, RO, "io_ignored" }, /* 79 */ 417 { CS_IO_RECEIVED, RO, "io_received" }, /* 80 */ 418 { CS_IO_SENT, RO, "io_sent" }, /* 81 */ 419 { CS_IO_SENDFAILED, RO, "io_sendfailed" }, /* 82 */ 420 { CS_IO_WAKEUPS, RO, "io_wakeups" }, /* 83 */ 421 { CS_IO_GOODWAKEUPS, RO, "io_goodwakeups" }, /* 84 */ 422 { CS_TIMERSTATS_RESET, RO, "timerstats_reset" },/* 85 */ 423 { CS_TIMER_OVERRUNS, RO, "timer_overruns" }, /* 86 */ 424 { CS_TIMER_XMTS, RO, "timer_xmts" }, /* 87 */ 425 { CS_FUZZ, RO, "fuzz" }, /* 88 */ 426 { CS_WANDER_THRESH, RO, "clk_wander_threshold" }, /* 89 */ 427 428 { CS_LEAPSMEARINTV, RO, "leapsmearinterval" }, /* 90 */ 429 { CS_LEAPSMEAROFFS, RO, "leapsmearoffset" }, /* 91 */ 430 431#ifdef AUTOKEY 432 { CS_FLAGS, RO, "flags" }, /* 1 + CS_MAX_NOAUTOKEY */ 433 { CS_HOST, RO, "host" }, /* 2 + CS_MAX_NOAUTOKEY */ 434 { CS_PUBLIC, RO, "update" }, /* 3 + CS_MAX_NOAUTOKEY */ 435 { CS_CERTIF, RO, "cert" }, /* 4 + CS_MAX_NOAUTOKEY */ 436 { CS_SIGNATURE, RO, "signature" }, /* 5 + CS_MAX_NOAUTOKEY */ 437 { CS_REVTIME, RO, "until" }, /* 6 + CS_MAX_NOAUTOKEY */ 438 { CS_IDENT, RO, "ident" }, /* 7 + CS_MAX_NOAUTOKEY */ 439 { CS_DIGEST, RO, "digest" }, /* 8 + CS_MAX_NOAUTOKEY */ 440#endif /* AUTOKEY */ 441 { 0, EOV, "" } /* 87/95 */ 442}; 443 444static struct ctl_var *ext_sys_var = NULL; 445 446/* 447 * System variables we print by default (in fuzzball order, 448 * more-or-less) 449 */ 450static const u_char def_sys_var[] = { 451 CS_VERSION, 452 CS_PROCESSOR, 453 CS_SYSTEM, 454 CS_LEAP, 455 CS_STRATUM, 456 CS_PRECISION, 457 CS_ROOTDELAY, 458 CS_ROOTDISPERSION, 459 CS_REFID, 460 CS_REFTIME, 461 CS_CLOCK, 462 CS_PEERID, 463 CS_POLL, 464 CS_RATE, 465 CS_OFFSET, 466 CS_DRIFT, 467 CS_JITTER, 468 CS_ERROR, 469 CS_STABIL, 470 CS_TAI, 471 CS_LEAPTAB, 472 CS_LEAPEND, 473 CS_LEAPSMEARINTV, 474 CS_LEAPSMEAROFFS, 475#ifdef AUTOKEY 476 CS_HOST, 477 CS_IDENT, 478 CS_FLAGS, 479 CS_DIGEST, 480 CS_SIGNATURE, 481 CS_PUBLIC, 482 CS_CERTIF, 483#endif /* AUTOKEY */ 484 0 485}; 486 487 488/* 489 * Peer variable list 490 */ 491static const struct ctl_var peer_var[] = { 492 { 0, PADDING, "" }, /* 0 */ 493 { CP_CONFIG, RO, "config" }, /* 1 */ 494 { CP_AUTHENABLE, RO, "authenable" }, /* 2 */ 495 { CP_AUTHENTIC, RO, "authentic" }, /* 3 */ 496 { CP_SRCADR, RO, "srcadr" }, /* 4 */ 497 { CP_SRCPORT, RO, "srcport" }, /* 5 */ 498 { CP_DSTADR, RO, "dstadr" }, /* 6 */ 499 { CP_DSTPORT, RO, "dstport" }, /* 7 */ 500 { CP_LEAP, RO, "leap" }, /* 8 */ 501 { CP_HMODE, RO, "hmode" }, /* 9 */ 502 { CP_STRATUM, RO, "stratum" }, /* 10 */ 503 { CP_PPOLL, RO, "ppoll" }, /* 11 */ 504 { CP_HPOLL, RO, "hpoll" }, /* 12 */ 505 { CP_PRECISION, RO, "precision" }, /* 13 */ 506 { CP_ROOTDELAY, RO, "rootdelay" }, /* 14 */ 507 { CP_ROOTDISPERSION, RO, "rootdisp" }, /* 15 */ 508 { CP_REFID, RO, "refid" }, /* 16 */ 509 { CP_REFTIME, RO, "reftime" }, /* 17 */ 510 { CP_ORG, RO, "org" }, /* 18 */ 511 { CP_REC, RO, "rec" }, /* 19 */ 512 { CP_XMT, RO, "xleave" }, /* 20 */ 513 { CP_REACH, RO, "reach" }, /* 21 */ 514 { CP_UNREACH, RO, "unreach" }, /* 22 */ 515 { CP_TIMER, RO, "timer" }, /* 23 */ 516 { CP_DELAY, RO, "delay" }, /* 24 */ 517 { CP_OFFSET, RO, "offset" }, /* 25 */ 518 { CP_JITTER, RO, "jitter" }, /* 26 */ 519 { CP_DISPERSION, RO, "dispersion" }, /* 27 */ 520 { CP_KEYID, RO, "keyid" }, /* 28 */ 521 { CP_FILTDELAY, RO, "filtdelay" }, /* 29 */ 522 { CP_FILTOFFSET, RO, "filtoffset" }, /* 30 */ 523 { CP_PMODE, RO, "pmode" }, /* 31 */ 524 { CP_RECEIVED, RO, "received"}, /* 32 */ 525 { CP_SENT, RO, "sent" }, /* 33 */ 526 { CP_FILTERROR, RO, "filtdisp" }, /* 34 */ 527 { CP_FLASH, RO, "flash" }, /* 35 */ 528 { CP_TTL, RO, "ttl" }, /* 36 */ 529 { CP_VARLIST, RO, "peer_var_list" }, /* 37 */ 530 { CP_IN, RO, "in" }, /* 38 */ 531 { CP_OUT, RO, "out" }, /* 39 */ 532 { CP_RATE, RO, "headway" }, /* 40 */ 533 { CP_BIAS, RO, "bias" }, /* 41 */ 534 { CP_SRCHOST, RO, "srchost" }, /* 42 */ 535 { CP_TIMEREC, RO, "timerec" }, /* 43 */ 536 { CP_TIMEREACH, RO, "timereach" }, /* 44 */ 537 { CP_BADAUTH, RO, "badauth" }, /* 45 */ 538 { CP_BOGUSORG, RO, "bogusorg" }, /* 46 */ 539 { CP_OLDPKT, RO, "oldpkt" }, /* 47 */ 540 { CP_SELDISP, RO, "seldisp" }, /* 48 */ 541 { CP_SELBROKEN, RO, "selbroken" }, /* 49 */ 542 { CP_CANDIDATE, RO, "candidate" }, /* 50 */ 543#ifdef AUTOKEY 544 { CP_FLAGS, RO, "flags" }, /* 1 + CP_MAX_NOAUTOKEY */ 545 { CP_HOST, RO, "host" }, /* 2 + CP_MAX_NOAUTOKEY */ 546 { CP_VALID, RO, "valid" }, /* 3 + CP_MAX_NOAUTOKEY */ 547 { CP_INITSEQ, RO, "initsequence" }, /* 4 + CP_MAX_NOAUTOKEY */ 548 { CP_INITKEY, RO, "initkey" }, /* 5 + CP_MAX_NOAUTOKEY */ 549 { CP_INITTSP, RO, "timestamp" }, /* 6 + CP_MAX_NOAUTOKEY */ 550 { CP_SIGNATURE, RO, "signature" }, /* 7 + CP_MAX_NOAUTOKEY */ 551 { CP_IDENT, RO, "ident" }, /* 8 + CP_MAX_NOAUTOKEY */ 552#endif /* AUTOKEY */ 553 { 0, EOV, "" } /* 50/58 */ 554}; 555 556 557/* 558 * Peer variables we print by default 559 */ 560static const u_char def_peer_var[] = { 561 CP_SRCADR, 562 CP_SRCPORT, 563 CP_SRCHOST, 564 CP_DSTADR, 565 CP_DSTPORT, 566 CP_OUT, 567 CP_IN, 568 CP_LEAP, 569 CP_STRATUM, 570 CP_PRECISION, 571 CP_ROOTDELAY, 572 CP_ROOTDISPERSION, 573 CP_REFID, 574 CP_REFTIME, 575 CP_REC, 576 CP_REACH, 577 CP_UNREACH, 578 CP_HMODE, 579 CP_PMODE, 580 CP_HPOLL, 581 CP_PPOLL, 582 CP_RATE, 583 CP_FLASH, 584 CP_KEYID, 585 CP_TTL, 586 CP_OFFSET, 587 CP_DELAY, 588 CP_DISPERSION, 589 CP_JITTER, 590 CP_XMT, 591 CP_BIAS, 592 CP_FILTDELAY, 593 CP_FILTOFFSET, 594 CP_FILTERROR, 595#ifdef AUTOKEY 596 CP_HOST, 597 CP_FLAGS, 598 CP_SIGNATURE, 599 CP_VALID, 600 CP_INITSEQ, 601 CP_IDENT, 602#endif /* AUTOKEY */ 603 0 604}; 605 606 607#ifdef REFCLOCK 608/* 609 * Clock variable list 610 */ 611static const struct ctl_var clock_var[] = { 612 { 0, PADDING, "" }, /* 0 */ 613 { CC_TYPE, RO, "type" }, /* 1 */ 614 { CC_TIMECODE, RO, "timecode" }, /* 2 */ 615 { CC_POLL, RO, "poll" }, /* 3 */ 616 { CC_NOREPLY, RO, "noreply" }, /* 4 */ 617 { CC_BADFORMAT, RO, "badformat" }, /* 5 */ 618 { CC_BADDATA, RO, "baddata" }, /* 6 */ 619 { CC_FUDGETIME1, RO, "fudgetime1" }, /* 7 */ 620 { CC_FUDGETIME2, RO, "fudgetime2" }, /* 8 */ 621 { CC_FUDGEVAL1, RO, "stratum" }, /* 9 */ 622 { CC_FUDGEVAL2, RO, "refid" }, /* 10 */ 623 { CC_FLAGS, RO, "flags" }, /* 11 */ 624 { CC_DEVICE, RO, "device" }, /* 12 */ 625 { CC_VARLIST, RO, "clock_var_list" }, /* 13 */ 626 { 0, EOV, "" } /* 14 */ 627}; 628 629 630/* 631 * Clock variables printed by default 632 */ 633static const u_char def_clock_var[] = { 634 CC_DEVICE, 635 CC_TYPE, /* won't be output if device = known */ 636 CC_TIMECODE, 637 CC_POLL, 638 CC_NOREPLY, 639 CC_BADFORMAT, 640 CC_BADDATA, 641 CC_FUDGETIME1, 642 CC_FUDGETIME2, 643 CC_FUDGEVAL1, 644 CC_FUDGEVAL2, 645 CC_FLAGS, 646 0 647}; 648#endif 649 650/* 651 * MRU string constants shared by send_mru_entry() and read_mru_list(). 652 */ 653static const char addr_fmt[] = "addr.%d"; 654static const char last_fmt[] = "last.%d"; 655 656/* 657 * System and processor definitions. 658 */ 659#ifndef HAVE_UNAME 660# ifndef STR_SYSTEM 661# define STR_SYSTEM "UNIX" 662# endif 663# ifndef STR_PROCESSOR 664# define STR_PROCESSOR "unknown" 665# endif 666 667static const char str_system[] = STR_SYSTEM; 668static const char str_processor[] = STR_PROCESSOR; 669#else 670# include <sys/utsname.h> 671static struct utsname utsnamebuf; 672#endif /* HAVE_UNAME */ 673 674/* 675 * Trap structures. We only allow a few of these, and send a copy of 676 * each async message to each live one. Traps time out after an hour, it 677 * is up to the trap receipient to keep resetting it to avoid being 678 * timed out. 679 */ 680/* ntp_request.c */ 681struct ctl_trap ctl_traps[CTL_MAXTRAPS]; 682int num_ctl_traps; 683 684/* 685 * Type bits, for ctlsettrap() call. 686 */ 687#define TRAP_TYPE_CONFIG 0 /* used by configuration code */ 688#define TRAP_TYPE_PRIO 1 /* priority trap */ 689#define TRAP_TYPE_NONPRIO 2 /* nonpriority trap */ 690 691 692/* 693 * List relating reference clock types to control message time sources. 694 * Index by the reference clock type. This list will only be used iff 695 * the reference clock driver doesn't set peer->sstclktype to something 696 * different than CTL_SST_TS_UNSPEC. 697 */ 698#ifdef REFCLOCK 699static const u_char clocktypes[] = { 700 CTL_SST_TS_NTP, /* REFCLK_NONE (0) */ 701 CTL_SST_TS_LOCAL, /* REFCLK_LOCALCLOCK (1) */ 702 CTL_SST_TS_UHF, /* deprecated REFCLK_GPS_TRAK (2) */ 703 CTL_SST_TS_HF, /* REFCLK_WWV_PST (3) */ 704 CTL_SST_TS_LF, /* REFCLK_WWVB_SPECTRACOM (4) */ 705 CTL_SST_TS_UHF, /* REFCLK_TRUETIME (5) */ 706 CTL_SST_TS_UHF, /* REFCLK_IRIG_AUDIO (6) */ 707 CTL_SST_TS_HF, /* REFCLK_CHU (7) */ 708 CTL_SST_TS_LF, /* REFCLOCK_PARSE (default) (8) */ 709 CTL_SST_TS_LF, /* REFCLK_GPS_MX4200 (9) */ 710 CTL_SST_TS_UHF, /* REFCLK_GPS_AS2201 (10) */ 711 CTL_SST_TS_UHF, /* REFCLK_GPS_ARBITER (11) */ 712 CTL_SST_TS_UHF, /* REFCLK_IRIG_TPRO (12) */ 713 CTL_SST_TS_ATOM, /* REFCLK_ATOM_LEITCH (13) */ 714 CTL_SST_TS_LF, /* deprecated REFCLK_MSF_EES (14) */ 715 CTL_SST_TS_NTP, /* not used (15) */ 716 CTL_SST_TS_UHF, /* REFCLK_IRIG_BANCOMM (16) */ 717 CTL_SST_TS_UHF, /* REFCLK_GPS_DATU (17) */ 718 CTL_SST_TS_TELEPHONE, /* REFCLK_NIST_ACTS (18) */ 719 CTL_SST_TS_HF, /* REFCLK_WWV_HEATH (19) */ 720 CTL_SST_TS_UHF, /* REFCLK_GPS_NMEA (20) */ 721 CTL_SST_TS_UHF, /* REFCLK_GPS_VME (21) */ 722 CTL_SST_TS_ATOM, /* REFCLK_ATOM_PPS (22) */ 723 CTL_SST_TS_NTP, /* not used (23) */ 724 CTL_SST_TS_NTP, /* not used (24) */ 725 CTL_SST_TS_NTP, /* not used (25) */ 726 CTL_SST_TS_UHF, /* REFCLK_GPS_HP (26) */ 727 CTL_SST_TS_LF, /* REFCLK_ARCRON_MSF (27) */ 728 CTL_SST_TS_UHF, /* REFCLK_SHM (28) */ 729 CTL_SST_TS_UHF, /* REFCLK_PALISADE (29) */ 730 CTL_SST_TS_UHF, /* REFCLK_ONCORE (30) */ 731 CTL_SST_TS_UHF, /* REFCLK_JUPITER (31) */ 732 CTL_SST_TS_LF, /* REFCLK_CHRONOLOG (32) */ 733 CTL_SST_TS_LF, /* REFCLK_DUMBCLOCK (33) */ 734 CTL_SST_TS_LF, /* REFCLK_ULINK (34) */ 735 CTL_SST_TS_LF, /* REFCLK_PCF (35) */ 736 CTL_SST_TS_HF, /* REFCLK_WWV (36) */ 737 CTL_SST_TS_LF, /* REFCLK_FG (37) */ 738 CTL_SST_TS_UHF, /* REFCLK_HOPF_SERIAL (38) */ 739 CTL_SST_TS_UHF, /* REFCLK_HOPF_PCI (39) */ 740 CTL_SST_TS_LF, /* REFCLK_JJY (40) */ 741 CTL_SST_TS_UHF, /* REFCLK_TT560 (41) */ 742 CTL_SST_TS_UHF, /* REFCLK_ZYFER (42) */ 743 CTL_SST_TS_UHF, /* REFCLK_RIPENCC (43) */ 744 CTL_SST_TS_UHF, /* REFCLK_NEOCLOCK4X (44) */ 745 CTL_SST_TS_UHF, /* REFCLK_TSYNCPCI (45) */ 746 CTL_SST_TS_UHF /* REFCLK_GPSDJSON (46) */ 747}; 748#endif /* REFCLOCK */ 749 750 751/* 752 * Keyid used for authenticating write requests. 753 */ 754keyid_t ctl_auth_keyid; 755 756/* 757 * We keep track of the last error reported by the system internally 758 */ 759static u_char ctl_sys_last_event; 760static u_char ctl_sys_num_events; 761 762 763/* 764 * Statistic counters to keep track of requests and responses. 765 */ 766u_long ctltimereset; /* time stats reset */ 767u_long numctlreq; /* number of requests we've received */ 768u_long numctlbadpkts; /* number of bad control packets */ 769u_long numctlresponses; /* number of resp packets sent with data */ 770u_long numctlfrags; /* number of fragments sent */ 771u_long numctlerrors; /* number of error responses sent */ 772u_long numctltooshort; /* number of too short input packets */ 773u_long numctlinputresp; /* number of responses on input */ 774u_long numctlinputfrag; /* number of fragments on input */ 775u_long numctlinputerr; /* number of input pkts with err bit set */ 776u_long numctlbadoffset; /* number of input pkts with nonzero offset */ 777u_long numctlbadversion; /* number of input pkts with unknown version */ 778u_long numctldatatooshort; /* data too short for count */ 779u_long numctlbadop; /* bad op code found in packet */ 780u_long numasyncmsgs; /* number of async messages we've sent */ 781 782/* 783 * Response packet used by these routines. Also some state information 784 * so that we can handle packet formatting within a common set of 785 * subroutines. Note we try to enter data in place whenever possible, 786 * but the need to set the more bit correctly means we occasionally 787 * use the extra buffer and copy. 788 */ 789static struct ntp_control rpkt; 790static u_char res_version; 791static u_char res_opcode; 792static associd_t res_associd; 793static u_short res_frags; /* datagrams in this response */ 794static int res_offset; /* offset of payload in response */ 795static u_char * datapt; 796static u_char * dataend; 797static int datalinelen; 798static int datasent; /* flag to avoid initial ", " */ 799static int datanotbinflag; 800static sockaddr_u *rmt_addr; 801static struct interface *lcl_inter; 802 803static u_char res_authenticate; 804static u_char res_authokay; 805static keyid_t res_keyid; 806 807#define MAXDATALINELEN (72) 808 809static u_char res_async; /* sending async trap response? */ 810 811/* 812 * Pointers for saving state when decoding request packets 813 */ 814static char *reqpt; 815static char *reqend; 816 817#ifndef MIN 818#define MIN(a, b) (((a) <= (b)) ? (a) : (b)) 819#endif 820 821/* 822 * init_control - initialize request data 823 */ 824void 825init_control(void) 826{ 827 size_t i; 828 829#ifdef HAVE_UNAME 830 uname(&utsnamebuf); 831#endif /* HAVE_UNAME */ 832 833 ctl_clr_stats(); 834 835 ctl_auth_keyid = 0; 836 ctl_sys_last_event = EVNT_UNSPEC; 837 ctl_sys_num_events = 0; 838 839 num_ctl_traps = 0; 840 for (i = 0; i < COUNTOF(ctl_traps); i++) 841 ctl_traps[i].tr_flags = 0; 842} 843 844 845/* 846 * ctl_error - send an error response for the current request 847 */ 848static void 849ctl_error( 850 u_char errcode 851 ) 852{ 853 size_t maclen; 854 855 numctlerrors++; 856 DPRINTF(3, ("sending control error %u\n", errcode)); 857 858 /* 859 * Fill in the fields. We assume rpkt.sequence and rpkt.associd 860 * have already been filled in. 861 */ 862 rpkt.r_m_e_op = (u_char)CTL_RESPONSE | CTL_ERROR | 863 (res_opcode & CTL_OP_MASK); 864 rpkt.status = htons((u_short)(errcode << 8) & 0xff00); 865 rpkt.count = 0; 866 867 /* 868 * send packet and bump counters 869 */ 870 if (res_authenticate && sys_authenticate) { 871 maclen = authencrypt(res_keyid, (u_int32 *)&rpkt, 872 CTL_HEADER_LEN); 873 sendpkt(rmt_addr, lcl_inter, -2, (void *)&rpkt, 874 CTL_HEADER_LEN + maclen); 875 } else 876 sendpkt(rmt_addr, lcl_inter, -3, (void *)&rpkt, 877 CTL_HEADER_LEN); 878} 879 880int/*BOOL*/ 881is_safe_filename(const char * name) 882{ 883 /* We need a strict validation of filenames we should write: The 884 * daemon might run with special permissions and is remote 885 * controllable, so we better take care what we allow as file 886 * name! 887 * 888 * The first character must be digit or a letter from the ASCII 889 * base plane or a '_' ([_A-Za-z0-9]), the following characters 890 * must be from [-._+A-Za-z0-9]. 891 * 892 * We do not trust the character classification much here: Since 893 * the NTP protocol makes no provisions for UTF-8 or local code 894 * pages, we strictly require the 7bit ASCII code page. 895 * 896 * The following table is a packed bit field of 128 two-bit 897 * groups. The LSB in each group tells us if a character is 898 * acceptable at the first position, the MSB if the character is 899 * accepted at any other position. 900 * 901 * This does not ensure that the file name is syntactically 902 * correct (multiple dots will not work with VMS...) but it will 903 * exclude potential globbing bombs and directory traversal. It 904 * also rules out drive selection. (For systems that have this 905 * notion, like Windows or VMS.) 906 */ 907 static const uint32_t chclass[8] = { 908 0x00000000, 0x00000000, 909 0x28800000, 0x000FFFFF, 910 0xFFFFFFFC, 0xC03FFFFF, 911 0xFFFFFFFC, 0x003FFFFF 912 }; 913 914 u_int widx, bidx, mask; 915 if ( ! (name && *name)) 916 return FALSE; 917 918 mask = 1u; 919 while (0 != (widx = (u_char)*name++)) { 920 bidx = (widx & 15) << 1; 921 widx = widx >> 4; 922 if (widx >= sizeof(chclass)/sizeof(chclass[0])) 923 return FALSE; 924 if (0 == ((chclass[widx] >> bidx) & mask)) 925 return FALSE; 926 mask = 2u; 927 } 928 return TRUE; 929} 930 931 932/* 933 * save_config - Implements ntpq -c "saveconfig <filename>" 934 * Writes current configuration including any runtime 935 * changes by ntpq's :config or config-from-file 936 * 937 * Note: There should be no buffer overflow or truncation in the 938 * processing of file names -- both cause security problems. This is bit 939 * painful to code but essential here. 940 */ 941void 942save_config( 943 struct recvbuf *rbufp, 944 int restrict_mask 945 ) 946{ 947 /* block directory traversal by searching for characters that 948 * indicate directory components in a file path. 949 * 950 * Conceptually we should be searching for DIRSEP in filename, 951 * however Windows actually recognizes both forward and 952 * backslashes as equivalent directory separators at the API 953 * level. On POSIX systems we could allow '\\' but such 954 * filenames are tricky to manipulate from a shell, so just 955 * reject both types of slashes on all platforms. 956 */ 957 /* TALOS-CAN-0062: block directory traversal for VMS, too */ 958 static const char * illegal_in_filename = 959#if defined(VMS) 960 ":[]" /* do not allow drive and path components here */ 961#elif defined(SYS_WINNT) 962 ":\\/" /* path and drive separators */ 963#else 964 "\\/" /* separator and critical char for POSIX */ 965#endif 966 ; 967 char reply[128]; 968#ifdef SAVECONFIG 969 static const char savedconfig_eq[] = "savedconfig="; 970 971 /* Build a safe open mode from the available mode flags. We want 972 * to create a new file and write it in text mode (when 973 * applicable -- only Windows does this...) 974 */ 975 static const int openmode = O_CREAT | O_TRUNC | O_WRONLY 976# if defined(O_EXCL) /* posix, vms */ 977 | O_EXCL 978# elif defined(_O_EXCL) /* windows is alway very special... */ 979 | _O_EXCL 980# endif 981# if defined(_O_TEXT) /* windows, again */ 982 | _O_TEXT 983#endif 984 ; 985 986 char filespec[128]; 987 char filename[128]; 988 char fullpath[512]; 989 char savedconfig[sizeof(savedconfig_eq) + sizeof(filename)]; 990 time_t now; 991 int fd; 992 FILE *fptr; 993 int prc; 994 size_t reqlen; 995#endif 996 997 if (RES_NOMODIFY & restrict_mask) { 998 ctl_printf("%s", "saveconfig prohibited by restrict ... nomodify"); 999 ctl_flushpkt(0); 1000 NLOG(NLOG_SYSINFO) 1001 msyslog(LOG_NOTICE, 1002 "saveconfig from %s rejected due to nomodify restriction", 1003 stoa(&rbufp->recv_srcadr)); 1004 sys_restricted++; 1005 return; 1006 } 1007 1008#ifdef SAVECONFIG 1009 if (NULL == saveconfigdir) { 1010 ctl_printf("%s", "saveconfig prohibited, no saveconfigdir configured"); 1011 ctl_flushpkt(0); 1012 NLOG(NLOG_SYSINFO) 1013 msyslog(LOG_NOTICE, 1014 "saveconfig from %s rejected, no saveconfigdir", 1015 stoa(&rbufp->recv_srcadr)); 1016 return; 1017 } 1018 1019 /* The length checking stuff gets serious. Do not assume a NUL 1020 * byte can be found, but if so, use it to calculate the needed 1021 * buffer size. If the available buffer is too short, bail out; 1022 * likewise if there is no file spec. (The latter will not 1023 * happen when using NTPQ, but there are other ways to craft a 1024 * network packet!) 1025 */ 1026 reqlen = (size_t)(reqend - reqpt); 1027 if (0 != reqlen) { 1028 char * nulpos = (char*)memchr(reqpt, 0, reqlen); 1029 if (NULL != nulpos) 1030 reqlen = (size_t)(nulpos - reqpt); 1031 } 1032 if (0 == reqlen) 1033 return; 1034 if (reqlen >= sizeof(filespec)) { 1035 ctl_printf("saveconfig exceeded maximum raw name length (%u)", 1036 (u_int)sizeof(filespec)); 1037 ctl_flushpkt(0); 1038 msyslog(LOG_NOTICE, 1039 "saveconfig exceeded maximum raw name length from %s", 1040 stoa(&rbufp->recv_srcadr)); 1041 return; 1042 } 1043 1044 /* copy data directly as we exactly know the size */ 1045 memcpy(filespec, reqpt, reqlen); 1046 filespec[reqlen] = '\0'; 1047 1048 /* 1049 * allow timestamping of the saved config filename with 1050 * strftime() format such as: 1051 * ntpq -c "saveconfig ntp-%Y%m%d-%H%M%S.conf" 1052 * XXX: Nice feature, but not too safe. 1053 * YYY: The check for permitted characters in file names should 1054 * weed out the worst. Let's hope 'strftime()' does not 1055 * develop pathological problems. 1056 */ 1057 time(&now); 1058 if (0 == strftime(filename, sizeof(filename), filespec, 1059 localtime(&now))) 1060 { 1061 /* 1062 * If we arrive here, 'strftime()' balked; most likely 1063 * the buffer was too short. (Or it encounterd an empty 1064 * format, or just a format that expands to an empty 1065 * string.) We try to use the original name, though this 1066 * is very likely to fail later if there are format 1067 * specs in the string. Note that truncation cannot 1068 * happen here as long as both buffers have the same 1069 * size! 1070 */ 1071 strlcpy(filename, filespec, sizeof(filename)); 1072 } 1073 1074 /* 1075 * Check the file name for sanity. This might/will rule out file 1076 * names that would be legal but problematic, and it blocks 1077 * directory traversal. 1078 */ 1079 if (!is_safe_filename(filename)) { 1080 ctl_printf("saveconfig rejects unsafe file name '%s'", 1081 filename); 1082 ctl_flushpkt(0); 1083 msyslog(LOG_NOTICE, 1084 "saveconfig rejects unsafe file name from %s", 1085 stoa(&rbufp->recv_srcadr)); 1086 return; 1087 } 1088 1089 /* 1090 * XXX: This next test may not be needed with is_safe_filename() 1091 */ 1092 1093 /* block directory/drive traversal */ 1094 /* TALOS-CAN-0062: block directory traversal for VMS, too */ 1095 if (NULL != strpbrk(filename, illegal_in_filename)) { 1096 snprintf(reply, sizeof(reply), 1097 "saveconfig does not allow directory in filename"); 1098 ctl_putdata(reply, strlen(reply), 0); 1099 ctl_flushpkt(0); 1100 msyslog(LOG_NOTICE, 1101 "saveconfig rejects unsafe file name from %s", 1102 stoa(&rbufp->recv_srcadr)); 1103 return; 1104 } 1105 1106 /* concatenation of directory and path can cause another 1107 * truncation... 1108 */ 1109 prc = snprintf(fullpath, sizeof(fullpath), "%s%s", 1110 saveconfigdir, filename); 1111 if (prc < 0 || prc >= sizeof(fullpath)) { 1112 ctl_printf("saveconfig exceeded maximum path length (%u)", 1113 (u_int)sizeof(fullpath)); 1114 ctl_flushpkt(0); 1115 msyslog(LOG_NOTICE, 1116 "saveconfig exceeded maximum path length from %s", 1117 stoa(&rbufp->recv_srcadr)); 1118 return; 1119 } 1120 1121 fd = open(fullpath, openmode, S_IRUSR | S_IWUSR); 1122 if (-1 == fd) 1123 fptr = NULL; 1124 else 1125 fptr = fdopen(fd, "w"); 1126 1127 if (NULL == fptr || -1 == dump_all_config_trees(fptr, 1)) { 1128 ctl_printf("Unable to save configuration to file '%s': %m", 1129 filename); 1130 msyslog(LOG_ERR, 1131 "saveconfig %s from %s failed", filename, 1132 stoa(&rbufp->recv_srcadr)); 1133 } else { 1134 ctl_printf("Configuration saved to '%s'", filename); 1135 msyslog(LOG_NOTICE, 1136 "Configuration saved to '%s' (requested by %s)", 1137 fullpath, stoa(&rbufp->recv_srcadr)); 1138 /* 1139 * save the output filename in system variable 1140 * savedconfig, retrieved with: 1141 * ntpq -c "rv 0 savedconfig" 1142 * Note: the way 'savedconfig' is defined makes overflow 1143 * checks unnecessary here. 1144 */ 1145 snprintf(savedconfig, sizeof(savedconfig), "%s%s", 1146 savedconfig_eq, filename); 1147 set_sys_var(savedconfig, strlen(savedconfig) + 1, RO); 1148 } 1149 1150 if (NULL != fptr) 1151 fclose(fptr); 1152#else /* !SAVECONFIG follows */ 1153 ctl_printf("%s", 1154 "saveconfig unavailable, configured with --disable-saveconfig"); 1155#endif 1156 ctl_flushpkt(0); 1157} 1158 1159 1160/* 1161 * process_control - process an incoming control message 1162 */ 1163void 1164process_control( 1165 struct recvbuf *rbufp, 1166 int restrict_mask 1167 ) 1168{ 1169 struct ntp_control *pkt; 1170 int req_count; 1171 int req_data; 1172 const struct ctl_proc *cc; 1173 keyid_t *pkid; 1174 int properlen; 1175 size_t maclen; 1176 1177 DPRINTF(3, ("in process_control()\n")); 1178 1179 /* 1180 * Save the addresses for error responses 1181 */ 1182 numctlreq++; 1183 rmt_addr = &rbufp->recv_srcadr; 1184 lcl_inter = rbufp->dstadr; 1185 pkt = (struct ntp_control *)&rbufp->recv_pkt; 1186 1187 /* 1188 * If the length is less than required for the header, or 1189 * it is a response or a fragment, ignore this. 1190 */ 1191 if (rbufp->recv_length < (int)CTL_HEADER_LEN 1192 || (CTL_RESPONSE | CTL_MORE | CTL_ERROR) & pkt->r_m_e_op 1193 || pkt->offset != 0) { 1194 DPRINTF(1, ("invalid format in control packet\n")); 1195 if (rbufp->recv_length < (int)CTL_HEADER_LEN) 1196 numctltooshort++; 1197 if (CTL_RESPONSE & pkt->r_m_e_op) 1198 numctlinputresp++; 1199 if (CTL_MORE & pkt->r_m_e_op) 1200 numctlinputfrag++; 1201 if (CTL_ERROR & pkt->r_m_e_op) 1202 numctlinputerr++; 1203 if (pkt->offset != 0) 1204 numctlbadoffset++; 1205 return; 1206 } 1207 res_version = PKT_VERSION(pkt->li_vn_mode); 1208 if (res_version > NTP_VERSION || res_version < NTP_OLDVERSION) { 1209 DPRINTF(1, ("unknown version %d in control packet\n", 1210 res_version)); 1211 numctlbadversion++; 1212 return; 1213 } 1214 1215 /* 1216 * Pull enough data from the packet to make intelligent 1217 * responses 1218 */ 1219 rpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, res_version, 1220 MODE_CONTROL); 1221 res_opcode = pkt->r_m_e_op; 1222 rpkt.sequence = pkt->sequence; 1223 rpkt.associd = pkt->associd; 1224 rpkt.status = 0; 1225 res_frags = 1; 1226 res_offset = 0; 1227 res_associd = htons(pkt->associd); 1228 res_async = FALSE; 1229 res_authenticate = FALSE; 1230 res_keyid = 0; 1231 res_authokay = FALSE; 1232 req_count = (int)ntohs(pkt->count); 1233 datanotbinflag = FALSE; 1234 datalinelen = 0; 1235 datasent = 0; 1236 datapt = rpkt.u.data; 1237 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN]; 1238 1239 if ((rbufp->recv_length & 0x3) != 0) 1240 DPRINTF(3, ("Control packet length %d unrounded\n", 1241 rbufp->recv_length)); 1242 1243 /* 1244 * We're set up now. Make sure we've got at least enough 1245 * incoming data space to match the count. 1246 */ 1247 req_data = rbufp->recv_length - CTL_HEADER_LEN; 1248 if (req_data < req_count || rbufp->recv_length & 0x3) { 1249 ctl_error(CERR_BADFMT); 1250 numctldatatooshort++; 1251 return; 1252 } 1253 1254 properlen = req_count + CTL_HEADER_LEN; 1255 /* round up proper len to a 8 octet boundary */ 1256 1257 properlen = (properlen + 7) & ~7; 1258 maclen = rbufp->recv_length - properlen; 1259 if ((rbufp->recv_length & 3) == 0 && 1260 maclen >= MIN_MAC_LEN && maclen <= MAX_MAC_LEN && 1261 sys_authenticate) { 1262 res_authenticate = TRUE; 1263 pkid = (void *)((char *)pkt + properlen); 1264 res_keyid = ntohl(*pkid); 1265 DPRINTF(3, ("recv_len %d, properlen %d, wants auth with keyid %08x, MAC length=%zu\n", 1266 rbufp->recv_length, properlen, res_keyid, 1267 maclen)); 1268 1269 if (!authistrusted(res_keyid)) 1270 DPRINTF(3, ("invalid keyid %08x\n", res_keyid)); 1271 else if (authdecrypt(res_keyid, (u_int32 *)pkt, 1272 rbufp->recv_length - maclen, 1273 maclen)) { 1274 res_authokay = TRUE; 1275 DPRINTF(3, ("authenticated okay\n")); 1276 } else { 1277 res_keyid = 0; 1278 DPRINTF(3, ("authentication failed\n")); 1279 } 1280 } 1281 1282 /* 1283 * Set up translate pointers 1284 */ 1285 reqpt = (char *)pkt->u.data; 1286 reqend = reqpt + req_count; 1287 1288 /* 1289 * Look for the opcode processor 1290 */ 1291 for (cc = control_codes; cc->control_code != NO_REQUEST; cc++) { 1292 if (cc->control_code == res_opcode) { 1293 DPRINTF(3, ("opcode %d, found command handler\n", 1294 res_opcode)); 1295 if (cc->flags == AUTH 1296 && (!res_authokay 1297 || res_keyid != ctl_auth_keyid)) { 1298 ctl_error(CERR_PERMISSION); 1299 return; 1300 } 1301 (cc->handler)(rbufp, restrict_mask); 1302 return; 1303 } 1304 } 1305 1306 /* 1307 * Can't find this one, return an error. 1308 */ 1309 numctlbadop++; 1310 ctl_error(CERR_BADOP); 1311 return; 1312} 1313 1314 1315/* 1316 * ctlpeerstatus - return a status word for this peer 1317 */ 1318u_short 1319ctlpeerstatus( 1320 register struct peer *p 1321 ) 1322{ 1323 u_short status; 1324 1325 status = p->status; 1326 if (FLAG_CONFIG & p->flags) 1327 status |= CTL_PST_CONFIG; 1328 if (p->keyid) 1329 status |= CTL_PST_AUTHENABLE; 1330 if (FLAG_AUTHENTIC & p->flags) 1331 status |= CTL_PST_AUTHENTIC; 1332 if (p->reach) 1333 status |= CTL_PST_REACH; 1334 if (MDF_TXONLY_MASK & p->cast_flags) 1335 status |= CTL_PST_BCAST; 1336 1337 return CTL_PEER_STATUS(status, p->num_events, p->last_event); 1338} 1339 1340 1341/* 1342 * ctlclkstatus - return a status word for this clock 1343 */ 1344#ifdef REFCLOCK 1345static u_short 1346ctlclkstatus( 1347 struct refclockstat *pcs 1348 ) 1349{ 1350 return CTL_PEER_STATUS(0, pcs->lastevent, pcs->currentstatus); 1351} 1352#endif 1353 1354 1355/* 1356 * ctlsysstatus - return the system status word 1357 */ 1358u_short 1359ctlsysstatus(void) 1360{ 1361 register u_char this_clock; 1362 1363 this_clock = CTL_SST_TS_UNSPEC; 1364#ifdef REFCLOCK 1365 if (sys_peer != NULL) { 1366 if (CTL_SST_TS_UNSPEC != sys_peer->sstclktype) 1367 this_clock = sys_peer->sstclktype; 1368 else if (sys_peer->refclktype < COUNTOF(clocktypes)) 1369 this_clock = clocktypes[sys_peer->refclktype]; 1370 } 1371#else /* REFCLOCK */ 1372 if (sys_peer != 0) 1373 this_clock = CTL_SST_TS_NTP; 1374#endif /* REFCLOCK */ 1375 return CTL_SYS_STATUS(sys_leap, this_clock, ctl_sys_num_events, 1376 ctl_sys_last_event); 1377} 1378 1379 1380/* 1381 * ctl_flushpkt - write out the current packet and prepare 1382 * another if necessary. 1383 */ 1384static void 1385ctl_flushpkt( 1386 u_char more 1387 ) 1388{ 1389 size_t i; 1390 size_t dlen; 1391 size_t sendlen; 1392 size_t maclen; 1393 size_t totlen; 1394 keyid_t keyid; 1395 1396 dlen = datapt - rpkt.u.data; 1397 if (!more && datanotbinflag && dlen + 2 < CTL_MAX_DATA_LEN) { 1398 /* 1399 * Big hack, output a trailing \r\n 1400 */ 1401 *datapt++ = '\r'; 1402 *datapt++ = '\n'; 1403 dlen += 2; 1404 } 1405 sendlen = dlen + CTL_HEADER_LEN; 1406 1407 /* 1408 * Pad to a multiple of 32 bits 1409 */ 1410 while (sendlen & 0x3) { 1411 *datapt++ = '\0'; 1412 sendlen++; 1413 } 1414 1415 /* 1416 * Fill in the packet with the current info 1417 */ 1418 rpkt.r_m_e_op = CTL_RESPONSE | more | 1419 (res_opcode & CTL_OP_MASK); 1420 rpkt.count = htons((u_short)dlen); 1421 rpkt.offset = htons((u_short)res_offset); 1422 if (res_async) { 1423 for (i = 0; i < COUNTOF(ctl_traps); i++) { 1424 if (TRAP_INUSE & ctl_traps[i].tr_flags) { 1425 rpkt.li_vn_mode = 1426 PKT_LI_VN_MODE( 1427 sys_leap, 1428 ctl_traps[i].tr_version, 1429 MODE_CONTROL); 1430 rpkt.sequence = 1431 htons(ctl_traps[i].tr_sequence); 1432 sendpkt(&ctl_traps[i].tr_addr, 1433 ctl_traps[i].tr_localaddr, -4, 1434 (struct pkt *)&rpkt, sendlen); 1435 if (!more) 1436 ctl_traps[i].tr_sequence++; 1437 numasyncmsgs++; 1438 } 1439 } 1440 } else { 1441 if (res_authenticate && sys_authenticate) { 1442 totlen = sendlen; 1443 /* 1444 * If we are going to authenticate, then there 1445 * is an additional requirement that the MAC 1446 * begin on a 64 bit boundary. 1447 */ 1448 while (totlen & 7) { 1449 *datapt++ = '\0'; 1450 totlen++; 1451 } 1452 keyid = htonl(res_keyid); 1453 memcpy(datapt, &keyid, sizeof(keyid)); 1454 maclen = authencrypt(res_keyid, 1455 (u_int32 *)&rpkt, totlen); 1456 sendpkt(rmt_addr, lcl_inter, -5, 1457 (struct pkt *)&rpkt, totlen + maclen); 1458 } else { 1459 sendpkt(rmt_addr, lcl_inter, -6, 1460 (struct pkt *)&rpkt, sendlen); 1461 } 1462 if (more) 1463 numctlfrags++; 1464 else 1465 numctlresponses++; 1466 } 1467 1468 /* 1469 * Set us up for another go around. 1470 */ 1471 res_frags++; 1472 res_offset += dlen; 1473 datapt = rpkt.u.data; 1474} 1475 1476 1477/* 1478 * ctl_putdata - write data into the packet, fragmenting and starting 1479 * another if this one is full. 1480 */ 1481static void 1482ctl_putdata( 1483 const char *dp, 1484 unsigned int dlen, 1485 int bin /* set to 1 when data is binary */ 1486 ) 1487{ 1488 int overhead; 1489 unsigned int currentlen; 1490 1491 overhead = 0; 1492 if (!bin) { 1493 datanotbinflag = TRUE; 1494 overhead = 3; 1495 if (datasent) { 1496 *datapt++ = ','; 1497 datalinelen++; 1498 if ((dlen + datalinelen + 1) >= MAXDATALINELEN) { 1499 *datapt++ = '\r'; 1500 *datapt++ = '\n'; 1501 datalinelen = 0; 1502 } else { 1503 *datapt++ = ' '; 1504 datalinelen++; 1505 } 1506 } 1507 } 1508 1509 /* 1510 * Save room for trailing junk 1511 */ 1512 while (dlen + overhead + datapt > dataend) { 1513 /* 1514 * Not enough room in this one, flush it out. 1515 */ 1516 currentlen = MIN(dlen, (unsigned int)(dataend - datapt)); 1517 1518 memcpy(datapt, dp, currentlen); 1519 1520 datapt += currentlen; 1521 dp += currentlen; 1522 dlen -= currentlen; 1523 datalinelen += currentlen; 1524 1525 ctl_flushpkt(CTL_MORE); 1526 } 1527 1528 memcpy(datapt, dp, dlen); 1529 datapt += dlen; 1530 datalinelen += dlen; 1531 datasent = TRUE; 1532} 1533 1534 1535/* 1536 * ctl_putstr - write a tagged string into the response packet 1537 * in the form: 1538 * 1539 * tag="data" 1540 * 1541 * len is the data length excluding the NUL terminator, 1542 * as in ctl_putstr("var", "value", strlen("value")); 1543 */ 1544static void 1545ctl_putstr( 1546 const char * tag, 1547 const char * data, 1548 size_t len 1549 ) 1550{ 1551 char buffer[512]; 1552 char *cp; 1553 size_t tl; 1554 1555 tl = strlen(tag); 1556 memcpy(buffer, tag, tl); 1557 cp = buffer + tl; 1558 if (len > 0) { 1559 INSIST(tl + 3 + len <= sizeof(buffer)); 1560 *cp++ = '='; 1561 *cp++ = '"'; 1562 memcpy(cp, data, len); 1563 cp += len; 1564 *cp++ = '"'; 1565 } 1566 ctl_putdata(buffer, (u_int)(cp - buffer), 0); 1567} 1568 1569 1570/* 1571 * ctl_putunqstr - write a tagged string into the response packet 1572 * in the form: 1573 * 1574 * tag=data 1575 * 1576 * len is the data length excluding the NUL terminator. 1577 * data must not contain a comma or whitespace. 1578 */ 1579static void 1580ctl_putunqstr( 1581 const char * tag, 1582 const char * data, 1583 size_t len 1584 ) 1585{ 1586 char buffer[512]; 1587 char *cp; 1588 size_t tl; 1589 1590 tl = strlen(tag); 1591 memcpy(buffer, tag, tl); 1592 cp = buffer + tl; 1593 if (len > 0) { 1594 INSIST(tl + 1 + len <= sizeof(buffer)); 1595 *cp++ = '='; 1596 memcpy(cp, data, len); 1597 cp += len; 1598 } 1599 ctl_putdata(buffer, (u_int)(cp - buffer), 0); 1600} 1601 1602 1603/* 1604 * ctl_putdblf - write a tagged, signed double into the response packet 1605 */ 1606static void 1607ctl_putdblf( 1608 const char * tag, 1609 int use_f, 1610 int precision, 1611 double d 1612 ) 1613{ 1614 char *cp; 1615 const char *cq; 1616 char buffer[200]; 1617 1618 cp = buffer; 1619 cq = tag; 1620 while (*cq != '\0') 1621 *cp++ = *cq++; 1622 *cp++ = '='; 1623 INSIST((size_t)(cp - buffer) < sizeof(buffer)); 1624 snprintf(cp, sizeof(buffer) - (cp - buffer), use_f ? "%.*f" : "%.*g", 1625 precision, d); 1626 cp += strlen(cp); 1627 ctl_putdata(buffer, (unsigned)(cp - buffer), 0); 1628} 1629 1630/* 1631 * ctl_putuint - write a tagged unsigned integer into the response 1632 */ 1633static void 1634ctl_putuint( 1635 const char *tag, 1636 u_long uval 1637 ) 1638{ 1639 register char *cp; 1640 register const char *cq; 1641 char buffer[200]; 1642 1643 cp = buffer; 1644 cq = tag; 1645 while (*cq != '\0') 1646 *cp++ = *cq++; 1647 1648 *cp++ = '='; 1649 INSIST((cp - buffer) < (int)sizeof(buffer)); 1650 snprintf(cp, sizeof(buffer) - (cp - buffer), "%lu", uval); 1651 cp += strlen(cp); 1652 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0); 1653} 1654 1655/* 1656 * ctl_putcal - write a decoded calendar data into the response 1657 */ 1658static void 1659ctl_putcal( 1660 const char *tag, 1661 const struct calendar *pcal 1662 ) 1663{ 1664 char buffer[100]; 1665 unsigned numch; 1666 1667 numch = snprintf(buffer, sizeof(buffer), 1668 "%s=%04d%02d%02d%02d%02d", 1669 tag, 1670 pcal->year, 1671 pcal->month, 1672 pcal->monthday, 1673 pcal->hour, 1674 pcal->minute 1675 ); 1676 INSIST(numch < sizeof(buffer)); 1677 ctl_putdata(buffer, numch, 0); 1678 1679 return; 1680} 1681 1682/* 1683 * ctl_putfs - write a decoded filestamp into the response 1684 */ 1685static void 1686ctl_putfs( 1687 const char *tag, 1688 tstamp_t uval 1689 ) 1690{ 1691 register char *cp; 1692 register const char *cq; 1693 char buffer[200]; 1694 struct tm *tm = NULL; 1695 time_t fstamp; 1696 1697 cp = buffer; 1698 cq = tag; 1699 while (*cq != '\0') 1700 *cp++ = *cq++; 1701 1702 *cp++ = '='; 1703 fstamp = uval - JAN_1970; 1704 tm = gmtime(&fstamp); 1705 if (NULL == tm) 1706 return; 1707 INSIST((cp - buffer) < (int)sizeof(buffer)); 1708 snprintf(cp, sizeof(buffer) - (cp - buffer), 1709 "%04d%02d%02d%02d%02d", tm->tm_year + 1900, 1710 tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min); 1711 cp += strlen(cp); 1712 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0); 1713} 1714 1715 1716/* 1717 * ctl_puthex - write a tagged unsigned integer, in hex, into the 1718 * response 1719 */ 1720static void 1721ctl_puthex( 1722 const char *tag, 1723 u_long uval 1724 ) 1725{ 1726 register char *cp; 1727 register const char *cq; 1728 char buffer[200]; 1729 1730 cp = buffer; 1731 cq = tag; 1732 while (*cq != '\0') 1733 *cp++ = *cq++; 1734 1735 *cp++ = '='; 1736 INSIST((cp - buffer) < (int)sizeof(buffer)); 1737 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%lx", uval); 1738 cp += strlen(cp); 1739 ctl_putdata(buffer,(unsigned)( cp - buffer ), 0); 1740} 1741 1742 1743/* 1744 * ctl_putint - write a tagged signed integer into the response 1745 */ 1746static void 1747ctl_putint( 1748 const char *tag, 1749 long ival 1750 ) 1751{ 1752 register char *cp; 1753 register const char *cq; 1754 char buffer[200]; 1755 1756 cp = buffer; 1757 cq = tag; 1758 while (*cq != '\0') 1759 *cp++ = *cq++; 1760 1761 *cp++ = '='; 1762 INSIST((cp - buffer) < (int)sizeof(buffer)); 1763 snprintf(cp, sizeof(buffer) - (cp - buffer), "%ld", ival); 1764 cp += strlen(cp); 1765 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0); 1766} 1767 1768 1769/* 1770 * ctl_putts - write a tagged timestamp, in hex, into the response 1771 */ 1772static void 1773ctl_putts( 1774 const char *tag, 1775 l_fp *ts 1776 ) 1777{ 1778 register char *cp; 1779 register const char *cq; 1780 char buffer[200]; 1781 1782 cp = buffer; 1783 cq = tag; 1784 while (*cq != '\0') 1785 *cp++ = *cq++; 1786 1787 *cp++ = '='; 1788 INSIST((size_t)(cp - buffer) < sizeof(buffer)); 1789 snprintf(cp, sizeof(buffer) - (cp - buffer), "0x%08x.%08x", 1790 (u_int)ts->l_ui, (u_int)ts->l_uf); 1791 cp += strlen(cp); 1792 ctl_putdata(buffer, (unsigned)( cp - buffer ), 0); 1793} 1794 1795 1796/* 1797 * ctl_putadr - write an IP address into the response 1798 */ 1799static void 1800ctl_putadr( 1801 const char *tag, 1802 u_int32 addr32, 1803 sockaddr_u *addr 1804 ) 1805{ 1806 register char *cp; 1807 register const char *cq; 1808 char buffer[200]; 1809 1810 cp = buffer; 1811 cq = tag; 1812 while (*cq != '\0') 1813 *cp++ = *cq++; 1814 1815 *cp++ = '='; 1816 if (NULL == addr) 1817 cq = numtoa(addr32); 1818 else 1819 cq = stoa(addr); 1820 INSIST((cp - buffer) < (int)sizeof(buffer)); 1821 snprintf(cp, sizeof(buffer) - (cp - buffer), "%s", cq); 1822 cp += strlen(cp); 1823 ctl_putdata(buffer, (unsigned)(cp - buffer), 0); 1824} 1825 1826 1827/* 1828 * ctl_putrefid - send a u_int32 refid as printable text 1829 */ 1830static void 1831ctl_putrefid( 1832 const char * tag, 1833 u_int32 refid 1834 ) 1835{ 1836 char output[16]; 1837 char * optr; 1838 char * oplim; 1839 char * iptr; 1840 char * iplim; 1841 char * past_eq; 1842 1843 optr = output; 1844 oplim = output + sizeof(output); 1845 while (optr < oplim && '\0' != *tag) 1846 *optr++ = *tag++; 1847 if (optr < oplim) { 1848 *optr++ = '='; 1849 past_eq = optr; 1850 } 1851 if (!(optr < oplim)) 1852 return; 1853 iptr = (char *)&refid; 1854 iplim = iptr + sizeof(refid); 1855 for ( ; optr < oplim && iptr < iplim && '\0' != *iptr; 1856 iptr++, optr++) 1857 if (isprint((int)*iptr)) 1858 *optr = *iptr; 1859 else 1860 *optr = '.'; 1861 if (!(optr <= oplim)) 1862 optr = past_eq; 1863 ctl_putdata(output, (u_int)(optr - output), FALSE); 1864} 1865 1866 1867/* 1868 * ctl_putarray - write a tagged eight element double array into the response 1869 */ 1870static void 1871ctl_putarray( 1872 const char *tag, 1873 double *arr, 1874 int start 1875 ) 1876{ 1877 register char *cp; 1878 register const char *cq; 1879 char buffer[200]; 1880 int i; 1881 cp = buffer; 1882 cq = tag; 1883 while (*cq != '\0') 1884 *cp++ = *cq++; 1885 *cp++ = '='; 1886 i = start; 1887 do { 1888 if (i == 0) 1889 i = NTP_SHIFT; 1890 i--; 1891 INSIST((cp - buffer) < (int)sizeof(buffer)); 1892 snprintf(cp, sizeof(buffer) - (cp - buffer), 1893 " %.2f", arr[i] * 1e3); 1894 cp += strlen(cp); 1895 } while (i != start); 1896 ctl_putdata(buffer, (unsigned)(cp - buffer), 0); 1897} 1898 1899/* 1900 * ctl_printf - put a formatted string into the data buffer 1901 */ 1902static void 1903ctl_printf( 1904 const char * fmt, 1905 ... 1906 ) 1907{ 1908 static const char * ellipsis = "[...]"; 1909 va_list va; 1910 char fmtbuf[128]; 1911 int rc; 1912 1913 va_start(va, fmt); 1914 rc = vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, va); 1915 va_end(va); 1916 if (rc < 0 || rc >= sizeof(fmtbuf)) 1917 strcpy(fmtbuf + sizeof(fmtbuf) - strlen(ellipsis) - 1, 1918 ellipsis); 1919 ctl_putdata(fmtbuf, strlen(fmtbuf), 0); 1920} 1921 1922 1923/* 1924 * ctl_putsys - output a system variable 1925 */ 1926static void 1927ctl_putsys( 1928 int varid 1929 ) 1930{ 1931 l_fp tmp; 1932 char str[256]; 1933 u_int u; 1934 double kb; 1935 double dtemp; 1936 const char *ss; 1937#ifdef AUTOKEY 1938 struct cert_info *cp; 1939#endif /* AUTOKEY */ 1940#ifdef KERNEL_PLL 1941 static struct timex ntx; 1942 static u_long ntp_adjtime_time; 1943 1944 static const double to_ms = 1945# ifdef STA_NANO 1946 1.0e-6; /* nsec to msec */ 1947# else 1948 1.0e-3; /* usec to msec */ 1949# endif 1950 1951 /* 1952 * CS_K_* variables depend on up-to-date output of ntp_adjtime() 1953 */ 1954 if (CS_KERN_FIRST <= varid && varid <= CS_KERN_LAST && 1955 current_time != ntp_adjtime_time) { 1956 ZERO(ntx); 1957 if (ntp_adjtime(&ntx) < 0) 1958 msyslog(LOG_ERR, "ntp_adjtime() for mode 6 query failed: %m"); 1959 else 1960 ntp_adjtime_time = current_time; 1961 } 1962#endif /* KERNEL_PLL */ 1963 1964 switch (varid) { 1965 1966 case CS_LEAP: 1967 ctl_putuint(sys_var[CS_LEAP].text, sys_leap); 1968 break; 1969 1970 case CS_STRATUM: 1971 ctl_putuint(sys_var[CS_STRATUM].text, sys_stratum); 1972 break; 1973 1974 case CS_PRECISION: 1975 ctl_putint(sys_var[CS_PRECISION].text, sys_precision); 1976 break; 1977 1978 case CS_ROOTDELAY: 1979 ctl_putdbl(sys_var[CS_ROOTDELAY].text, sys_rootdelay * 1980 1e3); 1981 break; 1982 1983 case CS_ROOTDISPERSION: 1984 ctl_putdbl(sys_var[CS_ROOTDISPERSION].text, 1985 sys_rootdisp * 1e3); 1986 break; 1987 1988 case CS_REFID: 1989 if (sys_stratum > 1 && sys_stratum < STRATUM_UNSPEC) 1990 ctl_putadr(sys_var[varid].text, sys_refid, NULL); 1991 else 1992 ctl_putrefid(sys_var[varid].text, sys_refid); 1993 break; 1994 1995 case CS_REFTIME: 1996 ctl_putts(sys_var[CS_REFTIME].text, &sys_reftime); 1997 break; 1998 1999 case CS_POLL: 2000 ctl_putuint(sys_var[CS_POLL].text, sys_poll); 2001 break; 2002 2003 case CS_PEERID: 2004 if (sys_peer == NULL) 2005 ctl_putuint(sys_var[CS_PEERID].text, 0); 2006 else 2007 ctl_putuint(sys_var[CS_PEERID].text, 2008 sys_peer->associd); 2009 break; 2010 2011 case CS_PEERADR: 2012 if (sys_peer != NULL && sys_peer->dstadr != NULL) 2013 ss = sptoa(&sys_peer->srcadr); 2014 else 2015 ss = "0.0.0.0:0"; 2016 ctl_putunqstr(sys_var[CS_PEERADR].text, ss, strlen(ss)); 2017 break; 2018 2019 case CS_PEERMODE: 2020 u = (sys_peer != NULL) 2021 ? sys_peer->hmode 2022 : MODE_UNSPEC; 2023 ctl_putuint(sys_var[CS_PEERMODE].text, u); 2024 break; 2025 2026 case CS_OFFSET: 2027 ctl_putdbl6(sys_var[CS_OFFSET].text, last_offset * 1e3); 2028 break; 2029 2030 case CS_DRIFT: 2031 ctl_putdbl(sys_var[CS_DRIFT].text, drift_comp * 1e6); 2032 break; 2033 2034 case CS_JITTER: 2035 ctl_putdbl6(sys_var[CS_JITTER].text, sys_jitter * 1e3); 2036 break; 2037 2038 case CS_ERROR: 2039 ctl_putdbl(sys_var[CS_ERROR].text, clock_jitter * 1e3); 2040 break; 2041 2042 case CS_CLOCK: 2043 get_systime(&tmp); 2044 ctl_putts(sys_var[CS_CLOCK].text, &tmp); 2045 break; 2046 2047 case CS_PROCESSOR: 2048#ifndef HAVE_UNAME 2049 ctl_putstr(sys_var[CS_PROCESSOR].text, str_processor, 2050 sizeof(str_processor) - 1); 2051#else 2052 ctl_putstr(sys_var[CS_PROCESSOR].text, 2053 utsnamebuf.machine, strlen(utsnamebuf.machine)); 2054#endif /* HAVE_UNAME */ 2055 break; 2056 2057 case CS_SYSTEM: 2058#ifndef HAVE_UNAME 2059 ctl_putstr(sys_var[CS_SYSTEM].text, str_system, 2060 sizeof(str_system) - 1); 2061#else 2062 snprintf(str, sizeof(str), "%s/%s", utsnamebuf.sysname, 2063 utsnamebuf.release); 2064 ctl_putstr(sys_var[CS_SYSTEM].text, str, strlen(str)); 2065#endif /* HAVE_UNAME */ 2066 break; 2067 2068 case CS_VERSION: 2069 ctl_putstr(sys_var[CS_VERSION].text, Version, 2070 strlen(Version)); 2071 break; 2072 2073 case CS_STABIL: 2074 ctl_putdbl(sys_var[CS_STABIL].text, clock_stability * 2075 1e6); 2076 break; 2077 2078 case CS_VARLIST: 2079 { 2080 char buf[CTL_MAX_DATA_LEN]; 2081 //buffPointer, firstElementPointer, buffEndPointer 2082 char *buffp, *buffend; 2083 int firstVarName; 2084 const char *ss1; 2085 int len; 2086 const struct ctl_var *k; 2087 2088 buffp = buf; 2089 buffend = buf + sizeof(buf); 2090 if (buffp + strlen(sys_var[CS_VARLIST].text) + 4 > buffend) 2091 break; /* really long var name */ 2092 2093 snprintf(buffp, sizeof(buf), "%s=\"",sys_var[CS_VARLIST].text); 2094 buffp += strlen(buffp); 2095 firstVarName = TRUE; 2096 for (k = sys_var; !(k->flags & EOV); k++) { 2097 if (k->flags & PADDING) 2098 continue; 2099 len = strlen(k->text); 2100 if (buffp + len + 1 >= buffend) 2101 break; 2102 if (!firstVarName) 2103 *buffp++ = ','; 2104 else 2105 firstVarName = FALSE; 2106 memcpy(buffp, k->text, len); 2107 buffp += len; 2108 } 2109 2110 for (k = ext_sys_var; k && !(k->flags & EOV); k++) { 2111 if (k->flags & PADDING) 2112 continue; 2113 if (NULL == k->text) 2114 continue; 2115 ss1 = strchr(k->text, '='); 2116 if (NULL == ss1) 2117 len = strlen(k->text); 2118 else 2119 len = ss1 - k->text; 2120 if (buffp + len + 1 >= buffend) 2121 break; 2122 if (firstVarName) { 2123 *buffp++ = ','; 2124 firstVarName = FALSE; 2125 } 2126 memcpy(buffp, k->text,(unsigned)len); 2127 buffp += len; 2128 } 2129 if (buffp + 2 >= buffend) 2130 break; 2131 2132 *buffp++ = '"'; 2133 *buffp = '\0'; 2134 2135 ctl_putdata(buf, (unsigned)( buffp - buf ), 0); 2136 break; 2137 } 2138 2139 case CS_TAI: 2140 if (sys_tai > 0) 2141 ctl_putuint(sys_var[CS_TAI].text, sys_tai); 2142 break; 2143 2144 case CS_LEAPTAB: 2145 { 2146 leap_signature_t lsig; 2147 leapsec_getsig(&lsig); 2148 if (lsig.ttime > 0) 2149 ctl_putfs(sys_var[CS_LEAPTAB].text, lsig.ttime); 2150 break; 2151 } 2152 2153 case CS_LEAPEND: 2154 { 2155 leap_signature_t lsig; 2156 leapsec_getsig(&lsig); 2157 if (lsig.etime > 0) 2158 ctl_putfs(sys_var[CS_LEAPEND].text, lsig.etime); 2159 break; 2160 } 2161 2162#ifdef LEAP_SMEAR 2163 case CS_LEAPSMEARINTV: 2164 if (leap_smear_intv > 0) 2165 ctl_putuint(sys_var[CS_LEAPSMEARINTV].text, leap_smear_intv); 2166 break; 2167 2168 case CS_LEAPSMEAROFFS: 2169 if (leap_smear_intv > 0) 2170 ctl_putdbl(sys_var[CS_LEAPSMEAROFFS].text, 2171 leap_smear.doffset * 1e3); 2172 break; 2173#endif /* LEAP_SMEAR */ 2174 2175 case CS_RATE: 2176 ctl_putuint(sys_var[CS_RATE].text, ntp_minpoll); 2177 break; 2178 2179 case CS_MRU_ENABLED: 2180 ctl_puthex(sys_var[varid].text, mon_enabled); 2181 break; 2182 2183 case CS_MRU_DEPTH: 2184 ctl_putuint(sys_var[varid].text, mru_entries); 2185 break; 2186 2187 case CS_MRU_MEM: 2188 kb = mru_entries * (sizeof(mon_entry) / 1024.); 2189 u = (u_int)kb; 2190 if (kb - u >= 0.5) 2191 u++; 2192 ctl_putuint(sys_var[varid].text, u); 2193 break; 2194 2195 case CS_MRU_DEEPEST: 2196 ctl_putuint(sys_var[varid].text, mru_peakentries); 2197 break; 2198 2199 case CS_MRU_MINDEPTH: 2200 ctl_putuint(sys_var[varid].text, mru_mindepth); 2201 break; 2202 2203 case CS_MRU_MAXAGE: 2204 ctl_putint(sys_var[varid].text, mru_maxage); 2205 break; 2206 2207 case CS_MRU_MAXDEPTH: 2208 ctl_putuint(sys_var[varid].text, mru_maxdepth); 2209 break; 2210 2211 case CS_MRU_MAXMEM: 2212 kb = mru_maxdepth * (sizeof(mon_entry) / 1024.); 2213 u = (u_int)kb; 2214 if (kb - u >= 0.5) 2215 u++; 2216 ctl_putuint(sys_var[varid].text, u); 2217 break; 2218 2219 case CS_SS_UPTIME: 2220 ctl_putuint(sys_var[varid].text, current_time); 2221 break; 2222 2223 case CS_SS_RESET: 2224 ctl_putuint(sys_var[varid].text, 2225 current_time - sys_stattime); 2226 break; 2227 2228 case CS_SS_RECEIVED: 2229 ctl_putuint(sys_var[varid].text, sys_received); 2230 break; 2231 2232 case CS_SS_THISVER: 2233 ctl_putuint(sys_var[varid].text, sys_newversion); 2234 break; 2235 2236 case CS_SS_OLDVER: 2237 ctl_putuint(sys_var[varid].text, sys_oldversion); 2238 break; 2239 2240 case CS_SS_BADFORMAT: 2241 ctl_putuint(sys_var[varid].text, sys_badlength); 2242 break; 2243 2244 case CS_SS_BADAUTH: 2245 ctl_putuint(sys_var[varid].text, sys_badauth); 2246 break; 2247 2248 case CS_SS_DECLINED: 2249 ctl_putuint(sys_var[varid].text, sys_declined); 2250 break; 2251 2252 case CS_SS_RESTRICTED: 2253 ctl_putuint(sys_var[varid].text, sys_restricted); 2254 break; 2255 2256 case CS_SS_LIMITED: 2257 ctl_putuint(sys_var[varid].text, sys_limitrejected); 2258 break; 2259 2260 case CS_SS_KODSENT: 2261 ctl_putuint(sys_var[varid].text, sys_kodsent); 2262 break; 2263 2264 case CS_SS_PROCESSED: 2265 ctl_putuint(sys_var[varid].text, sys_processed); 2266 break; 2267 2268 case CS_BCASTDELAY: 2269 ctl_putdbl(sys_var[varid].text, sys_bdelay * 1e3); 2270 break; 2271 2272 case CS_AUTHDELAY: 2273 LFPTOD(&sys_authdelay, dtemp); 2274 ctl_putdbl(sys_var[varid].text, dtemp * 1e3); 2275 break; 2276 2277 case CS_AUTHKEYS: 2278 ctl_putuint(sys_var[varid].text, authnumkeys); 2279 break; 2280 2281 case CS_AUTHFREEK: 2282 ctl_putuint(sys_var[varid].text, authnumfreekeys); 2283 break; 2284 2285 case CS_AUTHKLOOKUPS: 2286 ctl_putuint(sys_var[varid].text, authkeylookups); 2287 break; 2288 2289 case CS_AUTHKNOTFOUND: 2290 ctl_putuint(sys_var[varid].text, authkeynotfound); 2291 break; 2292 2293 case CS_AUTHKUNCACHED: 2294 ctl_putuint(sys_var[varid].text, authkeyuncached); 2295 break; 2296 2297 case CS_AUTHKEXPIRED: 2298 ctl_putuint(sys_var[varid].text, authkeyexpired); 2299 break; 2300 2301 case CS_AUTHENCRYPTS: 2302 ctl_putuint(sys_var[varid].text, authencryptions); 2303 break; 2304 2305 case CS_AUTHDECRYPTS: 2306 ctl_putuint(sys_var[varid].text, authdecryptions); 2307 break; 2308 2309 case CS_AUTHRESET: 2310 ctl_putuint(sys_var[varid].text, 2311 current_time - auth_timereset); 2312 break; 2313 2314 /* 2315 * CTL_IF_KERNLOOP() puts a zero if the kernel loop is 2316 * unavailable, otherwise calls putfunc with args. 2317 */ 2318#ifndef KERNEL_PLL 2319# define CTL_IF_KERNLOOP(putfunc, args) \ 2320 ctl_putint(sys_var[varid].text, 0) 2321#else 2322# define CTL_IF_KERNLOOP(putfunc, args) \ 2323 putfunc args 2324#endif 2325 2326 /* 2327 * CTL_IF_KERNPPS() puts a zero if either the kernel 2328 * loop is unavailable, or kernel hard PPS is not 2329 * active, otherwise calls putfunc with args. 2330 */ 2331#ifndef KERNEL_PLL 2332# define CTL_IF_KERNPPS(putfunc, args) \ 2333 ctl_putint(sys_var[varid].text, 0) 2334#else 2335# define CTL_IF_KERNPPS(putfunc, args) \ 2336 if (0 == ntx.shift) \ 2337 ctl_putint(sys_var[varid].text, 0); \ 2338 else \ 2339 putfunc args /* no trailing ; */ 2340#endif 2341 2342 case CS_K_OFFSET: 2343 CTL_IF_KERNLOOP( 2344 ctl_putdblf, 2345 (sys_var[varid].text, 0, -1, to_ms * ntx.offset) 2346 ); 2347 break; 2348 2349 case CS_K_FREQ: 2350 CTL_IF_KERNLOOP( 2351 ctl_putsfp, 2352 (sys_var[varid].text, ntx.freq) 2353 ); 2354 break; 2355 2356 case CS_K_MAXERR: 2357 CTL_IF_KERNLOOP( 2358 ctl_putdblf, 2359 (sys_var[varid].text, 0, 6, 2360 to_ms * ntx.maxerror) 2361 ); 2362 break; 2363 2364 case CS_K_ESTERR: 2365 CTL_IF_KERNLOOP( 2366 ctl_putdblf, 2367 (sys_var[varid].text, 0, 6, 2368 to_ms * ntx.esterror) 2369 ); 2370 break; 2371 2372 case CS_K_STFLAGS: 2373#ifndef KERNEL_PLL 2374 ss = ""; 2375#else 2376 ss = k_st_flags(ntx.status); 2377#endif 2378 ctl_putstr(sys_var[varid].text, ss, strlen(ss)); 2379 break; 2380 2381 case CS_K_TIMECONST: 2382 CTL_IF_KERNLOOP( 2383 ctl_putint, 2384 (sys_var[varid].text, ntx.constant) 2385 ); 2386 break; 2387 2388 case CS_K_PRECISION: 2389 CTL_IF_KERNLOOP( 2390 ctl_putdblf, 2391 (sys_var[varid].text, 0, 6, 2392 to_ms * ntx.precision) 2393 ); 2394 break; 2395 2396 case CS_K_FREQTOL: 2397 CTL_IF_KERNLOOP( 2398 ctl_putsfp, 2399 (sys_var[varid].text, ntx.tolerance) 2400 ); 2401 break; 2402 2403 case CS_K_PPS_FREQ: 2404 CTL_IF_KERNPPS( 2405 ctl_putsfp, 2406 (sys_var[varid].text, ntx.ppsfreq) 2407 ); 2408 break; 2409 2410 case CS_K_PPS_STABIL: 2411 CTL_IF_KERNPPS( 2412 ctl_putsfp, 2413 (sys_var[varid].text, ntx.stabil) 2414 ); 2415 break; 2416 2417 case CS_K_PPS_JITTER: 2418 CTL_IF_KERNPPS( 2419 ctl_putdbl, 2420 (sys_var[varid].text, to_ms * ntx.jitter) 2421 ); 2422 break; 2423 2424 case CS_K_PPS_CALIBDUR: 2425 CTL_IF_KERNPPS( 2426 ctl_putint, 2427 (sys_var[varid].text, 1 << ntx.shift) 2428 ); 2429 break; 2430 2431 case CS_K_PPS_CALIBS: 2432 CTL_IF_KERNPPS( 2433 ctl_putint, 2434 (sys_var[varid].text, ntx.calcnt) 2435 ); 2436 break; 2437 2438 case CS_K_PPS_CALIBERRS: 2439 CTL_IF_KERNPPS( 2440 ctl_putint, 2441 (sys_var[varid].text, ntx.errcnt) 2442 ); 2443 break; 2444 2445 case CS_K_PPS_JITEXC: 2446 CTL_IF_KERNPPS( 2447 ctl_putint, 2448 (sys_var[varid].text, ntx.jitcnt) 2449 ); 2450 break; 2451 2452 case CS_K_PPS_STBEXC: 2453 CTL_IF_KERNPPS( 2454 ctl_putint, 2455 (sys_var[varid].text, ntx.stbcnt) 2456 ); 2457 break; 2458 2459 case CS_IOSTATS_RESET: 2460 ctl_putuint(sys_var[varid].text, 2461 current_time - io_timereset); 2462 break; 2463 2464 case CS_TOTAL_RBUF: 2465 ctl_putuint(sys_var[varid].text, total_recvbuffs()); 2466 break; 2467 2468 case CS_FREE_RBUF: 2469 ctl_putuint(sys_var[varid].text, free_recvbuffs()); 2470 break; 2471 2472 case CS_USED_RBUF: 2473 ctl_putuint(sys_var[varid].text, full_recvbuffs()); 2474 break; 2475 2476 case CS_RBUF_LOWATER: 2477 ctl_putuint(sys_var[varid].text, lowater_additions()); 2478 break; 2479 2480 case CS_IO_DROPPED: 2481 ctl_putuint(sys_var[varid].text, packets_dropped); 2482 break; 2483 2484 case CS_IO_IGNORED: 2485 ctl_putuint(sys_var[varid].text, packets_ignored); 2486 break; 2487 2488 case CS_IO_RECEIVED: 2489 ctl_putuint(sys_var[varid].text, packets_received); 2490 break; 2491 2492 case CS_IO_SENT: 2493 ctl_putuint(sys_var[varid].text, packets_sent); 2494 break; 2495 2496 case CS_IO_SENDFAILED: 2497 ctl_putuint(sys_var[varid].text, packets_notsent); 2498 break; 2499 2500 case CS_IO_WAKEUPS: 2501 ctl_putuint(sys_var[varid].text, handler_calls); 2502 break; 2503 2504 case CS_IO_GOODWAKEUPS: 2505 ctl_putuint(sys_var[varid].text, handler_pkts); 2506 break; 2507 2508 case CS_TIMERSTATS_RESET: 2509 ctl_putuint(sys_var[varid].text, 2510 current_time - timer_timereset); 2511 break; 2512 2513 case CS_TIMER_OVERRUNS: 2514 ctl_putuint(sys_var[varid].text, alarm_overflow); 2515 break; 2516 2517 case CS_TIMER_XMTS: 2518 ctl_putuint(sys_var[varid].text, timer_xmtcalls); 2519 break; 2520 2521 case CS_FUZZ: 2522 ctl_putdbl(sys_var[varid].text, sys_fuzz * 1e3); 2523 break; 2524 case CS_WANDER_THRESH: 2525 ctl_putdbl(sys_var[varid].text, wander_threshold * 1e6); 2526 break; 2527#ifdef AUTOKEY 2528 case CS_FLAGS: 2529 if (crypto_flags) 2530 ctl_puthex(sys_var[CS_FLAGS].text, 2531 crypto_flags); 2532 break; 2533 2534 case CS_DIGEST: 2535 if (crypto_flags) { 2536 strlcpy(str, OBJ_nid2ln(crypto_nid), 2537 COUNTOF(str)); 2538 ctl_putstr(sys_var[CS_DIGEST].text, str, 2539 strlen(str)); 2540 } 2541 break; 2542 2543 case CS_SIGNATURE: 2544 if (crypto_flags) { 2545 const EVP_MD *dp; 2546 2547 dp = EVP_get_digestbynid(crypto_flags >> 16); 2548 strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)), 2549 COUNTOF(str)); 2550 ctl_putstr(sys_var[CS_SIGNATURE].text, str, 2551 strlen(str)); 2552 } 2553 break; 2554 2555 case CS_HOST: 2556 if (hostval.ptr != NULL) 2557 ctl_putstr(sys_var[CS_HOST].text, hostval.ptr, 2558 strlen(hostval.ptr)); 2559 break; 2560 2561 case CS_IDENT: 2562 if (sys_ident != NULL) 2563 ctl_putstr(sys_var[CS_IDENT].text, sys_ident, 2564 strlen(sys_ident)); 2565 break; 2566 2567 case CS_CERTIF: 2568 for (cp = cinfo; cp != NULL; cp = cp->link) { 2569 snprintf(str, sizeof(str), "%s %s 0x%x", 2570 cp->subject, cp->issuer, cp->flags); 2571 ctl_putstr(sys_var[CS_CERTIF].text, str, 2572 strlen(str)); 2573 ctl_putcal(sys_var[CS_REVTIME].text, &(cp->last)); 2574 } 2575 break; 2576 2577 case CS_PUBLIC: 2578 if (hostval.tstamp != 0) 2579 ctl_putfs(sys_var[CS_PUBLIC].text, 2580 ntohl(hostval.tstamp)); 2581 break; 2582#endif /* AUTOKEY */ 2583 2584 default: 2585 break; 2586 } 2587} 2588 2589 2590/* 2591 * ctl_putpeer - output a peer variable 2592 */ 2593static void 2594ctl_putpeer( 2595 int id, 2596 struct peer *p 2597 ) 2598{ 2599 char buf[CTL_MAX_DATA_LEN]; 2600 char *s; 2601 char *t; 2602 char *be; 2603 int i; 2604 const struct ctl_var *k; 2605#ifdef AUTOKEY 2606 struct autokey *ap; 2607 const EVP_MD *dp; 2608 const char *str; 2609#endif /* AUTOKEY */ 2610 2611 switch (id) { 2612 2613 case CP_CONFIG: 2614 ctl_putuint(peer_var[id].text, 2615 !(FLAG_PREEMPT & p->flags)); 2616 break; 2617 2618 case CP_AUTHENABLE: 2619 ctl_putuint(peer_var[id].text, !(p->keyid)); 2620 break; 2621 2622 case CP_AUTHENTIC: 2623 ctl_putuint(peer_var[id].text, 2624 !!(FLAG_AUTHENTIC & p->flags)); 2625 break; 2626 2627 case CP_SRCADR: 2628 ctl_putadr(peer_var[id].text, 0, &p->srcadr); 2629 break; 2630 2631 case CP_SRCPORT: 2632 ctl_putuint(peer_var[id].text, SRCPORT(&p->srcadr)); 2633 break; 2634 2635 case CP_SRCHOST: 2636 if (p->hostname != NULL) 2637 ctl_putstr(peer_var[id].text, p->hostname, 2638 strlen(p->hostname)); 2639 break; 2640 2641 case CP_DSTADR: 2642 ctl_putadr(peer_var[id].text, 0, 2643 (p->dstadr != NULL) 2644 ? &p->dstadr->sin 2645 : NULL); 2646 break; 2647 2648 case CP_DSTPORT: 2649 ctl_putuint(peer_var[id].text, 2650 (p->dstadr != NULL) 2651 ? SRCPORT(&p->dstadr->sin) 2652 : 0); 2653 break; 2654 2655 case CP_IN: 2656 if (p->r21 > 0.) 2657 ctl_putdbl(peer_var[id].text, p->r21 / 1e3); 2658 break; 2659 2660 case CP_OUT: 2661 if (p->r34 > 0.) 2662 ctl_putdbl(peer_var[id].text, p->r34 / 1e3); 2663 break; 2664 2665 case CP_RATE: 2666 ctl_putuint(peer_var[id].text, p->throttle); 2667 break; 2668 2669 case CP_LEAP: 2670 ctl_putuint(peer_var[id].text, p->leap); 2671 break; 2672 2673 case CP_HMODE: 2674 ctl_putuint(peer_var[id].text, p->hmode); 2675 break; 2676 2677 case CP_STRATUM: 2678 ctl_putuint(peer_var[id].text, p->stratum); 2679 break; 2680 2681 case CP_PPOLL: 2682 ctl_putuint(peer_var[id].text, p->ppoll); 2683 break; 2684 2685 case CP_HPOLL: 2686 ctl_putuint(peer_var[id].text, p->hpoll); 2687 break; 2688 2689 case CP_PRECISION: 2690 ctl_putint(peer_var[id].text, p->precision); 2691 break; 2692 2693 case CP_ROOTDELAY: 2694 ctl_putdbl(peer_var[id].text, p->rootdelay * 1e3); 2695 break; 2696 2697 case CP_ROOTDISPERSION: 2698 ctl_putdbl(peer_var[id].text, p->rootdisp * 1e3); 2699 break; 2700 2701 case CP_REFID: 2702#ifdef REFCLOCK 2703 if (p->flags & FLAG_REFCLOCK) { 2704 ctl_putrefid(peer_var[id].text, p->refid); 2705 break; 2706 } 2707#endif 2708 if (p->stratum > 1 && p->stratum < STRATUM_UNSPEC) 2709 ctl_putadr(peer_var[id].text, p->refid, 2710 NULL); 2711 else 2712 ctl_putrefid(peer_var[id].text, p->refid); 2713 break; 2714 2715 case CP_REFTIME: 2716 ctl_putts(peer_var[id].text, &p->reftime); 2717 break; 2718 2719 case CP_ORG: 2720 ctl_putts(peer_var[id].text, &p->aorg); 2721 break; 2722 2723 case CP_REC: 2724 ctl_putts(peer_var[id].text, &p->dst); 2725 break; 2726 2727 case CP_XMT: 2728 if (p->xleave) 2729 ctl_putdbl(peer_var[id].text, p->xleave * 1e3); 2730 break; 2731 2732 case CP_BIAS: 2733 if (p->bias != 0.) 2734 ctl_putdbl(peer_var[id].text, p->bias * 1e3); 2735 break; 2736 2737 case CP_REACH: 2738 ctl_puthex(peer_var[id].text, p->reach); 2739 break; 2740 2741 case CP_FLASH: 2742 ctl_puthex(peer_var[id].text, p->flash); 2743 break; 2744 2745 case CP_TTL: 2746#ifdef REFCLOCK 2747 if (p->flags & FLAG_REFCLOCK) { 2748 ctl_putuint(peer_var[id].text, p->ttl); 2749 break; 2750 } 2751#endif 2752 if (p->ttl > 0 && p->ttl < COUNTOF(sys_ttl)) 2753 ctl_putint(peer_var[id].text, 2754 sys_ttl[p->ttl]); 2755 break; 2756 2757 case CP_UNREACH: 2758 ctl_putuint(peer_var[id].text, p->unreach); 2759 break; 2760 2761 case CP_TIMER: 2762 ctl_putuint(peer_var[id].text, 2763 p->nextdate - current_time); 2764 break; 2765 2766 case CP_DELAY: 2767 ctl_putdbl(peer_var[id].text, p->delay * 1e3); 2768 break; 2769 2770 case CP_OFFSET: 2771 ctl_putdbl(peer_var[id].text, p->offset * 1e3); 2772 break; 2773 2774 case CP_JITTER: 2775 ctl_putdbl(peer_var[id].text, p->jitter * 1e3); 2776 break; 2777 2778 case CP_DISPERSION: 2779 ctl_putdbl(peer_var[id].text, p->disp * 1e3); 2780 break; 2781 2782 case CP_KEYID: 2783 if (p->keyid > NTP_MAXKEY) 2784 ctl_puthex(peer_var[id].text, p->keyid); 2785 else 2786 ctl_putuint(peer_var[id].text, p->keyid); 2787 break; 2788 2789 case CP_FILTDELAY: 2790 ctl_putarray(peer_var[id].text, p->filter_delay, 2791 p->filter_nextpt); 2792 break; 2793 2794 case CP_FILTOFFSET: 2795 ctl_putarray(peer_var[id].text, p->filter_offset, 2796 p->filter_nextpt); 2797 break; 2798 2799 case CP_FILTERROR: 2800 ctl_putarray(peer_var[id].text, p->filter_disp, 2801 p->filter_nextpt); 2802 break; 2803 2804 case CP_PMODE: 2805 ctl_putuint(peer_var[id].text, p->pmode); 2806 break; 2807 2808 case CP_RECEIVED: 2809 ctl_putuint(peer_var[id].text, p->received); 2810 break; 2811 2812 case CP_SENT: 2813 ctl_putuint(peer_var[id].text, p->sent); 2814 break; 2815 2816 case CP_VARLIST: 2817 s = buf; 2818 be = buf + sizeof(buf); 2819 if (strlen(peer_var[id].text) + 4 > sizeof(buf)) 2820 break; /* really long var name */ 2821 2822 snprintf(s, sizeof(buf), "%s=\"", peer_var[id].text); 2823 s += strlen(s); 2824 t = s; 2825 for (k = peer_var; !(EOV & k->flags); k++) { 2826 if (PADDING & k->flags) 2827 continue; 2828 i = strlen(k->text); 2829 if (s + i + 1 >= be) 2830 break; 2831 if (s != t) 2832 *s++ = ','; 2833 memcpy(s, k->text, i); 2834 s += i; 2835 } 2836 if (s + 2 < be) { 2837 *s++ = '"'; 2838 *s = '\0'; 2839 ctl_putdata(buf, (u_int)(s - buf), 0); 2840 } 2841 break; 2842 2843 case CP_TIMEREC: 2844 ctl_putuint(peer_var[id].text, 2845 current_time - p->timereceived); 2846 break; 2847 2848 case CP_TIMEREACH: 2849 ctl_putuint(peer_var[id].text, 2850 current_time - p->timereachable); 2851 break; 2852 2853 case CP_BADAUTH: 2854 ctl_putuint(peer_var[id].text, p->badauth); 2855 break; 2856 2857 case CP_BOGUSORG: 2858 ctl_putuint(peer_var[id].text, p->bogusorg); 2859 break; 2860 2861 case CP_OLDPKT: 2862 ctl_putuint(peer_var[id].text, p->oldpkt); 2863 break; 2864 2865 case CP_SELDISP: 2866 ctl_putuint(peer_var[id].text, p->seldisptoolarge); 2867 break; 2868 2869 case CP_SELBROKEN: 2870 ctl_putuint(peer_var[id].text, p->selbroken); 2871 break; 2872 2873 case CP_CANDIDATE: 2874 ctl_putuint(peer_var[id].text, p->status); 2875 break; 2876#ifdef AUTOKEY 2877 case CP_FLAGS: 2878 if (p->crypto) 2879 ctl_puthex(peer_var[id].text, p->crypto); 2880 break; 2881 2882 case CP_SIGNATURE: 2883 if (p->crypto) { 2884 dp = EVP_get_digestbynid(p->crypto >> 16); 2885 str = OBJ_nid2ln(EVP_MD_pkey_type(dp)); 2886 ctl_putstr(peer_var[id].text, str, strlen(str)); 2887 } 2888 break; 2889 2890 case CP_HOST: 2891 if (p->subject != NULL) 2892 ctl_putstr(peer_var[id].text, p->subject, 2893 strlen(p->subject)); 2894 break; 2895 2896 case CP_VALID: /* not used */ 2897 break; 2898 2899 case CP_INITSEQ: 2900 if (NULL == (ap = p->recval.ptr)) 2901 break; 2902 2903 ctl_putint(peer_var[CP_INITSEQ].text, ap->seq); 2904 ctl_puthex(peer_var[CP_INITKEY].text, ap->key); 2905 ctl_putfs(peer_var[CP_INITTSP].text, 2906 ntohl(p->recval.tstamp)); 2907 break; 2908 2909 case CP_IDENT: 2910 if (p->ident != NULL) 2911 ctl_putstr(peer_var[id].text, p->ident, 2912 strlen(p->ident)); 2913 break; 2914 2915 2916#endif /* AUTOKEY */ 2917 } 2918} 2919 2920 2921#ifdef REFCLOCK 2922/* 2923 * ctl_putclock - output clock variables 2924 */ 2925static void 2926ctl_putclock( 2927 int id, 2928 struct refclockstat *pcs, 2929 int mustput 2930 ) 2931{ 2932 char buf[CTL_MAX_DATA_LEN]; 2933 char *s, *t, *be; 2934 const char *ss; 2935 int i; 2936 const struct ctl_var *k; 2937 2938 switch (id) { 2939 2940 case CC_TYPE: 2941 if (mustput || pcs->clockdesc == NULL 2942 || *(pcs->clockdesc) == '\0') { 2943 ctl_putuint(clock_var[id].text, pcs->type); 2944 } 2945 break; 2946 case CC_TIMECODE: 2947 ctl_putstr(clock_var[id].text, 2948 pcs->p_lastcode, 2949 (unsigned)pcs->lencode); 2950 break; 2951 2952 case CC_POLL: 2953 ctl_putuint(clock_var[id].text, pcs->polls); 2954 break; 2955 2956 case CC_NOREPLY: 2957 ctl_putuint(clock_var[id].text, 2958 pcs->noresponse); 2959 break; 2960 2961 case CC_BADFORMAT: 2962 ctl_putuint(clock_var[id].text, 2963 pcs->badformat); 2964 break; 2965 2966 case CC_BADDATA: 2967 ctl_putuint(clock_var[id].text, 2968 pcs->baddata); 2969 break; 2970 2971 case CC_FUDGETIME1: 2972 if (mustput || (pcs->haveflags & CLK_HAVETIME1)) 2973 ctl_putdbl(clock_var[id].text, 2974 pcs->fudgetime1 * 1e3); 2975 break; 2976 2977 case CC_FUDGETIME2: 2978 if (mustput || (pcs->haveflags & CLK_HAVETIME2)) 2979 ctl_putdbl(clock_var[id].text, 2980 pcs->fudgetime2 * 1e3); 2981 break; 2982 2983 case CC_FUDGEVAL1: 2984 if (mustput || (pcs->haveflags & CLK_HAVEVAL1)) 2985 ctl_putint(clock_var[id].text, 2986 pcs->fudgeval1); 2987 break; 2988 2989 case CC_FUDGEVAL2: 2990 if (mustput || (pcs->haveflags & CLK_HAVEVAL2)) { 2991 if (pcs->fudgeval1 > 1) 2992 ctl_putadr(clock_var[id].text, 2993 pcs->fudgeval2, NULL); 2994 else 2995 ctl_putrefid(clock_var[id].text, 2996 pcs->fudgeval2); 2997 } 2998 break; 2999 3000 case CC_FLAGS: 3001 ctl_putuint(clock_var[id].text, pcs->flags); 3002 break; 3003 3004 case CC_DEVICE: 3005 if (pcs->clockdesc == NULL || 3006 *(pcs->clockdesc) == '\0') { 3007 if (mustput) 3008 ctl_putstr(clock_var[id].text, 3009 "", 0); 3010 } else { 3011 ctl_putstr(clock_var[id].text, 3012 pcs->clockdesc, 3013 strlen(pcs->clockdesc)); 3014 } 3015 break; 3016 3017 case CC_VARLIST: 3018 s = buf; 3019 be = buf + sizeof(buf); 3020 if (strlen(clock_var[CC_VARLIST].text) + 4 > 3021 sizeof(buf)) 3022 break; /* really long var name */ 3023 3024 snprintf(s, sizeof(buf), "%s=\"", 3025 clock_var[CC_VARLIST].text); 3026 s += strlen(s); 3027 t = s; 3028 3029 for (k = clock_var; !(EOV & k->flags); k++) { 3030 if (PADDING & k->flags) 3031 continue; 3032 3033 i = strlen(k->text); 3034 if (s + i + 1 >= be) 3035 break; 3036 3037 if (s != t) 3038 *s++ = ','; 3039 memcpy(s, k->text, i); 3040 s += i; 3041 } 3042 3043 for (k = pcs->kv_list; k && !(EOV & k->flags); k++) { 3044 if (PADDING & k->flags) 3045 continue; 3046 3047 ss = k->text; 3048 if (NULL == ss) 3049 continue; 3050 3051 while (*ss && *ss != '=') 3052 ss++; 3053 i = ss - k->text; 3054 if (s + i + 1 >= be) 3055 break; 3056 3057 if (s != t) 3058 *s++ = ','; 3059 memcpy(s, k->text, (unsigned)i); 3060 s += i; 3061 *s = '\0'; 3062 } 3063 if (s + 2 >= be) 3064 break; 3065 3066 *s++ = '"'; 3067 *s = '\0'; 3068 ctl_putdata(buf, (unsigned)(s - buf), 0); 3069 break; 3070 } 3071} 3072#endif 3073 3074 3075 3076/* 3077 * ctl_getitem - get the next data item from the incoming packet 3078 */ 3079static const struct ctl_var * 3080ctl_getitem( 3081 const struct ctl_var *var_list, 3082 char **data 3083 ) 3084{ 3085 /* [Bug 3008] First check the packet data sanity, then search 3086 * the key. This improves the consistency of result values: If 3087 * the result is NULL once, it will never be EOV again for this 3088 * packet; If it's EOV, it will never be NULL again until the 3089 * variable is found and processed in a given 'var_list'. (That 3090 * is, a result is returned that is neither NULL nor EOV). 3091 */ 3092 static const struct ctl_var eol = { 0, EOV, NULL }; 3093 static char buf[128]; 3094 static u_long quiet_until; 3095 const struct ctl_var *v; 3096 char *cp; 3097 char *tp; 3098 3099 /* 3100 * Part One: Validate the packet state 3101 */ 3102 3103 /* Delete leading commas and white space */ 3104 while (reqpt < reqend && (*reqpt == ',' || 3105 isspace((unsigned char)*reqpt))) 3106 reqpt++; 3107 if (reqpt >= reqend) 3108 return NULL; 3109 3110 /* Scan the string in the packet until we hit comma or 3111 * EoB. Register position of first '=' on the fly. */ 3112 for (tp = NULL, cp = reqpt; cp != reqend; ++cp) { 3113 if (*cp == '=' && tp == NULL) 3114 tp = cp; 3115 if (*cp == ',') 3116 break; 3117 } 3118 3119 /* Process payload, if any. */ 3120 *data = NULL; 3121 if (NULL != tp) { 3122 /* eventually strip white space from argument. */ 3123 const char *plhead = tp + 1; /* skip the '=' */ 3124 const char *pltail = cp; 3125 size_t plsize; 3126 3127 while (plhead != pltail && isspace((u_char)plhead[0])) 3128 ++plhead; 3129 while (plhead != pltail && isspace((u_char)pltail[-1])) 3130 --pltail; 3131 3132 /* check payload size, terminate packet on overflow */ 3133 plsize = (size_t)(pltail - plhead); 3134 if (plsize >= sizeof(buf)) 3135 goto badpacket; 3136 3137 /* copy data, NUL terminate, and set result data ptr */ 3138 memcpy(buf, plhead, plsize); 3139 buf[plsize] = '\0'; 3140 *data = buf; 3141 } else { 3142 /* no payload, current end --> current name termination */ 3143 tp = cp; 3144 } 3145 3146 /* Part Two 3147 * 3148 * Now we're sure that the packet data itself is sane. Scan the 3149 * list now. Make sure a NULL list is properly treated by 3150 * returning a synthetic End-Of-Values record. We must not 3151 * return NULL pointers after this point, or the behaviour would 3152 * become inconsistent if called several times with different 3153 * variable lists after an EoV was returned. (Such a behavior 3154 * actually caused Bug 3008.) 3155 */ 3156 3157 if (NULL == var_list) 3158 return &eol; 3159 3160 for (v = var_list; !(EOV & v->flags); ++v) 3161 if (!(PADDING & v->flags)) { 3162 /* Check if the var name matches the buffer. The 3163 * name is bracketed by [reqpt..tp] and not NUL 3164 * terminated, and it contains no '=' char. The 3165 * lookup value IS NUL-terminated but might 3166 * include a '='... We have to look out for 3167 * that! 3168 */ 3169 const char *sp1 = reqpt; 3170 const char *sp2 = v->text; 3171 3172 while ((sp1 != tp) && (*sp1 == *sp2)) { 3173 ++sp1; 3174 ++sp2; 3175 } 3176 if (sp1 == tp && (*sp2 == '\0' || *sp2 == '=')) 3177 break; 3178 } 3179 3180 /* See if we have found a valid entry or not. If found, advance 3181 * the request pointer for the next round; if not, clear the 3182 * data pointer so we have no dangling garbage here. 3183 */ 3184 if (EOV & v->flags) 3185 *data = NULL; 3186 else 3187 reqpt = cp + (cp != reqend); 3188 return v; 3189 3190 badpacket: 3191 /*TODO? somehow indicate this packet was bad, apart from syslog? */ 3192 numctlbadpkts++; 3193 NLOG(NLOG_SYSEVENT) 3194 if (quiet_until <= current_time) { 3195 quiet_until = current_time + 300; 3196 msyslog(LOG_WARNING, 3197 "Possible 'ntpdx' exploit from %s#%u (possibly spoofed)", 3198 stoa(rmt_addr), SRCPORT(rmt_addr)); 3199 } 3200 reqpt = reqend; /* never again for this packet! */ 3201 return NULL; 3202} 3203 3204 3205/* 3206 * control_unspec - response to an unspecified op-code 3207 */ 3208/*ARGSUSED*/ 3209static void 3210control_unspec( 3211 struct recvbuf *rbufp, 3212 int restrict_mask 3213 ) 3214{ 3215 struct peer *peer; 3216 3217 /* 3218 * What is an appropriate response to an unspecified op-code? 3219 * I return no errors and no data, unless a specified assocation 3220 * doesn't exist. 3221 */ 3222 if (res_associd) { 3223 peer = findpeerbyassoc(res_associd); 3224 if (NULL == peer) { 3225 ctl_error(CERR_BADASSOC); 3226 return; 3227 } 3228 rpkt.status = htons(ctlpeerstatus(peer)); 3229 } else 3230 rpkt.status = htons(ctlsysstatus()); 3231 ctl_flushpkt(0); 3232} 3233 3234 3235/* 3236 * read_status - return either a list of associd's, or a particular 3237 * peer's status. 3238 */ 3239/*ARGSUSED*/ 3240static void 3241read_status( 3242 struct recvbuf *rbufp, 3243 int restrict_mask 3244 ) 3245{ 3246 struct peer *peer; 3247 const u_char *cp; 3248 size_t n; 3249 /* a_st holds association ID, status pairs alternating */ 3250 u_short a_st[CTL_MAX_DATA_LEN / sizeof(u_short)]; 3251 3252#ifdef DEBUG 3253 if (debug > 2) 3254 printf("read_status: ID %d\n", res_associd); 3255#endif 3256 /* 3257 * Two choices here. If the specified association ID is 3258 * zero we return all known assocation ID's. Otherwise 3259 * we return a bunch of stuff about the particular peer. 3260 */ 3261 if (res_associd) { 3262 peer = findpeerbyassoc(res_associd); 3263 if (NULL == peer) { 3264 ctl_error(CERR_BADASSOC); 3265 return; 3266 } 3267 rpkt.status = htons(ctlpeerstatus(peer)); 3268 if (res_authokay) 3269 peer->num_events = 0; 3270 /* 3271 * For now, output everything we know about the 3272 * peer. May be more selective later. 3273 */ 3274 for (cp = def_peer_var; *cp != 0; cp++) 3275 ctl_putpeer((int)*cp, peer); 3276 ctl_flushpkt(0); 3277 return; 3278 } 3279 n = 0; 3280 rpkt.status = htons(ctlsysstatus()); 3281 for (peer = peer_list; peer != NULL; peer = peer->p_link) { 3282 a_st[n++] = htons(peer->associd); 3283 a_st[n++] = htons(ctlpeerstatus(peer)); 3284 /* two entries each loop iteration, so n + 1 */ 3285 if (n + 1 >= COUNTOF(a_st)) { 3286 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 3287 1); 3288 n = 0; 3289 } 3290 } 3291 if (n) 3292 ctl_putdata((void *)a_st, n * sizeof(a_st[0]), 1); 3293 ctl_flushpkt(0); 3294} 3295 3296 3297/* 3298 * read_peervars - half of read_variables() implementation 3299 */ 3300static void 3301read_peervars(void) 3302{ 3303 const struct ctl_var *v; 3304 struct peer *peer; 3305 const u_char *cp; 3306 size_t i; 3307 char * valuep; 3308 u_char wants[CP_MAXCODE + 1]; 3309 u_int gotvar; 3310 3311 /* 3312 * Wants info for a particular peer. See if we know 3313 * the guy. 3314 */ 3315 peer = findpeerbyassoc(res_associd); 3316 if (NULL == peer) { 3317 ctl_error(CERR_BADASSOC); 3318 return; 3319 } 3320 rpkt.status = htons(ctlpeerstatus(peer)); 3321 if (res_authokay) 3322 peer->num_events = 0; 3323 ZERO(wants); 3324 gotvar = 0; 3325 while (NULL != (v = ctl_getitem(peer_var, &valuep))) { 3326 if (v->flags & EOV) { 3327 ctl_error(CERR_UNKNOWNVAR); 3328 return; 3329 } 3330 INSIST(v->code < COUNTOF(wants)); 3331 wants[v->code] = 1; 3332 gotvar = 1; 3333 } 3334 if (gotvar) { 3335 for (i = 1; i < COUNTOF(wants); i++) 3336 if (wants[i]) 3337 ctl_putpeer(i, peer); 3338 } else 3339 for (cp = def_peer_var; *cp != 0; cp++) 3340 ctl_putpeer((int)*cp, peer); 3341 ctl_flushpkt(0); 3342} 3343 3344 3345/* 3346 * read_sysvars - half of read_variables() implementation 3347 */ 3348static void 3349read_sysvars(void) 3350{ 3351 const struct ctl_var *v; 3352 struct ctl_var *kv; 3353 u_int n; 3354 u_int gotvar; 3355 const u_char *cs; 3356 char * valuep; 3357 const char * pch; 3358 u_char *wants; 3359 size_t wants_count; 3360 3361 /* 3362 * Wants system variables. Figure out which he wants 3363 * and give them to him. 3364 */ 3365 rpkt.status = htons(ctlsysstatus()); 3366 if (res_authokay) 3367 ctl_sys_num_events = 0; 3368 wants_count = CS_MAXCODE + 1 + count_var(ext_sys_var); 3369 wants = emalloc_zero(wants_count); 3370 gotvar = 0; 3371 while (NULL != (v = ctl_getitem(sys_var, &valuep))) { 3372 if (!(EOV & v->flags)) { 3373 INSIST(v->code < wants_count); 3374 wants[v->code] = 1; 3375 gotvar = 1; 3376 } else { 3377 v = ctl_getitem(ext_sys_var, &valuep); 3378 if (NULL == v) { 3379 ctl_error(CERR_BADVALUE); 3380 free(wants); 3381 return; 3382 } 3383 if (EOV & v->flags) { 3384 ctl_error(CERR_UNKNOWNVAR); 3385 free(wants); 3386 return; 3387 } 3388 n = v->code + CS_MAXCODE + 1; 3389 INSIST(n < wants_count); 3390 wants[n] = 1; 3391 gotvar = 1; 3392 } 3393 } 3394 if (gotvar) { 3395 for (n = 1; n <= CS_MAXCODE; n++) 3396 if (wants[n]) 3397 ctl_putsys(n); 3398 for (n = 0; n + CS_MAXCODE + 1 < wants_count; n++) 3399 if (wants[n + CS_MAXCODE + 1]) { 3400 pch = ext_sys_var[n].text; 3401 ctl_putdata(pch, strlen(pch), 0); 3402 } 3403 } else { 3404 for (cs = def_sys_var; *cs != 0; cs++) 3405 ctl_putsys((int)*cs); 3406 for (kv = ext_sys_var; kv && !(EOV & kv->flags); kv++) 3407 if (DEF & kv->flags) 3408 ctl_putdata(kv->text, strlen(kv->text), 3409 0); 3410 } 3411 free(wants); 3412 ctl_flushpkt(0); 3413} 3414 3415 3416/* 3417 * read_variables - return the variables the caller asks for 3418 */ 3419/*ARGSUSED*/ 3420static void 3421read_variables( 3422 struct recvbuf *rbufp, 3423 int restrict_mask 3424 ) 3425{ 3426 if (res_associd) 3427 read_peervars(); 3428 else 3429 read_sysvars(); 3430} 3431 3432 3433/* 3434 * write_variables - write into variables. We only allow leap bit 3435 * writing this way. 3436 */ 3437/*ARGSUSED*/ 3438static void 3439write_variables( 3440 struct recvbuf *rbufp, 3441 int restrict_mask 3442 ) 3443{ 3444 const struct ctl_var *v; 3445 int ext_var; 3446 char *valuep; 3447 long val; 3448 size_t octets; 3449 char *vareqv; 3450 const char *t; 3451 char *tt; 3452 3453 val = 0; 3454 /* 3455 * If he's trying to write into a peer tell him no way 3456 */ 3457 if (res_associd != 0) { 3458 ctl_error(CERR_PERMISSION); 3459 return; 3460 } 3461 3462 /* 3463 * Set status 3464 */ 3465 rpkt.status = htons(ctlsysstatus()); 3466 3467 /* 3468 * Look through the variables. Dump out at the first sign of 3469 * trouble. 3470 */ 3471 while ((v = ctl_getitem(sys_var, &valuep)) != 0) { 3472 ext_var = 0; 3473 if (v->flags & EOV) { 3474 if ((v = ctl_getitem(ext_sys_var, &valuep)) != 3475 0) { 3476 if (v->flags & EOV) { 3477 ctl_error(CERR_UNKNOWNVAR); 3478 return; 3479 } 3480 ext_var = 1; 3481 } else { 3482 break; 3483 } 3484 } 3485 if (!(v->flags & CAN_WRITE)) { 3486 ctl_error(CERR_PERMISSION); 3487 return; 3488 } 3489 if (!ext_var && (*valuep == '\0' || !atoint(valuep, 3490 &val))) { 3491 ctl_error(CERR_BADFMT); 3492 return; 3493 } 3494 if (!ext_var && (val & ~LEAP_NOTINSYNC) != 0) { 3495 ctl_error(CERR_BADVALUE); 3496 return; 3497 } 3498 3499 if (ext_var) { 3500 octets = strlen(v->text) + strlen(valuep) + 2; 3501 vareqv = emalloc(octets); 3502 tt = vareqv; 3503 t = v->text; 3504 while (*t && *t != '=') 3505 *tt++ = *t++; 3506 *tt++ = '='; 3507 memcpy(tt, valuep, 1 + strlen(valuep)); 3508 set_sys_var(vareqv, 1 + strlen(vareqv), v->flags); 3509 free(vareqv); 3510 } else { 3511 ctl_error(CERR_UNSPEC); /* really */ 3512 return; 3513 } 3514 } 3515 3516 /* 3517 * If we got anything, do it. xxx nothing to do *** 3518 */ 3519 /* 3520 if (leapind != ~0 || leapwarn != ~0) { 3521 if (!leap_setleap((int)leapind, (int)leapwarn)) { 3522 ctl_error(CERR_PERMISSION); 3523 return; 3524 } 3525 } 3526 */ 3527 ctl_flushpkt(0); 3528} 3529 3530 3531/* 3532 * configure() processes ntpq :config/config-from-file, allowing 3533 * generic runtime reconfiguration. 3534 */ 3535static void configure( 3536 struct recvbuf *rbufp, 3537 int restrict_mask 3538 ) 3539{ 3540 size_t data_count; 3541 int retval; 3542 3543 /* I haven't yet implemented changes to an existing association. 3544 * Hence check if the association id is 0 3545 */ 3546 if (res_associd != 0) { 3547 ctl_error(CERR_BADVALUE); 3548 return; 3549 } 3550 3551 if (RES_NOMODIFY & restrict_mask) { 3552 snprintf(remote_config.err_msg, 3553 sizeof(remote_config.err_msg), 3554 "runtime configuration prohibited by restrict ... nomodify"); 3555 ctl_putdata(remote_config.err_msg, 3556 strlen(remote_config.err_msg), 0); 3557 ctl_flushpkt(0); 3558 NLOG(NLOG_SYSINFO) 3559 msyslog(LOG_NOTICE, 3560 "runtime config from %s rejected due to nomodify restriction", 3561 stoa(&rbufp->recv_srcadr)); 3562 sys_restricted++; 3563 return; 3564 } 3565 3566 /* Initialize the remote config buffer */ 3567 data_count = remoteconfig_cmdlength(reqpt, reqend); 3568 3569 if (data_count > sizeof(remote_config.buffer) - 2) { 3570 snprintf(remote_config.err_msg, 3571 sizeof(remote_config.err_msg), 3572 "runtime configuration failed: request too long"); 3573 ctl_putdata(remote_config.err_msg, 3574 strlen(remote_config.err_msg), 0); 3575 ctl_flushpkt(0); 3576 msyslog(LOG_NOTICE, 3577 "runtime config from %s rejected: request too long", 3578 stoa(&rbufp->recv_srcadr)); 3579 return; 3580 } 3581 /* Bug 2853 -- check if all characters were acceptable */ 3582 if (data_count != (size_t)(reqend - reqpt)) { 3583 snprintf(remote_config.err_msg, 3584 sizeof(remote_config.err_msg), 3585 "runtime configuration failed: request contains an unprintable character"); 3586 ctl_putdata(remote_config.err_msg, 3587 strlen(remote_config.err_msg), 0); 3588 ctl_flushpkt(0); 3589 msyslog(LOG_NOTICE, 3590 "runtime config from %s rejected: request contains an unprintable character: %0x", 3591 stoa(&rbufp->recv_srcadr), 3592 reqpt[data_count]); 3593 return; 3594 } 3595 3596 memcpy(remote_config.buffer, reqpt, data_count); 3597 /* The buffer has no trailing linefeed or NUL right now. For 3598 * logging, we do not want a newline, so we do that first after 3599 * adding the necessary NUL byte. 3600 */ 3601 remote_config.buffer[data_count] = '\0'; 3602 DPRINTF(1, ("Got Remote Configuration Command: %s\n", 3603 remote_config.buffer)); 3604 msyslog(LOG_NOTICE, "%s config: %s", 3605 stoa(&rbufp->recv_srcadr), 3606 remote_config.buffer); 3607 3608 /* Now we have to make sure there is a NL/NUL sequence at the 3609 * end of the buffer before we parse it. 3610 */ 3611 remote_config.buffer[data_count++] = '\n'; 3612 remote_config.buffer[data_count] = '\0'; 3613 remote_config.pos = 0; 3614 remote_config.err_pos = 0; 3615 remote_config.no_errors = 0; 3616 config_remotely(&rbufp->recv_srcadr); 3617 3618 /* 3619 * Check if errors were reported. If not, output 'Config 3620 * Succeeded'. Else output the error count. It would be nice 3621 * to output any parser error messages. 3622 */ 3623 if (0 == remote_config.no_errors) { 3624 retval = snprintf(remote_config.err_msg, 3625 sizeof(remote_config.err_msg), 3626 "Config Succeeded"); 3627 if (retval > 0) 3628 remote_config.err_pos += retval; 3629 } 3630 3631 ctl_putdata(remote_config.err_msg, remote_config.err_pos, 0); 3632 ctl_flushpkt(0); 3633 3634 DPRINTF(1, ("Reply: %s\n", remote_config.err_msg)); 3635 3636 if (remote_config.no_errors > 0) 3637 msyslog(LOG_NOTICE, "%d error in %s config", 3638 remote_config.no_errors, 3639 stoa(&rbufp->recv_srcadr)); 3640} 3641 3642 3643/* 3644 * derive_nonce - generate client-address-specific nonce value 3645 * associated with a given timestamp. 3646 */ 3647static u_int32 derive_nonce( 3648 sockaddr_u * addr, 3649 u_int32 ts_i, 3650 u_int32 ts_f 3651 ) 3652{ 3653 static u_int32 salt[4]; 3654 static u_long last_salt_update; 3655 union d_tag { 3656 u_char digest[EVP_MAX_MD_SIZE]; 3657 u_int32 extract; 3658 } d; 3659 EVP_MD_CTX *ctx; 3660 u_int len; 3661 3662 while (!salt[0] || current_time - last_salt_update >= 3600) { 3663 salt[0] = ntp_random(); 3664 salt[1] = ntp_random(); 3665 salt[2] = ntp_random(); 3666 salt[3] = ntp_random(); 3667 last_salt_update = current_time; 3668 } 3669 3670 ctx = EVP_MD_CTX_new(); 3671 EVP_DigestInit(ctx, EVP_get_digestbynid(NID_md5)); 3672 EVP_DigestUpdate(ctx, salt, sizeof(salt)); 3673 EVP_DigestUpdate(ctx, &ts_i, sizeof(ts_i)); 3674 EVP_DigestUpdate(ctx, &ts_f, sizeof(ts_f)); 3675 if (IS_IPV4(addr)) 3676 EVP_DigestUpdate(ctx, &SOCK_ADDR4(addr), 3677 sizeof(SOCK_ADDR4(addr))); 3678 else 3679 EVP_DigestUpdate(ctx, &SOCK_ADDR6(addr), 3680 sizeof(SOCK_ADDR6(addr))); 3681 EVP_DigestUpdate(ctx, &NSRCPORT(addr), sizeof(NSRCPORT(addr))); 3682 EVP_DigestUpdate(ctx, salt, sizeof(salt)); 3683 EVP_DigestFinal(ctx, d.digest, &len); 3684 EVP_MD_CTX_free(ctx); 3685 3686 return d.extract; 3687} 3688 3689 3690/* 3691 * generate_nonce - generate client-address-specific nonce string. 3692 */ 3693static void generate_nonce( 3694 struct recvbuf * rbufp, 3695 char * nonce, 3696 size_t nonce_octets 3697 ) 3698{ 3699 u_int32 derived; 3700 3701 derived = derive_nonce(&rbufp->recv_srcadr, 3702 rbufp->recv_time.l_ui, 3703 rbufp->recv_time.l_uf); 3704 snprintf(nonce, nonce_octets, "%08x%08x%08x", 3705 rbufp->recv_time.l_ui, rbufp->recv_time.l_uf, derived); 3706} 3707 3708 3709/* 3710 * validate_nonce - validate client-address-specific nonce string. 3711 * 3712 * Returns TRUE if the local calculation of the nonce matches the 3713 * client-provided value and the timestamp is recent enough. 3714 */ 3715static int validate_nonce( 3716 const char * pnonce, 3717 struct recvbuf * rbufp 3718 ) 3719{ 3720 u_int ts_i; 3721 u_int ts_f; 3722 l_fp ts; 3723 l_fp now_delta; 3724 u_int supposed; 3725 u_int derived; 3726 3727 if (3 != sscanf(pnonce, "%08x%08x%08x", &ts_i, &ts_f, &supposed)) 3728 return FALSE; 3729 3730 ts.l_ui = (u_int32)ts_i; 3731 ts.l_uf = (u_int32)ts_f; 3732 derived = derive_nonce(&rbufp->recv_srcadr, ts.l_ui, ts.l_uf); 3733 get_systime(&now_delta); 3734 L_SUB(&now_delta, &ts); 3735 3736 return (supposed == derived && now_delta.l_ui < 16); 3737} 3738 3739 3740/* 3741 * send_random_tag_value - send a randomly-generated three character 3742 * tag prefix, a '.', an index, a '=' and a 3743 * random integer value. 3744 * 3745 * To try to force clients to ignore unrecognized tags in mrulist, 3746 * reslist, and ifstats responses, the first and last rows are spiced 3747 * with randomly-generated tag names with correct .# index. Make it 3748 * three characters knowing that none of the currently-used subscripted 3749 * tags have that length, avoiding the need to test for 3750 * tag collision. 3751 */ 3752static void 3753send_random_tag_value( 3754 int indx 3755 ) 3756{ 3757 int noise; 3758 char buf[32]; 3759 3760 noise = rand() ^ (rand() << 16); 3761 buf[0] = 'a' + noise % 26; 3762 noise >>= 5; 3763 buf[1] = 'a' + noise % 26; 3764 noise >>= 5; 3765 buf[2] = 'a' + noise % 26; 3766 noise >>= 5; 3767 buf[3] = '.'; 3768 snprintf(&buf[4], sizeof(buf) - 4, "%d", indx); 3769 ctl_putuint(buf, noise); 3770} 3771 3772 3773/* 3774 * Send a MRU list entry in response to a "ntpq -c mrulist" operation. 3775 * 3776 * To keep clients honest about not depending on the order of values, 3777 * and thereby avoid being locked into ugly workarounds to maintain 3778 * backward compatibility later as new fields are added to the response, 3779 * the order is random. 3780 */ 3781static void 3782send_mru_entry( 3783 mon_entry * mon, 3784 int count 3785 ) 3786{ 3787 const char first_fmt[] = "first.%d"; 3788 const char ct_fmt[] = "ct.%d"; 3789 const char mv_fmt[] = "mv.%d"; 3790 const char rs_fmt[] = "rs.%d"; 3791 char tag[32]; 3792 u_char sent[6]; /* 6 tag=value pairs */ 3793 u_int32 noise; 3794 u_int which; 3795 u_int remaining; 3796 const char * pch; 3797 3798 remaining = COUNTOF(sent); 3799 ZERO(sent); 3800 noise = (u_int32)(rand() ^ (rand() << 16)); 3801 while (remaining > 0) { 3802 which = (noise & 7) % COUNTOF(sent); 3803 noise >>= 3; 3804 while (sent[which]) 3805 which = (which + 1) % COUNTOF(sent); 3806 3807 switch (which) { 3808 3809 case 0: 3810 snprintf(tag, sizeof(tag), addr_fmt, count); 3811 pch = sptoa(&mon->rmtadr); 3812 ctl_putunqstr(tag, pch, strlen(pch)); 3813 break; 3814 3815 case 1: 3816 snprintf(tag, sizeof(tag), last_fmt, count); 3817 ctl_putts(tag, &mon->last); 3818 break; 3819 3820 case 2: 3821 snprintf(tag, sizeof(tag), first_fmt, count); 3822 ctl_putts(tag, &mon->first); 3823 break; 3824 3825 case 3: 3826 snprintf(tag, sizeof(tag), ct_fmt, count); 3827 ctl_putint(tag, mon->count); 3828 break; 3829 3830 case 4: 3831 snprintf(tag, sizeof(tag), mv_fmt, count); 3832 ctl_putuint(tag, mon->vn_mode); 3833 break; 3834 3835 case 5: 3836 snprintf(tag, sizeof(tag), rs_fmt, count); 3837 ctl_puthex(tag, mon->flags); 3838 break; 3839 } 3840 sent[which] = TRUE; 3841 remaining--; 3842 } 3843} 3844 3845 3846/* 3847 * read_mru_list - supports ntpq's mrulist command. 3848 * 3849 * The challenge here is to match ntpdc's monlist functionality without 3850 * being limited to hundreds of entries returned total, and without 3851 * requiring state on the server. If state were required, ntpq's 3852 * mrulist command would require authentication. 3853 * 3854 * The approach was suggested by Ry Jones. A finite and variable number 3855 * of entries are retrieved per request, to avoid having responses with 3856 * such large numbers of packets that socket buffers are overflowed and 3857 * packets lost. The entries are retrieved oldest-first, taking into 3858 * account that the MRU list will be changing between each request. We 3859 * can expect to see duplicate entries for addresses updated in the MRU 3860 * list during the fetch operation. In the end, the client can assemble 3861 * a close approximation of the MRU list at the point in time the last 3862 * response was sent by ntpd. The only difference is it may be longer, 3863 * containing some number of oldest entries which have since been 3864 * reclaimed. If necessary, the protocol could be extended to zap those 3865 * from the client snapshot at the end, but so far that doesn't seem 3866 * useful. 3867 * 3868 * To accomodate the changing MRU list, the starting point for requests 3869 * after the first request is supplied as a series of last seen 3870 * timestamps and associated addresses, the newest ones the client has 3871 * received. As long as at least one of those entries hasn't been 3872 * bumped to the head of the MRU list, ntpd can pick up at that point. 3873 * Otherwise, the request is failed and it is up to ntpq to back up and 3874 * provide the next newest entry's timestamps and addresses, conceivably 3875 * backing up all the way to the starting point. 3876 * 3877 * input parameters: 3878 * nonce= Regurgitated nonce retrieved by the client 3879 * previously using CTL_OP_REQ_NONCE, demonstrating 3880 * ability to receive traffic sent to its address. 3881 * frags= Limit on datagrams (fragments) in response. Used 3882 * by newer ntpq versions instead of limit= when 3883 * retrieving multiple entries. 3884 * limit= Limit on MRU entries returned. One of frags= or 3885 * limit= must be provided. 3886 * limit=1 is a special case: Instead of fetching 3887 * beginning with the supplied starting point's 3888 * newer neighbor, fetch the supplied entry, and 3889 * in that case the #.last timestamp can be zero. 3890 * This enables fetching a single entry by IP 3891 * address. When limit is not one and frags= is 3892 * provided, the fragment limit controls. 3893 * mincount= (decimal) Return entries with count >= mincount. 3894 * laddr= Return entries associated with the server's IP 3895 * address given. No port specification is needed, 3896 * and any supplied is ignored. 3897 * resall= 0x-prefixed hex restrict bits which must all be 3898 * lit for an MRU entry to be included. 3899 * Has precedence over any resany=. 3900 * resany= 0x-prefixed hex restrict bits, at least one of 3901 * which must be list for an MRU entry to be 3902 * included. 3903 * last.0= 0x-prefixed hex l_fp timestamp of newest entry 3904 * which client previously received. 3905 * addr.0= text of newest entry's IP address and port, 3906 * IPv6 addresses in bracketed form: [::]:123 3907 * last.1= timestamp of 2nd newest entry client has. 3908 * addr.1= address of 2nd newest entry. 3909 * [...] 3910 * 3911 * ntpq provides as many last/addr pairs as will fit in a single request 3912 * packet, except for the first request in a MRU fetch operation. 3913 * 3914 * The response begins with a new nonce value to be used for any 3915 * followup request. Following the nonce is the next newer entry than 3916 * referred to by last.0 and addr.0, if the "0" entry has not been 3917 * bumped to the front. If it has, the first entry returned will be the 3918 * next entry newer than referred to by last.1 and addr.1, and so on. 3919 * If none of the referenced entries remain unchanged, the request fails 3920 * and ntpq backs up to the next earlier set of entries to resync. 3921 * 3922 * Except for the first response, the response begins with confirmation 3923 * of the entry that precedes the first additional entry provided: 3924 * 3925 * last.older= hex l_fp timestamp matching one of the input 3926 * .last timestamps, which entry now precedes the 3927 * response 0. entry in the MRU list. 3928 * addr.older= text of address corresponding to older.last. 3929 * 3930 * And in any case, a successful response contains sets of values 3931 * comprising entries, with the oldest numbered 0 and incrementing from 3932 * there: 3933 * 3934 * addr.# text of IPv4 or IPv6 address and port 3935 * last.# hex l_fp timestamp of last receipt 3936 * first.# hex l_fp timestamp of first receipt 3937 * ct.# count of packets received 3938 * mv.# mode and version 3939 * rs.# restriction mask (RES_* bits) 3940 * 3941 * Note the code currently assumes there are no valid three letter 3942 * tags sent with each row, and needs to be adjusted if that changes. 3943 * 3944 * The client should accept the values in any order, and ignore .# 3945 * values which it does not understand, to allow a smooth path to 3946 * future changes without requiring a new opcode. Clients can rely 3947 * on all *.0 values preceding any *.1 values, that is all values for 3948 * a given index number are together in the response. 3949 * 3950 * The end of the response list is noted with one or two tag=value 3951 * pairs. Unconditionally: 3952 * 3953 * now= 0x-prefixed l_fp timestamp at the server marking 3954 * the end of the operation. 3955 * 3956 * If any entries were returned, now= is followed by: 3957 * 3958 * last.newest= hex l_fp identical to last.# of the prior 3959 * entry. 3960 */ 3961static void read_mru_list( 3962 struct recvbuf *rbufp, 3963 int restrict_mask 3964 ) 3965{ 3966 static const char nulltxt[1] = { '\0' }; 3967 static const char nonce_text[] = "nonce"; 3968 static const char frags_text[] = "frags"; 3969 static const char limit_text[] = "limit"; 3970 static const char mincount_text[] = "mincount"; 3971 static const char resall_text[] = "resall"; 3972 static const char resany_text[] = "resany"; 3973 static const char maxlstint_text[] = "maxlstint"; 3974 static const char laddr_text[] = "laddr"; 3975 static const char resaxx_fmt[] = "0x%hx"; 3976 3977 u_int limit; 3978 u_short frags; 3979 u_short resall; 3980 u_short resany; 3981 int mincount; 3982 u_int maxlstint; 3983 sockaddr_u laddr; 3984 struct interface * lcladr; 3985 u_int count; 3986 u_int ui; 3987 u_int uf; 3988 l_fp last[16]; 3989 sockaddr_u addr[COUNTOF(last)]; 3990 char buf[128]; 3991 struct ctl_var * in_parms; 3992 const struct ctl_var * v; 3993 const char * val; 3994 const char * pch; 3995 char * pnonce; 3996 int nonce_valid; 3997 size_t i; 3998 int priors; 3999 u_short hash; 4000 mon_entry * mon; 4001 mon_entry * prior_mon; 4002 l_fp now; 4003 4004 if (RES_NOMRULIST & restrict_mask) { 4005 ctl_error(CERR_PERMISSION); 4006 NLOG(NLOG_SYSINFO) 4007 msyslog(LOG_NOTICE, 4008 "mrulist from %s rejected due to nomrulist restriction", 4009 stoa(&rbufp->recv_srcadr)); 4010 sys_restricted++; 4011 return; 4012 } 4013 /* 4014 * fill in_parms var list with all possible input parameters. 4015 */ 4016 in_parms = NULL; 4017 set_var(&in_parms, nonce_text, sizeof(nonce_text), 0); 4018 set_var(&in_parms, frags_text, sizeof(frags_text), 0); 4019 set_var(&in_parms, limit_text, sizeof(limit_text), 0); 4020 set_var(&in_parms, mincount_text, sizeof(mincount_text), 0); 4021 set_var(&in_parms, resall_text, sizeof(resall_text), 0); 4022 set_var(&in_parms, resany_text, sizeof(resany_text), 0); 4023 set_var(&in_parms, maxlstint_text, sizeof(maxlstint_text), 0); 4024 set_var(&in_parms, laddr_text, sizeof(laddr_text), 0); 4025 for (i = 0; i < COUNTOF(last); i++) { 4026 snprintf(buf, sizeof(buf), last_fmt, (int)i); 4027 set_var(&in_parms, buf, strlen(buf) + 1, 0); 4028 snprintf(buf, sizeof(buf), addr_fmt, (int)i); 4029 set_var(&in_parms, buf, strlen(buf) + 1, 0); 4030 } 4031 4032 /* decode input parms */ 4033 pnonce = NULL; 4034 frags = 0; 4035 limit = 0; 4036 mincount = 0; 4037 resall = 0; 4038 resany = 0; 4039 maxlstint = 0; 4040 lcladr = NULL; 4041 priors = 0; 4042 ZERO(last); 4043 ZERO(addr); 4044 4045 /* have to go through '(void*)' to drop 'const' property from pointer. 4046 * ctl_getitem()' needs some cleanup, too.... perlinger@ntp.org 4047 */ 4048 while (NULL != (v = ctl_getitem(in_parms, (void*)&val)) && 4049 !(EOV & v->flags)) { 4050 int si; 4051 4052 if (NULL == val) 4053 val = nulltxt; 4054 4055 if (!strcmp(nonce_text, v->text)) { 4056 free(pnonce); 4057 pnonce = (*val) ? estrdup(val) : NULL; 4058 } else if (!strcmp(frags_text, v->text)) { 4059 if (1 != sscanf(val, "%hu", &frags)) 4060 goto blooper; 4061 } else if (!strcmp(limit_text, v->text)) { 4062 if (1 != sscanf(val, "%u", &limit)) 4063 goto blooper; 4064 } else if (!strcmp(mincount_text, v->text)) { 4065 if (1 != sscanf(val, "%d", &mincount)) 4066 goto blooper; 4067 if (mincount < 0) 4068 mincount = 0; 4069 } else if (!strcmp(resall_text, v->text)) { 4070 if (1 != sscanf(val, resaxx_fmt, &resall)) 4071 goto blooper; 4072 } else if (!strcmp(resany_text, v->text)) { 4073 if (1 != sscanf(val, resaxx_fmt, &resany)) 4074 goto blooper; 4075 } else if (!strcmp(maxlstint_text, v->text)) { 4076 if (1 != sscanf(val, "%u", &maxlstint)) 4077 goto blooper; 4078 } else if (!strcmp(laddr_text, v->text)) { 4079 if (!decodenetnum(val, &laddr)) 4080 goto blooper; 4081 lcladr = getinterface(&laddr, 0); 4082 } else if (1 == sscanf(v->text, last_fmt, &si) && 4083 (size_t)si < COUNTOF(last)) { 4084 if (2 != sscanf(val, "0x%08x.%08x", &ui, &uf)) 4085 goto blooper; 4086 last[si].l_ui = ui; 4087 last[si].l_uf = uf; 4088 if (!SOCK_UNSPEC(&addr[si]) && si == priors) 4089 priors++; 4090 } else if (1 == sscanf(v->text, addr_fmt, &si) && 4091 (size_t)si < COUNTOF(addr)) { 4092 if (!decodenetnum(val, &addr[si])) 4093 goto blooper; 4094 if (last[si].l_ui && last[si].l_uf && si == priors) 4095 priors++; 4096 } else { 4097 DPRINTF(1, ("read_mru_list: invalid key item: '%s' (ignored)\n", 4098 v->text)); 4099 continue; 4100 4101 blooper: 4102 DPRINTF(1, ("read_mru_list: invalid param for '%s': '%s' (bailing)\n", 4103 v->text, val)); 4104 free(pnonce); 4105 pnonce = NULL; 4106 break; 4107 } 4108 } 4109 free_varlist(in_parms); 4110 in_parms = NULL; 4111 4112 /* return no responses until the nonce is validated */ 4113 if (NULL == pnonce) 4114 return; 4115 4116 nonce_valid = validate_nonce(pnonce, rbufp); 4117 free(pnonce); 4118 if (!nonce_valid) 4119 return; 4120 4121 if ((0 == frags && !(0 < limit && limit <= MRU_ROW_LIMIT)) || 4122 frags > MRU_FRAGS_LIMIT) { 4123 ctl_error(CERR_BADVALUE); 4124 return; 4125 } 4126 4127 /* 4128 * If either frags or limit is not given, use the max. 4129 */ 4130 if (0 != frags && 0 == limit) 4131 limit = UINT_MAX; 4132 else if (0 != limit && 0 == frags) 4133 frags = MRU_FRAGS_LIMIT; 4134 4135 /* 4136 * Find the starting point if one was provided. 4137 */ 4138 mon = NULL; 4139 for (i = 0; i < (size_t)priors; i++) { 4140 hash = MON_HASH(&addr[i]); 4141 for (mon = mon_hash[hash]; 4142 mon != NULL; 4143 mon = mon->hash_next) 4144 if (ADDR_PORT_EQ(&mon->rmtadr, &addr[i])) 4145 break; 4146 if (mon != NULL) { 4147 if (L_ISEQU(&mon->last, &last[i])) 4148 break; 4149 mon = NULL; 4150 } 4151 } 4152 4153 /* If a starting point was provided... */ 4154 if (priors) { 4155 /* and none could be found unmodified... */ 4156 if (NULL == mon) { 4157 /* tell ntpq to try again with older entries */ 4158 ctl_error(CERR_UNKNOWNVAR); 4159 return; 4160 } 4161 /* confirm the prior entry used as starting point */ 4162 ctl_putts("last.older", &mon->last); 4163 pch = sptoa(&mon->rmtadr); 4164 ctl_putunqstr("addr.older", pch, strlen(pch)); 4165 4166 /* 4167 * Move on to the first entry the client doesn't have, 4168 * except in the special case of a limit of one. In 4169 * that case return the starting point entry. 4170 */ 4171 if (limit > 1) 4172 mon = PREV_DLIST(mon_mru_list, mon, mru); 4173 } else { /* start with the oldest */ 4174 mon = TAIL_DLIST(mon_mru_list, mru); 4175 } 4176 4177 /* 4178 * send up to limit= entries in up to frags= datagrams 4179 */ 4180 get_systime(&now); 4181 generate_nonce(rbufp, buf, sizeof(buf)); 4182 ctl_putunqstr("nonce", buf, strlen(buf)); 4183 prior_mon = NULL; 4184 for (count = 0; 4185 mon != NULL && res_frags < frags && count < limit; 4186 mon = PREV_DLIST(mon_mru_list, mon, mru)) { 4187 4188 if (mon->count < mincount) 4189 continue; 4190 if (resall && resall != (resall & mon->flags)) 4191 continue; 4192 if (resany && !(resany & mon->flags)) 4193 continue; 4194 if (maxlstint > 0 && now.l_ui - mon->last.l_ui > 4195 maxlstint) 4196 continue; 4197 if (lcladr != NULL && mon->lcladr != lcladr) 4198 continue; 4199 4200 send_mru_entry(mon, count); 4201 if (!count) 4202 send_random_tag_value(0); 4203 count++; 4204 prior_mon = mon; 4205 } 4206 4207 /* 4208 * If this batch completes the MRU list, say so explicitly with 4209 * a now= l_fp timestamp. 4210 */ 4211 if (NULL == mon) { 4212 if (count > 1) 4213 send_random_tag_value(count - 1); 4214 ctl_putts("now", &now); 4215 /* if any entries were returned confirm the last */ 4216 if (prior_mon != NULL) 4217 ctl_putts("last.newest", &prior_mon->last); 4218 } 4219 ctl_flushpkt(0); 4220} 4221 4222 4223/* 4224 * Send a ifstats entry in response to a "ntpq -c ifstats" request. 4225 * 4226 * To keep clients honest about not depending on the order of values, 4227 * and thereby avoid being locked into ugly workarounds to maintain 4228 * backward compatibility later as new fields are added to the response, 4229 * the order is random. 4230 */ 4231static void 4232send_ifstats_entry( 4233 endpt * la, 4234 u_int ifnum 4235 ) 4236{ 4237 const char addr_fmtu[] = "addr.%u"; 4238 const char bcast_fmt[] = "bcast.%u"; 4239 const char en_fmt[] = "en.%u"; /* enabled */ 4240 const char name_fmt[] = "name.%u"; 4241 const char flags_fmt[] = "flags.%u"; 4242 const char tl_fmt[] = "tl.%u"; /* ttl */ 4243 const char mc_fmt[] = "mc.%u"; /* mcast count */ 4244 const char rx_fmt[] = "rx.%u"; 4245 const char tx_fmt[] = "tx.%u"; 4246 const char txerr_fmt[] = "txerr.%u"; 4247 const char pc_fmt[] = "pc.%u"; /* peer count */ 4248 const char up_fmt[] = "up.%u"; /* uptime */ 4249 char tag[32]; 4250 u_char sent[IFSTATS_FIELDS]; /* 12 tag=value pairs */ 4251 int noisebits; 4252 u_int32 noise; 4253 u_int which; 4254 u_int remaining; 4255 const char *pch; 4256 4257 remaining = COUNTOF(sent); 4258 ZERO(sent); 4259 noise = 0; 4260 noisebits = 0; 4261 while (remaining > 0) { 4262 if (noisebits < 4) { 4263 noise = rand() ^ (rand() << 16); 4264 noisebits = 31; 4265 } 4266 which = (noise & 0xf) % COUNTOF(sent); 4267 noise >>= 4; 4268 noisebits -= 4; 4269 4270 while (sent[which]) 4271 which = (which + 1) % COUNTOF(sent); 4272 4273 switch (which) { 4274 4275 case 0: 4276 snprintf(tag, sizeof(tag), addr_fmtu, ifnum); 4277 pch = sptoa(&la->sin); 4278 ctl_putunqstr(tag, pch, strlen(pch)); 4279 break; 4280 4281 case 1: 4282 snprintf(tag, sizeof(tag), bcast_fmt, ifnum); 4283 if (INT_BCASTOPEN & la->flags) 4284 pch = sptoa(&la->bcast); 4285 else 4286 pch = ""; 4287 ctl_putunqstr(tag, pch, strlen(pch)); 4288 break; 4289 4290 case 2: 4291 snprintf(tag, sizeof(tag), en_fmt, ifnum); 4292 ctl_putint(tag, !la->ignore_packets); 4293 break; 4294 4295 case 3: 4296 snprintf(tag, sizeof(tag), name_fmt, ifnum); 4297 ctl_putstr(tag, la->name, strlen(la->name)); 4298 break; 4299 4300 case 4: 4301 snprintf(tag, sizeof(tag), flags_fmt, ifnum); 4302 ctl_puthex(tag, (u_int)la->flags); 4303 break; 4304 4305 case 5: 4306 snprintf(tag, sizeof(tag), tl_fmt, ifnum); 4307 ctl_putint(tag, la->last_ttl); 4308 break; 4309 4310 case 6: 4311 snprintf(tag, sizeof(tag), mc_fmt, ifnum); 4312 ctl_putint(tag, la->num_mcast); 4313 break; 4314 4315 case 7: 4316 snprintf(tag, sizeof(tag), rx_fmt, ifnum); 4317 ctl_putint(tag, la->received); 4318 break; 4319 4320 case 8: 4321 snprintf(tag, sizeof(tag), tx_fmt, ifnum); 4322 ctl_putint(tag, la->sent); 4323 break; 4324 4325 case 9: 4326 snprintf(tag, sizeof(tag), txerr_fmt, ifnum); 4327 ctl_putint(tag, la->notsent); 4328 break; 4329 4330 case 10: 4331 snprintf(tag, sizeof(tag), pc_fmt, ifnum); 4332 ctl_putuint(tag, la->peercnt); 4333 break; 4334 4335 case 11: 4336 snprintf(tag, sizeof(tag), up_fmt, ifnum); 4337 ctl_putuint(tag, current_time - la->starttime); 4338 break; 4339 } 4340 sent[which] = TRUE; 4341 remaining--; 4342 } 4343 send_random_tag_value((int)ifnum); 4344} 4345 4346 4347/* 4348 * read_ifstats - send statistics for each local address, exposed by 4349 * ntpq -c ifstats 4350 */ 4351static void 4352read_ifstats( 4353 struct recvbuf * rbufp 4354 ) 4355{ 4356 u_int ifidx; 4357 endpt * la; 4358 4359 /* 4360 * loop over [0..sys_ifnum] searching ep_list for each 4361 * ifnum in turn. 4362 */ 4363 for (ifidx = 0; ifidx < sys_ifnum; ifidx++) { 4364 for (la = ep_list; la != NULL; la = la->elink) 4365 if (ifidx == la->ifnum) 4366 break; 4367 if (NULL == la) 4368 continue; 4369 /* return stats for one local address */ 4370 send_ifstats_entry(la, ifidx); 4371 } 4372 ctl_flushpkt(0); 4373} 4374 4375static void 4376sockaddrs_from_restrict_u( 4377 sockaddr_u * psaA, 4378 sockaddr_u * psaM, 4379 restrict_u * pres, 4380 int ipv6 4381 ) 4382{ 4383 ZERO(*psaA); 4384 ZERO(*psaM); 4385 if (!ipv6) { 4386 psaA->sa.sa_family = AF_INET; 4387 psaA->sa4.sin_addr.s_addr = htonl(pres->u.v4.addr); 4388 psaM->sa.sa_family = AF_INET; 4389 psaM->sa4.sin_addr.s_addr = htonl(pres->u.v4.mask); 4390 } else { 4391 psaA->sa.sa_family = AF_INET6; 4392 memcpy(&psaA->sa6.sin6_addr, &pres->u.v6.addr, 4393 sizeof(psaA->sa6.sin6_addr)); 4394 psaM->sa.sa_family = AF_INET6; 4395 memcpy(&psaM->sa6.sin6_addr, &pres->u.v6.mask, 4396 sizeof(psaA->sa6.sin6_addr)); 4397 } 4398} 4399 4400 4401/* 4402 * Send a restrict entry in response to a "ntpq -c reslist" request. 4403 * 4404 * To keep clients honest about not depending on the order of values, 4405 * and thereby avoid being locked into ugly workarounds to maintain 4406 * backward compatibility later as new fields are added to the response, 4407 * the order is random. 4408 */ 4409static void 4410send_restrict_entry( 4411 restrict_u * pres, 4412 int ipv6, 4413 u_int idx 4414 ) 4415{ 4416 const char addr_fmtu[] = "addr.%u"; 4417 const char mask_fmtu[] = "mask.%u"; 4418 const char hits_fmt[] = "hits.%u"; 4419 const char flags_fmt[] = "flags.%u"; 4420 char tag[32]; 4421 u_char sent[RESLIST_FIELDS]; /* 4 tag=value pairs */ 4422 int noisebits; 4423 u_int32 noise; 4424 u_int which; 4425 u_int remaining; 4426 sockaddr_u addr; 4427 sockaddr_u mask; 4428 const char * pch; 4429 char * buf; 4430 const char * match_str; 4431 const char * access_str; 4432 4433 sockaddrs_from_restrict_u(&addr, &mask, pres, ipv6); 4434 remaining = COUNTOF(sent); 4435 ZERO(sent); 4436 noise = 0; 4437 noisebits = 0; 4438 while (remaining > 0) { 4439 if (noisebits < 2) { 4440 noise = rand() ^ (rand() << 16); 4441 noisebits = 31; 4442 } 4443 which = (noise & 0x3) % COUNTOF(sent); 4444 noise >>= 2; 4445 noisebits -= 2; 4446 4447 while (sent[which]) 4448 which = (which + 1) % COUNTOF(sent); 4449 4450 switch (which) { 4451 4452 case 0: 4453 snprintf(tag, sizeof(tag), addr_fmtu, idx); 4454 pch = stoa(&addr); 4455 ctl_putunqstr(tag, pch, strlen(pch)); 4456 break; 4457 4458 case 1: 4459 snprintf(tag, sizeof(tag), mask_fmtu, idx); 4460 pch = stoa(&mask); 4461 ctl_putunqstr(tag, pch, strlen(pch)); 4462 break; 4463 4464 case 2: 4465 snprintf(tag, sizeof(tag), hits_fmt, idx); 4466 ctl_putuint(tag, pres->count); 4467 break; 4468 4469 case 3: 4470 snprintf(tag, sizeof(tag), flags_fmt, idx); 4471 match_str = res_match_flags(pres->mflags); 4472 access_str = res_access_flags(pres->flags); 4473 if ('\0' == match_str[0]) { 4474 pch = access_str; 4475 } else { 4476 LIB_GETBUF(buf); 4477 snprintf(buf, LIB_BUFLENGTH, "%s %s", 4478 match_str, access_str); 4479 pch = buf; 4480 } 4481 ctl_putunqstr(tag, pch, strlen(pch)); 4482 break; 4483 } 4484 sent[which] = TRUE; 4485 remaining--; 4486 } 4487 send_random_tag_value((int)idx); 4488} 4489 4490 4491static void 4492send_restrict_list( 4493 restrict_u * pres, 4494 int ipv6, 4495 u_int * pidx 4496 ) 4497{ 4498 for ( ; pres != NULL; pres = pres->link) { 4499 send_restrict_entry(pres, ipv6, *pidx); 4500 (*pidx)++; 4501 } 4502} 4503 4504 4505/* 4506 * read_addr_restrictions - returns IPv4 and IPv6 access control lists 4507 */ 4508static void 4509read_addr_restrictions( 4510 struct recvbuf * rbufp 4511) 4512{ 4513 u_int idx; 4514 4515 idx = 0; 4516 send_restrict_list(restrictlist4, FALSE, &idx); 4517 send_restrict_list(restrictlist6, TRUE, &idx); 4518 ctl_flushpkt(0); 4519} 4520 4521 4522/* 4523 * read_ordlist - CTL_OP_READ_ORDLIST_A for ntpq -c ifstats & reslist 4524 */ 4525static void 4526read_ordlist( 4527 struct recvbuf * rbufp, 4528 int restrict_mask 4529 ) 4530{ 4531 const char ifstats_s[] = "ifstats"; 4532 const size_t ifstats_chars = COUNTOF(ifstats_s) - 1; 4533 const char addr_rst_s[] = "addr_restrictions"; 4534 const size_t a_r_chars = COUNTOF(addr_rst_s) - 1; 4535 struct ntp_control * cpkt; 4536 u_short qdata_octets; 4537 4538 /* 4539 * CTL_OP_READ_ORDLIST_A was first named CTL_OP_READ_IFSTATS and 4540 * used only for ntpq -c ifstats. With the addition of reslist 4541 * the same opcode was generalized to retrieve ordered lists 4542 * which require authentication. The request data is empty or 4543 * contains "ifstats" (not null terminated) to retrieve local 4544 * addresses and associated stats. It is "addr_restrictions" 4545 * to retrieve the IPv4 then IPv6 remote address restrictions, 4546 * which are access control lists. Other request data return 4547 * CERR_UNKNOWNVAR. 4548 */ 4549 cpkt = (struct ntp_control *)&rbufp->recv_pkt; 4550 qdata_octets = ntohs(cpkt->count); 4551 if (0 == qdata_octets || (ifstats_chars == qdata_octets && 4552 !memcmp(ifstats_s, cpkt->u.data, ifstats_chars))) { 4553 read_ifstats(rbufp); 4554 return; 4555 } 4556 if (a_r_chars == qdata_octets && 4557 !memcmp(addr_rst_s, cpkt->u.data, a_r_chars)) { 4558 read_addr_restrictions(rbufp); 4559 return; 4560 } 4561 ctl_error(CERR_UNKNOWNVAR); 4562} 4563 4564 4565/* 4566 * req_nonce - CTL_OP_REQ_NONCE for ntpq -c mrulist prerequisite. 4567 */ 4568static void req_nonce( 4569 struct recvbuf * rbufp, 4570 int restrict_mask 4571 ) 4572{ 4573 char buf[64]; 4574 4575 generate_nonce(rbufp, buf, sizeof(buf)); 4576 ctl_putunqstr("nonce", buf, strlen(buf)); 4577 ctl_flushpkt(0); 4578} 4579 4580 4581/* 4582 * read_clockstatus - return clock radio status 4583 */ 4584/*ARGSUSED*/ 4585static void 4586read_clockstatus( 4587 struct recvbuf *rbufp, 4588 int restrict_mask 4589 ) 4590{ 4591#ifndef REFCLOCK 4592 /* 4593 * If no refclock support, no data to return 4594 */ 4595 ctl_error(CERR_BADASSOC); 4596#else 4597 const struct ctl_var * v; 4598 int i; 4599 struct peer * peer; 4600 char * valuep; 4601 u_char * wants; 4602 size_t wants_alloc; 4603 int gotvar; 4604 const u_char * cc; 4605 struct ctl_var * kv; 4606 struct refclockstat cs; 4607 4608 if (res_associd != 0) { 4609 peer = findpeerbyassoc(res_associd); 4610 } else { 4611 /* 4612 * Find a clock for this jerk. If the system peer 4613 * is a clock use it, else search peer_list for one. 4614 */ 4615 if (sys_peer != NULL && (FLAG_REFCLOCK & 4616 sys_peer->flags)) 4617 peer = sys_peer; 4618 else 4619 for (peer = peer_list; 4620 peer != NULL; 4621 peer = peer->p_link) 4622 if (FLAG_REFCLOCK & peer->flags) 4623 break; 4624 } 4625 if (NULL == peer || !(FLAG_REFCLOCK & peer->flags)) { 4626 ctl_error(CERR_BADASSOC); 4627 return; 4628 } 4629 /* 4630 * If we got here we have a peer which is a clock. Get his 4631 * status. 4632 */ 4633 cs.kv_list = NULL; 4634 refclock_control(&peer->srcadr, NULL, &cs); 4635 kv = cs.kv_list; 4636 /* 4637 * Look for variables in the packet. 4638 */ 4639 rpkt.status = htons(ctlclkstatus(&cs)); 4640 wants_alloc = CC_MAXCODE + 1 + count_var(kv); 4641 wants = emalloc_zero(wants_alloc); 4642 gotvar = FALSE; 4643 while (NULL != (v = ctl_getitem(clock_var, &valuep))) { 4644 if (!(EOV & v->flags)) { 4645 wants[v->code] = TRUE; 4646 gotvar = TRUE; 4647 } else { 4648 v = ctl_getitem(kv, &valuep); 4649 if (NULL == v) { 4650 ctl_error(CERR_BADVALUE); 4651 free(wants); 4652 free_varlist(cs.kv_list); 4653 return; 4654 } 4655 if (EOV & v->flags) { 4656 ctl_error(CERR_UNKNOWNVAR); 4657 free(wants); 4658 free_varlist(cs.kv_list); 4659 return; 4660 } 4661 wants[CC_MAXCODE + 1 + v->code] = TRUE; 4662 gotvar = TRUE; 4663 } 4664 } 4665 4666 if (gotvar) { 4667 for (i = 1; i <= CC_MAXCODE; i++) 4668 if (wants[i]) 4669 ctl_putclock(i, &cs, TRUE); 4670 if (kv != NULL) 4671 for (i = 0; !(EOV & kv[i].flags); i++) 4672 if (wants[i + CC_MAXCODE + 1]) 4673 ctl_putdata(kv[i].text, 4674 strlen(kv[i].text), 4675 FALSE); 4676 } else { 4677 for (cc = def_clock_var; *cc != 0; cc++) 4678 ctl_putclock((int)*cc, &cs, FALSE); 4679 for ( ; kv != NULL && !(EOV & kv->flags); kv++) 4680 if (DEF & kv->flags) 4681 ctl_putdata(kv->text, strlen(kv->text), 4682 FALSE); 4683 } 4684 4685 free(wants); 4686 free_varlist(cs.kv_list); 4687 4688 ctl_flushpkt(0); 4689#endif 4690} 4691 4692 4693/* 4694 * write_clockstatus - we don't do this 4695 */ 4696/*ARGSUSED*/ 4697static void 4698write_clockstatus( 4699 struct recvbuf *rbufp, 4700 int restrict_mask 4701 ) 4702{ 4703 ctl_error(CERR_PERMISSION); 4704} 4705 4706/* 4707 * Trap support from here on down. We send async trap messages when the 4708 * upper levels report trouble. Traps can by set either by control 4709 * messages or by configuration. 4710 */ 4711/* 4712 * set_trap - set a trap in response to a control message 4713 */ 4714static void 4715set_trap( 4716 struct recvbuf *rbufp, 4717 int restrict_mask 4718 ) 4719{ 4720 int traptype; 4721 4722 /* 4723 * See if this guy is allowed 4724 */ 4725 if (restrict_mask & RES_NOTRAP) { 4726 ctl_error(CERR_PERMISSION); 4727 return; 4728 } 4729 4730 /* 4731 * Determine his allowed trap type. 4732 */ 4733 traptype = TRAP_TYPE_PRIO; 4734 if (restrict_mask & RES_LPTRAP) 4735 traptype = TRAP_TYPE_NONPRIO; 4736 4737 /* 4738 * Call ctlsettrap() to do the work. Return 4739 * an error if it can't assign the trap. 4740 */ 4741 if (!ctlsettrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype, 4742 (int)res_version)) 4743 ctl_error(CERR_NORESOURCE); 4744 ctl_flushpkt(0); 4745} 4746 4747 4748/* 4749 * unset_trap - unset a trap in response to a control message 4750 */ 4751static void 4752unset_trap( 4753 struct recvbuf *rbufp, 4754 int restrict_mask 4755 ) 4756{ 4757 int traptype; 4758 4759 /* 4760 * We don't prevent anyone from removing his own trap unless the 4761 * trap is configured. Note we also must be aware of the 4762 * possibility that restriction flags were changed since this 4763 * guy last set his trap. Set the trap type based on this. 4764 */ 4765 traptype = TRAP_TYPE_PRIO; 4766 if (restrict_mask & RES_LPTRAP) 4767 traptype = TRAP_TYPE_NONPRIO; 4768 4769 /* 4770 * Call ctlclrtrap() to clear this out. 4771 */ 4772 if (!ctlclrtrap(&rbufp->recv_srcadr, rbufp->dstadr, traptype)) 4773 ctl_error(CERR_BADASSOC); 4774 ctl_flushpkt(0); 4775} 4776 4777 4778/* 4779 * ctlsettrap - called to set a trap 4780 */ 4781int 4782ctlsettrap( 4783 sockaddr_u *raddr, 4784 struct interface *linter, 4785 int traptype, 4786 int version 4787 ) 4788{ 4789 size_t n; 4790 struct ctl_trap *tp; 4791 struct ctl_trap *tptouse; 4792 4793 /* 4794 * See if we can find this trap. If so, we only need update 4795 * the flags and the time. 4796 */ 4797 if ((tp = ctlfindtrap(raddr, linter)) != NULL) { 4798 switch (traptype) { 4799 4800 case TRAP_TYPE_CONFIG: 4801 tp->tr_flags = TRAP_INUSE|TRAP_CONFIGURED; 4802 break; 4803 4804 case TRAP_TYPE_PRIO: 4805 if (tp->tr_flags & TRAP_CONFIGURED) 4806 return (1); /* don't change anything */ 4807 tp->tr_flags = TRAP_INUSE; 4808 break; 4809 4810 case TRAP_TYPE_NONPRIO: 4811 if (tp->tr_flags & TRAP_CONFIGURED) 4812 return (1); /* don't change anything */ 4813 tp->tr_flags = TRAP_INUSE|TRAP_NONPRIO; 4814 break; 4815 } 4816 tp->tr_settime = current_time; 4817 tp->tr_resets++; 4818 return (1); 4819 } 4820 4821 /* 4822 * First we heard of this guy. Try to find a trap structure 4823 * for him to use, clearing out lesser priority guys if we 4824 * have to. Clear out anyone who's expired while we're at it. 4825 */ 4826 tptouse = NULL; 4827 for (n = 0; n < COUNTOF(ctl_traps); n++) { 4828 tp = &ctl_traps[n]; 4829 if ((TRAP_INUSE & tp->tr_flags) && 4830 !(TRAP_CONFIGURED & tp->tr_flags) && 4831 ((tp->tr_settime + CTL_TRAPTIME) > current_time)) { 4832 tp->tr_flags = 0; 4833 num_ctl_traps--; 4834 } 4835 if (!(TRAP_INUSE & tp->tr_flags)) { 4836 tptouse = tp; 4837 } else if (!(TRAP_CONFIGURED & tp->tr_flags)) { 4838 switch (traptype) { 4839 4840 case TRAP_TYPE_CONFIG: 4841 if (tptouse == NULL) { 4842 tptouse = tp; 4843 break; 4844 } 4845 if ((TRAP_NONPRIO & tptouse->tr_flags) && 4846 !(TRAP_NONPRIO & tp->tr_flags)) 4847 break; 4848 4849 if (!(TRAP_NONPRIO & tptouse->tr_flags) 4850 && (TRAP_NONPRIO & tp->tr_flags)) { 4851 tptouse = tp; 4852 break; 4853 } 4854 if (tptouse->tr_origtime < 4855 tp->tr_origtime) 4856 tptouse = tp; 4857 break; 4858 4859 case TRAP_TYPE_PRIO: 4860 if ( TRAP_NONPRIO & tp->tr_flags) { 4861 if (tptouse == NULL || 4862 ((TRAP_INUSE & 4863 tptouse->tr_flags) && 4864 tptouse->tr_origtime < 4865 tp->tr_origtime)) 4866 tptouse = tp; 4867 } 4868 break; 4869 4870 case TRAP_TYPE_NONPRIO: 4871 break; 4872 } 4873 } 4874 } 4875 4876 /* 4877 * If we don't have room for him return an error. 4878 */ 4879 if (tptouse == NULL) 4880 return (0); 4881 4882 /* 4883 * Set up this structure for him. 4884 */ 4885 tptouse->tr_settime = tptouse->tr_origtime = current_time; 4886 tptouse->tr_count = tptouse->tr_resets = 0; 4887 tptouse->tr_sequence = 1; 4888 tptouse->tr_addr = *raddr; 4889 tptouse->tr_localaddr = linter; 4890 tptouse->tr_version = (u_char) version; 4891 tptouse->tr_flags = TRAP_INUSE; 4892 if (traptype == TRAP_TYPE_CONFIG) 4893 tptouse->tr_flags |= TRAP_CONFIGURED; 4894 else if (traptype == TRAP_TYPE_NONPRIO) 4895 tptouse->tr_flags |= TRAP_NONPRIO; 4896 num_ctl_traps++; 4897 return (1); 4898} 4899 4900 4901/* 4902 * ctlclrtrap - called to clear a trap 4903 */ 4904int 4905ctlclrtrap( 4906 sockaddr_u *raddr, 4907 struct interface *linter, 4908 int traptype 4909 ) 4910{ 4911 register struct ctl_trap *tp; 4912 4913 if ((tp = ctlfindtrap(raddr, linter)) == NULL) 4914 return (0); 4915 4916 if (tp->tr_flags & TRAP_CONFIGURED 4917 && traptype != TRAP_TYPE_CONFIG) 4918 return (0); 4919 4920 tp->tr_flags = 0; 4921 num_ctl_traps--; 4922 return (1); 4923} 4924 4925 4926/* 4927 * ctlfindtrap - find a trap given the remote and local addresses 4928 */ 4929static struct ctl_trap * 4930ctlfindtrap( 4931 sockaddr_u *raddr, 4932 struct interface *linter 4933 ) 4934{ 4935 size_t n; 4936 4937 for (n = 0; n < COUNTOF(ctl_traps); n++) 4938 if ((ctl_traps[n].tr_flags & TRAP_INUSE) 4939 && ADDR_PORT_EQ(raddr, &ctl_traps[n].tr_addr) 4940 && (linter == ctl_traps[n].tr_localaddr)) 4941 return &ctl_traps[n]; 4942 4943 return NULL; 4944} 4945 4946 4947/* 4948 * report_event - report an event to the trappers 4949 */ 4950void 4951report_event( 4952 int err, /* error code */ 4953 struct peer *peer, /* peer structure pointer */ 4954 const char *str /* protostats string */ 4955 ) 4956{ 4957 char statstr[NTP_MAXSTRLEN]; 4958 int i; 4959 size_t len; 4960 4961 /* 4962 * Report the error to the protostats file, system log and 4963 * trappers. 4964 */ 4965 if (peer == NULL) { 4966 4967 /* 4968 * Discard a system report if the number of reports of 4969 * the same type exceeds the maximum. 4970 */ 4971 if (ctl_sys_last_event != (u_char)err) 4972 ctl_sys_num_events= 0; 4973 if (ctl_sys_num_events >= CTL_SYS_MAXEVENTS) 4974 return; 4975 4976 ctl_sys_last_event = (u_char)err; 4977 ctl_sys_num_events++; 4978 snprintf(statstr, sizeof(statstr), 4979 "0.0.0.0 %04x %02x %s", 4980 ctlsysstatus(), err, eventstr(err)); 4981 if (str != NULL) { 4982 len = strlen(statstr); 4983 snprintf(statstr + len, sizeof(statstr) - len, 4984 " %s", str); 4985 } 4986 NLOG(NLOG_SYSEVENT) 4987 msyslog(LOG_INFO, "%s", statstr); 4988 } else { 4989 4990 /* 4991 * Discard a peer report if the number of reports of 4992 * the same type exceeds the maximum for that peer. 4993 */ 4994 const char * src; 4995 u_char errlast; 4996 4997 errlast = (u_char)err & ~PEER_EVENT; 4998 if (peer->last_event == errlast) 4999 peer->num_events = 0; 5000 if (peer->num_events >= CTL_PEER_MAXEVENTS) 5001 return; 5002 5003 peer->last_event = errlast; 5004 peer->num_events++; 5005 if (ISREFCLOCKADR(&peer->srcadr)) 5006 src = refnumtoa(&peer->srcadr); 5007 else 5008 src = stoa(&peer->srcadr); 5009 5010 snprintf(statstr, sizeof(statstr), 5011 "%s %04x %02x %s", src, 5012 ctlpeerstatus(peer), err, eventstr(err)); 5013 if (str != NULL) { 5014 len = strlen(statstr); 5015 snprintf(statstr + len, sizeof(statstr) - len, 5016 " %s", str); 5017 } 5018 NLOG(NLOG_PEEREVENT) 5019 msyslog(LOG_INFO, "%s", statstr); 5020 } 5021 record_proto_stats(statstr); 5022#if DEBUG 5023 if (debug) 5024 printf("event at %lu %s\n", current_time, statstr); 5025#endif 5026 5027 /* 5028 * If no trappers, return. 5029 */ 5030 if (num_ctl_traps <= 0) 5031 return; 5032 5033 /* [Bug 3119] 5034 * Peer Events should be associated with a peer -- hence the 5035 * name. But there are instances where this function is called 5036 * *without* a valid peer. This happens e.g. with an unsolicited 5037 * CryptoNAK, or when a leap second alarm is going off while 5038 * currently without a system peer. 5039 * 5040 * The most sensible approach to this seems to bail out here if 5041 * this happens. Avoiding to call this function would also 5042 * bypass the log reporting in the first part of this function, 5043 * and this is probably not the best of all options. 5044 * -*-perlinger@ntp.org-*- 5045 */ 5046 if ((err & PEER_EVENT) && !peer) 5047 return; 5048 5049 /* 5050 * Set up the outgoing packet variables 5051 */ 5052 res_opcode = CTL_OP_ASYNCMSG; 5053 res_offset = 0; 5054 res_async = TRUE; 5055 res_authenticate = FALSE; 5056 datapt = rpkt.u.data; 5057 dataend = &rpkt.u.data[CTL_MAX_DATA_LEN]; 5058 if (!(err & PEER_EVENT)) { 5059 rpkt.associd = 0; 5060 rpkt.status = htons(ctlsysstatus()); 5061 5062 /* Include the core system variables and the list. */ 5063 for (i = 1; i <= CS_VARLIST; i++) 5064 ctl_putsys(i); 5065 } else if (NULL != peer) { /* paranoia -- skip output */ 5066 rpkt.associd = htons(peer->associd); 5067 rpkt.status = htons(ctlpeerstatus(peer)); 5068 5069 /* Dump it all. Later, maybe less. */ 5070 for (i = 1; i <= CP_MAX_NOAUTOKEY; i++) 5071 ctl_putpeer(i, peer); 5072# ifdef REFCLOCK 5073 /* 5074 * for clock exception events: add clock variables to 5075 * reflect info on exception 5076 */ 5077 if (err == PEVNT_CLOCK) { 5078 struct refclockstat cs; 5079 struct ctl_var *kv; 5080 5081 cs.kv_list = NULL; 5082 refclock_control(&peer->srcadr, NULL, &cs); 5083 5084 ctl_puthex("refclockstatus", 5085 ctlclkstatus(&cs)); 5086 5087 for (i = 1; i <= CC_MAXCODE; i++) 5088 ctl_putclock(i, &cs, FALSE); 5089 for (kv = cs.kv_list; 5090 kv != NULL && !(EOV & kv->flags); 5091 kv++) 5092 if (DEF & kv->flags) 5093 ctl_putdata(kv->text, 5094 strlen(kv->text), 5095 FALSE); 5096 free_varlist(cs.kv_list); 5097 } 5098# endif /* REFCLOCK */ 5099 } 5100 5101 /* 5102 * We're done, return. 5103 */ 5104 ctl_flushpkt(0); 5105} 5106 5107 5108/* 5109 * mprintf_event - printf-style varargs variant of report_event() 5110 */ 5111int 5112mprintf_event( 5113 int evcode, /* event code */ 5114 struct peer * p, /* may be NULL */ 5115 const char * fmt, /* msnprintf format */ 5116 ... 5117 ) 5118{ 5119 va_list ap; 5120 int rc; 5121 char msg[512]; 5122 5123 va_start(ap, fmt); 5124 rc = mvsnprintf(msg, sizeof(msg), fmt, ap); 5125 va_end(ap); 5126 report_event(evcode, p, msg); 5127 5128 return rc; 5129} 5130 5131 5132/* 5133 * ctl_clr_stats - clear stat counters 5134 */ 5135void 5136ctl_clr_stats(void) 5137{ 5138 ctltimereset = current_time; 5139 numctlreq = 0; 5140 numctlbadpkts = 0; 5141 numctlresponses = 0; 5142 numctlfrags = 0; 5143 numctlerrors = 0; 5144 numctlfrags = 0; 5145 numctltooshort = 0; 5146 numctlinputresp = 0; 5147 numctlinputfrag = 0; 5148 numctlinputerr = 0; 5149 numctlbadoffset = 0; 5150 numctlbadversion = 0; 5151 numctldatatooshort = 0; 5152 numctlbadop = 0; 5153 numasyncmsgs = 0; 5154} 5155 5156static u_short 5157count_var( 5158 const struct ctl_var *k 5159 ) 5160{ 5161 u_int c; 5162 5163 if (NULL == k) 5164 return 0; 5165 5166 c = 0; 5167 while (!(EOV & (k++)->flags)) 5168 c++; 5169 5170 ENSURE(c <= USHRT_MAX); 5171 return (u_short)c; 5172} 5173 5174 5175char * 5176add_var( 5177 struct ctl_var **kv, 5178 u_long size, 5179 u_short def 5180 ) 5181{ 5182 u_short c; 5183 struct ctl_var *k; 5184 char * buf; 5185 5186 c = count_var(*kv); 5187 *kv = erealloc(*kv, (c + 2) * sizeof(**kv)); 5188 k = *kv; 5189 buf = emalloc(size); 5190 k[c].code = c; 5191 k[c].text = buf; 5192 k[c].flags = def; 5193 k[c + 1].code = 0; 5194 k[c + 1].text = NULL; 5195 k[c + 1].flags = EOV; 5196 5197 return buf; 5198} 5199 5200 5201void 5202set_var( 5203 struct ctl_var **kv, 5204 const char *data, 5205 u_long size, 5206 u_short def 5207 ) 5208{ 5209 struct ctl_var *k; 5210 const char *s; 5211 const char *t; 5212 char *td; 5213 5214 if (NULL == data || !size) 5215 return; 5216 5217 k = *kv; 5218 if (k != NULL) { 5219 while (!(EOV & k->flags)) { 5220 if (NULL == k->text) { 5221 td = emalloc(size); 5222 memcpy(td, data, size); 5223 k->text = td; 5224 k->flags = def; 5225 return; 5226 } else { 5227 s = data; 5228 t = k->text; 5229 while (*t != '=' && *s == *t) { 5230 s++; 5231 t++; 5232 } 5233 if (*s == *t && ((*t == '=') || !*t)) { 5234 td = erealloc((void *)(intptr_t)k->text, size); 5235 memcpy(td, data, size); 5236 k->text = td; 5237 k->flags = def; 5238 return; 5239 } 5240 } 5241 k++; 5242 } 5243 } 5244 td = add_var(kv, size, def); 5245 memcpy(td, data, size); 5246} 5247 5248 5249void 5250set_sys_var( 5251 const char *data, 5252 u_long size, 5253 u_short def 5254 ) 5255{ 5256 set_var(&ext_sys_var, data, size, def); 5257} 5258 5259 5260/* 5261 * get_ext_sys_var() retrieves the value of a user-defined variable or 5262 * NULL if the variable has not been setvar'd. 5263 */ 5264const char * 5265get_ext_sys_var(const char *tag) 5266{ 5267 struct ctl_var * v; 5268 size_t c; 5269 const char * val; 5270 5271 val = NULL; 5272 c = strlen(tag); 5273 for (v = ext_sys_var; !(EOV & v->flags); v++) { 5274 if (NULL != v->text && !memcmp(tag, v->text, c)) { 5275 if ('=' == v->text[c]) { 5276 val = v->text + c + 1; 5277 break; 5278 } else if ('\0' == v->text[c]) { 5279 val = ""; 5280 break; 5281 } 5282 } 5283 } 5284 5285 return val; 5286} 5287 5288 5289void 5290free_varlist( 5291 struct ctl_var *kv 5292 ) 5293{ 5294 struct ctl_var *k; 5295 if (kv) { 5296 for (k = kv; !(k->flags & EOV); k++) 5297 free((void *)(intptr_t)k->text); 5298 free((void *)kv); 5299 } 5300} 5301