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