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