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