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