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