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