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