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