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