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