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