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