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