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