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