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