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 * SPDX-License-Identifier: BSD-2-Clause 33 * 34 * Copyright (c) 2018 Prodrive Technologies, https://prodrive-technologies.com/ 35 * Author: Ed Schouten <ed@FreeBSD.org> 36 * 37 * Redistribution and use in source and binary forms, with or without 38 * modification, are permitted provided that the following conditions 39 * are met: 40 * 1. Redistributions of source code must retain the above copyright 41 * notice, this list of conditions and the following disclaimer. 42 * 2. Redistributions in binary form must reproduce the above copyright 43 * notice, this list of conditions and the following disclaimer in the 44 * documentation and/or other materials provided with the distribution. 45 * 46 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 47 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 49 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 50 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 51 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 52 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 54 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 55 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 56 * SUCH DAMAGE. 57 */ 58 59 /* 60 * syslogd -- log system messages 61 * 62 * This program implements a system log. It takes a series of lines. 63 * Each line may have a priority, signified as "<n>" as 64 * the first characters of the line. If this is 65 * not present, a default priority is used. 66 * 67 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will 68 * cause it to reread its configuration file. 69 * 70 * Author: Eric Allman 71 * extensive changes by Ralph Campbell 72 * more extensive changes by Eric Allman (again) 73 * Extension to log by program name as well as facility and priority 74 * by Peter da Silva. 75 * -u and -v by Harlan Stenn. 76 * Priority comparison code by Harlan Stenn. 77 */ 78 79 #define DEFUPRI (LOG_USER|LOG_NOTICE) 80 #define DEFSPRI (LOG_KERN|LOG_CRIT) 81 #define TIMERINTVL 30 /* interval for checking flush, mark */ 82 #define TTYMSGTIME 1 /* timeout passed to ttymsg */ 83 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */ 84 85 #include <sys/param.h> 86 #include <sys/event.h> 87 #include <sys/ioctl.h> 88 #include <sys/mman.h> 89 #include <sys/procdesc.h> 90 #include <sys/queue.h> 91 #include <sys/resource.h> 92 #include <sys/socket.h> 93 #include <sys/stat.h> 94 #include <sys/syslimits.h> 95 #include <sys/time.h> 96 #include <sys/uio.h> 97 #include <sys/un.h> 98 #include <sys/wait.h> 99 100 #if defined(INET) || defined(INET6) 101 #include <netinet/in.h> 102 #include <arpa/inet.h> 103 #endif 104 105 #include <assert.h> 106 #include <ctype.h> 107 #include <dirent.h> 108 #include <err.h> 109 #include <errno.h> 110 #include <fcntl.h> 111 #include <fnmatch.h> 112 #include <libgen.h> 113 #include <libutil.h> 114 #include <limits.h> 115 #include <netdb.h> 116 #include <paths.h> 117 #include <poll.h> 118 #include <regex.h> 119 #include <signal.h> 120 #include <stdbool.h> 121 #include <stddef.h> 122 #include <stdio.h> 123 #include <stdlib.h> 124 #include <string.h> 125 #include <sysexits.h> 126 #include <unistd.h> 127 #include <utmpx.h> 128 129 #include "pathnames.h" 130 #include "syslogd.h" 131 #include "syslogd_cap.h" 132 133 const char *ConfFile = _PATH_LOGCONF; 134 static const char *PidFile = _PATH_LOGPID; 135 static const char include_str[] = "include"; 136 static const char include_ext[] = ".conf"; 137 138 #define dprintf if (Debug) printf 139 140 #define sstosa(ss) ((struct sockaddr *)(ss)) 141 #ifdef INET 142 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss)) 143 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa)) 144 #endif 145 #ifdef INET6 146 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss)) 147 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa)) 148 #define s6_addr32 __u6_addr.__u6_addr32 149 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \ 150 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \ 151 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \ 152 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \ 153 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 ) 154 #endif 155 156 /* 157 * List of peers and sockets that can't be bound until 158 * flags have been parsed. 159 */ 160 struct peer { 161 const char *pe_name; 162 const char *pe_serv; 163 mode_t pe_mode; 164 STAILQ_ENTRY(peer) next; 165 }; 166 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue); 167 168 /* 169 * Sockets used for logging; monitored by kevent(). 170 */ 171 struct socklist { 172 struct addrinfo sl_ai; 173 #define sl_sa sl_ai.ai_addr 174 #define sl_salen sl_ai.ai_addrlen 175 #define sl_family sl_ai.ai_family 176 int sl_socket; 177 char *sl_name; 178 int sl_dirfd; 179 int (*sl_recv)(struct socklist *); 180 STAILQ_ENTRY(socklist) next; 181 }; 182 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead); 183 184 /* 185 * Flags to logmsg(). 186 */ 187 188 #define IGN_CONS 0x001 /* don't print on console */ 189 #define SYNC_FILE 0x002 /* do fsync on file after printing */ 190 #define MARK 0x008 /* this message is a mark */ 191 #define ISKERNEL 0x010 /* kernel generated message */ 192 193 /* Traditional syslog timestamp format. */ 194 #define RFC3164_DATELEN 15 195 #define RFC3164_DATEFMT "%b %e %H:%M:%S" 196 197 /* 198 * FORMAT_BSD_LEGACY and FORMAT_RFC3164_STRICT are two variations of 199 * the RFC 3164 logging format. 200 */ 201 #define IS_RFC3164_FORMAT (output_format == FORMAT_BSD_LEGACY || \ 202 output_format == FORMAT_RFC3164_STRICT) 203 204 static STAILQ_HEAD(, filed) fhead = 205 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */ 206 static struct filed consfile; /* Console */ 207 208 /* 209 * Queue of about-to-be dead processes we should watch out for. 210 */ 211 struct deadq_entry { 212 int dq_procdesc; 213 int dq_timeout; 214 TAILQ_ENTRY(deadq_entry) dq_entries; 215 }; 216 static TAILQ_HEAD(, deadq_entry) deadq_head = 217 TAILQ_HEAD_INITIALIZER(deadq_head); 218 219 /* 220 * The timeout to apply to processes waiting on the dead queue. Unit 221 * of measure is `mark intervals', i.e. 20 minutes by default. 222 * Processes on the dead queue will be terminated after that time. 223 */ 224 225 #define DQ_TIMO_INIT 2 226 227 /* 228 * Network addresses that are allowed to log to us. 229 */ 230 struct allowedpeer { 231 bool isnumeric; 232 u_short port; 233 union { 234 struct { 235 struct sockaddr_storage addr; 236 struct sockaddr_storage mask; 237 } numeric; 238 char *name; 239 } u; 240 #define a_addr u.numeric.addr 241 #define a_mask u.numeric.mask 242 #define a_name u.name 243 STAILQ_ENTRY(allowedpeer) next; 244 }; 245 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead); 246 247 /* 248 * Intervals at which we flush out "message repeated" messages, 249 * in seconds after previous message is logged. After each flush, 250 * we move to the next interval until we reach the largest. 251 */ 252 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */ 253 #define MAXREPEAT (nitems(repeatinterval) - 1) 254 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount]) 255 #define BACKOFF(f) do { \ 256 if (++(f)->f_repeatcount > MAXREPEAT) \ 257 (f)->f_repeatcount = MAXREPEAT; \ 258 } while (0) 259 260 static const char *TypeNames[] = { 261 "UNUSED", 262 "FILE", 263 "TTY", 264 "CONSOLE", 265 "FORW", 266 "USERS", 267 "WALL", 268 "PIPE", 269 }; 270 271 static const int sigcatch[] = { 272 SIGHUP, 273 SIGINT, 274 SIGQUIT, 275 SIGPIPE, 276 SIGALRM, 277 SIGTERM, 278 SIGCHLD, 279 }; 280 281 /* 282 * Communication channels between syslogd and libcasper 283 * services. These channels are used to request external 284 * resources while in capability mode. 285 */ 286 #ifdef WITH_CASPER 287 static cap_channel_t *cap_syslogd; 288 static cap_channel_t *cap_net; 289 #endif 290 291 static int nulldesc; /* /dev/null descriptor */ 292 static bool Debug; /* debug flag */ 293 static bool Foreground = false; /* Run in foreground, instead of daemonizing */ 294 static bool resolve = true; /* resolve hostname */ 295 char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */ 296 static const char *LocalDomain; /* our local domain name */ 297 static bool Initialized; /* set when we have initialized ourselves */ 298 static int MarkInterval = 20 * 60; /* interval between marks in seconds */ 299 static int MarkSeq; /* mark sequence number */ 300 static bool NoBind; /* don't bind() as suggested by RFC 3164 */ 301 static int SecureMode; /* when true, receive only unix domain socks */ 302 static int MaxForwardLen = 1024; /* max length of forwared message */ 303 #ifdef INET6 304 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */ 305 #else 306 static int family = PF_INET; /* protocol family (IPv4 only) */ 307 #endif 308 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */ 309 static int send_to_all; /* send message to all IPv4/IPv6 addresses */ 310 static int use_bootfile; /* log entire bootfile for every kern msg */ 311 static int no_compress; /* don't compress messages (1=pipes, 2=all) */ 312 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */ 313 314 static char bootfile[MAXPATHLEN]; /* booted kernel file */ 315 316 static bool RemoteAddDate; /* Always set the date on remote messages */ 317 static bool RemoteHostname; /* Log remote hostname from the message */ 318 319 static bool UniquePriority; /* Only log specified priority? */ 320 static int LogFacPri; /* Put facility and priority in log message: */ 321 /* 0=no, 1=numeric, 2=names */ 322 static bool KeepKernFac; /* Keep remotely logged kernel facility */ 323 static bool needdofsync = true; /* Are any file(s) waiting to be fsynced? */ 324 static struct pidfh *pfh; 325 static enum { 326 FORMAT_BSD_LEGACY, /* default, RFC 3164 with legacy deviations */ 327 FORMAT_RFC3164_STRICT, /* compliant to RFC 3164 recommendataions */ 328 FORMAT_RFC5424, /* RFC 5424 format */ 329 } output_format = FORMAT_BSD_LEGACY; 330 static int kq; /* kqueue(2) descriptor. */ 331 332 struct iovlist; 333 334 static bool allowaddr(char *); 335 static void addpeer(const char *, const char *, mode_t); 336 static void addsock(const char *, const char *, mode_t); 337 static void cfline(nvlist_t *, const char *, const char *, const char *, 338 const char *); 339 static const char *cvthname(struct sockaddr *); 340 static struct deadq_entry *deadq_enter(int); 341 static void deadq_remove(struct deadq_entry *); 342 static int decode(const char *, const CODE *); 343 static void die(int) __dead2; 344 static void dofsync(void); 345 static void fprintlog_first(struct filed *, const char *, const char *, 346 const char *, const char *, const char *, const char *, int); 347 static void fprintlog_write(struct filed *, struct iovlist *, int); 348 static void fprintlog_successive(struct filed *, int); 349 static void init(bool); 350 static void logmsg(int, const struct logtime *, const char *, const char *, 351 const char *, const char *, const char *, const char *, int); 352 static void log_deadchild(int, int, const struct filed *); 353 static void markit(void); 354 static struct socklist *socksetup(struct addrinfo *, const char *, mode_t); 355 static int socklist_recv_file(struct socklist *); 356 static int socklist_recv_sock(struct socklist *); 357 static int skip_message(const char *, const char *, int); 358 static int evaluate_prop_filter(const struct prop_filter *filter, 359 const char *value); 360 static nvlist_t *prop_filter_compile(const char *); 361 static void parsemsg(const char *, char *); 362 static void printsys(char *); 363 static const char *ttymsg_check(struct iovec *, int, char *, int); 364 static void usage(void); 365 static bool validate(struct sockaddr *, const char *); 366 static void unmapped(struct sockaddr *); 367 static int waitdaemon(int); 368 static void increase_rcvbuf(int); 369 370 static void 371 close_filed(struct filed *f) 372 { 373 switch (f->f_type) { 374 case F_FORW: 375 if (f->f_addr_fds != NULL) { 376 free(f->f_addrs); 377 for (size_t i = 0; i < f->f_num_addr_fds; ++i) 378 close(f->f_addr_fds[i]); 379 free(f->f_addr_fds); 380 f->f_addr_fds = NULL; 381 f->f_num_addr_fds = 0; 382 } 383 /* FALLTHROUGH */ 384 case F_FILE: 385 case F_TTY: 386 case F_CONSOLE: 387 f->f_type = F_UNUSED; 388 break; 389 case F_PIPE: 390 if (f->f_procdesc != -1) { 391 /* 392 * Close the procdesc, killing the underlying 393 * process (if it is still alive). 394 */ 395 (void)close(f->f_procdesc); 396 f->f_procdesc = -1; 397 /* 398 * The pipe process is guaranteed to be dead now, 399 * so remove it from the deadq. 400 */ 401 if (f->f_dq != NULL) { 402 deadq_remove(f->f_dq); 403 f->f_dq = NULL; 404 } 405 } 406 break; 407 default: 408 break; 409 } 410 if (f->f_file != -1) 411 (void)close(f->f_file); 412 f->f_file = -1; 413 } 414 415 static void 416 addpeer(const char *name, const char *serv, mode_t mode) 417 { 418 struct peer *pe = calloc(1, sizeof(*pe)); 419 if (pe == NULL) 420 err(1, "malloc failed"); 421 pe->pe_name = name; 422 pe->pe_serv = serv; 423 pe->pe_mode = mode; 424 STAILQ_INSERT_TAIL(&pqueue, pe, next); 425 } 426 427 static void 428 addsock(const char *name, const char *serv, mode_t mode) 429 { 430 struct addrinfo hints = { }, *res, *res0; 431 struct socklist *sl; 432 int error; 433 char *cp, *msgbuf; 434 435 /* 436 * We have to handle this case for backwards compatibility: 437 * If there are two (or more) colons but no '[' and ']', 438 * assume this is an inet6 address without a service. 439 */ 440 if (name != NULL) { 441 #ifdef INET6 442 if (name[0] == '[' && 443 (cp = strchr(name + 1, ']')) != NULL) { 444 name = &name[1]; 445 *cp = '\0'; 446 if (cp[1] == ':' && cp[2] != '\0') 447 serv = cp + 2; 448 } else { 449 #endif 450 cp = strchr(name, ':'); 451 if (cp != NULL && strchr(cp + 1, ':') == NULL) { 452 *cp = '\0'; 453 if (cp[1] != '\0') 454 serv = cp + 1; 455 if (cp == name) 456 name = NULL; 457 } 458 #ifdef INET6 459 } 460 #endif 461 } 462 hints.ai_family = AF_UNSPEC; 463 hints.ai_socktype = SOCK_DGRAM; 464 hints.ai_flags = AI_PASSIVE; 465 if (name != NULL) 466 dprintf("Trying peer: %s\n", name); 467 if (serv == NULL) 468 serv = "syslog"; 469 error = getaddrinfo(name, serv, &hints, &res0); 470 if (error == EAI_NONAME && name == NULL && SecureMode > 1) { 471 /* 472 * If we're in secure mode, we won't open inet sockets anyway. 473 * This failure can arise legitimately when running in a jail 474 * without networking. 475 */ 476 return; 477 } 478 if (error) { 479 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s", 480 name == NULL ? "" : name, serv, 481 gai_strerror(error)); 482 errno = 0; 483 if (msgbuf == NULL) 484 logerror(gai_strerror(error)); 485 else 486 logerror(msgbuf); 487 free(msgbuf); 488 die(0); 489 } 490 for (res = res0; res != NULL; res = res->ai_next) { 491 sl = socksetup(res, name, mode); 492 if (sl == NULL) 493 continue; 494 STAILQ_INSERT_TAIL(&shead, sl, next); 495 } 496 freeaddrinfo(res0); 497 } 498 499 static void 500 addfile(int fd) 501 { 502 struct socklist *sl = calloc(1, sizeof(*sl)); 503 if (sl == NULL) 504 err(1, "malloc failed"); 505 sl->sl_socket = fd; 506 sl->sl_recv = socklist_recv_file; 507 STAILQ_INSERT_TAIL(&shead, sl, next); 508 } 509 510 int 511 main(int argc, char *argv[]) 512 { 513 struct sigaction act = { }; 514 struct kevent ev; 515 struct socklist *sl; 516 pid_t spid; 517 int ch, ppipe_w = -1, s; 518 char *p; 519 bool bflag = false, pflag = false, Sflag = false; 520 521 if (madvise(NULL, 0, MADV_PROTECT) != 0) 522 dprintf("madvise() failed: %s\n", strerror(errno)); 523 524 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:M:m:nNoO:p:P:sS:Tuv")) 525 != -1) 526 switch (ch) { 527 #ifdef INET 528 case '4': 529 family = PF_INET; 530 break; 531 #endif 532 #ifdef INET6 533 case '6': 534 family = PF_INET6; 535 break; 536 #endif 537 case '8': 538 mask_C1 = 0; 539 break; 540 case 'A': 541 send_to_all = true; 542 break; 543 case 'a': /* allow specific network addresses only */ 544 if (!allowaddr(optarg)) 545 usage(); 546 break; 547 case 'b': 548 bflag = true; 549 p = strchr(optarg, ']'); 550 if (p != NULL) 551 p = strchr(p + 1, ':'); 552 else { 553 p = strchr(optarg, ':'); 554 if (p != NULL && strchr(p + 1, ':') != NULL) 555 p = NULL; /* backward compatibility */ 556 } 557 if (p == NULL) { 558 /* A hostname or filename only. */ 559 addpeer(optarg, "syslog", 0); 560 } else { 561 /* The case of "name:service". */ 562 *p++ = '\0'; 563 addpeer(strlen(optarg) == 0 ? NULL : optarg, 564 p, 0); 565 } 566 break; 567 case 'c': 568 no_compress++; 569 break; 570 case 'C': 571 logflags |= O_CREAT; 572 break; 573 case 'd': /* debug */ 574 Debug = true; 575 break; 576 case 'f': /* configuration file */ 577 ConfFile = optarg; 578 break; 579 case 'F': /* run in foreground instead of daemon */ 580 Foreground = true; 581 break; 582 case 'H': 583 RemoteHostname = true; 584 break; 585 case 'k': /* keep remote kern fac */ 586 KeepKernFac = true; 587 break; 588 case 'l': 589 case 'p': 590 case 'S': 591 { 592 long perml; 593 mode_t mode; 594 char *name, *ep; 595 596 if (ch == 'l') 597 mode = DEFFILEMODE; 598 else if (ch == 'p') { 599 mode = DEFFILEMODE; 600 pflag = true; 601 } else { 602 mode = S_IRUSR | S_IWUSR; 603 Sflag = true; 604 } 605 if (optarg[0] == '/') 606 name = optarg; 607 else if ((name = strchr(optarg, ':')) != NULL) { 608 *name++ = '\0'; 609 if (name[0] != '/') 610 errx(1, "socket name must be absolute " 611 "path"); 612 if (isdigit(*optarg)) { 613 perml = strtol(optarg, &ep, 8); 614 if (*ep || perml < 0 || 615 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO)) 616 errx(1, "invalid mode %s, exiting", 617 optarg); 618 mode = (mode_t )perml; 619 } else 620 errx(1, "invalid mode %s, exiting", 621 optarg); 622 } else 623 errx(1, "invalid filename %s, exiting", 624 optarg); 625 addpeer(name, NULL, mode); 626 break; 627 } 628 case 'M': /* max length of forwarded message */ 629 MaxForwardLen = atoi(optarg); 630 if (MaxForwardLen < 480) 631 errx(1, "minimum length limit of forwarded " 632 "messages is 480 bytes"); 633 break; 634 case 'm': /* mark interval */ 635 MarkInterval = atoi(optarg) * 60; 636 break; 637 case 'N': 638 NoBind = true; 639 if (!SecureMode) 640 SecureMode = 1; 641 break; 642 case 'n': 643 resolve = false; 644 break; 645 case 'O': 646 if (strcmp(optarg, "bsd") == 0 || 647 strcmp(optarg, "rfc3164") == 0) 648 output_format = FORMAT_BSD_LEGACY; 649 else if (strcmp(optarg, "rfc3164-strict") == 0) 650 output_format = FORMAT_RFC3164_STRICT; 651 else if (strcmp(optarg, "syslog") == 0 || 652 strcmp(optarg, "rfc5424") == 0) 653 output_format = FORMAT_RFC5424; 654 else 655 usage(); 656 break; 657 case 'o': 658 use_bootfile = true; 659 break; 660 case 'P': /* path for alt. PID */ 661 PidFile = optarg; 662 break; 663 case 's': /* no network mode */ 664 SecureMode++; 665 break; 666 case 'T': 667 RemoteAddDate = true; 668 break; 669 case 'u': /* only log specified priority */ 670 UniquePriority = true; 671 break; 672 case 'v': /* log facility and priority */ 673 LogFacPri++; 674 break; 675 default: 676 usage(); 677 } 678 if ((argc -= optind) != 0) 679 usage(); 680 681 if (IS_RFC3164_FORMAT && MaxForwardLen > 1024) 682 errx(1, "RFC 3164 messages may not exceed 1024 bytes"); 683 684 pfh = pidfile_open(PidFile, 0600, &spid); 685 if (pfh == NULL) { 686 if (errno == EEXIST) 687 errx(1, "syslogd already running, pid: %d", spid); 688 warn("cannot open pid file"); 689 } 690 691 /* 692 * Now that flags have been parsed, we know if we're in 693 * secure mode. Add peers to the socklist, if allowed. 694 */ 695 while (!STAILQ_EMPTY(&pqueue)) { 696 struct peer *pe = STAILQ_FIRST(&pqueue); 697 STAILQ_REMOVE_HEAD(&pqueue, next); 698 addsock(pe->pe_name, pe->pe_serv, pe->pe_mode); 699 free(pe); 700 } 701 /* Listen by default: /dev/klog. */ 702 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0); 703 if (s < 0) { 704 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno); 705 } else { 706 addfile(s); 707 } 708 /* Listen by default: *:514 if no -b flag. */ 709 if (bflag == 0) 710 addsock(NULL, "syslog", 0); 711 /* Listen by default: /var/run/log if no -p flag. */ 712 if (pflag == 0) 713 addsock(_PATH_LOG, NULL, DEFFILEMODE); 714 /* Listen by default: /var/run/logpriv if no -S flag. */ 715 if (Sflag == 0) 716 addsock(_PATH_LOG_PRIV, NULL, S_IRUSR | S_IWUSR); 717 718 consfile.f_type = F_CONSOLE; 719 consfile.f_file = -1; 720 (void)strlcpy(consfile.f_fname, _PATH_CONSOLE + sizeof(_PATH_DEV) - 1, 721 sizeof(consfile.f_fname)); 722 723 nulldesc = open(_PATH_DEVNULL, O_RDWR); 724 if (nulldesc == -1) { 725 warn("cannot open %s", _PATH_DEVNULL); 726 pidfile_remove(pfh); 727 exit(1); 728 } 729 730 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile)); 731 732 if (!Foreground && !Debug) 733 ppipe_w = waitdaemon(30); 734 else if (Debug) 735 setlinebuf(stdout); 736 737 kq = kqueue(); 738 if (kq == -1) { 739 warn("failed to initialize kqueue"); 740 pidfile_remove(pfh); 741 exit(1); 742 } 743 STAILQ_FOREACH(sl, &shead, next) { 744 if (sl->sl_recv == NULL) 745 continue; 746 EV_SET(&ev, sl->sl_socket, EVFILT_READ, EV_ADD, 0, 0, sl); 747 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) { 748 warn("failed to add kevent to kqueue"); 749 pidfile_remove(pfh); 750 exit(1); 751 } 752 } 753 754 /* 755 * Syslogd will not reap its children via wait(). 756 * When SIGCHLD is ignored, zombie processes are 757 * not created. A child's PID will be recycled 758 * upon its exit. 759 */ 760 act.sa_handler = SIG_IGN; 761 for (size_t i = 0; i < nitems(sigcatch); ++i) { 762 EV_SET(&ev, sigcatch[i], EVFILT_SIGNAL, EV_ADD, 0, 0, NULL); 763 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) { 764 warn("failed to add kevent to kqueue"); 765 pidfile_remove(pfh); 766 exit(1); 767 } 768 if (sigaction(sigcatch[i], &act, NULL) == -1) { 769 warn("failed to apply signal handler"); 770 pidfile_remove(pfh); 771 exit(1); 772 } 773 } 774 (void)alarm(TIMERINTVL); 775 776 /* tuck my process id away */ 777 pidfile_write(pfh); 778 779 dprintf("off & running....\n"); 780 init(false); 781 for (;;) { 782 if (needdofsync) { 783 dofsync(); 784 if (ppipe_w != -1) { 785 /* 786 * Close our end of the pipe so our 787 * parent knows that we have finished 788 * initialization. 789 */ 790 (void)close(ppipe_w); 791 ppipe_w = -1; 792 } 793 } 794 if (kevent(kq, NULL, 0, &ev, 1, NULL) == -1) { 795 if (errno != EINTR) 796 logerror("kevent"); 797 continue; 798 } 799 switch (ev.filter) { 800 case EVFILT_READ: 801 sl = ev.udata; 802 if (sl->sl_socket != -1 && sl->sl_recv != NULL) 803 sl->sl_recv(sl); 804 break; 805 case EVFILT_SIGNAL: 806 switch (ev.ident) { 807 case SIGHUP: 808 init(true); 809 break; 810 case SIGINT: 811 case SIGQUIT: 812 case SIGTERM: 813 if (ev.ident == SIGTERM || Debug) 814 die(ev.ident); 815 break; 816 case SIGALRM: 817 markit(); 818 break; 819 } 820 break; 821 case EVFILT_PROCDESC: 822 if ((ev.fflags & NOTE_EXIT) != 0) { 823 log_deadchild(ev.ident, ev.data, ev.udata); 824 close_filed(ev.udata); 825 } 826 break; 827 } 828 } 829 } 830 831 static int 832 socklist_recv_sock(struct socklist *sl) 833 { 834 struct sockaddr_storage ss; 835 struct sockaddr *sa = (struct sockaddr *)&ss; 836 socklen_t sslen; 837 const char *hname; 838 char line[MAXLINE + 1]; 839 int len; 840 841 sslen = sizeof(ss); 842 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen); 843 dprintf("received sa_len = %d\n", sslen); 844 if (len == 0) 845 return (-1); 846 if (len < 0) { 847 if (errno != EINTR) 848 logerror("recvfrom"); 849 return (-1); 850 } 851 /* Received valid data. */ 852 line[len] = '\0'; 853 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL) 854 hname = LocalHostName; 855 else { 856 hname = cvthname(sa); 857 unmapped(sa); 858 if (validate(sa, hname) == 0) { 859 dprintf("Message from %s was ignored.", hname); 860 return (-1); 861 } 862 } 863 parsemsg(hname, line); 864 865 return (0); 866 } 867 868 static void 869 unmapped(struct sockaddr *sa) 870 { 871 #if defined(INET) && defined(INET6) 872 struct sockaddr_in6 *sin6; 873 struct sockaddr_in sin; 874 875 if (sa == NULL || 876 sa->sa_family != AF_INET6 || 877 sa->sa_len != sizeof(*sin6)) 878 return; 879 sin6 = satosin6(sa); 880 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) 881 return; 882 sin = (struct sockaddr_in){ 883 .sin_family = AF_INET, 884 .sin_len = sizeof(sin), 885 .sin_port = sin6->sin6_port 886 }; 887 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12], 888 sizeof(sin.sin_addr)); 889 memcpy(sa, &sin, sizeof(sin)); 890 #else 891 if (sa == NULL) 892 return; 893 #endif 894 } 895 896 static void 897 usage(void) 898 { 899 900 fprintf(stderr, 901 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n" 902 " [-b bind_address] [-f config_file]\n" 903 " [-l [mode:]path] [-M fwd_length]\n" 904 " [-m mark_interval] [-O format] [-P pid_file]\n" 905 " [-p log_socket] [-S logpriv_socket]\n"); 906 exit(1); 907 } 908 909 /* 910 * Removes characters from log messages that are unsafe to display. 911 * TODO: Permit UTF-8 strings that include a BOM per RFC 5424? 912 */ 913 static void 914 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen) 915 { 916 char *q; 917 int c; 918 919 q = out; 920 while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) { 921 if (mask_C1 && (c & 0x80) && c < 0xA0) { 922 c &= 0x7F; 923 *q++ = 'M'; 924 *q++ = '-'; 925 } 926 if (isascii(c) && iscntrl(c)) { 927 if (c == '\n') { 928 *q++ = ' '; 929 } else if (c == '\t') { 930 *q++ = '\t'; 931 } else { 932 *q++ = '^'; 933 *q++ = c ^ 0100; 934 } 935 } else { 936 *q++ = c; 937 } 938 } 939 *q = '\0'; 940 } 941 942 /* 943 * Parses a syslog message according to RFC 5424, assuming that PRI and 944 * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The 945 * parsed result is passed to logmsg(). 946 */ 947 static void 948 parsemsg_rfc5424(const char *from, int pri, char *msg) 949 { 950 const struct logtime *timestamp; 951 struct logtime timestamp_remote; 952 const char *omsg, *hostname, *app_name, *procid, *msgid, 953 *structured_data; 954 char line[MAXLINE + 1]; 955 956 #define FAIL_IF(field, expr) do { \ 957 if (expr) { \ 958 dprintf("Failed to parse " field " from %s: %s\n", \ 959 from, omsg); \ 960 return; \ 961 } \ 962 } while (0) 963 #define PARSE_CHAR(field, sep) do { \ 964 FAIL_IF(field, *msg != sep); \ 965 ++msg; \ 966 } while (0) 967 #define IF_NOT_NILVALUE(var) \ 968 if (msg[0] == '-' && msg[1] == ' ') { \ 969 msg += 2; \ 970 var = NULL; \ 971 } else if (msg[0] == '-' && msg[1] == '\0') { \ 972 ++msg; \ 973 var = NULL; \ 974 } else 975 976 omsg = msg; 977 IF_NOT_NILVALUE(timestamp) { 978 /* Parse RFC 3339-like timestamp. */ 979 #define PARSE_NUMBER(dest, length, min, max) do { \ 980 int i, v; \ 981 \ 982 v = 0; \ 983 for (i = 0; i < length; ++i) { \ 984 FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9'); \ 985 v = v * 10 + *msg++ - '0'; \ 986 } \ 987 FAIL_IF("TIMESTAMP", v < min || v > max); \ 988 dest = v; \ 989 } while (0) 990 /* Date and time. */ 991 memset(×tamp_remote, 0, sizeof(timestamp_remote)); 992 PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999); 993 timestamp_remote.tm.tm_year -= 1900; 994 PARSE_CHAR("TIMESTAMP", '-'); 995 PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12); 996 --timestamp_remote.tm.tm_mon; 997 PARSE_CHAR("TIMESTAMP", '-'); 998 PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31); 999 PARSE_CHAR("TIMESTAMP", 'T'); 1000 PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23); 1001 PARSE_CHAR("TIMESTAMP", ':'); 1002 PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59); 1003 PARSE_CHAR("TIMESTAMP", ':'); 1004 PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59); 1005 /* Perform normalization. */ 1006 timegm(×tamp_remote.tm); 1007 /* Optional: fractional seconds. */ 1008 if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') { 1009 int i; 1010 1011 ++msg; 1012 for (i = 100000; i != 0; i /= 10) { 1013 if (*msg < '0' || *msg > '9') 1014 break; 1015 timestamp_remote.usec += (*msg++ - '0') * i; 1016 } 1017 } 1018 /* Timezone. */ 1019 if (*msg == 'Z') { 1020 /* UTC. */ 1021 ++msg; 1022 } else { 1023 int sign, tz_hour, tz_min; 1024 1025 /* Local time zone offset. */ 1026 FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+'); 1027 sign = *msg++ == '-' ? -1 : 1; 1028 PARSE_NUMBER(tz_hour, 2, 0, 23); 1029 PARSE_CHAR("TIMESTAMP", ':'); 1030 PARSE_NUMBER(tz_min, 2, 0, 59); 1031 timestamp_remote.tm.tm_gmtoff = 1032 sign * (tz_hour * 3600 + tz_min * 60); 1033 } 1034 #undef PARSE_NUMBER 1035 PARSE_CHAR("TIMESTAMP", ' '); 1036 timestamp = RemoteAddDate ? NULL : ×tamp_remote; 1037 } 1038 1039 /* String fields part of the HEADER. */ 1040 #define PARSE_STRING(field, var) \ 1041 IF_NOT_NILVALUE(var) { \ 1042 var = msg; \ 1043 while (*msg >= '!' && *msg <= '~') \ 1044 ++msg; \ 1045 FAIL_IF(field, var == msg); \ 1046 PARSE_CHAR(field, ' '); \ 1047 msg[-1] = '\0'; \ 1048 } 1049 PARSE_STRING("HOSTNAME", hostname); 1050 if (hostname == NULL || !RemoteHostname) 1051 hostname = from; 1052 PARSE_STRING("APP-NAME", app_name); 1053 PARSE_STRING("PROCID", procid); 1054 PARSE_STRING("MSGID", msgid); 1055 #undef PARSE_STRING 1056 1057 /* Structured data. */ 1058 #define PARSE_SD_NAME() do { \ 1059 const char *start; \ 1060 \ 1061 start = msg; \ 1062 while (*msg >= '!' && *msg <= '~' && *msg != '=' && \ 1063 *msg != ']' && *msg != '"') \ 1064 ++msg; \ 1065 FAIL_IF("STRUCTURED-NAME", start == msg); \ 1066 } while (0) 1067 IF_NOT_NILVALUE(structured_data) { 1068 structured_data = msg; 1069 /* SD-ELEMENT. */ 1070 while (*msg == '[') { 1071 ++msg; 1072 /* SD-ID. */ 1073 PARSE_SD_NAME(); 1074 /* SD-PARAM. */ 1075 while (*msg == ' ') { 1076 ++msg; 1077 /* PARAM-NAME. */ 1078 PARSE_SD_NAME(); 1079 PARSE_CHAR("STRUCTURED-NAME", '='); 1080 PARSE_CHAR("STRUCTURED-NAME", '"'); 1081 while (*msg != '"') { 1082 FAIL_IF("STRUCTURED-NAME", 1083 *msg == '\0'); 1084 if (*msg++ == '\\') { 1085 FAIL_IF("STRUCTURED-NAME", 1086 *msg == '\0'); 1087 ++msg; 1088 } 1089 } 1090 ++msg; 1091 } 1092 PARSE_CHAR("STRUCTURED-NAME", ']'); 1093 } 1094 PARSE_CHAR("STRUCTURED-NAME", ' '); 1095 msg[-1] = '\0'; 1096 } 1097 #undef PARSE_SD_NAME 1098 1099 #undef FAIL_IF 1100 #undef PARSE_CHAR 1101 #undef IF_NOT_NILVALUE 1102 1103 parsemsg_remove_unsafe_characters(msg, line, sizeof(line)); 1104 logmsg(pri, timestamp, hostname, app_name, procid, msgid, 1105 structured_data, line, 0); 1106 } 1107 1108 /* 1109 * Returns the length of the application name ("TAG" in RFC 3164 1110 * terminology) and process ID from a message if present. 1111 */ 1112 static void 1113 parsemsg_rfc3164_get_app_name_procid(const char *msg, size_t *app_name_length_p, 1114 ptrdiff_t *procid_begin_offset_p, size_t *procid_length_p) 1115 { 1116 const char *m, *procid_begin; 1117 size_t app_name_length, procid_length; 1118 1119 m = msg; 1120 1121 /* Application name. */ 1122 app_name_length = strspn(m, 1123 "abcdefghijklmnopqrstuvwxyz" 1124 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 1125 "0123456789" 1126 "_-/"); 1127 if (app_name_length == 0) 1128 goto bad; 1129 m += app_name_length; 1130 1131 /* Process identifier (optional). */ 1132 if (*m == '[') { 1133 procid_begin = ++m; 1134 procid_length = strspn(m, "0123456789"); 1135 if (procid_length == 0) 1136 goto bad; 1137 m += procid_length; 1138 if (*m++ != ']') 1139 goto bad; 1140 } else { 1141 procid_begin = NULL; 1142 procid_length = 0; 1143 } 1144 1145 /* Separator. */ 1146 if (m[0] != ':' || m[1] != ' ') 1147 goto bad; 1148 1149 *app_name_length_p = app_name_length; 1150 if (procid_begin_offset_p != NULL) 1151 *procid_begin_offset_p = 1152 procid_begin == NULL ? 0 : procid_begin - msg; 1153 if (procid_length_p != NULL) 1154 *procid_length_p = procid_length; 1155 return; 1156 bad: 1157 *app_name_length_p = 0; 1158 if (procid_begin_offset_p != NULL) 1159 *procid_begin_offset_p = 0; 1160 if (procid_length_p != NULL) 1161 *procid_length_p = 0; 1162 } 1163 1164 /* 1165 * Trims the application name ("TAG" in RFC 3164 terminology) and 1166 * process ID from a message if present. 1167 */ 1168 static void 1169 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name, 1170 const char **procid) 1171 { 1172 char *m, *app_name_begin, *procid_begin; 1173 size_t app_name_length, procid_length; 1174 ptrdiff_t procid_begin_offset; 1175 1176 m = *msg; 1177 app_name_begin = m; 1178 1179 parsemsg_rfc3164_get_app_name_procid(app_name_begin, &app_name_length, 1180 &procid_begin_offset, &procid_length); 1181 if (app_name_length == 0) 1182 goto bad; 1183 procid_begin = procid_begin_offset == 0 ? NULL : 1184 app_name_begin + procid_begin_offset; 1185 1186 /* Split strings from input. */ 1187 app_name_begin[app_name_length] = '\0'; 1188 m += app_name_length; 1189 if (procid_begin != NULL) { 1190 procid_begin[procid_length] = '\0'; 1191 /* Skip "[PID]". */ 1192 m += procid_length + 2; 1193 } 1194 1195 /* Skip separator ": ". */ 1196 *msg = m + 2; 1197 *app_name = app_name_begin; 1198 *procid = procid_begin; 1199 return; 1200 bad: 1201 *app_name = NULL; 1202 *procid = NULL; 1203 } 1204 1205 /* 1206 * Parses a syslog message according to RFC 3164, assuming that PRI 1207 * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed 1208 * result is passed to logmsg(). 1209 */ 1210 static void 1211 parsemsg_rfc3164(const char *from, int pri, char *msg) 1212 { 1213 struct tm tm_parsed; 1214 const struct logtime *timestamp; 1215 struct logtime timestamp_remote; 1216 const char *app_name, *procid; 1217 size_t i, msglen; 1218 char line[MAXLINE + 1]; 1219 1220 /* 1221 * Parse the TIMESTAMP provided by the remote side. If none is 1222 * found, assume this is not an RFC 3164 formatted message, 1223 * only containing a TAG and a MSG. 1224 */ 1225 timestamp = NULL; 1226 if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) == 1227 msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') { 1228 msg += RFC3164_DATELEN + 1; 1229 if (!RemoteAddDate) { 1230 struct tm tm_now; 1231 time_t t_now; 1232 int year; 1233 1234 /* 1235 * As the timestamp does not contain the year 1236 * number, daylight saving time information, nor 1237 * a time zone, attempt to infer it. Due to 1238 * clock skews, the timestamp may even be part 1239 * of the next year. Use the last year for which 1240 * the timestamp is at most one week in the 1241 * future. 1242 * 1243 * This loop can only run for at most three 1244 * iterations before terminating. 1245 */ 1246 t_now = time(NULL); 1247 localtime_r(&t_now, &tm_now); 1248 for (year = tm_now.tm_year + 1;; --year) { 1249 assert(year >= tm_now.tm_year - 1); 1250 timestamp_remote.tm = tm_parsed; 1251 timestamp_remote.tm.tm_year = year; 1252 timestamp_remote.tm.tm_isdst = -1; 1253 timestamp_remote.usec = 0; 1254 if (mktime(×tamp_remote.tm) < 1255 t_now + 7 * 24 * 60 * 60) 1256 break; 1257 } 1258 timestamp = ×tamp_remote; 1259 } 1260 1261 /* 1262 * A single space character MUST also follow the HOSTNAME field. 1263 */ 1264 msglen = strlen(msg); 1265 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) { 1266 if (msg[i] == ' ') { 1267 if (RemoteHostname) { 1268 msg[i] = '\0'; 1269 from = msg; 1270 } 1271 msg += i + 1; 1272 break; 1273 } 1274 /* 1275 * Support non RFC compliant messages, without hostname. 1276 */ 1277 if (msg[i] == ':') 1278 break; 1279 } 1280 if (i == MIN(MAXHOSTNAMELEN, msglen)) { 1281 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg); 1282 return; 1283 } 1284 } 1285 1286 /* Remove the TAG, if present. */ 1287 parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid); 1288 parsemsg_remove_unsafe_characters(msg, line, sizeof(line)); 1289 logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0); 1290 } 1291 1292 /* 1293 * Takes a raw input line, extracts PRI and determines whether the 1294 * message is formatted according to RFC 3164 or RFC 5424. Continues 1295 * parsing of addition fields in the message according to those 1296 * standards and prints the message on the appropriate log files. 1297 */ 1298 static void 1299 parsemsg(const char *from, char *msg) 1300 { 1301 char *q; 1302 long n; 1303 size_t i; 1304 int pri; 1305 1306 i = -1; 1307 pri = DEFUPRI; 1308 1309 /* Parse PRI. */ 1310 if (msg[0] == '<' && isdigit(msg[1])) { 1311 for (i = 2; i <= 4; i++) { 1312 if (msg[i] == '>') { 1313 errno = 0; 1314 n = strtol(msg + 1, &q, 10); 1315 if (errno == 0 && *q == msg[i] && n >= 0 && n <= INT_MAX) { 1316 pri = n; 1317 msg += i + 1; 1318 i = 0; 1319 } 1320 break; 1321 } 1322 } 1323 } 1324 1325 if (pri &~ (LOG_FACMASK|LOG_PRIMASK)) 1326 pri = DEFUPRI; 1327 1328 /* 1329 * Don't allow users to log kernel messages. 1330 * NOTE: since LOG_KERN == 0 this will also match 1331 * messages with no facility specified. 1332 */ 1333 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac) 1334 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri)); 1335 1336 /* Parse VERSION. */ 1337 if (i == 0 && msg[0] == '1' && msg[1] == ' ') 1338 parsemsg_rfc5424(from, pri, msg + 2); 1339 else 1340 parsemsg_rfc3164(from, pri, msg); 1341 } 1342 1343 /* 1344 * Read /dev/klog while data are available, split into lines. 1345 */ 1346 static int 1347 socklist_recv_file(struct socklist *sl) 1348 { 1349 char *p, *q, line[MAXLINE + 1]; 1350 int len, i; 1351 1352 len = 0; 1353 for (;;) { 1354 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len); 1355 if (i > 0) { 1356 line[i + len] = '\0'; 1357 } else { 1358 if (i < 0 && errno != EINTR && errno != EAGAIN) { 1359 logerror("klog"); 1360 close(sl->sl_socket); 1361 sl->sl_socket = -1; 1362 } 1363 break; 1364 } 1365 1366 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) { 1367 *q = '\0'; 1368 printsys(p); 1369 } 1370 len = strlen(p); 1371 if (len >= MAXLINE - 1) { 1372 printsys(p); 1373 len = 0; 1374 } 1375 if (len > 0) 1376 memmove(line, p, len + 1); 1377 } 1378 if (len > 0) 1379 printsys(line); 1380 1381 return (len); 1382 } 1383 1384 /* 1385 * Take a raw input line from /dev/klog, format similar to syslog(). 1386 */ 1387 static void 1388 printsys(char *msg) 1389 { 1390 char *p, *q; 1391 long n; 1392 int flags, isprintf, pri; 1393 1394 flags = ISKERNEL | SYNC_FILE; /* fsync after write */ 1395 p = msg; 1396 pri = DEFSPRI; 1397 isprintf = 1; 1398 if (*p == '<') { 1399 errno = 0; 1400 n = strtol(p + 1, &q, 10); 1401 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) { 1402 p = q + 1; 1403 pri = n; 1404 isprintf = 0; 1405 } 1406 } 1407 /* 1408 * Kernel printf's and LOG_CONSOLE messages have been displayed 1409 * on the console already. 1410 */ 1411 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE) 1412 flags |= IGN_CONS; 1413 if (pri &~ (LOG_FACMASK|LOG_PRIMASK)) 1414 pri = DEFSPRI; 1415 logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags); 1416 } 1417 1418 static time_t now; 1419 1420 /* 1421 * Match a program or host name against a specification. 1422 * Return a non-0 value if the message must be ignored 1423 * based on the specification. 1424 */ 1425 static int 1426 skip_message(const char *name, const char *spec, int checkcase) 1427 { 1428 const char *s; 1429 char prev, next; 1430 int exclude = 0; 1431 /* Behaviour on explicit match */ 1432 1433 if (spec == NULL || *spec == '\0') 1434 return (0); 1435 switch (*spec) { 1436 case '-': 1437 exclude = 1; 1438 /*FALLTHROUGH*/ 1439 case '+': 1440 spec++; 1441 break; 1442 default: 1443 break; 1444 } 1445 if (checkcase) 1446 s = strstr (spec, name); 1447 else 1448 s = strcasestr (spec, name); 1449 1450 if (s != NULL) { 1451 prev = (s == spec ? ',' : *(s - 1)); 1452 next = *(s + strlen (name)); 1453 1454 if (prev == ',' && (next == '\0' || next == ',')) 1455 /* Explicit match: skip iff the spec is an 1456 exclusive one. */ 1457 return (exclude); 1458 } 1459 1460 /* No explicit match for this name: skip the message iff 1461 the spec is an inclusive one. */ 1462 return (!exclude); 1463 } 1464 1465 /* 1466 * Match some property of the message against a filter. 1467 * Return a non-0 value if the message must be ignored 1468 * based on the filter. 1469 */ 1470 static int 1471 evaluate_prop_filter(const struct prop_filter *filter, const char *value) 1472 { 1473 const char *s = NULL; 1474 const int exclude = ((filter->cmp_flags & FILT_FLAG_EXCLUDE) > 0); 1475 size_t valuelen; 1476 1477 if (value == NULL) 1478 return (-1); 1479 1480 if (filter->cmp_type == FILT_CMP_REGEX) { 1481 if (regexec(filter->pflt_re, value, 0, NULL, 0) == 0) 1482 return (exclude); 1483 else 1484 return (!exclude); 1485 } 1486 1487 valuelen = strlen(value); 1488 1489 /* a shortcut for equal with different length is always false */ 1490 if (filter->cmp_type == FILT_CMP_EQUAL && 1491 valuelen != strlen(filter->pflt_strval)) 1492 return (!exclude); 1493 1494 if (filter->cmp_flags & FILT_FLAG_ICASE) 1495 s = strcasestr(value, filter->pflt_strval); 1496 else 1497 s = strstr(value, filter->pflt_strval); 1498 1499 /* 1500 * FILT_CMP_CONTAINS true if s 1501 * FILT_CMP_STARTS true if s && s == value 1502 * FILT_CMP_EQUAL true if s && s == value && 1503 * valuelen == filter->pflt_strlen 1504 * (and length match is checked 1505 * already) 1506 */ 1507 1508 switch (filter->cmp_type) { 1509 case FILT_CMP_STARTS: 1510 case FILT_CMP_EQUAL: 1511 if (s != value) 1512 return (!exclude); 1513 /* FALLTHROUGH */ 1514 case FILT_CMP_CONTAINS: 1515 if (s) 1516 return (exclude); 1517 else 1518 return (!exclude); 1519 break; 1520 default: 1521 /* unknown cmp_type */ 1522 break; 1523 } 1524 1525 return (-1); 1526 } 1527 1528 /* 1529 * Logs a message to the appropriate log files, users, etc. based on the 1530 * priority. Log messages are formatted according to RFC 3164 or 1531 * RFC 5424 in subsequent fprintlog_*() functions. 1532 */ 1533 static void 1534 logmsg(int pri, const struct logtime *timestamp, const char *hostname, 1535 const char *app_name, const char *procid, const char *msgid, 1536 const char *structured_data, const char *msg, int flags) 1537 { 1538 struct timeval tv; 1539 struct logtime timestamp_now; 1540 struct filed *f; 1541 size_t savedlen; 1542 int fac, prilev; 1543 char saved[MAXSVLINE], kernel_app_name[100]; 1544 1545 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n", 1546 pri, flags, hostname, msg); 1547 1548 (void)gettimeofday(&tv, NULL); 1549 now = tv.tv_sec; 1550 if (timestamp == NULL) { 1551 localtime_r(&now, ×tamp_now.tm); 1552 timestamp_now.usec = tv.tv_usec; 1553 timestamp = ×tamp_now; 1554 } 1555 1556 /* extract facility and priority level */ 1557 if (flags & MARK) 1558 fac = LOG_NFACILITIES; 1559 else 1560 fac = LOG_FAC(pri); 1561 1562 /* Check maximum facility number. */ 1563 if (fac > LOG_NFACILITIES) 1564 return; 1565 1566 prilev = LOG_PRI(pri); 1567 1568 /* 1569 * Lookup kernel app name from log prefix if present. 1570 * This is only used for local program specification matching. 1571 */ 1572 if (flags & ISKERNEL) { 1573 size_t kernel_app_name_length; 1574 1575 parsemsg_rfc3164_get_app_name_procid(msg, 1576 &kernel_app_name_length, NULL, NULL); 1577 if (kernel_app_name_length != 0) { 1578 strlcpy(kernel_app_name, msg, 1579 MIN(sizeof(kernel_app_name), 1580 kernel_app_name_length + 1)); 1581 } else 1582 kernel_app_name[0] = '\0'; 1583 } 1584 1585 /* log the message to the particular outputs */ 1586 if (!Initialized) { 1587 consfile.f_lasttime = *timestamp; 1588 fprintlog_first(&consfile, hostname, app_name, procid, 1589 msgid, structured_data, msg, flags); 1590 return; 1591 } 1592 1593 /* 1594 * Store all of the fields of the message, except the timestamp, 1595 * in a single string. This string is used to detect duplicate 1596 * messages. 1597 */ 1598 assert(hostname != NULL); 1599 assert(msg != NULL); 1600 savedlen = snprintf(saved, sizeof(saved), 1601 "%d %s %s %s %s %s %s", pri, hostname, 1602 app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid, 1603 msgid == NULL ? "-" : msgid, 1604 structured_data == NULL ? "-" : structured_data, msg); 1605 1606 STAILQ_FOREACH(f, &fhead, next) { 1607 /* skip messages that are incorrect priority */ 1608 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev)) 1609 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev)) 1610 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev)) 1611 ) 1612 || f->f_pmask[fac] == INTERNAL_NOPRI) 1613 continue; 1614 1615 /* skip messages with the incorrect hostname */ 1616 if (skip_message(hostname, f->f_host, 0)) 1617 continue; 1618 1619 /* skip messages with the incorrect program name */ 1620 if (flags & ISKERNEL && kernel_app_name[0] != '\0') { 1621 if (skip_message(kernel_app_name, f->f_program, 1)) 1622 continue; 1623 } else if (skip_message(app_name == NULL ? "" : app_name, 1624 f->f_program, 1)) 1625 continue; 1626 1627 /* skip messages if a property does not match filter */ 1628 if (f->f_prop_filter != NULL && 1629 f->f_prop_filter->prop_type != FILT_PROP_NOOP) { 1630 switch (f->f_prop_filter->prop_type) { 1631 case FILT_PROP_MSG: 1632 if (evaluate_prop_filter(f->f_prop_filter, 1633 msg)) 1634 continue; 1635 break; 1636 case FILT_PROP_HOSTNAME: 1637 if (evaluate_prop_filter(f->f_prop_filter, 1638 hostname)) 1639 continue; 1640 break; 1641 case FILT_PROP_PROGNAME: 1642 if (evaluate_prop_filter(f->f_prop_filter, 1643 app_name == NULL ? "" : app_name)) 1644 continue; 1645 break; 1646 default: 1647 continue; 1648 } 1649 } 1650 1651 /* skip message to console if it has already been printed */ 1652 if (f->f_type == F_CONSOLE && (flags & IGN_CONS)) 1653 continue; 1654 1655 /* don't output marks to recently written files */ 1656 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2) 1657 continue; 1658 1659 /* 1660 * suppress duplicate lines to this file 1661 */ 1662 if (no_compress - (f->f_type != F_PIPE) < 1 && 1663 (flags & MARK) == 0 && savedlen == f->f_prevlen && 1664 strcmp(saved, f->f_prevline) == 0) { 1665 f->f_lasttime = *timestamp; 1666 f->f_prevcount++; 1667 dprintf("msg repeated %d times, %ld sec of %d\n", 1668 f->f_prevcount, (long)(now - f->f_time), 1669 repeatinterval[f->f_repeatcount]); 1670 /* 1671 * If domark would have logged this by now, 1672 * flush it now (so we don't hold isolated messages), 1673 * but back off so we'll flush less often 1674 * in the future. 1675 */ 1676 if (now > REPEATTIME(f)) { 1677 fprintlog_successive(f, flags); 1678 BACKOFF(f); 1679 } 1680 } else { 1681 /* new line, save it */ 1682 if (f->f_prevcount) 1683 fprintlog_successive(f, 0); 1684 f->f_repeatcount = 0; 1685 f->f_prevpri = pri; 1686 f->f_lasttime = *timestamp; 1687 static_assert(sizeof(f->f_prevline) == sizeof(saved), 1688 "Space to store saved line incorrect"); 1689 (void)strcpy(f->f_prevline, saved); 1690 f->f_prevlen = savedlen; 1691 fprintlog_first(f, hostname, app_name, procid, msgid, 1692 structured_data, msg, flags); 1693 } 1694 } 1695 } 1696 1697 static void 1698 dofsync(void) 1699 { 1700 struct filed *f; 1701 1702 STAILQ_FOREACH(f, &fhead, next) { 1703 if (f->f_type == F_FILE && 1704 (f->f_flags & FFLAG_NEEDSYNC) != 0) { 1705 f->f_flags &= ~FFLAG_NEEDSYNC; 1706 (void)fsync(f->f_file); 1707 } 1708 } 1709 needdofsync = false; 1710 } 1711 1712 static void 1713 iovlist_init(struct iovlist *il) 1714 { 1715 1716 il->iovcnt = 0; 1717 il->totalsize = 0; 1718 } 1719 1720 static void 1721 iovlist_append(struct iovlist *il, const char *str) 1722 { 1723 size_t size; 1724 1725 /* Discard components if we've run out of iovecs. */ 1726 if (il->iovcnt < nitems(il->iov)) { 1727 size = strlen(str); 1728 il->iov[il->iovcnt++] = (struct iovec){ 1729 .iov_base = __DECONST(char *, str), 1730 .iov_len = size, 1731 }; 1732 il->totalsize += size; 1733 } 1734 } 1735 1736 #if defined(INET) || defined(INET6) 1737 static void 1738 iovlist_truncate(struct iovlist *il, size_t size) 1739 { 1740 struct iovec *last; 1741 size_t diff; 1742 1743 while (il->totalsize > size) { 1744 diff = il->totalsize - size; 1745 last = &il->iov[il->iovcnt - 1]; 1746 if (diff >= last->iov_len) { 1747 /* Remove the last iovec entirely. */ 1748 --il->iovcnt; 1749 il->totalsize -= last->iov_len; 1750 } else { 1751 /* Remove the last iovec partially. */ 1752 last->iov_len -= diff; 1753 il->totalsize -= diff; 1754 } 1755 } 1756 } 1757 #endif 1758 1759 static void 1760 fprintlog_write(struct filed *f, struct iovlist *il, int flags) 1761 { 1762 const char *msgret; 1763 1764 switch (f->f_type) { 1765 case F_FORW: { 1766 ssize_t lsent; 1767 1768 if (Debug) { 1769 int domain, sockfd = f->f_addr_fds[0]; 1770 socklen_t len = sizeof(domain); 1771 1772 if (getsockopt(sockfd, SOL_SOCKET, SO_DOMAIN, 1773 &domain, &len) < 0) 1774 err(1, "getsockopt"); 1775 1776 printf(" %s", f->f_hname); 1777 switch (domain) { 1778 #ifdef INET 1779 case AF_INET: { 1780 struct sockaddr_in sin; 1781 1782 len = sizeof(sin); 1783 if (getpeername(sockfd, 1784 (struct sockaddr *)&sin, &len) < 0) 1785 err(1, "getpeername"); 1786 printf(":%d\n", ntohs(sin.sin_port)); 1787 break; 1788 } 1789 #endif 1790 #ifdef INET6 1791 case AF_INET6: { 1792 struct sockaddr_in6 sin6; 1793 1794 len = sizeof(sin6); 1795 if (getpeername(sockfd, 1796 (struct sockaddr *)&sin6, &len) < 0) 1797 err(1, "getpeername"); 1798 printf(":%d\n", ntohs(sin6.sin6_port)); 1799 break; 1800 } 1801 #endif 1802 default: 1803 printf("\n"); 1804 } 1805 } 1806 1807 #if defined(INET) || defined(INET6) 1808 /* Truncate messages to maximum forward length. */ 1809 iovlist_truncate(il, MaxForwardLen); 1810 #endif 1811 1812 lsent = 0; 1813 for (size_t i = 0; i < f->f_num_addr_fds; ++i) { 1814 struct msghdr msg = { 1815 .msg_iov = il->iov, 1816 .msg_iovlen = il->iovcnt, 1817 }; 1818 1819 lsent = sendmsg(f->f_addr_fds[i], &msg, 0); 1820 if (lsent == (ssize_t)il->totalsize && !send_to_all) 1821 break; 1822 } 1823 dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize); 1824 if (lsent != (ssize_t)il->totalsize) { 1825 int e = errno; 1826 logerror("sendto"); 1827 errno = e; 1828 switch (errno) { 1829 case ENOBUFS: 1830 case ENETDOWN: 1831 case ENETUNREACH: 1832 case EHOSTUNREACH: 1833 case EHOSTDOWN: 1834 case EADDRNOTAVAIL: 1835 case EAGAIN: 1836 case ECONNREFUSED: 1837 break; 1838 /* case EBADF: */ 1839 /* case EACCES: */ 1840 /* case ENOTSOCK: */ 1841 /* case EFAULT: */ 1842 /* case EMSGSIZE: */ 1843 default: 1844 dprintf("removing entry: errno=%d\n", e); 1845 f->f_type = F_UNUSED; 1846 break; 1847 } 1848 } 1849 break; 1850 } 1851 1852 case F_FILE: 1853 dprintf(" %s\n", f->f_fname); 1854 iovlist_append(il, "\n"); 1855 if (writev(f->f_file, il->iov, il->iovcnt) < 0) { 1856 /* 1857 * If writev(2) fails for potentially transient errors 1858 * like the filesystem being full, ignore it. 1859 * Otherwise remove this logfile from the list. 1860 */ 1861 if (errno != ENOSPC) { 1862 int e = errno; 1863 close_filed(f); 1864 errno = e; 1865 logerror(f->f_fname); 1866 } 1867 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) { 1868 f->f_flags |= FFLAG_NEEDSYNC; 1869 needdofsync = true; 1870 } 1871 break; 1872 1873 case F_PIPE: 1874 dprintf(" %s\n", f->f_pname); 1875 iovlist_append(il, "\n"); 1876 if (f->f_procdesc == -1) { 1877 struct kevent ev; 1878 struct filed *f_in_list; 1879 size_t i = 0; 1880 1881 STAILQ_FOREACH(f_in_list, &fhead, next) { 1882 if (f_in_list == f) 1883 break; 1884 ++i; 1885 } 1886 f->f_file = cap_p_open(cap_syslogd, i, f->f_pname, 1887 &f->f_procdesc); 1888 if (f->f_file < 0) { 1889 logerror(f->f_pname); 1890 break; 1891 } 1892 EV_SET(&ev, f->f_procdesc, EVFILT_PROCDESC, EV_ADD, 1893 NOTE_EXIT, 0, f); 1894 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) { 1895 logerror("failed to add procdesc kevent"); 1896 exit(1); 1897 } 1898 } 1899 if (writev(f->f_file, il->iov, il->iovcnt) < 0) { 1900 logerror(f->f_pname); 1901 f->f_dq = deadq_enter(f->f_procdesc); 1902 } 1903 break; 1904 1905 case F_CONSOLE: 1906 if (flags & IGN_CONS) { 1907 dprintf(" (ignored)\n"); 1908 break; 1909 } 1910 /* FALLTHROUGH */ 1911 1912 case F_TTY: 1913 dprintf(" %s%s\n", _PATH_DEV, f->f_fname); 1914 iovlist_append(il, "\r\n"); 1915 errno = 0; /* ttymsg() only sometimes returns an errno */ 1916 if ((msgret = cap_ttymsg(cap_syslogd, il->iov, il->iovcnt, 1917 f->f_fname, 10))) { 1918 f->f_type = F_UNUSED; 1919 logerror(msgret); 1920 } 1921 break; 1922 1923 case F_USERS: 1924 case F_WALL: 1925 dprintf("\n"); 1926 iovlist_append(il, "\r\n"); 1927 cap_wallmsg(cap_syslogd, f, il->iov, il->iovcnt); 1928 break; 1929 default: 1930 break; 1931 } 1932 } 1933 1934 static void 1935 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name, 1936 const char *procid, const char *msgid, const char *structured_data, 1937 const char *msg, int flags) 1938 { 1939 struct iovlist il; 1940 suseconds_t usec; 1941 int i; 1942 char timebuf[33], priority_number[5]; 1943 1944 iovlist_init(&il); 1945 if (f->f_type == F_WALL) 1946 iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n"); 1947 iovlist_append(&il, "<"); 1948 snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri); 1949 iovlist_append(&il, priority_number); 1950 iovlist_append(&il, ">1 "); 1951 if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z", 1952 &f->f_lasttime.tm) == sizeof(timebuf) - 2) { 1953 /* Add colon to the time zone offset, which %z doesn't do. */ 1954 timebuf[32] = '\0'; 1955 timebuf[31] = timebuf[30]; 1956 timebuf[30] = timebuf[29]; 1957 timebuf[29] = ':'; 1958 1959 /* Overwrite space for microseconds with actual value. */ 1960 usec = f->f_lasttime.usec; 1961 for (i = 25; i >= 20; --i) { 1962 timebuf[i] = usec % 10 + '0'; 1963 usec /= 10; 1964 } 1965 iovlist_append(&il, timebuf); 1966 } else 1967 iovlist_append(&il, "-"); 1968 iovlist_append(&il, " "); 1969 iovlist_append(&il, hostname); 1970 iovlist_append(&il, " "); 1971 iovlist_append(&il, app_name == NULL ? "-" : app_name); 1972 iovlist_append(&il, " "); 1973 iovlist_append(&il, procid == NULL ? "-" : procid); 1974 iovlist_append(&il, " "); 1975 iovlist_append(&il, msgid == NULL ? "-" : msgid); 1976 iovlist_append(&il, " "); 1977 iovlist_append(&il, structured_data == NULL ? "-" : structured_data); 1978 iovlist_append(&il, " "); 1979 iovlist_append(&il, msg); 1980 1981 fprintlog_write(f, &il, flags); 1982 } 1983 1984 static void 1985 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name, 1986 const char *procid, const char *msg, int flags) 1987 { 1988 struct iovlist il; 1989 const CODE *c; 1990 int facility, priority; 1991 char timebuf[RFC3164_DATELEN + 1], facility_number[5], 1992 priority_number[5]; 1993 bool facility_found, priority_found; 1994 1995 if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT, 1996 &f->f_lasttime.tm) == 0) 1997 timebuf[0] = '\0'; 1998 1999 iovlist_init(&il); 2000 switch (f->f_type) { 2001 case F_FORW: 2002 /* Message forwarded over the network. */ 2003 iovlist_append(&il, "<"); 2004 snprintf(priority_number, sizeof(priority_number), "%d", 2005 f->f_prevpri); 2006 iovlist_append(&il, priority_number); 2007 iovlist_append(&il, ">"); 2008 iovlist_append(&il, timebuf); 2009 if (output_format == FORMAT_RFC3164_STRICT) { 2010 iovlist_append(&il, " "); 2011 iovlist_append(&il, hostname); 2012 } else if (strcasecmp(hostname, LocalHostName) != 0) { 2013 iovlist_append(&il, " Forwarded from "); 2014 iovlist_append(&il, hostname); 2015 iovlist_append(&il, ":"); 2016 } 2017 iovlist_append(&il, " "); 2018 break; 2019 2020 case F_WALL: 2021 /* Message written to terminals. */ 2022 iovlist_append(&il, "\r\n\aMessage from syslogd@"); 2023 iovlist_append(&il, hostname); 2024 iovlist_append(&il, " at "); 2025 iovlist_append(&il, timebuf); 2026 iovlist_append(&il, " ...\r\n"); 2027 break; 2028 2029 default: 2030 /* Message written to files. */ 2031 iovlist_append(&il, timebuf); 2032 iovlist_append(&il, " "); 2033 2034 if (LogFacPri) { 2035 iovlist_append(&il, "<"); 2036 2037 facility = f->f_prevpri & LOG_FACMASK; 2038 facility_found = false; 2039 if (LogFacPri > 1) { 2040 for (c = facilitynames; c->c_name; c++) { 2041 if (c->c_val == facility) { 2042 iovlist_append(&il, c->c_name); 2043 facility_found = true; 2044 break; 2045 } 2046 } 2047 } 2048 if (!facility_found) { 2049 snprintf(facility_number, 2050 sizeof(facility_number), "%d", 2051 LOG_FAC(facility)); 2052 iovlist_append(&il, facility_number); 2053 } 2054 2055 iovlist_append(&il, "."); 2056 2057 priority = LOG_PRI(f->f_prevpri); 2058 priority_found = false; 2059 if (LogFacPri > 1) { 2060 for (c = prioritynames; c->c_name; c++) { 2061 if (c->c_val == priority) { 2062 iovlist_append(&il, c->c_name); 2063 priority_found = true; 2064 break; 2065 } 2066 } 2067 } 2068 if (!priority_found) { 2069 snprintf(priority_number, 2070 sizeof(priority_number), "%d", priority); 2071 iovlist_append(&il, priority_number); 2072 } 2073 2074 iovlist_append(&il, "> "); 2075 } 2076 2077 iovlist_append(&il, hostname); 2078 iovlist_append(&il, " "); 2079 break; 2080 } 2081 2082 /* Message body with application name and process ID prefixed. */ 2083 if (app_name != NULL) { 2084 iovlist_append(&il, app_name); 2085 if (procid != NULL) { 2086 iovlist_append(&il, "["); 2087 iovlist_append(&il, procid); 2088 iovlist_append(&il, "]"); 2089 } 2090 iovlist_append(&il, ": "); 2091 } 2092 iovlist_append(&il, msg); 2093 2094 fprintlog_write(f, &il, flags); 2095 } 2096 2097 static void 2098 fprintlog_first(struct filed *f, const char *hostname, const char *app_name, 2099 const char *procid, const char *msgid __unused, 2100 const char *structured_data __unused, const char *msg, int flags) 2101 { 2102 2103 dprintf("Logging to %s", TypeNames[f->f_type]); 2104 f->f_time = now; 2105 f->f_prevcount = 0; 2106 if (f->f_type == F_UNUSED) { 2107 dprintf("\n"); 2108 return; 2109 } 2110 2111 if (IS_RFC3164_FORMAT) 2112 fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags); 2113 else 2114 fprintlog_rfc5424(f, hostname, app_name, procid, msgid, 2115 structured_data, msg, flags); 2116 } 2117 2118 /* 2119 * Prints a message to a log file that the previously logged message was 2120 * received multiple times. 2121 */ 2122 static void 2123 fprintlog_successive(struct filed *f, int flags) 2124 { 2125 char msg[100]; 2126 2127 assert(f->f_prevcount > 0); 2128 snprintf(msg, sizeof(msg), "last message repeated %d times", 2129 f->f_prevcount); 2130 fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg, 2131 flags); 2132 } 2133 2134 /* 2135 * WALLMSG -- Write a message to the world at large 2136 * 2137 * Write the specified message to either the entire 2138 * world, or a list of approved users. 2139 * 2140 * Note: This function is wrapped by cap_wallmsg() when Capsicum support is 2141 * enabled so ttymsg() can be called. 2142 */ 2143 void 2144 wallmsg(const struct filed *f, struct iovec *iov, const int iovlen) 2145 { 2146 static int reenter; /* avoid calling ourselves */ 2147 struct utmpx *ut; 2148 int i; 2149 const char *p; 2150 2151 if (reenter++) 2152 return; 2153 setutxent(); 2154 /* NOSTRICT */ 2155 while ((ut = getutxent()) != NULL) { 2156 if (ut->ut_type != USER_PROCESS) 2157 continue; 2158 if (f->f_type == F_WALL) { 2159 if ((p = ttymsg(iov, iovlen, ut->ut_line, 2160 TTYMSGTIME)) != NULL) 2161 dprintf("%s\n", p); 2162 continue; 2163 } 2164 /* should we send the message to this user? */ 2165 for (i = 0; i < MAXUNAMES; i++) { 2166 if (!f->f_uname[i][0]) 2167 break; 2168 if (!strcmp(f->f_uname[i], ut->ut_user)) { 2169 if ((p = ttymsg_check(iov, iovlen, ut->ut_line, 2170 TTYMSGTIME)) != NULL) 2171 dprintf("%s\n", p); 2172 break; 2173 } 2174 } 2175 } 2176 endutxent(); 2177 reenter = 0; 2178 } 2179 2180 /* 2181 * Wrapper routine for ttymsg() that checks the terminal for messages enabled. 2182 */ 2183 static const char * 2184 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout) 2185 { 2186 static char device[1024]; 2187 static char errbuf[1024]; 2188 struct stat sb; 2189 2190 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line); 2191 2192 if (stat(device, &sb) < 0) { 2193 (void) snprintf(errbuf, sizeof(errbuf), 2194 "%s: %s", device, strerror(errno)); 2195 return (errbuf); 2196 } 2197 if ((sb.st_mode & S_IWGRP) == 0) 2198 /* Messages disabled. */ 2199 return (NULL); 2200 return (ttymsg(iov, iovcnt, line, tmout)); 2201 } 2202 2203 /* 2204 * Return a printable representation of a host address. 2205 */ 2206 static const char * 2207 cvthname(struct sockaddr *f) 2208 { 2209 int error, hl; 2210 static char hname[NI_MAXHOST], ip[NI_MAXHOST]; 2211 2212 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len); 2213 error = cap_getnameinfo(cap_net, f, f->sa_len, ip, sizeof(ip), NULL, 0, 2214 NI_NUMERICHOST); 2215 if (error) { 2216 dprintf("Malformed from address %s\n", gai_strerror(error)); 2217 return ("???"); 2218 } 2219 dprintf("cvthname(%s)\n", ip); 2220 2221 if (!resolve) 2222 return (ip); 2223 2224 error = cap_getnameinfo(cap_net, f, f->sa_len, hname, sizeof(hname), 2225 NULL, 0, NI_NAMEREQD); 2226 if (error) { 2227 dprintf("Host name for your address (%s) unknown\n", ip); 2228 return (ip); 2229 } 2230 hl = strlen(hname); 2231 if (hl > 0 && hname[hl-1] == '.') 2232 hname[--hl] = '\0'; 2233 /* RFC 5424 prefers logging FQDNs. */ 2234 if (IS_RFC3164_FORMAT) 2235 trimdomain(hname, hl); 2236 return (hname); 2237 } 2238 2239 /* 2240 * Print syslogd errors some place. 2241 */ 2242 void 2243 logerror(const char *msg) 2244 { 2245 char buf[512]; 2246 static int recursed = 0; 2247 2248 /* If there's an error while trying to log an error, give up. */ 2249 if (recursed) 2250 return; 2251 recursed++; 2252 if (errno != 0) { 2253 (void)snprintf(buf, sizeof(buf), "%s: %s", msg, 2254 strerror(errno)); 2255 msg = buf; 2256 } 2257 errno = 0; 2258 dprintf("%s\n", msg); 2259 logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL, 2260 NULL, msg, 0); 2261 recursed--; 2262 } 2263 2264 static void 2265 die(int signo) 2266 { 2267 struct filed *f; 2268 struct socklist *sl; 2269 char buf[100]; 2270 2271 STAILQ_FOREACH(f, &fhead, next) { 2272 /* flush any pending output */ 2273 if (f->f_prevcount) 2274 fprintlog_successive(f, 0); 2275 /* terminate existing pipe processes */ 2276 if (f->f_type == F_PIPE) 2277 close_filed(f); 2278 } 2279 if (signo) { 2280 dprintf("syslogd: exiting on signal %d\n", signo); 2281 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo); 2282 errno = 0; 2283 logerror(buf); 2284 } 2285 STAILQ_FOREACH(sl, &shead, next) { 2286 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL) { 2287 if (unlinkat(sl->sl_dirfd, sl->sl_name, 0) == -1) { 2288 dprintf("Failed to unlink %s: %s", sl->sl_name, 2289 strerror(errno)); 2290 } 2291 } 2292 } 2293 pidfile_remove(pfh); 2294 2295 exit(1); 2296 } 2297 2298 static int 2299 configfiles(const struct dirent *dp) 2300 { 2301 const char *p; 2302 size_t ext_len; 2303 2304 if (dp->d_name[0] == '.') 2305 return (0); 2306 2307 ext_len = sizeof(include_ext) -1; 2308 2309 if (dp->d_namlen <= ext_len) 2310 return (0); 2311 2312 p = &dp->d_name[dp->d_namlen - ext_len]; 2313 if (strcmp(p, include_ext) != 0) 2314 return (0); 2315 2316 return (1); 2317 } 2318 2319 static nvlist_t * 2320 parseconfigfile(FILE *cf, bool allow_includes, nvlist_t *nvl_conf) 2321 { 2322 FILE *cf2; 2323 struct dirent **ent; 2324 char cline[LINE_MAX]; 2325 char host[MAXHOSTNAMELEN]; 2326 char prog[LINE_MAX]; 2327 char file[MAXPATHLEN]; 2328 char pfilter[LINE_MAX]; 2329 char *p, *tmp; 2330 int i, nents; 2331 size_t include_len; 2332 2333 /* 2334 * Foreach line in the conf table, open that file. 2335 */ 2336 include_len = sizeof(include_str) - 1; 2337 (void)strlcpy(host, "*", sizeof(host)); 2338 (void)strlcpy(prog, "*", sizeof(prog)); 2339 (void)strlcpy(pfilter, "*", sizeof(pfilter)); 2340 while (fgets(cline, sizeof(cline), cf) != NULL) { 2341 /* 2342 * check for end-of-section, comments, strip off trailing 2343 * spaces and newline character. #!prog is treated specially: 2344 * following lines apply only to that program. 2345 */ 2346 for (p = cline; isspace(*p); ++p) 2347 continue; 2348 if (*p == '\0') 2349 continue; 2350 if (allow_includes && 2351 strncmp(p, include_str, include_len) == 0 && 2352 isspace(p[include_len])) { 2353 p += include_len; 2354 while (isspace(*p)) 2355 p++; 2356 tmp = p; 2357 while (*tmp != '\0' && !isspace(*tmp)) 2358 tmp++; 2359 *tmp = '\0'; 2360 dprintf("Trying to include files in '%s'\n", p); 2361 nents = scandir(p, &ent, configfiles, alphasort); 2362 if (nents == -1) { 2363 dprintf("Unable to open '%s': %s\n", p, 2364 strerror(errno)); 2365 continue; 2366 } 2367 for (i = 0; i < nents; i++) { 2368 if (snprintf(file, sizeof(file), "%s/%s", p, 2369 ent[i]->d_name) >= (int)sizeof(file)) { 2370 dprintf("ignoring path too long: " 2371 "'%s/%s'\n", p, ent[i]->d_name); 2372 free(ent[i]); 2373 continue; 2374 } 2375 free(ent[i]); 2376 cf2 = fopen(file, "r"); 2377 if (cf2 == NULL) 2378 continue; 2379 dprintf("reading %s\n", file); 2380 parseconfigfile(cf2, false, nvl_conf); 2381 fclose(cf2); 2382 } 2383 free(ent); 2384 continue; 2385 } 2386 if (*p == '#') { 2387 p++; 2388 if (*p == '\0' || strchr("!+-:", *p) == NULL) 2389 continue; 2390 } 2391 if (*p == '+' || *p == '-') { 2392 host[0] = *p++; 2393 while (isspace(*p)) 2394 p++; 2395 if (*p == '\0' || *p == '*') { 2396 (void)strlcpy(host, "*", sizeof(host)); 2397 continue; 2398 } 2399 if (*p == '@') 2400 p = LocalHostName; 2401 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) { 2402 if (!isalnum(*p) && *p != '.' && *p != '-' 2403 && *p != ',' && *p != ':' && *p != '%') 2404 break; 2405 host[i] = *p++; 2406 } 2407 host[i] = '\0'; 2408 continue; 2409 } 2410 if (*p == '!') { 2411 p++; 2412 while (isspace(*p)) 2413 p++; 2414 if (*p == '\0' || *p == '*') { 2415 (void)strlcpy(prog, "*", sizeof(prog)); 2416 continue; 2417 } 2418 for (i = 0; i < LINE_MAX - 1; i++) { 2419 if (!isprint(p[i]) || isspace(p[i])) 2420 break; 2421 prog[i] = p[i]; 2422 } 2423 prog[i] = '\0'; 2424 continue; 2425 } 2426 if (*p == ':') { 2427 p++; 2428 while (isspace(*p)) 2429 p++; 2430 if (*p == '\0' || *p == '*') { 2431 (void)strlcpy(pfilter, "*", sizeof(pfilter)); 2432 continue; 2433 } 2434 (void)strlcpy(pfilter, p, sizeof(pfilter)); 2435 continue; 2436 } 2437 for (p = cline + 1; *p != '\0'; p++) { 2438 if (*p != '#') 2439 continue; 2440 if (*(p - 1) == '\\') { 2441 strcpy(p - 1, p); 2442 p--; 2443 continue; 2444 } 2445 *p = '\0'; 2446 break; 2447 } 2448 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--) 2449 cline[i] = '\0'; 2450 cfline(nvl_conf, cline, prog, host, pfilter); 2451 2452 } 2453 return (nvl_conf); 2454 } 2455 2456 /* 2457 * Read configuration file and create filed entries for each line. 2458 * 2459 * Note: This function is wrapped by cap_readconfigfile() when Capsicum 2460 * support is enabled so resources can be acquired outside of the security 2461 * sandbox. 2462 */ 2463 nvlist_t * 2464 readconfigfile(const char *path) 2465 { 2466 FILE *cf; 2467 nvlist_t *nvl_conf = nvlist_create(0); 2468 2469 if ((cf = fopen(path, "r")) != NULL) { 2470 nvl_conf = parseconfigfile(cf, true, nvl_conf); 2471 (void)fclose(cf); 2472 } else { 2473 dprintf("cannot open %s\n", path); 2474 cfline(nvl_conf, "*.ERR\t/dev/console", "*", "*", "*"); 2475 cfline(nvl_conf, "*.PANIC\t*", "*", "*", "*"); 2476 } 2477 return (nvl_conf); 2478 } 2479 2480 static void 2481 fill_flist(nvlist_t *nvl_conf) 2482 { 2483 const nvlist_t * const *filed_list; 2484 size_t nfileds; 2485 2486 if (!nvlist_exists_nvlist_array(nvl_conf, "filed_list")) 2487 return; 2488 filed_list = nvlist_get_nvlist_array(nvl_conf, "filed_list", 2489 &nfileds); 2490 for (size_t i = 0; i < nfileds; ++i) { 2491 struct filed *f; 2492 2493 f = nvlist_to_filed(filed_list[i]); 2494 STAILQ_INSERT_TAIL(&fhead, f, next); 2495 } 2496 nvlist_destroy(nvl_conf); 2497 } 2498 2499 /* 2500 * Close all open log files. 2501 */ 2502 void 2503 closelogfiles(void) 2504 { 2505 struct filed *f; 2506 2507 while (!STAILQ_EMPTY(&fhead)) { 2508 f = STAILQ_FIRST(&fhead); 2509 STAILQ_REMOVE_HEAD(&fhead, next); 2510 2511 /* flush any pending output */ 2512 if (f->f_prevcount) 2513 fprintlog_successive(f, 0); 2514 2515 switch (f->f_type) { 2516 case F_FILE: 2517 case F_FORW: 2518 case F_CONSOLE: 2519 case F_TTY: 2520 close_filed(f); 2521 break; 2522 case F_PIPE: 2523 if (f->f_procdesc != -1) { 2524 struct kevent ev; 2525 /* 2526 * This filed is going to be freed. 2527 * Delete procdesc kevents that reference it. 2528 */ 2529 EV_SET(&ev, f->f_procdesc, EVFILT_PROCDESC, 2530 EV_DELETE, NOTE_EXIT, 0, f); 2531 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) { 2532 logerror("failed to delete procdesc" 2533 "kevent"); 2534 exit(1); 2535 } 2536 } 2537 close_filed(f); 2538 break; 2539 default: 2540 break; 2541 } 2542 2543 if (f->f_prop_filter) { 2544 switch (f->f_prop_filter->cmp_type) { 2545 case FILT_CMP_REGEX: 2546 regfree(f->f_prop_filter->pflt_re); 2547 free(f->f_prop_filter->pflt_re); 2548 /* FALLTHROUGH */ 2549 case FILT_CMP_CONTAINS: 2550 case FILT_CMP_EQUAL: 2551 case FILT_CMP_STARTS: 2552 free(f->f_prop_filter->pflt_strval); 2553 break; 2554 } 2555 free(f->f_prop_filter); 2556 } 2557 free(f); 2558 } 2559 } 2560 2561 static void 2562 syslogd_cap_enter(void) 2563 { 2564 #ifdef WITH_CASPER 2565 cap_channel_t *cap_casper; 2566 cap_net_limit_t *limit; 2567 2568 cap_casper = cap_init(); 2569 if (cap_casper == NULL) 2570 err(1, "Failed to communicate with libcasper"); 2571 cap_syslogd = cap_service_open(cap_casper, "syslogd.casper"); 2572 if (cap_syslogd == NULL) 2573 err(1, "Failed to open the syslogd.casper libcasper service"); 2574 cap_net = cap_service_open(cap_casper, "system.net"); 2575 if (cap_net == NULL) 2576 err(1, "Failed to open the system.net libcasper service"); 2577 cap_close(cap_casper); 2578 limit = cap_net_limit_init(cap_net, 2579 CAPNET_ADDR2NAME | CAPNET_NAME2ADDR); 2580 if (limit == NULL) 2581 err(1, "Failed to create system.net limits"); 2582 if (cap_net_limit(limit) == -1) 2583 err(1, "Failed to apply system.net limits"); 2584 caph_cache_tzdata(); 2585 caph_cache_catpages(); 2586 if (caph_enter_casper() == -1) 2587 err(1, "Failed to enter capability mode"); 2588 #endif 2589 } 2590 2591 /* 2592 * INIT -- Initialize syslogd from configuration table 2593 */ 2594 static void 2595 init(bool reload) 2596 { 2597 int i; 2598 char *p; 2599 char oldLocalHostName[MAXHOSTNAMELEN]; 2600 char hostMsg[2*MAXHOSTNAMELEN+40]; 2601 char bootfileMsg[MAXLINE + 1]; 2602 2603 dprintf("init\n"); 2604 2605 /* 2606 * Load hostname (may have changed). 2607 */ 2608 if (reload) 2609 (void)strlcpy(oldLocalHostName, LocalHostName, 2610 sizeof(oldLocalHostName)); 2611 if (gethostname(LocalHostName, sizeof(LocalHostName))) 2612 err(EX_OSERR, "gethostname() failed"); 2613 if ((p = strchr(LocalHostName, '.')) != NULL) { 2614 /* RFC 5424 prefers logging FQDNs. */ 2615 if (IS_RFC3164_FORMAT) 2616 *p = '\0'; 2617 LocalDomain = p + 1; 2618 } else { 2619 LocalDomain = ""; 2620 } 2621 2622 #ifndef WITH_CASPER 2623 /* 2624 * XXX: Disable when running in capability mode, for now. 2625 * This requires a new interface in the tzcode module to 2626 * get running without capability violations. 2627 * 2628 * Load / reload timezone data (in case it changed). 2629 * 2630 * Just calling tzset() again does not work, the timezone code 2631 * caches the result. However, by setting the TZ variable, one 2632 * can defeat the caching and have the timezone code really 2633 * reload the timezone data. Respect any initial setting of 2634 * TZ, in case the system is configured specially. 2635 */ 2636 dprintf("loading timezone data via tzset()\n"); 2637 if (getenv("TZ")) { 2638 tzset(); 2639 } else { 2640 setenv("TZ", ":/etc/localtime", 1); 2641 tzset(); 2642 unsetenv("TZ"); 2643 } 2644 #endif 2645 2646 if (!reload) { 2647 struct tm tm; 2648 /* Cache time files before entering capability mode. */ 2649 timegm(&tm); 2650 syslogd_cap_enter(); 2651 } 2652 2653 Initialized = false; 2654 closelogfiles(); 2655 fill_flist(cap_readconfigfile(cap_syslogd, ConfFile)); 2656 Initialized = true; 2657 2658 if (Debug) { 2659 struct filed *f; 2660 int port; 2661 2662 STAILQ_FOREACH(f, &fhead, next) { 2663 for (i = 0; i <= LOG_NFACILITIES; i++) 2664 if (f->f_pmask[i] == INTERNAL_NOPRI) 2665 printf("X "); 2666 else 2667 printf("%d ", f->f_pmask[i]); 2668 printf("%s: ", TypeNames[f->f_type]); 2669 switch (f->f_type) { 2670 case F_FILE: 2671 printf("%s", f->f_fname); 2672 break; 2673 2674 case F_CONSOLE: 2675 case F_TTY: 2676 printf("%s%s", _PATH_DEV, f->f_fname); 2677 break; 2678 2679 case F_FORW: { 2680 int domain, sockfd = f->f_addr_fds[0]; 2681 socklen_t len = sizeof(domain); 2682 2683 if (getsockopt(sockfd, SOL_SOCKET, SO_DOMAIN, 2684 &domain, &len) < 0) 2685 err(1, "getsockopt"); 2686 2687 switch (domain) { 2688 #ifdef INET 2689 case AF_INET: { 2690 struct sockaddr_in sin; 2691 2692 len = sizeof(sin); 2693 if (getpeername(sockfd, (struct sockaddr *)&sin, &len) < 0) 2694 err(1, "getpeername"); 2695 port = ntohs(sin.sin_port); 2696 break; 2697 } 2698 #endif 2699 #ifdef INET6 2700 case AF_INET6: { 2701 struct sockaddr_in6 sin6; 2702 2703 len = sizeof(sin6); 2704 if (getpeername(sockfd, (struct sockaddr *)&sin6, &len) < 0) 2705 err(1, "getpeername"); 2706 port = ntohs(sin6.sin6_port); 2707 break; 2708 } 2709 #endif 2710 default: 2711 port = 0; 2712 } 2713 if (port != 514) { 2714 printf("%s:%d", f->f_hname, port); 2715 } else { 2716 printf("%s", f->f_hname); 2717 } 2718 break; 2719 } 2720 2721 case F_PIPE: 2722 printf("%s", f->f_pname); 2723 break; 2724 2725 case F_USERS: 2726 for (i = 0; i < MAXUNAMES && *f->f_uname[i]; i++) 2727 printf("%s, ", f->f_uname[i]); 2728 break; 2729 default: 2730 break; 2731 } 2732 if (*f->f_program != '\0') 2733 printf(" (%s)", f->f_program); 2734 printf("\n"); 2735 } 2736 } 2737 2738 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL, 2739 NULL, NULL, "restart", 0); 2740 dprintf("syslogd: restarted\n"); 2741 /* 2742 * Log a change in hostname, but only on reload. 2743 */ 2744 if (reload && strcmp(oldLocalHostName, LocalHostName) != 0) { 2745 (void)snprintf(hostMsg, sizeof(hostMsg), 2746 "hostname changed, \"%s\" to \"%s\"", 2747 oldLocalHostName, LocalHostName); 2748 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", 2749 NULL, NULL, NULL, hostMsg, 0); 2750 dprintf("%s\n", hostMsg); 2751 } 2752 /* 2753 * Log the kernel boot file if we aren't going to use it as 2754 * the prefix, and if this is *not* a reload. 2755 */ 2756 if (!reload && !use_bootfile) { 2757 (void)snprintf(bootfileMsg, sizeof(bootfileMsg), 2758 "kernel boot file is %s", bootfile); 2759 logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd", 2760 NULL, NULL, NULL, bootfileMsg, 0); 2761 dprintf("%s\n", bootfileMsg); 2762 } 2763 } 2764 2765 /* 2766 * Compile property-based filter. 2767 */ 2768 static nvlist_t * 2769 prop_filter_compile(const char *cfilter) 2770 { 2771 nvlist_t *nvl_pfilter; 2772 struct prop_filter pfilter = { }; 2773 char *filter, *filter_endpos, *filter_begpos, *p; 2774 char **ap, *argv[2] = {NULL, NULL}; 2775 int escaped; 2776 2777 filter = strdup(cfilter); 2778 if (filter == NULL) 2779 err(1, "strdup"); 2780 filter_begpos = filter; 2781 2782 /* 2783 * Here's some filter examples mentioned in syslog.conf(5) 2784 * 'msg, contains, ".*Deny.*"' 2785 * 'programname, regex, "^bird6?$"' 2786 * 'hostname, icase_ereregex, "^server-(dcA|podB)-rack1[0-9]{2}\\..*"' 2787 */ 2788 2789 /* 2790 * Split filter into 3 parts: property name (argv[0]), 2791 * cmp type (argv[1]) and lvalue for comparison (filter). 2792 */ 2793 for (ap = argv; (*ap = strsep(&filter, ", \t\n")) != NULL;) { 2794 if (**ap != '\0') 2795 if (++ap >= &argv[2]) 2796 break; 2797 } 2798 2799 if (argv[0] == NULL || argv[1] == NULL) { 2800 dprintf("filter parse error"); 2801 goto error; 2802 } 2803 2804 /* fill in prop_type */ 2805 if (strcasecmp(argv[0], "msg") == 0) 2806 pfilter.prop_type = FILT_PROP_MSG; 2807 else if (strcasecmp(argv[0], "hostname") == 0) 2808 pfilter.prop_type = FILT_PROP_HOSTNAME; 2809 else if (strcasecmp(argv[0], "source") == 0) 2810 pfilter.prop_type = FILT_PROP_HOSTNAME; 2811 else if (strcasecmp(argv[0], "programname") == 0) 2812 pfilter.prop_type = FILT_PROP_PROGNAME; 2813 else { 2814 dprintf("unknown property"); 2815 goto error; 2816 } 2817 2818 /* full in cmp_flags (i.e. !contains, icase_regex, etc.) */ 2819 if (*argv[1] == '!') { 2820 pfilter.cmp_flags |= FILT_FLAG_EXCLUDE; 2821 argv[1]++; 2822 } 2823 if (strncasecmp(argv[1], "icase_", (sizeof("icase_") - 1)) == 0) { 2824 pfilter.cmp_flags |= FILT_FLAG_ICASE; 2825 argv[1] += sizeof("icase_") - 1; 2826 } 2827 2828 /* fill in cmp_type */ 2829 if (strcasecmp(argv[1], "contains") == 0) 2830 pfilter.cmp_type = FILT_CMP_CONTAINS; 2831 else if (strcasecmp(argv[1], "isequal") == 0) 2832 pfilter.cmp_type = FILT_CMP_EQUAL; 2833 else if (strcasecmp(argv[1], "startswith") == 0) 2834 pfilter.cmp_type = FILT_CMP_STARTS; 2835 else if (strcasecmp(argv[1], "regex") == 0) 2836 pfilter.cmp_type = FILT_CMP_REGEX; 2837 else if (strcasecmp(argv[1], "ereregex") == 0) { 2838 pfilter.cmp_type = FILT_CMP_REGEX; 2839 pfilter.cmp_flags |= REG_EXTENDED; 2840 } else { 2841 dprintf("unknown cmp function"); 2842 goto error; 2843 } 2844 2845 /* 2846 * Handle filter value 2847 */ 2848 2849 /* ' ".*Deny.*"' */ 2850 /* remove leading whitespace and check for '"' next character */ 2851 filter += strspn(filter, ", \t\n"); 2852 if (*filter != '"' || strlen(filter) < 3) { 2853 dprintf("property value parse error"); 2854 goto error; 2855 } 2856 filter++; 2857 2858 /* '.*Deny.*"' */ 2859 /* process possible backslash (\") escaping */ 2860 escaped = 0; 2861 filter_endpos = filter; 2862 for (p = filter; *p != '\0'; p++) { 2863 if (*p == '\\' && !escaped) { 2864 escaped = 1; 2865 /* do not shift filter_endpos */ 2866 continue; 2867 } 2868 if (*p == '"' && !escaped) { 2869 p++; 2870 break; 2871 } 2872 /* we've seen some esc symbols, need to compress the line */ 2873 if (filter_endpos != p) 2874 *filter_endpos = *p; 2875 2876 filter_endpos++; 2877 escaped = 0; 2878 } 2879 2880 *filter_endpos = '\0'; 2881 /* '.*Deny.*' */ 2882 2883 /* We should not have anything but whitespace left after closing '"' */ 2884 if (*p != '\0' && strspn(p, " \t\n") != strlen(p)) { 2885 dprintf("property value parse error"); 2886 goto error; 2887 } 2888 2889 pfilter.pflt_strval = filter; 2890 /* An nvlist is heap allocated heap here. */ 2891 nvl_pfilter = prop_filter_to_nvlist(&pfilter); 2892 2893 free(filter_begpos); 2894 return (nvl_pfilter); 2895 error: 2896 free(filter_begpos); 2897 return (NULL); 2898 } 2899 2900 static const char * 2901 parse_selector(const char *p, struct filed *f) 2902 { 2903 int i, pri; 2904 int pri_done = 0, pri_cmp = 0, pri_invert = 0; 2905 char *bp, buf[LINE_MAX]; 2906 const char *q; 2907 2908 /* find the end of this facility name list */ 2909 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.';) 2910 continue; 2911 2912 /* get the priority comparison */ 2913 if (*q == '!') { 2914 pri_invert = 1; 2915 q++; 2916 } 2917 while (!pri_done) { 2918 switch (*q) { 2919 case '<': 2920 pri_cmp |= PRI_LT; 2921 q++; 2922 break; 2923 case '=': 2924 pri_cmp |= PRI_EQ; 2925 q++; 2926 break; 2927 case '>': 2928 pri_cmp |= PRI_GT; 2929 q++; 2930 break; 2931 default: 2932 pri_done++; 2933 break; 2934 } 2935 } 2936 2937 /* collect priority name */ 2938 for (bp = buf; *q != '\0' && !strchr("\t,; ", *q); ) 2939 *bp++ = *q++; 2940 *bp = '\0'; 2941 2942 /* skip cruft */ 2943 while (strchr(",;", *q)) 2944 q++; 2945 2946 /* decode priority name */ 2947 if (*buf == '*') { 2948 pri = LOG_PRIMASK; 2949 pri_cmp = PRI_LT | PRI_EQ | PRI_GT; 2950 } else { 2951 /* Ignore trailing spaces. */ 2952 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--) 2953 buf[i] = '\0'; 2954 2955 pri = decode(buf, prioritynames); 2956 if (pri < 0) { 2957 dprintf("unknown priority name \"%s\"", buf); 2958 return (NULL); 2959 } 2960 } 2961 if (!pri_cmp) 2962 pri_cmp = UniquePriority ? PRI_EQ : (PRI_EQ | PRI_GT); 2963 if (pri_invert) 2964 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT; 2965 2966 /* scan facilities */ 2967 while (*p != '\0' && !strchr("\t.; ", *p)) { 2968 for (bp = buf; *p != '\0' && !strchr("\t,;. ", *p); ) 2969 *bp++ = *p++; 2970 *bp = '\0'; 2971 2972 if (*buf == '*') { 2973 for (i = 0; i < LOG_NFACILITIES; i++) { 2974 f->f_pmask[i] = pri; 2975 f->f_pcmp[i] = pri_cmp; 2976 } 2977 } else { 2978 i = decode(buf, facilitynames); 2979 if (i < 0) { 2980 dprintf("unknown facility name \"%s\"", buf); 2981 return (NULL); 2982 } 2983 f->f_pmask[i >> 3] = pri; 2984 f->f_pcmp[i >> 3] = pri_cmp; 2985 } 2986 while (*p == ',' || *p == ' ') 2987 p++; 2988 } 2989 return (q); 2990 } 2991 2992 static int 2993 maybe_dup_forw_socket(const nvlist_t *nvl, const struct sockaddr *rsa, 2994 const struct sockaddr *lsa) 2995 { 2996 const nvlist_t * const *line; 2997 size_t linecount; 2998 2999 if (!nvlist_exists_nvlist_array(nvl, "filed_list")) 3000 return (-1); 3001 line = nvlist_get_nvlist_array(nvl, "filed_list", &linecount); 3002 for (size_t i = 0; i < linecount; i++) { 3003 const struct forw_addr *forw; 3004 const int *fdp; 3005 size_t fdc; 3006 3007 if (nvlist_get_number(line[i], "f_type") != F_FORW) 3008 continue; 3009 fdp = nvlist_get_descriptor_array(line[i], "f_addr_fds", &fdc); 3010 forw = nvlist_get_binary(line[i], "f_addrs", NULL); 3011 for (size_t j = 0; j < fdc; j++) { 3012 int fd; 3013 3014 if (memcmp(&forw[j].raddr, rsa, rsa->sa_len) != 0 || 3015 memcmp(&forw[j].laddr, lsa, lsa->sa_len) != 0) 3016 continue; 3017 3018 fd = dup(fdp[j]); 3019 if (fd < 0) 3020 err(1, "dup"); 3021 return (fd); 3022 } 3023 } 3024 3025 return (-1); 3026 } 3027 3028 /* 3029 * Create a UDP socket that will forward messages from "lai" to "ai". 3030 * Capsicum doesn't permit connect() or sendto(), so we can't reuse the (bound) 3031 * sockets used to listen for messages. 3032 */ 3033 static int 3034 make_forw_socket(const nvlist_t *nvl, struct addrinfo *ai, struct addrinfo *lai) 3035 { 3036 int s; 3037 3038 s = socket(ai->ai_family, ai->ai_socktype, 0); 3039 if (s < 0) 3040 err(1, "socket"); 3041 if (lai != NULL) { 3042 if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &(int){1}, 3043 sizeof(int)) < 0) 3044 err(1, "setsockopt"); 3045 if (bind(s, lai->ai_addr, lai->ai_addrlen) < 0) 3046 err(1, "bind"); 3047 } 3048 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) { 3049 if (errno == EADDRINUSE && lai != NULL) { 3050 int s1; 3051 3052 s1 = maybe_dup_forw_socket(nvl, ai->ai_addr, 3053 lai->ai_addr); 3054 if (s1 < 0) 3055 errc(1, EADDRINUSE, "connect"); 3056 (void)close(s); 3057 s = s1; 3058 } else { 3059 err(1, "connect"); 3060 } 3061 } 3062 /* Make it a write-only socket. */ 3063 if (shutdown(s, SHUT_RD) < 0) 3064 err(1, "shutdown"); 3065 3066 return (s); 3067 } 3068 3069 static void 3070 make_forw_socket_array(const nvlist_t *nvl, struct filed *f, 3071 struct addrinfo *res) 3072 { 3073 struct addrinfo *ai; 3074 size_t i; 3075 3076 f->f_num_addr_fds = 0; 3077 3078 /* How many sockets do we need? */ 3079 for (ai = res; ai != NULL; ai = ai->ai_next) { 3080 struct socklist *boundsock; 3081 int count; 3082 3083 count = 0; 3084 STAILQ_FOREACH(boundsock, &shead, next) { 3085 if (boundsock->sl_ai.ai_family == ai->ai_family) 3086 count++; 3087 } 3088 if (count == 0) 3089 count = 1; 3090 f->f_num_addr_fds += count; 3091 } 3092 3093 f->f_addr_fds = calloc(f->f_num_addr_fds, sizeof(*f->f_addr_fds)); 3094 f->f_addrs = calloc(f->f_num_addr_fds, sizeof(*f->f_addrs)); 3095 if (f->f_addr_fds == NULL || f->f_addrs == NULL) 3096 err(1, "malloc failed"); 3097 3098 /* 3099 * Create our forwarding sockets: for each bound socket 3100 * belonging to the destination address, create one socket 3101 * connected to the destination and bound to the address of the 3102 * listening socket. 3103 */ 3104 i = 0; 3105 for (ai = res; ai != NULL; ai = ai->ai_next) { 3106 struct socklist *boundsock; 3107 int count; 3108 3109 count = 0; 3110 STAILQ_FOREACH(boundsock, &shead, next) { 3111 if (boundsock->sl_ai.ai_family == 3112 ai->ai_family) { 3113 memcpy(&f->f_addrs[i].raddr, ai->ai_addr, 3114 ai->ai_addrlen); 3115 memcpy(&f->f_addrs[i].laddr, 3116 boundsock->sl_ai.ai_addr, 3117 boundsock->sl_ai.ai_addrlen); 3118 f->f_addr_fds[i++] = make_forw_socket(nvl, ai, 3119 &boundsock->sl_ai); 3120 count++; 3121 } 3122 } 3123 if (count == 0) { 3124 memcpy(&f->f_addrs[i].raddr, ai->ai_addr, 3125 ai->ai_addrlen); 3126 f->f_addr_fds[i++] = make_forw_socket(nvl, ai, NULL); 3127 } 3128 } 3129 assert(i == f->f_num_addr_fds); 3130 } 3131 3132 static void 3133 parse_action(const nvlist_t *nvl, const char *p, struct filed *f) 3134 { 3135 struct addrinfo hints, *res; 3136 size_t i; 3137 int error; 3138 const char *q; 3139 bool syncfile; 3140 3141 if (*p == '-') { 3142 syncfile = false; 3143 p++; 3144 } else 3145 syncfile = true; 3146 3147 f->f_file = -1; 3148 switch (*p) { 3149 case '@': 3150 { 3151 char *tp; 3152 char endkey = ':'; 3153 /* 3154 * scan forward to see if there is a port defined. 3155 * so we can't use strlcpy.. 3156 */ 3157 i = sizeof(f->f_hname); 3158 tp = f->f_hname; 3159 p++; 3160 3161 /* 3162 * an ipv6 address should start with a '[' in that case 3163 * we should scan for a ']' 3164 */ 3165 if (*p == '[') { 3166 p++; 3167 endkey = ']'; 3168 } 3169 while (*p && (*p != endkey) && (i-- > 0)) { 3170 *tp++ = *p++; 3171 } 3172 if (endkey == ']' && *p == endkey) 3173 p++; 3174 *tp = '\0'; 3175 } 3176 /* See if we copied a domain and have a port */ 3177 if (*p == ':') 3178 p++; 3179 else 3180 p = NULL; 3181 3182 hints = (struct addrinfo){ 3183 .ai_family = family, 3184 .ai_socktype = SOCK_DGRAM 3185 }; 3186 error = getaddrinfo(f->f_hname, p ? p : "syslog", &hints, &res); 3187 if (error) { 3188 dprintf("%s\n", gai_strerror(error)); 3189 break; 3190 } 3191 make_forw_socket_array(nvl, f, res); 3192 freeaddrinfo(res); 3193 f->f_type = F_FORW; 3194 break; 3195 3196 case '/': 3197 if ((f->f_file = open(p, logflags, 0600)) < 0) { 3198 f->f_type = F_UNUSED; 3199 dprintf("%s\n", p); 3200 break; 3201 } 3202 if (syncfile) 3203 f->f_flags |= FFLAG_SYNC; 3204 if (isatty(f->f_file)) { 3205 if (strcmp(p, _PATH_CONSOLE) == 0) 3206 f->f_type = F_CONSOLE; 3207 else 3208 f->f_type = F_TTY; 3209 (void)strlcpy(f->f_fname, p + sizeof(_PATH_DEV) - 1, 3210 sizeof(f->f_fname)); 3211 } else { 3212 (void)strlcpy(f->f_fname, p, sizeof(f->f_fname)); 3213 f->f_type = F_FILE; 3214 } 3215 break; 3216 3217 case '|': 3218 f->f_procdesc = -1; 3219 (void)strlcpy(f->f_pname, p + 1, sizeof(f->f_pname)); 3220 f->f_type = F_PIPE; 3221 break; 3222 3223 case '*': 3224 f->f_type = F_WALL; 3225 break; 3226 3227 default: 3228 for (i = 0; i < MAXUNAMES && *p; i++) { 3229 for (q = p; *q && *q != ','; ) 3230 q++; 3231 (void)strncpy(f->f_uname[i], p, MAXLOGNAME - 1); 3232 if ((q - p) >= MAXLOGNAME) 3233 f->f_uname[i][MAXLOGNAME - 1] = '\0'; 3234 else 3235 f->f_uname[i][q - p] = '\0'; 3236 while (*q == ',' || *q == ' ') 3237 q++; 3238 p = q; 3239 } 3240 f->f_type = F_USERS; 3241 break; 3242 } 3243 } 3244 3245 /* 3246 * Convert a configuration file line to an nvlist and add to "nvl", which 3247 * contains all of the log configuration processed thus far. 3248 */ 3249 static void 3250 cfline(nvlist_t *nvl, const char *line, const char *prog, const char *host, 3251 const char *pfilter) 3252 { 3253 nvlist_t *nvl_filed; 3254 struct filed f = { }; 3255 const char *p; 3256 3257 dprintf("cfline(\"%s\", f, \"%s\", \"%s\", \"%s\")\n", line, prog, 3258 host, pfilter); 3259 3260 for (int i = 0; i <= LOG_NFACILITIES; i++) 3261 f.f_pmask[i] = INTERNAL_NOPRI; 3262 3263 /* save hostname if any */ 3264 if (host != NULL && *host != '*') { 3265 int hl; 3266 3267 strlcpy(f.f_host, host, sizeof(f.f_host)); 3268 hl = strlen(f.f_host); 3269 if (hl > 0 && f.f_host[hl-1] == '.') 3270 f.f_host[--hl] = '\0'; 3271 /* RFC 5424 prefers logging FQDNs. */ 3272 if (IS_RFC3164_FORMAT) 3273 trimdomain(f.f_host, hl); 3274 } 3275 3276 /* save program name if any */ 3277 if (prog != NULL && *prog != '*') 3278 strlcpy(f.f_program, prog, sizeof(f.f_program)); 3279 3280 /* scan through the list of selectors */ 3281 for (p = line; *p != '\0' && *p != '\t' && *p != ' ';) 3282 p = parse_selector(p, &f); 3283 3284 /* skip to action part */ 3285 while (*p == '\t' || *p == ' ') 3286 p++; 3287 parse_action(nvl, p, &f); 3288 3289 /* An nvlist is heap allocated heap here. */ 3290 nvl_filed = filed_to_nvlist(&f); 3291 close_filed(&f); 3292 3293 if (pfilter && *pfilter != '*') { 3294 nvlist_t *nvl_pfilter; 3295 3296 nvl_pfilter = prop_filter_compile(pfilter); 3297 if (nvl_pfilter == NULL) 3298 err(1, "filter compile error"); 3299 nvlist_add_nvlist(nvl_filed, "f_prop_filter", nvl_pfilter); 3300 } 3301 3302 nvlist_append_nvlist_array(nvl, "filed_list", nvl_filed); 3303 nvlist_destroy(nvl_filed); 3304 } 3305 3306 /* 3307 * Decode a symbolic name to a numeric value 3308 */ 3309 static int 3310 decode(const char *name, const CODE *codetab) 3311 { 3312 const CODE *c; 3313 char *p, buf[40]; 3314 3315 if (isdigit(*name)) 3316 return (atoi(name)); 3317 3318 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) { 3319 if (isupper(*name)) 3320 *p = tolower(*name); 3321 else 3322 *p = *name; 3323 } 3324 *p = '\0'; 3325 for (c = codetab; c->c_name; c++) 3326 if (!strcmp(buf, c->c_name)) 3327 return (c->c_val); 3328 3329 return (-1); 3330 } 3331 3332 static void 3333 markit(void) 3334 { 3335 struct filed *f; 3336 struct deadq_entry *dq, *dq0; 3337 3338 now = time((time_t *)NULL); 3339 MarkSeq += TIMERINTVL; 3340 if (MarkSeq >= MarkInterval) { 3341 logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL, 3342 "-- MARK --", MARK); 3343 MarkSeq = 0; 3344 } 3345 3346 STAILQ_FOREACH(f, &fhead, next) { 3347 if (f->f_prevcount && now >= REPEATTIME(f)) { 3348 dprintf("flush %s: repeated %d times, %d sec.\n", 3349 TypeNames[f->f_type], f->f_prevcount, 3350 repeatinterval[f->f_repeatcount]); 3351 fprintlog_successive(f, 0); 3352 BACKOFF(f); 3353 } 3354 } 3355 3356 /* Walk the dead queue, and see if we should signal somebody. */ 3357 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) { 3358 switch (dq->dq_timeout) { 3359 case 0: 3360 /* Already signalled once, try harder now. */ 3361 (void)pdkill(dq->dq_procdesc, SIGKILL); 3362 break; 3363 3364 case 1: 3365 (void)pdkill(dq->dq_procdesc, SIGTERM); 3366 /* FALLTHROUGH. */ 3367 default: 3368 dq->dq_timeout--; 3369 } 3370 } 3371 (void)alarm(TIMERINTVL); 3372 } 3373 3374 /* 3375 * fork off and become a daemon, but wait for the child to come online 3376 * before returning to the parent, or we get disk thrashing at boot etc. 3377 */ 3378 static int 3379 waitdaemon(int maxwait) 3380 { 3381 struct pollfd pollfd; 3382 int events, pipefd[2], status; 3383 pid_t pid; 3384 3385 if (pipe(pipefd) == -1) { 3386 warn("failed to daemonize, pipe"); 3387 die(0); 3388 } 3389 pid = fork(); 3390 if (pid == -1) { 3391 warn("failed to daemonize, fork"); 3392 die(0); 3393 } else if (pid > 0) { 3394 close(pipefd[1]); 3395 pollfd.fd = pipefd[0]; 3396 pollfd.events = POLLHUP; 3397 events = poll(&pollfd, 1, maxwait * 1000); 3398 if (events == -1) 3399 err(1, "failed to daemonize, poll"); 3400 else if (events == 0) 3401 errx(1, "timed out waiting for child"); 3402 if (waitpid(pid, &status, WNOHANG) > 0) { 3403 if (WIFEXITED(status)) 3404 errx(1, "child pid %d exited with return code %d", 3405 pid, WEXITSTATUS(status)); 3406 if (WIFSIGNALED(status)) 3407 errx(1, "child pid %d exited on signal %d%s", 3408 pid, WTERMSIG(status), 3409 WCOREDUMP(status) ? " (core dumped)" : ""); 3410 } 3411 exit(0); 3412 } 3413 close(pipefd[0]); 3414 if (setsid() == -1) { 3415 warn("failed to daemonize, setsid"); 3416 die(0); 3417 } 3418 (void)chdir("/"); 3419 (void)dup2(nulldesc, STDIN_FILENO); 3420 (void)dup2(nulldesc, STDOUT_FILENO); 3421 (void)dup2(nulldesc, STDERR_FILENO); 3422 return (pipefd[1]); 3423 } 3424 3425 /* 3426 * Add `s' to the list of allowable peer addresses to accept messages 3427 * from. 3428 * 3429 * `s' is a string in the form: 3430 * 3431 * [*]domainname[:{servicename|portnumber|*}] 3432 * 3433 * or 3434 * 3435 * netaddr/maskbits[:{servicename|portnumber|*}] 3436 * 3437 * Returns false on error, true if the argument was valid. 3438 */ 3439 static bool 3440 #if defined(INET) || defined(INET6) 3441 allowaddr(char *s) 3442 #else 3443 allowaddr(char *s __unused) 3444 #endif 3445 { 3446 #if defined(INET) || defined(INET6) 3447 char *cp1, *cp2; 3448 struct allowedpeer *ap; 3449 struct servent *se; 3450 int masklen = -1; 3451 struct addrinfo hints, *res = NULL; 3452 #ifdef INET 3453 in_addr_t *addrp, *maskp; 3454 #endif 3455 #ifdef INET6 3456 uint32_t *addr6p, *mask6p; 3457 #endif 3458 char ip[NI_MAXHOST]; 3459 3460 ap = calloc(1, sizeof(*ap)); 3461 if (ap == NULL) 3462 err(1, "malloc failed"); 3463 3464 #ifdef INET6 3465 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL) 3466 #endif 3467 cp1 = s; 3468 if ((cp1 = strrchr(cp1, ':'))) { 3469 /* service/port provided */ 3470 *cp1++ = '\0'; 3471 if (strlen(cp1) == 1 && *cp1 == '*') 3472 /* any port allowed */ 3473 ap->port = 0; 3474 else if ((se = getservbyname(cp1, "udp"))) { 3475 ap->port = ntohs(se->s_port); 3476 } else { 3477 ap->port = strtol(cp1, &cp2, 0); 3478 /* port not numeric */ 3479 if (*cp2 != '\0') 3480 goto err; 3481 } 3482 } else { 3483 if ((se = getservbyname("syslog", "udp"))) 3484 ap->port = ntohs(se->s_port); 3485 else 3486 /* sanity, should not happen */ 3487 ap->port = 514; 3488 } 3489 3490 if ((cp1 = strchr(s, '/')) != NULL && 3491 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) { 3492 *cp1 = '\0'; 3493 if ((masklen = atoi(cp1 + 1)) < 0) 3494 goto err; 3495 } 3496 #ifdef INET6 3497 if (*s == '[') { 3498 cp2 = s + strlen(s) - 1; 3499 if (*cp2 == ']') { 3500 ++s; 3501 *cp2 = '\0'; 3502 } else { 3503 cp2 = NULL; 3504 } 3505 } else { 3506 cp2 = NULL; 3507 } 3508 #endif 3509 hints = (struct addrinfo){ 3510 .ai_family = PF_UNSPEC, 3511 .ai_socktype = SOCK_DGRAM, 3512 .ai_flags = AI_PASSIVE | AI_NUMERICHOST 3513 }; 3514 if (getaddrinfo(s, NULL, &hints, &res) == 0) { 3515 ap->isnumeric = true; 3516 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen); 3517 ap->a_mask = (struct sockaddr_storage){ 3518 .ss_family = res->ai_family, 3519 .ss_len = res->ai_addrlen 3520 }; 3521 switch (res->ai_family) { 3522 #ifdef INET 3523 case AF_INET: 3524 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr; 3525 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr; 3526 if (masklen < 0) { 3527 /* use default netmask */ 3528 if (IN_CLASSA(ntohl(*addrp))) 3529 *maskp = htonl(IN_CLASSA_NET); 3530 else if (IN_CLASSB(ntohl(*addrp))) 3531 *maskp = htonl(IN_CLASSB_NET); 3532 else 3533 *maskp = htonl(IN_CLASSC_NET); 3534 } else if (masklen == 0) { 3535 *maskp = 0; 3536 } else if (masklen <= 32) { 3537 /* convert masklen to netmask */ 3538 *maskp = htonl(~((1 << (32 - masklen)) - 1)); 3539 } else { 3540 goto err; 3541 } 3542 /* Lose any host bits in the network number. */ 3543 *addrp &= *maskp; 3544 break; 3545 #endif 3546 #ifdef INET6 3547 case AF_INET6: 3548 if (masklen > 128) 3549 goto err; 3550 3551 if (masklen < 0) 3552 masklen = 128; 3553 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0]; 3554 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0]; 3555 /* convert masklen to netmask */ 3556 while (masklen > 0) { 3557 if (masklen < 32) { 3558 *mask6p = 3559 htonl(~(0xffffffff >> masklen)); 3560 *addr6p &= *mask6p; 3561 break; 3562 } else { 3563 *mask6p++ = 0xffffffff; 3564 addr6p++; 3565 masklen -= 32; 3566 } 3567 } 3568 break; 3569 #endif 3570 default: 3571 goto err; 3572 } 3573 freeaddrinfo(res); 3574 } else { 3575 /* arg `s' is domain name */ 3576 ap->isnumeric = false; 3577 ap->a_name = s; 3578 if (cp1) 3579 *cp1 = '/'; 3580 #ifdef INET6 3581 if (cp2) { 3582 *cp2 = ']'; 3583 --s; 3584 } 3585 #endif 3586 } 3587 STAILQ_INSERT_TAIL(&aphead, ap, next); 3588 3589 if (Debug) { 3590 printf("allowaddr: rule "); 3591 if (ap->isnumeric) { 3592 printf("numeric, "); 3593 getnameinfo(sstosa(&ap->a_addr), 3594 (sstosa(&ap->a_addr))->sa_len, 3595 ip, sizeof(ip), NULL, 0, NI_NUMERICHOST); 3596 printf("addr = %s, ", ip); 3597 getnameinfo(sstosa(&ap->a_mask), 3598 (sstosa(&ap->a_mask))->sa_len, 3599 ip, sizeof(ip), NULL, 0, NI_NUMERICHOST); 3600 printf("mask = %s; ", ip); 3601 } else { 3602 printf("domainname = %s; ", ap->a_name); 3603 } 3604 printf("port = %d\n", ap->port); 3605 } 3606 3607 return (true); 3608 err: 3609 if (res != NULL) 3610 freeaddrinfo(res); 3611 free(ap); 3612 #endif 3613 return (false); 3614 } 3615 3616 /* 3617 * Validate that the remote peer has permission to log to us. 3618 */ 3619 static bool 3620 validate(struct sockaddr *sa, const char *hname) 3621 { 3622 int i; 3623 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV]; 3624 struct allowedpeer *ap; 3625 #ifdef INET 3626 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL; 3627 #endif 3628 #ifdef INET6 3629 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL; 3630 #endif 3631 struct addrinfo hints, *res; 3632 u_short sport; 3633 3634 /* traditional behaviour, allow everything */ 3635 if (STAILQ_EMPTY(&aphead)) 3636 return (true); 3637 3638 (void)strlcpy(name, hname, sizeof(name)); 3639 hints = (struct addrinfo){ 3640 .ai_family = PF_UNSPEC, 3641 .ai_socktype = SOCK_DGRAM, 3642 .ai_flags = AI_PASSIVE | AI_NUMERICHOST 3643 }; 3644 if (cap_getaddrinfo(cap_net, name, NULL, &hints, &res) == 0) 3645 freeaddrinfo(res); 3646 else if (strchr(name, '.') == NULL) { 3647 strlcat(name, ".", sizeof(name)); 3648 strlcat(name, LocalDomain, sizeof(name)); 3649 } 3650 if (cap_getnameinfo(cap_net, sa, sa->sa_len, ip, sizeof(ip), port, 3651 sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV) != 0) 3652 return (false); /* for safety, should not occur */ 3653 dprintf("validate: dgram from IP %s, port %s, name %s;\n", 3654 ip, port, name); 3655 sport = atoi(port); 3656 3657 /* now, walk down the list */ 3658 i = 0; 3659 STAILQ_FOREACH(ap, &aphead, next) { 3660 i++; 3661 if (ap->port != 0 && ap->port != sport) { 3662 dprintf("rejected in rule %d due to port mismatch.\n", 3663 i); 3664 continue; 3665 } 3666 3667 if (ap->isnumeric) { 3668 if (ap->a_addr.ss_family != sa->sa_family) { 3669 dprintf("rejected in rule %d due to address family mismatch.\n", i); 3670 continue; 3671 } 3672 #ifdef INET 3673 else if (ap->a_addr.ss_family == AF_INET) { 3674 sin4 = satosin(sa); 3675 a4p = satosin(&ap->a_addr); 3676 m4p = satosin(&ap->a_mask); 3677 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr) 3678 != a4p->sin_addr.s_addr) { 3679 dprintf("rejected in rule %d due to IP mismatch.\n", i); 3680 continue; 3681 } 3682 } 3683 #endif 3684 #ifdef INET6 3685 else if (ap->a_addr.ss_family == AF_INET6) { 3686 sin6 = satosin6(sa); 3687 a6p = satosin6(&ap->a_addr); 3688 m6p = satosin6(&ap->a_mask); 3689 if (a6p->sin6_scope_id != 0 && 3690 sin6->sin6_scope_id != a6p->sin6_scope_id) { 3691 dprintf("rejected in rule %d due to scope mismatch.\n", i); 3692 continue; 3693 } 3694 if (!IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr, 3695 &a6p->sin6_addr, &m6p->sin6_addr)) { 3696 dprintf("rejected in rule %d due to IP mismatch.\n", i); 3697 continue; 3698 } 3699 } 3700 #endif 3701 else 3702 continue; 3703 } else { 3704 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) == 3705 FNM_NOMATCH) { 3706 dprintf("rejected in rule %d due to name " 3707 "mismatch.\n", i); 3708 continue; 3709 } 3710 } 3711 dprintf("accepted in rule %d.\n", i); 3712 return (true); /* hooray! */ 3713 } 3714 return (false); 3715 } 3716 3717 /* 3718 * Fairly similar to popen(3), but returns an open descriptor, as 3719 * opposed to a FILE *. 3720 * 3721 * Note: This function is wrapped by cap_p_open() when Capsicum support is 3722 * enabled, which allows piped processes to run outside of the capability 3723 * sandbox. 3724 */ 3725 int 3726 p_open(const char *prog, int *rpd) 3727 { 3728 struct sigaction act = { }; 3729 int pfd[2], pd; 3730 pid_t pid; 3731 char *argv[4]; /* sh -c cmd NULL */ 3732 3733 if (pipe(pfd) == -1) 3734 return (-1); 3735 3736 switch ((pid = pdfork(&pd, PD_CLOEXEC))) { 3737 case -1: 3738 return (-1); 3739 3740 case 0: 3741 (void)setsid(); /* Avoid catching SIGHUPs. */ 3742 argv[0] = strdup("sh"); 3743 argv[1] = strdup("-c"); 3744 argv[2] = strdup(prog); 3745 argv[3] = NULL; 3746 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) 3747 err(1, "strdup"); 3748 3749 alarm(0); 3750 act.sa_handler = SIG_DFL; 3751 for (size_t i = 0; i < nitems(sigcatch); ++i) { 3752 if (sigaction(sigcatch[i], &act, NULL) == -1) 3753 err(1, "sigaction"); 3754 } 3755 3756 dup2(pfd[0], STDIN_FILENO); 3757 dup2(nulldesc, STDOUT_FILENO); 3758 dup2(nulldesc, STDERR_FILENO); 3759 closefrom(STDERR_FILENO + 1); 3760 3761 (void)execvp(_PATH_BSHELL, argv); 3762 _exit(255); 3763 } 3764 close(pfd[0]); 3765 /* 3766 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are 3767 * supposed to get an EWOULDBLOCK on writev(2), which is 3768 * caught by the logic above anyway, which will in turn close 3769 * the pipe, and fork a new logging subprocess if necessary. 3770 * The stale subprocess will be killed some time later unless 3771 * it terminated itself due to closing its input pipe (so we 3772 * get rid of really dead puppies). 3773 */ 3774 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) { 3775 /* This is bad. */ 3776 dprintf("Warning: cannot change pipe to PID %d to non-blocking" 3777 "behaviour.", pid); 3778 } 3779 *rpd = pd; 3780 return (pfd[1]); 3781 } 3782 3783 static struct deadq_entry * 3784 deadq_enter(int pd) 3785 { 3786 struct deadq_entry *dq; 3787 3788 if (pd == -1) 3789 return (NULL); 3790 3791 dq = malloc(sizeof(*dq)); 3792 if (dq == NULL) { 3793 logerror("malloc"); 3794 exit(1); 3795 } 3796 3797 dq->dq_procdesc = pd; 3798 dq->dq_timeout = DQ_TIMO_INIT; 3799 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries); 3800 return (dq); 3801 } 3802 3803 static void 3804 deadq_remove(struct deadq_entry *dq) 3805 { 3806 TAILQ_REMOVE(&deadq_head, dq, dq_entries); 3807 free(dq); 3808 } 3809 3810 static void 3811 log_deadchild(int pd, int status, const struct filed *f) 3812 { 3813 pid_t pid; 3814 int code; 3815 char buf[256]; 3816 const char *reason; 3817 3818 errno = 0; /* Keep strerror() stuff out of logerror messages. */ 3819 if (WIFSIGNALED(status)) { 3820 reason = "due to signal"; 3821 code = WTERMSIG(status); 3822 } else { 3823 reason = "with status"; 3824 code = WEXITSTATUS(status); 3825 if (code == 0) 3826 return; 3827 } 3828 if (pdgetpid(pd, &pid) == -1) 3829 err(1, "pdgetpid"); 3830 (void)snprintf(buf, sizeof(buf), 3831 "Logging subprocess %d (%s) exited %s %d.", 3832 pid, f->f_pname, reason, code); 3833 logerror(buf); 3834 } 3835 3836 static struct socklist * 3837 socksetup(struct addrinfo *ai, const char *name, mode_t mode) 3838 { 3839 struct socklist *sl; 3840 int (*sl_recv)(struct socklist *); 3841 int s, optval = 1; 3842 3843 if (ai->ai_family != AF_LOCAL && SecureMode > 1) { 3844 /* Only AF_LOCAL in secure mode. */ 3845 return (NULL); 3846 } 3847 if (family != AF_UNSPEC && ai->ai_family != AF_LOCAL && 3848 ai->ai_family != family) 3849 return (NULL); 3850 3851 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); 3852 if (s < 0) { 3853 logerror("socket"); 3854 return (NULL); 3855 } 3856 #ifdef INET6 3857 if (ai->ai_family == AF_INET6) { 3858 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &optval, 3859 sizeof(int)) < 0) { 3860 logerror("setsockopt(IPV6_V6ONLY)"); 3861 close(s); 3862 return (NULL); 3863 } 3864 } 3865 #endif 3866 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, 3867 sizeof(int)) < 0) { 3868 logerror("setsockopt(SO_REUSEADDR)"); 3869 close(s); 3870 return (NULL); 3871 } 3872 3873 /* 3874 * Bind INET and UNIX-domain sockets. 3875 * 3876 * A UNIX-domain socket is always bound to a pathname 3877 * regardless of -N flag. 3878 * 3879 * For INET sockets, RFC 3164 recommends that client 3880 * side message should come from the privileged syslogd port. 3881 * 3882 * If the system administrator chooses not to obey 3883 * this, we can skip the bind() step so that the 3884 * system will choose a port for us. 3885 */ 3886 if (ai->ai_family == AF_LOCAL) 3887 unlink(name); 3888 if (ai->ai_family == AF_LOCAL || NoBind == 0 || name != NULL) { 3889 mode_t mask; 3890 int error; 3891 3892 if (ai->ai_family == AF_LOCAL && fchmod(s, mode) < 0) { 3893 dprintf("fchmod %s: %s\n", name, strerror(errno)); 3894 close(s); 3895 return (NULL); 3896 } 3897 3898 if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &(int){1}, 3899 sizeof(int)) < 0) { 3900 logerror("setsockopt(SO_REUSEPORT)"); 3901 close(s); 3902 return (NULL); 3903 } 3904 3905 /* 3906 * For AF_LOCAL sockets, the process umask is applied to the 3907 * mode set above, so temporarily clear it to ensure that the 3908 * socket always has the correct permissions. 3909 */ 3910 mask = umask(0); 3911 error = bind(s, ai->ai_addr, ai->ai_addrlen); 3912 (void)umask(mask); 3913 if (error < 0) { 3914 logerror("bind"); 3915 close(s); 3916 return (NULL); 3917 } 3918 if (ai->ai_family == AF_LOCAL || SecureMode == 0) 3919 increase_rcvbuf(s); 3920 } 3921 dprintf("new socket fd is %d\n", s); 3922 sl_recv = socklist_recv_sock; 3923 #if defined(INET) || defined(INET6) 3924 if (SecureMode && (ai->ai_family == AF_INET || 3925 ai->ai_family == AF_INET6)) { 3926 dprintf("shutdown\n"); 3927 /* Forbid communication in secure mode. */ 3928 if (shutdown(s, SHUT_RD) < 0 && errno != ENOTCONN) { 3929 logerror("shutdown"); 3930 if (!Debug) 3931 die(0); 3932 } 3933 sl_recv = NULL; 3934 } else 3935 #endif 3936 dprintf("listening on socket\n"); 3937 dprintf("sending on socket\n"); 3938 /* Copy *ai->ai_addr to the tail of struct socklist if any. */ 3939 sl = calloc(1, sizeof(*sl) + ai->ai_addrlen); 3940 if (sl == NULL) 3941 err(1, "malloc failed"); 3942 sl->sl_socket = s; 3943 if (ai->ai_family == AF_LOCAL) { 3944 char *name2 = strdup(name); 3945 if (name2 == NULL) 3946 err(1, "strdup failed"); 3947 sl->sl_name = strdup(basename(name2)); 3948 sl->sl_dirfd = open(dirname(name2), O_DIRECTORY); 3949 if (sl->sl_name == NULL || sl->sl_dirfd == -1) 3950 err(1, "failed to save dir info for %s", name); 3951 free(name2); 3952 } 3953 sl->sl_recv = sl_recv; 3954 (void)memcpy(&sl->sl_ai, ai, sizeof(*ai)); 3955 if (ai->ai_addrlen > 0) { 3956 (void)memcpy((sl + 1), ai->ai_addr, ai->ai_addrlen); 3957 sl->sl_sa = (struct sockaddr *)(sl + 1); 3958 } else { 3959 sl->sl_sa = NULL; 3960 } 3961 return (sl); 3962 } 3963 3964 static void 3965 increase_rcvbuf(int fd) 3966 { 3967 socklen_t len; 3968 3969 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, 3970 &(socklen_t){sizeof(len)}) == 0) { 3971 if (len < RCVBUF_MINSIZE) { 3972 len = RCVBUF_MINSIZE; 3973 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)); 3974 } 3975 } 3976 } 3977