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