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