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