1 /* 2 * Copyright (c) 1983, 1988, 1993, 1994 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by the University of 16 * California, Berkeley and its contributors. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 */ 33 34 #ifndef lint 35 static const char copyright[] = 36 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\ 37 The Regents of the University of California. All rights reserved.\n"; 38 #endif /* not lint */ 39 40 #ifndef lint 41 #if 0 42 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94"; 43 #endif 44 #endif /* not lint */ 45 46 #include <sys/cdefs.h> 47 __FBSDID("$FreeBSD$"); 48 49 /* 50 * syslogd -- log system messages 51 * 52 * This program implements a system log. It takes a series of lines. 53 * Each line may have a priority, signified as "<n>" as 54 * the first characters of the line. If this is 55 * not present, a default priority is used. 56 * 57 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will 58 * cause it to reread its configuration file. 59 * 60 * Defined Constants: 61 * 62 * MAXLINE -- the maximimum line length that can be handled. 63 * DEFUPRI -- the default priority for user messages 64 * DEFSPRI -- the default priority for kernel messages 65 * 66 * Author: Eric Allman 67 * extensive changes by Ralph Campbell 68 * more extensive changes by Eric Allman (again) 69 * Extension to log by program name as well as facility and priority 70 * by Peter da Silva. 71 * -u and -v by Harlan Stenn. 72 * Priority comparison code by Harlan Stenn. 73 */ 74 75 #define MAXLINE 1024 /* maximum line length */ 76 #define MAXSVLINE 120 /* maximum saved line length */ 77 #define DEFUPRI (LOG_USER|LOG_NOTICE) 78 #define DEFSPRI (LOG_KERN|LOG_CRIT) 79 #define TIMERINTVL 30 /* interval for checking flush, mark */ 80 #define TTYMSGTIME 1 /* timed out passed to ttymsg */ 81 82 #include <sys/param.h> 83 #include <sys/ioctl.h> 84 #include <sys/stat.h> 85 #include <sys/wait.h> 86 #include <sys/socket.h> 87 #include <sys/queue.h> 88 #include <sys/uio.h> 89 #include <sys/un.h> 90 #include <sys/time.h> 91 #include <sys/resource.h> 92 #include <sys/syslimits.h> 93 94 #include <netinet/in.h> 95 #include <netdb.h> 96 #include <arpa/inet.h> 97 98 #include <ctype.h> 99 #include <err.h> 100 #include <errno.h> 101 #include <fcntl.h> 102 #include <limits.h> 103 #include <paths.h> 104 #include <signal.h> 105 #include <stdio.h> 106 #include <stdlib.h> 107 #include <string.h> 108 #include <sysexits.h> 109 #include <unistd.h> 110 #include <utmp.h> 111 112 #include "pathnames.h" 113 #include "ttymsg.h" 114 115 #define SYSLOG_NAMES 116 #include <sys/syslog.h> 117 118 #ifdef NI_WITHSCOPEID 119 static const int withscopeid = NI_WITHSCOPEID; 120 #else 121 static const int withscopeid; 122 #endif 123 124 const char *ConfFile = _PATH_LOGCONF; 125 const char *PidFile = _PATH_LOGPID; 126 const char ctty[] = _PATH_CONSOLE; 127 128 #define dprintf if (Debug) printf 129 130 #define MAXUNAMES 20 /* maximum number of user names */ 131 132 #define MAXFUNIX 20 133 134 int nfunix = 1; 135 const char *funixn[MAXFUNIX] = { _PATH_LOG }; 136 int funix[MAXFUNIX]; 137 138 /* 139 * Flags to logmsg(). 140 */ 141 142 #define IGN_CONS 0x001 /* don't print on console */ 143 #define SYNC_FILE 0x002 /* do fsync on file after printing */ 144 #define ADDDATE 0x004 /* add a date to the message */ 145 #define MARK 0x008 /* this message is a mark */ 146 #define ISKERNEL 0x010 /* kernel generated message */ 147 148 /* 149 * This structure represents the files that will have log 150 * copies printed. 151 */ 152 153 struct filed { 154 struct filed *f_next; /* next in linked list */ 155 short f_type; /* entry type, see below */ 156 short f_file; /* file descriptor */ 157 time_t f_time; /* time this was last written */ 158 char *f_host; /* host from which to recd. */ 159 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */ 160 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */ 161 #define PRI_LT 0x1 162 #define PRI_EQ 0x2 163 #define PRI_GT 0x4 164 char *f_program; /* program this applies to */ 165 union { 166 char f_uname[MAXUNAMES][UT_NAMESIZE+1]; 167 struct { 168 char f_hname[MAXHOSTNAMELEN]; 169 struct addrinfo *f_addr; 170 171 } f_forw; /* forwarding address */ 172 char f_fname[MAXPATHLEN]; 173 struct { 174 char f_pname[MAXPATHLEN]; 175 pid_t f_pid; 176 } f_pipe; 177 } f_un; 178 char f_prevline[MAXSVLINE]; /* last message logged */ 179 char f_lasttime[16]; /* time of last occurrence */ 180 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */ 181 int f_prevpri; /* pri of f_prevline */ 182 int f_prevlen; /* length of f_prevline */ 183 int f_prevcount; /* repetition cnt of prevline */ 184 u_int f_repeatcount; /* number of "repeated" msgs */ 185 }; 186 187 /* 188 * Queue of about-to-be dead processes we should watch out for. 189 */ 190 191 TAILQ_HEAD(stailhead, deadq_entry) deadq_head; 192 struct stailhead *deadq_headp; 193 194 struct deadq_entry { 195 pid_t dq_pid; 196 int dq_timeout; 197 TAILQ_ENTRY(deadq_entry) dq_entries; 198 }; 199 200 /* 201 * The timeout to apply to processes waiting on the dead queue. Unit 202 * of measure is `mark intervals', i.e. 20 minutes by default. 203 * Processes on the dead queue will be terminated after that time. 204 */ 205 206 #define DQ_TIMO_INIT 2 207 208 typedef struct deadq_entry *dq_t; 209 210 211 /* 212 * Struct to hold records of network addresses that are allowed to log 213 * to us. 214 */ 215 struct allowedpeer { 216 int isnumeric; 217 u_short port; 218 union { 219 struct { 220 struct sockaddr_storage addr; 221 struct sockaddr_storage mask; 222 } numeric; 223 char *name; 224 } u; 225 #define a_addr u.numeric.addr 226 #define a_mask u.numeric.mask 227 #define a_name u.name 228 }; 229 230 231 /* 232 * Intervals at which we flush out "message repeated" messages, 233 * in seconds after previous message is logged. After each flush, 234 * we move to the next interval until we reach the largest. 235 */ 236 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */ 237 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1) 238 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount]) 239 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \ 240 (f)->f_repeatcount = MAXREPEAT; \ 241 } 242 243 /* values for f_type */ 244 #define F_UNUSED 0 /* unused entry */ 245 #define F_FILE 1 /* regular file */ 246 #define F_TTY 2 /* terminal */ 247 #define F_CONSOLE 3 /* console terminal */ 248 #define F_FORW 4 /* remote machine */ 249 #define F_USERS 5 /* list of users */ 250 #define F_WALL 6 /* everyone logged on */ 251 #define F_PIPE 7 /* pipe to program */ 252 253 const char *TypeNames[8] = { 254 "UNUSED", "FILE", "TTY", "CONSOLE", 255 "FORW", "USERS", "WALL", "PIPE" 256 }; 257 258 static struct filed *Files; /* Log files that we write to */ 259 static struct filed consfile; /* Console */ 260 261 static int Debug; /* debug flag */ 262 static int resolve = 1; /* resolve hostname */ 263 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */ 264 static char *LocalDomain; /* our local domain name */ 265 static int *finet; /* Internet datagram socket */ 266 static int fklog = -1; /* /dev/klog */ 267 static int Initialized; /* set when we have initialized ourselves */ 268 static int MarkInterval = 20 * 60; /* interval between marks in seconds */ 269 static int MarkSeq; /* mark sequence number */ 270 static int SecureMode; /* when true, receive only unix domain socks */ 271 #ifdef INET6 272 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */ 273 #else 274 static int family = PF_INET; /* protocol family (IPv4 only) */ 275 #endif 276 static int send_to_all; /* send message to all IPv4/IPv6 addresses */ 277 static int use_bootfile; /* log entire bootfile for every kern msg */ 278 static int no_compress; /* don't compress messages (1=pipes, 2=all) */ 279 280 static char bootfile[MAXLINE+1]; /* booted kernel file */ 281 282 struct allowedpeer *AllowedPeers; /* List of allowed peers */ 283 static int NumAllowed; /* Number of entries in AllowedPeers */ 284 285 static int UniquePriority; /* Only log specified priority? */ 286 static int LogFacPri; /* Put facility and priority in log message: */ 287 /* 0=no, 1=numeric, 2=names */ 288 static int KeepKernFac; /* Keep remotely logged kernel facility */ 289 290 volatile sig_atomic_t MarkSet, WantDie; 291 292 static int allowaddr(char *); 293 static void cfline(const char *, struct filed *, 294 const char *, const char *); 295 static const char *cvthname(struct sockaddr *); 296 static void deadq_enter(pid_t, const char *); 297 static int deadq_remove(pid_t); 298 static int decode(const char *, CODE *); 299 static void die(int); 300 static void dodie(int); 301 static void domark(int); 302 static void fprintlog(struct filed *, int, const char *); 303 static int *socksetup(int, const char *); 304 static void init(int); 305 static void logerror(const char *); 306 static void logmsg(int, const char *, const char *, int); 307 static void log_deadchild(pid_t, int, const char *); 308 static void markit(void); 309 static void printline(const char *, char *); 310 static void printsys(char *); 311 static int p_open(const char *, pid_t *); 312 static void readklog(void); 313 static void reapchild(int); 314 static void usage(void); 315 static int validate(struct sockaddr *, const char *); 316 static void unmapped(struct sockaddr *); 317 static void wallmsg(struct filed *, struct iovec *); 318 static int waitdaemon(int, int, int); 319 static void timedout(int); 320 321 int 322 main(int argc, char *argv[]) 323 { 324 int ch, i, fdsrmax = 0, l; 325 struct sockaddr_un sunx, fromunix; 326 struct sockaddr_storage frominet; 327 fd_set *fdsr = NULL; 328 FILE *fp; 329 char line[MAXLINE + 1]; 330 const char *bindhostname, *hname; 331 struct timeval tv, *tvp; 332 struct sigaction sact; 333 sigset_t mask; 334 pid_t ppid = 1; 335 socklen_t len; 336 337 bindhostname = NULL; 338 while ((ch = getopt(argc, argv, "46Aa:b:cdf:kl:m:nop:P:suv")) != -1) 339 switch (ch) { 340 case '4': 341 family = PF_INET; 342 break; 343 #ifdef INET6 344 case '6': 345 family = PF_INET6; 346 break; 347 #endif 348 case 'A': 349 send_to_all++; 350 break; 351 case 'a': /* allow specific network addresses only */ 352 if (allowaddr(optarg) == -1) 353 usage(); 354 break; 355 case 'b': 356 bindhostname = optarg; 357 break; 358 case 'c': 359 no_compress++; 360 break; 361 case 'd': /* debug */ 362 Debug++; 363 break; 364 case 'f': /* configuration file */ 365 ConfFile = optarg; 366 break; 367 case 'k': /* keep remote kern fac */ 368 KeepKernFac = 1; 369 break; 370 case 'l': 371 if (nfunix < MAXFUNIX) 372 funixn[nfunix++] = optarg; 373 else 374 warnx("out of descriptors, ignoring %s", 375 optarg); 376 break; 377 case 'm': /* mark interval */ 378 MarkInterval = atoi(optarg) * 60; 379 break; 380 case 'n': 381 resolve = 0; 382 break; 383 case 'o': 384 use_bootfile = 1; 385 break; 386 case 'p': /* path */ 387 funixn[0] = optarg; 388 break; 389 case 'P': /* path for alt. PID */ 390 PidFile = optarg; 391 break; 392 case 's': /* no network mode */ 393 SecureMode++; 394 break; 395 case 'u': /* only log specified priority */ 396 UniquePriority++; 397 break; 398 case 'v': /* log facility and priority */ 399 LogFacPri++; 400 break; 401 case '?': 402 default: 403 usage(); 404 } 405 if ((argc -= optind) != 0) 406 usage(); 407 408 if (!Debug) { 409 ppid = waitdaemon(0, 0, 30); 410 if (ppid < 0) 411 err(1, "could not become daemon"); 412 } else { 413 setlinebuf(stdout); 414 } 415 416 if (NumAllowed) 417 endservent(); 418 419 consfile.f_type = F_CONSOLE; 420 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1, 421 sizeof(consfile.f_un.f_fname)); 422 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile)); 423 (void)signal(SIGTERM, dodie); 424 (void)signal(SIGINT, Debug ? dodie : SIG_IGN); 425 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN); 426 /* 427 * We don't want the SIGCHLD and SIGHUP handlers to interfere 428 * with each other; they are likely candidates for being called 429 * simultaneously (SIGHUP closes pipe descriptor, process dies, 430 * SIGCHLD happens). 431 */ 432 sigemptyset(&mask); 433 sigaddset(&mask, SIGHUP); 434 sact.sa_handler = reapchild; 435 sact.sa_mask = mask; 436 sact.sa_flags = SA_RESTART; 437 (void)sigaction(SIGCHLD, &sact, NULL); 438 (void)signal(SIGALRM, domark); 439 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */ 440 (void)alarm(TIMERINTVL); 441 442 TAILQ_INIT(&deadq_head); 443 444 #ifndef SUN_LEN 445 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2) 446 #endif 447 for (i = 0; i < nfunix; i++) { 448 (void)unlink(funixn[i]); 449 memset(&sunx, 0, sizeof(sunx)); 450 sunx.sun_family = AF_UNIX; 451 (void)strlcpy(sunx.sun_path, funixn[i], sizeof(sunx.sun_path)); 452 funix[i] = socket(AF_UNIX, SOCK_DGRAM, 0); 453 if (funix[i] < 0 || 454 bind(funix[i], (struct sockaddr *)&sunx, 455 SUN_LEN(&sunx)) < 0 || 456 chmod(funixn[i], 0666) < 0) { 457 (void)snprintf(line, sizeof line, 458 "cannot create %s", funixn[i]); 459 logerror(line); 460 dprintf("cannot create %s (%d)\n", funixn[i], errno); 461 if (i == 0) 462 die(0); 463 } 464 } 465 if (SecureMode <= 1) 466 finet = socksetup(family, bindhostname); 467 468 if (finet) { 469 if (SecureMode) { 470 for (i = 0; i < *finet; i++) { 471 if (shutdown(finet[i+1], SHUT_RD) < 0) { 472 logerror("shutdown"); 473 if (!Debug) 474 die(0); 475 } 476 } 477 } else { 478 dprintf("listening on inet and/or inet6 socket\n"); 479 } 480 dprintf("sending on inet and/or inet6 socket\n"); 481 } 482 483 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0) 484 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0) 485 fklog = -1; 486 if (fklog < 0) 487 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno); 488 489 /* tuck my process id away */ 490 fp = fopen(PidFile, "w"); 491 if (fp != NULL) { 492 fprintf(fp, "%d\n", getpid()); 493 (void)fclose(fp); 494 } 495 496 dprintf("off & running....\n"); 497 498 init(0); 499 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */ 500 sigemptyset(&mask); 501 sigaddset(&mask, SIGCHLD); 502 sact.sa_handler = init; 503 sact.sa_mask = mask; 504 sact.sa_flags = SA_RESTART; 505 (void)sigaction(SIGHUP, &sact, NULL); 506 507 tvp = &tv; 508 tv.tv_sec = tv.tv_usec = 0; 509 510 if (fklog != -1 && fklog > fdsrmax) 511 fdsrmax = fklog; 512 if (finet && !SecureMode) { 513 for (i = 0; i < *finet; i++) { 514 if (finet[i+1] != -1 && finet[i+1] > fdsrmax) 515 fdsrmax = finet[i+1]; 516 } 517 } 518 for (i = 0; i < nfunix; i++) { 519 if (funix[i] != -1 && funix[i] > fdsrmax) 520 fdsrmax = funix[i]; 521 } 522 523 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS), 524 sizeof(fd_mask)); 525 if (fdsr == NULL) 526 errx(1, "calloc fd_set"); 527 528 for (;;) { 529 if (MarkSet) 530 markit(); 531 if (WantDie) 532 die(WantDie); 533 534 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) * 535 sizeof(fd_mask)); 536 537 if (fklog != -1) 538 FD_SET(fklog, fdsr); 539 if (finet && !SecureMode) { 540 for (i = 0; i < *finet; i++) { 541 if (finet[i+1] != -1) 542 FD_SET(finet[i+1], fdsr); 543 } 544 } 545 for (i = 0; i < nfunix; i++) { 546 if (funix[i] != -1) 547 FD_SET(funix[i], fdsr); 548 } 549 550 i = select(fdsrmax+1, fdsr, NULL, NULL, tvp); 551 switch (i) { 552 case 0: 553 if (tvp) { 554 tvp = NULL; 555 if (ppid != 1) 556 kill(ppid, SIGALRM); 557 } 558 continue; 559 case -1: 560 if (errno != EINTR) 561 logerror("select"); 562 continue; 563 } 564 if (fklog != -1 && FD_ISSET(fklog, fdsr)) 565 readklog(); 566 if (finet && !SecureMode) { 567 for (i = 0; i < *finet; i++) { 568 if (FD_ISSET(finet[i+1], fdsr)) { 569 len = sizeof(frominet); 570 l = recvfrom(finet[i+1], line, MAXLINE, 571 0, (struct sockaddr *)&frominet, 572 &len); 573 if (l > 0) { 574 line[l] = '\0'; 575 hname = cvthname((struct sockaddr *)&frominet); 576 unmapped((struct sockaddr *)&frominet); 577 if (validate((struct sockaddr *)&frominet, hname)) 578 printline(hname, line); 579 } else if (l < 0 && errno != EINTR) 580 logerror("recvfrom inet"); 581 } 582 } 583 } 584 for (i = 0; i < nfunix; i++) { 585 if (funix[i] != -1 && FD_ISSET(funix[i], fdsr)) { 586 len = sizeof(fromunix); 587 l = recvfrom(funix[i], line, MAXLINE, 0, 588 (struct sockaddr *)&fromunix, &len); 589 if (l > 0) { 590 line[l] = '\0'; 591 printline(LocalHostName, line); 592 } else if (l < 0 && errno != EINTR) 593 logerror("recvfrom unix"); 594 } 595 } 596 } 597 if (fdsr) 598 free(fdsr); 599 } 600 601 static void 602 unmapped(struct sockaddr *sa) 603 { 604 struct sockaddr_in6 *sin6; 605 struct sockaddr_in sin4; 606 607 if (sa->sa_family != AF_INET6) 608 return; 609 if (sa->sa_len != sizeof(struct sockaddr_in6) || 610 sizeof(sin4) > sa->sa_len) 611 return; 612 sin6 = (struct sockaddr_in6 *)sa; 613 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) 614 return; 615 616 memset(&sin4, 0, sizeof(sin4)); 617 sin4.sin_family = AF_INET; 618 sin4.sin_len = sizeof(struct sockaddr_in); 619 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12], 620 sizeof(sin4.sin_addr)); 621 sin4.sin_port = sin6->sin6_port; 622 623 memcpy(sa, &sin4, sin4.sin_len); 624 } 625 626 static void 627 usage(void) 628 { 629 630 fprintf(stderr, "%s\n%s\n%s\n%s\n", 631 "usage: syslogd [-46Acdknosuv] [-a allowed_peer]", 632 " [-b bind address] [-f config_file]", 633 " [-l log_socket] [-m mark_interval]", 634 " [-P pid_file] [-p log_socket]"); 635 exit(1); 636 } 637 638 /* 639 * Take a raw input line, decode the message, and print the message 640 * on the appropriate log files. 641 */ 642 static void 643 printline(const char *hname, char *msg) 644 { 645 int c, pri; 646 char *p, *q, line[MAXLINE + 1]; 647 648 /* test for special codes */ 649 pri = DEFUPRI; 650 p = msg; 651 if (*p == '<') { 652 pri = 0; 653 while (isdigit(*++p)) 654 pri = 10 * pri + (*p - '0'); 655 if (*p == '>') 656 ++p; 657 } 658 if (pri &~ (LOG_FACMASK|LOG_PRIMASK)) 659 pri = DEFUPRI; 660 661 /* don't allow users to log kernel messages */ 662 if (LOG_FAC(pri) == LOG_KERN && !KeepKernFac) 663 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri)); 664 665 q = line; 666 667 while ((c = (unsigned char)*p++) != '\0' && 668 q < &line[sizeof(line) - 4]) { 669 if ((c & 0x80) && c < 0xA0) { 670 c &= 0x7F; 671 *q++ = 'M'; 672 *q++ = '-'; 673 } 674 if (isascii(c) && iscntrl(c)) { 675 if (c == '\n') { 676 *q++ = ' '; 677 } else if (c == '\t') { 678 *q++ = '\t'; 679 } else { 680 *q++ = '^'; 681 *q++ = c ^ 0100; 682 } 683 } else { 684 *q++ = c; 685 } 686 } 687 *q = '\0'; 688 689 logmsg(pri, line, hname, 0); 690 } 691 692 /* 693 * Read /dev/klog while data are available, split into lines. 694 */ 695 static void 696 readklog(void) 697 { 698 char *p, *q, line[MAXLINE + 1]; 699 int len, i; 700 701 len = 0; 702 for (;;) { 703 i = read(fklog, line + len, MAXLINE - 1 - len); 704 if (i > 0) { 705 line[i + len] = '\0'; 706 } else { 707 if (i < 0 && errno != EINTR && errno != EAGAIN) { 708 logerror("klog"); 709 fklog = -1; 710 } 711 break; 712 } 713 714 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) { 715 *q = '\0'; 716 printsys(p); 717 } 718 len = strlen(p); 719 if (len >= MAXLINE - 1) { 720 printsys(p); 721 len = 0; 722 } 723 if (len > 0) 724 memmove(line, p, len + 1); 725 } 726 if (len > 0) 727 printsys(line); 728 } 729 730 /* 731 * Take a raw input line from /dev/klog, format similar to syslog(). 732 */ 733 static void 734 printsys(char *p) 735 { 736 int pri, flags; 737 738 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */ 739 pri = DEFSPRI; 740 if (*p == '<') { 741 pri = 0; 742 while (isdigit(*++p)) 743 pri = 10 * pri + (*p - '0'); 744 if (*p == '>') 745 ++p; 746 if ((pri & LOG_FACMASK) == LOG_CONSOLE) 747 flags |= IGN_CONS; 748 } else { 749 /* kernel printf's come out on console */ 750 flags |= IGN_CONS; 751 } 752 if (pri &~ (LOG_FACMASK|LOG_PRIMASK)) 753 pri = DEFSPRI; 754 logmsg(pri, p, LocalHostName, flags); 755 } 756 757 static time_t now; 758 759 /* 760 * Log a message to the appropriate log files, users, etc. based on 761 * the priority. 762 */ 763 static void 764 logmsg(int pri, const char *msg, const char *from, int flags) 765 { 766 struct filed *f; 767 int i, fac, msglen, omask, prilev; 768 const char *timestamp; 769 char prog[NAME_MAX+1]; 770 char buf[MAXLINE+1]; 771 772 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n", 773 pri, flags, from, msg); 774 775 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM)); 776 777 /* 778 * Check to see if msg looks non-standard. 779 */ 780 msglen = strlen(msg); 781 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' || 782 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') 783 flags |= ADDDATE; 784 785 (void)time(&now); 786 if (flags & ADDDATE) { 787 timestamp = ctime(&now) + 4; 788 } else { 789 timestamp = msg; 790 msg += 16; 791 msglen -= 16; 792 } 793 794 /* skip leading blanks */ 795 while (isspace(*msg)) { 796 msg++; 797 msglen--; 798 } 799 800 /* extract facility and priority level */ 801 if (flags & MARK) 802 fac = LOG_NFACILITIES; 803 else 804 fac = LOG_FAC(pri); 805 prilev = LOG_PRI(pri); 806 807 /* extract program name */ 808 for (i = 0; i < NAME_MAX; i++) { 809 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[') 810 break; 811 prog[i] = msg[i]; 812 } 813 prog[i] = 0; 814 815 /* add kernel prefix for kernel messages */ 816 if (flags & ISKERNEL) { 817 snprintf(buf, sizeof(buf), "%s: %s", 818 use_bootfile ? bootfile : "kernel", msg); 819 msg = buf; 820 msglen = strlen(buf); 821 } 822 823 /* log the message to the particular outputs */ 824 if (!Initialized) { 825 f = &consfile; 826 f->f_file = open(ctty, O_WRONLY, 0); 827 828 if (f->f_file >= 0) { 829 fprintlog(f, flags, msg); 830 (void)close(f->f_file); 831 } 832 (void)sigsetmask(omask); 833 return; 834 } 835 for (f = Files; f; f = f->f_next) { 836 /* skip messages that are incorrect priority */ 837 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev)) 838 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev)) 839 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev)) 840 ) 841 || f->f_pmask[fac] == INTERNAL_NOPRI) 842 continue; 843 /* skip messages with the incorrect hostname */ 844 if (f->f_host) 845 switch (f->f_host[0]) { 846 case '+': 847 if (strcmp(from, f->f_host + 1) != 0) 848 continue; 849 break; 850 case '-': 851 if (strcmp(from, f->f_host + 1) == 0) 852 continue; 853 break; 854 } 855 856 /* skip messages with the incorrect program name */ 857 if (f->f_program) 858 switch (f->f_program[0]) { 859 case '+': 860 if (strcmp(prog, f->f_program + 1) != 0) 861 continue; 862 break; 863 case '-': 864 if (strcmp(prog, f->f_program + 1) == 0) 865 continue; 866 break; 867 default: 868 if (strcmp(prog, f->f_program) != 0) 869 continue; 870 break; 871 } 872 873 if (f->f_type == F_CONSOLE && (flags & IGN_CONS)) 874 continue; 875 876 /* don't output marks to recently written files */ 877 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2) 878 continue; 879 880 /* 881 * suppress duplicate lines to this file 882 */ 883 if (no_compress - (f->f_type != F_PIPE) < 1 && 884 (flags & MARK) == 0 && msglen == f->f_prevlen && 885 !strcmp(msg, f->f_prevline) && 886 !strcasecmp(from, f->f_prevhost)) { 887 (void)strlcpy(f->f_lasttime, timestamp, 16); 888 f->f_prevcount++; 889 dprintf("msg repeated %d times, %ld sec of %d\n", 890 f->f_prevcount, (long)(now - f->f_time), 891 repeatinterval[f->f_repeatcount]); 892 /* 893 * If domark would have logged this by now, 894 * flush it now (so we don't hold isolated messages), 895 * but back off so we'll flush less often 896 * in the future. 897 */ 898 if (now > REPEATTIME(f)) { 899 fprintlog(f, flags, (char *)NULL); 900 BACKOFF(f); 901 } 902 } else { 903 /* new line, save it */ 904 if (f->f_prevcount) 905 fprintlog(f, 0, (char *)NULL); 906 f->f_repeatcount = 0; 907 f->f_prevpri = pri; 908 (void)strlcpy(f->f_lasttime, timestamp, 16); 909 (void)strlcpy(f->f_prevhost, from, 910 sizeof(f->f_prevhost)); 911 if (msglen < MAXSVLINE) { 912 f->f_prevlen = msglen; 913 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline)); 914 fprintlog(f, flags, (char *)NULL); 915 } else { 916 f->f_prevline[0] = 0; 917 f->f_prevlen = 0; 918 fprintlog(f, flags, msg); 919 } 920 } 921 } 922 (void)sigsetmask(omask); 923 } 924 925 static void 926 fprintlog(struct filed *f, int flags, const char *msg) 927 { 928 struct iovec iov[7]; 929 struct iovec *v; 930 struct addrinfo *r; 931 int i, l, lsent = 0; 932 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL; 933 const char *msgret; 934 935 v = iov; 936 if (f->f_type == F_WALL) { 937 v->iov_base = greetings; 938 v->iov_len = snprintf(greetings, sizeof greetings, 939 "\r\n\7Message from syslogd@%s at %.24s ...\r\n", 940 f->f_prevhost, ctime(&now)); 941 if (v->iov_len > 0) 942 v++; 943 v->iov_base = ""; 944 v->iov_len = 0; 945 v++; 946 } else { 947 v->iov_base = f->f_lasttime; 948 v->iov_len = 15; 949 v++; 950 v->iov_base = " "; 951 v->iov_len = 1; 952 v++; 953 } 954 955 if (LogFacPri) { 956 static char fp_buf[30]; /* Hollow laugh */ 957 int fac = f->f_prevpri & LOG_FACMASK; 958 int pri = LOG_PRI(f->f_prevpri); 959 const char *f_s = NULL; 960 char f_n[5]; /* Hollow laugh */ 961 const char *p_s = NULL; 962 char p_n[5]; /* Hollow laugh */ 963 964 if (LogFacPri > 1) { 965 CODE *c; 966 967 for (c = facilitynames; c->c_name; c++) { 968 if (c->c_val == fac) { 969 f_s = c->c_name; 970 break; 971 } 972 } 973 for (c = prioritynames; c->c_name; c++) { 974 if (c->c_val == pri) { 975 p_s = c->c_name; 976 break; 977 } 978 } 979 } 980 if (!f_s) { 981 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac)); 982 f_s = f_n; 983 } 984 if (!p_s) { 985 snprintf(p_n, sizeof p_n, "%d", pri); 986 p_s = p_n; 987 } 988 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s); 989 v->iov_base = fp_buf; 990 v->iov_len = strlen(fp_buf); 991 } else { 992 v->iov_base=""; 993 v->iov_len = 0; 994 } 995 v++; 996 997 v->iov_base = f->f_prevhost; 998 v->iov_len = strlen(v->iov_base); 999 v++; 1000 v->iov_base = " "; 1001 v->iov_len = 1; 1002 v++; 1003 1004 if (msg) { 1005 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */ 1006 if (wmsg == NULL) { 1007 logerror("strdup"); 1008 exit(1); 1009 } 1010 v->iov_base = wmsg; 1011 v->iov_len = strlen(msg); 1012 } else if (f->f_prevcount > 1) { 1013 v->iov_base = repbuf; 1014 v->iov_len = snprintf(repbuf, sizeof repbuf, 1015 "last message repeated %d times", f->f_prevcount); 1016 } else { 1017 v->iov_base = f->f_prevline; 1018 v->iov_len = f->f_prevlen; 1019 } 1020 v++; 1021 1022 dprintf("Logging to %s", TypeNames[f->f_type]); 1023 f->f_time = now; 1024 1025 switch (f->f_type) { 1026 case F_UNUSED: 1027 dprintf("\n"); 1028 break; 1029 1030 case F_FORW: 1031 dprintf(" %s\n", f->f_un.f_forw.f_hname); 1032 /* check for local vs remote messages */ 1033 if (strcasecmp(f->f_prevhost, LocalHostName)) 1034 l = snprintf(line, sizeof line - 1, 1035 "<%d>%.15s Forwarded from %s: %s", 1036 f->f_prevpri, iov[0].iov_base, f->f_prevhost, 1037 iov[5].iov_base); 1038 else 1039 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s", 1040 f->f_prevpri, iov[0].iov_base, iov[5].iov_base); 1041 if (l < 0) 1042 l = 0; 1043 else if (l > MAXLINE) 1044 l = MAXLINE; 1045 1046 if (finet) { 1047 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) { 1048 for (i = 0; i < *finet; i++) { 1049 #if 0 1050 /* 1051 * should we check AF first, or just 1052 * trial and error? FWD 1053 */ 1054 if (r->ai_family == 1055 address_family_of(finet[i+1])) 1056 #endif 1057 lsent = sendto(finet[i+1], line, l, 0, 1058 r->ai_addr, r->ai_addrlen); 1059 if (lsent == l) 1060 break; 1061 } 1062 if (lsent == l && !send_to_all) 1063 break; 1064 } 1065 dprintf("lsent/l: %d/%d\n", lsent, l); 1066 if (lsent != l) { 1067 int e = errno; 1068 logerror("sendto"); 1069 errno = e; 1070 switch (errno) { 1071 case EHOSTUNREACH: 1072 case EHOSTDOWN: 1073 break; 1074 /* case EBADF: */ 1075 /* case EACCES: */ 1076 /* case ENOTSOCK: */ 1077 /* case EFAULT: */ 1078 /* case EMSGSIZE: */ 1079 /* case EAGAIN: */ 1080 /* case ENOBUFS: */ 1081 /* case ECONNREFUSED: */ 1082 default: 1083 dprintf("removing entry\n", e); 1084 (void)close(f->f_file); 1085 f->f_type = F_UNUSED; 1086 break; 1087 } 1088 } 1089 } 1090 break; 1091 1092 case F_FILE: 1093 dprintf(" %s\n", f->f_un.f_fname); 1094 v->iov_base = "\n"; 1095 v->iov_len = 1; 1096 if (writev(f->f_file, iov, 7) < 0) { 1097 int e = errno; 1098 (void)close(f->f_file); 1099 f->f_type = F_UNUSED; 1100 errno = e; 1101 logerror(f->f_un.f_fname); 1102 } else if (flags & SYNC_FILE) 1103 (void)fsync(f->f_file); 1104 break; 1105 1106 case F_PIPE: 1107 dprintf(" %s\n", f->f_un.f_pipe.f_pname); 1108 v->iov_base = "\n"; 1109 v->iov_len = 1; 1110 if (f->f_un.f_pipe.f_pid == 0) { 1111 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname, 1112 &f->f_un.f_pipe.f_pid)) < 0) { 1113 f->f_type = F_UNUSED; 1114 logerror(f->f_un.f_pipe.f_pname); 1115 break; 1116 } 1117 } 1118 if (writev(f->f_file, iov, 7) < 0) { 1119 int e = errno; 1120 (void)close(f->f_file); 1121 if (f->f_un.f_pipe.f_pid > 0) 1122 deadq_enter(f->f_un.f_pipe.f_pid, 1123 f->f_un.f_pipe.f_pname); 1124 f->f_un.f_pipe.f_pid = 0; 1125 errno = e; 1126 logerror(f->f_un.f_pipe.f_pname); 1127 } 1128 break; 1129 1130 case F_CONSOLE: 1131 if (flags & IGN_CONS) { 1132 dprintf(" (ignored)\n"); 1133 break; 1134 } 1135 /* FALLTHROUGH */ 1136 1137 case F_TTY: 1138 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname); 1139 v->iov_base = "\r\n"; 1140 v->iov_len = 2; 1141 1142 errno = 0; /* ttymsg() only sometimes returns an errno */ 1143 if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) { 1144 f->f_type = F_UNUSED; 1145 logerror(msgret); 1146 } 1147 break; 1148 1149 case F_USERS: 1150 case F_WALL: 1151 dprintf("\n"); 1152 v->iov_base = "\r\n"; 1153 v->iov_len = 2; 1154 wallmsg(f, iov); 1155 break; 1156 } 1157 f->f_prevcount = 0; 1158 if (msg) 1159 free(wmsg); 1160 } 1161 1162 /* 1163 * WALLMSG -- Write a message to the world at large 1164 * 1165 * Write the specified message to either the entire 1166 * world, or a list of approved users. 1167 */ 1168 static void 1169 wallmsg(struct filed *f, struct iovec *iov) 1170 { 1171 static int reenter; /* avoid calling ourselves */ 1172 FILE *uf; 1173 struct utmp ut; 1174 int i; 1175 const char *p; 1176 char line[sizeof(ut.ut_line) + 1]; 1177 1178 if (reenter++) 1179 return; 1180 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) { 1181 logerror(_PATH_UTMP); 1182 reenter = 0; 1183 return; 1184 } 1185 /* NOSTRICT */ 1186 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) { 1187 if (ut.ut_name[0] == '\0') 1188 continue; 1189 (void)strlcpy(line, ut.ut_line, sizeof(line)); 1190 if (f->f_type == F_WALL) { 1191 if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) { 1192 errno = 0; /* already in msg */ 1193 logerror(p); 1194 } 1195 continue; 1196 } 1197 /* should we send the message to this user? */ 1198 for (i = 0; i < MAXUNAMES; i++) { 1199 if (!f->f_un.f_uname[i][0]) 1200 break; 1201 if (!strncmp(f->f_un.f_uname[i], ut.ut_name, 1202 UT_NAMESIZE)) { 1203 if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) 1204 != NULL) { 1205 errno = 0; /* already in msg */ 1206 logerror(p); 1207 } 1208 break; 1209 } 1210 } 1211 } 1212 (void)fclose(uf); 1213 reenter = 0; 1214 } 1215 1216 static void 1217 reapchild(int signo __unused) 1218 { 1219 int status; 1220 pid_t pid; 1221 struct filed *f; 1222 1223 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) { 1224 if (!Initialized) 1225 /* Don't tell while we are initting. */ 1226 continue; 1227 1228 /* First, look if it's a process from the dead queue. */ 1229 if (deadq_remove(pid)) 1230 goto oncemore; 1231 1232 /* Now, look in list of active processes. */ 1233 for (f = Files; f; f = f->f_next) 1234 if (f->f_type == F_PIPE && 1235 f->f_un.f_pipe.f_pid == pid) { 1236 (void)close(f->f_file); 1237 f->f_un.f_pipe.f_pid = 0; 1238 log_deadchild(pid, status, 1239 f->f_un.f_pipe.f_pname); 1240 break; 1241 } 1242 oncemore: 1243 continue; 1244 } 1245 } 1246 1247 /* 1248 * Return a printable representation of a host address. 1249 */ 1250 static const char * 1251 cvthname(struct sockaddr *f) 1252 { 1253 int error; 1254 sigset_t omask, nmask; 1255 char *p; 1256 static char hname[NI_MAXHOST], ip[NI_MAXHOST]; 1257 1258 error = getnameinfo((struct sockaddr *)f, 1259 ((struct sockaddr *)f)->sa_len, 1260 ip, sizeof ip, NULL, 0, 1261 NI_NUMERICHOST | withscopeid); 1262 dprintf("cvthname(%s)\n", ip); 1263 1264 if (error) { 1265 dprintf("Malformed from address %s\n", gai_strerror(error)); 1266 return ("???"); 1267 } 1268 if (!resolve) 1269 return (ip); 1270 1271 sigemptyset(&nmask); 1272 sigaddset(&nmask, SIGHUP); 1273 sigprocmask(SIG_BLOCK, &nmask, &omask); 1274 error = getnameinfo((struct sockaddr *)f, 1275 ((struct sockaddr *)f)->sa_len, 1276 hname, sizeof hname, NULL, 0, 1277 NI_NAMEREQD | withscopeid); 1278 sigprocmask(SIG_SETMASK, &omask, NULL); 1279 if (error) { 1280 dprintf("Host name for your address (%s) unknown\n", ip); 1281 return (ip); 1282 } 1283 /* XXX Not quite correct, but close enough for government work. */ 1284 if ((p = strchr(hname, '.')) && strcasecmp(p + 1, LocalDomain) == 0) 1285 *p = '\0'; 1286 return (hname); 1287 } 1288 1289 static void 1290 dodie(int signo) 1291 { 1292 1293 WantDie = signo; 1294 } 1295 1296 static void 1297 domark(int signo __unused) 1298 { 1299 1300 MarkSet = 1; 1301 } 1302 1303 /* 1304 * Print syslogd errors some place. 1305 */ 1306 static void 1307 logerror(const char *type) 1308 { 1309 char buf[512]; 1310 1311 if (errno) 1312 (void)snprintf(buf, 1313 sizeof buf, "syslogd: %s: %s", type, strerror(errno)); 1314 else 1315 (void)snprintf(buf, sizeof buf, "syslogd: %s", type); 1316 errno = 0; 1317 dprintf("%s\n", buf); 1318 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE); 1319 } 1320 1321 static void 1322 die(int signo) 1323 { 1324 struct filed *f; 1325 int was_initialized; 1326 char buf[100]; 1327 int i; 1328 1329 was_initialized = Initialized; 1330 Initialized = 0; /* Don't log SIGCHLDs. */ 1331 for (f = Files; f != NULL; f = f->f_next) { 1332 /* flush any pending output */ 1333 if (f->f_prevcount) 1334 fprintlog(f, 0, (char *)NULL); 1335 if (f->f_type == F_PIPE) 1336 (void)close(f->f_file); 1337 } 1338 Initialized = was_initialized; 1339 if (signo) { 1340 dprintf("syslogd: exiting on signal %d\n", signo); 1341 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo); 1342 errno = 0; 1343 logerror(buf); 1344 } 1345 for (i = 0; i < nfunix; i++) 1346 if (funixn[i] && funix[i] != -1) 1347 (void)unlink(funixn[i]); 1348 exit(1); 1349 } 1350 1351 /* 1352 * INIT -- Initialize syslogd from configuration table 1353 */ 1354 static void 1355 init(int signo) 1356 { 1357 int i; 1358 FILE *cf; 1359 struct filed *f, *next, **nextp; 1360 char *p; 1361 char cline[LINE_MAX]; 1362 char prog[NAME_MAX+1]; 1363 char host[MAXHOSTNAMELEN]; 1364 char oldLocalHostName[MAXHOSTNAMELEN]; 1365 char hostMsg[2*MAXHOSTNAMELEN+40]; 1366 char bootfileMsg[LINE_MAX]; 1367 1368 dprintf("init\n"); 1369 1370 /* 1371 * Load hostname (may have changed). 1372 */ 1373 if (signo != 0) 1374 (void)strlcpy(oldLocalHostName, LocalHostName, 1375 sizeof(oldLocalHostName)); 1376 if (gethostname(LocalHostName, sizeof(LocalHostName))) 1377 err(EX_OSERR, "gethostname() failed"); 1378 if ((p = strchr(LocalHostName, '.')) != NULL) { 1379 *p++ = '\0'; 1380 LocalDomain = p; 1381 } else { 1382 LocalDomain = ""; 1383 } 1384 1385 /* 1386 * Close all open log files. 1387 */ 1388 Initialized = 0; 1389 for (f = Files; f != NULL; f = next) { 1390 /* flush any pending output */ 1391 if (f->f_prevcount) 1392 fprintlog(f, 0, (char *)NULL); 1393 1394 switch (f->f_type) { 1395 case F_FILE: 1396 case F_FORW: 1397 case F_CONSOLE: 1398 case F_TTY: 1399 (void)close(f->f_file); 1400 break; 1401 case F_PIPE: 1402 (void)close(f->f_file); 1403 if (f->f_un.f_pipe.f_pid > 0) 1404 deadq_enter(f->f_un.f_pipe.f_pid, 1405 f->f_un.f_pipe.f_pname); 1406 f->f_un.f_pipe.f_pid = 0; 1407 break; 1408 } 1409 next = f->f_next; 1410 if (f->f_program) free(f->f_program); 1411 if (f->f_host) free(f->f_host); 1412 free((char *)f); 1413 } 1414 Files = NULL; 1415 nextp = &Files; 1416 1417 /* open the configuration file */ 1418 if ((cf = fopen(ConfFile, "r")) == NULL) { 1419 dprintf("cannot open %s\n", ConfFile); 1420 *nextp = (struct filed *)calloc(1, sizeof(*f)); 1421 if (*nextp == NULL) { 1422 logerror("calloc"); 1423 exit(1); 1424 } 1425 cfline("*.ERR\t/dev/console", *nextp, "*", "*"); 1426 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f)); 1427 if ((*nextp)->f_next == NULL) { 1428 logerror("calloc"); 1429 exit(1); 1430 } 1431 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*"); 1432 Initialized = 1; 1433 return; 1434 } 1435 1436 /* 1437 * Foreach line in the conf table, open that file. 1438 */ 1439 f = NULL; 1440 (void)strlcpy(host, "*", sizeof(host)); 1441 (void)strlcpy(prog, "*", sizeof(prog)); 1442 while (fgets(cline, sizeof(cline), cf) != NULL) { 1443 /* 1444 * check for end-of-section, comments, strip off trailing 1445 * spaces and newline character. #!prog is treated specially: 1446 * following lines apply only to that program. 1447 */ 1448 for (p = cline; isspace(*p); ++p) 1449 continue; 1450 if (*p == 0) 1451 continue; 1452 if (*p == '#') { 1453 p++; 1454 if (*p != '!' && *p != '+' && *p != '-') 1455 continue; 1456 } 1457 if (*p == '+' || *p == '-') { 1458 host[0] = *p++; 1459 while (isspace(*p)) 1460 p++; 1461 if ((!*p) || (*p == '*')) { 1462 (void)strlcpy(host, "*", sizeof(host)); 1463 continue; 1464 } 1465 if (*p == '@') 1466 p = LocalHostName; 1467 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) { 1468 if (!isalnum(*p) && *p != '.' && *p != '-') 1469 break; 1470 host[i] = *p++; 1471 } 1472 host[i] = '\0'; 1473 continue; 1474 } 1475 if (*p == '!') { 1476 p++; 1477 while (isspace(*p)) p++; 1478 if ((!*p) || (*p == '*')) { 1479 (void)strlcpy(prog, "*", sizeof(prog)); 1480 continue; 1481 } 1482 for (i = 0; i < NAME_MAX; i++) { 1483 if (!isprint(p[i])) 1484 break; 1485 prog[i] = p[i]; 1486 } 1487 prog[i] = 0; 1488 continue; 1489 } 1490 for (p = strchr(cline, '\0'); isspace(*--p);) 1491 continue; 1492 *++p = '\0'; 1493 f = (struct filed *)calloc(1, sizeof(*f)); 1494 if (f == NULL) { 1495 logerror("calloc"); 1496 exit(1); 1497 } 1498 *nextp = f; 1499 nextp = &f->f_next; 1500 cfline(cline, f, prog, host); 1501 } 1502 1503 /* close the configuration file */ 1504 (void)fclose(cf); 1505 1506 Initialized = 1; 1507 1508 if (Debug) { 1509 for (f = Files; f; f = f->f_next) { 1510 for (i = 0; i <= LOG_NFACILITIES; i++) 1511 if (f->f_pmask[i] == INTERNAL_NOPRI) 1512 printf("X "); 1513 else 1514 printf("%d ", f->f_pmask[i]); 1515 printf("%s: ", TypeNames[f->f_type]); 1516 switch (f->f_type) { 1517 case F_FILE: 1518 printf("%s", f->f_un.f_fname); 1519 break; 1520 1521 case F_CONSOLE: 1522 case F_TTY: 1523 printf("%s%s", _PATH_DEV, f->f_un.f_fname); 1524 break; 1525 1526 case F_FORW: 1527 printf("%s", f->f_un.f_forw.f_hname); 1528 break; 1529 1530 case F_PIPE: 1531 printf("%s", f->f_un.f_pipe.f_pname); 1532 break; 1533 1534 case F_USERS: 1535 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++) 1536 printf("%s, ", f->f_un.f_uname[i]); 1537 break; 1538 } 1539 if (f->f_program) 1540 printf(" (%s)", f->f_program); 1541 printf("\n"); 1542 } 1543 } 1544 1545 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE); 1546 dprintf("syslogd: restarted\n"); 1547 /* 1548 * Log a change in hostname, but only on a restart. 1549 */ 1550 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) { 1551 (void)snprintf(hostMsg, sizeof(hostMsg), 1552 "syslogd: hostname changed, \"%s\" to \"%s\"", 1553 oldLocalHostName, LocalHostName); 1554 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE); 1555 dprintf("%s\n", hostMsg); 1556 } 1557 /* 1558 * Log the kernel boot file if we aren't going to use it as 1559 * the prefix, and if this is *not* a restart. 1560 */ 1561 if (signo == 0 && !use_bootfile) { 1562 (void)snprintf(bootfileMsg, sizeof(bootfileMsg), 1563 "syslogd: kernel boot file is %s", bootfile); 1564 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE); 1565 dprintf("%s\n", bootfileMsg); 1566 } 1567 } 1568 1569 /* 1570 * Crack a configuration file line 1571 */ 1572 static void 1573 cfline(const char *line, struct filed *f, const char *prog, const char *host) 1574 { 1575 struct addrinfo hints, *res; 1576 int error, i, pri; 1577 const char *p, *q; 1578 char *bp; 1579 char buf[MAXLINE], ebuf[100]; 1580 1581 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host); 1582 1583 errno = 0; /* keep strerror() stuff out of logerror messages */ 1584 1585 /* clear out file entry */ 1586 memset(f, 0, sizeof(*f)); 1587 for (i = 0; i <= LOG_NFACILITIES; i++) 1588 f->f_pmask[i] = INTERNAL_NOPRI; 1589 1590 /* save hostname if any */ 1591 if (host && *host == '*') 1592 host = NULL; 1593 if (host) { 1594 int hl, dl; 1595 1596 f->f_host = strdup(host); 1597 if (f->f_host == NULL) { 1598 logerror("strdup"); 1599 exit(1); 1600 } 1601 hl = strlen(f->f_host); 1602 if (f->f_host[hl-1] == '.') 1603 f->f_host[--hl] = '\0'; 1604 dl = strlen(LocalDomain) + 1; 1605 if (hl > dl && f->f_host[hl-dl] == '.' && 1606 strcasecmp(f->f_host + hl - dl + 1, LocalDomain) == 0) 1607 f->f_host[hl-dl] = '\0'; 1608 } 1609 1610 /* save program name if any */ 1611 if (prog && *prog == '*') 1612 prog = NULL; 1613 if (prog) { 1614 f->f_program = strdup(prog); 1615 if (f->f_program == NULL) { 1616 logerror("strdup"); 1617 exit(1); 1618 } 1619 } 1620 1621 /* scan through the list of selectors */ 1622 for (p = line; *p && *p != '\t' && *p != ' ';) { 1623 int pri_done; 1624 int pri_cmp; 1625 int pri_invert; 1626 1627 /* find the end of this facility name list */ 1628 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; ) 1629 continue; 1630 1631 /* get the priority comparison */ 1632 pri_cmp = 0; 1633 pri_done = 0; 1634 pri_invert = 0; 1635 if (*q == '!') { 1636 pri_invert = 1; 1637 q++; 1638 } 1639 while (!pri_done) { 1640 switch (*q) { 1641 case '<': 1642 pri_cmp |= PRI_LT; 1643 q++; 1644 break; 1645 case '=': 1646 pri_cmp |= PRI_EQ; 1647 q++; 1648 break; 1649 case '>': 1650 pri_cmp |= PRI_GT; 1651 q++; 1652 break; 1653 default: 1654 pri_done++; 1655 break; 1656 } 1657 } 1658 1659 /* collect priority name */ 1660 for (bp = buf; *q && !strchr("\t,; ", *q); ) 1661 *bp++ = *q++; 1662 *bp = '\0'; 1663 1664 /* skip cruft */ 1665 while (strchr(",;", *q)) 1666 q++; 1667 1668 /* decode priority name */ 1669 if (*buf == '*') { 1670 pri = LOG_PRIMASK + 1; 1671 pri_cmp = PRI_LT | PRI_EQ | PRI_GT; 1672 } else { 1673 pri = decode(buf, prioritynames); 1674 if (pri < 0) { 1675 (void)snprintf(ebuf, sizeof ebuf, 1676 "unknown priority name \"%s\"", buf); 1677 logerror(ebuf); 1678 return; 1679 } 1680 } 1681 if (!pri_cmp) 1682 pri_cmp = (UniquePriority) 1683 ? (PRI_EQ) 1684 : (PRI_EQ | PRI_GT) 1685 ; 1686 if (pri_invert) 1687 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT; 1688 1689 /* scan facilities */ 1690 while (*p && !strchr("\t.; ", *p)) { 1691 for (bp = buf; *p && !strchr("\t,;. ", *p); ) 1692 *bp++ = *p++; 1693 *bp = '\0'; 1694 1695 if (*buf == '*') { 1696 for (i = 0; i < LOG_NFACILITIES; i++) { 1697 f->f_pmask[i] = pri; 1698 f->f_pcmp[i] = pri_cmp; 1699 } 1700 } else { 1701 i = decode(buf, facilitynames); 1702 if (i < 0) { 1703 (void)snprintf(ebuf, sizeof ebuf, 1704 "unknown facility name \"%s\"", 1705 buf); 1706 logerror(ebuf); 1707 return; 1708 } 1709 f->f_pmask[i >> 3] = pri; 1710 f->f_pcmp[i >> 3] = pri_cmp; 1711 } 1712 while (*p == ',' || *p == ' ') 1713 p++; 1714 } 1715 1716 p = q; 1717 } 1718 1719 /* skip to action part */ 1720 while (*p == '\t' || *p == ' ') 1721 p++; 1722 1723 switch (*p) { 1724 case '@': 1725 (void)strlcpy(f->f_un.f_forw.f_hname, ++p, 1726 sizeof(f->f_un.f_forw.f_hname)); 1727 memset(&hints, 0, sizeof(hints)); 1728 hints.ai_family = family; 1729 hints.ai_socktype = SOCK_DGRAM; 1730 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints, 1731 &res); 1732 if (error) { 1733 logerror(gai_strerror(error)); 1734 break; 1735 } 1736 f->f_un.f_forw.f_addr = res; 1737 f->f_type = F_FORW; 1738 break; 1739 1740 case '/': 1741 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) { 1742 f->f_type = F_UNUSED; 1743 logerror(p); 1744 break; 1745 } 1746 if (isatty(f->f_file)) { 1747 if (strcmp(p, ctty) == 0) 1748 f->f_type = F_CONSOLE; 1749 else 1750 f->f_type = F_TTY; 1751 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1, 1752 sizeof(f->f_un.f_fname)); 1753 } else { 1754 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname)); 1755 f->f_type = F_FILE; 1756 } 1757 break; 1758 1759 case '|': 1760 f->f_un.f_pipe.f_pid = 0; 1761 (void)strlcpy(f->f_un.f_fname, p + 1, sizeof(f->f_un.f_fname)); 1762 f->f_type = F_PIPE; 1763 break; 1764 1765 case '*': 1766 f->f_type = F_WALL; 1767 break; 1768 1769 default: 1770 for (i = 0; i < MAXUNAMES && *p; i++) { 1771 for (q = p; *q && *q != ','; ) 1772 q++; 1773 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE); 1774 if ((q - p) > UT_NAMESIZE) 1775 f->f_un.f_uname[i][UT_NAMESIZE] = '\0'; 1776 else 1777 f->f_un.f_uname[i][q - p] = '\0'; 1778 while (*q == ',' || *q == ' ') 1779 q++; 1780 p = q; 1781 } 1782 f->f_type = F_USERS; 1783 break; 1784 } 1785 } 1786 1787 1788 /* 1789 * Decode a symbolic name to a numeric value 1790 */ 1791 static int 1792 decode(const char *name, CODE *codetab) 1793 { 1794 CODE *c; 1795 char *p, buf[40]; 1796 1797 if (isdigit(*name)) 1798 return (atoi(name)); 1799 1800 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) { 1801 if (isupper(*name)) 1802 *p = tolower(*name); 1803 else 1804 *p = *name; 1805 } 1806 *p = '\0'; 1807 for (c = codetab; c->c_name; c++) 1808 if (!strcmp(buf, c->c_name)) 1809 return (c->c_val); 1810 1811 return (-1); 1812 } 1813 1814 static void 1815 markit(void) 1816 { 1817 struct filed *f; 1818 dq_t q, next; 1819 1820 now = time((time_t *)NULL); 1821 MarkSeq += TIMERINTVL; 1822 if (MarkSeq >= MarkInterval) { 1823 logmsg(LOG_INFO, "-- MARK --", 1824 LocalHostName, ADDDATE|MARK); 1825 MarkSeq = 0; 1826 } 1827 1828 for (f = Files; f; f = f->f_next) { 1829 if (f->f_prevcount && now >= REPEATTIME(f)) { 1830 dprintf("flush %s: repeated %d times, %d sec.\n", 1831 TypeNames[f->f_type], f->f_prevcount, 1832 repeatinterval[f->f_repeatcount]); 1833 fprintlog(f, 0, (char *)NULL); 1834 BACKOFF(f); 1835 } 1836 } 1837 1838 /* Walk the dead queue, and see if we should signal somebody. */ 1839 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) { 1840 next = TAILQ_NEXT(q, dq_entries); 1841 1842 switch (q->dq_timeout) { 1843 case 0: 1844 /* Already signalled once, try harder now. */ 1845 if (kill(q->dq_pid, SIGKILL) != 0) 1846 (void)deadq_remove(q->dq_pid); 1847 break; 1848 1849 case 1: 1850 /* 1851 * Timed out on dead queue, send terminate 1852 * signal. Note that we leave the removal 1853 * from the dead queue to reapchild(), which 1854 * will also log the event (unless the process 1855 * didn't even really exist, in case we simply 1856 * drop it from the dead queue). 1857 */ 1858 if (kill(q->dq_pid, SIGTERM) != 0) 1859 (void)deadq_remove(q->dq_pid); 1860 /* FALLTHROUGH */ 1861 1862 default: 1863 q->dq_timeout--; 1864 } 1865 } 1866 MarkSet = 0; 1867 (void)alarm(TIMERINTVL); 1868 } 1869 1870 /* 1871 * fork off and become a daemon, but wait for the child to come online 1872 * before returing to the parent, or we get disk thrashing at boot etc. 1873 * Set a timer so we don't hang forever if it wedges. 1874 */ 1875 static int 1876 waitdaemon(int nochdir, int noclose, int maxwait) 1877 { 1878 int fd; 1879 int status; 1880 pid_t pid, childpid; 1881 1882 switch (childpid = fork()) { 1883 case -1: 1884 return (-1); 1885 case 0: 1886 break; 1887 default: 1888 signal(SIGALRM, timedout); 1889 alarm(maxwait); 1890 while ((pid = wait3(&status, 0, NULL)) != -1) { 1891 if (WIFEXITED(status)) 1892 errx(1, "child pid %d exited with return code %d", 1893 pid, WEXITSTATUS(status)); 1894 if (WIFSIGNALED(status)) 1895 errx(1, "child pid %d exited on signal %d%s", 1896 pid, WTERMSIG(status), 1897 WCOREDUMP(status) ? " (core dumped)" : 1898 ""); 1899 if (pid == childpid) /* it's gone... */ 1900 break; 1901 } 1902 exit(0); 1903 } 1904 1905 if (setsid() == -1) 1906 return (-1); 1907 1908 if (!nochdir) 1909 (void)chdir("/"); 1910 1911 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { 1912 (void)dup2(fd, STDIN_FILENO); 1913 (void)dup2(fd, STDOUT_FILENO); 1914 (void)dup2(fd, STDERR_FILENO); 1915 if (fd > 2) 1916 (void)close (fd); 1917 } 1918 return (getppid()); 1919 } 1920 1921 /* 1922 * We get a SIGALRM from the child when it's running and finished doing it's 1923 * fsync()'s or O_SYNC writes for all the boot messages. 1924 * 1925 * We also get a signal from the kernel if the timer expires, so check to 1926 * see what happened. 1927 */ 1928 static void 1929 timedout(int sig __unused) 1930 { 1931 int left; 1932 left = alarm(0); 1933 signal(SIGALRM, SIG_DFL); 1934 if (left == 0) 1935 errx(1, "timed out waiting for child"); 1936 else 1937 _exit(0); 1938 } 1939 1940 /* 1941 * Add `s' to the list of allowable peer addresses to accept messages 1942 * from. 1943 * 1944 * `s' is a string in the form: 1945 * 1946 * [*]domainname[:{servicename|portnumber|*}] 1947 * 1948 * or 1949 * 1950 * netaddr/maskbits[:{servicename|portnumber|*}] 1951 * 1952 * Returns -1 on error, 0 if the argument was valid. 1953 */ 1954 static int 1955 allowaddr(char *s) 1956 { 1957 char *cp1, *cp2; 1958 struct allowedpeer ap; 1959 struct servent *se; 1960 int masklen = -1, i; 1961 struct addrinfo hints, *res; 1962 struct in_addr *addrp, *maskp; 1963 u_int32_t *addr6p, *mask6p; 1964 char ip[NI_MAXHOST]; 1965 1966 #ifdef INET6 1967 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL) 1968 #endif 1969 cp1 = s; 1970 if ((cp1 = strrchr(cp1, ':'))) { 1971 /* service/port provided */ 1972 *cp1++ = '\0'; 1973 if (strlen(cp1) == 1 && *cp1 == '*') 1974 /* any port allowed */ 1975 ap.port = 0; 1976 else if ((se = getservbyname(cp1, "udp"))) { 1977 ap.port = ntohs(se->s_port); 1978 } else { 1979 ap.port = strtol(cp1, &cp2, 0); 1980 if (*cp2 != '\0') 1981 return (-1); /* port not numeric */ 1982 } 1983 } else { 1984 if ((se = getservbyname("syslog", "udp"))) 1985 ap.port = ntohs(se->s_port); 1986 else 1987 /* sanity, should not happen */ 1988 ap.port = 514; 1989 } 1990 1991 if ((cp1 = strchr(s, '/')) != NULL && 1992 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) { 1993 *cp1 = '\0'; 1994 if ((masklen = atoi(cp1 + 1)) < 0) 1995 return (-1); 1996 } 1997 #ifdef INET6 1998 if (*s == '[') { 1999 cp2 = s + strlen(s) - 1; 2000 if (*cp2 == ']') { 2001 ++s; 2002 *cp2 = '\0'; 2003 } else { 2004 cp2 = NULL; 2005 } 2006 } else { 2007 cp2 = NULL; 2008 } 2009 #endif 2010 memset(&hints, 0, sizeof(hints)); 2011 hints.ai_family = PF_UNSPEC; 2012 hints.ai_socktype = SOCK_DGRAM; 2013 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; 2014 if (getaddrinfo(s, NULL, &hints, &res) == 0) { 2015 ap.isnumeric = 1; 2016 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen); 2017 memset(&ap.a_mask, 0, sizeof(ap.a_mask)); 2018 ap.a_mask.ss_family = res->ai_family; 2019 if (res->ai_family == AF_INET) { 2020 ap.a_mask.ss_len = sizeof(struct sockaddr_in); 2021 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr; 2022 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr; 2023 if (masklen < 0) { 2024 /* use default netmask */ 2025 if (IN_CLASSA(ntohl(addrp->s_addr))) 2026 maskp->s_addr = htonl(IN_CLASSA_NET); 2027 else if (IN_CLASSB(ntohl(addrp->s_addr))) 2028 maskp->s_addr = htonl(IN_CLASSB_NET); 2029 else 2030 maskp->s_addr = htonl(IN_CLASSC_NET); 2031 } else if (masklen <= 32) { 2032 /* convert masklen to netmask */ 2033 if (masklen == 0) 2034 maskp->s_addr = 0; 2035 else 2036 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1)); 2037 } else { 2038 freeaddrinfo(res); 2039 return (-1); 2040 } 2041 /* Lose any host bits in the network number. */ 2042 addrp->s_addr &= maskp->s_addr; 2043 } 2044 #ifdef INET6 2045 else if (res->ai_family == AF_INET6 && masklen <= 128) { 2046 ap.a_mask.ss_len = sizeof(struct sockaddr_in6); 2047 if (masklen < 0) 2048 masklen = 128; 2049 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr; 2050 /* convert masklen to netmask */ 2051 while (masklen > 0) { 2052 if (masklen < 32) { 2053 *mask6p = htonl(~(0xffffffff >> masklen)); 2054 break; 2055 } 2056 *mask6p++ = 0xffffffff; 2057 masklen -= 32; 2058 } 2059 /* Lose any host bits in the network number. */ 2060 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr; 2061 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr; 2062 for (i = 0; i < 4; i++) 2063 addr6p[i] &= mask6p[i]; 2064 } 2065 #endif 2066 else { 2067 freeaddrinfo(res); 2068 return (-1); 2069 } 2070 freeaddrinfo(res); 2071 } else { 2072 /* arg `s' is domain name */ 2073 ap.isnumeric = 0; 2074 ap.a_name = s; 2075 if (cp1) 2076 *cp1 = '/'; 2077 #ifdef INET6 2078 if (cp2) { 2079 *cp2 = ']'; 2080 --s; 2081 } 2082 #endif 2083 } 2084 2085 if (Debug) { 2086 printf("allowaddr: rule %d: ", NumAllowed); 2087 if (ap.isnumeric) { 2088 printf("numeric, "); 2089 getnameinfo((struct sockaddr *)&ap.a_addr, 2090 ((struct sockaddr *)&ap.a_addr)->sa_len, 2091 ip, sizeof ip, NULL, 0, 2092 NI_NUMERICHOST | withscopeid); 2093 printf("addr = %s, ", ip); 2094 getnameinfo((struct sockaddr *)&ap.a_mask, 2095 ((struct sockaddr *)&ap.a_mask)->sa_len, 2096 ip, sizeof ip, NULL, 0, 2097 NI_NUMERICHOST | withscopeid); 2098 printf("mask = %s; ", ip); 2099 } else { 2100 printf("domainname = %s; ", ap.a_name); 2101 } 2102 printf("port = %d\n", ap.port); 2103 } 2104 2105 if ((AllowedPeers = realloc(AllowedPeers, 2106 ++NumAllowed * sizeof(struct allowedpeer))) 2107 == NULL) { 2108 logerror("realloc"); 2109 exit(1); 2110 } 2111 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer)); 2112 return (0); 2113 } 2114 2115 /* 2116 * Validate that the remote peer has permission to log to us. 2117 */ 2118 static int 2119 validate(struct sockaddr *sa, const char *hname) 2120 { 2121 int i, j, reject; 2122 size_t l1, l2; 2123 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV]; 2124 struct allowedpeer *ap; 2125 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL; 2126 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL; 2127 struct addrinfo hints, *res; 2128 u_short sport; 2129 2130 if (NumAllowed == 0) 2131 /* traditional behaviour, allow everything */ 2132 return (1); 2133 2134 (void)strlcpy(name, hname, sizeof(name)); 2135 memset(&hints, 0, sizeof(hints)); 2136 hints.ai_family = PF_UNSPEC; 2137 hints.ai_socktype = SOCK_DGRAM; 2138 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; 2139 if (getaddrinfo(name, NULL, &hints, &res) == 0) 2140 freeaddrinfo(res); 2141 else if (strchr(name, '.') == NULL) { 2142 strlcat(name, ".", sizeof name); 2143 strlcat(name, LocalDomain, sizeof name); 2144 } 2145 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port, 2146 NI_NUMERICHOST | withscopeid | NI_NUMERICSERV) != 0) 2147 return (0); /* for safety, should not occur */ 2148 dprintf("validate: dgram from IP %s, port %s, name %s;\n", 2149 ip, port, name); 2150 sport = atoi(port); 2151 2152 /* now, walk down the list */ 2153 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) { 2154 if (ap->port != 0 && ap->port != sport) { 2155 dprintf("rejected in rule %d due to port mismatch.\n", i); 2156 continue; 2157 } 2158 2159 if (ap->isnumeric) { 2160 if (ap->a_addr.ss_family != sa->sa_family) { 2161 dprintf("rejected in rule %d due to address family mismatch.\n", i); 2162 continue; 2163 } 2164 if (ap->a_addr.ss_family == AF_INET) { 2165 sin4 = (struct sockaddr_in *)sa; 2166 a4p = (struct sockaddr_in *)&ap->a_addr; 2167 m4p = (struct sockaddr_in *)&ap->a_mask; 2168 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr) 2169 != a4p->sin_addr.s_addr) { 2170 dprintf("rejected in rule %d due to IP mismatch.\n", i); 2171 continue; 2172 } 2173 } 2174 #ifdef INET6 2175 else if (ap->a_addr.ss_family == AF_INET6) { 2176 sin6 = (struct sockaddr_in6 *)sa; 2177 a6p = (struct sockaddr_in6 *)&ap->a_addr; 2178 m6p = (struct sockaddr_in6 *)&ap->a_mask; 2179 #ifdef NI_WITHSCOPEID 2180 if (a6p->sin6_scope_id != 0 && 2181 sin6->sin6_scope_id != a6p->sin6_scope_id) { 2182 dprintf("rejected in rule %d due to scope mismatch.\n", i); 2183 continue; 2184 } 2185 #endif 2186 reject = 0; 2187 for (j = 0; j < 16; j += 4) { 2188 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j]) 2189 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) { 2190 ++reject; 2191 break; 2192 } 2193 } 2194 if (reject) { 2195 dprintf("rejected in rule %d due to IP mismatch.\n", i); 2196 continue; 2197 } 2198 } 2199 #endif 2200 else 2201 continue; 2202 } else { 2203 cp = ap->a_name; 2204 l1 = strlen(name); 2205 if (*cp == '*') { 2206 /* allow wildmatch */ 2207 cp++; 2208 l2 = strlen(cp); 2209 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) { 2210 dprintf("rejected in rule %d due to name mismatch.\n", i); 2211 continue; 2212 } 2213 } else { 2214 /* exact match */ 2215 l2 = strlen(cp); 2216 if (l2 != l1 || memcmp(cp, name, l1) != 0) { 2217 dprintf("rejected in rule %d due to name mismatch.\n", i); 2218 continue; 2219 } 2220 } 2221 } 2222 dprintf("accepted in rule %d.\n", i); 2223 return (1); /* hooray! */ 2224 } 2225 return (0); 2226 } 2227 2228 /* 2229 * Fairly similar to popen(3), but returns an open descriptor, as 2230 * opposed to a FILE *. 2231 */ 2232 static int 2233 p_open(const char *prog, pid_t *pid) 2234 { 2235 int pfd[2], nulldesc, i; 2236 sigset_t omask, mask; 2237 char *argv[4]; /* sh -c cmd NULL */ 2238 char errmsg[200]; 2239 2240 if (pipe(pfd) == -1) 2241 return (-1); 2242 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) 2243 /* we are royally screwed anyway */ 2244 return (-1); 2245 2246 sigemptyset(&mask); 2247 sigaddset(&mask, SIGALRM); 2248 sigaddset(&mask, SIGHUP); 2249 sigprocmask(SIG_BLOCK, &mask, &omask); 2250 switch ((*pid = fork())) { 2251 case -1: 2252 sigprocmask(SIG_SETMASK, &omask, 0); 2253 close(nulldesc); 2254 return (-1); 2255 2256 case 0: 2257 /* XXX should check for NULL return */ 2258 argv[0] = strdup("sh"); 2259 argv[1] = strdup("-c"); 2260 argv[2] = strdup(prog); 2261 argv[3] = NULL; 2262 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) { 2263 logerror("strdup"); 2264 exit(1); 2265 } 2266 2267 alarm(0); 2268 (void)setsid(); /* Avoid catching SIGHUPs. */ 2269 2270 /* 2271 * Throw away pending signals, and reset signal 2272 * behaviour to standard values. 2273 */ 2274 signal(SIGALRM, SIG_IGN); 2275 signal(SIGHUP, SIG_IGN); 2276 sigprocmask(SIG_SETMASK, &omask, 0); 2277 signal(SIGPIPE, SIG_DFL); 2278 signal(SIGQUIT, SIG_DFL); 2279 signal(SIGALRM, SIG_DFL); 2280 signal(SIGHUP, SIG_DFL); 2281 2282 dup2(pfd[0], STDIN_FILENO); 2283 dup2(nulldesc, STDOUT_FILENO); 2284 dup2(nulldesc, STDERR_FILENO); 2285 for (i = getdtablesize(); i > 2; i--) 2286 (void)close(i); 2287 2288 (void)execvp(_PATH_BSHELL, argv); 2289 _exit(255); 2290 } 2291 2292 sigprocmask(SIG_SETMASK, &omask, 0); 2293 close(nulldesc); 2294 close(pfd[0]); 2295 /* 2296 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are 2297 * supposed to get an EWOULDBLOCK on writev(2), which is 2298 * caught by the logic above anyway, which will in turn close 2299 * the pipe, and fork a new logging subprocess if necessary. 2300 * The stale subprocess will be killed some time later unless 2301 * it terminated itself due to closing its input pipe (so we 2302 * get rid of really dead puppies). 2303 */ 2304 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) { 2305 /* This is bad. */ 2306 (void)snprintf(errmsg, sizeof errmsg, 2307 "Warning: cannot change pipe to PID %d to " 2308 "non-blocking behaviour.", 2309 (int)*pid); 2310 logerror(errmsg); 2311 } 2312 return (pfd[1]); 2313 } 2314 2315 static void 2316 deadq_enter(pid_t pid, const char *name) 2317 { 2318 dq_t p; 2319 int status; 2320 2321 /* 2322 * Be paranoid, if we can't signal the process, don't enter it 2323 * into the dead queue (perhaps it's already dead). If possible, 2324 * we try to fetch and log the child's status. 2325 */ 2326 if (kill(pid, 0) != 0) { 2327 if (waitpid(pid, &status, WNOHANG) > 0) 2328 log_deadchild(pid, status, name); 2329 return; 2330 } 2331 2332 p = malloc(sizeof(struct deadq_entry)); 2333 if (p == NULL) { 2334 logerror("malloc"); 2335 exit(1); 2336 } 2337 2338 p->dq_pid = pid; 2339 p->dq_timeout = DQ_TIMO_INIT; 2340 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries); 2341 } 2342 2343 static int 2344 deadq_remove(pid_t pid) 2345 { 2346 dq_t q; 2347 2348 TAILQ_FOREACH(q, &deadq_head, dq_entries) { 2349 if (q->dq_pid == pid) { 2350 TAILQ_REMOVE(&deadq_head, q, dq_entries); 2351 free(q); 2352 return (1); 2353 } 2354 } 2355 2356 return (0); 2357 } 2358 2359 static void 2360 log_deadchild(pid_t pid, int status, const char *name) 2361 { 2362 int code; 2363 char buf[256]; 2364 const char *reason; 2365 2366 errno = 0; /* Keep strerror() stuff out of logerror messages. */ 2367 if (WIFSIGNALED(status)) { 2368 reason = "due to signal"; 2369 code = WTERMSIG(status); 2370 } else { 2371 reason = "with status"; 2372 code = WEXITSTATUS(status); 2373 if (code == 0) 2374 return; 2375 } 2376 (void)snprintf(buf, sizeof buf, 2377 "Logging subprocess %d (%s) exited %s %d.", 2378 pid, name, reason, code); 2379 logerror(buf); 2380 } 2381 2382 static int * 2383 socksetup(int af, const char *bindhostname) 2384 { 2385 struct addrinfo hints, *res, *r; 2386 int error, maxs, *s, *socks; 2387 2388 memset(&hints, 0, sizeof(hints)); 2389 hints.ai_flags = AI_PASSIVE; 2390 hints.ai_family = af; 2391 hints.ai_socktype = SOCK_DGRAM; 2392 error = getaddrinfo(bindhostname, "syslog", &hints, &res); 2393 if (error) { 2394 logerror(gai_strerror(error)); 2395 errno = 0; 2396 die(0); 2397 } 2398 2399 /* Count max number of sockets we may open */ 2400 for (maxs = 0, r = res; r; r = r->ai_next, maxs++); 2401 socks = malloc((maxs+1) * sizeof(int)); 2402 if (socks == NULL) { 2403 logerror("couldn't allocate memory for sockets"); 2404 die(0); 2405 } 2406 2407 *socks = 0; /* num of sockets counter at start of array */ 2408 s = socks + 1; 2409 for (r = res; r; r = r->ai_next) { 2410 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol); 2411 if (*s < 0) { 2412 logerror("socket"); 2413 continue; 2414 } 2415 if (r->ai_family == AF_INET6) { 2416 int on = 1; 2417 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY, 2418 (char *)&on, sizeof (on)) < 0) { 2419 logerror("setsockopt"); 2420 close(*s); 2421 continue; 2422 } 2423 } 2424 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) { 2425 close(*s); 2426 logerror("bind"); 2427 continue; 2428 } 2429 2430 (*socks)++; 2431 s++; 2432 } 2433 2434 if (*socks == 0) { 2435 free(socks); 2436 if (Debug) 2437 return (NULL); 2438 else 2439 die(0); 2440 } 2441 if (res) 2442 freeaddrinfo(res); 2443 2444 return (socks); 2445 } 2446