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