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