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 const char *s; 842 char prev, next; 843 int exclude = 0; 844 /* Behaviour on explicit match */ 845 846 if (spec == NULL) 847 return 0; 848 switch (*spec) { 849 case '-': 850 exclude = 1; 851 /*FALLTHROUGH*/ 852 case '+': 853 spec++; 854 break; 855 default: 856 break; 857 } 858 if (checkcase) 859 s = strstr (spec, name); 860 else 861 s = strcasestr (spec, name); 862 863 if (s != NULL) { 864 prev = (s == spec ? ',' : *(s - 1)); 865 next = *(s + strlen (name)); 866 867 if (prev == ',' && (next == '\0' || next == ',')) 868 /* Explicit match: skip iff the spec is an 869 exclusive one. */ 870 return exclude; 871 } 872 873 /* No explicit match for this name: skip the message iff 874 the spec is an inclusive one. */ 875 return !exclude; 876 } 877 878 /* 879 * Log a message to the appropriate log files, users, etc. based on 880 * the priority. 881 */ 882 static void 883 logmsg(int pri, const char *msg, const char *from, int flags) 884 { 885 struct filed *f; 886 int i, fac, msglen, omask, prilev; 887 const char *timestamp; 888 char prog[NAME_MAX+1]; 889 char buf[MAXLINE+1]; 890 891 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n", 892 pri, flags, from, msg); 893 894 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM)); 895 896 /* 897 * Check to see if msg looks non-standard. 898 */ 899 msglen = strlen(msg); 900 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' || 901 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') 902 flags |= ADDDATE; 903 904 (void)time(&now); 905 if (flags & ADDDATE) { 906 timestamp = ctime(&now) + 4; 907 } else { 908 timestamp = msg; 909 msg += 16; 910 msglen -= 16; 911 } 912 913 /* skip leading blanks */ 914 while (isspace(*msg)) { 915 msg++; 916 msglen--; 917 } 918 919 /* extract facility and priority level */ 920 if (flags & MARK) 921 fac = LOG_NFACILITIES; 922 else 923 fac = LOG_FAC(pri); 924 925 /* Check maximum facility number. */ 926 if (fac > LOG_NFACILITIES) { 927 (void)sigsetmask(omask); 928 return; 929 } 930 931 prilev = LOG_PRI(pri); 932 933 /* extract program name */ 934 for (i = 0; i < NAME_MAX; i++) { 935 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' || 936 msg[i] == '/' || isspace(msg[i])) 937 break; 938 prog[i] = msg[i]; 939 } 940 prog[i] = 0; 941 942 /* add kernel prefix for kernel messages */ 943 if (flags & ISKERNEL) { 944 snprintf(buf, sizeof(buf), "%s: %s", 945 use_bootfile ? bootfile : "kernel", msg); 946 msg = buf; 947 msglen = strlen(buf); 948 } 949 950 /* log the message to the particular outputs */ 951 if (!Initialized) { 952 f = &consfile; 953 f->f_file = open(ctty, O_WRONLY, 0); 954 955 if (f->f_file >= 0) { 956 (void)strlcpy(f->f_lasttime, timestamp, 957 sizeof(f->f_lasttime)); 958 fprintlog(f, flags, msg); 959 (void)close(f->f_file); 960 } 961 (void)sigsetmask(omask); 962 return; 963 } 964 for (f = Files; f; f = f->f_next) { 965 /* skip messages that are incorrect priority */ 966 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev)) 967 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev)) 968 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev)) 969 ) 970 || f->f_pmask[fac] == INTERNAL_NOPRI) 971 continue; 972 973 /* skip messages with the incorrect hostname */ 974 if (skip_message(from, f->f_host, 0)) 975 continue; 976 977 /* skip messages with the incorrect program name */ 978 if (skip_message(prog, f->f_program, 1)) 979 continue; 980 981 /* skip message to console if it has already been printed */ 982 if (f->f_type == F_CONSOLE && (flags & IGN_CONS)) 983 continue; 984 985 /* don't output marks to recently written files */ 986 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2) 987 continue; 988 989 /* 990 * suppress duplicate lines to this file 991 */ 992 if (no_compress - (f->f_type != F_PIPE) < 1 && 993 (flags & MARK) == 0 && msglen == f->f_prevlen && 994 !strcmp(msg, f->f_prevline) && 995 !strcasecmp(from, f->f_prevhost)) { 996 (void)strlcpy(f->f_lasttime, timestamp, 997 sizeof(f->f_lasttime)); 998 f->f_prevcount++; 999 dprintf("msg repeated %d times, %ld sec of %d\n", 1000 f->f_prevcount, (long)(now - f->f_time), 1001 repeatinterval[f->f_repeatcount]); 1002 /* 1003 * If domark would have logged this by now, 1004 * flush it now (so we don't hold isolated messages), 1005 * but back off so we'll flush less often 1006 * in the future. 1007 */ 1008 if (now > REPEATTIME(f)) { 1009 fprintlog(f, flags, (char *)NULL); 1010 BACKOFF(f); 1011 } 1012 } else { 1013 /* new line, save it */ 1014 if (f->f_prevcount) 1015 fprintlog(f, 0, (char *)NULL); 1016 f->f_repeatcount = 0; 1017 f->f_prevpri = pri; 1018 (void)strlcpy(f->f_lasttime, timestamp, 1019 sizeof(f->f_lasttime)); 1020 (void)strlcpy(f->f_prevhost, from, 1021 sizeof(f->f_prevhost)); 1022 if (msglen < MAXSVLINE) { 1023 f->f_prevlen = msglen; 1024 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline)); 1025 fprintlog(f, flags, (char *)NULL); 1026 } else { 1027 f->f_prevline[0] = 0; 1028 f->f_prevlen = 0; 1029 fprintlog(f, flags, msg); 1030 } 1031 } 1032 } 1033 (void)sigsetmask(omask); 1034 } 1035 1036 static void 1037 dofsync(void) 1038 { 1039 struct filed *f; 1040 1041 for (f = Files; f; f = f->f_next) { 1042 if ((f->f_type == F_FILE) && 1043 (f->f_flags & FFLAG_NEEDSYNC)) { 1044 f->f_flags &= ~FFLAG_NEEDSYNC; 1045 (void)fsync(f->f_file); 1046 } 1047 } 1048 } 1049 1050 static void 1051 fprintlog(struct filed *f, int flags, const char *msg) 1052 { 1053 struct iovec iov[7]; 1054 struct iovec *v; 1055 struct addrinfo *r; 1056 int i, l, lsent = 0; 1057 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL; 1058 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n"; 1059 const char *msgret; 1060 1061 v = iov; 1062 if (f->f_type == F_WALL) { 1063 v->iov_base = greetings; 1064 v->iov_len = snprintf(greetings, sizeof greetings, 1065 "\r\n\7Message from syslogd@%s at %.24s ...\r\n", 1066 f->f_prevhost, ctime(&now)); 1067 if (v->iov_len > 0) 1068 v++; 1069 v->iov_base = nul; 1070 v->iov_len = 0; 1071 v++; 1072 } else { 1073 v->iov_base = f->f_lasttime; 1074 v->iov_len = 15; 1075 v++; 1076 v->iov_base = space; 1077 v->iov_len = 1; 1078 v++; 1079 } 1080 1081 if (LogFacPri) { 1082 static char fp_buf[30]; /* Hollow laugh */ 1083 int fac = f->f_prevpri & LOG_FACMASK; 1084 int pri = LOG_PRI(f->f_prevpri); 1085 const char *f_s = NULL; 1086 char f_n[5]; /* Hollow laugh */ 1087 const char *p_s = NULL; 1088 char p_n[5]; /* Hollow laugh */ 1089 1090 if (LogFacPri > 1) { 1091 CODE *c; 1092 1093 for (c = facilitynames; c->c_name; c++) { 1094 if (c->c_val == fac) { 1095 f_s = c->c_name; 1096 break; 1097 } 1098 } 1099 for (c = prioritynames; c->c_name; c++) { 1100 if (c->c_val == pri) { 1101 p_s = c->c_name; 1102 break; 1103 } 1104 } 1105 } 1106 if (!f_s) { 1107 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac)); 1108 f_s = f_n; 1109 } 1110 if (!p_s) { 1111 snprintf(p_n, sizeof p_n, "%d", pri); 1112 p_s = p_n; 1113 } 1114 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s); 1115 v->iov_base = fp_buf; 1116 v->iov_len = strlen(fp_buf); 1117 } else { 1118 v->iov_base = nul; 1119 v->iov_len = 0; 1120 } 1121 v++; 1122 1123 v->iov_base = f->f_prevhost; 1124 v->iov_len = strlen(v->iov_base); 1125 v++; 1126 v->iov_base = space; 1127 v->iov_len = 1; 1128 v++; 1129 1130 if (msg) { 1131 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */ 1132 if (wmsg == NULL) { 1133 logerror("strdup"); 1134 exit(1); 1135 } 1136 v->iov_base = wmsg; 1137 v->iov_len = strlen(msg); 1138 } else if (f->f_prevcount > 1) { 1139 v->iov_base = repbuf; 1140 v->iov_len = snprintf(repbuf, sizeof repbuf, 1141 "last message repeated %d times", f->f_prevcount); 1142 } else { 1143 v->iov_base = f->f_prevline; 1144 v->iov_len = f->f_prevlen; 1145 } 1146 v++; 1147 1148 dprintf("Logging to %s", TypeNames[f->f_type]); 1149 f->f_time = now; 1150 1151 switch (f->f_type) { 1152 case F_UNUSED: 1153 dprintf("\n"); 1154 break; 1155 1156 case F_FORW: 1157 dprintf(" %s\n", f->f_un.f_forw.f_hname); 1158 /* check for local vs remote messages */ 1159 if (strcasecmp(f->f_prevhost, LocalHostName)) 1160 l = snprintf(line, sizeof line - 1, 1161 "<%d>%.15s Forwarded from %s: %s", 1162 f->f_prevpri, (char *)iov[0].iov_base, 1163 f->f_prevhost, (char *)iov[5].iov_base); 1164 else 1165 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s", 1166 f->f_prevpri, (char *)iov[0].iov_base, 1167 (char *)iov[5].iov_base); 1168 if (l < 0) 1169 l = 0; 1170 else if (l > MAXLINE) 1171 l = MAXLINE; 1172 1173 if (finet) { 1174 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) { 1175 for (i = 0; i < *finet; i++) { 1176 #if 0 1177 /* 1178 * should we check AF first, or just 1179 * trial and error? FWD 1180 */ 1181 if (r->ai_family == 1182 address_family_of(finet[i+1])) 1183 #endif 1184 lsent = sendto(finet[i+1], line, l, 0, 1185 r->ai_addr, r->ai_addrlen); 1186 if (lsent == l) 1187 break; 1188 } 1189 if (lsent == l && !send_to_all) 1190 break; 1191 } 1192 dprintf("lsent/l: %d/%d\n", lsent, l); 1193 if (lsent != l) { 1194 int e = errno; 1195 logerror("sendto"); 1196 errno = e; 1197 switch (errno) { 1198 case ENOBUFS: 1199 case ENETDOWN: 1200 case EHOSTUNREACH: 1201 case EHOSTDOWN: 1202 break; 1203 /* case EBADF: */ 1204 /* case EACCES: */ 1205 /* case ENOTSOCK: */ 1206 /* case EFAULT: */ 1207 /* case EMSGSIZE: */ 1208 /* case EAGAIN: */ 1209 /* case ENOBUFS: */ 1210 /* case ECONNREFUSED: */ 1211 default: 1212 dprintf("removing entry\n"); 1213 f->f_type = F_UNUSED; 1214 break; 1215 } 1216 } 1217 } 1218 break; 1219 1220 case F_FILE: 1221 dprintf(" %s\n", f->f_un.f_fname); 1222 v->iov_base = lf; 1223 v->iov_len = 1; 1224 if (writev(f->f_file, iov, 7) < 0) { 1225 int e = errno; 1226 (void)close(f->f_file); 1227 f->f_type = F_UNUSED; 1228 errno = e; 1229 logerror(f->f_un.f_fname); 1230 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) { 1231 f->f_flags |= FFLAG_NEEDSYNC; 1232 needdofsync = 1; 1233 } 1234 break; 1235 1236 case F_PIPE: 1237 dprintf(" %s\n", f->f_un.f_pipe.f_pname); 1238 v->iov_base = lf; 1239 v->iov_len = 1; 1240 if (f->f_un.f_pipe.f_pid == 0) { 1241 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname, 1242 &f->f_un.f_pipe.f_pid)) < 0) { 1243 f->f_type = F_UNUSED; 1244 logerror(f->f_un.f_pipe.f_pname); 1245 break; 1246 } 1247 } 1248 if (writev(f->f_file, iov, 7) < 0) { 1249 int e = errno; 1250 (void)close(f->f_file); 1251 if (f->f_un.f_pipe.f_pid > 0) 1252 deadq_enter(f->f_un.f_pipe.f_pid, 1253 f->f_un.f_pipe.f_pname); 1254 f->f_un.f_pipe.f_pid = 0; 1255 errno = e; 1256 logerror(f->f_un.f_pipe.f_pname); 1257 } 1258 break; 1259 1260 case F_CONSOLE: 1261 if (flags & IGN_CONS) { 1262 dprintf(" (ignored)\n"); 1263 break; 1264 } 1265 /* FALLTHROUGH */ 1266 1267 case F_TTY: 1268 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname); 1269 v->iov_base = crlf; 1270 v->iov_len = 2; 1271 1272 errno = 0; /* ttymsg() only sometimes returns an errno */ 1273 if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) { 1274 f->f_type = F_UNUSED; 1275 logerror(msgret); 1276 } 1277 break; 1278 1279 case F_USERS: 1280 case F_WALL: 1281 dprintf("\n"); 1282 v->iov_base = crlf; 1283 v->iov_len = 2; 1284 wallmsg(f, iov); 1285 break; 1286 } 1287 f->f_prevcount = 0; 1288 if (msg) 1289 free(wmsg); 1290 } 1291 1292 /* 1293 * WALLMSG -- Write a message to the world at large 1294 * 1295 * Write the specified message to either the entire 1296 * world, or a list of approved users. 1297 */ 1298 static void 1299 wallmsg(struct filed *f, struct iovec *iov) 1300 { 1301 static int reenter; /* avoid calling ourselves */ 1302 FILE *uf; 1303 struct utmp ut; 1304 int i; 1305 const char *p; 1306 char line[sizeof(ut.ut_line) + 1]; 1307 1308 if (reenter++) 1309 return; 1310 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) { 1311 logerror(_PATH_UTMP); 1312 reenter = 0; 1313 return; 1314 } 1315 /* NOSTRICT */ 1316 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) { 1317 if (ut.ut_name[0] == '\0') 1318 continue; 1319 /* We must use strncpy since ut_* may not be NUL terminated. */ 1320 strncpy(line, ut.ut_line, sizeof(line) - 1); 1321 line[sizeof(line) - 1] = '\0'; 1322 if (f->f_type == F_WALL) { 1323 if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) { 1324 errno = 0; /* already in msg */ 1325 logerror(p); 1326 } 1327 continue; 1328 } 1329 /* should we send the message to this user? */ 1330 for (i = 0; i < MAXUNAMES; i++) { 1331 if (!f->f_un.f_uname[i][0]) 1332 break; 1333 if (!strncmp(f->f_un.f_uname[i], ut.ut_name, 1334 UT_NAMESIZE)) { 1335 if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) 1336 != NULL) { 1337 errno = 0; /* already in msg */ 1338 logerror(p); 1339 } 1340 break; 1341 } 1342 } 1343 } 1344 (void)fclose(uf); 1345 reenter = 0; 1346 } 1347 1348 static void 1349 reapchild(int signo __unused) 1350 { 1351 int status; 1352 pid_t pid; 1353 struct filed *f; 1354 1355 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) { 1356 if (!Initialized) 1357 /* Don't tell while we are initting. */ 1358 continue; 1359 1360 /* First, look if it's a process from the dead queue. */ 1361 if (deadq_remove(pid)) 1362 goto oncemore; 1363 1364 /* Now, look in list of active processes. */ 1365 for (f = Files; f; f = f->f_next) 1366 if (f->f_type == F_PIPE && 1367 f->f_un.f_pipe.f_pid == pid) { 1368 (void)close(f->f_file); 1369 f->f_un.f_pipe.f_pid = 0; 1370 log_deadchild(pid, status, 1371 f->f_un.f_pipe.f_pname); 1372 break; 1373 } 1374 oncemore: 1375 continue; 1376 } 1377 } 1378 1379 /* 1380 * Return a printable representation of a host address. 1381 */ 1382 static const char * 1383 cvthname(struct sockaddr *f) 1384 { 1385 int error, hl; 1386 sigset_t omask, nmask; 1387 static char hname[NI_MAXHOST], ip[NI_MAXHOST]; 1388 1389 error = getnameinfo((struct sockaddr *)f, 1390 ((struct sockaddr *)f)->sa_len, 1391 ip, sizeof ip, NULL, 0, NI_NUMERICHOST); 1392 dprintf("cvthname(%s)\n", ip); 1393 1394 if (error) { 1395 dprintf("Malformed from address %s\n", gai_strerror(error)); 1396 return ("???"); 1397 } 1398 if (!resolve) 1399 return (ip); 1400 1401 sigemptyset(&nmask); 1402 sigaddset(&nmask, SIGHUP); 1403 sigprocmask(SIG_BLOCK, &nmask, &omask); 1404 error = getnameinfo((struct sockaddr *)f, 1405 ((struct sockaddr *)f)->sa_len, 1406 hname, sizeof hname, NULL, 0, NI_NAMEREQD); 1407 sigprocmask(SIG_SETMASK, &omask, NULL); 1408 if (error) { 1409 dprintf("Host name for your address (%s) unknown\n", ip); 1410 return (ip); 1411 } 1412 hl = strlen(hname); 1413 if (hl > 0 && hname[hl-1] == '.') 1414 hname[--hl] = '\0'; 1415 trimdomain(hname, hl); 1416 return (hname); 1417 } 1418 1419 static void 1420 dodie(int signo) 1421 { 1422 1423 WantDie = signo; 1424 } 1425 1426 static void 1427 domark(int signo __unused) 1428 { 1429 1430 MarkSet = 1; 1431 } 1432 1433 /* 1434 * Print syslogd errors some place. 1435 */ 1436 static void 1437 logerror(const char *type) 1438 { 1439 char buf[512]; 1440 static int recursed = 0; 1441 1442 /* If there's an error while trying to log an error, give up. */ 1443 if (recursed) 1444 return; 1445 recursed++; 1446 if (errno) 1447 (void)snprintf(buf, 1448 sizeof buf, "syslogd: %s: %s", type, strerror(errno)); 1449 else 1450 (void)snprintf(buf, sizeof buf, "syslogd: %s", type); 1451 errno = 0; 1452 dprintf("%s\n", buf); 1453 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE); 1454 recursed--; 1455 } 1456 1457 static void 1458 die(int signo) 1459 { 1460 struct filed *f; 1461 struct funix *fx; 1462 int was_initialized; 1463 char buf[100]; 1464 1465 was_initialized = Initialized; 1466 Initialized = 0; /* Don't log SIGCHLDs. */ 1467 for (f = Files; f != NULL; f = f->f_next) { 1468 /* flush any pending output */ 1469 if (f->f_prevcount) 1470 fprintlog(f, 0, (char *)NULL); 1471 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) { 1472 (void)close(f->f_file); 1473 f->f_un.f_pipe.f_pid = 0; 1474 } 1475 } 1476 Initialized = was_initialized; 1477 if (signo) { 1478 dprintf("syslogd: exiting on signal %d\n", signo); 1479 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo); 1480 errno = 0; 1481 logerror(buf); 1482 } 1483 STAILQ_FOREACH(fx, &funixes, next) 1484 (void)unlink(fx->name); 1485 pidfile_remove(pfh); 1486 1487 exit(1); 1488 } 1489 1490 /* 1491 * INIT -- Initialize syslogd from configuration table 1492 */ 1493 static void 1494 init(int signo) 1495 { 1496 int i; 1497 FILE *cf; 1498 struct filed *f, *next, **nextp; 1499 char *p; 1500 char cline[LINE_MAX]; 1501 char prog[NAME_MAX+1]; 1502 char host[MAXHOSTNAMELEN]; 1503 char oldLocalHostName[MAXHOSTNAMELEN]; 1504 char hostMsg[2*MAXHOSTNAMELEN+40]; 1505 char bootfileMsg[LINE_MAX]; 1506 1507 dprintf("init\n"); 1508 1509 /* 1510 * Load hostname (may have changed). 1511 */ 1512 if (signo != 0) 1513 (void)strlcpy(oldLocalHostName, LocalHostName, 1514 sizeof(oldLocalHostName)); 1515 if (gethostname(LocalHostName, sizeof(LocalHostName))) 1516 err(EX_OSERR, "gethostname() failed"); 1517 if ((p = strchr(LocalHostName, '.')) != NULL) { 1518 *p++ = '\0'; 1519 LocalDomain = p; 1520 } else { 1521 LocalDomain = ""; 1522 } 1523 1524 /* 1525 * Close all open log files. 1526 */ 1527 Initialized = 0; 1528 for (f = Files; f != NULL; f = next) { 1529 /* flush any pending output */ 1530 if (f->f_prevcount) 1531 fprintlog(f, 0, (char *)NULL); 1532 1533 switch (f->f_type) { 1534 case F_FILE: 1535 case F_FORW: 1536 case F_CONSOLE: 1537 case F_TTY: 1538 (void)close(f->f_file); 1539 break; 1540 case F_PIPE: 1541 if (f->f_un.f_pipe.f_pid > 0) { 1542 (void)close(f->f_file); 1543 deadq_enter(f->f_un.f_pipe.f_pid, 1544 f->f_un.f_pipe.f_pname); 1545 } 1546 f->f_un.f_pipe.f_pid = 0; 1547 break; 1548 } 1549 next = f->f_next; 1550 if (f->f_program) free(f->f_program); 1551 if (f->f_host) free(f->f_host); 1552 free((char *)f); 1553 } 1554 Files = NULL; 1555 nextp = &Files; 1556 1557 /* open the configuration file */ 1558 if ((cf = fopen(ConfFile, "r")) == NULL) { 1559 dprintf("cannot open %s\n", ConfFile); 1560 *nextp = (struct filed *)calloc(1, sizeof(*f)); 1561 if (*nextp == NULL) { 1562 logerror("calloc"); 1563 exit(1); 1564 } 1565 cfline("*.ERR\t/dev/console", *nextp, "*", "*"); 1566 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f)); 1567 if ((*nextp)->f_next == NULL) { 1568 logerror("calloc"); 1569 exit(1); 1570 } 1571 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*"); 1572 Initialized = 1; 1573 return; 1574 } 1575 1576 /* 1577 * Foreach line in the conf table, open that file. 1578 */ 1579 f = NULL; 1580 (void)strlcpy(host, "*", sizeof(host)); 1581 (void)strlcpy(prog, "*", sizeof(prog)); 1582 while (fgets(cline, sizeof(cline), cf) != NULL) { 1583 /* 1584 * check for end-of-section, comments, strip off trailing 1585 * spaces and newline character. #!prog is treated specially: 1586 * following lines apply only to that program. 1587 */ 1588 for (p = cline; isspace(*p); ++p) 1589 continue; 1590 if (*p == 0) 1591 continue; 1592 if (*p == '#') { 1593 p++; 1594 if (*p != '!' && *p != '+' && *p != '-') 1595 continue; 1596 } 1597 if (*p == '+' || *p == '-') { 1598 host[0] = *p++; 1599 while (isspace(*p)) 1600 p++; 1601 if ((!*p) || (*p == '*')) { 1602 (void)strlcpy(host, "*", sizeof(host)); 1603 continue; 1604 } 1605 if (*p == '@') 1606 p = LocalHostName; 1607 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) { 1608 if (!isalnum(*p) && *p != '.' && *p != '-' 1609 && *p != ',' && *p != ':' && *p != '%') 1610 break; 1611 host[i] = *p++; 1612 } 1613 host[i] = '\0'; 1614 continue; 1615 } 1616 if (*p == '!') { 1617 p++; 1618 while (isspace(*p)) p++; 1619 if ((!*p) || (*p == '*')) { 1620 (void)strlcpy(prog, "*", sizeof(prog)); 1621 continue; 1622 } 1623 for (i = 0; i < NAME_MAX; i++) { 1624 if (!isprint(p[i]) || isspace(p[i])) 1625 break; 1626 prog[i] = p[i]; 1627 } 1628 prog[i] = 0; 1629 continue; 1630 } 1631 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--) 1632 cline[i] = '\0'; 1633 f = (struct filed *)calloc(1, sizeof(*f)); 1634 if (f == NULL) { 1635 logerror("calloc"); 1636 exit(1); 1637 } 1638 *nextp = f; 1639 nextp = &f->f_next; 1640 cfline(cline, f, prog, host); 1641 } 1642 1643 /* close the configuration file */ 1644 (void)fclose(cf); 1645 1646 Initialized = 1; 1647 1648 if (Debug) { 1649 for (f = Files; f; f = f->f_next) { 1650 for (i = 0; i <= LOG_NFACILITIES; i++) 1651 if (f->f_pmask[i] == INTERNAL_NOPRI) 1652 printf("X "); 1653 else 1654 printf("%d ", f->f_pmask[i]); 1655 printf("%s: ", TypeNames[f->f_type]); 1656 switch (f->f_type) { 1657 case F_FILE: 1658 printf("%s", f->f_un.f_fname); 1659 break; 1660 1661 case F_CONSOLE: 1662 case F_TTY: 1663 printf("%s%s", _PATH_DEV, f->f_un.f_fname); 1664 break; 1665 1666 case F_FORW: 1667 printf("%s", f->f_un.f_forw.f_hname); 1668 break; 1669 1670 case F_PIPE: 1671 printf("%s", f->f_un.f_pipe.f_pname); 1672 break; 1673 1674 case F_USERS: 1675 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++) 1676 printf("%s, ", f->f_un.f_uname[i]); 1677 break; 1678 } 1679 if (f->f_program) 1680 printf(" (%s)", f->f_program); 1681 printf("\n"); 1682 } 1683 } 1684 1685 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE); 1686 dprintf("syslogd: restarted\n"); 1687 /* 1688 * Log a change in hostname, but only on a restart. 1689 */ 1690 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) { 1691 (void)snprintf(hostMsg, sizeof(hostMsg), 1692 "syslogd: hostname changed, \"%s\" to \"%s\"", 1693 oldLocalHostName, LocalHostName); 1694 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE); 1695 dprintf("%s\n", hostMsg); 1696 } 1697 /* 1698 * Log the kernel boot file if we aren't going to use it as 1699 * the prefix, and if this is *not* a restart. 1700 */ 1701 if (signo == 0 && !use_bootfile) { 1702 (void)snprintf(bootfileMsg, sizeof(bootfileMsg), 1703 "syslogd: kernel boot file is %s", bootfile); 1704 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE); 1705 dprintf("%s\n", bootfileMsg); 1706 } 1707 } 1708 1709 /* 1710 * Crack a configuration file line 1711 */ 1712 static void 1713 cfline(const char *line, struct filed *f, const char *prog, const char *host) 1714 { 1715 struct addrinfo hints, *res; 1716 int error, i, pri, syncfile; 1717 const char *p, *q; 1718 char *bp; 1719 char buf[MAXLINE], ebuf[100]; 1720 1721 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host); 1722 1723 errno = 0; /* keep strerror() stuff out of logerror messages */ 1724 1725 /* clear out file entry */ 1726 memset(f, 0, sizeof(*f)); 1727 for (i = 0; i <= LOG_NFACILITIES; i++) 1728 f->f_pmask[i] = INTERNAL_NOPRI; 1729 1730 /* save hostname if any */ 1731 if (host && *host == '*') 1732 host = NULL; 1733 if (host) { 1734 int hl; 1735 1736 f->f_host = strdup(host); 1737 if (f->f_host == NULL) { 1738 logerror("strdup"); 1739 exit(1); 1740 } 1741 hl = strlen(f->f_host); 1742 if (hl > 0 && f->f_host[hl-1] == '.') 1743 f->f_host[--hl] = '\0'; 1744 trimdomain(f->f_host, hl); 1745 } 1746 1747 /* save program name if any */ 1748 if (prog && *prog == '*') 1749 prog = NULL; 1750 if (prog) { 1751 f->f_program = strdup(prog); 1752 if (f->f_program == NULL) { 1753 logerror("strdup"); 1754 exit(1); 1755 } 1756 } 1757 1758 /* scan through the list of selectors */ 1759 for (p = line; *p && *p != '\t' && *p != ' ';) { 1760 int pri_done; 1761 int pri_cmp; 1762 int pri_invert; 1763 1764 /* find the end of this facility name list */ 1765 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; ) 1766 continue; 1767 1768 /* get the priority comparison */ 1769 pri_cmp = 0; 1770 pri_done = 0; 1771 pri_invert = 0; 1772 if (*q == '!') { 1773 pri_invert = 1; 1774 q++; 1775 } 1776 while (!pri_done) { 1777 switch (*q) { 1778 case '<': 1779 pri_cmp |= PRI_LT; 1780 q++; 1781 break; 1782 case '=': 1783 pri_cmp |= PRI_EQ; 1784 q++; 1785 break; 1786 case '>': 1787 pri_cmp |= PRI_GT; 1788 q++; 1789 break; 1790 default: 1791 pri_done++; 1792 break; 1793 } 1794 } 1795 1796 /* collect priority name */ 1797 for (bp = buf; *q && !strchr("\t,; ", *q); ) 1798 *bp++ = *q++; 1799 *bp = '\0'; 1800 1801 /* skip cruft */ 1802 while (strchr(",;", *q)) 1803 q++; 1804 1805 /* decode priority name */ 1806 if (*buf == '*') { 1807 pri = LOG_PRIMASK + 1; 1808 pri_cmp = PRI_LT | PRI_EQ | PRI_GT; 1809 } else { 1810 /* Ignore trailing spaces. */ 1811 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--) 1812 buf[i] = '\0'; 1813 1814 pri = decode(buf, prioritynames); 1815 if (pri < 0) { 1816 (void)snprintf(ebuf, sizeof ebuf, 1817 "unknown priority name \"%s\"", buf); 1818 logerror(ebuf); 1819 return; 1820 } 1821 } 1822 if (!pri_cmp) 1823 pri_cmp = (UniquePriority) 1824 ? (PRI_EQ) 1825 : (PRI_EQ | PRI_GT) 1826 ; 1827 if (pri_invert) 1828 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT; 1829 1830 /* scan facilities */ 1831 while (*p && !strchr("\t.; ", *p)) { 1832 for (bp = buf; *p && !strchr("\t,;. ", *p); ) 1833 *bp++ = *p++; 1834 *bp = '\0'; 1835 1836 if (*buf == '*') { 1837 for (i = 0; i < LOG_NFACILITIES; i++) { 1838 f->f_pmask[i] = pri; 1839 f->f_pcmp[i] = pri_cmp; 1840 } 1841 } else { 1842 i = decode(buf, facilitynames); 1843 if (i < 0) { 1844 (void)snprintf(ebuf, sizeof ebuf, 1845 "unknown facility name \"%s\"", 1846 buf); 1847 logerror(ebuf); 1848 return; 1849 } 1850 f->f_pmask[i >> 3] = pri; 1851 f->f_pcmp[i >> 3] = pri_cmp; 1852 } 1853 while (*p == ',' || *p == ' ') 1854 p++; 1855 } 1856 1857 p = q; 1858 } 1859 1860 /* skip to action part */ 1861 while (*p == '\t' || *p == ' ') 1862 p++; 1863 1864 if (*p == '-') { 1865 syncfile = 0; 1866 p++; 1867 } else 1868 syncfile = 1; 1869 1870 switch (*p) { 1871 case '@': 1872 (void)strlcpy(f->f_un.f_forw.f_hname, ++p, 1873 sizeof(f->f_un.f_forw.f_hname)); 1874 memset(&hints, 0, sizeof(hints)); 1875 hints.ai_family = family; 1876 hints.ai_socktype = SOCK_DGRAM; 1877 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints, 1878 &res); 1879 if (error) { 1880 logerror(gai_strerror(error)); 1881 break; 1882 } 1883 f->f_un.f_forw.f_addr = res; 1884 f->f_type = F_FORW; 1885 break; 1886 1887 case '/': 1888 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) { 1889 f->f_type = F_UNUSED; 1890 logerror(p); 1891 break; 1892 } 1893 if (syncfile) 1894 f->f_flags |= FFLAG_SYNC; 1895 if (isatty(f->f_file)) { 1896 if (strcmp(p, ctty) == 0) 1897 f->f_type = F_CONSOLE; 1898 else 1899 f->f_type = F_TTY; 1900 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1, 1901 sizeof(f->f_un.f_fname)); 1902 } else { 1903 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname)); 1904 f->f_type = F_FILE; 1905 } 1906 break; 1907 1908 case '|': 1909 f->f_un.f_pipe.f_pid = 0; 1910 (void)strlcpy(f->f_un.f_fname, p + 1, sizeof(f->f_un.f_fname)); 1911 f->f_type = F_PIPE; 1912 break; 1913 1914 case '*': 1915 f->f_type = F_WALL; 1916 break; 1917 1918 default: 1919 for (i = 0; i < MAXUNAMES && *p; i++) { 1920 for (q = p; *q && *q != ','; ) 1921 q++; 1922 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE); 1923 if ((q - p) > UT_NAMESIZE) 1924 f->f_un.f_uname[i][UT_NAMESIZE] = '\0'; 1925 else 1926 f->f_un.f_uname[i][q - p] = '\0'; 1927 while (*q == ',' || *q == ' ') 1928 q++; 1929 p = q; 1930 } 1931 f->f_type = F_USERS; 1932 break; 1933 } 1934 } 1935 1936 1937 /* 1938 * Decode a symbolic name to a numeric value 1939 */ 1940 static int 1941 decode(const char *name, CODE *codetab) 1942 { 1943 CODE *c; 1944 char *p, buf[40]; 1945 1946 if (isdigit(*name)) 1947 return (atoi(name)); 1948 1949 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) { 1950 if (isupper(*name)) 1951 *p = tolower(*name); 1952 else 1953 *p = *name; 1954 } 1955 *p = '\0'; 1956 for (c = codetab; c->c_name; c++) 1957 if (!strcmp(buf, c->c_name)) 1958 return (c->c_val); 1959 1960 return (-1); 1961 } 1962 1963 static void 1964 markit(void) 1965 { 1966 struct filed *f; 1967 dq_t q, next; 1968 1969 now = time((time_t *)NULL); 1970 MarkSeq += TIMERINTVL; 1971 if (MarkSeq >= MarkInterval) { 1972 logmsg(LOG_INFO, "-- MARK --", 1973 LocalHostName, ADDDATE|MARK); 1974 MarkSeq = 0; 1975 } 1976 1977 for (f = Files; f; f = f->f_next) { 1978 if (f->f_prevcount && now >= REPEATTIME(f)) { 1979 dprintf("flush %s: repeated %d times, %d sec.\n", 1980 TypeNames[f->f_type], f->f_prevcount, 1981 repeatinterval[f->f_repeatcount]); 1982 fprintlog(f, 0, (char *)NULL); 1983 BACKOFF(f); 1984 } 1985 } 1986 1987 /* Walk the dead queue, and see if we should signal somebody. */ 1988 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) { 1989 next = TAILQ_NEXT(q, dq_entries); 1990 1991 switch (q->dq_timeout) { 1992 case 0: 1993 /* Already signalled once, try harder now. */ 1994 if (kill(q->dq_pid, SIGKILL) != 0) 1995 (void)deadq_remove(q->dq_pid); 1996 break; 1997 1998 case 1: 1999 /* 2000 * Timed out on dead queue, send terminate 2001 * signal. Note that we leave the removal 2002 * from the dead queue to reapchild(), which 2003 * will also log the event (unless the process 2004 * didn't even really exist, in case we simply 2005 * drop it from the dead queue). 2006 */ 2007 if (kill(q->dq_pid, SIGTERM) != 0) 2008 (void)deadq_remove(q->dq_pid); 2009 /* FALLTHROUGH */ 2010 2011 default: 2012 q->dq_timeout--; 2013 } 2014 } 2015 MarkSet = 0; 2016 (void)alarm(TIMERINTVL); 2017 } 2018 2019 /* 2020 * fork off and become a daemon, but wait for the child to come online 2021 * before returing to the parent, or we get disk thrashing at boot etc. 2022 * Set a timer so we don't hang forever if it wedges. 2023 */ 2024 static int 2025 waitdaemon(int nochdir, int noclose, int maxwait) 2026 { 2027 int fd; 2028 int status; 2029 pid_t pid, childpid; 2030 2031 switch (childpid = fork()) { 2032 case -1: 2033 return (-1); 2034 case 0: 2035 break; 2036 default: 2037 signal(SIGALRM, timedout); 2038 alarm(maxwait); 2039 while ((pid = wait3(&status, 0, NULL)) != -1) { 2040 if (WIFEXITED(status)) 2041 errx(1, "child pid %d exited with return code %d", 2042 pid, WEXITSTATUS(status)); 2043 if (WIFSIGNALED(status)) 2044 errx(1, "child pid %d exited on signal %d%s", 2045 pid, WTERMSIG(status), 2046 WCOREDUMP(status) ? " (core dumped)" : 2047 ""); 2048 if (pid == childpid) /* it's gone... */ 2049 break; 2050 } 2051 exit(0); 2052 } 2053 2054 if (setsid() == -1) 2055 return (-1); 2056 2057 if (!nochdir) 2058 (void)chdir("/"); 2059 2060 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { 2061 (void)dup2(fd, STDIN_FILENO); 2062 (void)dup2(fd, STDOUT_FILENO); 2063 (void)dup2(fd, STDERR_FILENO); 2064 if (fd > 2) 2065 (void)close (fd); 2066 } 2067 return (getppid()); 2068 } 2069 2070 /* 2071 * We get a SIGALRM from the child when it's running and finished doing it's 2072 * fsync()'s or O_SYNC writes for all the boot messages. 2073 * 2074 * We also get a signal from the kernel if the timer expires, so check to 2075 * see what happened. 2076 */ 2077 static void 2078 timedout(int sig __unused) 2079 { 2080 int left; 2081 left = alarm(0); 2082 signal(SIGALRM, SIG_DFL); 2083 if (left == 0) 2084 errx(1, "timed out waiting for child"); 2085 else 2086 _exit(0); 2087 } 2088 2089 /* 2090 * Add `s' to the list of allowable peer addresses to accept messages 2091 * from. 2092 * 2093 * `s' is a string in the form: 2094 * 2095 * [*]domainname[:{servicename|portnumber|*}] 2096 * 2097 * or 2098 * 2099 * netaddr/maskbits[:{servicename|portnumber|*}] 2100 * 2101 * Returns -1 on error, 0 if the argument was valid. 2102 */ 2103 static int 2104 allowaddr(char *s) 2105 { 2106 char *cp1, *cp2; 2107 struct allowedpeer ap; 2108 struct servent *se; 2109 int masklen = -1, i; 2110 struct addrinfo hints, *res; 2111 struct in_addr *addrp, *maskp; 2112 u_int32_t *addr6p, *mask6p; 2113 char ip[NI_MAXHOST]; 2114 2115 #ifdef INET6 2116 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL) 2117 #endif 2118 cp1 = s; 2119 if ((cp1 = strrchr(cp1, ':'))) { 2120 /* service/port provided */ 2121 *cp1++ = '\0'; 2122 if (strlen(cp1) == 1 && *cp1 == '*') 2123 /* any port allowed */ 2124 ap.port = 0; 2125 else if ((se = getservbyname(cp1, "udp"))) { 2126 ap.port = ntohs(se->s_port); 2127 } else { 2128 ap.port = strtol(cp1, &cp2, 0); 2129 if (*cp2 != '\0') 2130 return (-1); /* port not numeric */ 2131 } 2132 } else { 2133 if ((se = getservbyname("syslog", "udp"))) 2134 ap.port = ntohs(se->s_port); 2135 else 2136 /* sanity, should not happen */ 2137 ap.port = 514; 2138 } 2139 2140 if ((cp1 = strchr(s, '/')) != NULL && 2141 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) { 2142 *cp1 = '\0'; 2143 if ((masklen = atoi(cp1 + 1)) < 0) 2144 return (-1); 2145 } 2146 #ifdef INET6 2147 if (*s == '[') { 2148 cp2 = s + strlen(s) - 1; 2149 if (*cp2 == ']') { 2150 ++s; 2151 *cp2 = '\0'; 2152 } else { 2153 cp2 = NULL; 2154 } 2155 } else { 2156 cp2 = NULL; 2157 } 2158 #endif 2159 memset(&hints, 0, sizeof(hints)); 2160 hints.ai_family = PF_UNSPEC; 2161 hints.ai_socktype = SOCK_DGRAM; 2162 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; 2163 if (getaddrinfo(s, NULL, &hints, &res) == 0) { 2164 ap.isnumeric = 1; 2165 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen); 2166 memset(&ap.a_mask, 0, sizeof(ap.a_mask)); 2167 ap.a_mask.ss_family = res->ai_family; 2168 if (res->ai_family == AF_INET) { 2169 ap.a_mask.ss_len = sizeof(struct sockaddr_in); 2170 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr; 2171 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr; 2172 if (masklen < 0) { 2173 /* use default netmask */ 2174 if (IN_CLASSA(ntohl(addrp->s_addr))) 2175 maskp->s_addr = htonl(IN_CLASSA_NET); 2176 else if (IN_CLASSB(ntohl(addrp->s_addr))) 2177 maskp->s_addr = htonl(IN_CLASSB_NET); 2178 else 2179 maskp->s_addr = htonl(IN_CLASSC_NET); 2180 } else if (masklen <= 32) { 2181 /* convert masklen to netmask */ 2182 if (masklen == 0) 2183 maskp->s_addr = 0; 2184 else 2185 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1)); 2186 } else { 2187 freeaddrinfo(res); 2188 return (-1); 2189 } 2190 /* Lose any host bits in the network number. */ 2191 addrp->s_addr &= maskp->s_addr; 2192 } 2193 #ifdef INET6 2194 else if (res->ai_family == AF_INET6 && masklen <= 128) { 2195 ap.a_mask.ss_len = sizeof(struct sockaddr_in6); 2196 if (masklen < 0) 2197 masklen = 128; 2198 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr; 2199 /* convert masklen to netmask */ 2200 while (masklen > 0) { 2201 if (masklen < 32) { 2202 *mask6p = htonl(~(0xffffffff >> masklen)); 2203 break; 2204 } 2205 *mask6p++ = 0xffffffff; 2206 masklen -= 32; 2207 } 2208 /* Lose any host bits in the network number. */ 2209 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr; 2210 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr; 2211 for (i = 0; i < 4; i++) 2212 addr6p[i] &= mask6p[i]; 2213 } 2214 #endif 2215 else { 2216 freeaddrinfo(res); 2217 return (-1); 2218 } 2219 freeaddrinfo(res); 2220 } else { 2221 /* arg `s' is domain name */ 2222 ap.isnumeric = 0; 2223 ap.a_name = s; 2224 if (cp1) 2225 *cp1 = '/'; 2226 #ifdef INET6 2227 if (cp2) { 2228 *cp2 = ']'; 2229 --s; 2230 } 2231 #endif 2232 } 2233 2234 if (Debug) { 2235 printf("allowaddr: rule %d: ", NumAllowed); 2236 if (ap.isnumeric) { 2237 printf("numeric, "); 2238 getnameinfo((struct sockaddr *)&ap.a_addr, 2239 ((struct sockaddr *)&ap.a_addr)->sa_len, 2240 ip, sizeof ip, NULL, 0, NI_NUMERICHOST); 2241 printf("addr = %s, ", ip); 2242 getnameinfo((struct sockaddr *)&ap.a_mask, 2243 ((struct sockaddr *)&ap.a_mask)->sa_len, 2244 ip, sizeof ip, NULL, 0, NI_NUMERICHOST); 2245 printf("mask = %s; ", ip); 2246 } else { 2247 printf("domainname = %s; ", ap.a_name); 2248 } 2249 printf("port = %d\n", ap.port); 2250 } 2251 2252 if ((AllowedPeers = realloc(AllowedPeers, 2253 ++NumAllowed * sizeof(struct allowedpeer))) 2254 == NULL) { 2255 logerror("realloc"); 2256 exit(1); 2257 } 2258 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer)); 2259 return (0); 2260 } 2261 2262 /* 2263 * Validate that the remote peer has permission to log to us. 2264 */ 2265 static int 2266 validate(struct sockaddr *sa, const char *hname) 2267 { 2268 int i, j, reject; 2269 size_t l1, l2; 2270 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV]; 2271 struct allowedpeer *ap; 2272 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL; 2273 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL; 2274 struct addrinfo hints, *res; 2275 u_short sport; 2276 2277 if (NumAllowed == 0) 2278 /* traditional behaviour, allow everything */ 2279 return (1); 2280 2281 (void)strlcpy(name, hname, sizeof(name)); 2282 memset(&hints, 0, sizeof(hints)); 2283 hints.ai_family = PF_UNSPEC; 2284 hints.ai_socktype = SOCK_DGRAM; 2285 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; 2286 if (getaddrinfo(name, NULL, &hints, &res) == 0) 2287 freeaddrinfo(res); 2288 else if (strchr(name, '.') == NULL) { 2289 strlcat(name, ".", sizeof name); 2290 strlcat(name, LocalDomain, sizeof name); 2291 } 2292 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port, 2293 NI_NUMERICHOST | NI_NUMERICSERV) != 0) 2294 return (0); /* for safety, should not occur */ 2295 dprintf("validate: dgram from IP %s, port %s, name %s;\n", 2296 ip, port, name); 2297 sport = atoi(port); 2298 2299 /* now, walk down the list */ 2300 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) { 2301 if (ap->port != 0 && ap->port != sport) { 2302 dprintf("rejected in rule %d due to port mismatch.\n", i); 2303 continue; 2304 } 2305 2306 if (ap->isnumeric) { 2307 if (ap->a_addr.ss_family != sa->sa_family) { 2308 dprintf("rejected in rule %d due to address family mismatch.\n", i); 2309 continue; 2310 } 2311 if (ap->a_addr.ss_family == AF_INET) { 2312 sin4 = (struct sockaddr_in *)sa; 2313 a4p = (struct sockaddr_in *)&ap->a_addr; 2314 m4p = (struct sockaddr_in *)&ap->a_mask; 2315 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr) 2316 != a4p->sin_addr.s_addr) { 2317 dprintf("rejected in rule %d due to IP mismatch.\n", i); 2318 continue; 2319 } 2320 } 2321 #ifdef INET6 2322 else if (ap->a_addr.ss_family == AF_INET6) { 2323 sin6 = (struct sockaddr_in6 *)sa; 2324 a6p = (struct sockaddr_in6 *)&ap->a_addr; 2325 m6p = (struct sockaddr_in6 *)&ap->a_mask; 2326 if (a6p->sin6_scope_id != 0 && 2327 sin6->sin6_scope_id != a6p->sin6_scope_id) { 2328 dprintf("rejected in rule %d due to scope mismatch.\n", i); 2329 continue; 2330 } 2331 reject = 0; 2332 for (j = 0; j < 16; j += 4) { 2333 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j]) 2334 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) { 2335 ++reject; 2336 break; 2337 } 2338 } 2339 if (reject) { 2340 dprintf("rejected in rule %d due to IP mismatch.\n", i); 2341 continue; 2342 } 2343 } 2344 #endif 2345 else 2346 continue; 2347 } else { 2348 cp = ap->a_name; 2349 l1 = strlen(name); 2350 if (*cp == '*') { 2351 /* allow wildmatch */ 2352 cp++; 2353 l2 = strlen(cp); 2354 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) { 2355 dprintf("rejected in rule %d due to name mismatch.\n", i); 2356 continue; 2357 } 2358 } else { 2359 /* exact match */ 2360 l2 = strlen(cp); 2361 if (l2 != l1 || memcmp(cp, name, l1) != 0) { 2362 dprintf("rejected in rule %d due to name mismatch.\n", i); 2363 continue; 2364 } 2365 } 2366 } 2367 dprintf("accepted in rule %d.\n", i); 2368 return (1); /* hooray! */ 2369 } 2370 return (0); 2371 } 2372 2373 /* 2374 * Fairly similar to popen(3), but returns an open descriptor, as 2375 * opposed to a FILE *. 2376 */ 2377 static int 2378 p_open(const char *prog, pid_t *rpid) 2379 { 2380 int pfd[2], nulldesc, i; 2381 pid_t pid; 2382 sigset_t omask, mask; 2383 char *argv[4]; /* sh -c cmd NULL */ 2384 char errmsg[200]; 2385 2386 if (pipe(pfd) == -1) 2387 return (-1); 2388 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) 2389 /* we are royally screwed anyway */ 2390 return (-1); 2391 2392 sigemptyset(&mask); 2393 sigaddset(&mask, SIGALRM); 2394 sigaddset(&mask, SIGHUP); 2395 sigprocmask(SIG_BLOCK, &mask, &omask); 2396 switch ((pid = fork())) { 2397 case -1: 2398 sigprocmask(SIG_SETMASK, &omask, 0); 2399 close(nulldesc); 2400 return (-1); 2401 2402 case 0: 2403 argv[0] = strdup("sh"); 2404 argv[1] = strdup("-c"); 2405 argv[2] = strdup(prog); 2406 argv[3] = NULL; 2407 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) { 2408 logerror("strdup"); 2409 exit(1); 2410 } 2411 2412 alarm(0); 2413 (void)setsid(); /* Avoid catching SIGHUPs. */ 2414 2415 /* 2416 * Throw away pending signals, and reset signal 2417 * behaviour to standard values. 2418 */ 2419 signal(SIGALRM, SIG_IGN); 2420 signal(SIGHUP, SIG_IGN); 2421 sigprocmask(SIG_SETMASK, &omask, 0); 2422 signal(SIGPIPE, SIG_DFL); 2423 signal(SIGQUIT, SIG_DFL); 2424 signal(SIGALRM, SIG_DFL); 2425 signal(SIGHUP, SIG_DFL); 2426 2427 dup2(pfd[0], STDIN_FILENO); 2428 dup2(nulldesc, STDOUT_FILENO); 2429 dup2(nulldesc, STDERR_FILENO); 2430 for (i = getdtablesize(); i > 2; i--) 2431 (void)close(i); 2432 2433 (void)execvp(_PATH_BSHELL, argv); 2434 _exit(255); 2435 } 2436 2437 sigprocmask(SIG_SETMASK, &omask, 0); 2438 close(nulldesc); 2439 close(pfd[0]); 2440 /* 2441 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are 2442 * supposed to get an EWOULDBLOCK on writev(2), which is 2443 * caught by the logic above anyway, which will in turn close 2444 * the pipe, and fork a new logging subprocess if necessary. 2445 * The stale subprocess will be killed some time later unless 2446 * it terminated itself due to closing its input pipe (so we 2447 * get rid of really dead puppies). 2448 */ 2449 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) { 2450 /* This is bad. */ 2451 (void)snprintf(errmsg, sizeof errmsg, 2452 "Warning: cannot change pipe to PID %d to " 2453 "non-blocking behaviour.", 2454 (int)pid); 2455 logerror(errmsg); 2456 } 2457 *rpid = pid; 2458 return (pfd[1]); 2459 } 2460 2461 static void 2462 deadq_enter(pid_t pid, const char *name) 2463 { 2464 dq_t p; 2465 int status; 2466 2467 /* 2468 * Be paranoid, if we can't signal the process, don't enter it 2469 * into the dead queue (perhaps it's already dead). If possible, 2470 * we try to fetch and log the child's status. 2471 */ 2472 if (kill(pid, 0) != 0) { 2473 if (waitpid(pid, &status, WNOHANG) > 0) 2474 log_deadchild(pid, status, name); 2475 return; 2476 } 2477 2478 p = malloc(sizeof(struct deadq_entry)); 2479 if (p == NULL) { 2480 logerror("malloc"); 2481 exit(1); 2482 } 2483 2484 p->dq_pid = pid; 2485 p->dq_timeout = DQ_TIMO_INIT; 2486 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries); 2487 } 2488 2489 static int 2490 deadq_remove(pid_t pid) 2491 { 2492 dq_t q; 2493 2494 TAILQ_FOREACH(q, &deadq_head, dq_entries) { 2495 if (q->dq_pid == pid) { 2496 TAILQ_REMOVE(&deadq_head, q, dq_entries); 2497 free(q); 2498 return (1); 2499 } 2500 } 2501 2502 return (0); 2503 } 2504 2505 static void 2506 log_deadchild(pid_t pid, int status, const char *name) 2507 { 2508 int code; 2509 char buf[256]; 2510 const char *reason; 2511 2512 errno = 0; /* Keep strerror() stuff out of logerror messages. */ 2513 if (WIFSIGNALED(status)) { 2514 reason = "due to signal"; 2515 code = WTERMSIG(status); 2516 } else { 2517 reason = "with status"; 2518 code = WEXITSTATUS(status); 2519 if (code == 0) 2520 return; 2521 } 2522 (void)snprintf(buf, sizeof buf, 2523 "Logging subprocess %d (%s) exited %s %d.", 2524 pid, name, reason, code); 2525 logerror(buf); 2526 } 2527 2528 static int * 2529 socksetup(int af, const char *bindhostname) 2530 { 2531 struct addrinfo hints, *res, *r; 2532 int error, maxs, *s, *socks; 2533 2534 memset(&hints, 0, sizeof(hints)); 2535 hints.ai_flags = AI_PASSIVE; 2536 hints.ai_family = af; 2537 hints.ai_socktype = SOCK_DGRAM; 2538 error = getaddrinfo(bindhostname, "syslog", &hints, &res); 2539 if (error) { 2540 logerror(gai_strerror(error)); 2541 errno = 0; 2542 die(0); 2543 } 2544 2545 /* Count max number of sockets we may open */ 2546 for (maxs = 0, r = res; r; r = r->ai_next, maxs++); 2547 socks = malloc((maxs+1) * sizeof(int)); 2548 if (socks == NULL) { 2549 logerror("couldn't allocate memory for sockets"); 2550 die(0); 2551 } 2552 2553 *socks = 0; /* num of sockets counter at start of array */ 2554 s = socks + 1; 2555 for (r = res; r; r = r->ai_next) { 2556 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol); 2557 if (*s < 0) { 2558 logerror("socket"); 2559 continue; 2560 } 2561 if (r->ai_family == AF_INET6) { 2562 int on = 1; 2563 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY, 2564 (char *)&on, sizeof (on)) < 0) { 2565 logerror("setsockopt"); 2566 close(*s); 2567 continue; 2568 } 2569 } 2570 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) { 2571 close(*s); 2572 logerror("bind"); 2573 continue; 2574 } 2575 2576 double_rbuf(*s); 2577 2578 (*socks)++; 2579 s++; 2580 } 2581 2582 if (*socks == 0) { 2583 free(socks); 2584 if (Debug) 2585 return (NULL); 2586 else 2587 die(0); 2588 } 2589 if (res) 2590 freeaddrinfo(res); 2591 2592 return (socks); 2593 } 2594 2595 static void 2596 double_rbuf(int fd) 2597 { 2598 socklen_t slen, len; 2599 2600 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) { 2601 len *= 2; 2602 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen); 2603 } 2604 } 2605