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