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