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