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 /* Maximum number of characters in time of last occurrence */
101 #define MAXLINE 2048 /* maximum line length */
102 #define MAXSVLINE MAXLINE /* maximum saved line length */
103 #define DEFUPRI (LOG_USER|LOG_NOTICE)
104 #define DEFSPRI (LOG_KERN|LOG_CRIT)
105 #define TIMERINTVL 30 /* interval for checking flush, mark */
106 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
107 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
109 #include <sys/param.h>
110 #include <sys/ioctl.h>
111 #include <sys/mman.h>
112 #include <sys/queue.h>
113 #include <sys/resource.h>
114 #include <sys/socket.h>
115 #include <sys/stat.h>
116 #include <sys/syslimits.h>
117 #include <sys/time.h>
120 #include <sys/wait.h>
122 #if defined(INET) || defined(INET6)
123 #include <netinet/in.h>
124 #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 */
210 /* Timestamps of log entries. */
216 /* Traditional syslog timestamp format. */
217 #define RFC3164_DATELEN 15
218 #define RFC3164_DATEFMT "%b %e %H:%M:%S"
221 * This structure holds a property-based filter
226 #define PROP_TYPE_NOOP 0
227 #define PROP_TYPE_MSG 1
228 #define PROP_TYPE_HOSTNAME 2
229 #define PROP_TYPE_PROGNAME 3
232 #define PROP_CMP_CONTAINS 1
233 #define PROP_CMP_EQUAL 2
234 #define PROP_CMP_STARTS 3
235 #define PROP_CMP_REGEX 4
238 #define PROP_FLAG_EXCLUDE (1 << 0)
239 #define PROP_FLAG_ICASE (1 << 1)
245 #define pflt_strval pflt_uniptr.p_strval
246 #define pflt_re pflt_uniptr.p_re
252 * This structure represents the files that will have log
254 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
255 * or if f_type is F_PIPE and f_pid > 0.
259 STAILQ_ENTRY(filed) next; /* next in linked list */
260 short f_type; /* entry type, see below */
261 short f_file; /* file descriptor */
262 time_t f_time; /* time this was last written */
263 char *f_host; /* host from which to recd. */
264 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
265 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
269 char *f_program; /* program this applies to */
270 struct prop_filter *f_prop_filter; /* property-based filter */
272 char f_uname[MAXUNAMES][MAXLOGNAME];
274 char f_hname[MAXHOSTNAMELEN];
275 struct addrinfo *f_addr;
277 } f_forw; /* forwarding address */
278 char f_fname[MAXPATHLEN];
280 char f_pname[MAXPATHLEN];
284 #define fu_uname f_un.f_uname
285 #define fu_forw_hname f_un.f_forw.f_hname
286 #define fu_forw_addr f_un.f_forw.f_addr
287 #define fu_fname f_un.f_fname
288 #define fu_pipe_pname f_un.f_pipe.f_pname
289 #define fu_pipe_pid f_un.f_pipe.f_pid
290 char f_prevline[MAXSVLINE]; /* last message logged */
291 struct logtime f_lasttime; /* time of last occurrence */
292 int f_prevpri; /* pri of f_prevline */
293 size_t f_prevlen; /* length of f_prevline */
294 int f_prevcount; /* repetition cnt of prevline */
295 u_int f_repeatcount; /* number of "repeated" msgs */
296 int f_flags; /* file-specific flags */
297 #define FFLAG_SYNC 0x01
298 #define FFLAG_NEEDSYNC 0x02
302 * Queue of about-to-be dead processes we should watch out for.
307 TAILQ_ENTRY(deadq_entry) dq_entries;
309 static TAILQ_HEAD(, deadq_entry) deadq_head =
310 TAILQ_HEAD_INITIALIZER(deadq_head);
313 * The timeout to apply to processes waiting on the dead queue. Unit
314 * of measure is `mark intervals', i.e. 20 minutes by default.
315 * Processes on the dead queue will be terminated after that time.
318 #define DQ_TIMO_INIT 2
321 * Struct to hold records of network addresses that are allowed to log
329 struct sockaddr_storage addr;
330 struct sockaddr_storage mask;
334 #define a_addr u.numeric.addr
335 #define a_mask u.numeric.mask
336 #define a_name u.name
337 STAILQ_ENTRY(allowedpeer) next;
339 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
343 * Intervals at which we flush out "message repeated" messages,
344 * in seconds after previous message is logged. After each flush,
345 * we move to the next interval until we reach the largest.
347 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
348 #define MAXREPEAT (nitems(repeatinterval) - 1)
349 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
350 #define BACKOFF(f) do { \
351 if (++(f)->f_repeatcount > MAXREPEAT) \
352 (f)->f_repeatcount = MAXREPEAT; \
355 /* values for f_type */
356 #define F_UNUSED 0 /* unused entry */
357 #define F_FILE 1 /* regular file */
358 #define F_TTY 2 /* terminal */
359 #define F_CONSOLE 3 /* console terminal */
360 #define F_FORW 4 /* remote machine */
361 #define F_USERS 5 /* list of users */
362 #define F_WALL 6 /* everyone logged on */
363 #define F_PIPE 7 /* pipe to program */
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 */
385 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
387 static int family = PF_INET; /* protocol family (IPv4 only) */
389 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
390 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
391 static int use_bootfile; /* log entire bootfile for every kern msg */
392 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
393 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
395 static char bootfile[MAXLINE+1]; /* booted kernel file */
397 static int RemoteAddDate; /* Always set the date on remote messages */
398 static int RemoteHostname; /* Log remote hostname from the message */
400 static int UniquePriority; /* Only log specified priority? */
401 static int LogFacPri; /* Put facility and priority in log message: */
402 /* 0=no, 1=numeric, 2=names */
403 static int KeepKernFac; /* Keep remotely logged kernel facility */
404 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
405 static struct pidfh *pfh;
406 static int sigpipe[2]; /* Pipe to catch a signal during select(). */
407 static bool RFC3164OutputFormat = true; /* Use legacy format by default. */
409 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
413 static int allowaddr(char *);
414 static int addfile(struct filed *);
415 static int addpeer(struct peer *);
416 static int addsock(struct addrinfo *, struct socklist *);
417 static struct filed *cfline(const char *, const char *, const char *,
419 static const char *cvthname(struct sockaddr *);
420 static void deadq_enter(pid_t, const char *);
421 static int deadq_remove(struct deadq_entry *);
422 static int deadq_removebypid(pid_t);
423 static int decode(const char *, const CODE *);
424 static void die(int) __dead2;
425 static void dodie(int);
426 static void dofsync(void);
427 static void domark(int);
428 static void fprintlog_first(struct filed *, const char *, const char *,
429 const char *, const char *, const char *, const char *, int);
430 static void fprintlog_write(struct filed *, struct iovlist *, int);
431 static void fprintlog_successive(struct filed *, int);
432 static void init(int);
433 static void logerror(const char *);
434 static void logmsg(int, const struct logtime *, const char *, const char *,
435 const char *, const char *, const char *, const char *, int);
436 static void log_deadchild(pid_t, int, const char *);
437 static void markit(void);
438 static int socksetup(struct peer *);
439 static int socklist_recv_file(struct socklist *);
440 static int socklist_recv_sock(struct socklist *);
441 static int socklist_recv_signal(struct socklist *);
442 static void sighandler(int);
443 static int skip_message(const char *, const char *, int);
444 static int evaluate_prop_filter(const struct prop_filter *filter,
446 static int prop_filter_compile(struct prop_filter *pfilter,
448 static void parsemsg(const char *, char *);
449 static void printsys(char *);
450 static int p_open(const char *, pid_t *);
451 static void reapchild(int);
452 static const char *ttymsg_check(struct iovec *, int, char *, int);
453 static void usage(void);
454 static int validate(struct sockaddr *, const char *);
455 static void unmapped(struct sockaddr *);
456 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
457 static int waitdaemon(int);
458 static void timedout(int);
459 static void increase_rcvbuf(int);
462 close_filed(struct filed *f)
465 if (f == NULL || f->f_file == -1)
470 if (f->fu_forw_addr != NULL) {
471 freeaddrinfo(f->fu_forw_addr);
472 f->fu_forw_addr = NULL;
479 f->f_type = F_UNUSED;
485 (void)close(f->f_file);
490 addfile(struct filed *f0)
494 f = calloc(1, sizeof(*f));
496 err(1, "malloc failed");
498 STAILQ_INSERT_TAIL(&fhead, f, next);
504 addpeer(struct peer *pe0)
508 pe = calloc(1, sizeof(*pe));
510 err(1, "malloc failed");
512 STAILQ_INSERT_TAIL(&pqueue, pe, next);
518 addsock(struct addrinfo *ai, struct socklist *sl0)
522 /* Copy *ai->ai_addr to the tail of struct socklist if any. */
523 sl = calloc(1, sizeof(*sl) + ((ai != NULL) ? ai->ai_addrlen : 0));
525 err(1, "malloc failed");
528 memcpy(&sl->sl_ai, ai, sizeof(*ai));
529 if (ai->ai_addrlen > 0) {
530 memcpy((sl + 1), ai->ai_addr, ai->ai_addrlen);
531 sl->sl_sa = (struct sockaddr *)(sl + 1);
535 STAILQ_INSERT_TAIL(&shead, sl, next);
541 main(int argc, char *argv[])
543 int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
545 struct timeval tv, *tvp;
548 pid_t ppid = 1, spid;
551 if (madvise(NULL, 0, MADV_PROTECT) != 0)
552 dprintf("madvise() failed: %s\n", strerror(errno));
554 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:m:nNoO:p:P:sS:Tuv"))
573 case 'a': /* allow specific network addresses only */
574 if (allowaddr(optarg) == -1)
579 p = strchr(optarg, ']');
581 p = strchr(p + 1, ':');
583 p = strchr(optarg, ':');
584 if (p != NULL && strchr(p + 1, ':') != NULL)
585 p = NULL; /* backward compatibility */
588 /* A hostname or filename only. */
589 addpeer(&(struct peer){
594 /* The case of "name:service". */
596 addpeer(&(struct peer){
598 .pe_name = (strlen(optarg) == 0) ?
609 case 'd': /* debug */
612 case 'f': /* configuration file */
615 case 'F': /* run in foreground instead of daemon */
621 case 'k': /* keep remote kern fac */
634 else if (ch == 'p') {
638 mode = S_IRUSR | S_IWUSR;
641 if (optarg[0] == '/')
643 else if ((name = strchr(optarg, ':')) != NULL) {
646 errx(1, "socket name must be absolute "
648 if (isdigit(*optarg)) {
649 perml = strtol(optarg, &ep, 8);
650 if (*ep || perml < 0 ||
651 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
652 errx(1, "invalid mode %s, exiting",
654 mode = (mode_t )perml;
656 errx(1, "invalid mode %s, exiting",
659 errx(1, "invalid filename %s, exiting",
661 addpeer(&(struct peer){
667 case 'm': /* mark interval */
668 MarkInterval = atoi(optarg) * 60;
678 if (strcmp(optarg, "bsd") == 0 ||
679 strcmp(optarg, "rfc3164") == 0)
680 RFC3164OutputFormat = true;
681 else if (strcmp(optarg, "syslog") == 0 ||
682 strcmp(optarg, "rfc5424") == 0)
683 RFC3164OutputFormat = false;
690 case 'P': /* path for alt. PID */
693 case 's': /* no network mode */
699 case 'u': /* only log specified priority */
702 case 'v': /* log facility and priority */
708 if ((argc -= optind) != 0)
711 /* Pipe to catch a signal during select(). */
712 s = pipe2(sigpipe, O_CLOEXEC);
714 err(1, "cannot open a pipe for signals");
716 addsock(NULL, &(struct socklist){
717 .sl_socket = sigpipe[0],
718 .sl_recv = socklist_recv_signal
722 /* Listen by default: /dev/klog. */
723 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
725 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
727 addsock(NULL, &(struct socklist){
729 .sl_recv = socklist_recv_file,
732 /* Listen by default: *:514 if no -b flag. */
734 addpeer(&(struct peer){
737 /* Listen by default: /var/run/log if no -p flag. */
739 addpeer(&(struct peer){
740 .pe_name = _PATH_LOG,
741 .pe_mode = DEFFILEMODE,
743 /* Listen by default: /var/run/logpriv if no -S flag. */
745 addpeer(&(struct peer){
746 .pe_name = _PATH_LOG_PRIV,
747 .pe_mode = S_IRUSR | S_IWUSR,
749 STAILQ_FOREACH(pe, &pqueue, next)
752 pfh = pidfile_open(PidFile, 0600, &spid);
755 errx(1, "syslogd already running, pid: %d", spid);
756 warn("cannot open pid file");
759 if ((!Foreground) && (!Debug)) {
760 ppid = waitdaemon(30);
762 warn("could not become daemon");
769 consfile.f_type = F_CONSOLE;
770 (void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
771 sizeof(consfile.fu_fname));
772 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
773 (void)signal(SIGTERM, dodie);
774 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
775 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
776 (void)signal(SIGHUP, sighandler);
777 (void)signal(SIGCHLD, sighandler);
778 (void)signal(SIGALRM, domark);
779 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
780 (void)alarm(TIMERINTVL);
782 /* tuck my process id away */
785 dprintf("off & running....\n");
788 tv.tv_sec = tv.tv_usec = 0;
790 STAILQ_FOREACH(sl, &shead, next) {
791 if (sl->sl_socket > fdsrmax)
792 fdsrmax = sl->sl_socket;
794 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
797 errx(1, "calloc fd_set");
800 if (Initialized == 0)
802 else if (WantInitialize)
803 init(WantInitialize);
805 reapchild(WantReapchild);
813 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
816 STAILQ_FOREACH(sl, &shead, next) {
817 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
818 FD_SET(sl->sl_socket, fdsr);
820 i = select(fdsrmax + 1, fdsr, NULL, NULL,
821 needdofsync ? &tv : tvp);
837 STAILQ_FOREACH(sl, &shead, next) {
838 if (FD_ISSET(sl->sl_socket, fdsr))
846 socklist_recv_signal(struct socklist *sl __unused)
851 if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
852 logerror("ioctl(FIONREAD)");
853 err(1, "signal pipe read failed");
855 nsig = i / sizeof(signo);
856 dprintf("# of received signals = %d\n", nsig);
857 for (i = 0; i < nsig; i++) {
858 len = read(sigpipe[0], &signo, sizeof(signo));
859 if (len != sizeof(signo)) {
860 logerror("signal pipe read failed");
861 err(1, "signal pipe read failed");
863 dprintf("Received signal: %d from fd=%d\n", signo,
878 socklist_recv_sock(struct socklist *sl)
880 struct sockaddr_storage ss;
881 struct sockaddr *sa = (struct sockaddr *)&ss;
884 char line[MAXLINE + 1];
888 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
889 dprintf("received sa_len = %d\n", sslen);
894 logerror("recvfrom");
897 /* Received valid data. */
899 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
900 hname = LocalHostName;
902 hname = cvthname(sa);
904 if (validate(sa, hname) == 0) {
905 dprintf("Message from %s was ignored.", hname);
909 parsemsg(hname, line);
915 unmapped(struct sockaddr *sa)
917 #if defined(INET) && defined(INET6)
918 struct sockaddr_in6 *sin6;
919 struct sockaddr_in sin;
922 sa->sa_family != AF_INET6 ||
923 sa->sa_len != sizeof(*sin6))
926 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
928 sin = (struct sockaddr_in){
929 .sin_family = AF_INET,
930 .sin_len = sizeof(sin),
931 .sin_port = sin6->sin6_port
933 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
934 sizeof(sin.sin_addr));
935 memcpy(sa, &sin, sizeof(sin));
947 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n"
948 " [-b bind_address] [-f config_file]\n"
949 " [-l [mode:]path] [-m mark_interval]\n"
950 " [-O format] [-P pid_file] [-p log_socket]\n"
951 " [-S logpriv_socket]\n");
956 * Removes characters from log messages that are unsafe to display.
957 * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
960 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
966 while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
967 if (mask_C1 && (c & 0x80) && c < 0xA0) {
972 if (isascii(c) && iscntrl(c)) {
975 } else if (c == '\t') {
989 * Parses a syslog message according to RFC 5424, assuming that PRI and
990 * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
991 * parsed result is passed to logmsg().
994 parsemsg_rfc5424(const char *from, int pri, char *msg)
996 const struct logtime *timestamp;
997 struct logtime timestamp_remote;
998 const char *omsg, *hostname, *app_name, *procid, *msgid,
1000 char line[MAXLINE + 1];
1002 #define FAIL_IF(field, expr) do { \
1004 dprintf("Failed to parse " field " from %s: %s\n", \
1009 #define PARSE_CHAR(field, sep) do { \
1010 FAIL_IF(field, *msg != sep); \
1013 #define IF_NOT_NILVALUE(var) \
1014 if (msg[0] == '-' && msg[1] == ' ') { \
1017 } else if (msg[0] == '-' && msg[1] == '\0') { \
1023 IF_NOT_NILVALUE(timestamp) {
1024 /* Parse RFC 3339-like timestamp. */
1025 #define PARSE_NUMBER(dest, length, min, max) do { \
1029 for (i = 0; i < length; ++i) { \
1030 FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9'); \
1031 v = v * 10 + *msg++ - '0'; \
1033 FAIL_IF("TIMESTAMP", v < min || v > max); \
1036 /* Date and time. */
1037 memset(×tamp_remote, 0, sizeof(timestamp_remote));
1038 PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
1039 timestamp_remote.tm.tm_year -= 1900;
1040 PARSE_CHAR("TIMESTAMP", '-');
1041 PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
1042 --timestamp_remote.tm.tm_mon;
1043 PARSE_CHAR("TIMESTAMP", '-');
1044 PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
1045 PARSE_CHAR("TIMESTAMP", 'T');
1046 PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
1047 PARSE_CHAR("TIMESTAMP", ':');
1048 PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
1049 PARSE_CHAR("TIMESTAMP", ':');
1050 PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
1051 /* Perform normalization. */
1052 timegm(×tamp_remote.tm);
1053 /* Optional: fractional seconds. */
1054 if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
1058 for (i = 100000; i != 0; i /= 10) {
1059 if (*msg < '0' || *msg > '9')
1061 timestamp_remote.usec += (*msg++ - '0') * i;
1069 int sign, tz_hour, tz_min;
1071 /* Local time zone offset. */
1072 FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1073 sign = *msg++ == '-' ? -1 : 1;
1074 PARSE_NUMBER(tz_hour, 2, 0, 23);
1075 PARSE_CHAR("TIMESTAMP", ':');
1076 PARSE_NUMBER(tz_min, 2, 0, 59);
1077 timestamp_remote.tm.tm_gmtoff =
1078 sign * (tz_hour * 3600 + tz_min * 60);
1081 PARSE_CHAR("TIMESTAMP", ' ');
1082 timestamp = RemoteAddDate ? NULL : ×tamp_remote;
1085 /* String fields part of the HEADER. */
1086 #define PARSE_STRING(field, var) \
1087 IF_NOT_NILVALUE(var) { \
1089 while (*msg >= '!' && *msg <= '~') \
1091 FAIL_IF(field, var == msg); \
1092 PARSE_CHAR(field, ' '); \
1095 PARSE_STRING("HOSTNAME", hostname);
1096 if (hostname == NULL || !RemoteHostname)
1098 PARSE_STRING("APP-NAME", app_name);
1099 PARSE_STRING("PROCID", procid);
1100 PARSE_STRING("MSGID", msgid);
1103 /* Structured data. */
1104 #define PARSE_SD_NAME() do { \
1105 const char *start; \
1108 while (*msg >= '!' && *msg <= '~' && *msg != '=' && \
1109 *msg != ']' && *msg != '"') \
1111 FAIL_IF("STRUCTURED-NAME", start == msg); \
1113 IF_NOT_NILVALUE(structured_data) {
1115 while (*msg == '[') {
1120 while (*msg == ' ') {
1124 PARSE_CHAR("STRUCTURED-NAME", '=');
1125 PARSE_CHAR("STRUCTURED-NAME", '"');
1126 while (*msg != '"') {
1127 FAIL_IF("STRUCTURED-NAME",
1129 if (*msg++ == '\\') {
1130 FAIL_IF("STRUCTURED-NAME",
1137 PARSE_CHAR("STRUCTURED-NAME", ']');
1139 PARSE_CHAR("STRUCTURED-NAME", ' ');
1142 #undef PARSE_SD_NAME
1146 #undef IF_NOT_NILVALUE
1148 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1149 logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1150 structured_data, line, 0);
1154 * Trims the application name ("TAG" in RFC 3164 terminology) and
1155 * process ID from a message if present.
1158 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1159 const char **procid) {
1160 char *m, *app_name_begin, *procid_begin;
1161 size_t app_name_length, procid_length;
1165 /* Application name. */
1167 app_name_length = strspn(m,
1168 "abcdefghijklmnopqrstuvwxyz"
1169 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1172 if (app_name_length == 0)
1174 m += app_name_length;
1176 /* Process identifier (optional). */
1179 procid_length = strspn(m, "0123456789");
1180 if (procid_length == 0)
1186 procid_begin = NULL;
1191 if (m[0] != ':' || m[1] != ' ')
1194 /* Split strings from input. */
1195 app_name_begin[app_name_length] = '\0';
1196 if (procid_begin != 0)
1197 procid_begin[procid_length] = '\0';
1200 *app_name = app_name_begin;
1201 *procid = procid_begin;
1209 * Parses a syslog message according to RFC 3164, assuming that PRI
1210 * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1211 * result is passed to logmsg().
1214 parsemsg_rfc3164(const char *from, int pri, char *msg)
1216 struct tm tm_parsed;
1217 const struct logtime *timestamp;
1218 struct logtime timestamp_remote;
1219 const char *app_name, *procid;
1221 char line[MAXLINE + 1];
1224 * Parse the TIMESTAMP provided by the remote side. If none is
1225 * found, assume this is not an RFC 3164 formatted message,
1226 * only containing a TAG and a MSG.
1229 if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) ==
1230 msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') {
1231 msg += RFC3164_DATELEN + 1;
1232 if (!RemoteAddDate) {
1238 * As the timestamp does not contain the year
1239 * number, daylight saving time information, nor
1240 * a time zone, attempt to infer it. Due to
1241 * clock skews, the timestamp may even be part
1242 * of the next year. Use the last year for which
1243 * the timestamp is at most one week in the
1246 * This loop can only run for at most three
1247 * iterations before terminating.
1250 localtime_r(&t_now, &tm_now);
1251 for (year = tm_now.tm_year + 1;; --year) {
1252 assert(year >= tm_now.tm_year - 1);
1253 timestamp_remote.tm = tm_parsed;
1254 timestamp_remote.tm.tm_year = year;
1255 timestamp_remote.tm.tm_isdst = -1;
1256 timestamp_remote.usec = 0;
1257 if (mktime(×tamp_remote.tm) <
1258 t_now + 7 * 24 * 60 * 60)
1261 timestamp = ×tamp_remote;
1265 * A single space character MUST also follow the HOSTNAME field.
1267 msglen = strlen(msg);
1268 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1269 if (msg[i] == ' ') {
1270 if (RemoteHostname) {
1278 * Support non RFC compliant messages, without hostname.
1283 if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1284 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1289 /* Remove the TAG, if present. */
1290 parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1291 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1292 logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1296 * Takes a raw input line, extracts PRI and determines whether the
1297 * message is formatted according to RFC 3164 or RFC 5424. Continues
1298 * parsing of addition fields in the message according to those
1299 * standards and prints the message on the appropriate log files.
1302 parsemsg(const char *from, char *msg)
1310 if (msg[0] != '<' || !isdigit(msg[1])) {
1311 dprintf("Invalid PRI from %s\n", from);
1314 for (i = 2; i <= 4; i++) {
1317 if (!isdigit(msg[i])) {
1318 dprintf("Invalid PRI header from %s\n", from);
1322 if (msg[i] != '>') {
1323 dprintf("Invalid PRI header from %s\n", from);
1327 n = strtol(msg + 1, &q, 10);
1328 if (errno != 0 || *q != msg[i] || n < 0 || n >= INT_MAX) {
1329 dprintf("Invalid PRI %ld from %s: %s\n",
1330 n, from, strerror(errno));
1334 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1338 * Don't allow users to log kernel messages.
1339 * NOTE: since LOG_KERN == 0 this will also match
1340 * messages with no facility specified.
1342 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1343 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1345 /* Parse VERSION. */
1347 if (msg[0] == '1' && msg[1] == ' ')
1348 parsemsg_rfc5424(from, pri, msg + 2);
1350 parsemsg_rfc3164(from, pri, msg);
1354 * Read /dev/klog while data are available, split into lines.
1357 socklist_recv_file(struct socklist *sl)
1359 char *p, *q, line[MAXLINE + 1];
1364 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1366 line[i + len] = '\0';
1368 if (i < 0 && errno != EINTR && errno != EAGAIN) {
1370 close(sl->sl_socket);
1376 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1381 if (len >= MAXLINE - 1) {
1386 memmove(line, p, len + 1);
1395 * Take a raw input line from /dev/klog, format similar to syslog().
1402 int flags, isprintf, pri;
1404 flags = SYNC_FILE; /* fsync after write */
1410 n = strtol(p + 1, &q, 10);
1411 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1418 * Kernel printf's and LOG_CONSOLE messages have been displayed
1419 * on the console already.
1421 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1423 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1425 logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1431 * Match a program or host name against a specification.
1432 * Return a non-0 value if the message must be ignored
1433 * based on the specification.
1436 skip_message(const char *name, const char *spec, int checkcase)
1441 /* Behaviour on explicit match */
1456 s = strstr (spec, name);
1458 s = strcasestr (spec, name);
1461 prev = (s == spec ? ',' : *(s - 1));
1462 next = *(s + strlen (name));
1464 if (prev == ',' && (next == '\0' || next == ','))
1465 /* Explicit match: skip iff the spec is an
1470 /* No explicit match for this name: skip the message iff
1471 the spec is an inclusive one. */
1476 * Match some property of the message against a filter.
1477 * Return a non-0 value if the message must be ignored
1478 * based on the filter.
1481 evaluate_prop_filter(const struct prop_filter *filter, const char *value)
1483 const char *s = NULL;
1484 const int exclude = ((filter->cmp_flags & PROP_FLAG_EXCLUDE) > 0);
1490 if (filter->cmp_type == PROP_CMP_REGEX) {
1491 if (regexec(filter->pflt_re, value, 0, NULL, 0) == 0)
1497 valuelen = strlen(value);
1499 /* a shortcut for equal with different length is always false */
1500 if (filter->cmp_type == PROP_CMP_EQUAL &&
1501 valuelen != filter->pflt_strlen)
1504 if (filter->cmp_flags & PROP_FLAG_ICASE)
1505 s = strcasestr(value, filter->pflt_strval);
1507 s = strstr(value, filter->pflt_strval);
1510 * PROP_CMP_CONTAINS true if s
1511 * PROP_CMP_STARTS true if s && s == value
1512 * PROP_CMP_EQUAL true if s && s == value &&
1513 * valuelen == filter->pflt_strlen
1514 * (and length match is checked
1518 switch (filter->cmp_type) {
1519 case PROP_CMP_STARTS:
1520 case PROP_CMP_EQUAL:
1524 case PROP_CMP_CONTAINS:
1531 /* unknown cmp_type */
1539 * Logs a message to the appropriate log files, users, etc. based on the
1540 * priority. Log messages are always formatted according to RFC 3164,
1541 * even if they were in RFC 5424 format originally, The MSGID and
1542 * STRUCTURED-DATA fields are thus discarded for the time being.
1545 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1546 const char *app_name, const char *procid, const char *msgid,
1547 const char *structured_data, const char *msg, int flags)
1550 struct logtime timestamp_now;
1554 char saved[MAXSVLINE];
1556 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1557 pri, flags, hostname, msg);
1559 (void)gettimeofday(&tv, NULL);
1561 if (timestamp == NULL) {
1562 localtime_r(&now, ×tamp_now.tm);
1563 timestamp_now.usec = tv.tv_usec;
1564 timestamp = ×tamp_now;
1567 /* extract facility and priority level */
1569 fac = LOG_NFACILITIES;
1573 /* Check maximum facility number. */
1574 if (fac > LOG_NFACILITIES)
1577 prilev = LOG_PRI(pri);
1579 /* log the message to the particular outputs */
1583 * Open in non-blocking mode to avoid hangs during open
1584 * and close(waiting for the port to drain).
1586 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1588 if (f->f_file >= 0) {
1589 f->f_lasttime = *timestamp;
1590 fprintlog_first(f, hostname, app_name, procid, msgid,
1591 structured_data, msg, flags);
1599 * Store all of the fields of the message, except the timestamp,
1600 * in a single string. This string is used to detect duplicate
1603 assert(hostname != NULL);
1604 assert(msg != NULL);
1605 savedlen = snprintf(saved, sizeof(saved),
1606 "%d %s %s %s %s %s %s", pri, hostname,
1607 app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1608 msgid == NULL ? "-" : msgid,
1609 structured_data == NULL ? "-" : structured_data, msg);
1611 STAILQ_FOREACH(f, &fhead, next) {
1612 /* skip messages that are incorrect priority */
1613 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1614 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1615 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1617 || f->f_pmask[fac] == INTERNAL_NOPRI)
1620 /* skip messages with the incorrect hostname */
1621 if (skip_message(hostname, f->f_host, 0))
1624 /* skip messages with the incorrect program name */
1625 if (skip_message(app_name == NULL ? "" : app_name,
1629 /* skip messages if a property does not match filter */
1630 if (f->f_prop_filter != NULL &&
1631 f->f_prop_filter->prop_type != PROP_TYPE_NOOP) {
1632 switch (f->f_prop_filter->prop_type) {
1634 if (evaluate_prop_filter(f->f_prop_filter,
1638 case PROP_TYPE_HOSTNAME:
1639 if (evaluate_prop_filter(f->f_prop_filter,
1643 case PROP_TYPE_PROGNAME:
1644 if (evaluate_prop_filter(f->f_prop_filter,
1645 app_name == NULL ? "" : app_name))
1653 /* skip message to console if it has already been printed */
1654 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1657 /* don't output marks to recently written files */
1658 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1662 * suppress duplicate lines to this file
1664 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1665 (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1666 strcmp(saved, f->f_prevline) == 0) {
1667 f->f_lasttime = *timestamp;
1669 dprintf("msg repeated %d times, %ld sec of %d\n",
1670 f->f_prevcount, (long)(now - f->f_time),
1671 repeatinterval[f->f_repeatcount]);
1673 * If domark would have logged this by now,
1674 * flush it now (so we don't hold isolated messages),
1675 * but back off so we'll flush less often
1678 if (now > REPEATTIME(f)) {
1679 fprintlog_successive(f, flags);
1683 /* new line, save it */
1685 fprintlog_successive(f, 0);
1686 f->f_repeatcount = 0;
1688 f->f_lasttime = *timestamp;
1689 static_assert(sizeof(f->f_prevline) == sizeof(saved),
1690 "Space to store saved line incorrect");
1691 (void)strcpy(f->f_prevline, saved);
1692 f->f_prevlen = savedlen;
1693 fprintlog_first(f, hostname, app_name, procid, msgid,
1694 structured_data, msg, flags);
1704 STAILQ_FOREACH(f, &fhead, next) {
1705 if ((f->f_type == F_FILE) &&
1706 (f->f_flags & FFLAG_NEEDSYNC)) {
1707 f->f_flags &= ~FFLAG_NEEDSYNC;
1708 (void)fsync(f->f_file);
1714 * List of iovecs to which entries can be appended.
1715 * Used for constructing the message to be logged.
1718 struct iovec iov[TTYMSG_IOV_MAX];
1724 iovlist_init(struct iovlist *il)
1732 iovlist_append(struct iovlist *il, const char *str)
1736 /* Discard components if we've run out of iovecs. */
1737 if (il->iovcnt < nitems(il->iov)) {
1739 il->iov[il->iovcnt++] = (struct iovec){
1740 .iov_base = __DECONST(char *, str),
1743 il->totalsize += size;
1747 #if defined(INET) || defined(INET6)
1749 iovlist_truncate(struct iovlist *il, size_t size)
1754 while (il->totalsize > size) {
1755 diff = il->totalsize - size;
1756 last = &il->iov[il->iovcnt - 1];
1757 if (diff >= last->iov_len) {
1758 /* Remove the last iovec entirely. */
1760 il->totalsize -= last->iov_len;
1762 /* Remove the last iovec partially. */
1763 last->iov_len -= diff;
1764 il->totalsize -= diff;
1771 fprintlog_write(struct filed *f, struct iovlist *il, int flags)
1773 struct msghdr msghdr;
1775 struct socklist *sl;
1779 switch (f->f_type) {
1781 /* Truncate messages to RFC 5426 recommended size. */
1782 dprintf(" %s", f->fu_forw_hname);
1783 switch (f->fu_forw_addr->ai_family) {
1787 ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1788 iovlist_truncate(il, 480);
1794 ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1795 iovlist_truncate(il, 1180);
1803 for (r = f->fu_forw_addr; r; r = r->ai_next) {
1804 memset(&msghdr, 0, sizeof(msghdr));
1805 msghdr.msg_name = r->ai_addr;
1806 msghdr.msg_namelen = r->ai_addrlen;
1807 msghdr.msg_iov = il->iov;
1808 msghdr.msg_iovlen = il->iovcnt;
1809 STAILQ_FOREACH(sl, &shead, next) {
1810 if (sl->sl_socket < 0)
1812 if (sl->sl_sa != NULL &&
1813 (sl->sl_family == AF_LOCAL ||
1814 sl->sl_family == AF_UNSPEC))
1816 lsent = sendmsg(sl->sl_socket, &msghdr, 0);
1817 if (lsent == (ssize_t)il->totalsize)
1820 if (lsent == (ssize_t)il->totalsize && !send_to_all)
1823 dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize);
1824 if (lsent != (ssize_t)il->totalsize) {
1838 /* case ENOTSOCK: */
1840 /* case EMSGSIZE: */
1843 /* case ECONNREFUSED: */
1845 dprintf("removing entry: errno=%d\n", e);
1846 f->f_type = F_UNUSED;
1853 dprintf(" %s\n", f->fu_fname);
1854 iovlist_append(il, "\n");
1855 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1857 * If writev(2) fails for potentially transient errors
1858 * like the filesystem being full, ignore it.
1859 * Otherwise remove this logfile from the list.
1861 if (errno != ENOSPC) {
1865 logerror(f->fu_fname);
1867 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1868 f->f_flags |= FFLAG_NEEDSYNC;
1874 dprintf(" %s\n", f->fu_pipe_pname);
1875 iovlist_append(il, "\n");
1876 if (f->fu_pipe_pid == 0) {
1877 if ((f->f_file = p_open(f->fu_pipe_pname,
1878 &f->fu_pipe_pid)) < 0) {
1879 logerror(f->fu_pipe_pname);
1883 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1886 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1889 logerror(f->fu_pipe_pname);
1894 if (flags & IGN_CONS) {
1895 dprintf(" (ignored)\n");
1901 dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1902 iovlist_append(il, "\r\n");
1903 errno = 0; /* ttymsg() only sometimes returns an errno */
1904 if ((msgret = ttymsg(il->iov, il->iovcnt, f->fu_fname, 10))) {
1905 f->f_type = F_UNUSED;
1913 iovlist_append(il, "\r\n");
1914 wallmsg(f, il->iov, il->iovcnt);
1920 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name,
1921 const char *procid, const char *msgid, const char *structured_data,
1922 const char *msg, int flags)
1927 char timebuf[33], priority_number[5];
1930 if (f->f_type == F_WALL)
1931 iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n");
1932 iovlist_append(&il, "<");
1933 snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri);
1934 iovlist_append(&il, priority_number);
1935 iovlist_append(&il, ">1 ");
1936 if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z",
1937 &f->f_lasttime.tm) == sizeof(timebuf) - 2) {
1938 /* Add colon to the time zone offset, which %z doesn't do. */
1940 timebuf[31] = timebuf[30];
1941 timebuf[30] = timebuf[29];
1944 /* Overwrite space for microseconds with actual value. */
1945 usec = f->f_lasttime.usec;
1946 for (i = 25; i >= 20; --i) {
1947 timebuf[i] = usec % 10 + '0';
1950 iovlist_append(&il, timebuf);
1952 iovlist_append(&il, "-");
1953 iovlist_append(&il, " ");
1954 iovlist_append(&il, hostname);
1955 iovlist_append(&il, " ");
1956 iovlist_append(&il, app_name == NULL ? "-" : app_name);
1957 iovlist_append(&il, " ");
1958 iovlist_append(&il, procid == NULL ? "-" : procid);
1959 iovlist_append(&il, " ");
1960 iovlist_append(&il, msgid == NULL ? "-" : msgid);
1961 iovlist_append(&il, " ");
1962 iovlist_append(&il, structured_data == NULL ? "-" : structured_data);
1963 iovlist_append(&il, " ");
1964 iovlist_append(&il, msg);
1966 fprintlog_write(f, &il, flags);
1970 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name,
1971 const char *procid, const char *msg, int flags)
1975 int facility, priority;
1976 char timebuf[RFC3164_DATELEN + 1], facility_number[5],
1978 bool facility_found, priority_found;
1980 if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
1981 &f->f_lasttime.tm) == 0)
1985 switch (f->f_type) {
1987 /* Message forwarded over the network. */
1988 iovlist_append(&il, "<");
1989 snprintf(priority_number, sizeof(priority_number), "%d",
1991 iovlist_append(&il, priority_number);
1992 iovlist_append(&il, ">");
1993 iovlist_append(&il, timebuf);
1994 if (strcasecmp(hostname, LocalHostName) != 0) {
1995 iovlist_append(&il, " Forwarded from ");
1996 iovlist_append(&il, hostname);
1997 iovlist_append(&il, ":");
1999 iovlist_append(&il, " ");
2003 /* Message written to terminals. */
2004 iovlist_append(&il, "\r\n\aMessage from syslogd@");
2005 iovlist_append(&il, hostname);
2006 iovlist_append(&il, " at ");
2007 iovlist_append(&il, timebuf);
2008 iovlist_append(&il, " ...\r\n");
2012 /* Message written to files. */
2013 iovlist_append(&il, timebuf);
2014 iovlist_append(&il, " ");
2017 iovlist_append(&il, "<");
2019 facility = f->f_prevpri & LOG_FACMASK;
2020 facility_found = false;
2021 if (LogFacPri > 1) {
2022 for (c = facilitynames; c->c_name; c++) {
2023 if (c->c_val == facility) {
2024 iovlist_append(&il, c->c_name);
2025 facility_found = true;
2030 if (!facility_found) {
2031 snprintf(facility_number,
2032 sizeof(facility_number), "%d",
2034 iovlist_append(&il, facility_number);
2037 iovlist_append(&il, ".");
2039 priority = LOG_PRI(f->f_prevpri);
2040 priority_found = false;
2041 if (LogFacPri > 1) {
2042 for (c = prioritynames; c->c_name; c++) {
2043 if (c->c_val == priority) {
2044 iovlist_append(&il, c->c_name);
2045 priority_found = true;
2050 if (!priority_found) {
2051 snprintf(priority_number,
2052 sizeof(priority_number), "%d", priority);
2053 iovlist_append(&il, priority_number);
2056 iovlist_append(&il, "> ");
2059 iovlist_append(&il, hostname);
2060 iovlist_append(&il, " ");
2064 /* Message body with application name and process ID prefixed. */
2065 if (app_name != NULL) {
2066 iovlist_append(&il, app_name);
2067 if (procid != NULL) {
2068 iovlist_append(&il, "[");
2069 iovlist_append(&il, procid);
2070 iovlist_append(&il, "]");
2072 iovlist_append(&il, ": ");
2074 iovlist_append(&il, msg);
2076 fprintlog_write(f, &il, flags);
2080 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
2081 const char *procid, const char *msgid __unused,
2082 const char *structured_data __unused, const char *msg, int flags)
2085 dprintf("Logging to %s", TypeNames[f->f_type]);
2088 if (f->f_type == F_UNUSED) {
2093 if (RFC3164OutputFormat)
2094 fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags);
2096 fprintlog_rfc5424(f, hostname, app_name, procid, msgid,
2097 structured_data, msg, flags);
2101 * Prints a message to a log file that the previously logged message was
2102 * received multiple times.
2105 fprintlog_successive(struct filed *f, int flags)
2109 assert(f->f_prevcount > 0);
2110 snprintf(msg, sizeof(msg), "last message repeated %d times",
2112 fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
2117 * WALLMSG -- Write a message to the world at large
2119 * Write the specified message to either the entire
2120 * world, or a list of approved users.
2123 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
2125 static int reenter; /* avoid calling ourselves */
2134 while ((ut = getutxent()) != NULL) {
2135 if (ut->ut_type != USER_PROCESS)
2137 if (f->f_type == F_WALL) {
2138 if ((p = ttymsg(iov, iovlen, ut->ut_line,
2139 TTYMSGTIME)) != NULL) {
2140 errno = 0; /* already in msg */
2145 /* should we send the message to this user? */
2146 for (i = 0; i < MAXUNAMES; i++) {
2147 if (!f->fu_uname[i][0])
2149 if (!strcmp(f->fu_uname[i], ut->ut_user)) {
2150 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
2151 TTYMSGTIME)) != NULL) {
2152 errno = 0; /* already in msg */
2164 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
2167 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
2169 static char device[1024];
2170 static char errbuf[1024];
2173 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
2175 if (stat(device, &sb) < 0) {
2176 (void) snprintf(errbuf, sizeof(errbuf),
2177 "%s: %s", device, strerror(errno));
2180 if ((sb.st_mode & S_IWGRP) == 0)
2181 /* Messages disabled. */
2183 return ttymsg(iov, iovcnt, line, tmout);
2187 reapchild(int signo __unused)
2193 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
2194 /* First, look if it's a process from the dead queue. */
2195 if (deadq_removebypid(pid))
2198 /* Now, look in list of active processes. */
2199 STAILQ_FOREACH(f, &fhead, next) {
2200 if (f->f_type == F_PIPE &&
2201 f->fu_pipe_pid == pid) {
2203 log_deadchild(pid, status, f->fu_pipe_pname);
2212 * Return a printable representation of a host address.
2215 cvthname(struct sockaddr *f)
2218 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
2220 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
2221 error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
2224 dprintf("Malformed from address %s\n", gai_strerror(error));
2227 dprintf("cvthname(%s)\n", ip);
2232 error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
2233 NULL, 0, NI_NAMEREQD);
2235 dprintf("Host name for your address (%s) unknown\n", ip);
2239 if (hl > 0 && hname[hl-1] == '.')
2241 trimdomain(hname, hl);
2253 domark(int signo __unused)
2260 * Print syslogd errors some place.
2263 logerror(const char *msg)
2266 static int recursed = 0;
2268 /* If there's an error while trying to log an error, give up. */
2273 (void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2278 dprintf("%s\n", buf);
2279 logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2288 struct socklist *sl;
2291 STAILQ_FOREACH(f, &fhead, next) {
2292 /* flush any pending output */
2294 fprintlog_successive(f, 0);
2295 if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
2299 dprintf("syslogd: exiting on signal %d\n", signo);
2300 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2304 STAILQ_FOREACH(sl, &shead, next) {
2305 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
2306 unlink(sl->sl_peer->pe_name);
2308 pidfile_remove(pfh);
2314 configfiles(const struct dirent *dp)
2319 if (dp->d_name[0] == '.')
2322 ext_len = sizeof(include_ext) -1;
2324 if (dp->d_namlen <= ext_len)
2327 p = &dp->d_name[dp->d_namlen - ext_len];
2328 if (strcmp(p, include_ext) != 0)
2335 readconfigfile(FILE *cf, int allow_includes)
2339 struct dirent **ent;
2340 char cline[LINE_MAX];
2341 char host[MAXHOSTNAMELEN];
2342 char prog[LINE_MAX];
2343 char file[MAXPATHLEN];
2344 char pfilter[LINE_MAX];
2350 * Foreach line in the conf table, open that file.
2352 include_len = sizeof(include_str) -1;
2353 (void)strlcpy(host, "*", sizeof(host));
2354 (void)strlcpy(prog, "*", sizeof(prog));
2355 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2356 while (fgets(cline, sizeof(cline), cf) != NULL) {
2358 * check for end-of-section, comments, strip off trailing
2359 * spaces and newline character. #!prog is treated specially:
2360 * following lines apply only to that program.
2362 for (p = cline; isspace(*p); ++p)
2366 if (allow_includes &&
2367 strncmp(p, include_str, include_len) == 0 &&
2368 isspace(p[include_len])) {
2373 while (*tmp != '\0' && !isspace(*tmp))
2376 dprintf("Trying to include files in '%s'\n", p);
2377 nents = scandir(p, &ent, configfiles, alphasort);
2379 dprintf("Unable to open '%s': %s\n", p,
2383 for (i = 0; i < nents; i++) {
2384 if (snprintf(file, sizeof(file), "%s/%s", p,
2385 ent[i]->d_name) >= (int)sizeof(file)) {
2386 dprintf("ignoring path too long: "
2387 "'%s/%s'\n", p, ent[i]->d_name);
2392 cf2 = fopen(file, "r");
2395 dprintf("reading %s\n", file);
2396 readconfigfile(cf2, 0);
2404 if (*p == '\0' || strchr("!+-:", *p) == NULL)
2407 if (*p == '+' || *p == '-') {
2411 if ((!*p) || (*p == '*')) {
2412 (void)strlcpy(host, "*", sizeof(host));
2417 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2418 if (!isalnum(*p) && *p != '.' && *p != '-'
2419 && *p != ',' && *p != ':' && *p != '%')
2428 while (isspace(*p)) p++;
2429 if ((!*p) || (*p == '*')) {
2430 (void)strlcpy(prog, "*", sizeof(prog));
2433 for (i = 0; i < LINE_MAX - 1; i++) {
2434 if (!isprint(p[i]) || isspace(p[i]))
2445 if ((!*p) || (*p == '*')) {
2446 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2449 (void)strlcpy(pfilter, p, sizeof(pfilter));
2452 for (p = cline + 1; *p != '\0'; p++) {
2455 if (*(p - 1) == '\\') {
2463 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2465 f = cfline(cline, prog, host, pfilter);
2473 sighandler(int signo)
2476 /* Send an wake-up signal to the select() loop. */
2477 write(sigpipe[1], &signo, sizeof(signo));
2481 * INIT -- Initialize syslogd from configuration table
2490 char oldLocalHostName[MAXHOSTNAMELEN];
2491 char hostMsg[2*MAXHOSTNAMELEN+40];
2492 char bootfileMsg[LINE_MAX];
2498 * Load hostname (may have changed).
2501 (void)strlcpy(oldLocalHostName, LocalHostName,
2502 sizeof(oldLocalHostName));
2503 if (gethostname(LocalHostName, sizeof(LocalHostName)))
2504 err(EX_OSERR, "gethostname() failed");
2505 if ((p = strchr(LocalHostName, '.')) != NULL) {
2506 /* RFC 5424 prefers logging FQDNs. */
2507 if (RFC3164OutputFormat)
2509 LocalDomain = p + 1;
2515 * Load / reload timezone data (in case it changed).
2517 * Just calling tzset() again does not work, the timezone code
2518 * caches the result. However, by setting the TZ variable, one
2519 * can defeat the caching and have the timezone code really
2520 * reload the timezone data. Respect any initial setting of
2521 * TZ, in case the system is configured specially.
2523 dprintf("loading timezone data via tzset()\n");
2527 setenv("TZ", ":/etc/localtime", 1);
2533 * Close all open log files.
2536 STAILQ_FOREACH(f, &fhead, next) {
2537 /* flush any pending output */
2539 fprintlog_successive(f, 0);
2541 switch (f->f_type) {
2549 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
2554 while(!STAILQ_EMPTY(&fhead)) {
2555 f = STAILQ_FIRST(&fhead);
2556 STAILQ_REMOVE_HEAD(&fhead, next);
2559 if (f->f_prop_filter) {
2560 switch (f->f_prop_filter->cmp_type) {
2561 case PROP_CMP_REGEX:
2562 regfree(f->f_prop_filter->pflt_re);
2563 free(f->f_prop_filter->pflt_re);
2565 case PROP_CMP_CONTAINS:
2566 case PROP_CMP_EQUAL:
2567 case PROP_CMP_STARTS:
2568 free(f->f_prop_filter->pflt_strval);
2571 free(f->f_prop_filter);
2576 /* open the configuration file */
2577 if ((cf = fopen(ConfFile, "r")) == NULL) {
2578 dprintf("cannot open %s\n", ConfFile);
2579 f = cfline("*.ERR\t/dev/console", "*", "*", "*");
2583 f = cfline("*.PANIC\t*", "*", "*", "*");
2592 readconfigfile(cf, 1);
2594 /* close the configuration file */
2601 STAILQ_FOREACH(f, &fhead, next) {
2602 for (i = 0; i <= LOG_NFACILITIES; i++)
2603 if (f->f_pmask[i] == INTERNAL_NOPRI)
2606 printf("%d ", f->f_pmask[i]);
2607 printf("%s: ", TypeNames[f->f_type]);
2608 switch (f->f_type) {
2610 printf("%s", f->fu_fname);
2615 printf("%s%s", _PATH_DEV, f->fu_fname);
2619 switch (f->fu_forw_addr->ai_family) {
2622 port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2627 port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2635 f->fu_forw_hname, port);
2637 printf("%s", f->fu_forw_hname);
2642 printf("%s", f->fu_pipe_pname);
2646 for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2647 printf("%s, ", f->fu_uname[i]);
2651 printf(" (%s)", f->f_program);
2656 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2657 NULL, NULL, "restart", 0);
2658 dprintf("syslogd: restarted\n");
2660 * Log a change in hostname, but only on a restart.
2662 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
2663 (void)snprintf(hostMsg, sizeof(hostMsg),
2664 "hostname changed, \"%s\" to \"%s\"",
2665 oldLocalHostName, LocalHostName);
2666 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2667 NULL, NULL, NULL, hostMsg, 0);
2668 dprintf("%s\n", hostMsg);
2671 * Log the kernel boot file if we aren't going to use it as
2672 * the prefix, and if this is *not* a restart.
2674 if (signo == 0 && !use_bootfile) {
2675 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2676 "kernel boot file is %s", bootfile);
2677 logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2678 NULL, NULL, NULL, bootfileMsg, 0);
2679 dprintf("%s\n", bootfileMsg);
2684 * Compile property-based filter.
2685 * Returns 0 on success, -1 otherwise.
2688 prop_filter_compile(struct prop_filter *pfilter, char *filter)
2690 char *filter_endpos, *p;
2691 char **ap, *argv[2] = {NULL, NULL};
2692 int re_flags = REG_NOSUB;
2695 bzero(pfilter, sizeof(struct prop_filter));
2698 * Here's some filter examples mentioned in syslog.conf(5)
2699 * 'msg, contains, ".*Deny.*"'
2700 * 'processname, regex, "^bird6?$"'
2701 * 'hostname, icase_ereregex, "^server-(dcA|podB)-rack1[0-9]{2}\\..*"'
2705 * Split filter into 3 parts: property name (argv[0]),
2706 * cmp type (argv[1]) and lvalue for comparison (filter).
2708 for (ap = argv; (*ap = strsep(&filter, ", \t\n")) != NULL;) {
2710 if (++ap >= &argv[2])
2714 if (argv[0] == NULL || argv[1] == NULL) {
2715 logerror("filter parse error");
2719 /* fill in prop_type */
2720 if (strcasecmp(argv[0], "msg") == 0)
2721 pfilter->prop_type = PROP_TYPE_MSG;
2722 else if(strcasecmp(argv[0], "hostname") == 0)
2723 pfilter->prop_type = PROP_TYPE_HOSTNAME;
2724 else if(strcasecmp(argv[0], "source") == 0)
2725 pfilter->prop_type = PROP_TYPE_HOSTNAME;
2726 else if(strcasecmp(argv[0], "programname") == 0)
2727 pfilter->prop_type = PROP_TYPE_PROGNAME;
2729 logerror("unknown property");
2733 /* full in cmp_flags (i.e. !contains, icase_regex, etc.) */
2734 if (*argv[1] == '!') {
2735 pfilter->cmp_flags |= PROP_FLAG_EXCLUDE;
2738 if (strncasecmp(argv[1], "icase_", (sizeof("icase_") - 1)) == 0) {
2739 pfilter->cmp_flags |= PROP_FLAG_ICASE;
2740 argv[1] += sizeof("icase_") - 1;
2743 /* fill in cmp_type */
2744 if (strcasecmp(argv[1], "contains") == 0)
2745 pfilter->cmp_type = PROP_CMP_CONTAINS;
2746 else if (strcasecmp(argv[1], "isequal") == 0)
2747 pfilter->cmp_type = PROP_CMP_EQUAL;
2748 else if (strcasecmp(argv[1], "startswith") == 0)
2749 pfilter->cmp_type = PROP_CMP_STARTS;
2750 else if (strcasecmp(argv[1], "regex") == 0)
2751 pfilter->cmp_type = PROP_CMP_REGEX;
2752 else if (strcasecmp(argv[1], "ereregex") == 0) {
2753 pfilter->cmp_type = PROP_CMP_REGEX;
2754 re_flags |= REG_EXTENDED;
2756 logerror("unknown cmp function");
2761 * Handle filter value
2765 /* remove leading whitespace and check for '"' next character */
2766 filter += strspn(filter, ", \t\n");
2767 if (*filter != '"' || strlen(filter) < 3) {
2768 logerror("property value parse error");
2774 /* process possible backslash (\") escaping */
2776 filter_endpos = filter;
2777 for (p = filter; *p != '\0'; p++) {
2778 if (*p == '\\' && !escaped) {
2780 /* do not shift filter_endpos */
2783 if (*p == '"' && !escaped) {
2787 /* we've seen some esc symbols, need to compress the line */
2788 if (filter_endpos != p)
2789 *filter_endpos = *p;
2795 *filter_endpos = '\0';
2798 /* We should not have anything but whitespace left after closing '"' */
2799 if (*p != '\0' && strspn(p, " \t\n") != strlen(p)) {
2800 logerror("property value parse error");
2804 if (pfilter->cmp_type == PROP_CMP_REGEX) {
2805 pfilter->pflt_re = calloc(1, sizeof(*pfilter->pflt_re));
2806 if (pfilter->pflt_re == NULL) {
2807 logerror("RE calloc() error");
2808 free(pfilter->pflt_re);
2811 if (pfilter->cmp_flags & PROP_FLAG_ICASE)
2812 re_flags |= REG_ICASE;
2813 if (regcomp(pfilter->pflt_re, filter, re_flags) != 0) {
2814 logerror("RE compilation error");
2815 free(pfilter->pflt_re);
2819 pfilter->pflt_strval = strdup(filter);
2820 pfilter->pflt_strlen = strlen(filter);
2828 * Crack a configuration file line
2830 static struct filed *
2831 cfline(const char *line, const char *prog, const char *host,
2832 const char *pfilter)
2835 struct addrinfo hints, *res;
2836 int error, i, pri, syncfile;
2838 char *bp, *pfilter_dup;
2839 char buf[MAXLINE], ebuf[100];
2841 dprintf("cfline(\"%s\", f, \"%s\", \"%s\", \"%s\")\n", line, prog,
2844 f = calloc(1, sizeof(*f));
2849 errno = 0; /* keep strerror() stuff out of logerror messages */
2851 for (i = 0; i <= LOG_NFACILITIES; i++)
2852 f->f_pmask[i] = INTERNAL_NOPRI;
2854 /* save hostname if any */
2855 if (host && *host == '*')
2860 f->f_host = strdup(host);
2861 if (f->f_host == NULL) {
2865 hl = strlen(f->f_host);
2866 if (hl > 0 && f->f_host[hl-1] == '.')
2867 f->f_host[--hl] = '\0';
2868 trimdomain(f->f_host, hl);
2871 /* save program name if any */
2872 if (prog && *prog == '*')
2875 f->f_program = strdup(prog);
2876 if (f->f_program == NULL) {
2883 f->f_prop_filter = calloc(1, sizeof(*(f->f_prop_filter)));
2884 if (f->f_prop_filter == NULL) {
2885 logerror("pfilter calloc");
2888 if (*pfilter == '*')
2889 f->f_prop_filter->prop_type = PROP_TYPE_NOOP;
2891 pfilter_dup = strdup(pfilter);
2892 if (pfilter_dup == NULL) {
2896 if (prop_filter_compile(f->f_prop_filter, pfilter_dup)) {
2897 logerror("filter compile error");
2903 /* scan through the list of selectors */
2904 for (p = line; *p && *p != '\t' && *p != ' ';) {
2909 /* find the end of this facility name list */
2910 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2913 /* get the priority comparison */
2941 /* collect priority name */
2942 for (bp = buf; *q && !strchr("\t,; ", *q); )
2947 while (strchr(",;", *q))
2950 /* decode priority name */
2953 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2955 /* Ignore trailing spaces. */
2956 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2959 pri = decode(buf, prioritynames);
2962 (void)snprintf(ebuf, sizeof ebuf,
2963 "unknown priority name \"%s\"", buf);
2970 pri_cmp = (UniquePriority)
2975 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2977 /* scan facilities */
2978 while (*p && !strchr("\t.; ", *p)) {
2979 for (bp = buf; *p && !strchr("\t,;. ", *p); )
2984 for (i = 0; i < LOG_NFACILITIES; i++) {
2985 f->f_pmask[i] = pri;
2986 f->f_pcmp[i] = pri_cmp;
2989 i = decode(buf, facilitynames);
2992 (void)snprintf(ebuf, sizeof ebuf,
2993 "unknown facility name \"%s\"",
2999 f->f_pmask[i >> 3] = pri;
3000 f->f_pcmp[i >> 3] = pri_cmp;
3002 while (*p == ',' || *p == ' ')
3009 /* skip to action part */
3010 while (*p == '\t' || *p == ' ')
3025 * scan forward to see if there is a port defined.
3026 * so we can't use strlcpy..
3028 i = sizeof(f->fu_forw_hname);
3029 tp = f->fu_forw_hname;
3033 * an ipv6 address should start with a '[' in that case
3034 * we should scan for a ']'
3040 while (*p && (*p != endkey) && (i-- > 0)) {
3043 if (endkey == ']' && *p == endkey)
3047 /* See if we copied a domain and have a port */
3053 hints = (struct addrinfo){
3054 .ai_family = family,
3055 .ai_socktype = SOCK_DGRAM
3057 error = getaddrinfo(f->fu_forw_hname,
3058 p ? p : "syslog", &hints, &res);
3060 logerror(gai_strerror(error));
3063 f->fu_forw_addr = res;
3068 if ((f->f_file = open(p, logflags, 0600)) < 0) {
3069 f->f_type = F_UNUSED;
3074 f->f_flags |= FFLAG_SYNC;
3075 if (isatty(f->f_file)) {
3076 if (strcmp(p, ctty) == 0)
3077 f->f_type = F_CONSOLE;
3080 (void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
3081 sizeof(f->fu_fname));
3083 (void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
3090 (void)strlcpy(f->fu_pipe_pname, p + 1,
3091 sizeof(f->fu_pipe_pname));
3100 for (i = 0; i < MAXUNAMES && *p; i++) {
3101 for (q = p; *q && *q != ','; )
3103 (void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
3104 if ((q - p) >= MAXLOGNAME)
3105 f->fu_uname[i][MAXLOGNAME - 1] = '\0';
3107 f->fu_uname[i][q - p] = '\0';
3108 while (*q == ',' || *q == ' ')
3112 f->f_type = F_USERS;
3120 * Decode a symbolic name to a numeric value
3123 decode(const char *name, const CODE *codetab)
3129 return (atoi(name));
3131 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3133 *p = tolower(*name);
3138 for (c = codetab; c->c_name; c++)
3139 if (!strcmp(buf, c->c_name))
3149 struct deadq_entry *dq, *dq0;
3151 now = time((time_t *)NULL);
3152 MarkSeq += TIMERINTVL;
3153 if (MarkSeq >= MarkInterval) {
3154 logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
3155 "-- MARK --", MARK);
3159 STAILQ_FOREACH(f, &fhead, next) {
3160 if (f->f_prevcount && now >= REPEATTIME(f)) {
3161 dprintf("flush %s: repeated %d times, %d sec.\n",
3162 TypeNames[f->f_type], f->f_prevcount,
3163 repeatinterval[f->f_repeatcount]);
3164 fprintlog_successive(f, 0);
3169 /* Walk the dead queue, and see if we should signal somebody. */
3170 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
3171 switch (dq->dq_timeout) {
3173 /* Already signalled once, try harder now. */
3174 if (kill(dq->dq_pid, SIGKILL) != 0)
3175 (void)deadq_remove(dq);
3180 * Timed out on dead queue, send terminate
3181 * signal. Note that we leave the removal
3182 * from the dead queue to reapchild(), which
3183 * will also log the event (unless the process
3184 * didn't even really exist, in case we simply
3185 * drop it from the dead queue).
3187 if (kill(dq->dq_pid, SIGTERM) != 0)
3188 (void)deadq_remove(dq);
3197 (void)alarm(TIMERINTVL);
3201 * fork off and become a daemon, but wait for the child to come online
3202 * before returning to the parent, or we get disk thrashing at boot etc.
3203 * Set a timer so we don't hang forever if it wedges.
3206 waitdaemon(int maxwait)
3210 pid_t pid, childpid;
3212 switch (childpid = fork()) {
3218 signal(SIGALRM, timedout);
3220 while ((pid = wait3(&status, 0, NULL)) != -1) {
3221 if (WIFEXITED(status))
3222 errx(1, "child pid %d exited with return code %d",
3223 pid, WEXITSTATUS(status));
3224 if (WIFSIGNALED(status))
3225 errx(1, "child pid %d exited on signal %d%s",
3226 pid, WTERMSIG(status),
3227 WCOREDUMP(status) ? " (core dumped)" :
3229 if (pid == childpid) /* it's gone... */
3239 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
3240 (void)dup2(fd, STDIN_FILENO);
3241 (void)dup2(fd, STDOUT_FILENO);
3242 (void)dup2(fd, STDERR_FILENO);
3243 if (fd > STDERR_FILENO)
3250 * We get a SIGALRM from the child when it's running and finished doing it's
3251 * fsync()'s or O_SYNC writes for all the boot messages.
3253 * We also get a signal from the kernel if the timer expires, so check to
3254 * see what happened.
3257 timedout(int sig __unused)
3261 signal(SIGALRM, SIG_DFL);
3263 errx(1, "timed out waiting for child");
3269 * Add `s' to the list of allowable peer addresses to accept messages
3272 * `s' is a string in the form:
3274 * [*]domainname[:{servicename|portnumber|*}]
3278 * netaddr/maskbits[:{servicename|portnumber|*}]
3280 * Returns -1 on error, 0 if the argument was valid.
3283 #if defined(INET) || defined(INET6)
3286 allowaddr(char *s __unused)
3289 #if defined(INET) || defined(INET6)
3291 struct allowedpeer *ap;
3294 struct addrinfo hints, *res = NULL;
3296 in_addr_t *addrp, *maskp;
3299 uint32_t *addr6p, *mask6p;
3301 char ip[NI_MAXHOST];
3303 ap = calloc(1, sizeof(*ap));
3305 err(1, "malloc failed");
3308 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
3311 if ((cp1 = strrchr(cp1, ':'))) {
3312 /* service/port provided */
3314 if (strlen(cp1) == 1 && *cp1 == '*')
3315 /* any port allowed */
3317 else if ((se = getservbyname(cp1, "udp"))) {
3318 ap->port = ntohs(se->s_port);
3320 ap->port = strtol(cp1, &cp2, 0);
3321 /* port not numeric */
3326 if ((se = getservbyname("syslog", "udp")))
3327 ap->port = ntohs(se->s_port);
3329 /* sanity, should not happen */
3333 if ((cp1 = strchr(s, '/')) != NULL &&
3334 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
3336 if ((masklen = atoi(cp1 + 1)) < 0)
3341 cp2 = s + strlen(s) - 1;
3352 hints = (struct addrinfo){
3353 .ai_family = PF_UNSPEC,
3354 .ai_socktype = SOCK_DGRAM,
3355 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3357 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
3359 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
3360 ap->a_mask = (struct sockaddr_storage){
3361 .ss_family = res->ai_family,
3362 .ss_len = res->ai_addrlen
3364 switch (res->ai_family) {
3367 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
3368 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
3370 /* use default netmask */
3371 if (IN_CLASSA(ntohl(*addrp)))
3372 *maskp = htonl(IN_CLASSA_NET);
3373 else if (IN_CLASSB(ntohl(*addrp)))
3374 *maskp = htonl(IN_CLASSB_NET);
3376 *maskp = htonl(IN_CLASSC_NET);
3377 } else if (masklen == 0) {
3379 } else if (masklen <= 32) {
3380 /* convert masklen to netmask */
3381 *maskp = htonl(~((1 << (32 - masklen)) - 1));
3385 /* Lose any host bits in the network number. */
3396 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
3397 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
3398 /* convert masklen to netmask */
3399 while (masklen > 0) {
3402 htonl(~(0xffffffff >> masklen));
3406 *mask6p++ = 0xffffffff;
3418 /* arg `s' is domain name */
3430 STAILQ_INSERT_TAIL(&aphead, ap, next);
3433 printf("allowaddr: rule ");
3434 if (ap->isnumeric) {
3435 printf("numeric, ");
3436 getnameinfo(sstosa(&ap->a_addr),
3437 (sstosa(&ap->a_addr))->sa_len,
3438 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3439 printf("addr = %s, ", ip);
3440 getnameinfo(sstosa(&ap->a_mask),
3441 (sstosa(&ap->a_mask))->sa_len,
3442 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3443 printf("mask = %s; ", ip);
3445 printf("domainname = %s; ", ap->a_name);
3447 printf("port = %d\n", ap->port);
3460 * Validate that the remote peer has permission to log to us.
3463 validate(struct sockaddr *sa, const char *hname)
3466 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3467 struct allowedpeer *ap;
3469 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3472 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3474 struct addrinfo hints, *res;
3478 STAILQ_FOREACH(ap, &aphead, next) {
3481 dprintf("# of validation rule: %d\n", num);
3483 /* traditional behaviour, allow everything */
3486 (void)strlcpy(name, hname, sizeof(name));
3487 hints = (struct addrinfo){
3488 .ai_family = PF_UNSPEC,
3489 .ai_socktype = SOCK_DGRAM,
3490 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3492 if (getaddrinfo(name, NULL, &hints, &res) == 0)
3494 else if (strchr(name, '.') == NULL) {
3495 strlcat(name, ".", sizeof name);
3496 strlcat(name, LocalDomain, sizeof name);
3498 if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
3499 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3500 return (0); /* for safety, should not occur */
3501 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3505 /* now, walk down the list */
3507 STAILQ_FOREACH(ap, &aphead, next) {
3509 if (ap->port != 0 && ap->port != sport) {
3510 dprintf("rejected in rule %d due to port mismatch.\n",
3515 if (ap->isnumeric) {
3516 if (ap->a_addr.ss_family != sa->sa_family) {
3517 dprintf("rejected in rule %d due to address family mismatch.\n", i);
3521 else if (ap->a_addr.ss_family == AF_INET) {
3523 a4p = satosin(&ap->a_addr);
3524 m4p = satosin(&ap->a_mask);
3525 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3526 != a4p->sin_addr.s_addr) {
3527 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3533 else if (ap->a_addr.ss_family == AF_INET6) {
3534 sin6 = satosin6(sa);
3535 a6p = satosin6(&ap->a_addr);
3536 m6p = satosin6(&ap->a_mask);
3537 if (a6p->sin6_scope_id != 0 &&
3538 sin6->sin6_scope_id != a6p->sin6_scope_id) {
3539 dprintf("rejected in rule %d due to scope mismatch.\n", i);
3542 if (!IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3543 &a6p->sin6_addr, &m6p->sin6_addr)) {
3544 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3552 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3554 dprintf("rejected in rule %d due to name "
3559 dprintf("accepted in rule %d.\n", i);
3560 return (1); /* hooray! */
3566 * Fairly similar to popen(3), but returns an open descriptor, as
3567 * opposed to a FILE *.
3570 p_open(const char *prog, pid_t *rpid)
3572 int pfd[2], nulldesc;
3574 char *argv[4]; /* sh -c cmd NULL */
3577 if (pipe(pfd) == -1)
3579 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
3580 /* we are royally screwed anyway */
3583 switch ((pid = fork())) {
3589 (void)setsid(); /* Avoid catching SIGHUPs. */
3590 argv[0] = strdup("sh");
3591 argv[1] = strdup("-c");
3592 argv[2] = strdup(prog);
3594 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
3601 /* Restore signals marked as SIG_IGN. */
3602 (void)signal(SIGINT, SIG_DFL);
3603 (void)signal(SIGQUIT, SIG_DFL);
3604 (void)signal(SIGPIPE, SIG_DFL);
3606 dup2(pfd[0], STDIN_FILENO);
3607 dup2(nulldesc, STDOUT_FILENO);
3608 dup2(nulldesc, STDERR_FILENO);
3609 closefrom(STDERR_FILENO + 1);
3611 (void)execvp(_PATH_BSHELL, argv);
3617 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
3618 * supposed to get an EWOULDBLOCK on writev(2), which is
3619 * caught by the logic above anyway, which will in turn close
3620 * the pipe, and fork a new logging subprocess if necessary.
3621 * The stale subprocess will be killed some time later unless
3622 * it terminated itself due to closing its input pipe (so we
3623 * get rid of really dead puppies).
3625 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3627 (void)snprintf(errmsg, sizeof errmsg,
3628 "Warning: cannot change pipe to PID %d to "
3629 "non-blocking behaviour.",
3638 deadq_enter(pid_t pid, const char *name)
3640 struct deadq_entry *dq;
3646 * Be paranoid, if we can't signal the process, don't enter it
3647 * into the dead queue (perhaps it's already dead). If possible,
3648 * we try to fetch and log the child's status.
3650 if (kill(pid, 0) != 0) {
3651 if (waitpid(pid, &status, WNOHANG) > 0)
3652 log_deadchild(pid, status, name);
3656 dq = malloc(sizeof(*dq));
3661 *dq = (struct deadq_entry){
3663 .dq_timeout = DQ_TIMO_INIT
3665 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3669 deadq_remove(struct deadq_entry *dq)
3672 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3681 deadq_removebypid(pid_t pid)
3683 struct deadq_entry *dq;
3685 TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
3686 if (dq->dq_pid == pid)
3689 return (deadq_remove(dq));
3693 log_deadchild(pid_t pid, int status, const char *name)
3699 errno = 0; /* Keep strerror() stuff out of logerror messages. */
3700 if (WIFSIGNALED(status)) {
3701 reason = "due to signal";
3702 code = WTERMSIG(status);
3704 reason = "with status";
3705 code = WEXITSTATUS(status);
3709 (void)snprintf(buf, sizeof buf,
3710 "Logging subprocess %d (%s) exited %s %d.",
3711 pid, name, reason, code);
3716 socksetup(struct peer *pe)
3718 struct addrinfo hints, *res, *res0;
3721 int (*sl_recv)(struct socklist *);
3723 * We have to handle this case for backwards compatibility:
3724 * If there are two (or more) colons but no '[' and ']',
3725 * assume this is an inet6 address without a service.
3727 if (pe->pe_name != NULL) {
3729 if (pe->pe_name[0] == '[' &&
3730 (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
3731 pe->pe_name = &pe->pe_name[1];
3733 if (cp[1] == ':' && cp[2] != '\0')
3734 pe->pe_serv = cp + 2;
3737 cp = strchr(pe->pe_name, ':');
3738 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
3741 pe->pe_serv = cp + 1;
3742 if (cp == pe->pe_name)
3749 hints = (struct addrinfo){
3750 .ai_family = AF_UNSPEC,
3751 .ai_socktype = SOCK_DGRAM,
3752 .ai_flags = AI_PASSIVE
3754 if (pe->pe_name != NULL)
3755 dprintf("Trying peer: %s\n", pe->pe_name);
3756 if (pe->pe_serv == NULL)
3757 pe->pe_serv = "syslog";
3758 error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
3762 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
3763 pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
3764 gai_strerror(error));
3767 logerror(gai_strerror(error));
3773 for (res = res0; res != NULL; res = res->ai_next) {
3776 if (res->ai_family != AF_LOCAL &&
3778 /* Only AF_LOCAL in secure mode. */
3781 if (family != AF_UNSPEC &&
3782 res->ai_family != AF_LOCAL && res->ai_family != family)
3785 s = socket(res->ai_family, res->ai_socktype,
3793 if (res->ai_family == AF_INET6) {
3794 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
3795 &(int){1}, sizeof(int)) < 0) {
3796 logerror("setsockopt(IPV6_V6ONLY)");
3803 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
3804 &(int){1}, sizeof(int)) < 0) {
3805 logerror("setsockopt(SO_REUSEADDR)");
3812 * Bind INET and UNIX-domain sockets.
3814 * A UNIX-domain socket is always bound to a pathname
3815 * regardless of -N flag.
3817 * For INET sockets, RFC 3164 recommends that client
3818 * side message should come from the privileged syslogd port.
3820 * If the system administrator chooses not to obey
3821 * this, we can skip the bind() step so that the
3822 * system will choose a port for us.
3824 if (res->ai_family == AF_LOCAL)
3825 unlink(pe->pe_name);
3826 if (res->ai_family == AF_LOCAL ||
3827 NoBind == 0 || pe->pe_name != NULL) {
3828 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
3834 if (res->ai_family == AF_LOCAL ||
3838 if (res->ai_family == AF_LOCAL &&
3839 chmod(pe->pe_name, pe->pe_mode) < 0) {
3840 dprintf("chmod %s: %s\n", pe->pe_name,
3846 dprintf("new socket fd is %d\n", s);
3847 if (res->ai_socktype != SOCK_DGRAM) {
3850 sl_recv = socklist_recv_sock;
3851 #if defined(INET) || defined(INET6)
3852 if (SecureMode && (res->ai_family == AF_INET ||
3853 res->ai_family == AF_INET6)) {
3854 dprintf("shutdown\n");
3855 /* Forbid communication in secure mode. */
3856 if (shutdown(s, SHUT_RD) < 0 &&
3857 errno != ENOTCONN) {
3858 logerror("shutdown");
3865 dprintf("listening on socket\n");
3866 dprintf("sending on socket\n");
3867 addsock(res, &(struct socklist){
3879 increase_rcvbuf(int fd)
3883 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3884 &(socklen_t){sizeof(len)}) == 0) {
3885 if (len < RCVBUF_MINSIZE) {
3886 len = RCVBUF_MINSIZE;
3887 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));