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