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