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
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>
73 * syslogd -- log system messages
75 * This program implements a system log. It takes a series of lines.
76 * Each line may have a priority, signified as "<n>" as
77 * the first characters of the line. If this is
78 * not present, a default priority is used.
80 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
81 * cause it to reread its configuration file.
85 * MAXLINE -- the maximum line length that can be handled.
86 * DEFUPRI -- the default priority for user messages
87 * DEFSPRI -- the default priority for kernel messages
90 * extensive changes by Ralph Campbell
91 * more extensive changes by Eric Allman (again)
92 * Extension to log by program name as well as facility and priority
94 * -u and -v by Harlan Stenn.
95 * Priority comparison code by Harlan Stenn.
98 #define MAXLINE 8192 /* maximum line length */
99 #define MAXSVLINE MAXLINE /* maximum saved line length */
100 #define DEFUPRI (LOG_USER|LOG_NOTICE)
101 #define DEFSPRI (LOG_KERN|LOG_CRIT)
102 #define TIMERINTVL 30 /* interval for checking flush, mark */
103 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
104 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
106 #include <sys/param.h>
107 #include <sys/ioctl.h>
108 #include <sys/mman.h>
109 #include <sys/queue.h>
110 #include <sys/resource.h>
111 #include <sys/socket.h>
112 #include <sys/stat.h>
113 #include <sys/syslimits.h>
114 #include <sys/time.h>
117 #include <sys/wait.h>
119 #if defined(INET) || defined(INET6)
120 #include <netinet/in.h>
121 #include <arpa/inet.h>
141 #include <sysexits.h>
146 #include "pathnames.h"
150 #include <sys/syslog.h>
152 static const char *ConfFile = _PATH_LOGCONF;
153 static const char *PidFile = _PATH_LOGPID;
154 static const char ctty[] = _PATH_CONSOLE;
155 static const char include_str[] = "include";
156 static const char include_ext[] = ".conf";
158 #define dprintf if (Debug) printf
160 #define MAXUNAMES 20 /* maximum number of user names */
162 #define sstosa(ss) ((struct sockaddr *)(ss))
164 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss))
165 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa))
168 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss))
169 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa))
170 #define s6_addr32 __u6_addr.__u6_addr32
171 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \
172 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
173 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
174 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
175 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
178 * List of peers and sockets for binding.
184 STAILQ_ENTRY(peer) next;
186 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
189 struct addrinfo sl_ai;
190 #define sl_sa sl_ai.ai_addr
191 #define sl_salen sl_ai.ai_addrlen
192 #define sl_family sl_ai.ai_family
194 struct peer *sl_peer;
195 int (*sl_recv)(struct socklist *);
196 STAILQ_ENTRY(socklist) next;
198 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
204 #define IGN_CONS 0x001 /* don't print on console */
205 #define SYNC_FILE 0x002 /* do fsync on file after printing */
206 #define MARK 0x008 /* this message is a mark */
207 #define ISKERNEL 0x010 /* kernel generated message */
209 /* Timestamps of log entries. */
215 /* Traditional syslog timestamp format. */
216 #define RFC3164_DATELEN 15
217 #define RFC3164_DATEFMT "%b %e %H:%M:%S"
220 * This structure holds a property-based filter
225 #define PROP_TYPE_NOOP 0
226 #define PROP_TYPE_MSG 1
227 #define PROP_TYPE_HOSTNAME 2
228 #define PROP_TYPE_PROGNAME 3
231 #define PROP_CMP_CONTAINS 1
232 #define PROP_CMP_EQUAL 2
233 #define PROP_CMP_STARTS 3
234 #define PROP_CMP_REGEX 4
237 #define PROP_FLAG_EXCLUDE (1 << 0)
238 #define PROP_FLAG_ICASE (1 << 1)
244 #define pflt_strval pflt_uniptr.p_strval
245 #define pflt_re pflt_uniptr.p_re
251 F_UNUSED, /* unused entry */
252 F_FILE, /* regular file */
253 F_TTY, /* terminal */
254 F_CONSOLE, /* console terminal */
255 F_FORW, /* remote machine */
256 F_USERS, /* list of users */
257 F_WALL, /* everyone logged on */
258 F_PIPE, /* pipe to program */
262 * This structure represents the files that will have log
264 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
265 * or if f_type is F_PIPE and f_pid > 0.
269 STAILQ_ENTRY(filed) next; /* next in linked list */
271 int f_file; /* file descriptor */
272 time_t f_time; /* time this was last written */
273 char *f_host; /* host from which to recd. */
274 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
275 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
279 char *f_program; /* program this applies to */
280 struct prop_filter *f_prop_filter; /* property-based filter */
282 char f_uname[MAXUNAMES][MAXLOGNAME];
284 char f_hname[MAXHOSTNAMELEN];
285 struct addrinfo *f_addr;
287 } f_forw; /* forwarding address */
288 char f_fname[MAXPATHLEN];
290 char f_pname[MAXPATHLEN];
294 #define fu_uname f_un.f_uname
295 #define fu_forw_hname f_un.f_forw.f_hname
296 #define fu_forw_addr f_un.f_forw.f_addr
297 #define fu_fname f_un.f_fname
298 #define fu_pipe_pname f_un.f_pipe.f_pname
299 #define fu_pipe_pid f_un.f_pipe.f_pid
300 char f_prevline[MAXSVLINE]; /* last message logged */
301 struct logtime f_lasttime; /* time of last occurrence */
302 int f_prevpri; /* pri of f_prevline */
303 size_t f_prevlen; /* length of f_prevline */
304 int f_prevcount; /* repetition cnt of prevline */
305 u_int f_repeatcount; /* number of "repeated" msgs */
306 int f_flags; /* file-specific flags */
307 #define FFLAG_SYNC 0x01
308 #define FFLAG_NEEDSYNC 0x02
312 * Queue of about-to-be dead processes we should watch out for.
317 TAILQ_ENTRY(deadq_entry) dq_entries;
319 static TAILQ_HEAD(, deadq_entry) deadq_head =
320 TAILQ_HEAD_INITIALIZER(deadq_head);
323 * The timeout to apply to processes waiting on the dead queue. Unit
324 * of measure is `mark intervals', i.e. 20 minutes by default.
325 * Processes on the dead queue will be terminated after that time.
328 #define DQ_TIMO_INIT 2
331 * Struct to hold records of network addresses that are allowed to log
339 struct sockaddr_storage addr;
340 struct sockaddr_storage mask;
344 #define a_addr u.numeric.addr
345 #define a_mask u.numeric.mask
346 #define a_name u.name
347 STAILQ_ENTRY(allowedpeer) next;
349 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
353 * Intervals at which we flush out "message repeated" messages,
354 * in seconds after previous message is logged. After each flush,
355 * we move to the next interval until we reach the largest.
357 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
358 #define MAXREPEAT (nitems(repeatinterval) - 1)
359 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
360 #define BACKOFF(f) do { \
361 if (++(f)->f_repeatcount > MAXREPEAT) \
362 (f)->f_repeatcount = MAXREPEAT; \
365 static const char *TypeNames[] = {
366 "UNUSED", "FILE", "TTY", "CONSOLE",
367 "FORW", "USERS", "WALL", "PIPE"
370 static STAILQ_HEAD(, filed) fhead =
371 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */
372 static struct filed consfile; /* Console */
374 static int Debug; /* debug flag */
375 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
376 static int resolve = 1; /* resolve hostname */
377 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
378 static const char *LocalDomain; /* our local domain name */
379 static int Initialized; /* set when we have initialized ourselves */
380 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
381 static int MarkSeq; /* mark sequence number */
382 static int NoBind; /* don't bind() as suggested by RFC 3164 */
383 static int SecureMode; /* when true, receive only unix domain socks */
384 static int MaxForwardLen = 1024; /* max length of forwared message */
386 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
388 static int family = PF_INET; /* protocol family (IPv4 only) */
390 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
391 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
392 static int use_bootfile; /* log entire bootfile for every kern msg */
393 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
394 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
396 static char bootfile[MAXPATHLEN]; /* booted kernel file */
398 static int RemoteAddDate; /* Always set the date on remote messages */
399 static int RemoteHostname; /* Log remote hostname from the message */
401 static int UniquePriority; /* Only log specified priority? */
402 static int LogFacPri; /* Put facility and priority in log message: */
403 /* 0=no, 1=numeric, 2=names */
404 static int KeepKernFac; /* Keep remotely logged kernel facility */
405 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
406 static struct pidfh *pfh;
407 static int sigpipe[2]; /* Pipe to catch a signal during select(). */
408 static bool RFC3164OutputFormat = true; /* Use legacy format by default. */
410 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
414 static int allowaddr(char *);
415 static int addpeer(struct peer *);
416 static int addsock(struct addrinfo *, struct socklist *);
417 static void cfline(const char *, const char *, const char *, const char *);
418 static const char *cvthname(struct sockaddr *);
419 static void deadq_enter(pid_t, const char *);
420 static int deadq_remove(struct deadq_entry *);
421 static int deadq_removebypid(pid_t);
422 static int decode(const char *, const CODE *);
423 static void die(int) __dead2;
424 static void dodie(int);
425 static void dofsync(void);
426 static void domark(int);
427 static void fprintlog_first(struct filed *, const char *, const char *,
428 const char *, const char *, const char *, const char *, int);
429 static void fprintlog_write(struct filed *, struct iovlist *, int);
430 static void fprintlog_successive(struct filed *, int);
431 static void init(int);
432 static void logerror(const char *);
433 static void logmsg(int, const struct logtime *, const char *, const char *,
434 const char *, const char *, const char *, const char *, int);
435 static void log_deadchild(pid_t, int, const char *);
436 static void markit(void);
437 static int socksetup(struct peer *);
438 static int socklist_recv_file(struct socklist *);
439 static int socklist_recv_sock(struct socklist *);
440 static int socklist_recv_signal(struct socklist *);
441 static void sighandler(int);
442 static int skip_message(const char *, const char *, int);
443 static int evaluate_prop_filter(const struct prop_filter *filter,
445 static int prop_filter_compile(struct prop_filter *pfilter,
447 static void parsemsg(const char *, char *);
448 static void printsys(char *);
449 static int p_open(const char *, pid_t *);
450 static void reapchild(int);
451 static const char *ttymsg_check(struct iovec *, int, char *, int);
452 static void usage(void);
453 static int validate(struct sockaddr *, const char *);
454 static void unmapped(struct sockaddr *);
455 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
456 static int waitdaemon(int);
457 static void timedout(int);
458 static void increase_rcvbuf(int);
461 close_filed(struct filed *f)
464 if (f == NULL || f->f_file == -1)
469 if (f->fu_forw_addr != NULL) {
470 freeaddrinfo(f->fu_forw_addr);
471 f->fu_forw_addr = NULL;
477 f->f_type = F_UNUSED;
485 (void)close(f->f_file);
490 addpeer(struct peer *pe0)
494 pe = calloc(1, sizeof(*pe));
496 err(1, "malloc failed");
498 STAILQ_INSERT_TAIL(&pqueue, pe, next);
504 addsock(struct addrinfo *ai, struct socklist *sl0)
508 /* Copy *ai->ai_addr to the tail of struct socklist if any. */
509 sl = calloc(1, sizeof(*sl) + ((ai != NULL) ? ai->ai_addrlen : 0));
511 err(1, "malloc failed");
514 memcpy(&sl->sl_ai, ai, sizeof(*ai));
515 if (ai->ai_addrlen > 0) {
516 memcpy((sl + 1), ai->ai_addr, ai->ai_addrlen);
517 sl->sl_sa = (struct sockaddr *)(sl + 1);
521 STAILQ_INSERT_TAIL(&shead, sl, next);
527 main(int argc, char *argv[])
529 int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
531 struct timeval tv, *tvp;
534 pid_t ppid = 1, spid;
537 if (madvise(NULL, 0, MADV_PROTECT) != 0)
538 dprintf("madvise() failed: %s\n", strerror(errno));
540 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:M:m:nNoO:p:P:sS:Tuv"))
559 case 'a': /* allow specific network addresses only */
560 if (allowaddr(optarg) == -1)
565 p = strchr(optarg, ']');
567 p = strchr(p + 1, ':');
569 p = strchr(optarg, ':');
570 if (p != NULL && strchr(p + 1, ':') != NULL)
571 p = NULL; /* backward compatibility */
574 /* A hostname or filename only. */
575 addpeer(&(struct peer){
580 /* The case of "name:service". */
582 addpeer(&(struct peer){
584 .pe_name = (strlen(optarg) == 0) ?
595 case 'd': /* debug */
598 case 'f': /* configuration file */
601 case 'F': /* run in foreground instead of daemon */
607 case 'k': /* keep remote kern fac */
620 else if (ch == 'p') {
624 mode = S_IRUSR | S_IWUSR;
627 if (optarg[0] == '/')
629 else if ((name = strchr(optarg, ':')) != NULL) {
632 errx(1, "socket name must be absolute "
634 if (isdigit(*optarg)) {
635 perml = strtol(optarg, &ep, 8);
636 if (*ep || perml < 0 ||
637 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
638 errx(1, "invalid mode %s, exiting",
640 mode = (mode_t )perml;
642 errx(1, "invalid mode %s, exiting",
645 errx(1, "invalid filename %s, exiting",
647 addpeer(&(struct peer){
653 case 'M': /* max length of forwarded message */
654 MaxForwardLen = atoi(optarg);
655 if (MaxForwardLen < 480)
656 errx(1, "minimum length limit of forwarded "
657 "messages is 480 bytes");
659 case 'm': /* mark interval */
660 MarkInterval = atoi(optarg) * 60;
671 if (strcmp(optarg, "bsd") == 0 ||
672 strcmp(optarg, "rfc3164") == 0)
673 RFC3164OutputFormat = true;
674 else if (strcmp(optarg, "syslog") == 0 ||
675 strcmp(optarg, "rfc5424") == 0)
676 RFC3164OutputFormat = false;
683 case 'P': /* path for alt. PID */
686 case 's': /* no network mode */
692 case 'u': /* only log specified priority */
695 case 'v': /* log facility and priority */
701 if ((argc -= optind) != 0)
704 if (RFC3164OutputFormat && MaxForwardLen > 1024)
705 errx(1, "RFC 3164 messages may not exceed 1024 bytes");
707 /* Pipe to catch a signal during select(). */
708 s = pipe2(sigpipe, O_CLOEXEC);
710 err(1, "cannot open a pipe for signals");
712 addsock(NULL, &(struct socklist){
713 .sl_socket = sigpipe[0],
714 .sl_recv = socklist_recv_signal
718 /* Listen by default: /dev/klog. */
719 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
721 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
723 addsock(NULL, &(struct socklist){
725 .sl_recv = socklist_recv_file,
728 /* Listen by default: *:514 if no -b flag. */
730 addpeer(&(struct peer){
733 /* Listen by default: /var/run/log if no -p flag. */
735 addpeer(&(struct peer){
736 .pe_name = _PATH_LOG,
737 .pe_mode = DEFFILEMODE,
739 /* Listen by default: /var/run/logpriv if no -S flag. */
741 addpeer(&(struct peer){
742 .pe_name = _PATH_LOG_PRIV,
743 .pe_mode = S_IRUSR | S_IWUSR,
745 STAILQ_FOREACH(pe, &pqueue, next)
748 pfh = pidfile_open(PidFile, 0600, &spid);
751 errx(1, "syslogd already running, pid: %d", spid);
752 warn("cannot open pid file");
755 if ((!Foreground) && (!Debug)) {
756 ppid = waitdaemon(30);
758 warn("could not become daemon");
765 consfile.f_type = F_CONSOLE;
766 (void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
767 sizeof(consfile.fu_fname));
768 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
769 (void)signal(SIGTERM, dodie);
770 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
771 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
772 (void)signal(SIGHUP, sighandler);
773 (void)signal(SIGCHLD, sighandler);
774 (void)signal(SIGALRM, domark);
775 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
776 (void)alarm(TIMERINTVL);
778 /* tuck my process id away */
781 dprintf("off & running....\n");
784 tv.tv_sec = tv.tv_usec = 0;
786 STAILQ_FOREACH(sl, &shead, next) {
787 if (sl->sl_socket > fdsrmax)
788 fdsrmax = sl->sl_socket;
790 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
793 errx(1, "calloc fd_set");
796 if (Initialized == 0)
798 else if (WantInitialize)
799 init(WantInitialize);
801 reapchild(WantReapchild);
809 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
812 STAILQ_FOREACH(sl, &shead, next) {
813 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
814 FD_SET(sl->sl_socket, fdsr);
816 i = select(fdsrmax + 1, fdsr, NULL, NULL,
817 needdofsync ? &tv : tvp);
833 STAILQ_FOREACH(sl, &shead, next) {
834 if (FD_ISSET(sl->sl_socket, fdsr))
842 socklist_recv_signal(struct socklist *sl __unused)
847 if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
848 logerror("ioctl(FIONREAD)");
849 err(1, "signal pipe read failed");
851 nsig = i / sizeof(signo);
852 dprintf("# of received signals = %d\n", nsig);
853 for (i = 0; i < nsig; i++) {
854 len = read(sigpipe[0], &signo, sizeof(signo));
855 if (len != sizeof(signo)) {
856 logerror("signal pipe read failed");
857 err(1, "signal pipe read failed");
859 dprintf("Received signal: %d from fd=%d\n", signo,
874 socklist_recv_sock(struct socklist *sl)
876 struct sockaddr_storage ss;
877 struct sockaddr *sa = (struct sockaddr *)&ss;
880 char line[MAXLINE + 1];
884 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
885 dprintf("received sa_len = %d\n", sslen);
890 logerror("recvfrom");
893 /* Received valid data. */
895 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
896 hname = LocalHostName;
898 hname = cvthname(sa);
900 if (validate(sa, hname) == 0) {
901 dprintf("Message from %s was ignored.", hname);
905 parsemsg(hname, line);
911 unmapped(struct sockaddr *sa)
913 #if defined(INET) && defined(INET6)
914 struct sockaddr_in6 *sin6;
915 struct sockaddr_in sin;
918 sa->sa_family != AF_INET6 ||
919 sa->sa_len != sizeof(*sin6))
922 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
924 sin = (struct sockaddr_in){
925 .sin_family = AF_INET,
926 .sin_len = sizeof(sin),
927 .sin_port = sin6->sin6_port
929 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
930 sizeof(sin.sin_addr));
931 memcpy(sa, &sin, sizeof(sin));
943 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n"
944 " [-b bind_address] [-f config_file]\n"
945 " [-l [mode:]path] [-M fwd_length]\n"
946 " [-m mark_interval] [-O format] [-P pid_file]\n"
947 " [-p log_socket] [-S logpriv_socket]\n");
952 * Removes characters from log messages that are unsafe to display.
953 * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
956 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
962 while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
963 if (mask_C1 && (c & 0x80) && c < 0xA0) {
968 if (isascii(c) && iscntrl(c)) {
971 } else if (c == '\t') {
985 * Parses a syslog message according to RFC 5424, assuming that PRI and
986 * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
987 * parsed result is passed to logmsg().
990 parsemsg_rfc5424(const char *from, int pri, char *msg)
992 const struct logtime *timestamp;
993 struct logtime timestamp_remote;
994 const char *omsg, *hostname, *app_name, *procid, *msgid,
996 char line[MAXLINE + 1];
998 #define FAIL_IF(field, expr) do { \
1000 dprintf("Failed to parse " field " from %s: %s\n", \
1005 #define PARSE_CHAR(field, sep) do { \
1006 FAIL_IF(field, *msg != sep); \
1009 #define IF_NOT_NILVALUE(var) \
1010 if (msg[0] == '-' && msg[1] == ' ') { \
1013 } else if (msg[0] == '-' && msg[1] == '\0') { \
1019 IF_NOT_NILVALUE(timestamp) {
1020 /* Parse RFC 3339-like timestamp. */
1021 #define PARSE_NUMBER(dest, length, min, max) do { \
1025 for (i = 0; i < length; ++i) { \
1026 FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9'); \
1027 v = v * 10 + *msg++ - '0'; \
1029 FAIL_IF("TIMESTAMP", v < min || v > max); \
1032 /* Date and time. */
1033 memset(×tamp_remote, 0, sizeof(timestamp_remote));
1034 PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
1035 timestamp_remote.tm.tm_year -= 1900;
1036 PARSE_CHAR("TIMESTAMP", '-');
1037 PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
1038 --timestamp_remote.tm.tm_mon;
1039 PARSE_CHAR("TIMESTAMP", '-');
1040 PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
1041 PARSE_CHAR("TIMESTAMP", 'T');
1042 PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
1043 PARSE_CHAR("TIMESTAMP", ':');
1044 PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
1045 PARSE_CHAR("TIMESTAMP", ':');
1046 PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
1047 /* Perform normalization. */
1048 timegm(×tamp_remote.tm);
1049 /* Optional: fractional seconds. */
1050 if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
1054 for (i = 100000; i != 0; i /= 10) {
1055 if (*msg < '0' || *msg > '9')
1057 timestamp_remote.usec += (*msg++ - '0') * i;
1065 int sign, tz_hour, tz_min;
1067 /* Local time zone offset. */
1068 FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1069 sign = *msg++ == '-' ? -1 : 1;
1070 PARSE_NUMBER(tz_hour, 2, 0, 23);
1071 PARSE_CHAR("TIMESTAMP", ':');
1072 PARSE_NUMBER(tz_min, 2, 0, 59);
1073 timestamp_remote.tm.tm_gmtoff =
1074 sign * (tz_hour * 3600 + tz_min * 60);
1077 PARSE_CHAR("TIMESTAMP", ' ');
1078 timestamp = RemoteAddDate ? NULL : ×tamp_remote;
1081 /* String fields part of the HEADER. */
1082 #define PARSE_STRING(field, var) \
1083 IF_NOT_NILVALUE(var) { \
1085 while (*msg >= '!' && *msg <= '~') \
1087 FAIL_IF(field, var == msg); \
1088 PARSE_CHAR(field, ' '); \
1091 PARSE_STRING("HOSTNAME", hostname);
1092 if (hostname == NULL || !RemoteHostname)
1094 PARSE_STRING("APP-NAME", app_name);
1095 PARSE_STRING("PROCID", procid);
1096 PARSE_STRING("MSGID", msgid);
1099 /* Structured data. */
1100 #define PARSE_SD_NAME() do { \
1101 const char *start; \
1104 while (*msg >= '!' && *msg <= '~' && *msg != '=' && \
1105 *msg != ']' && *msg != '"') \
1107 FAIL_IF("STRUCTURED-NAME", start == msg); \
1109 IF_NOT_NILVALUE(structured_data) {
1110 structured_data = msg;
1112 while (*msg == '[') {
1117 while (*msg == ' ') {
1121 PARSE_CHAR("STRUCTURED-NAME", '=');
1122 PARSE_CHAR("STRUCTURED-NAME", '"');
1123 while (*msg != '"') {
1124 FAIL_IF("STRUCTURED-NAME",
1126 if (*msg++ == '\\') {
1127 FAIL_IF("STRUCTURED-NAME",
1134 PARSE_CHAR("STRUCTURED-NAME", ']');
1136 PARSE_CHAR("STRUCTURED-NAME", ' ');
1139 #undef PARSE_SD_NAME
1143 #undef IF_NOT_NILVALUE
1145 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1146 logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1147 structured_data, line, 0);
1151 * Returns the length of the application name ("TAG" in RFC 3164
1152 * terminology) and process ID from a message if present.
1155 parsemsg_rfc3164_get_app_name_procid(const char *msg, size_t *app_name_length_p,
1156 ptrdiff_t *procid_begin_offset_p, size_t *procid_length_p)
1158 const char *m, *procid_begin;
1159 size_t app_name_length, procid_length;
1163 /* Application name. */
1164 app_name_length = strspn(m,
1165 "abcdefghijklmnopqrstuvwxyz"
1166 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1169 if (app_name_length == 0)
1171 m += app_name_length;
1173 /* Process identifier (optional). */
1176 procid_length = strspn(m, "0123456789");
1177 if (procid_length == 0)
1183 procid_begin = NULL;
1188 if (m[0] != ':' || m[1] != ' ')
1191 *app_name_length_p = app_name_length;
1192 if (procid_begin_offset_p != NULL)
1193 *procid_begin_offset_p =
1194 procid_begin == NULL ? 0 : procid_begin - msg;
1195 if (procid_length_p != NULL)
1196 *procid_length_p = procid_length;
1199 *app_name_length_p = 0;
1200 if (procid_begin_offset_p != NULL)
1201 *procid_begin_offset_p = 0;
1202 if (procid_length_p != NULL)
1203 *procid_length_p = 0;
1207 * Trims the application name ("TAG" in RFC 3164 terminology) and
1208 * process ID from a message if present.
1211 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1212 const char **procid)
1214 char *m, *app_name_begin, *procid_begin;
1215 size_t app_name_length, procid_length;
1216 ptrdiff_t procid_begin_offset;
1221 parsemsg_rfc3164_get_app_name_procid(app_name_begin, &app_name_length,
1222 &procid_begin_offset, &procid_length);
1223 if (app_name_length == 0)
1225 procid_begin = procid_begin_offset == 0 ? NULL :
1226 app_name_begin + procid_begin_offset;
1228 /* Split strings from input. */
1229 app_name_begin[app_name_length] = '\0';
1230 m += app_name_length + 1;
1231 if (procid_begin != NULL) {
1232 procid_begin[procid_length] = '\0';
1233 m += procid_length + 2;
1237 *app_name = app_name_begin;
1238 *procid = procid_begin;
1246 * Parses a syslog message according to RFC 3164, assuming that PRI
1247 * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1248 * result is passed to logmsg().
1251 parsemsg_rfc3164(const char *from, int pri, char *msg)
1253 struct tm tm_parsed;
1254 const struct logtime *timestamp;
1255 struct logtime timestamp_remote;
1256 const char *app_name, *procid;
1258 char line[MAXLINE + 1];
1261 * Parse the TIMESTAMP provided by the remote side. If none is
1262 * found, assume this is not an RFC 3164 formatted message,
1263 * only containing a TAG and a MSG.
1266 if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) ==
1267 msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') {
1268 msg += RFC3164_DATELEN + 1;
1269 if (!RemoteAddDate) {
1275 * As the timestamp does not contain the year
1276 * number, daylight saving time information, nor
1277 * a time zone, attempt to infer it. Due to
1278 * clock skews, the timestamp may even be part
1279 * of the next year. Use the last year for which
1280 * the timestamp is at most one week in the
1283 * This loop can only run for at most three
1284 * iterations before terminating.
1287 localtime_r(&t_now, &tm_now);
1288 for (year = tm_now.tm_year + 1;; --year) {
1289 assert(year >= tm_now.tm_year - 1);
1290 timestamp_remote.tm = tm_parsed;
1291 timestamp_remote.tm.tm_year = year;
1292 timestamp_remote.tm.tm_isdst = -1;
1293 timestamp_remote.usec = 0;
1294 if (mktime(×tamp_remote.tm) <
1295 t_now + 7 * 24 * 60 * 60)
1298 timestamp = ×tamp_remote;
1302 * A single space character MUST also follow the HOSTNAME field.
1304 msglen = strlen(msg);
1305 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1306 if (msg[i] == ' ') {
1307 if (RemoteHostname) {
1315 * Support non RFC compliant messages, without hostname.
1320 if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1321 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1326 /* Remove the TAG, if present. */
1327 parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1328 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1329 logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1333 * Takes a raw input line, extracts PRI and determines whether the
1334 * message is formatted according to RFC 3164 or RFC 5424. Continues
1335 * parsing of addition fields in the message according to those
1336 * standards and prints the message on the appropriate log files.
1339 parsemsg(const char *from, char *msg)
1350 if (msg[0] == '<' && isdigit(msg[1])) {
1351 for (i = 2; i <= 4; i++) {
1352 if (msg[i] == '>') {
1354 n = strtol(msg + 1, &q, 10);
1355 if (errno == 0 && *q == msg[i] && n >= 0 && n <= INT_MAX) {
1365 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1369 * Don't allow users to log kernel messages.
1370 * NOTE: since LOG_KERN == 0 this will also match
1371 * messages with no facility specified.
1373 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1374 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1376 /* Parse VERSION. */
1377 if (i == 0 && msg[0] == '1' && msg[1] == ' ')
1378 parsemsg_rfc5424(from, pri, msg + 2);
1380 parsemsg_rfc3164(from, pri, msg);
1384 * Read /dev/klog while data are available, split into lines.
1387 socklist_recv_file(struct socklist *sl)
1389 char *p, *q, line[MAXLINE + 1];
1394 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1396 line[i + len] = '\0';
1398 if (i < 0 && errno != EINTR && errno != EAGAIN) {
1400 close(sl->sl_socket);
1406 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1411 if (len >= MAXLINE - 1) {
1416 memmove(line, p, len + 1);
1425 * Take a raw input line from /dev/klog, format similar to syslog().
1432 int flags, isprintf, pri;
1434 flags = ISKERNEL | SYNC_FILE; /* fsync after write */
1440 n = strtol(p + 1, &q, 10);
1441 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1448 * Kernel printf's and LOG_CONSOLE messages have been displayed
1449 * on the console already.
1451 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1453 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1455 logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1461 * Match a program or host name against a specification.
1462 * Return a non-0 value if the message must be ignored
1463 * based on the specification.
1466 skip_message(const char *name, const char *spec, int checkcase)
1471 /* Behaviour on explicit match */
1486 s = strstr (spec, name);
1488 s = strcasestr (spec, name);
1491 prev = (s == spec ? ',' : *(s - 1));
1492 next = *(s + strlen (name));
1494 if (prev == ',' && (next == '\0' || next == ','))
1495 /* Explicit match: skip iff the spec is an
1500 /* No explicit match for this name: skip the message iff
1501 the spec is an inclusive one. */
1506 * Match some property of the message against a filter.
1507 * Return a non-0 value if the message must be ignored
1508 * based on the filter.
1511 evaluate_prop_filter(const struct prop_filter *filter, const char *value)
1513 const char *s = NULL;
1514 const int exclude = ((filter->cmp_flags & PROP_FLAG_EXCLUDE) > 0);
1520 if (filter->cmp_type == PROP_CMP_REGEX) {
1521 if (regexec(filter->pflt_re, value, 0, NULL, 0) == 0)
1527 valuelen = strlen(value);
1529 /* a shortcut for equal with different length is always false */
1530 if (filter->cmp_type == PROP_CMP_EQUAL &&
1531 valuelen != filter->pflt_strlen)
1534 if (filter->cmp_flags & PROP_FLAG_ICASE)
1535 s = strcasestr(value, filter->pflt_strval);
1537 s = strstr(value, filter->pflt_strval);
1540 * PROP_CMP_CONTAINS true if s
1541 * PROP_CMP_STARTS true if s && s == value
1542 * PROP_CMP_EQUAL true if s && s == value &&
1543 * valuelen == filter->pflt_strlen
1544 * (and length match is checked
1548 switch (filter->cmp_type) {
1549 case PROP_CMP_STARTS:
1550 case PROP_CMP_EQUAL:
1554 case PROP_CMP_CONTAINS:
1561 /* unknown cmp_type */
1569 * Logs a message to the appropriate log files, users, etc. based on the
1570 * priority. Log messages are formatted according to RFC 3164 or
1571 * RFC 5424 in subsequent fprintlog_*() functions.
1574 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1575 const char *app_name, const char *procid, const char *msgid,
1576 const char *structured_data, const char *msg, int flags)
1579 struct logtime timestamp_now;
1583 char saved[MAXSVLINE], kernel_app_name[100];
1585 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1586 pri, flags, hostname, msg);
1588 (void)gettimeofday(&tv, NULL);
1590 if (timestamp == NULL) {
1591 localtime_r(&now, ×tamp_now.tm);
1592 timestamp_now.usec = tv.tv_usec;
1593 timestamp = ×tamp_now;
1596 /* extract facility and priority level */
1598 fac = LOG_NFACILITIES;
1602 /* Check maximum facility number. */
1603 if (fac > LOG_NFACILITIES)
1606 prilev = LOG_PRI(pri);
1609 * Lookup kernel app name from log prefix if present.
1610 * This is only used for local program specification matching.
1612 if (flags & ISKERNEL) {
1613 size_t kernel_app_name_length;
1615 parsemsg_rfc3164_get_app_name_procid(msg,
1616 &kernel_app_name_length, NULL, NULL);
1617 if (kernel_app_name_length != 0) {
1618 strlcpy(kernel_app_name, msg,
1619 MIN(sizeof(kernel_app_name),
1620 kernel_app_name_length + 1));
1622 kernel_app_name[0] = '\0';
1625 /* log the message to the particular outputs */
1629 * Open in non-blocking mode to avoid hangs during open
1630 * and close(waiting for the port to drain).
1632 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1634 if (f->f_file >= 0) {
1635 f->f_lasttime = *timestamp;
1636 fprintlog_first(f, hostname, app_name, procid, msgid,
1637 structured_data, msg, flags);
1645 * Store all of the fields of the message, except the timestamp,
1646 * in a single string. This string is used to detect duplicate
1649 assert(hostname != NULL);
1650 assert(msg != NULL);
1651 savedlen = snprintf(saved, sizeof(saved),
1652 "%d %s %s %s %s %s %s", pri, hostname,
1653 app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1654 msgid == NULL ? "-" : msgid,
1655 structured_data == NULL ? "-" : structured_data, msg);
1657 STAILQ_FOREACH(f, &fhead, next) {
1658 /* skip messages that are incorrect priority */
1659 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1660 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1661 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1663 || f->f_pmask[fac] == INTERNAL_NOPRI)
1666 /* skip messages with the incorrect hostname */
1667 if (skip_message(hostname, f->f_host, 0))
1670 /* skip messages with the incorrect program name */
1671 if (flags & ISKERNEL && kernel_app_name[0] != '\0') {
1672 if (skip_message(kernel_app_name, f->f_program, 1))
1674 } else if (skip_message(app_name == NULL ? "" : app_name,
1678 /* skip messages if a property does not match filter */
1679 if (f->f_prop_filter != NULL &&
1680 f->f_prop_filter->prop_type != PROP_TYPE_NOOP) {
1681 switch (f->f_prop_filter->prop_type) {
1683 if (evaluate_prop_filter(f->f_prop_filter,
1687 case PROP_TYPE_HOSTNAME:
1688 if (evaluate_prop_filter(f->f_prop_filter,
1692 case PROP_TYPE_PROGNAME:
1693 if (evaluate_prop_filter(f->f_prop_filter,
1694 app_name == NULL ? "" : app_name))
1702 /* skip message to console if it has already been printed */
1703 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1706 /* don't output marks to recently written files */
1707 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1711 * suppress duplicate lines to this file
1713 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1714 (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1715 strcmp(saved, f->f_prevline) == 0) {
1716 f->f_lasttime = *timestamp;
1718 dprintf("msg repeated %d times, %ld sec of %d\n",
1719 f->f_prevcount, (long)(now - f->f_time),
1720 repeatinterval[f->f_repeatcount]);
1722 * If domark would have logged this by now,
1723 * flush it now (so we don't hold isolated messages),
1724 * but back off so we'll flush less often
1727 if (now > REPEATTIME(f)) {
1728 fprintlog_successive(f, flags);
1732 /* new line, save it */
1734 fprintlog_successive(f, 0);
1735 f->f_repeatcount = 0;
1737 f->f_lasttime = *timestamp;
1738 static_assert(sizeof(f->f_prevline) == sizeof(saved),
1739 "Space to store saved line incorrect");
1740 (void)strcpy(f->f_prevline, saved);
1741 f->f_prevlen = savedlen;
1742 fprintlog_first(f, hostname, app_name, procid, msgid,
1743 structured_data, msg, flags);
1753 STAILQ_FOREACH(f, &fhead, next) {
1754 if ((f->f_type == F_FILE) &&
1755 (f->f_flags & FFLAG_NEEDSYNC)) {
1756 f->f_flags &= ~FFLAG_NEEDSYNC;
1757 (void)fsync(f->f_file);
1763 * List of iovecs to which entries can be appended.
1764 * Used for constructing the message to be logged.
1767 struct iovec iov[TTYMSG_IOV_MAX];
1773 iovlist_init(struct iovlist *il)
1781 iovlist_append(struct iovlist *il, const char *str)
1785 /* Discard components if we've run out of iovecs. */
1786 if (il->iovcnt < nitems(il->iov)) {
1788 il->iov[il->iovcnt++] = (struct iovec){
1789 .iov_base = __DECONST(char *, str),
1792 il->totalsize += size;
1796 #if defined(INET) || defined(INET6)
1798 iovlist_truncate(struct iovlist *il, size_t size)
1803 while (il->totalsize > size) {
1804 diff = il->totalsize - size;
1805 last = &il->iov[il->iovcnt - 1];
1806 if (diff >= last->iov_len) {
1807 /* Remove the last iovec entirely. */
1809 il->totalsize -= last->iov_len;
1811 /* Remove the last iovec partially. */
1812 last->iov_len -= diff;
1813 il->totalsize -= diff;
1820 fprintlog_write(struct filed *f, struct iovlist *il, int flags)
1822 struct msghdr msghdr;
1824 struct socklist *sl;
1828 switch (f->f_type) {
1830 dprintf(" %s", f->fu_forw_hname);
1831 switch (f->fu_forw_addr->ai_family) {
1835 ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1841 ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1848 #if defined(INET) || defined(INET6)
1849 /* Truncate messages to maximum forward length. */
1850 iovlist_truncate(il, MaxForwardLen);
1854 for (r = f->fu_forw_addr; r; r = r->ai_next) {
1855 memset(&msghdr, 0, sizeof(msghdr));
1856 msghdr.msg_name = r->ai_addr;
1857 msghdr.msg_namelen = r->ai_addrlen;
1858 msghdr.msg_iov = il->iov;
1859 msghdr.msg_iovlen = il->iovcnt;
1860 STAILQ_FOREACH(sl, &shead, next) {
1861 if (sl->sl_socket < 0)
1863 if (sl->sl_sa == NULL ||
1864 sl->sl_family == AF_UNSPEC ||
1865 sl->sl_family == AF_LOCAL)
1867 lsent = sendmsg(sl->sl_socket, &msghdr, 0);
1868 if (lsent == (ssize_t)il->totalsize)
1871 if (lsent == (ssize_t)il->totalsize && !send_to_all)
1874 dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize);
1875 if (lsent != (ssize_t)il->totalsize) {
1889 /* case ENOTSOCK: */
1891 /* case EMSGSIZE: */
1894 /* case ECONNREFUSED: */
1896 dprintf("removing entry: errno=%d\n", e);
1897 f->f_type = F_UNUSED;
1904 dprintf(" %s\n", f->fu_fname);
1905 iovlist_append(il, "\n");
1906 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1908 * If writev(2) fails for potentially transient errors
1909 * like the filesystem being full, ignore it.
1910 * Otherwise remove this logfile from the list.
1912 if (errno != ENOSPC) {
1916 logerror(f->fu_fname);
1918 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1919 f->f_flags |= FFLAG_NEEDSYNC;
1925 dprintf(" %s\n", f->fu_pipe_pname);
1926 iovlist_append(il, "\n");
1927 if (f->fu_pipe_pid == 0) {
1928 if ((f->f_file = p_open(f->fu_pipe_pname,
1929 &f->fu_pipe_pid)) < 0) {
1930 logerror(f->fu_pipe_pname);
1934 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1937 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1940 logerror(f->fu_pipe_pname);
1945 if (flags & IGN_CONS) {
1946 dprintf(" (ignored)\n");
1952 dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1953 iovlist_append(il, "\r\n");
1954 errno = 0; /* ttymsg() only sometimes returns an errno */
1955 if ((msgret = ttymsg(il->iov, il->iovcnt, f->fu_fname, 10))) {
1956 f->f_type = F_UNUSED;
1964 iovlist_append(il, "\r\n");
1965 wallmsg(f, il->iov, il->iovcnt);
1973 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name,
1974 const char *procid, const char *msgid, const char *structured_data,
1975 const char *msg, int flags)
1980 char timebuf[33], priority_number[5];
1983 if (f->f_type == F_WALL)
1984 iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n");
1985 iovlist_append(&il, "<");
1986 snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri);
1987 iovlist_append(&il, priority_number);
1988 iovlist_append(&il, ">1 ");
1989 if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z",
1990 &f->f_lasttime.tm) == sizeof(timebuf) - 2) {
1991 /* Add colon to the time zone offset, which %z doesn't do. */
1993 timebuf[31] = timebuf[30];
1994 timebuf[30] = timebuf[29];
1997 /* Overwrite space for microseconds with actual value. */
1998 usec = f->f_lasttime.usec;
1999 for (i = 25; i >= 20; --i) {
2000 timebuf[i] = usec % 10 + '0';
2003 iovlist_append(&il, timebuf);
2005 iovlist_append(&il, "-");
2006 iovlist_append(&il, " ");
2007 iovlist_append(&il, hostname);
2008 iovlist_append(&il, " ");
2009 iovlist_append(&il, app_name == NULL ? "-" : app_name);
2010 iovlist_append(&il, " ");
2011 iovlist_append(&il, procid == NULL ? "-" : procid);
2012 iovlist_append(&il, " ");
2013 iovlist_append(&il, msgid == NULL ? "-" : msgid);
2014 iovlist_append(&il, " ");
2015 iovlist_append(&il, structured_data == NULL ? "-" : structured_data);
2016 iovlist_append(&il, " ");
2017 iovlist_append(&il, msg);
2019 fprintlog_write(f, &il, flags);
2023 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name,
2024 const char *procid, const char *msg, int flags)
2028 int facility, priority;
2029 char timebuf[RFC3164_DATELEN + 1], facility_number[5],
2031 bool facility_found, priority_found;
2033 if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
2034 &f->f_lasttime.tm) == 0)
2038 switch (f->f_type) {
2040 /* Message forwarded over the network. */
2041 iovlist_append(&il, "<");
2042 snprintf(priority_number, sizeof(priority_number), "%d",
2044 iovlist_append(&il, priority_number);
2045 iovlist_append(&il, ">");
2046 iovlist_append(&il, timebuf);
2047 if (strcasecmp(hostname, LocalHostName) != 0) {
2048 iovlist_append(&il, " Forwarded from ");
2049 iovlist_append(&il, hostname);
2050 iovlist_append(&il, ":");
2052 iovlist_append(&il, " ");
2056 /* Message written to terminals. */
2057 iovlist_append(&il, "\r\n\aMessage from syslogd@");
2058 iovlist_append(&il, hostname);
2059 iovlist_append(&il, " at ");
2060 iovlist_append(&il, timebuf);
2061 iovlist_append(&il, " ...\r\n");
2065 /* Message written to files. */
2066 iovlist_append(&il, timebuf);
2067 iovlist_append(&il, " ");
2070 iovlist_append(&il, "<");
2072 facility = f->f_prevpri & LOG_FACMASK;
2073 facility_found = false;
2074 if (LogFacPri > 1) {
2075 for (c = facilitynames; c->c_name; c++) {
2076 if (c->c_val == facility) {
2077 iovlist_append(&il, c->c_name);
2078 facility_found = true;
2083 if (!facility_found) {
2084 snprintf(facility_number,
2085 sizeof(facility_number), "%d",
2087 iovlist_append(&il, facility_number);
2090 iovlist_append(&il, ".");
2092 priority = LOG_PRI(f->f_prevpri);
2093 priority_found = false;
2094 if (LogFacPri > 1) {
2095 for (c = prioritynames; c->c_name; c++) {
2096 if (c->c_val == priority) {
2097 iovlist_append(&il, c->c_name);
2098 priority_found = true;
2103 if (!priority_found) {
2104 snprintf(priority_number,
2105 sizeof(priority_number), "%d", priority);
2106 iovlist_append(&il, priority_number);
2109 iovlist_append(&il, "> ");
2112 iovlist_append(&il, hostname);
2113 iovlist_append(&il, " ");
2117 /* Message body with application name and process ID prefixed. */
2118 if (app_name != NULL) {
2119 iovlist_append(&il, app_name);
2120 if (procid != NULL) {
2121 iovlist_append(&il, "[");
2122 iovlist_append(&il, procid);
2123 iovlist_append(&il, "]");
2125 iovlist_append(&il, ": ");
2127 iovlist_append(&il, msg);
2129 fprintlog_write(f, &il, flags);
2133 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
2134 const char *procid, const char *msgid __unused,
2135 const char *structured_data __unused, const char *msg, int flags)
2138 dprintf("Logging to %s", TypeNames[f->f_type]);
2141 if (f->f_type == F_UNUSED) {
2146 if (RFC3164OutputFormat)
2147 fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags);
2149 fprintlog_rfc5424(f, hostname, app_name, procid, msgid,
2150 structured_data, msg, flags);
2154 * Prints a message to a log file that the previously logged message was
2155 * received multiple times.
2158 fprintlog_successive(struct filed *f, int flags)
2162 assert(f->f_prevcount > 0);
2163 snprintf(msg, sizeof(msg), "last message repeated %d times",
2165 fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
2170 * WALLMSG -- Write a message to the world at large
2172 * Write the specified message to either the entire
2173 * world, or a list of approved users.
2176 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
2178 static int reenter; /* avoid calling ourselves */
2187 while ((ut = getutxent()) != NULL) {
2188 if (ut->ut_type != USER_PROCESS)
2190 if (f->f_type == F_WALL) {
2191 if ((p = ttymsg(iov, iovlen, ut->ut_line,
2192 TTYMSGTIME)) != NULL) {
2193 errno = 0; /* already in msg */
2198 /* should we send the message to this user? */
2199 for (i = 0; i < MAXUNAMES; i++) {
2200 if (!f->fu_uname[i][0])
2202 if (!strcmp(f->fu_uname[i], ut->ut_user)) {
2203 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
2204 TTYMSGTIME)) != NULL) {
2205 errno = 0; /* already in msg */
2217 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
2220 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
2222 static char device[1024];
2223 static char errbuf[1024];
2226 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
2228 if (stat(device, &sb) < 0) {
2229 (void) snprintf(errbuf, sizeof(errbuf),
2230 "%s: %s", device, strerror(errno));
2233 if ((sb.st_mode & S_IWGRP) == 0)
2234 /* Messages disabled. */
2236 return ttymsg(iov, iovcnt, line, tmout);
2240 reapchild(int signo __unused)
2246 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
2247 /* First, look if it's a process from the dead queue. */
2248 if (deadq_removebypid(pid))
2251 /* Now, look in list of active processes. */
2252 STAILQ_FOREACH(f, &fhead, next) {
2253 if (f->f_type == F_PIPE &&
2254 f->fu_pipe_pid == pid) {
2256 log_deadchild(pid, status, f->fu_pipe_pname);
2265 * Return a printable representation of a host address.
2268 cvthname(struct sockaddr *f)
2271 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
2273 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
2274 error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
2277 dprintf("Malformed from address %s\n", gai_strerror(error));
2280 dprintf("cvthname(%s)\n", ip);
2285 error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
2286 NULL, 0, NI_NAMEREQD);
2288 dprintf("Host name for your address (%s) unknown\n", ip);
2292 if (hl > 0 && hname[hl-1] == '.')
2294 /* RFC 5424 prefers logging FQDNs. */
2295 if (RFC3164OutputFormat)
2296 trimdomain(hname, hl);
2308 domark(int signo __unused)
2315 * Print syslogd errors some place.
2318 logerror(const char *msg)
2321 static int recursed = 0;
2323 /* If there's an error while trying to log an error, give up. */
2328 (void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2333 dprintf("%s\n", buf);
2334 logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2343 struct socklist *sl;
2346 STAILQ_FOREACH(f, &fhead, next) {
2347 /* flush any pending output */
2349 fprintlog_successive(f, 0);
2350 if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
2354 dprintf("syslogd: exiting on signal %d\n", signo);
2355 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2359 STAILQ_FOREACH(sl, &shead, next) {
2360 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
2361 unlink(sl->sl_peer->pe_name);
2363 pidfile_remove(pfh);
2369 configfiles(const struct dirent *dp)
2374 if (dp->d_name[0] == '.')
2377 ext_len = sizeof(include_ext) -1;
2379 if (dp->d_namlen <= ext_len)
2382 p = &dp->d_name[dp->d_namlen - ext_len];
2383 if (strcmp(p, include_ext) != 0)
2390 parseconfigfile(FILE *cf, bool allow_includes)
2393 struct dirent **ent;
2394 char cline[LINE_MAX];
2395 char host[MAXHOSTNAMELEN];
2396 char prog[LINE_MAX];
2397 char file[MAXPATHLEN];
2398 char pfilter[LINE_MAX];
2404 * Foreach line in the conf table, open that file.
2406 include_len = sizeof(include_str) -1;
2407 (void)strlcpy(host, "*", sizeof(host));
2408 (void)strlcpy(prog, "*", sizeof(prog));
2409 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2410 while (fgets(cline, sizeof(cline), cf) != NULL) {
2412 * check for end-of-section, comments, strip off trailing
2413 * spaces and newline character. #!prog is treated specially:
2414 * following lines apply only to that program.
2416 for (p = cline; isspace(*p); ++p)
2420 if (allow_includes &&
2421 strncmp(p, include_str, include_len) == 0 &&
2422 isspace(p[include_len])) {
2427 while (*tmp != '\0' && !isspace(*tmp))
2430 dprintf("Trying to include files in '%s'\n", p);
2431 nents = scandir(p, &ent, configfiles, alphasort);
2433 dprintf("Unable to open '%s': %s\n", p,
2437 for (i = 0; i < nents; i++) {
2438 if (snprintf(file, sizeof(file), "%s/%s", p,
2439 ent[i]->d_name) >= (int)sizeof(file)) {
2440 dprintf("ignoring path too long: "
2441 "'%s/%s'\n", p, ent[i]->d_name);
2446 cf2 = fopen(file, "r");
2449 dprintf("reading %s\n", file);
2450 parseconfigfile(cf2, false);
2458 if (*p == '\0' || strchr("!+-:", *p) == NULL)
2461 if (*p == '+' || *p == '-') {
2465 if ((!*p) || (*p == '*')) {
2466 (void)strlcpy(host, "*", sizeof(host));
2471 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2472 if (!isalnum(*p) && *p != '.' && *p != '-'
2473 && *p != ',' && *p != ':' && *p != '%')
2482 while (isspace(*p)) p++;
2483 if ((!*p) || (*p == '*')) {
2484 (void)strlcpy(prog, "*", sizeof(prog));
2487 for (i = 0; i < LINE_MAX - 1; i++) {
2488 if (!isprint(p[i]) || isspace(p[i]))
2499 if ((!*p) || (*p == '*')) {
2500 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2503 (void)strlcpy(pfilter, p, sizeof(pfilter));
2506 for (p = cline + 1; *p != '\0'; p++) {
2509 if (*(p - 1) == '\\') {
2517 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2519 cfline(cline, prog, host, pfilter);
2524 readconfigfile(const char *path)
2528 if ((cf = fopen(path, "r")) != NULL) {
2529 parseconfigfile(cf, true);
2532 dprintf("cannot open %s\n", ConfFile);
2533 cfline("*.ERR\t/dev/console", "*", "*", "*");
2534 cfline("*.PANIC\t*", "*", "*", "*");
2539 sighandler(int signo)
2542 /* Send an wake-up signal to the select() loop. */
2543 write(sigpipe[1], &signo, sizeof(signo));
2547 * INIT -- Initialize syslogd from configuration table
2555 char oldLocalHostName[MAXHOSTNAMELEN];
2556 char hostMsg[2*MAXHOSTNAMELEN+40];
2557 char bootfileMsg[MAXLINE + 1];
2563 * Load hostname (may have changed).
2566 (void)strlcpy(oldLocalHostName, LocalHostName,
2567 sizeof(oldLocalHostName));
2568 if (gethostname(LocalHostName, sizeof(LocalHostName)))
2569 err(EX_OSERR, "gethostname() failed");
2570 if ((p = strchr(LocalHostName, '.')) != NULL) {
2571 /* RFC 5424 prefers logging FQDNs. */
2572 if (RFC3164OutputFormat)
2574 LocalDomain = p + 1;
2580 * Load / reload timezone data (in case it changed).
2582 * Just calling tzset() again does not work, the timezone code
2583 * caches the result. However, by setting the TZ variable, one
2584 * can defeat the caching and have the timezone code really
2585 * reload the timezone data. Respect any initial setting of
2586 * TZ, in case the system is configured specially.
2588 dprintf("loading timezone data via tzset()\n");
2592 setenv("TZ", ":/etc/localtime", 1);
2598 * Close all open log files.
2601 STAILQ_FOREACH(f, &fhead, next) {
2602 /* flush any pending output */
2604 fprintlog_successive(f, 0);
2606 switch (f->f_type) {
2614 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
2621 while(!STAILQ_EMPTY(&fhead)) {
2622 f = STAILQ_FIRST(&fhead);
2623 STAILQ_REMOVE_HEAD(&fhead, next);
2626 if (f->f_prop_filter) {
2627 switch (f->f_prop_filter->cmp_type) {
2628 case PROP_CMP_REGEX:
2629 regfree(f->f_prop_filter->pflt_re);
2630 free(f->f_prop_filter->pflt_re);
2632 case PROP_CMP_CONTAINS:
2633 case PROP_CMP_EQUAL:
2634 case PROP_CMP_STARTS:
2635 free(f->f_prop_filter->pflt_strval);
2638 free(f->f_prop_filter);
2643 readconfigfile(ConfFile);
2648 STAILQ_FOREACH(f, &fhead, next) {
2649 for (i = 0; i <= LOG_NFACILITIES; i++)
2650 if (f->f_pmask[i] == INTERNAL_NOPRI)
2653 printf("%d ", f->f_pmask[i]);
2654 printf("%s: ", TypeNames[f->f_type]);
2655 switch (f->f_type) {
2657 printf("%s", f->fu_fname);
2662 printf("%s%s", _PATH_DEV, f->fu_fname);
2666 switch (f->fu_forw_addr->ai_family) {
2669 port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2674 port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2682 f->fu_forw_hname, port);
2684 printf("%s", f->fu_forw_hname);
2689 printf("%s", f->fu_pipe_pname);
2693 for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2694 printf("%s, ", f->fu_uname[i]);
2700 printf(" (%s)", f->f_program);
2705 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2706 NULL, NULL, "restart", 0);
2707 dprintf("syslogd: restarted\n");
2709 * Log a change in hostname, but only on a restart.
2711 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
2712 (void)snprintf(hostMsg, sizeof(hostMsg),
2713 "hostname changed, \"%s\" to \"%s\"",
2714 oldLocalHostName, LocalHostName);
2715 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2716 NULL, NULL, NULL, hostMsg, 0);
2717 dprintf("%s\n", hostMsg);
2720 * Log the kernel boot file if we aren't going to use it as
2721 * the prefix, and if this is *not* a restart.
2723 if (signo == 0 && !use_bootfile) {
2724 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2725 "kernel boot file is %s", bootfile);
2726 logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2727 NULL, NULL, NULL, bootfileMsg, 0);
2728 dprintf("%s\n", bootfileMsg);
2733 * Compile property-based filter.
2734 * Returns 0 on success, -1 otherwise.
2737 prop_filter_compile(struct prop_filter *pfilter, char *filter)
2739 char *filter_endpos, *p;
2740 char **ap, *argv[2] = {NULL, NULL};
2741 int re_flags = REG_NOSUB;
2744 bzero(pfilter, sizeof(struct prop_filter));
2747 * Here's some filter examples mentioned in syslog.conf(5)
2748 * 'msg, contains, ".*Deny.*"'
2749 * 'programname, regex, "^bird6?$"'
2750 * 'hostname, icase_ereregex, "^server-(dcA|podB)-rack1[0-9]{2}\\..*"'
2754 * Split filter into 3 parts: property name (argv[0]),
2755 * cmp type (argv[1]) and lvalue for comparison (filter).
2757 for (ap = argv; (*ap = strsep(&filter, ", \t\n")) != NULL;) {
2759 if (++ap >= &argv[2])
2763 if (argv[0] == NULL || argv[1] == NULL) {
2764 logerror("filter parse error");
2768 /* fill in prop_type */
2769 if (strcasecmp(argv[0], "msg") == 0)
2770 pfilter->prop_type = PROP_TYPE_MSG;
2771 else if(strcasecmp(argv[0], "hostname") == 0)
2772 pfilter->prop_type = PROP_TYPE_HOSTNAME;
2773 else if(strcasecmp(argv[0], "source") == 0)
2774 pfilter->prop_type = PROP_TYPE_HOSTNAME;
2775 else if(strcasecmp(argv[0], "programname") == 0)
2776 pfilter->prop_type = PROP_TYPE_PROGNAME;
2778 logerror("unknown property");
2782 /* full in cmp_flags (i.e. !contains, icase_regex, etc.) */
2783 if (*argv[1] == '!') {
2784 pfilter->cmp_flags |= PROP_FLAG_EXCLUDE;
2787 if (strncasecmp(argv[1], "icase_", (sizeof("icase_") - 1)) == 0) {
2788 pfilter->cmp_flags |= PROP_FLAG_ICASE;
2789 argv[1] += sizeof("icase_") - 1;
2792 /* fill in cmp_type */
2793 if (strcasecmp(argv[1], "contains") == 0)
2794 pfilter->cmp_type = PROP_CMP_CONTAINS;
2795 else if (strcasecmp(argv[1], "isequal") == 0)
2796 pfilter->cmp_type = PROP_CMP_EQUAL;
2797 else if (strcasecmp(argv[1], "startswith") == 0)
2798 pfilter->cmp_type = PROP_CMP_STARTS;
2799 else if (strcasecmp(argv[1], "regex") == 0)
2800 pfilter->cmp_type = PROP_CMP_REGEX;
2801 else if (strcasecmp(argv[1], "ereregex") == 0) {
2802 pfilter->cmp_type = PROP_CMP_REGEX;
2803 re_flags |= REG_EXTENDED;
2805 logerror("unknown cmp function");
2810 * Handle filter value
2814 /* remove leading whitespace and check for '"' next character */
2815 filter += strspn(filter, ", \t\n");
2816 if (*filter != '"' || strlen(filter) < 3) {
2817 logerror("property value parse error");
2823 /* process possible backslash (\") escaping */
2825 filter_endpos = filter;
2826 for (p = filter; *p != '\0'; p++) {
2827 if (*p == '\\' && !escaped) {
2829 /* do not shift filter_endpos */
2832 if (*p == '"' && !escaped) {
2836 /* we've seen some esc symbols, need to compress the line */
2837 if (filter_endpos != p)
2838 *filter_endpos = *p;
2844 *filter_endpos = '\0';
2847 /* We should not have anything but whitespace left after closing '"' */
2848 if (*p != '\0' && strspn(p, " \t\n") != strlen(p)) {
2849 logerror("property value parse error");
2853 if (pfilter->cmp_type == PROP_CMP_REGEX) {
2854 pfilter->pflt_re = calloc(1, sizeof(*pfilter->pflt_re));
2855 if (pfilter->pflt_re == NULL) {
2856 logerror("RE calloc() error");
2857 free(pfilter->pflt_re);
2860 if (pfilter->cmp_flags & PROP_FLAG_ICASE)
2861 re_flags |= REG_ICASE;
2862 if (regcomp(pfilter->pflt_re, filter, re_flags) != 0) {
2863 logerror("RE compilation error");
2864 free(pfilter->pflt_re);
2868 pfilter->pflt_strval = strdup(filter);
2869 pfilter->pflt_strlen = strlen(filter);
2877 * Crack a configuration file line
2880 cfline(const char *line, const char *prog, const char *host,
2881 const char *pfilter)
2884 struct addrinfo hints, *res;
2885 int error, i, pri, syncfile;
2887 char *bp, *pfilter_dup;
2888 char buf[LINE_MAX], ebuf[100];
2890 dprintf("cfline(\"%s\", f, \"%s\", \"%s\", \"%s\")\n", line, prog,
2893 f = calloc(1, sizeof(*f));
2898 errno = 0; /* keep strerror() stuff out of logerror messages */
2900 for (i = 0; i <= LOG_NFACILITIES; i++)
2901 f->f_pmask[i] = INTERNAL_NOPRI;
2903 /* save hostname if any */
2904 if (host && *host == '*')
2909 f->f_host = strdup(host);
2910 if (f->f_host == NULL) {
2914 hl = strlen(f->f_host);
2915 if (hl > 0 && f->f_host[hl-1] == '.')
2916 f->f_host[--hl] = '\0';
2917 /* RFC 5424 prefers logging FQDNs. */
2918 if (RFC3164OutputFormat)
2919 trimdomain(f->f_host, hl);
2922 /* save program name if any */
2923 if (prog && *prog == '*')
2926 f->f_program = strdup(prog);
2927 if (f->f_program == NULL) {
2934 f->f_prop_filter = calloc(1, sizeof(*(f->f_prop_filter)));
2935 if (f->f_prop_filter == NULL) {
2936 logerror("pfilter calloc");
2939 if (*pfilter == '*')
2940 f->f_prop_filter->prop_type = PROP_TYPE_NOOP;
2942 pfilter_dup = strdup(pfilter);
2943 if (pfilter_dup == NULL) {
2947 if (prop_filter_compile(f->f_prop_filter, pfilter_dup)) {
2948 logerror("filter compile error");
2954 /* scan through the list of selectors */
2955 for (p = line; *p && *p != '\t' && *p != ' ';) {
2960 /* find the end of this facility name list */
2961 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2964 /* get the priority comparison */
2992 /* collect priority name */
2993 for (bp = buf; *q && !strchr("\t,; ", *q); )
2998 while (strchr(",;", *q))
3001 /* decode priority name */
3004 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
3006 /* Ignore trailing spaces. */
3007 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
3010 pri = decode(buf, prioritynames);
3013 (void)snprintf(ebuf, sizeof ebuf,
3014 "unknown priority name \"%s\"", buf);
3021 pri_cmp = (UniquePriority)
3026 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
3028 /* scan facilities */
3029 while (*p && !strchr("\t.; ", *p)) {
3030 for (bp = buf; *p && !strchr("\t,;. ", *p); )
3035 for (i = 0; i < LOG_NFACILITIES; i++) {
3036 f->f_pmask[i] = pri;
3037 f->f_pcmp[i] = pri_cmp;
3040 i = decode(buf, facilitynames);
3043 (void)snprintf(ebuf, sizeof ebuf,
3044 "unknown facility name \"%s\"",
3050 f->f_pmask[i >> 3] = pri;
3051 f->f_pcmp[i >> 3] = pri_cmp;
3053 while (*p == ',' || *p == ' ')
3060 /* skip to action part */
3061 while (*p == '\t' || *p == ' ')
3076 * scan forward to see if there is a port defined.
3077 * so we can't use strlcpy..
3079 i = sizeof(f->fu_forw_hname);
3080 tp = f->fu_forw_hname;
3084 * an ipv6 address should start with a '[' in that case
3085 * we should scan for a ']'
3091 while (*p && (*p != endkey) && (i-- > 0)) {
3094 if (endkey == ']' && *p == endkey)
3098 /* See if we copied a domain and have a port */
3104 hints = (struct addrinfo){
3105 .ai_family = family,
3106 .ai_socktype = SOCK_DGRAM
3108 error = getaddrinfo(f->fu_forw_hname,
3109 p ? p : "syslog", &hints, &res);
3111 logerror(gai_strerror(error));
3114 f->fu_forw_addr = res;
3119 if ((f->f_file = open(p, logflags, 0600)) < 0) {
3120 f->f_type = F_UNUSED;
3125 f->f_flags |= FFLAG_SYNC;
3126 if (isatty(f->f_file)) {
3127 if (strcmp(p, ctty) == 0)
3128 f->f_type = F_CONSOLE;
3131 (void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
3132 sizeof(f->fu_fname));
3134 (void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
3141 (void)strlcpy(f->fu_pipe_pname, p + 1,
3142 sizeof(f->fu_pipe_pname));
3151 for (i = 0; i < MAXUNAMES && *p; i++) {
3152 for (q = p; *q && *q != ','; )
3154 (void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
3155 if ((q - p) >= MAXLOGNAME)
3156 f->fu_uname[i][MAXLOGNAME - 1] = '\0';
3158 f->fu_uname[i][q - p] = '\0';
3159 while (*q == ',' || *q == ' ')
3163 f->f_type = F_USERS;
3166 STAILQ_INSERT_TAIL(&fhead, f, next);
3171 * Decode a symbolic name to a numeric value
3174 decode(const char *name, const CODE *codetab)
3180 return (atoi(name));
3182 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3184 *p = tolower(*name);
3189 for (c = codetab; c->c_name; c++)
3190 if (!strcmp(buf, c->c_name))
3200 struct deadq_entry *dq, *dq0;
3202 now = time((time_t *)NULL);
3203 MarkSeq += TIMERINTVL;
3204 if (MarkSeq >= MarkInterval) {
3205 logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
3206 "-- MARK --", MARK);
3210 STAILQ_FOREACH(f, &fhead, next) {
3211 if (f->f_prevcount && now >= REPEATTIME(f)) {
3212 dprintf("flush %s: repeated %d times, %d sec.\n",
3213 TypeNames[f->f_type], f->f_prevcount,
3214 repeatinterval[f->f_repeatcount]);
3215 fprintlog_successive(f, 0);
3220 /* Walk the dead queue, and see if we should signal somebody. */
3221 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
3222 switch (dq->dq_timeout) {
3224 /* Already signalled once, try harder now. */
3225 if (kill(dq->dq_pid, SIGKILL) != 0)
3226 (void)deadq_remove(dq);
3231 * Timed out on dead queue, send terminate
3232 * signal. Note that we leave the removal
3233 * from the dead queue to reapchild(), which
3234 * will also log the event (unless the process
3235 * didn't even really exist, in case we simply
3236 * drop it from the dead queue).
3238 if (kill(dq->dq_pid, SIGTERM) != 0)
3239 (void)deadq_remove(dq);
3248 (void)alarm(TIMERINTVL);
3252 * fork off and become a daemon, but wait for the child to come online
3253 * before returning to the parent, or we get disk thrashing at boot etc.
3254 * Set a timer so we don't hang forever if it wedges.
3257 waitdaemon(int maxwait)
3261 pid_t pid, childpid;
3263 switch (childpid = fork()) {
3269 signal(SIGALRM, timedout);
3271 while ((pid = wait3(&status, 0, NULL)) != -1) {
3272 if (WIFEXITED(status))
3273 errx(1, "child pid %d exited with return code %d",
3274 pid, WEXITSTATUS(status));
3275 if (WIFSIGNALED(status))
3276 errx(1, "child pid %d exited on signal %d%s",
3277 pid, WTERMSIG(status),
3278 WCOREDUMP(status) ? " (core dumped)" :
3280 if (pid == childpid) /* it's gone... */
3290 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
3291 (void)dup2(fd, STDIN_FILENO);
3292 (void)dup2(fd, STDOUT_FILENO);
3293 (void)dup2(fd, STDERR_FILENO);
3294 if (fd > STDERR_FILENO)
3301 * We get a SIGALRM from the child when it's running and finished doing it's
3302 * fsync()'s or O_SYNC writes for all the boot messages.
3304 * We also get a signal from the kernel if the timer expires, so check to
3305 * see what happened.
3308 timedout(int sig __unused)
3312 signal(SIGALRM, SIG_DFL);
3314 errx(1, "timed out waiting for child");
3320 * Add `s' to the list of allowable peer addresses to accept messages
3323 * `s' is a string in the form:
3325 * [*]domainname[:{servicename|portnumber|*}]
3329 * netaddr/maskbits[:{servicename|portnumber|*}]
3331 * Returns -1 on error, 0 if the argument was valid.
3334 #if defined(INET) || defined(INET6)
3337 allowaddr(char *s __unused)
3340 #if defined(INET) || defined(INET6)
3342 struct allowedpeer *ap;
3345 struct addrinfo hints, *res = NULL;
3347 in_addr_t *addrp, *maskp;
3350 uint32_t *addr6p, *mask6p;
3352 char ip[NI_MAXHOST];
3354 ap = calloc(1, sizeof(*ap));
3356 err(1, "malloc failed");
3359 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
3362 if ((cp1 = strrchr(cp1, ':'))) {
3363 /* service/port provided */
3365 if (strlen(cp1) == 1 && *cp1 == '*')
3366 /* any port allowed */
3368 else if ((se = getservbyname(cp1, "udp"))) {
3369 ap->port = ntohs(se->s_port);
3371 ap->port = strtol(cp1, &cp2, 0);
3372 /* port not numeric */
3377 if ((se = getservbyname("syslog", "udp")))
3378 ap->port = ntohs(se->s_port);
3380 /* sanity, should not happen */
3384 if ((cp1 = strchr(s, '/')) != NULL &&
3385 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
3387 if ((masklen = atoi(cp1 + 1)) < 0)
3392 cp2 = s + strlen(s) - 1;
3403 hints = (struct addrinfo){
3404 .ai_family = PF_UNSPEC,
3405 .ai_socktype = SOCK_DGRAM,
3406 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3408 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
3410 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
3411 ap->a_mask = (struct sockaddr_storage){
3412 .ss_family = res->ai_family,
3413 .ss_len = res->ai_addrlen
3415 switch (res->ai_family) {
3418 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
3419 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
3421 /* use default netmask */
3422 if (IN_CLASSA(ntohl(*addrp)))
3423 *maskp = htonl(IN_CLASSA_NET);
3424 else if (IN_CLASSB(ntohl(*addrp)))
3425 *maskp = htonl(IN_CLASSB_NET);
3427 *maskp = htonl(IN_CLASSC_NET);
3428 } else if (masklen == 0) {
3430 } else if (masklen <= 32) {
3431 /* convert masklen to netmask */
3432 *maskp = htonl(~((1 << (32 - masklen)) - 1));
3436 /* Lose any host bits in the network number. */
3447 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
3448 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
3449 /* convert masklen to netmask */
3450 while (masklen > 0) {
3453 htonl(~(0xffffffff >> masklen));
3457 *mask6p++ = 0xffffffff;
3469 /* arg `s' is domain name */
3481 STAILQ_INSERT_TAIL(&aphead, ap, next);
3484 printf("allowaddr: rule ");
3485 if (ap->isnumeric) {
3486 printf("numeric, ");
3487 getnameinfo(sstosa(&ap->a_addr),
3488 (sstosa(&ap->a_addr))->sa_len,
3489 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3490 printf("addr = %s, ", ip);
3491 getnameinfo(sstosa(&ap->a_mask),
3492 (sstosa(&ap->a_mask))->sa_len,
3493 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3494 printf("mask = %s; ", ip);
3496 printf("domainname = %s; ", ap->a_name);
3498 printf("port = %d\n", ap->port);
3511 * Validate that the remote peer has permission to log to us.
3514 validate(struct sockaddr *sa, const char *hname)
3517 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3518 struct allowedpeer *ap;
3520 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3523 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3525 struct addrinfo hints, *res;
3529 STAILQ_FOREACH(ap, &aphead, next) {
3532 dprintf("# of validation rule: %d\n", num);
3534 /* traditional behaviour, allow everything */
3537 (void)strlcpy(name, hname, sizeof(name));
3538 hints = (struct addrinfo){
3539 .ai_family = PF_UNSPEC,
3540 .ai_socktype = SOCK_DGRAM,
3541 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3543 if (getaddrinfo(name, NULL, &hints, &res) == 0)
3545 else if (strchr(name, '.') == NULL) {
3546 strlcat(name, ".", sizeof name);
3547 strlcat(name, LocalDomain, sizeof name);
3549 if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
3550 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3551 return (0); /* for safety, should not occur */
3552 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3556 /* now, walk down the list */
3558 STAILQ_FOREACH(ap, &aphead, next) {
3560 if (ap->port != 0 && ap->port != sport) {
3561 dprintf("rejected in rule %d due to port mismatch.\n",
3566 if (ap->isnumeric) {
3567 if (ap->a_addr.ss_family != sa->sa_family) {
3568 dprintf("rejected in rule %d due to address family mismatch.\n", i);
3572 else if (ap->a_addr.ss_family == AF_INET) {
3574 a4p = satosin(&ap->a_addr);
3575 m4p = satosin(&ap->a_mask);
3576 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3577 != a4p->sin_addr.s_addr) {
3578 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3584 else if (ap->a_addr.ss_family == AF_INET6) {
3585 sin6 = satosin6(sa);
3586 a6p = satosin6(&ap->a_addr);
3587 m6p = satosin6(&ap->a_mask);
3588 if (a6p->sin6_scope_id != 0 &&
3589 sin6->sin6_scope_id != a6p->sin6_scope_id) {
3590 dprintf("rejected in rule %d due to scope mismatch.\n", i);
3593 if (!IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3594 &a6p->sin6_addr, &m6p->sin6_addr)) {
3595 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3603 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3605 dprintf("rejected in rule %d due to name "
3610 dprintf("accepted in rule %d.\n", i);
3611 return (1); /* hooray! */
3617 * Fairly similar to popen(3), but returns an open descriptor, as
3618 * opposed to a FILE *.
3621 p_open(const char *prog, pid_t *rpid)
3623 int pfd[2], nulldesc;
3625 char *argv[4]; /* sh -c cmd NULL */
3628 if (pipe(pfd) == -1)
3630 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
3631 /* we are royally screwed anyway */
3634 switch ((pid = fork())) {
3640 (void)setsid(); /* Avoid catching SIGHUPs. */
3641 argv[0] = strdup("sh");
3642 argv[1] = strdup("-c");
3643 argv[2] = strdup(prog);
3645 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
3652 /* Restore signals marked as SIG_IGN. */
3653 (void)signal(SIGINT, SIG_DFL);
3654 (void)signal(SIGQUIT, SIG_DFL);
3655 (void)signal(SIGPIPE, SIG_DFL);
3657 dup2(pfd[0], STDIN_FILENO);
3658 dup2(nulldesc, STDOUT_FILENO);
3659 dup2(nulldesc, STDERR_FILENO);
3660 closefrom(STDERR_FILENO + 1);
3662 (void)execvp(_PATH_BSHELL, argv);
3668 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
3669 * supposed to get an EWOULDBLOCK on writev(2), which is
3670 * caught by the logic above anyway, which will in turn close
3671 * the pipe, and fork a new logging subprocess if necessary.
3672 * The stale subprocess will be killed some time later unless
3673 * it terminated itself due to closing its input pipe (so we
3674 * get rid of really dead puppies).
3676 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3678 (void)snprintf(errmsg, sizeof errmsg,
3679 "Warning: cannot change pipe to PID %d to "
3680 "non-blocking behaviour.",
3689 deadq_enter(pid_t pid, const char *name)
3691 struct deadq_entry *dq;
3697 * Be paranoid, if we can't signal the process, don't enter it
3698 * into the dead queue (perhaps it's already dead). If possible,
3699 * we try to fetch and log the child's status.
3701 if (kill(pid, 0) != 0) {
3702 if (waitpid(pid, &status, WNOHANG) > 0)
3703 log_deadchild(pid, status, name);
3707 dq = malloc(sizeof(*dq));
3712 *dq = (struct deadq_entry){
3714 .dq_timeout = DQ_TIMO_INIT
3716 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3720 deadq_remove(struct deadq_entry *dq)
3723 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3732 deadq_removebypid(pid_t pid)
3734 struct deadq_entry *dq;
3736 TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
3737 if (dq->dq_pid == pid)
3740 return (deadq_remove(dq));
3744 log_deadchild(pid_t pid, int status, const char *name)
3750 errno = 0; /* Keep strerror() stuff out of logerror messages. */
3751 if (WIFSIGNALED(status)) {
3752 reason = "due to signal";
3753 code = WTERMSIG(status);
3755 reason = "with status";
3756 code = WEXITSTATUS(status);
3760 (void)snprintf(buf, sizeof buf,
3761 "Logging subprocess %d (%s) exited %s %d.",
3762 pid, name, reason, code);
3767 socksetup(struct peer *pe)
3769 struct addrinfo hints, *res, *res0;
3772 int (*sl_recv)(struct socklist *);
3774 * We have to handle this case for backwards compatibility:
3775 * If there are two (or more) colons but no '[' and ']',
3776 * assume this is an inet6 address without a service.
3778 if (pe->pe_name != NULL) {
3780 if (pe->pe_name[0] == '[' &&
3781 (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
3782 pe->pe_name = &pe->pe_name[1];
3784 if (cp[1] == ':' && cp[2] != '\0')
3785 pe->pe_serv = cp + 2;
3788 cp = strchr(pe->pe_name, ':');
3789 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
3792 pe->pe_serv = cp + 1;
3793 if (cp == pe->pe_name)
3800 hints = (struct addrinfo){
3801 .ai_family = AF_UNSPEC,
3802 .ai_socktype = SOCK_DGRAM,
3803 .ai_flags = AI_PASSIVE
3805 if (pe->pe_name != NULL)
3806 dprintf("Trying peer: %s\n", pe->pe_name);
3807 if (pe->pe_serv == NULL)
3808 pe->pe_serv = "syslog";
3809 error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
3813 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
3814 pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
3815 gai_strerror(error));
3818 logerror(gai_strerror(error));
3824 for (res = res0; res != NULL; res = res->ai_next) {
3827 if (res->ai_family != AF_LOCAL &&
3829 /* Only AF_LOCAL in secure mode. */
3832 if (family != AF_UNSPEC &&
3833 res->ai_family != AF_LOCAL && res->ai_family != family)
3836 s = socket(res->ai_family, res->ai_socktype,
3844 if (res->ai_family == AF_INET6) {
3845 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
3846 &(int){1}, sizeof(int)) < 0) {
3847 logerror("setsockopt(IPV6_V6ONLY)");
3854 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
3855 &(int){1}, sizeof(int)) < 0) {
3856 logerror("setsockopt(SO_REUSEADDR)");
3863 * Bind INET and UNIX-domain sockets.
3865 * A UNIX-domain socket is always bound to a pathname
3866 * regardless of -N flag.
3868 * For INET sockets, RFC 3164 recommends that client
3869 * side message should come from the privileged syslogd port.
3871 * If the system administrator chooses not to obey
3872 * this, we can skip the bind() step so that the
3873 * system will choose a port for us.
3875 if (res->ai_family == AF_LOCAL)
3876 unlink(pe->pe_name);
3877 if (res->ai_family == AF_LOCAL ||
3878 NoBind == 0 || pe->pe_name != NULL) {
3879 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
3885 if (res->ai_family == AF_LOCAL ||
3889 if (res->ai_family == AF_LOCAL &&
3890 chmod(pe->pe_name, pe->pe_mode) < 0) {
3891 dprintf("chmod %s: %s\n", pe->pe_name,
3897 dprintf("new socket fd is %d\n", s);
3898 if (res->ai_socktype != SOCK_DGRAM) {
3901 sl_recv = socklist_recv_sock;
3902 #if defined(INET) || defined(INET6)
3903 if (SecureMode && (res->ai_family == AF_INET ||
3904 res->ai_family == AF_INET6)) {
3905 dprintf("shutdown\n");
3906 /* Forbid communication in secure mode. */
3907 if (shutdown(s, SHUT_RD) < 0 &&
3908 errno != ENOTCONN) {
3909 logerror("shutdown");
3916 dprintf("listening on socket\n");
3917 dprintf("sending on socket\n");
3918 addsock(res, &(struct socklist){
3930 increase_rcvbuf(int fd)
3934 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3935 &(socklen_t){sizeof(len)}) == 0) {
3936 if (len < RCVBUF_MINSIZE) {
3937 len = RCVBUF_MINSIZE;
3938 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));