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