2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1983, 1988, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
32 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
34 * Copyright (c) 2018 Prodrive Technologies, https://prodrive-technologies.com/
35 * Author: Ed Schouten <ed@FreeBSD.org>
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
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.
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
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";
67 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
75 * syslogd -- log system messages
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.
82 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
83 * cause it to reread its configuration file.
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
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
96 * -u and -v by Harlan Stenn.
97 * Priority comparison code by Harlan Stenn.
100 #define MAXLINE 8192 /* maximum line length */
101 #define MAXSVLINE MAXLINE /* maximum saved line length */
102 #define DEFUPRI (LOG_USER|LOG_NOTICE)
103 #define DEFSPRI (LOG_KERN|LOG_CRIT)
104 #define TIMERINTVL 30 /* interval for checking flush, mark */
105 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
106 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
108 #include <sys/param.h>
109 #include <sys/ioctl.h>
110 #include <sys/mman.h>
111 #include <sys/queue.h>
112 #include <sys/resource.h>
113 #include <sys/socket.h>
114 #include <sys/stat.h>
115 #include <sys/syslimits.h>
116 #include <sys/time.h>
119 #include <sys/wait.h>
121 #if defined(INET) || defined(INET6)
122 #include <netinet/in.h>
123 #include <arpa/inet.h>
143 #include <sysexits.h>
148 #include "pathnames.h"
152 #include <sys/syslog.h>
154 static const char *ConfFile = _PATH_LOGCONF;
155 static const char *PidFile = _PATH_LOGPID;
156 static const char ctty[] = _PATH_CONSOLE;
157 static const char include_str[] = "include";
158 static const char include_ext[] = ".conf";
160 #define dprintf if (Debug) printf
162 #define MAXUNAMES 20 /* maximum number of user names */
164 #define sstosa(ss) ((struct sockaddr *)(ss))
166 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss))
167 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa))
170 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss))
171 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa))
172 #define s6_addr32 __u6_addr.__u6_addr32
173 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \
174 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
175 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
176 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
177 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
180 * List of peers and sockets for binding.
186 STAILQ_ENTRY(peer) next;
188 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
191 struct addrinfo sl_ai;
192 #define sl_sa sl_ai.ai_addr
193 #define sl_salen sl_ai.ai_addrlen
194 #define sl_family sl_ai.ai_family
196 struct peer *sl_peer;
197 int (*sl_recv)(struct socklist *);
198 STAILQ_ENTRY(socklist) next;
200 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
206 #define IGN_CONS 0x001 /* don't print on console */
207 #define SYNC_FILE 0x002 /* do fsync on file after printing */
208 #define MARK 0x008 /* this message is a mark */
209 #define ISKERNEL 0x010 /* kernel generated message */
211 /* Timestamps of log entries. */
217 /* Traditional syslog timestamp format. */
218 #define RFC3164_DATELEN 15
219 #define RFC3164_DATEFMT "%b %e %H:%M:%S"
222 * This structure holds a property-based filter
227 #define PROP_TYPE_NOOP 0
228 #define PROP_TYPE_MSG 1
229 #define PROP_TYPE_HOSTNAME 2
230 #define PROP_TYPE_PROGNAME 3
233 #define PROP_CMP_CONTAINS 1
234 #define PROP_CMP_EQUAL 2
235 #define PROP_CMP_STARTS 3
236 #define PROP_CMP_REGEX 4
239 #define PROP_FLAG_EXCLUDE (1 << 0)
240 #define PROP_FLAG_ICASE (1 << 1)
246 #define pflt_strval pflt_uniptr.p_strval
247 #define pflt_re pflt_uniptr.p_re
253 * This structure represents the files that will have log
255 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
256 * or if f_type is F_PIPE and f_pid > 0.
260 STAILQ_ENTRY(filed) next; /* next in linked list */
261 short f_type; /* entry type, see below */
262 short f_file; /* file descriptor */
263 time_t f_time; /* time this was last written */
264 char *f_host; /* host from which to recd. */
265 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
266 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
270 char *f_program; /* program this applies to */
271 struct prop_filter *f_prop_filter; /* property-based filter */
273 char f_uname[MAXUNAMES][MAXLOGNAME];
275 char f_hname[MAXHOSTNAMELEN];
276 struct addrinfo *f_addr;
278 } f_forw; /* forwarding address */
279 char f_fname[MAXPATHLEN];
281 char f_pname[MAXPATHLEN];
285 #define fu_uname f_un.f_uname
286 #define fu_forw_hname f_un.f_forw.f_hname
287 #define fu_forw_addr f_un.f_forw.f_addr
288 #define fu_fname f_un.f_fname
289 #define fu_pipe_pname f_un.f_pipe.f_pname
290 #define fu_pipe_pid f_un.f_pipe.f_pid
291 char f_prevline[MAXSVLINE]; /* last message logged */
292 struct logtime f_lasttime; /* time of last occurrence */
293 int f_prevpri; /* pri of f_prevline */
294 size_t f_prevlen; /* length of f_prevline */
295 int f_prevcount; /* repetition cnt of prevline */
296 u_int f_repeatcount; /* number of "repeated" msgs */
297 int f_flags; /* file-specific flags */
298 #define FFLAG_SYNC 0x01
299 #define FFLAG_NEEDSYNC 0x02
303 * Queue of about-to-be dead processes we should watch out for.
308 TAILQ_ENTRY(deadq_entry) dq_entries;
310 static TAILQ_HEAD(, deadq_entry) deadq_head =
311 TAILQ_HEAD_INITIALIZER(deadq_head);
314 * The timeout to apply to processes waiting on the dead queue. Unit
315 * of measure is `mark intervals', i.e. 20 minutes by default.
316 * Processes on the dead queue will be terminated after that time.
319 #define DQ_TIMO_INIT 2
322 * Struct to hold records of network addresses that are allowed to log
330 struct sockaddr_storage addr;
331 struct sockaddr_storage mask;
335 #define a_addr u.numeric.addr
336 #define a_mask u.numeric.mask
337 #define a_name u.name
338 STAILQ_ENTRY(allowedpeer) next;
340 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
344 * Intervals at which we flush out "message repeated" messages,
345 * in seconds after previous message is logged. After each flush,
346 * we move to the next interval until we reach the largest.
348 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
349 #define MAXREPEAT (nitems(repeatinterval) - 1)
350 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
351 #define BACKOFF(f) do { \
352 if (++(f)->f_repeatcount > MAXREPEAT) \
353 (f)->f_repeatcount = MAXREPEAT; \
356 /* values for f_type */
357 #define F_UNUSED 0 /* unused entry */
358 #define F_FILE 1 /* regular file */
359 #define F_TTY 2 /* terminal */
360 #define F_CONSOLE 3 /* console terminal */
361 #define F_FORW 4 /* remote machine */
362 #define F_USERS 5 /* list of users */
363 #define F_WALL 6 /* everyone logged on */
364 #define F_PIPE 7 /* pipe to program */
366 static const char *TypeNames[] = {
367 "UNUSED", "FILE", "TTY", "CONSOLE",
368 "FORW", "USERS", "WALL", "PIPE"
371 static STAILQ_HEAD(, filed) fhead =
372 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */
373 static struct filed consfile; /* Console */
375 static int Debug; /* debug flag */
376 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
377 static int resolve = 1; /* resolve hostname */
378 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
379 static const char *LocalDomain; /* our local domain name */
380 static int Initialized; /* set when we have initialized ourselves */
381 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
382 static int MarkSeq; /* mark sequence number */
383 static int NoBind; /* don't bind() as suggested by RFC 3164 */
384 static int SecureMode; /* when true, receive only unix domain socks */
385 static int MaxForwardLen = 1024; /* max length of forwared message */
387 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
389 static int family = PF_INET; /* protocol family (IPv4 only) */
391 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
392 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
393 static int use_bootfile; /* log entire bootfile for every kern msg */
394 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
395 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
397 static char bootfile[MAXPATHLEN]; /* booted kernel file */
399 static int RemoteAddDate; /* Always set the date on remote messages */
400 static int RemoteHostname; /* Log remote hostname from the message */
402 static int UniquePriority; /* Only log specified priority? */
403 static int LogFacPri; /* Put facility and priority in log message: */
404 /* 0=no, 1=numeric, 2=names */
405 static int KeepKernFac; /* Keep remotely logged kernel facility */
406 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
407 static struct pidfh *pfh;
408 static int sigpipe[2]; /* Pipe to catch a signal during select(). */
409 static bool RFC3164OutputFormat = true; /* Use legacy format by default. */
411 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
415 static int allowaddr(char *);
416 static int addfile(struct filed *);
417 static int addpeer(struct peer *);
418 static int addsock(struct addrinfo *, struct socklist *);
419 static struct filed *cfline(const char *, const char *, const char *,
421 static const char *cvthname(struct sockaddr *);
422 static void deadq_enter(pid_t, const char *);
423 static int deadq_remove(struct deadq_entry *);
424 static int deadq_removebypid(pid_t);
425 static int decode(const char *, const CODE *);
426 static void die(int) __dead2;
427 static void dodie(int);
428 static void dofsync(void);
429 static void domark(int);
430 static void fprintlog_first(struct filed *, const char *, const char *,
431 const char *, const char *, const char *, const char *, int);
432 static void fprintlog_write(struct filed *, struct iovlist *, int);
433 static void fprintlog_successive(struct filed *, int);
434 static void init(int);
435 static void logerror(const char *);
436 static void logmsg(int, const struct logtime *, const char *, const char *,
437 const char *, const char *, const char *, const char *, int);
438 static void log_deadchild(pid_t, int, const char *);
439 static void markit(void);
440 static int socksetup(struct peer *);
441 static int socklist_recv_file(struct socklist *);
442 static int socklist_recv_sock(struct socklist *);
443 static int socklist_recv_signal(struct socklist *);
444 static void sighandler(int);
445 static int skip_message(const char *, const char *, int);
446 static int evaluate_prop_filter(const struct prop_filter *filter,
448 static int prop_filter_compile(struct prop_filter *pfilter,
450 static void parsemsg(const char *, char *);
451 static void printsys(char *);
452 static int p_open(const char *, pid_t *);
453 static void reapchild(int);
454 static const char *ttymsg_check(struct iovec *, int, char *, int);
455 static void usage(void);
456 static int validate(struct sockaddr *, const char *);
457 static void unmapped(struct sockaddr *);
458 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
459 static int waitdaemon(int);
460 static void timedout(int);
461 static void increase_rcvbuf(int);
464 close_filed(struct filed *f)
467 if (f == NULL || f->f_file == -1)
472 if (f->fu_forw_addr != NULL) {
473 freeaddrinfo(f->fu_forw_addr);
474 f->fu_forw_addr = NULL;
481 f->f_type = F_UNUSED;
487 (void)close(f->f_file);
492 addfile(struct filed *f0)
496 f = calloc(1, sizeof(*f));
498 err(1, "malloc failed");
500 STAILQ_INSERT_TAIL(&fhead, f, next);
506 addpeer(struct peer *pe0)
510 pe = calloc(1, sizeof(*pe));
512 err(1, "malloc failed");
514 STAILQ_INSERT_TAIL(&pqueue, pe, next);
520 addsock(struct addrinfo *ai, struct socklist *sl0)
524 /* Copy *ai->ai_addr to the tail of struct socklist if any. */
525 sl = calloc(1, sizeof(*sl) + ((ai != NULL) ? ai->ai_addrlen : 0));
527 err(1, "malloc failed");
530 memcpy(&sl->sl_ai, ai, sizeof(*ai));
531 if (ai->ai_addrlen > 0) {
532 memcpy((sl + 1), ai->ai_addr, ai->ai_addrlen);
533 sl->sl_sa = (struct sockaddr *)(sl + 1);
537 STAILQ_INSERT_TAIL(&shead, sl, next);
543 main(int argc, char *argv[])
545 int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
547 struct timeval tv, *tvp;
550 pid_t ppid = 1, spid;
553 if (madvise(NULL, 0, MADV_PROTECT) != 0)
554 dprintf("madvise() failed: %s\n", strerror(errno));
556 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:M:m:nNoO:p:P:sS:Tuv"))
575 case 'a': /* allow specific network addresses only */
576 if (allowaddr(optarg) == -1)
581 p = strchr(optarg, ']');
583 p = strchr(p + 1, ':');
585 p = strchr(optarg, ':');
586 if (p != NULL && strchr(p + 1, ':') != NULL)
587 p = NULL; /* backward compatibility */
590 /* A hostname or filename only. */
591 addpeer(&(struct peer){
596 /* The case of "name:service". */
598 addpeer(&(struct peer){
600 .pe_name = (strlen(optarg) == 0) ?
611 case 'd': /* debug */
614 case 'f': /* configuration file */
617 case 'F': /* run in foreground instead of daemon */
623 case 'k': /* keep remote kern fac */
636 else if (ch == 'p') {
640 mode = S_IRUSR | S_IWUSR;
643 if (optarg[0] == '/')
645 else if ((name = strchr(optarg, ':')) != NULL) {
648 errx(1, "socket name must be absolute "
650 if (isdigit(*optarg)) {
651 perml = strtol(optarg, &ep, 8);
652 if (*ep || perml < 0 ||
653 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
654 errx(1, "invalid mode %s, exiting",
656 mode = (mode_t )perml;
658 errx(1, "invalid mode %s, exiting",
661 errx(1, "invalid filename %s, exiting",
663 addpeer(&(struct peer){
669 case 'M': /* max length of forwarded message */
670 MaxForwardLen = atoi(optarg);
671 if (MaxForwardLen < 480)
672 errx(1, "minimum length limit of forwarded "
673 "messages is 480 bytes");
675 case 'm': /* mark interval */
676 MarkInterval = atoi(optarg) * 60;
686 if (strcmp(optarg, "bsd") == 0 ||
687 strcmp(optarg, "rfc3164") == 0)
688 RFC3164OutputFormat = true;
689 else if (strcmp(optarg, "syslog") == 0 ||
690 strcmp(optarg, "rfc5424") == 0)
691 RFC3164OutputFormat = false;
698 case 'P': /* path for alt. PID */
701 case 's': /* no network mode */
707 case 'u': /* only log specified priority */
710 case 'v': /* log facility and priority */
716 if ((argc -= optind) != 0)
719 if (RFC3164OutputFormat && MaxForwardLen > 1024)
720 errx(1, "RFC 3164 messages may not exceed 1024 bytes");
722 /* Pipe to catch a signal during select(). */
723 s = pipe2(sigpipe, O_CLOEXEC);
725 err(1, "cannot open a pipe for signals");
727 addsock(NULL, &(struct socklist){
728 .sl_socket = sigpipe[0],
729 .sl_recv = socklist_recv_signal
733 /* Listen by default: /dev/klog. */
734 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
736 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
738 addsock(NULL, &(struct socklist){
740 .sl_recv = socklist_recv_file,
743 /* Listen by default: *:514 if no -b flag. */
745 addpeer(&(struct peer){
748 /* Listen by default: /var/run/log if no -p flag. */
750 addpeer(&(struct peer){
751 .pe_name = _PATH_LOG,
752 .pe_mode = DEFFILEMODE,
754 /* Listen by default: /var/run/logpriv if no -S flag. */
756 addpeer(&(struct peer){
757 .pe_name = _PATH_LOG_PRIV,
758 .pe_mode = S_IRUSR | S_IWUSR,
760 STAILQ_FOREACH(pe, &pqueue, next)
763 pfh = pidfile_open(PidFile, 0600, &spid);
766 errx(1, "syslogd already running, pid: %d", spid);
767 warn("cannot open pid file");
770 if ((!Foreground) && (!Debug)) {
771 ppid = waitdaemon(30);
773 warn("could not become daemon");
780 consfile.f_type = F_CONSOLE;
781 (void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
782 sizeof(consfile.fu_fname));
783 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
784 (void)signal(SIGTERM, dodie);
785 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
786 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
787 (void)signal(SIGHUP, sighandler);
788 (void)signal(SIGCHLD, sighandler);
789 (void)signal(SIGALRM, domark);
790 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
791 (void)alarm(TIMERINTVL);
793 /* tuck my process id away */
796 dprintf("off & running....\n");
799 tv.tv_sec = tv.tv_usec = 0;
801 STAILQ_FOREACH(sl, &shead, next) {
802 if (sl->sl_socket > fdsrmax)
803 fdsrmax = sl->sl_socket;
805 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
808 errx(1, "calloc fd_set");
811 if (Initialized == 0)
813 else if (WantInitialize)
814 init(WantInitialize);
816 reapchild(WantReapchild);
824 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
827 STAILQ_FOREACH(sl, &shead, next) {
828 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
829 FD_SET(sl->sl_socket, fdsr);
831 i = select(fdsrmax + 1, fdsr, NULL, NULL,
832 needdofsync ? &tv : tvp);
848 STAILQ_FOREACH(sl, &shead, next) {
849 if (FD_ISSET(sl->sl_socket, fdsr))
857 socklist_recv_signal(struct socklist *sl __unused)
862 if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
863 logerror("ioctl(FIONREAD)");
864 err(1, "signal pipe read failed");
866 nsig = i / sizeof(signo);
867 dprintf("# of received signals = %d\n", nsig);
868 for (i = 0; i < nsig; i++) {
869 len = read(sigpipe[0], &signo, sizeof(signo));
870 if (len != sizeof(signo)) {
871 logerror("signal pipe read failed");
872 err(1, "signal pipe read failed");
874 dprintf("Received signal: %d from fd=%d\n", signo,
889 socklist_recv_sock(struct socklist *sl)
891 struct sockaddr_storage ss;
892 struct sockaddr *sa = (struct sockaddr *)&ss;
895 char line[MAXLINE + 1];
899 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
900 dprintf("received sa_len = %d\n", sslen);
905 logerror("recvfrom");
908 /* Received valid data. */
910 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
911 hname = LocalHostName;
913 hname = cvthname(sa);
915 if (validate(sa, hname) == 0) {
916 dprintf("Message from %s was ignored.", hname);
920 parsemsg(hname, line);
926 unmapped(struct sockaddr *sa)
928 #if defined(INET) && defined(INET6)
929 struct sockaddr_in6 *sin6;
930 struct sockaddr_in sin;
933 sa->sa_family != AF_INET6 ||
934 sa->sa_len != sizeof(*sin6))
937 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
939 sin = (struct sockaddr_in){
940 .sin_family = AF_INET,
941 .sin_len = sizeof(sin),
942 .sin_port = sin6->sin6_port
944 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
945 sizeof(sin.sin_addr));
946 memcpy(sa, &sin, sizeof(sin));
958 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n"
959 " [-b bind_address] [-f config_file]\n"
960 " [-l [mode:]path] [-M fwd_length]\n"
961 " [-m mark_interval] [-O format] [-P pid_file]\n"
962 " [-p log_socket] [-S logpriv_socket]\n");
967 * Removes characters from log messages that are unsafe to display.
968 * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
971 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
977 while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
978 if (mask_C1 && (c & 0x80) && c < 0xA0) {
983 if (isascii(c) && iscntrl(c)) {
986 } else if (c == '\t') {
1000 * Parses a syslog message according to RFC 5424, assuming that PRI and
1001 * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
1002 * parsed result is passed to logmsg().
1005 parsemsg_rfc5424(const char *from, int pri, char *msg)
1007 const struct logtime *timestamp;
1008 struct logtime timestamp_remote;
1009 const char *omsg, *hostname, *app_name, *procid, *msgid,
1011 char line[MAXLINE + 1];
1013 #define FAIL_IF(field, expr) do { \
1015 dprintf("Failed to parse " field " from %s: %s\n", \
1020 #define PARSE_CHAR(field, sep) do { \
1021 FAIL_IF(field, *msg != sep); \
1024 #define IF_NOT_NILVALUE(var) \
1025 if (msg[0] == '-' && msg[1] == ' ') { \
1028 } else if (msg[0] == '-' && msg[1] == '\0') { \
1034 IF_NOT_NILVALUE(timestamp) {
1035 /* Parse RFC 3339-like timestamp. */
1036 #define PARSE_NUMBER(dest, length, min, max) do { \
1040 for (i = 0; i < length; ++i) { \
1041 FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9'); \
1042 v = v * 10 + *msg++ - '0'; \
1044 FAIL_IF("TIMESTAMP", v < min || v > max); \
1047 /* Date and time. */
1048 memset(×tamp_remote, 0, sizeof(timestamp_remote));
1049 PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
1050 timestamp_remote.tm.tm_year -= 1900;
1051 PARSE_CHAR("TIMESTAMP", '-');
1052 PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
1053 --timestamp_remote.tm.tm_mon;
1054 PARSE_CHAR("TIMESTAMP", '-');
1055 PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
1056 PARSE_CHAR("TIMESTAMP", 'T');
1057 PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
1058 PARSE_CHAR("TIMESTAMP", ':');
1059 PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
1060 PARSE_CHAR("TIMESTAMP", ':');
1061 PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
1062 /* Perform normalization. */
1063 timegm(×tamp_remote.tm);
1064 /* Optional: fractional seconds. */
1065 if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
1069 for (i = 100000; i != 0; i /= 10) {
1070 if (*msg < '0' || *msg > '9')
1072 timestamp_remote.usec += (*msg++ - '0') * i;
1080 int sign, tz_hour, tz_min;
1082 /* Local time zone offset. */
1083 FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1084 sign = *msg++ == '-' ? -1 : 1;
1085 PARSE_NUMBER(tz_hour, 2, 0, 23);
1086 PARSE_CHAR("TIMESTAMP", ':');
1087 PARSE_NUMBER(tz_min, 2, 0, 59);
1088 timestamp_remote.tm.tm_gmtoff =
1089 sign * (tz_hour * 3600 + tz_min * 60);
1092 PARSE_CHAR("TIMESTAMP", ' ');
1093 timestamp = RemoteAddDate ? NULL : ×tamp_remote;
1096 /* String fields part of the HEADER. */
1097 #define PARSE_STRING(field, var) \
1098 IF_NOT_NILVALUE(var) { \
1100 while (*msg >= '!' && *msg <= '~') \
1102 FAIL_IF(field, var == msg); \
1103 PARSE_CHAR(field, ' '); \
1106 PARSE_STRING("HOSTNAME", hostname);
1107 if (hostname == NULL || !RemoteHostname)
1109 PARSE_STRING("APP-NAME", app_name);
1110 PARSE_STRING("PROCID", procid);
1111 PARSE_STRING("MSGID", msgid);
1114 /* Structured data. */
1115 #define PARSE_SD_NAME() do { \
1116 const char *start; \
1119 while (*msg >= '!' && *msg <= '~' && *msg != '=' && \
1120 *msg != ']' && *msg != '"') \
1122 FAIL_IF("STRUCTURED-NAME", start == msg); \
1124 IF_NOT_NILVALUE(structured_data) {
1126 while (*msg == '[') {
1131 while (*msg == ' ') {
1135 PARSE_CHAR("STRUCTURED-NAME", '=');
1136 PARSE_CHAR("STRUCTURED-NAME", '"');
1137 while (*msg != '"') {
1138 FAIL_IF("STRUCTURED-NAME",
1140 if (*msg++ == '\\') {
1141 FAIL_IF("STRUCTURED-NAME",
1148 PARSE_CHAR("STRUCTURED-NAME", ']');
1150 PARSE_CHAR("STRUCTURED-NAME", ' ');
1153 #undef PARSE_SD_NAME
1157 #undef IF_NOT_NILVALUE
1159 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1160 logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1161 structured_data, line, 0);
1165 * Returns the length of the application name ("TAG" in RFC 3164
1166 * terminology) and process ID from a message if present.
1169 parsemsg_rfc3164_get_app_name_procid(const char *msg, size_t *app_name_length_p,
1170 ptrdiff_t *procid_begin_offset_p, size_t *procid_length_p)
1172 const char *m, *procid_begin;
1173 size_t app_name_length, procid_length;
1177 /* Application name. */
1178 app_name_length = strspn(m,
1179 "abcdefghijklmnopqrstuvwxyz"
1180 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1183 if (app_name_length == 0)
1185 m += app_name_length;
1187 /* Process identifier (optional). */
1190 procid_length = strspn(m, "0123456789");
1191 if (procid_length == 0)
1197 procid_begin = NULL;
1202 if (m[0] != ':' || m[1] != ' ')
1205 *app_name_length_p = app_name_length;
1206 if (procid_begin_offset_p != NULL)
1207 *procid_begin_offset_p =
1208 procid_begin == NULL ? 0 : procid_begin - msg;
1209 if (procid_length_p != NULL)
1210 *procid_length_p = procid_length;
1213 *app_name_length_p = 0;
1214 if (procid_begin_offset_p != NULL)
1215 *procid_begin_offset_p = 0;
1216 if (procid_length_p != NULL)
1217 *procid_length_p = 0;
1221 * Trims the application name ("TAG" in RFC 3164 terminology) and
1222 * process ID from a message if present.
1225 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1226 const char **procid)
1228 char *m, *app_name_begin, *procid_begin;
1229 size_t app_name_length, procid_length;
1230 ptrdiff_t procid_begin_offset;
1235 parsemsg_rfc3164_get_app_name_procid(app_name_begin, &app_name_length,
1236 &procid_begin_offset, &procid_length);
1237 if (app_name_length == 0)
1239 procid_begin = procid_begin_offset == 0 ? NULL :
1240 app_name_begin + procid_begin_offset;
1242 /* Split strings from input. */
1243 app_name_begin[app_name_length] = '\0';
1244 m += app_name_length + 1;
1245 if (procid_begin != NULL) {
1246 procid_begin[procid_length] = '\0';
1247 m += procid_length + 2;
1251 *app_name = app_name_begin;
1252 *procid = procid_begin;
1260 * Parses a syslog message according to RFC 3164, assuming that PRI
1261 * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1262 * result is passed to logmsg().
1265 parsemsg_rfc3164(const char *from, int pri, char *msg)
1267 struct tm tm_parsed;
1268 const struct logtime *timestamp;
1269 struct logtime timestamp_remote;
1270 const char *app_name, *procid;
1272 char line[MAXLINE + 1];
1275 * Parse the TIMESTAMP provided by the remote side. If none is
1276 * found, assume this is not an RFC 3164 formatted message,
1277 * only containing a TAG and a MSG.
1280 if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) ==
1281 msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') {
1282 msg += RFC3164_DATELEN + 1;
1283 if (!RemoteAddDate) {
1289 * As the timestamp does not contain the year
1290 * number, daylight saving time information, nor
1291 * a time zone, attempt to infer it. Due to
1292 * clock skews, the timestamp may even be part
1293 * of the next year. Use the last year for which
1294 * the timestamp is at most one week in the
1297 * This loop can only run for at most three
1298 * iterations before terminating.
1301 localtime_r(&t_now, &tm_now);
1302 for (year = tm_now.tm_year + 1;; --year) {
1303 assert(year >= tm_now.tm_year - 1);
1304 timestamp_remote.tm = tm_parsed;
1305 timestamp_remote.tm.tm_year = year;
1306 timestamp_remote.tm.tm_isdst = -1;
1307 timestamp_remote.usec = 0;
1308 if (mktime(×tamp_remote.tm) <
1309 t_now + 7 * 24 * 60 * 60)
1312 timestamp = ×tamp_remote;
1316 * A single space character MUST also follow the HOSTNAME field.
1318 msglen = strlen(msg);
1319 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1320 if (msg[i] == ' ') {
1321 if (RemoteHostname) {
1329 * Support non RFC compliant messages, without hostname.
1334 if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1335 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1340 /* Remove the TAG, if present. */
1341 parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1342 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1343 logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1347 * Takes a raw input line, extracts PRI and determines whether the
1348 * message is formatted according to RFC 3164 or RFC 5424. Continues
1349 * parsing of addition fields in the message according to those
1350 * standards and prints the message on the appropriate log files.
1353 parsemsg(const char *from, char *msg)
1361 if (msg[0] != '<' || !isdigit(msg[1])) {
1362 dprintf("Invalid PRI from %s\n", from);
1365 for (i = 2; i <= 4; i++) {
1368 if (!isdigit(msg[i])) {
1369 dprintf("Invalid PRI header from %s\n", from);
1373 if (msg[i] != '>') {
1374 dprintf("Invalid PRI header from %s\n", from);
1378 n = strtol(msg + 1, &q, 10);
1379 if (errno != 0 || *q != msg[i] || n < 0 || n >= INT_MAX) {
1380 dprintf("Invalid PRI %ld from %s: %s\n",
1381 n, from, strerror(errno));
1385 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1389 * Don't allow users to log kernel messages.
1390 * NOTE: since LOG_KERN == 0 this will also match
1391 * messages with no facility specified.
1393 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1394 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1396 /* Parse VERSION. */
1398 if (msg[0] == '1' && msg[1] == ' ')
1399 parsemsg_rfc5424(from, pri, msg + 2);
1401 parsemsg_rfc3164(from, pri, msg);
1405 * Read /dev/klog while data are available, split into lines.
1408 socklist_recv_file(struct socklist *sl)
1410 char *p, *q, line[MAXLINE + 1];
1415 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1417 line[i + len] = '\0';
1419 if (i < 0 && errno != EINTR && errno != EAGAIN) {
1421 close(sl->sl_socket);
1427 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1432 if (len >= MAXLINE - 1) {
1437 memmove(line, p, len + 1);
1446 * Take a raw input line from /dev/klog, format similar to syslog().
1453 int flags, isprintf, pri;
1455 flags = ISKERNEL | SYNC_FILE; /* fsync after write */
1461 n = strtol(p + 1, &q, 10);
1462 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1469 * Kernel printf's and LOG_CONSOLE messages have been displayed
1470 * on the console already.
1472 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1474 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1476 logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1482 * Match a program or host name against a specification.
1483 * Return a non-0 value if the message must be ignored
1484 * based on the specification.
1487 skip_message(const char *name, const char *spec, int checkcase)
1492 /* Behaviour on explicit match */
1507 s = strstr (spec, name);
1509 s = strcasestr (spec, name);
1512 prev = (s == spec ? ',' : *(s - 1));
1513 next = *(s + strlen (name));
1515 if (prev == ',' && (next == '\0' || next == ','))
1516 /* Explicit match: skip iff the spec is an
1521 /* No explicit match for this name: skip the message iff
1522 the spec is an inclusive one. */
1527 * Match some property of the message against a filter.
1528 * Return a non-0 value if the message must be ignored
1529 * based on the filter.
1532 evaluate_prop_filter(const struct prop_filter *filter, const char *value)
1534 const char *s = NULL;
1535 const int exclude = ((filter->cmp_flags & PROP_FLAG_EXCLUDE) > 0);
1541 if (filter->cmp_type == PROP_CMP_REGEX) {
1542 if (regexec(filter->pflt_re, value, 0, NULL, 0) == 0)
1548 valuelen = strlen(value);
1550 /* a shortcut for equal with different length is always false */
1551 if (filter->cmp_type == PROP_CMP_EQUAL &&
1552 valuelen != filter->pflt_strlen)
1555 if (filter->cmp_flags & PROP_FLAG_ICASE)
1556 s = strcasestr(value, filter->pflt_strval);
1558 s = strstr(value, filter->pflt_strval);
1561 * PROP_CMP_CONTAINS true if s
1562 * PROP_CMP_STARTS true if s && s == value
1563 * PROP_CMP_EQUAL true if s && s == value &&
1564 * valuelen == filter->pflt_strlen
1565 * (and length match is checked
1569 switch (filter->cmp_type) {
1570 case PROP_CMP_STARTS:
1571 case PROP_CMP_EQUAL:
1575 case PROP_CMP_CONTAINS:
1582 /* unknown cmp_type */
1590 * Logs a message to the appropriate log files, users, etc. based on the
1591 * priority. Log messages are always formatted according to RFC 3164,
1592 * even if they were in RFC 5424 format originally, The MSGID and
1593 * STRUCTURED-DATA fields are thus discarded for the time being.
1596 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1597 const char *app_name, const char *procid, const char *msgid,
1598 const char *structured_data, const char *msg, int flags)
1601 struct logtime timestamp_now;
1605 char saved[MAXSVLINE], kernel_app_name[100];
1607 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1608 pri, flags, hostname, msg);
1610 (void)gettimeofday(&tv, NULL);
1612 if (timestamp == NULL) {
1613 localtime_r(&now, ×tamp_now.tm);
1614 timestamp_now.usec = tv.tv_usec;
1615 timestamp = ×tamp_now;
1618 /* extract facility and priority level */
1620 fac = LOG_NFACILITIES;
1624 /* Check maximum facility number. */
1625 if (fac > LOG_NFACILITIES)
1628 prilev = LOG_PRI(pri);
1631 * Lookup kernel app name from log prefix if present.
1632 * This is only used for local program specification matching.
1634 if (flags & ISKERNEL) {
1635 size_t kernel_app_name_length;
1637 parsemsg_rfc3164_get_app_name_procid(msg,
1638 &kernel_app_name_length, NULL, NULL);
1639 if (kernel_app_name_length != 0) {
1640 strlcpy(kernel_app_name, msg,
1641 MIN(sizeof(kernel_app_name),
1642 kernel_app_name_length + 1));
1644 kernel_app_name[0] = '\0';
1647 /* log the message to the particular outputs */
1651 * Open in non-blocking mode to avoid hangs during open
1652 * and close(waiting for the port to drain).
1654 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1656 if (f->f_file >= 0) {
1657 f->f_lasttime = *timestamp;
1658 fprintlog_first(f, hostname, app_name, procid, msgid,
1659 structured_data, msg, flags);
1667 * Store all of the fields of the message, except the timestamp,
1668 * in a single string. This string is used to detect duplicate
1671 assert(hostname != NULL);
1672 assert(msg != NULL);
1673 savedlen = snprintf(saved, sizeof(saved),
1674 "%d %s %s %s %s %s %s", pri, hostname,
1675 app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1676 msgid == NULL ? "-" : msgid,
1677 structured_data == NULL ? "-" : structured_data, msg);
1679 STAILQ_FOREACH(f, &fhead, next) {
1680 /* skip messages that are incorrect priority */
1681 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1682 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1683 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1685 || f->f_pmask[fac] == INTERNAL_NOPRI)
1688 /* skip messages with the incorrect hostname */
1689 if (skip_message(hostname, f->f_host, 0))
1692 /* skip messages with the incorrect program name */
1693 if (flags & ISKERNEL && kernel_app_name[0] != '\0') {
1694 if (skip_message(kernel_app_name, f->f_program, 1))
1696 } else if (skip_message(app_name == NULL ? "" : app_name,
1700 /* skip messages if a property does not match filter */
1701 if (f->f_prop_filter != NULL &&
1702 f->f_prop_filter->prop_type != PROP_TYPE_NOOP) {
1703 switch (f->f_prop_filter->prop_type) {
1705 if (evaluate_prop_filter(f->f_prop_filter,
1709 case PROP_TYPE_HOSTNAME:
1710 if (evaluate_prop_filter(f->f_prop_filter,
1714 case PROP_TYPE_PROGNAME:
1715 if (evaluate_prop_filter(f->f_prop_filter,
1716 app_name == NULL ? "" : app_name))
1724 /* skip message to console if it has already been printed */
1725 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1728 /* don't output marks to recently written files */
1729 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1733 * suppress duplicate lines to this file
1735 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1736 (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1737 strcmp(saved, f->f_prevline) == 0) {
1738 f->f_lasttime = *timestamp;
1740 dprintf("msg repeated %d times, %ld sec of %d\n",
1741 f->f_prevcount, (long)(now - f->f_time),
1742 repeatinterval[f->f_repeatcount]);
1744 * If domark would have logged this by now,
1745 * flush it now (so we don't hold isolated messages),
1746 * but back off so we'll flush less often
1749 if (now > REPEATTIME(f)) {
1750 fprintlog_successive(f, flags);
1754 /* new line, save it */
1756 fprintlog_successive(f, 0);
1757 f->f_repeatcount = 0;
1759 f->f_lasttime = *timestamp;
1760 static_assert(sizeof(f->f_prevline) == sizeof(saved),
1761 "Space to store saved line incorrect");
1762 (void)strcpy(f->f_prevline, saved);
1763 f->f_prevlen = savedlen;
1764 fprintlog_first(f, hostname, app_name, procid, msgid,
1765 structured_data, msg, flags);
1775 STAILQ_FOREACH(f, &fhead, next) {
1776 if ((f->f_type == F_FILE) &&
1777 (f->f_flags & FFLAG_NEEDSYNC)) {
1778 f->f_flags &= ~FFLAG_NEEDSYNC;
1779 (void)fsync(f->f_file);
1785 * List of iovecs to which entries can be appended.
1786 * Used for constructing the message to be logged.
1789 struct iovec iov[TTYMSG_IOV_MAX];
1795 iovlist_init(struct iovlist *il)
1803 iovlist_append(struct iovlist *il, const char *str)
1807 /* Discard components if we've run out of iovecs. */
1808 if (il->iovcnt < nitems(il->iov)) {
1810 il->iov[il->iovcnt++] = (struct iovec){
1811 .iov_base = __DECONST(char *, str),
1814 il->totalsize += size;
1818 #if defined(INET) || defined(INET6)
1820 iovlist_truncate(struct iovlist *il, size_t size)
1825 while (il->totalsize > size) {
1826 diff = il->totalsize - size;
1827 last = &il->iov[il->iovcnt - 1];
1828 if (diff >= last->iov_len) {
1829 /* Remove the last iovec entirely. */
1831 il->totalsize -= last->iov_len;
1833 /* Remove the last iovec partially. */
1834 last->iov_len -= diff;
1835 il->totalsize -= diff;
1842 fprintlog_write(struct filed *f, struct iovlist *il, int flags)
1844 struct msghdr msghdr;
1846 struct socklist *sl;
1850 switch (f->f_type) {
1852 dprintf(" %s", f->fu_forw_hname);
1853 switch (f->fu_forw_addr->ai_family) {
1857 ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1863 ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1870 /* Truncate messages to maximum forward length. */
1871 iovlist_truncate(il, MaxForwardLen);
1874 for (r = f->fu_forw_addr; r; r = r->ai_next) {
1875 memset(&msghdr, 0, sizeof(msghdr));
1876 msghdr.msg_name = r->ai_addr;
1877 msghdr.msg_namelen = r->ai_addrlen;
1878 msghdr.msg_iov = il->iov;
1879 msghdr.msg_iovlen = il->iovcnt;
1880 STAILQ_FOREACH(sl, &shead, next) {
1881 if (sl->sl_socket < 0)
1883 if (sl->sl_sa == NULL ||
1884 sl->sl_family == AF_UNSPEC ||
1885 sl->sl_family == AF_LOCAL)
1887 lsent = sendmsg(sl->sl_socket, &msghdr, 0);
1888 if (lsent == (ssize_t)il->totalsize)
1891 if (lsent == (ssize_t)il->totalsize && !send_to_all)
1894 dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize);
1895 if (lsent != (ssize_t)il->totalsize) {
1909 /* case ENOTSOCK: */
1911 /* case EMSGSIZE: */
1914 /* case ECONNREFUSED: */
1916 dprintf("removing entry: errno=%d\n", e);
1917 f->f_type = F_UNUSED;
1924 dprintf(" %s\n", f->fu_fname);
1925 iovlist_append(il, "\n");
1926 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1928 * If writev(2) fails for potentially transient errors
1929 * like the filesystem being full, ignore it.
1930 * Otherwise remove this logfile from the list.
1932 if (errno != ENOSPC) {
1936 logerror(f->fu_fname);
1938 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1939 f->f_flags |= FFLAG_NEEDSYNC;
1945 dprintf(" %s\n", f->fu_pipe_pname);
1946 iovlist_append(il, "\n");
1947 if (f->fu_pipe_pid == 0) {
1948 if ((f->f_file = p_open(f->fu_pipe_pname,
1949 &f->fu_pipe_pid)) < 0) {
1950 logerror(f->fu_pipe_pname);
1954 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1957 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1960 logerror(f->fu_pipe_pname);
1965 if (flags & IGN_CONS) {
1966 dprintf(" (ignored)\n");
1972 dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1973 iovlist_append(il, "\r\n");
1974 errno = 0; /* ttymsg() only sometimes returns an errno */
1975 if ((msgret = ttymsg(il->iov, il->iovcnt, f->fu_fname, 10))) {
1976 f->f_type = F_UNUSED;
1984 iovlist_append(il, "\r\n");
1985 wallmsg(f, il->iov, il->iovcnt);
1991 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name,
1992 const char *procid, const char *msgid, const char *structured_data,
1993 const char *msg, int flags)
1998 char timebuf[33], priority_number[5];
2001 if (f->f_type == F_WALL)
2002 iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n");
2003 iovlist_append(&il, "<");
2004 snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri);
2005 iovlist_append(&il, priority_number);
2006 iovlist_append(&il, ">1 ");
2007 if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z",
2008 &f->f_lasttime.tm) == sizeof(timebuf) - 2) {
2009 /* Add colon to the time zone offset, which %z doesn't do. */
2011 timebuf[31] = timebuf[30];
2012 timebuf[30] = timebuf[29];
2015 /* Overwrite space for microseconds with actual value. */
2016 usec = f->f_lasttime.usec;
2017 for (i = 25; i >= 20; --i) {
2018 timebuf[i] = usec % 10 + '0';
2021 iovlist_append(&il, timebuf);
2023 iovlist_append(&il, "-");
2024 iovlist_append(&il, " ");
2025 iovlist_append(&il, hostname);
2026 iovlist_append(&il, " ");
2027 iovlist_append(&il, app_name == NULL ? "-" : app_name);
2028 iovlist_append(&il, " ");
2029 iovlist_append(&il, procid == NULL ? "-" : procid);
2030 iovlist_append(&il, " ");
2031 iovlist_append(&il, msgid == NULL ? "-" : msgid);
2032 iovlist_append(&il, " ");
2033 iovlist_append(&il, structured_data == NULL ? "-" : structured_data);
2034 iovlist_append(&il, " ");
2035 iovlist_append(&il, msg);
2037 fprintlog_write(f, &il, flags);
2041 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name,
2042 const char *procid, const char *msg, int flags)
2046 int facility, priority;
2047 char timebuf[RFC3164_DATELEN + 1], facility_number[5],
2049 bool facility_found, priority_found;
2051 if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
2052 &f->f_lasttime.tm) == 0)
2056 switch (f->f_type) {
2058 /* Message forwarded over the network. */
2059 iovlist_append(&il, "<");
2060 snprintf(priority_number, sizeof(priority_number), "%d",
2062 iovlist_append(&il, priority_number);
2063 iovlist_append(&il, ">");
2064 iovlist_append(&il, timebuf);
2065 if (strcasecmp(hostname, LocalHostName) != 0) {
2066 iovlist_append(&il, " Forwarded from ");
2067 iovlist_append(&il, hostname);
2068 iovlist_append(&il, ":");
2070 iovlist_append(&il, " ");
2074 /* Message written to terminals. */
2075 iovlist_append(&il, "\r\n\aMessage from syslogd@");
2076 iovlist_append(&il, hostname);
2077 iovlist_append(&il, " at ");
2078 iovlist_append(&il, timebuf);
2079 iovlist_append(&il, " ...\r\n");
2083 /* Message written to files. */
2084 iovlist_append(&il, timebuf);
2085 iovlist_append(&il, " ");
2088 iovlist_append(&il, "<");
2090 facility = f->f_prevpri & LOG_FACMASK;
2091 facility_found = false;
2092 if (LogFacPri > 1) {
2093 for (c = facilitynames; c->c_name; c++) {
2094 if (c->c_val == facility) {
2095 iovlist_append(&il, c->c_name);
2096 facility_found = true;
2101 if (!facility_found) {
2102 snprintf(facility_number,
2103 sizeof(facility_number), "%d",
2105 iovlist_append(&il, facility_number);
2108 iovlist_append(&il, ".");
2110 priority = LOG_PRI(f->f_prevpri);
2111 priority_found = false;
2112 if (LogFacPri > 1) {
2113 for (c = prioritynames; c->c_name; c++) {
2114 if (c->c_val == priority) {
2115 iovlist_append(&il, c->c_name);
2116 priority_found = true;
2121 if (!priority_found) {
2122 snprintf(priority_number,
2123 sizeof(priority_number), "%d", priority);
2124 iovlist_append(&il, priority_number);
2127 iovlist_append(&il, "> ");
2130 iovlist_append(&il, hostname);
2131 iovlist_append(&il, " ");
2135 /* Message body with application name and process ID prefixed. */
2136 if (app_name != NULL) {
2137 iovlist_append(&il, app_name);
2138 if (procid != NULL) {
2139 iovlist_append(&il, "[");
2140 iovlist_append(&il, procid);
2141 iovlist_append(&il, "]");
2143 iovlist_append(&il, ": ");
2145 iovlist_append(&il, msg);
2147 fprintlog_write(f, &il, flags);
2151 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
2152 const char *procid, const char *msgid __unused,
2153 const char *structured_data __unused, const char *msg, int flags)
2156 dprintf("Logging to %s", TypeNames[f->f_type]);
2159 if (f->f_type == F_UNUSED) {
2164 if (RFC3164OutputFormat)
2165 fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags);
2167 fprintlog_rfc5424(f, hostname, app_name, procid, msgid,
2168 structured_data, msg, flags);
2172 * Prints a message to a log file that the previously logged message was
2173 * received multiple times.
2176 fprintlog_successive(struct filed *f, int flags)
2180 assert(f->f_prevcount > 0);
2181 snprintf(msg, sizeof(msg), "last message repeated %d times",
2183 fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
2188 * WALLMSG -- Write a message to the world at large
2190 * Write the specified message to either the entire
2191 * world, or a list of approved users.
2194 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
2196 static int reenter; /* avoid calling ourselves */
2205 while ((ut = getutxent()) != NULL) {
2206 if (ut->ut_type != USER_PROCESS)
2208 if (f->f_type == F_WALL) {
2209 if ((p = ttymsg(iov, iovlen, ut->ut_line,
2210 TTYMSGTIME)) != NULL) {
2211 errno = 0; /* already in msg */
2216 /* should we send the message to this user? */
2217 for (i = 0; i < MAXUNAMES; i++) {
2218 if (!f->fu_uname[i][0])
2220 if (!strcmp(f->fu_uname[i], ut->ut_user)) {
2221 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
2222 TTYMSGTIME)) != NULL) {
2223 errno = 0; /* already in msg */
2235 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
2238 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
2240 static char device[1024];
2241 static char errbuf[1024];
2244 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
2246 if (stat(device, &sb) < 0) {
2247 (void) snprintf(errbuf, sizeof(errbuf),
2248 "%s: %s", device, strerror(errno));
2251 if ((sb.st_mode & S_IWGRP) == 0)
2252 /* Messages disabled. */
2254 return ttymsg(iov, iovcnt, line, tmout);
2258 reapchild(int signo __unused)
2264 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
2265 /* First, look if it's a process from the dead queue. */
2266 if (deadq_removebypid(pid))
2269 /* Now, look in list of active processes. */
2270 STAILQ_FOREACH(f, &fhead, next) {
2271 if (f->f_type == F_PIPE &&
2272 f->fu_pipe_pid == pid) {
2274 log_deadchild(pid, status, f->fu_pipe_pname);
2283 * Return a printable representation of a host address.
2286 cvthname(struct sockaddr *f)
2289 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
2291 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
2292 error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
2295 dprintf("Malformed from address %s\n", gai_strerror(error));
2298 dprintf("cvthname(%s)\n", ip);
2303 error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
2304 NULL, 0, NI_NAMEREQD);
2306 dprintf("Host name for your address (%s) unknown\n", ip);
2310 if (hl > 0 && hname[hl-1] == '.')
2312 /* RFC 5424 prefers logging FQDNs. */
2313 if (RFC3164OutputFormat)
2314 trimdomain(hname, hl);
2326 domark(int signo __unused)
2333 * Print syslogd errors some place.
2336 logerror(const char *msg)
2339 static int recursed = 0;
2341 /* If there's an error while trying to log an error, give up. */
2346 (void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2351 dprintf("%s\n", buf);
2352 logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2361 struct socklist *sl;
2364 STAILQ_FOREACH(f, &fhead, next) {
2365 /* flush any pending output */
2367 fprintlog_successive(f, 0);
2368 if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
2372 dprintf("syslogd: exiting on signal %d\n", signo);
2373 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2377 STAILQ_FOREACH(sl, &shead, next) {
2378 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
2379 unlink(sl->sl_peer->pe_name);
2381 pidfile_remove(pfh);
2387 configfiles(const struct dirent *dp)
2392 if (dp->d_name[0] == '.')
2395 ext_len = sizeof(include_ext) -1;
2397 if (dp->d_namlen <= ext_len)
2400 p = &dp->d_name[dp->d_namlen - ext_len];
2401 if (strcmp(p, include_ext) != 0)
2408 readconfigfile(FILE *cf, int allow_includes)
2412 struct dirent **ent;
2413 char cline[LINE_MAX];
2414 char host[MAXHOSTNAMELEN];
2415 char prog[LINE_MAX];
2416 char file[MAXPATHLEN];
2417 char pfilter[LINE_MAX];
2423 * Foreach line in the conf table, open that file.
2425 include_len = sizeof(include_str) -1;
2426 (void)strlcpy(host, "*", sizeof(host));
2427 (void)strlcpy(prog, "*", sizeof(prog));
2428 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2429 while (fgets(cline, sizeof(cline), cf) != NULL) {
2431 * check for end-of-section, comments, strip off trailing
2432 * spaces and newline character. #!prog is treated specially:
2433 * following lines apply only to that program.
2435 for (p = cline; isspace(*p); ++p)
2439 if (allow_includes &&
2440 strncmp(p, include_str, include_len) == 0 &&
2441 isspace(p[include_len])) {
2446 while (*tmp != '\0' && !isspace(*tmp))
2449 dprintf("Trying to include files in '%s'\n", p);
2450 nents = scandir(p, &ent, configfiles, alphasort);
2452 dprintf("Unable to open '%s': %s\n", p,
2456 for (i = 0; i < nents; i++) {
2457 if (snprintf(file, sizeof(file), "%s/%s", p,
2458 ent[i]->d_name) >= (int)sizeof(file)) {
2459 dprintf("ignoring path too long: "
2460 "'%s/%s'\n", p, ent[i]->d_name);
2465 cf2 = fopen(file, "r");
2468 dprintf("reading %s\n", file);
2469 readconfigfile(cf2, 0);
2477 if (*p == '\0' || strchr("!+-:", *p) == NULL)
2480 if (*p == '+' || *p == '-') {
2484 if ((!*p) || (*p == '*')) {
2485 (void)strlcpy(host, "*", sizeof(host));
2490 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2491 if (!isalnum(*p) && *p != '.' && *p != '-'
2492 && *p != ',' && *p != ':' && *p != '%')
2501 while (isspace(*p)) p++;
2502 if ((!*p) || (*p == '*')) {
2503 (void)strlcpy(prog, "*", sizeof(prog));
2506 for (i = 0; i < LINE_MAX - 1; i++) {
2507 if (!isprint(p[i]) || isspace(p[i]))
2518 if ((!*p) || (*p == '*')) {
2519 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2522 (void)strlcpy(pfilter, p, sizeof(pfilter));
2525 for (p = cline + 1; *p != '\0'; p++) {
2528 if (*(p - 1) == '\\') {
2536 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2538 f = cfline(cline, prog, host, pfilter);
2546 sighandler(int signo)
2549 /* Send an wake-up signal to the select() loop. */
2550 write(sigpipe[1], &signo, sizeof(signo));
2554 * INIT -- Initialize syslogd from configuration table
2563 char oldLocalHostName[MAXHOSTNAMELEN];
2564 char hostMsg[2*MAXHOSTNAMELEN+40];
2565 char bootfileMsg[MAXLINE + 1];
2571 * Load hostname (may have changed).
2574 (void)strlcpy(oldLocalHostName, LocalHostName,
2575 sizeof(oldLocalHostName));
2576 if (gethostname(LocalHostName, sizeof(LocalHostName)))
2577 err(EX_OSERR, "gethostname() failed");
2578 if ((p = strchr(LocalHostName, '.')) != NULL) {
2579 /* RFC 5424 prefers logging FQDNs. */
2580 if (RFC3164OutputFormat)
2582 LocalDomain = p + 1;
2588 * Load / reload timezone data (in case it changed).
2590 * Just calling tzset() again does not work, the timezone code
2591 * caches the result. However, by setting the TZ variable, one
2592 * can defeat the caching and have the timezone code really
2593 * reload the timezone data. Respect any initial setting of
2594 * TZ, in case the system is configured specially.
2596 dprintf("loading timezone data via tzset()\n");
2600 setenv("TZ", ":/etc/localtime", 1);
2606 * Close all open log files.
2609 STAILQ_FOREACH(f, &fhead, next) {
2610 /* flush any pending output */
2612 fprintlog_successive(f, 0);
2614 switch (f->f_type) {
2622 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
2627 while(!STAILQ_EMPTY(&fhead)) {
2628 f = STAILQ_FIRST(&fhead);
2629 STAILQ_REMOVE_HEAD(&fhead, next);
2632 if (f->f_prop_filter) {
2633 switch (f->f_prop_filter->cmp_type) {
2634 case PROP_CMP_REGEX:
2635 regfree(f->f_prop_filter->pflt_re);
2636 free(f->f_prop_filter->pflt_re);
2638 case PROP_CMP_CONTAINS:
2639 case PROP_CMP_EQUAL:
2640 case PROP_CMP_STARTS:
2641 free(f->f_prop_filter->pflt_strval);
2644 free(f->f_prop_filter);
2649 /* open the configuration file */
2650 if ((cf = fopen(ConfFile, "r")) == NULL) {
2651 dprintf("cannot open %s\n", ConfFile);
2652 f = cfline("*.ERR\t/dev/console", "*", "*", "*");
2656 f = cfline("*.PANIC\t*", "*", "*", "*");
2665 readconfigfile(cf, 1);
2667 /* close the configuration file */
2674 STAILQ_FOREACH(f, &fhead, next) {
2675 for (i = 0; i <= LOG_NFACILITIES; i++)
2676 if (f->f_pmask[i] == INTERNAL_NOPRI)
2679 printf("%d ", f->f_pmask[i]);
2680 printf("%s: ", TypeNames[f->f_type]);
2681 switch (f->f_type) {
2683 printf("%s", f->fu_fname);
2688 printf("%s%s", _PATH_DEV, f->fu_fname);
2692 switch (f->fu_forw_addr->ai_family) {
2695 port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2700 port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2708 f->fu_forw_hname, port);
2710 printf("%s", f->fu_forw_hname);
2715 printf("%s", f->fu_pipe_pname);
2719 for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2720 printf("%s, ", f->fu_uname[i]);
2724 printf(" (%s)", f->f_program);
2729 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2730 NULL, NULL, "restart", 0);
2731 dprintf("syslogd: restarted\n");
2733 * Log a change in hostname, but only on a restart.
2735 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
2736 (void)snprintf(hostMsg, sizeof(hostMsg),
2737 "hostname changed, \"%s\" to \"%s\"",
2738 oldLocalHostName, LocalHostName);
2739 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2740 NULL, NULL, NULL, hostMsg, 0);
2741 dprintf("%s\n", hostMsg);
2744 * Log the kernel boot file if we aren't going to use it as
2745 * the prefix, and if this is *not* a restart.
2747 if (signo == 0 && !use_bootfile) {
2748 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2749 "kernel boot file is %s", bootfile);
2750 logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2751 NULL, NULL, NULL, bootfileMsg, 0);
2752 dprintf("%s\n", bootfileMsg);
2757 * Compile property-based filter.
2758 * Returns 0 on success, -1 otherwise.
2761 prop_filter_compile(struct prop_filter *pfilter, char *filter)
2763 char *filter_endpos, *p;
2764 char **ap, *argv[2] = {NULL, NULL};
2765 int re_flags = REG_NOSUB;
2768 bzero(pfilter, sizeof(struct prop_filter));
2771 * Here's some filter examples mentioned in syslog.conf(5)
2772 * 'msg, contains, ".*Deny.*"'
2773 * 'programname, regex, "^bird6?$"'
2774 * 'hostname, icase_ereregex, "^server-(dcA|podB)-rack1[0-9]{2}\\..*"'
2778 * Split filter into 3 parts: property name (argv[0]),
2779 * cmp type (argv[1]) and lvalue for comparison (filter).
2781 for (ap = argv; (*ap = strsep(&filter, ", \t\n")) != NULL;) {
2783 if (++ap >= &argv[2])
2787 if (argv[0] == NULL || argv[1] == NULL) {
2788 logerror("filter parse error");
2792 /* fill in prop_type */
2793 if (strcasecmp(argv[0], "msg") == 0)
2794 pfilter->prop_type = PROP_TYPE_MSG;
2795 else if(strcasecmp(argv[0], "hostname") == 0)
2796 pfilter->prop_type = PROP_TYPE_HOSTNAME;
2797 else if(strcasecmp(argv[0], "source") == 0)
2798 pfilter->prop_type = PROP_TYPE_HOSTNAME;
2799 else if(strcasecmp(argv[0], "programname") == 0)
2800 pfilter->prop_type = PROP_TYPE_PROGNAME;
2802 logerror("unknown property");
2806 /* full in cmp_flags (i.e. !contains, icase_regex, etc.) */
2807 if (*argv[1] == '!') {
2808 pfilter->cmp_flags |= PROP_FLAG_EXCLUDE;
2811 if (strncasecmp(argv[1], "icase_", (sizeof("icase_") - 1)) == 0) {
2812 pfilter->cmp_flags |= PROP_FLAG_ICASE;
2813 argv[1] += sizeof("icase_") - 1;
2816 /* fill in cmp_type */
2817 if (strcasecmp(argv[1], "contains") == 0)
2818 pfilter->cmp_type = PROP_CMP_CONTAINS;
2819 else if (strcasecmp(argv[1], "isequal") == 0)
2820 pfilter->cmp_type = PROP_CMP_EQUAL;
2821 else if (strcasecmp(argv[1], "startswith") == 0)
2822 pfilter->cmp_type = PROP_CMP_STARTS;
2823 else if (strcasecmp(argv[1], "regex") == 0)
2824 pfilter->cmp_type = PROP_CMP_REGEX;
2825 else if (strcasecmp(argv[1], "ereregex") == 0) {
2826 pfilter->cmp_type = PROP_CMP_REGEX;
2827 re_flags |= REG_EXTENDED;
2829 logerror("unknown cmp function");
2834 * Handle filter value
2838 /* remove leading whitespace and check for '"' next character */
2839 filter += strspn(filter, ", \t\n");
2840 if (*filter != '"' || strlen(filter) < 3) {
2841 logerror("property value parse error");
2847 /* process possible backslash (\") escaping */
2849 filter_endpos = filter;
2850 for (p = filter; *p != '\0'; p++) {
2851 if (*p == '\\' && !escaped) {
2853 /* do not shift filter_endpos */
2856 if (*p == '"' && !escaped) {
2860 /* we've seen some esc symbols, need to compress the line */
2861 if (filter_endpos != p)
2862 *filter_endpos = *p;
2868 *filter_endpos = '\0';
2871 /* We should not have anything but whitespace left after closing '"' */
2872 if (*p != '\0' && strspn(p, " \t\n") != strlen(p)) {
2873 logerror("property value parse error");
2877 if (pfilter->cmp_type == PROP_CMP_REGEX) {
2878 pfilter->pflt_re = calloc(1, sizeof(*pfilter->pflt_re));
2879 if (pfilter->pflt_re == NULL) {
2880 logerror("RE calloc() error");
2881 free(pfilter->pflt_re);
2884 if (pfilter->cmp_flags & PROP_FLAG_ICASE)
2885 re_flags |= REG_ICASE;
2886 if (regcomp(pfilter->pflt_re, filter, re_flags) != 0) {
2887 logerror("RE compilation error");
2888 free(pfilter->pflt_re);
2892 pfilter->pflt_strval = strdup(filter);
2893 pfilter->pflt_strlen = strlen(filter);
2901 * Crack a configuration file line
2903 static struct filed *
2904 cfline(const char *line, const char *prog, const char *host,
2905 const char *pfilter)
2908 struct addrinfo hints, *res;
2909 int error, i, pri, syncfile;
2911 char *bp, *pfilter_dup;
2912 char buf[LINE_MAX], ebuf[100];
2914 dprintf("cfline(\"%s\", f, \"%s\", \"%s\", \"%s\")\n", line, prog,
2917 f = calloc(1, sizeof(*f));
2922 errno = 0; /* keep strerror() stuff out of logerror messages */
2924 for (i = 0; i <= LOG_NFACILITIES; i++)
2925 f->f_pmask[i] = INTERNAL_NOPRI;
2927 /* save hostname if any */
2928 if (host && *host == '*')
2933 f->f_host = strdup(host);
2934 if (f->f_host == NULL) {
2938 hl = strlen(f->f_host);
2939 if (hl > 0 && f->f_host[hl-1] == '.')
2940 f->f_host[--hl] = '\0';
2941 /* RFC 5424 prefers logging FQDNs. */
2942 if (RFC3164OutputFormat)
2943 trimdomain(f->f_host, hl);
2946 /* save program name if any */
2947 if (prog && *prog == '*')
2950 f->f_program = strdup(prog);
2951 if (f->f_program == NULL) {
2958 f->f_prop_filter = calloc(1, sizeof(*(f->f_prop_filter)));
2959 if (f->f_prop_filter == NULL) {
2960 logerror("pfilter calloc");
2963 if (*pfilter == '*')
2964 f->f_prop_filter->prop_type = PROP_TYPE_NOOP;
2966 pfilter_dup = strdup(pfilter);
2967 if (pfilter_dup == NULL) {
2971 if (prop_filter_compile(f->f_prop_filter, pfilter_dup)) {
2972 logerror("filter compile error");
2978 /* scan through the list of selectors */
2979 for (p = line; *p && *p != '\t' && *p != ' ';) {
2984 /* find the end of this facility name list */
2985 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2988 /* get the priority comparison */
3016 /* collect priority name */
3017 for (bp = buf; *q && !strchr("\t,; ", *q); )
3022 while (strchr(",;", *q))
3025 /* decode priority name */
3028 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
3030 /* Ignore trailing spaces. */
3031 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
3034 pri = decode(buf, prioritynames);
3037 (void)snprintf(ebuf, sizeof ebuf,
3038 "unknown priority name \"%s\"", buf);
3045 pri_cmp = (UniquePriority)
3050 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
3052 /* scan facilities */
3053 while (*p && !strchr("\t.; ", *p)) {
3054 for (bp = buf; *p && !strchr("\t,;. ", *p); )
3059 for (i = 0; i < LOG_NFACILITIES; i++) {
3060 f->f_pmask[i] = pri;
3061 f->f_pcmp[i] = pri_cmp;
3064 i = decode(buf, facilitynames);
3067 (void)snprintf(ebuf, sizeof ebuf,
3068 "unknown facility name \"%s\"",
3074 f->f_pmask[i >> 3] = pri;
3075 f->f_pcmp[i >> 3] = pri_cmp;
3077 while (*p == ',' || *p == ' ')
3084 /* skip to action part */
3085 while (*p == '\t' || *p == ' ')
3100 * scan forward to see if there is a port defined.
3101 * so we can't use strlcpy..
3103 i = sizeof(f->fu_forw_hname);
3104 tp = f->fu_forw_hname;
3108 * an ipv6 address should start with a '[' in that case
3109 * we should scan for a ']'
3115 while (*p && (*p != endkey) && (i-- > 0)) {
3118 if (endkey == ']' && *p == endkey)
3122 /* See if we copied a domain and have a port */
3128 hints = (struct addrinfo){
3129 .ai_family = family,
3130 .ai_socktype = SOCK_DGRAM
3132 error = getaddrinfo(f->fu_forw_hname,
3133 p ? p : "syslog", &hints, &res);
3135 logerror(gai_strerror(error));
3138 f->fu_forw_addr = res;
3143 if ((f->f_file = open(p, logflags, 0600)) < 0) {
3144 f->f_type = F_UNUSED;
3149 f->f_flags |= FFLAG_SYNC;
3150 if (isatty(f->f_file)) {
3151 if (strcmp(p, ctty) == 0)
3152 f->f_type = F_CONSOLE;
3155 (void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
3156 sizeof(f->fu_fname));
3158 (void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
3165 (void)strlcpy(f->fu_pipe_pname, p + 1,
3166 sizeof(f->fu_pipe_pname));
3175 for (i = 0; i < MAXUNAMES && *p; i++) {
3176 for (q = p; *q && *q != ','; )
3178 (void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
3179 if ((q - p) >= MAXLOGNAME)
3180 f->fu_uname[i][MAXLOGNAME - 1] = '\0';
3182 f->fu_uname[i][q - p] = '\0';
3183 while (*q == ',' || *q == ' ')
3187 f->f_type = F_USERS;
3195 * Decode a symbolic name to a numeric value
3198 decode(const char *name, const CODE *codetab)
3204 return (atoi(name));
3206 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3208 *p = tolower(*name);
3213 for (c = codetab; c->c_name; c++)
3214 if (!strcmp(buf, c->c_name))
3224 struct deadq_entry *dq, *dq0;
3226 now = time((time_t *)NULL);
3227 MarkSeq += TIMERINTVL;
3228 if (MarkSeq >= MarkInterval) {
3229 logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
3230 "-- MARK --", MARK);
3234 STAILQ_FOREACH(f, &fhead, next) {
3235 if (f->f_prevcount && now >= REPEATTIME(f)) {
3236 dprintf("flush %s: repeated %d times, %d sec.\n",
3237 TypeNames[f->f_type], f->f_prevcount,
3238 repeatinterval[f->f_repeatcount]);
3239 fprintlog_successive(f, 0);
3244 /* Walk the dead queue, and see if we should signal somebody. */
3245 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
3246 switch (dq->dq_timeout) {
3248 /* Already signalled once, try harder now. */
3249 if (kill(dq->dq_pid, SIGKILL) != 0)
3250 (void)deadq_remove(dq);
3255 * Timed out on dead queue, send terminate
3256 * signal. Note that we leave the removal
3257 * from the dead queue to reapchild(), which
3258 * will also log the event (unless the process
3259 * didn't even really exist, in case we simply
3260 * drop it from the dead queue).
3262 if (kill(dq->dq_pid, SIGTERM) != 0)
3263 (void)deadq_remove(dq);
3272 (void)alarm(TIMERINTVL);
3276 * fork off and become a daemon, but wait for the child to come online
3277 * before returning to the parent, or we get disk thrashing at boot etc.
3278 * Set a timer so we don't hang forever if it wedges.
3281 waitdaemon(int maxwait)
3285 pid_t pid, childpid;
3287 switch (childpid = fork()) {
3293 signal(SIGALRM, timedout);
3295 while ((pid = wait3(&status, 0, NULL)) != -1) {
3296 if (WIFEXITED(status))
3297 errx(1, "child pid %d exited with return code %d",
3298 pid, WEXITSTATUS(status));
3299 if (WIFSIGNALED(status))
3300 errx(1, "child pid %d exited on signal %d%s",
3301 pid, WTERMSIG(status),
3302 WCOREDUMP(status) ? " (core dumped)" :
3304 if (pid == childpid) /* it's gone... */
3314 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
3315 (void)dup2(fd, STDIN_FILENO);
3316 (void)dup2(fd, STDOUT_FILENO);
3317 (void)dup2(fd, STDERR_FILENO);
3318 if (fd > STDERR_FILENO)
3325 * We get a SIGALRM from the child when it's running and finished doing it's
3326 * fsync()'s or O_SYNC writes for all the boot messages.
3328 * We also get a signal from the kernel if the timer expires, so check to
3329 * see what happened.
3332 timedout(int sig __unused)
3336 signal(SIGALRM, SIG_DFL);
3338 errx(1, "timed out waiting for child");
3344 * Add `s' to the list of allowable peer addresses to accept messages
3347 * `s' is a string in the form:
3349 * [*]domainname[:{servicename|portnumber|*}]
3353 * netaddr/maskbits[:{servicename|portnumber|*}]
3355 * Returns -1 on error, 0 if the argument was valid.
3358 #if defined(INET) || defined(INET6)
3361 allowaddr(char *s __unused)
3364 #if defined(INET) || defined(INET6)
3366 struct allowedpeer *ap;
3369 struct addrinfo hints, *res = NULL;
3371 in_addr_t *addrp, *maskp;
3374 uint32_t *addr6p, *mask6p;
3376 char ip[NI_MAXHOST];
3378 ap = calloc(1, sizeof(*ap));
3380 err(1, "malloc failed");
3383 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
3386 if ((cp1 = strrchr(cp1, ':'))) {
3387 /* service/port provided */
3389 if (strlen(cp1) == 1 && *cp1 == '*')
3390 /* any port allowed */
3392 else if ((se = getservbyname(cp1, "udp"))) {
3393 ap->port = ntohs(se->s_port);
3395 ap->port = strtol(cp1, &cp2, 0);
3396 /* port not numeric */
3401 if ((se = getservbyname("syslog", "udp")))
3402 ap->port = ntohs(se->s_port);
3404 /* sanity, should not happen */
3408 if ((cp1 = strchr(s, '/')) != NULL &&
3409 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
3411 if ((masklen = atoi(cp1 + 1)) < 0)
3416 cp2 = s + strlen(s) - 1;
3427 hints = (struct addrinfo){
3428 .ai_family = PF_UNSPEC,
3429 .ai_socktype = SOCK_DGRAM,
3430 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3432 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
3434 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
3435 ap->a_mask = (struct sockaddr_storage){
3436 .ss_family = res->ai_family,
3437 .ss_len = res->ai_addrlen
3439 switch (res->ai_family) {
3442 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
3443 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
3445 /* use default netmask */
3446 if (IN_CLASSA(ntohl(*addrp)))
3447 *maskp = htonl(IN_CLASSA_NET);
3448 else if (IN_CLASSB(ntohl(*addrp)))
3449 *maskp = htonl(IN_CLASSB_NET);
3451 *maskp = htonl(IN_CLASSC_NET);
3452 } else if (masklen == 0) {
3454 } else if (masklen <= 32) {
3455 /* convert masklen to netmask */
3456 *maskp = htonl(~((1 << (32 - masklen)) - 1));
3460 /* Lose any host bits in the network number. */
3471 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
3472 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
3473 /* convert masklen to netmask */
3474 while (masklen > 0) {
3477 htonl(~(0xffffffff >> masklen));
3481 *mask6p++ = 0xffffffff;
3493 /* arg `s' is domain name */
3505 STAILQ_INSERT_TAIL(&aphead, ap, next);
3508 printf("allowaddr: rule ");
3509 if (ap->isnumeric) {
3510 printf("numeric, ");
3511 getnameinfo(sstosa(&ap->a_addr),
3512 (sstosa(&ap->a_addr))->sa_len,
3513 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3514 printf("addr = %s, ", ip);
3515 getnameinfo(sstosa(&ap->a_mask),
3516 (sstosa(&ap->a_mask))->sa_len,
3517 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3518 printf("mask = %s; ", ip);
3520 printf("domainname = %s; ", ap->a_name);
3522 printf("port = %d\n", ap->port);
3535 * Validate that the remote peer has permission to log to us.
3538 validate(struct sockaddr *sa, const char *hname)
3541 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3542 struct allowedpeer *ap;
3544 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3547 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3549 struct addrinfo hints, *res;
3553 STAILQ_FOREACH(ap, &aphead, next) {
3556 dprintf("# of validation rule: %d\n", num);
3558 /* traditional behaviour, allow everything */
3561 (void)strlcpy(name, hname, sizeof(name));
3562 hints = (struct addrinfo){
3563 .ai_family = PF_UNSPEC,
3564 .ai_socktype = SOCK_DGRAM,
3565 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3567 if (getaddrinfo(name, NULL, &hints, &res) == 0)
3569 else if (strchr(name, '.') == NULL) {
3570 strlcat(name, ".", sizeof name);
3571 strlcat(name, LocalDomain, sizeof name);
3573 if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
3574 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3575 return (0); /* for safety, should not occur */
3576 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3580 /* now, walk down the list */
3582 STAILQ_FOREACH(ap, &aphead, next) {
3584 if (ap->port != 0 && ap->port != sport) {
3585 dprintf("rejected in rule %d due to port mismatch.\n",
3590 if (ap->isnumeric) {
3591 if (ap->a_addr.ss_family != sa->sa_family) {
3592 dprintf("rejected in rule %d due to address family mismatch.\n", i);
3596 else if (ap->a_addr.ss_family == AF_INET) {
3598 a4p = satosin(&ap->a_addr);
3599 m4p = satosin(&ap->a_mask);
3600 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3601 != a4p->sin_addr.s_addr) {
3602 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3608 else if (ap->a_addr.ss_family == AF_INET6) {
3609 sin6 = satosin6(sa);
3610 a6p = satosin6(&ap->a_addr);
3611 m6p = satosin6(&ap->a_mask);
3612 if (a6p->sin6_scope_id != 0 &&
3613 sin6->sin6_scope_id != a6p->sin6_scope_id) {
3614 dprintf("rejected in rule %d due to scope mismatch.\n", i);
3617 if (!IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3618 &a6p->sin6_addr, &m6p->sin6_addr)) {
3619 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3627 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3629 dprintf("rejected in rule %d due to name "
3634 dprintf("accepted in rule %d.\n", i);
3635 return (1); /* hooray! */
3641 * Fairly similar to popen(3), but returns an open descriptor, as
3642 * opposed to a FILE *.
3645 p_open(const char *prog, pid_t *rpid)
3647 int pfd[2], nulldesc;
3649 char *argv[4]; /* sh -c cmd NULL */
3652 if (pipe(pfd) == -1)
3654 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
3655 /* we are royally screwed anyway */
3658 switch ((pid = fork())) {
3664 (void)setsid(); /* Avoid catching SIGHUPs. */
3665 argv[0] = strdup("sh");
3666 argv[1] = strdup("-c");
3667 argv[2] = strdup(prog);
3669 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
3676 /* Restore signals marked as SIG_IGN. */
3677 (void)signal(SIGINT, SIG_DFL);
3678 (void)signal(SIGQUIT, SIG_DFL);
3679 (void)signal(SIGPIPE, SIG_DFL);
3681 dup2(pfd[0], STDIN_FILENO);
3682 dup2(nulldesc, STDOUT_FILENO);
3683 dup2(nulldesc, STDERR_FILENO);
3684 closefrom(STDERR_FILENO + 1);
3686 (void)execvp(_PATH_BSHELL, argv);
3692 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
3693 * supposed to get an EWOULDBLOCK on writev(2), which is
3694 * caught by the logic above anyway, which will in turn close
3695 * the pipe, and fork a new logging subprocess if necessary.
3696 * The stale subprocess will be killed some time later unless
3697 * it terminated itself due to closing its input pipe (so we
3698 * get rid of really dead puppies).
3700 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3702 (void)snprintf(errmsg, sizeof errmsg,
3703 "Warning: cannot change pipe to PID %d to "
3704 "non-blocking behaviour.",
3713 deadq_enter(pid_t pid, const char *name)
3715 struct deadq_entry *dq;
3721 * Be paranoid, if we can't signal the process, don't enter it
3722 * into the dead queue (perhaps it's already dead). If possible,
3723 * we try to fetch and log the child's status.
3725 if (kill(pid, 0) != 0) {
3726 if (waitpid(pid, &status, WNOHANG) > 0)
3727 log_deadchild(pid, status, name);
3731 dq = malloc(sizeof(*dq));
3736 *dq = (struct deadq_entry){
3738 .dq_timeout = DQ_TIMO_INIT
3740 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3744 deadq_remove(struct deadq_entry *dq)
3747 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3756 deadq_removebypid(pid_t pid)
3758 struct deadq_entry *dq;
3760 TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
3761 if (dq->dq_pid == pid)
3764 return (deadq_remove(dq));
3768 log_deadchild(pid_t pid, int status, const char *name)
3774 errno = 0; /* Keep strerror() stuff out of logerror messages. */
3775 if (WIFSIGNALED(status)) {
3776 reason = "due to signal";
3777 code = WTERMSIG(status);
3779 reason = "with status";
3780 code = WEXITSTATUS(status);
3784 (void)snprintf(buf, sizeof buf,
3785 "Logging subprocess %d (%s) exited %s %d.",
3786 pid, name, reason, code);
3791 socksetup(struct peer *pe)
3793 struct addrinfo hints, *res, *res0;
3796 int (*sl_recv)(struct socklist *);
3798 * We have to handle this case for backwards compatibility:
3799 * If there are two (or more) colons but no '[' and ']',
3800 * assume this is an inet6 address without a service.
3802 if (pe->pe_name != NULL) {
3804 if (pe->pe_name[0] == '[' &&
3805 (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
3806 pe->pe_name = &pe->pe_name[1];
3808 if (cp[1] == ':' && cp[2] != '\0')
3809 pe->pe_serv = cp + 2;
3812 cp = strchr(pe->pe_name, ':');
3813 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
3816 pe->pe_serv = cp + 1;
3817 if (cp == pe->pe_name)
3824 hints = (struct addrinfo){
3825 .ai_family = AF_UNSPEC,
3826 .ai_socktype = SOCK_DGRAM,
3827 .ai_flags = AI_PASSIVE
3829 if (pe->pe_name != NULL)
3830 dprintf("Trying peer: %s\n", pe->pe_name);
3831 if (pe->pe_serv == NULL)
3832 pe->pe_serv = "syslog";
3833 error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
3837 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
3838 pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
3839 gai_strerror(error));
3842 logerror(gai_strerror(error));
3848 for (res = res0; res != NULL; res = res->ai_next) {
3851 if (res->ai_family != AF_LOCAL &&
3853 /* Only AF_LOCAL in secure mode. */
3856 if (family != AF_UNSPEC &&
3857 res->ai_family != AF_LOCAL && res->ai_family != family)
3860 s = socket(res->ai_family, res->ai_socktype,
3868 if (res->ai_family == AF_INET6) {
3869 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
3870 &(int){1}, sizeof(int)) < 0) {
3871 logerror("setsockopt(IPV6_V6ONLY)");
3878 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
3879 &(int){1}, sizeof(int)) < 0) {
3880 logerror("setsockopt(SO_REUSEADDR)");
3887 * Bind INET and UNIX-domain sockets.
3889 * A UNIX-domain socket is always bound to a pathname
3890 * regardless of -N flag.
3892 * For INET sockets, RFC 3164 recommends that client
3893 * side message should come from the privileged syslogd port.
3895 * If the system administrator chooses not to obey
3896 * this, we can skip the bind() step so that the
3897 * system will choose a port for us.
3899 if (res->ai_family == AF_LOCAL)
3900 unlink(pe->pe_name);
3901 if (res->ai_family == AF_LOCAL ||
3902 NoBind == 0 || pe->pe_name != NULL) {
3903 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
3909 if (res->ai_family == AF_LOCAL ||
3913 if (res->ai_family == AF_LOCAL &&
3914 chmod(pe->pe_name, pe->pe_mode) < 0) {
3915 dprintf("chmod %s: %s\n", pe->pe_name,
3921 dprintf("new socket fd is %d\n", s);
3922 if (res->ai_socktype != SOCK_DGRAM) {
3925 sl_recv = socklist_recv_sock;
3926 #if defined(INET) || defined(INET6)
3927 if (SecureMode && (res->ai_family == AF_INET ||
3928 res->ai_family == AF_INET6)) {
3929 dprintf("shutdown\n");
3930 /* Forbid communication in secure mode. */
3931 if (shutdown(s, SHUT_RD) < 0 &&
3932 errno != ENOTCONN) {
3933 logerror("shutdown");
3940 dprintf("listening on socket\n");
3941 dprintf("sending on socket\n");
3942 addsock(res, &(struct socklist){
3954 increase_rcvbuf(int fd)
3958 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3959 &(socklen_t){sizeof(len)}) == 0) {
3960 if (len < RCVBUF_MINSIZE) {
3961 len = RCVBUF_MINSIZE;
3962 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));