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