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