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