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/event.h>
108 #include <sys/ioctl.h>
109 #include <sys/mman.h>
110 #include <sys/procdesc.h>
111 #include <sys/queue.h>
112 #include <sys/resource.h>
113 #include <sys/socket.h>
114 #include <sys/stat.h>
115 #include <sys/syslimits.h>
116 #include <sys/time.h>
119 #include <sys/wait.h>
121 #if defined(INET) || defined(INET6)
122 #include <netinet/in.h>
123 #include <arpa/inet.h>
146 #include <sysexits.h>
150 #include "pathnames.h"
154 #include <sys/syslog.h>
156 static const char *ConfFile = _PATH_LOGCONF;
157 static const char *PidFile = _PATH_LOGPID;
158 static const char include_str[] = "include";
159 static const char include_ext[] = ".conf";
161 #define dprintf if (Debug) printf
163 #define MAXUNAMES 20 /* maximum number of user names */
165 #define sstosa(ss) ((struct sockaddr *)(ss))
167 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss))
168 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa))
171 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss))
172 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa))
173 #define s6_addr32 __u6_addr.__u6_addr32
174 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \
175 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
176 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
177 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
178 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
182 * List of peers and sockets that can't be bound until
183 * flags have been parsed.
189 STAILQ_ENTRY(peer) next;
191 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
194 * Sockets used for logging; monitored by kevent().
197 struct addrinfo sl_ai;
198 #define sl_sa sl_ai.ai_addr
199 #define sl_salen sl_ai.ai_addrlen
200 #define sl_family sl_ai.ai_family
204 int (*sl_recv)(struct socklist *);
205 STAILQ_ENTRY(socklist) next;
207 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
213 #define IGN_CONS 0x001 /* don't print on console */
214 #define SYNC_FILE 0x002 /* do fsync on file after printing */
215 #define MARK 0x008 /* this message is a mark */
216 #define ISKERNEL 0x010 /* kernel generated message */
218 /* Timestamps of log entries. */
224 /* Traditional syslog timestamp format. */
225 #define RFC3164_DATELEN 15
226 #define RFC3164_DATEFMT "%b %e %H:%M:%S"
243 * This structure holds a property-based filter
246 enum filt_proptype prop_type;
247 enum filt_cmptype cmp_type;
249 #define FILT_FLAG_EXCLUDE (1 << 0)
250 #define FILT_FLAG_ICASE (1 << 1)
255 #define pflt_strval pflt_uniptr.p_strval
256 #define pflt_re pflt_uniptr.p_re
261 F_UNUSED, /* unused entry */
262 F_FILE, /* regular file */
263 F_TTY, /* terminal */
264 F_CONSOLE, /* console terminal */
265 F_FORW, /* remote machine */
266 F_USERS, /* list of users */
267 F_WALL, /* everyone logged on */
268 F_PIPE, /* pipe to program */
272 * This structure represents the files that will have log
274 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
275 * or if f_type is F_PIPE and f_pid > 0.
280 /* Used for filtering. */
281 char *f_host; /* host from which to recd. */
282 char *f_program; /* program this applies to */
283 struct prop_filter *f_prop_filter; /* property-based filter */
284 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
285 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
290 /* Logging destinations. */
291 int f_file; /* file descriptor */
292 int f_flags; /* file-specific flags */
293 #define FFLAG_SYNC 0x01
294 #define FFLAG_NEEDSYNC 0x02
296 char f_uname[MAXUNAMES][MAXLOGNAME]; /* F_WALL, F_USERS */
297 char f_fname[MAXPATHLEN]; /* F_FILE, F_CONSOLE, F_TTY */
299 char f_hname[MAXHOSTNAMELEN];
300 struct addrinfo *f_addr;
301 } f_forw; /* F_FORW */
303 char f_pname[MAXPATHLEN];
305 } f_pipe; /* F_PIPE */
307 #define fu_uname f_un.f_uname
308 #define fu_fname f_un.f_fname
309 #define fu_forw_hname f_un.f_forw.f_hname
310 #define fu_forw_addr f_un.f_forw.f_addr
311 #define fu_pipe_pname f_un.f_pipe.f_pname
312 #define fu_pipe_pd f_un.f_pipe.f_procdesc
315 char f_prevline[MAXSVLINE]; /* last message logged */
316 time_t f_time; /* time this was last written */
317 struct logtime f_lasttime; /* time of last occurrence */
318 int f_prevpri; /* pri of f_prevline */
319 size_t f_prevlen; /* length of f_prevline */
320 int f_prevcount; /* repetition cnt of prevline */
321 u_int f_repeatcount; /* number of "repeated" msgs */
322 STAILQ_ENTRY(filed) next; /* next in linked list */
324 static STAILQ_HEAD(, filed) fhead =
325 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */
326 static struct filed consfile; /* Console */
330 * Queue of about-to-be dead processes we should watch out for.
335 TAILQ_ENTRY(deadq_entry) dq_entries;
337 static TAILQ_HEAD(, deadq_entry) deadq_head =
338 TAILQ_HEAD_INITIALIZER(deadq_head);
341 * The timeout to apply to processes waiting on the dead queue. Unit
342 * of measure is `mark intervals', i.e. 20 minutes by default.
343 * Processes on the dead queue will be terminated after that time.
346 #define DQ_TIMO_INIT 2
349 * Network addresses that are allowed to log to us.
356 struct sockaddr_storage addr;
357 struct sockaddr_storage mask;
361 #define a_addr u.numeric.addr
362 #define a_mask u.numeric.mask
363 #define a_name u.name
364 STAILQ_ENTRY(allowedpeer) next;
366 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
369 * Intervals at which we flush out "message repeated" messages,
370 * in seconds after previous message is logged. After each flush,
371 * we move to the next interval until we reach the largest.
373 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
374 #define MAXREPEAT (nitems(repeatinterval) - 1)
375 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
376 #define BACKOFF(f) do { \
377 if (++(f)->f_repeatcount > MAXREPEAT) \
378 (f)->f_repeatcount = MAXREPEAT; \
381 static const char *TypeNames[] = {
392 static const int sigcatch[] = {
402 static int nulldesc; /* /dev/null descriptor */
403 static bool Debug; /* debug flag */
404 static bool Foreground = false; /* Run in foreground, instead of daemonizing */
405 static bool resolve = true; /* resolve hostname */
406 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
407 static const char *LocalDomain; /* our local domain name */
408 static bool Initialized; /* set when we have initialized ourselves */
409 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
410 static int MarkSeq; /* mark sequence number */
411 static bool NoBind; /* don't bind() as suggested by RFC 3164 */
412 static int SecureMode; /* when true, receive only unix domain socks */
413 static int MaxForwardLen = 1024; /* max length of forwared message */
415 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
417 static int family = PF_INET; /* protocol family (IPv4 only) */
419 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
420 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
421 static int use_bootfile; /* log entire bootfile for every kern msg */
422 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
423 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
425 static char bootfile[MAXPATHLEN]; /* booted kernel file */
427 static bool RemoteAddDate; /* Always set the date on remote messages */
428 static bool RemoteHostname; /* Log remote hostname from the message */
430 static bool UniquePriority; /* Only log specified priority? */
431 static int LogFacPri; /* Put facility and priority in log message: */
432 /* 0=no, 1=numeric, 2=names */
433 static bool KeepKernFac; /* Keep remotely logged kernel facility */
434 static bool needdofsync = true; /* Are any file(s) waiting to be fsynced? */
435 static struct pidfh *pfh;
436 static bool RFC3164OutputFormat = true; /* Use legacy format by default. */
440 static bool allowaddr(char *);
441 static void addpeer(const char *, const char *, mode_t);
442 static void addsock(const char *, const char *, mode_t);
443 static void cfline(const char *, const char *, const char *, const char *);
444 static const char *cvthname(struct sockaddr *);
445 static void deadq_enter(int);
446 static void deadq_remove(struct deadq_entry *);
447 static int decode(const char *, const CODE *);
448 static void die(int) __dead2;
449 static void dofsync(void);
450 static void fprintlog_first(struct filed *, const char *, const char *,
451 const char *, const char *, const char *, const char *, int);
452 static void fprintlog_write(struct filed *, struct iovlist *, int);
453 static void fprintlog_successive(struct filed *, int);
454 static void init(bool);
455 static void logerror(const char *);
456 static void logmsg(int, const struct logtime *, const char *, const char *,
457 const char *, const char *, const char *, const char *, int);
458 static void markit(void);
459 static struct socklist *socksetup(struct addrinfo *, const char *, mode_t);
460 static int socklist_recv_file(struct socklist *);
461 static int socklist_recv_sock(struct socklist *);
462 static int skip_message(const char *, const char *, int);
463 static int evaluate_prop_filter(const struct prop_filter *filter,
465 static struct prop_filter *prop_filter_compile(const char *);
466 static void parsemsg(const char *, char *);
467 static void printsys(char *);
468 static int p_open(const char *, pid_t *);
469 static const char *ttymsg_check(struct iovec *, int, char *, int);
470 static void usage(void);
471 static bool validate(struct sockaddr *, const char *);
472 static void unmapped(struct sockaddr *);
473 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
474 static int waitdaemon(int);
475 static void increase_rcvbuf(int);
478 close_filed(struct filed *f)
481 if (f == NULL || f->f_file == -1)
486 if (f->fu_forw_addr != NULL) {
487 freeaddrinfo(f->fu_forw_addr);
488 f->fu_forw_addr = NULL;
494 f->f_type = F_UNUSED;
497 if (f->fu_pipe_pd >= 0) {
498 deadq_enter(f->fu_pipe_pd);
505 (void)close(f->f_file);
510 addpeer(const char *name, const char *serv, mode_t mode)
512 struct peer *pe = calloc(1, sizeof(*pe));
514 err(1, "malloc failed");
518 STAILQ_INSERT_TAIL(&pqueue, pe, next);
522 addsock(const char *name, const char *serv, mode_t mode)
524 struct addrinfo hints = { }, *res, *res0;
530 * We have to handle this case for backwards compatibility:
531 * If there are two (or more) colons but no '[' and ']',
532 * assume this is an inet6 address without a service.
536 if (name[0] == '[' &&
537 (cp = strchr(name + 1, ']')) != NULL) {
540 if (cp[1] == ':' && cp[2] != '\0')
544 cp = strchr(name, ':');
545 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
556 hints.ai_family = AF_UNSPEC;
557 hints.ai_socktype = SOCK_DGRAM;
558 hints.ai_flags = AI_PASSIVE;
560 dprintf("Trying peer: %s\n", name);
563 error = getaddrinfo(name, serv, &hints, &res0);
565 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
566 name == NULL ? "" : name, serv,
567 gai_strerror(error));
570 logerror(gai_strerror(error));
576 for (res = res0; res != NULL; res = res->ai_next) {
577 sl = socksetup(res, name, mode);
580 STAILQ_INSERT_TAIL(&shead, sl, next);
588 struct socklist *sl = calloc(1, sizeof(*sl));
590 err(1, "malloc failed");
592 sl->sl_recv = socklist_recv_file;
593 STAILQ_INSERT_TAIL(&shead, sl, next);
597 main(int argc, char *argv[])
599 struct sigaction act = { };
603 int ch, kq, ppipe_w = -1, s;
605 bool bflag = false, pflag = false, Sflag = false;
607 if (madvise(NULL, 0, MADV_PROTECT) != 0)
608 dprintf("madvise() failed: %s\n", strerror(errno));
610 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:M:m:nNoO:p:P:sS:Tuv"))
629 case 'a': /* allow specific network addresses only */
630 if (!allowaddr(optarg))
635 p = strchr(optarg, ']');
637 p = strchr(p + 1, ':');
639 p = strchr(optarg, ':');
640 if (p != NULL && strchr(p + 1, ':') != NULL)
641 p = NULL; /* backward compatibility */
644 /* A hostname or filename only. */
645 addpeer(optarg, "syslog", 0);
647 /* The case of "name:service". */
649 addpeer(strlen(optarg) == 0 ? NULL : optarg,
659 case 'd': /* debug */
662 case 'f': /* configuration file */
665 case 'F': /* run in foreground instead of daemon */
669 RemoteHostname = true;
671 case 'k': /* keep remote kern fac */
684 else if (ch == 'p') {
688 mode = S_IRUSR | S_IWUSR;
691 if (optarg[0] == '/')
693 else if ((name = strchr(optarg, ':')) != NULL) {
696 errx(1, "socket name must be absolute "
698 if (isdigit(*optarg)) {
699 perml = strtol(optarg, &ep, 8);
700 if (*ep || perml < 0 ||
701 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
702 errx(1, "invalid mode %s, exiting",
704 mode = (mode_t )perml;
706 errx(1, "invalid mode %s, exiting",
709 errx(1, "invalid filename %s, exiting",
711 addpeer(name, NULL, mode);
714 case 'M': /* max length of forwarded message */
715 MaxForwardLen = atoi(optarg);
716 if (MaxForwardLen < 480)
717 errx(1, "minimum length limit of forwarded "
718 "messages is 480 bytes");
720 case 'm': /* mark interval */
721 MarkInterval = atoi(optarg) * 60;
732 if (strcmp(optarg, "bsd") == 0 ||
733 strcmp(optarg, "rfc3164") == 0)
734 RFC3164OutputFormat = true;
735 else if (strcmp(optarg, "syslog") == 0 ||
736 strcmp(optarg, "rfc5424") == 0)
737 RFC3164OutputFormat = false;
744 case 'P': /* path for alt. PID */
747 case 's': /* no network mode */
751 RemoteAddDate = true;
753 case 'u': /* only log specified priority */
754 UniquePriority = true;
756 case 'v': /* log facility and priority */
762 if ((argc -= optind) != 0)
765 if (RFC3164OutputFormat && MaxForwardLen > 1024)
766 errx(1, "RFC 3164 messages may not exceed 1024 bytes");
768 pfh = pidfile_open(PidFile, 0600, &spid);
771 errx(1, "syslogd already running, pid: %d", spid);
772 warn("cannot open pid file");
776 * Now that flags have been parsed, we know if we're in
777 * secure mode. Add peers to the socklist, if allowed.
779 while (!STAILQ_EMPTY(&pqueue)) {
780 struct peer *pe = STAILQ_FIRST(&pqueue);
781 STAILQ_REMOVE_HEAD(&pqueue, next);
782 addsock(pe->pe_name, pe->pe_serv, pe->pe_mode);
785 /* Listen by default: /dev/klog. */
786 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
788 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
792 /* Listen by default: *:514 if no -b flag. */
794 addsock(NULL, "syslog", 0);
795 /* Listen by default: /var/run/log if no -p flag. */
797 addsock(_PATH_LOG, NULL, DEFFILEMODE);
798 /* Listen by default: /var/run/logpriv if no -S flag. */
800 addsock(_PATH_LOG_PRIV, NULL, S_IRUSR | S_IWUSR);
802 consfile.f_type = F_CONSOLE;
803 consfile.f_file = -1;
804 (void)strlcpy(consfile.fu_fname, _PATH_CONSOLE + sizeof(_PATH_DEV) - 1,
805 sizeof(consfile.fu_fname));
807 nulldesc = open(_PATH_DEVNULL, O_RDWR);
808 if (nulldesc == -1) {
809 warn("cannot open %s", _PATH_DEVNULL);
814 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
816 if (!Foreground && !Debug)
817 ppipe_w = waitdaemon(30);
823 warn("failed to initialize kqueue");
827 STAILQ_FOREACH(sl, &shead, next) {
828 if (sl->sl_recv == NULL)
830 EV_SET(&ev, sl->sl_socket, EVFILT_READ, EV_ADD, 0, 0, sl);
831 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) {
832 warn("failed to add kevent to kqueue");
839 * Syslogd will not reap its children via wait().
840 * When SIGCHLD is ignored, zombie processes are
841 * not created. A child's PID will be recycled
844 act.sa_handler = SIG_IGN;
845 for (size_t i = 0; i < nitems(sigcatch); ++i) {
846 EV_SET(&ev, sigcatch[i], EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
847 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) {
848 warn("failed to add kevent to kqueue");
852 if (sigaction(sigcatch[i], &act, NULL) == -1) {
853 warn("failed to apply signal handler");
858 (void)alarm(TIMERINTVL);
860 /* tuck my process id away */
863 dprintf("off & running....\n");
870 * Close our end of the pipe so our
871 * parent knows that we have finished
874 (void)close(ppipe_w);
878 if (kevent(kq, NULL, 0, &ev, 1, NULL) == -1) {
886 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
897 if (ev.ident == SIGTERM || Debug)
910 socklist_recv_sock(struct socklist *sl)
912 struct sockaddr_storage ss;
913 struct sockaddr *sa = (struct sockaddr *)&ss;
916 char line[MAXLINE + 1];
920 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
921 dprintf("received sa_len = %d\n", sslen);
926 logerror("recvfrom");
929 /* Received valid data. */
931 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
932 hname = LocalHostName;
934 hname = cvthname(sa);
936 if (validate(sa, hname) == 0) {
937 dprintf("Message from %s was ignored.", hname);
941 parsemsg(hname, line);
947 unmapped(struct sockaddr *sa)
949 #if defined(INET) && defined(INET6)
950 struct sockaddr_in6 *sin6;
951 struct sockaddr_in sin;
954 sa->sa_family != AF_INET6 ||
955 sa->sa_len != sizeof(*sin6))
958 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
960 sin = (struct sockaddr_in){
961 .sin_family = AF_INET,
962 .sin_len = sizeof(sin),
963 .sin_port = sin6->sin6_port
965 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
966 sizeof(sin.sin_addr));
967 memcpy(sa, &sin, sizeof(sin));
979 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n"
980 " [-b bind_address] [-f config_file]\n"
981 " [-l [mode:]path] [-M fwd_length]\n"
982 " [-m mark_interval] [-O format] [-P pid_file]\n"
983 " [-p log_socket] [-S logpriv_socket]\n");
988 * Removes characters from log messages that are unsafe to display.
989 * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
992 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
998 while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
999 if (mask_C1 && (c & 0x80) && c < 0xA0) {
1004 if (isascii(c) && iscntrl(c)) {
1007 } else if (c == '\t') {
1021 * Parses a syslog message according to RFC 5424, assuming that PRI and
1022 * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
1023 * parsed result is passed to logmsg().
1026 parsemsg_rfc5424(const char *from, int pri, char *msg)
1028 const struct logtime *timestamp;
1029 struct logtime timestamp_remote;
1030 const char *omsg, *hostname, *app_name, *procid, *msgid,
1032 char line[MAXLINE + 1];
1034 #define FAIL_IF(field, expr) do { \
1036 dprintf("Failed to parse " field " from %s: %s\n", \
1041 #define PARSE_CHAR(field, sep) do { \
1042 FAIL_IF(field, *msg != sep); \
1045 #define IF_NOT_NILVALUE(var) \
1046 if (msg[0] == '-' && msg[1] == ' ') { \
1049 } else if (msg[0] == '-' && msg[1] == '\0') { \
1055 IF_NOT_NILVALUE(timestamp) {
1056 /* Parse RFC 3339-like timestamp. */
1057 #define PARSE_NUMBER(dest, length, min, max) do { \
1061 for (i = 0; i < length; ++i) { \
1062 FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9'); \
1063 v = v * 10 + *msg++ - '0'; \
1065 FAIL_IF("TIMESTAMP", v < min || v > max); \
1068 /* Date and time. */
1069 memset(×tamp_remote, 0, sizeof(timestamp_remote));
1070 PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
1071 timestamp_remote.tm.tm_year -= 1900;
1072 PARSE_CHAR("TIMESTAMP", '-');
1073 PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
1074 --timestamp_remote.tm.tm_mon;
1075 PARSE_CHAR("TIMESTAMP", '-');
1076 PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
1077 PARSE_CHAR("TIMESTAMP", 'T');
1078 PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
1079 PARSE_CHAR("TIMESTAMP", ':');
1080 PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
1081 PARSE_CHAR("TIMESTAMP", ':');
1082 PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
1083 /* Perform normalization. */
1084 timegm(×tamp_remote.tm);
1085 /* Optional: fractional seconds. */
1086 if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
1090 for (i = 100000; i != 0; i /= 10) {
1091 if (*msg < '0' || *msg > '9')
1093 timestamp_remote.usec += (*msg++ - '0') * i;
1101 int sign, tz_hour, tz_min;
1103 /* Local time zone offset. */
1104 FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1105 sign = *msg++ == '-' ? -1 : 1;
1106 PARSE_NUMBER(tz_hour, 2, 0, 23);
1107 PARSE_CHAR("TIMESTAMP", ':');
1108 PARSE_NUMBER(tz_min, 2, 0, 59);
1109 timestamp_remote.tm.tm_gmtoff =
1110 sign * (tz_hour * 3600 + tz_min * 60);
1113 PARSE_CHAR("TIMESTAMP", ' ');
1114 timestamp = RemoteAddDate ? NULL : ×tamp_remote;
1117 /* String fields part of the HEADER. */
1118 #define PARSE_STRING(field, var) \
1119 IF_NOT_NILVALUE(var) { \
1121 while (*msg >= '!' && *msg <= '~') \
1123 FAIL_IF(field, var == msg); \
1124 PARSE_CHAR(field, ' '); \
1127 PARSE_STRING("HOSTNAME", hostname);
1128 if (hostname == NULL || !RemoteHostname)
1130 PARSE_STRING("APP-NAME", app_name);
1131 PARSE_STRING("PROCID", procid);
1132 PARSE_STRING("MSGID", msgid);
1135 /* Structured data. */
1136 #define PARSE_SD_NAME() do { \
1137 const char *start; \
1140 while (*msg >= '!' && *msg <= '~' && *msg != '=' && \
1141 *msg != ']' && *msg != '"') \
1143 FAIL_IF("STRUCTURED-NAME", start == msg); \
1145 IF_NOT_NILVALUE(structured_data) {
1146 structured_data = msg;
1148 while (*msg == '[') {
1153 while (*msg == ' ') {
1157 PARSE_CHAR("STRUCTURED-NAME", '=');
1158 PARSE_CHAR("STRUCTURED-NAME", '"');
1159 while (*msg != '"') {
1160 FAIL_IF("STRUCTURED-NAME",
1162 if (*msg++ == '\\') {
1163 FAIL_IF("STRUCTURED-NAME",
1170 PARSE_CHAR("STRUCTURED-NAME", ']');
1172 PARSE_CHAR("STRUCTURED-NAME", ' ');
1175 #undef PARSE_SD_NAME
1179 #undef IF_NOT_NILVALUE
1181 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1182 logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1183 structured_data, line, 0);
1187 * Returns the length of the application name ("TAG" in RFC 3164
1188 * terminology) and process ID from a message if present.
1191 parsemsg_rfc3164_get_app_name_procid(const char *msg, size_t *app_name_length_p,
1192 ptrdiff_t *procid_begin_offset_p, size_t *procid_length_p)
1194 const char *m, *procid_begin;
1195 size_t app_name_length, procid_length;
1199 /* Application name. */
1200 app_name_length = strspn(m,
1201 "abcdefghijklmnopqrstuvwxyz"
1202 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1205 if (app_name_length == 0)
1207 m += app_name_length;
1209 /* Process identifier (optional). */
1212 procid_length = strspn(m, "0123456789");
1213 if (procid_length == 0)
1219 procid_begin = NULL;
1224 if (m[0] != ':' || m[1] != ' ')
1227 *app_name_length_p = app_name_length;
1228 if (procid_begin_offset_p != NULL)
1229 *procid_begin_offset_p =
1230 procid_begin == NULL ? 0 : procid_begin - msg;
1231 if (procid_length_p != NULL)
1232 *procid_length_p = procid_length;
1235 *app_name_length_p = 0;
1236 if (procid_begin_offset_p != NULL)
1237 *procid_begin_offset_p = 0;
1238 if (procid_length_p != NULL)
1239 *procid_length_p = 0;
1243 * Trims the application name ("TAG" in RFC 3164 terminology) and
1244 * process ID from a message if present.
1247 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1248 const char **procid)
1250 char *m, *app_name_begin, *procid_begin;
1251 size_t app_name_length, procid_length;
1252 ptrdiff_t procid_begin_offset;
1257 parsemsg_rfc3164_get_app_name_procid(app_name_begin, &app_name_length,
1258 &procid_begin_offset, &procid_length);
1259 if (app_name_length == 0)
1261 procid_begin = procid_begin_offset == 0 ? NULL :
1262 app_name_begin + procid_begin_offset;
1264 /* Split strings from input. */
1265 app_name_begin[app_name_length] = '\0';
1266 m += app_name_length + 1;
1267 if (procid_begin != NULL) {
1268 procid_begin[procid_length] = '\0';
1269 m += procid_length + 2;
1273 *app_name = app_name_begin;
1274 *procid = procid_begin;
1282 * Parses a syslog message according to RFC 3164, assuming that PRI
1283 * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1284 * result is passed to logmsg().
1287 parsemsg_rfc3164(const char *from, int pri, char *msg)
1289 struct tm tm_parsed;
1290 const struct logtime *timestamp;
1291 struct logtime timestamp_remote;
1292 const char *app_name, *procid;
1294 char line[MAXLINE + 1];
1297 * Parse the TIMESTAMP provided by the remote side. If none is
1298 * found, assume this is not an RFC 3164 formatted message,
1299 * only containing a TAG and a MSG.
1302 if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) ==
1303 msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') {
1304 msg += RFC3164_DATELEN + 1;
1305 if (!RemoteAddDate) {
1311 * As the timestamp does not contain the year
1312 * number, daylight saving time information, nor
1313 * a time zone, attempt to infer it. Due to
1314 * clock skews, the timestamp may even be part
1315 * of the next year. Use the last year for which
1316 * the timestamp is at most one week in the
1319 * This loop can only run for at most three
1320 * iterations before terminating.
1323 localtime_r(&t_now, &tm_now);
1324 for (year = tm_now.tm_year + 1;; --year) {
1325 assert(year >= tm_now.tm_year - 1);
1326 timestamp_remote.tm = tm_parsed;
1327 timestamp_remote.tm.tm_year = year;
1328 timestamp_remote.tm.tm_isdst = -1;
1329 timestamp_remote.usec = 0;
1330 if (mktime(×tamp_remote.tm) <
1331 t_now + 7 * 24 * 60 * 60)
1334 timestamp = ×tamp_remote;
1338 * A single space character MUST also follow the HOSTNAME field.
1340 msglen = strlen(msg);
1341 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1342 if (msg[i] == ' ') {
1343 if (RemoteHostname) {
1351 * Support non RFC compliant messages, without hostname.
1356 if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1357 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1362 /* Remove the TAG, if present. */
1363 parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1364 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1365 logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1369 * Takes a raw input line, extracts PRI and determines whether the
1370 * message is formatted according to RFC 3164 or RFC 5424. Continues
1371 * parsing of addition fields in the message according to those
1372 * standards and prints the message on the appropriate log files.
1375 parsemsg(const char *from, char *msg)
1386 if (msg[0] == '<' && isdigit(msg[1])) {
1387 for (i = 2; i <= 4; i++) {
1388 if (msg[i] == '>') {
1390 n = strtol(msg + 1, &q, 10);
1391 if (errno == 0 && *q == msg[i] && n >= 0 && n <= INT_MAX) {
1401 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1405 * Don't allow users to log kernel messages.
1406 * NOTE: since LOG_KERN == 0 this will also match
1407 * messages with no facility specified.
1409 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1410 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1412 /* Parse VERSION. */
1413 if (i == 0 && msg[0] == '1' && msg[1] == ' ')
1414 parsemsg_rfc5424(from, pri, msg + 2);
1416 parsemsg_rfc3164(from, pri, msg);
1420 * Read /dev/klog while data are available, split into lines.
1423 socklist_recv_file(struct socklist *sl)
1425 char *p, *q, line[MAXLINE + 1];
1430 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1432 line[i + len] = '\0';
1434 if (i < 0 && errno != EINTR && errno != EAGAIN) {
1436 close(sl->sl_socket);
1442 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1447 if (len >= MAXLINE - 1) {
1452 memmove(line, p, len + 1);
1461 * Take a raw input line from /dev/klog, format similar to syslog().
1468 int flags, isprintf, pri;
1470 flags = ISKERNEL | SYNC_FILE; /* fsync after write */
1476 n = strtol(p + 1, &q, 10);
1477 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1484 * Kernel printf's and LOG_CONSOLE messages have been displayed
1485 * on the console already.
1487 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1489 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1491 logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1497 * Match a program or host name against a specification.
1498 * Return a non-0 value if the message must be ignored
1499 * based on the specification.
1502 skip_message(const char *name, const char *spec, int checkcase)
1507 /* Behaviour on explicit match */
1522 s = strstr (spec, name);
1524 s = strcasestr (spec, name);
1527 prev = (s == spec ? ',' : *(s - 1));
1528 next = *(s + strlen (name));
1530 if (prev == ',' && (next == '\0' || next == ','))
1531 /* Explicit match: skip iff the spec is an
1536 /* No explicit match for this name: skip the message iff
1537 the spec is an inclusive one. */
1542 * Match some property of the message against a filter.
1543 * Return a non-0 value if the message must be ignored
1544 * based on the filter.
1547 evaluate_prop_filter(const struct prop_filter *filter, const char *value)
1549 const char *s = NULL;
1550 const int exclude = ((filter->cmp_flags & FILT_FLAG_EXCLUDE) > 0);
1556 if (filter->cmp_type == FILT_CMP_REGEX) {
1557 if (regexec(filter->pflt_re, value, 0, NULL, 0) == 0)
1563 valuelen = strlen(value);
1565 /* a shortcut for equal with different length is always false */
1566 if (filter->cmp_type == FILT_CMP_EQUAL &&
1567 valuelen != filter->pflt_strlen)
1570 if (filter->cmp_flags & FILT_FLAG_ICASE)
1571 s = strcasestr(value, filter->pflt_strval);
1573 s = strstr(value, filter->pflt_strval);
1576 * FILT_CMP_CONTAINS true if s
1577 * FILT_CMP_STARTS true if s && s == value
1578 * FILT_CMP_EQUAL true if s && s == value &&
1579 * valuelen == filter->pflt_strlen
1580 * (and length match is checked
1584 switch (filter->cmp_type) {
1585 case FILT_CMP_STARTS:
1586 case FILT_CMP_EQUAL:
1590 case FILT_CMP_CONTAINS:
1597 /* unknown cmp_type */
1605 * Logs a message to the appropriate log files, users, etc. based on the
1606 * priority. Log messages are formatted according to RFC 3164 or
1607 * RFC 5424 in subsequent fprintlog_*() functions.
1610 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1611 const char *app_name, const char *procid, const char *msgid,
1612 const char *structured_data, const char *msg, int flags)
1615 struct logtime timestamp_now;
1619 char saved[MAXSVLINE], kernel_app_name[100];
1621 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1622 pri, flags, hostname, msg);
1624 (void)gettimeofday(&tv, NULL);
1626 if (timestamp == NULL) {
1627 localtime_r(&now, ×tamp_now.tm);
1628 timestamp_now.usec = tv.tv_usec;
1629 timestamp = ×tamp_now;
1632 /* extract facility and priority level */
1634 fac = LOG_NFACILITIES;
1638 /* Check maximum facility number. */
1639 if (fac > LOG_NFACILITIES)
1642 prilev = LOG_PRI(pri);
1645 * Lookup kernel app name from log prefix if present.
1646 * This is only used for local program specification matching.
1648 if (flags & ISKERNEL) {
1649 size_t kernel_app_name_length;
1651 parsemsg_rfc3164_get_app_name_procid(msg,
1652 &kernel_app_name_length, NULL, NULL);
1653 if (kernel_app_name_length != 0) {
1654 strlcpy(kernel_app_name, msg,
1655 MIN(sizeof(kernel_app_name),
1656 kernel_app_name_length + 1));
1658 kernel_app_name[0] = '\0';
1661 /* log the message to the particular outputs */
1663 consfile.f_lasttime = *timestamp;
1664 fprintlog_first(&consfile, hostname, app_name, procid,
1665 msgid, structured_data, msg, flags);
1670 * Store all of the fields of the message, except the timestamp,
1671 * in a single string. This string is used to detect duplicate
1674 assert(hostname != NULL);
1675 assert(msg != NULL);
1676 savedlen = snprintf(saved, sizeof(saved),
1677 "%d %s %s %s %s %s %s", pri, hostname,
1678 app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1679 msgid == NULL ? "-" : msgid,
1680 structured_data == NULL ? "-" : structured_data, msg);
1682 STAILQ_FOREACH(f, &fhead, next) {
1683 /* skip messages that are incorrect priority */
1684 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1685 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1686 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1688 || f->f_pmask[fac] == INTERNAL_NOPRI)
1691 /* skip messages with the incorrect hostname */
1692 if (skip_message(hostname, f->f_host, 0))
1695 /* skip messages with the incorrect program name */
1696 if (flags & ISKERNEL && kernel_app_name[0] != '\0') {
1697 if (skip_message(kernel_app_name, f->f_program, 1))
1699 } else if (skip_message(app_name == NULL ? "" : app_name,
1703 /* skip messages if a property does not match filter */
1704 if (f->f_prop_filter != NULL &&
1705 f->f_prop_filter->prop_type != FILT_PROP_NOOP) {
1706 switch (f->f_prop_filter->prop_type) {
1708 if (evaluate_prop_filter(f->f_prop_filter,
1712 case FILT_PROP_HOSTNAME:
1713 if (evaluate_prop_filter(f->f_prop_filter,
1717 case FILT_PROP_PROGNAME:
1718 if (evaluate_prop_filter(f->f_prop_filter,
1719 app_name == NULL ? "" : app_name))
1727 /* skip message to console if it has already been printed */
1728 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1731 /* don't output marks to recently written files */
1732 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1736 * suppress duplicate lines to this file
1738 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1739 (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1740 strcmp(saved, f->f_prevline) == 0) {
1741 f->f_lasttime = *timestamp;
1743 dprintf("msg repeated %d times, %ld sec of %d\n",
1744 f->f_prevcount, (long)(now - f->f_time),
1745 repeatinterval[f->f_repeatcount]);
1747 * If domark would have logged this by now,
1748 * flush it now (so we don't hold isolated messages),
1749 * but back off so we'll flush less often
1752 if (now > REPEATTIME(f)) {
1753 fprintlog_successive(f, flags);
1757 /* new line, save it */
1759 fprintlog_successive(f, 0);
1760 f->f_repeatcount = 0;
1762 f->f_lasttime = *timestamp;
1763 static_assert(sizeof(f->f_prevline) == sizeof(saved),
1764 "Space to store saved line incorrect");
1765 (void)strcpy(f->f_prevline, saved);
1766 f->f_prevlen = savedlen;
1767 fprintlog_first(f, hostname, app_name, procid, msgid,
1768 structured_data, msg, flags);
1778 STAILQ_FOREACH(f, &fhead, next) {
1779 if (f->f_type == F_FILE &&
1780 (f->f_flags & FFLAG_NEEDSYNC) != 0) {
1781 f->f_flags &= ~FFLAG_NEEDSYNC;
1782 (void)fsync(f->f_file);
1785 needdofsync = false;
1789 * List of iovecs to which entries can be appended.
1790 * Used for constructing the message to be logged.
1793 struct iovec iov[TTYMSG_IOV_MAX];
1799 iovlist_init(struct iovlist *il)
1807 iovlist_append(struct iovlist *il, const char *str)
1811 /* Discard components if we've run out of iovecs. */
1812 if (il->iovcnt < nitems(il->iov)) {
1814 il->iov[il->iovcnt++] = (struct iovec){
1815 .iov_base = __DECONST(char *, str),
1818 il->totalsize += size;
1822 #if defined(INET) || defined(INET6)
1824 iovlist_truncate(struct iovlist *il, size_t size)
1829 while (il->totalsize > size) {
1830 diff = il->totalsize - size;
1831 last = &il->iov[il->iovcnt - 1];
1832 if (diff >= last->iov_len) {
1833 /* Remove the last iovec entirely. */
1835 il->totalsize -= last->iov_len;
1837 /* Remove the last iovec partially. */
1838 last->iov_len -= diff;
1839 il->totalsize -= diff;
1846 fprintlog_write(struct filed *f, struct iovlist *il, int flags)
1848 struct msghdr msghdr;
1850 struct socklist *sl;
1854 switch (f->f_type) {
1856 dprintf(" %s", f->fu_forw_hname);
1857 switch (f->fu_forw_addr->ai_family) {
1861 ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1867 ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1874 #if defined(INET) || defined(INET6)
1875 /* Truncate messages to maximum forward length. */
1876 iovlist_truncate(il, MaxForwardLen);
1880 for (r = f->fu_forw_addr; r; r = r->ai_next) {
1881 memset(&msghdr, 0, sizeof(msghdr));
1882 msghdr.msg_name = r->ai_addr;
1883 msghdr.msg_namelen = r->ai_addrlen;
1884 msghdr.msg_iov = il->iov;
1885 msghdr.msg_iovlen = il->iovcnt;
1886 STAILQ_FOREACH(sl, &shead, next) {
1887 if (sl->sl_socket < 0)
1889 if (sl->sl_sa == NULL ||
1890 sl->sl_family == AF_UNSPEC ||
1891 sl->sl_family == AF_LOCAL)
1893 lsent = sendmsg(sl->sl_socket, &msghdr, 0);
1894 if (lsent == (ssize_t)il->totalsize)
1897 if (lsent == (ssize_t)il->totalsize && !send_to_all)
1900 dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize);
1901 if (lsent != (ssize_t)il->totalsize) {
1915 /* case ENOTSOCK: */
1917 /* case EMSGSIZE: */
1920 /* case ECONNREFUSED: */
1922 dprintf("removing entry: errno=%d\n", e);
1923 f->f_type = F_UNUSED;
1930 dprintf(" %s\n", f->fu_fname);
1931 iovlist_append(il, "\n");
1932 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1934 * If writev(2) fails for potentially transient errors
1935 * like the filesystem being full, ignore it.
1936 * Otherwise remove this logfile from the list.
1938 if (errno != ENOSPC) {
1942 logerror(f->fu_fname);
1944 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1945 f->f_flags |= FFLAG_NEEDSYNC;
1951 dprintf(" %s\n", f->fu_pipe_pname);
1952 iovlist_append(il, "\n");
1953 if (f->fu_pipe_pd == -1) {
1954 if ((f->f_file = p_open(f->fu_pipe_pname,
1955 &f->fu_pipe_pd)) < 0) {
1956 logerror(f->fu_pipe_pname);
1960 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1961 logerror(f->fu_pipe_pname);
1967 if (flags & IGN_CONS) {
1968 dprintf(" (ignored)\n");
1974 dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1975 iovlist_append(il, "\r\n");
1976 errno = 0; /* ttymsg() only sometimes returns an errno */
1977 if ((msgret = ttymsg(il->iov, il->iovcnt, f->fu_fname, 10))) {
1978 f->f_type = F_UNUSED;
1986 iovlist_append(il, "\r\n");
1987 wallmsg(f, il->iov, il->iovcnt);
1995 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name,
1996 const char *procid, const char *msgid, const char *structured_data,
1997 const char *msg, int flags)
2002 char timebuf[33], priority_number[5];
2005 if (f->f_type == F_WALL)
2006 iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n");
2007 iovlist_append(&il, "<");
2008 snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri);
2009 iovlist_append(&il, priority_number);
2010 iovlist_append(&il, ">1 ");
2011 if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z",
2012 &f->f_lasttime.tm) == sizeof(timebuf) - 2) {
2013 /* Add colon to the time zone offset, which %z doesn't do. */
2015 timebuf[31] = timebuf[30];
2016 timebuf[30] = timebuf[29];
2019 /* Overwrite space for microseconds with actual value. */
2020 usec = f->f_lasttime.usec;
2021 for (i = 25; i >= 20; --i) {
2022 timebuf[i] = usec % 10 + '0';
2025 iovlist_append(&il, timebuf);
2027 iovlist_append(&il, "-");
2028 iovlist_append(&il, " ");
2029 iovlist_append(&il, hostname);
2030 iovlist_append(&il, " ");
2031 iovlist_append(&il, app_name == NULL ? "-" : app_name);
2032 iovlist_append(&il, " ");
2033 iovlist_append(&il, procid == NULL ? "-" : procid);
2034 iovlist_append(&il, " ");
2035 iovlist_append(&il, msgid == NULL ? "-" : msgid);
2036 iovlist_append(&il, " ");
2037 iovlist_append(&il, structured_data == NULL ? "-" : structured_data);
2038 iovlist_append(&il, " ");
2039 iovlist_append(&il, msg);
2041 fprintlog_write(f, &il, flags);
2045 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name,
2046 const char *procid, const char *msg, int flags)
2050 int facility, priority;
2051 char timebuf[RFC3164_DATELEN + 1], facility_number[5],
2053 bool facility_found, priority_found;
2055 if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
2056 &f->f_lasttime.tm) == 0)
2060 switch (f->f_type) {
2062 /* Message forwarded over the network. */
2063 iovlist_append(&il, "<");
2064 snprintf(priority_number, sizeof(priority_number), "%d",
2066 iovlist_append(&il, priority_number);
2067 iovlist_append(&il, ">");
2068 iovlist_append(&il, timebuf);
2069 if (strcasecmp(hostname, LocalHostName) != 0) {
2070 iovlist_append(&il, " Forwarded from ");
2071 iovlist_append(&il, hostname);
2072 iovlist_append(&il, ":");
2074 iovlist_append(&il, " ");
2078 /* Message written to terminals. */
2079 iovlist_append(&il, "\r\n\aMessage from syslogd@");
2080 iovlist_append(&il, hostname);
2081 iovlist_append(&il, " at ");
2082 iovlist_append(&il, timebuf);
2083 iovlist_append(&il, " ...\r\n");
2087 /* Message written to files. */
2088 iovlist_append(&il, timebuf);
2089 iovlist_append(&il, " ");
2092 iovlist_append(&il, "<");
2094 facility = f->f_prevpri & LOG_FACMASK;
2095 facility_found = false;
2096 if (LogFacPri > 1) {
2097 for (c = facilitynames; c->c_name; c++) {
2098 if (c->c_val == facility) {
2099 iovlist_append(&il, c->c_name);
2100 facility_found = true;
2105 if (!facility_found) {
2106 snprintf(facility_number,
2107 sizeof(facility_number), "%d",
2109 iovlist_append(&il, facility_number);
2112 iovlist_append(&il, ".");
2114 priority = LOG_PRI(f->f_prevpri);
2115 priority_found = false;
2116 if (LogFacPri > 1) {
2117 for (c = prioritynames; c->c_name; c++) {
2118 if (c->c_val == priority) {
2119 iovlist_append(&il, c->c_name);
2120 priority_found = true;
2125 if (!priority_found) {
2126 snprintf(priority_number,
2127 sizeof(priority_number), "%d", priority);
2128 iovlist_append(&il, priority_number);
2131 iovlist_append(&il, "> ");
2134 iovlist_append(&il, hostname);
2135 iovlist_append(&il, " ");
2139 /* Message body with application name and process ID prefixed. */
2140 if (app_name != NULL) {
2141 iovlist_append(&il, app_name);
2142 if (procid != NULL) {
2143 iovlist_append(&il, "[");
2144 iovlist_append(&il, procid);
2145 iovlist_append(&il, "]");
2147 iovlist_append(&il, ": ");
2149 iovlist_append(&il, msg);
2151 fprintlog_write(f, &il, flags);
2155 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
2156 const char *procid, const char *msgid __unused,
2157 const char *structured_data __unused, const char *msg, int flags)
2160 dprintf("Logging to %s", TypeNames[f->f_type]);
2163 if (f->f_type == F_UNUSED) {
2168 if (RFC3164OutputFormat)
2169 fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags);
2171 fprintlog_rfc5424(f, hostname, app_name, procid, msgid,
2172 structured_data, msg, flags);
2176 * Prints a message to a log file that the previously logged message was
2177 * received multiple times.
2180 fprintlog_successive(struct filed *f, int flags)
2184 assert(f->f_prevcount > 0);
2185 snprintf(msg, sizeof(msg), "last message repeated %d times",
2187 fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
2192 * WALLMSG -- Write a message to the world at large
2194 * Write the specified message to either the entire
2195 * world, or a list of approved users.
2198 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
2200 static int reenter; /* avoid calling ourselves */
2209 while ((ut = getutxent()) != NULL) {
2210 if (ut->ut_type != USER_PROCESS)
2212 if (f->f_type == F_WALL) {
2213 if ((p = ttymsg(iov, iovlen, ut->ut_line,
2214 TTYMSGTIME)) != NULL) {
2215 errno = 0; /* already in msg */
2220 /* should we send the message to this user? */
2221 for (i = 0; i < MAXUNAMES; i++) {
2222 if (!f->fu_uname[i][0])
2224 if (!strcmp(f->fu_uname[i], ut->ut_user)) {
2225 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
2226 TTYMSGTIME)) != NULL) {
2227 errno = 0; /* already in msg */
2239 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
2242 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
2244 static char device[1024];
2245 static char errbuf[1024];
2248 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
2250 if (stat(device, &sb) < 0) {
2251 (void) snprintf(errbuf, sizeof(errbuf),
2252 "%s: %s", device, strerror(errno));
2255 if ((sb.st_mode & S_IWGRP) == 0)
2256 /* Messages disabled. */
2258 return (ttymsg(iov, iovcnt, line, tmout));
2262 * Return a printable representation of a host address.
2265 cvthname(struct sockaddr *f)
2268 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
2270 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
2271 error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
2274 dprintf("Malformed from address %s\n", gai_strerror(error));
2277 dprintf("cvthname(%s)\n", ip);
2282 error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
2283 NULL, 0, NI_NAMEREQD);
2285 dprintf("Host name for your address (%s) unknown\n", ip);
2289 if (hl > 0 && hname[hl-1] == '.')
2291 /* RFC 5424 prefers logging FQDNs. */
2292 if (RFC3164OutputFormat)
2293 trimdomain(hname, hl);
2298 * Print syslogd errors some place.
2301 logerror(const char *msg)
2304 static int recursed = 0;
2306 /* If there's an error while trying to log an error, give up. */
2311 (void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2316 dprintf("%s\n", msg);
2317 logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2326 struct socklist *sl;
2329 STAILQ_FOREACH(f, &fhead, next) {
2330 /* flush any pending output */
2332 fprintlog_successive(f, 0);
2333 /* close our end of the pipe */
2334 if (f->f_type == F_PIPE)
2338 dprintf("syslogd: exiting on signal %d\n", signo);
2339 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2343 STAILQ_FOREACH(sl, &shead, next) {
2344 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL) {
2345 if (unlinkat(sl->sl_dirfd, sl->sl_name, 0) == -1) {
2346 dprintf("Failed to unlink %s: %s", sl->sl_name,
2351 pidfile_remove(pfh);
2357 configfiles(const struct dirent *dp)
2362 if (dp->d_name[0] == '.')
2365 ext_len = sizeof(include_ext) -1;
2367 if (dp->d_namlen <= ext_len)
2370 p = &dp->d_name[dp->d_namlen - ext_len];
2371 if (strcmp(p, include_ext) != 0)
2378 parseconfigfile(FILE *cf, bool allow_includes)
2381 struct dirent **ent;
2382 char cline[LINE_MAX];
2383 char host[MAXHOSTNAMELEN];
2384 char prog[LINE_MAX];
2385 char file[MAXPATHLEN];
2386 char pfilter[LINE_MAX];
2392 * Foreach line in the conf table, open that file.
2394 include_len = sizeof(include_str) - 1;
2395 (void)strlcpy(host, "*", sizeof(host));
2396 (void)strlcpy(prog, "*", sizeof(prog));
2397 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2398 while (fgets(cline, sizeof(cline), cf) != NULL) {
2400 * check for end-of-section, comments, strip off trailing
2401 * spaces and newline character. #!prog is treated specially:
2402 * following lines apply only to that program.
2404 for (p = cline; isspace(*p); ++p)
2408 if (allow_includes &&
2409 strncmp(p, include_str, include_len) == 0 &&
2410 isspace(p[include_len])) {
2415 while (*tmp != '\0' && !isspace(*tmp))
2418 dprintf("Trying to include files in '%s'\n", p);
2419 nents = scandir(p, &ent, configfiles, alphasort);
2421 dprintf("Unable to open '%s': %s\n", p,
2425 for (i = 0; i < nents; i++) {
2426 if (snprintf(file, sizeof(file), "%s/%s", p,
2427 ent[i]->d_name) >= (int)sizeof(file)) {
2428 dprintf("ignoring path too long: "
2429 "'%s/%s'\n", p, ent[i]->d_name);
2434 cf2 = fopen(file, "r");
2437 dprintf("reading %s\n", file);
2438 parseconfigfile(cf2, false);
2446 if (*p == '\0' || strchr("!+-:", *p) == NULL)
2449 if (*p == '+' || *p == '-') {
2453 if (*p == '\0' || *p == '*') {
2454 (void)strlcpy(host, "*", sizeof(host));
2459 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2460 if (!isalnum(*p) && *p != '.' && *p != '-'
2461 && *p != ',' && *p != ':' && *p != '%')
2472 if (*p == '\0' || *p == '*') {
2473 (void)strlcpy(prog, "*", sizeof(prog));
2476 for (i = 0; i < LINE_MAX - 1; i++) {
2477 if (!isprint(p[i]) || isspace(p[i]))
2488 if (*p == '\0' || *p == '*') {
2489 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2492 (void)strlcpy(pfilter, p, sizeof(pfilter));
2495 for (p = cline + 1; *p != '\0'; p++) {
2498 if (*(p - 1) == '\\') {
2506 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2508 cfline(cline, prog, host, pfilter);
2513 readconfigfile(const char *path)
2517 if ((cf = fopen(path, "r")) != NULL) {
2518 parseconfigfile(cf, true);
2521 dprintf("cannot open %s\n", ConfFile);
2522 cfline("*.ERR\t/dev/console", "*", "*", "*");
2523 cfline("*.PANIC\t*", "*", "*", "*");
2528 * Close all open log files.
2535 while (!STAILQ_EMPTY(&fhead)) {
2536 f = STAILQ_FIRST(&fhead);
2537 STAILQ_REMOVE_HEAD(&fhead, next);
2539 /* flush any pending output */
2541 fprintlog_successive(f, 0);
2543 switch (f->f_type) {
2557 if (f->f_prop_filter) {
2558 switch (f->f_prop_filter->cmp_type) {
2559 case FILT_CMP_REGEX:
2560 regfree(f->f_prop_filter->pflt_re);
2561 free(f->f_prop_filter->pflt_re);
2563 case FILT_CMP_CONTAINS:
2564 case FILT_CMP_EQUAL:
2565 case FILT_CMP_STARTS:
2566 free(f->f_prop_filter->pflt_strval);
2569 free(f->f_prop_filter);
2576 * INIT -- Initialize syslogd from configuration table
2583 char oldLocalHostName[MAXHOSTNAMELEN];
2584 char hostMsg[2*MAXHOSTNAMELEN+40];
2585 char bootfileMsg[MAXLINE + 1];
2590 * Load hostname (may have changed).
2593 (void)strlcpy(oldLocalHostName, LocalHostName,
2594 sizeof(oldLocalHostName));
2595 if (gethostname(LocalHostName, sizeof(LocalHostName)))
2596 err(EX_OSERR, "gethostname() failed");
2597 if ((p = strchr(LocalHostName, '.')) != NULL) {
2598 /* RFC 5424 prefers logging FQDNs. */
2599 if (RFC3164OutputFormat)
2601 LocalDomain = p + 1;
2607 * Load / reload timezone data (in case it changed).
2609 * Just calling tzset() again does not work, the timezone code
2610 * caches the result. However, by setting the TZ variable, one
2611 * can defeat the caching and have the timezone code really
2612 * reload the timezone data. Respect any initial setting of
2613 * TZ, in case the system is configured specially.
2615 dprintf("loading timezone data via tzset()\n");
2619 setenv("TZ", ":/etc/localtime", 1);
2624 Initialized = false;
2626 readconfigfile(ConfFile);
2633 STAILQ_FOREACH(f, &fhead, next) {
2634 for (i = 0; i <= LOG_NFACILITIES; i++)
2635 if (f->f_pmask[i] == INTERNAL_NOPRI)
2638 printf("%d ", f->f_pmask[i]);
2639 printf("%s: ", TypeNames[f->f_type]);
2640 switch (f->f_type) {
2642 printf("%s", f->fu_fname);
2647 printf("%s%s", _PATH_DEV, f->fu_fname);
2651 switch (f->fu_forw_addr->ai_family) {
2654 port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2659 port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2667 f->fu_forw_hname, port);
2669 printf("%s", f->fu_forw_hname);
2674 printf("%s", f->fu_pipe_pname);
2678 for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2679 printf("%s, ", f->fu_uname[i]);
2685 printf(" (%s)", f->f_program);
2690 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2691 NULL, NULL, "restart", 0);
2692 dprintf("syslogd: restarted\n");
2694 * Log a change in hostname, but only on reload.
2696 if (reload && strcmp(oldLocalHostName, LocalHostName) != 0) {
2697 (void)snprintf(hostMsg, sizeof(hostMsg),
2698 "hostname changed, \"%s\" to \"%s\"",
2699 oldLocalHostName, LocalHostName);
2700 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2701 NULL, NULL, NULL, hostMsg, 0);
2702 dprintf("%s\n", hostMsg);
2705 * Log the kernel boot file if we aren't going to use it as
2706 * the prefix, and if this is *not* a reload.
2708 if (!reload && !use_bootfile) {
2709 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2710 "kernel boot file is %s", bootfile);
2711 logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2712 NULL, NULL, NULL, bootfileMsg, 0);
2713 dprintf("%s\n", bootfileMsg);
2718 * Compile property-based filter.
2720 static struct prop_filter *
2721 prop_filter_compile(const char *cfilter)
2723 struct prop_filter *pfilter;
2724 char *filter, *filter_endpos, *filter_begpos, *p;
2725 char **ap, *argv[2] = {NULL, NULL};
2726 int re_flags = REG_NOSUB;
2729 pfilter = calloc(1, sizeof(*pfilter));
2730 if (pfilter == NULL) {
2731 logerror("pfilter calloc");
2734 if (*cfilter == '*') {
2735 pfilter->prop_type = FILT_PROP_NOOP;
2738 filter = strdup(cfilter);
2739 if (filter == NULL) {
2743 filter_begpos = filter;
2746 * Here's some filter examples mentioned in syslog.conf(5)
2747 * 'msg, contains, ".*Deny.*"'
2748 * 'programname, regex, "^bird6?$"'
2749 * 'hostname, icase_ereregex, "^server-(dcA|podB)-rack1[0-9]{2}\\..*"'
2753 * Split filter into 3 parts: property name (argv[0]),
2754 * cmp type (argv[1]) and lvalue for comparison (filter).
2756 for (ap = argv; (*ap = strsep(&filter, ", \t\n")) != NULL;) {
2758 if (++ap >= &argv[2])
2762 if (argv[0] == NULL || argv[1] == NULL) {
2763 logerror("filter parse error");
2767 /* fill in prop_type */
2768 if (strcasecmp(argv[0], "msg") == 0)
2769 pfilter->prop_type = FILT_PROP_MSG;
2770 else if (strcasecmp(argv[0], "hostname") == 0)
2771 pfilter->prop_type = FILT_PROP_HOSTNAME;
2772 else if (strcasecmp(argv[0], "source") == 0)
2773 pfilter->prop_type = FILT_PROP_HOSTNAME;
2774 else if (strcasecmp(argv[0], "programname") == 0)
2775 pfilter->prop_type = FILT_PROP_PROGNAME;
2777 logerror("unknown property");
2781 /* full in cmp_flags (i.e. !contains, icase_regex, etc.) */
2782 if (*argv[1] == '!') {
2783 pfilter->cmp_flags |= FILT_FLAG_EXCLUDE;
2786 if (strncasecmp(argv[1], "icase_", (sizeof("icase_") - 1)) == 0) {
2787 pfilter->cmp_flags |= FILT_FLAG_ICASE;
2788 argv[1] += sizeof("icase_") - 1;
2791 /* fill in cmp_type */
2792 if (strcasecmp(argv[1], "contains") == 0)
2793 pfilter->cmp_type = FILT_CMP_CONTAINS;
2794 else if (strcasecmp(argv[1], "isequal") == 0)
2795 pfilter->cmp_type = FILT_CMP_EQUAL;
2796 else if (strcasecmp(argv[1], "startswith") == 0)
2797 pfilter->cmp_type = FILT_CMP_STARTS;
2798 else if (strcasecmp(argv[1], "regex") == 0)
2799 pfilter->cmp_type = FILT_CMP_REGEX;
2800 else if (strcasecmp(argv[1], "ereregex") == 0) {
2801 pfilter->cmp_type = FILT_CMP_REGEX;
2802 re_flags |= REG_EXTENDED;
2804 logerror("unknown cmp function");
2809 * Handle filter value
2813 /* remove leading whitespace and check for '"' next character */
2814 filter += strspn(filter, ", \t\n");
2815 if (*filter != '"' || strlen(filter) < 3) {
2816 logerror("property value parse error");
2822 /* process possible backslash (\") escaping */
2824 filter_endpos = filter;
2825 for (p = filter; *p != '\0'; p++) {
2826 if (*p == '\\' && !escaped) {
2828 /* do not shift filter_endpos */
2831 if (*p == '"' && !escaped) {
2835 /* we've seen some esc symbols, need to compress the line */
2836 if (filter_endpos != p)
2837 *filter_endpos = *p;
2843 *filter_endpos = '\0';
2846 /* We should not have anything but whitespace left after closing '"' */
2847 if (*p != '\0' && strspn(p, " \t\n") != strlen(p)) {
2848 logerror("property value parse error");
2852 if (pfilter->cmp_type == FILT_CMP_REGEX) {
2853 pfilter->pflt_re = calloc(1, sizeof(*pfilter->pflt_re));
2854 if (pfilter->pflt_re == NULL) {
2855 logerror("RE calloc() error");
2858 if (pfilter->cmp_flags & FILT_FLAG_ICASE)
2859 re_flags |= REG_ICASE;
2860 if (regcomp(pfilter->pflt_re, filter, re_flags) != 0) {
2861 logerror("RE compilation error");
2865 pfilter->pflt_strval = strdup(filter);
2866 pfilter->pflt_strlen = strlen(filter);
2869 free(filter_begpos);
2872 free(filter_begpos);
2873 free(pfilter->pflt_re);
2879 parse_selector(const char *p, struct filed *f)
2882 int pri_done = 0, pri_cmp = 0, pri_invert = 0;
2883 char *bp, buf[LINE_MAX], ebuf[100];
2886 /* find the end of this facility name list */
2887 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.';)
2890 /* get the priority comparison */
2915 /* collect priority name */
2916 for (bp = buf; *q != '\0' && !strchr("\t,; ", *q); )
2921 while (strchr(",;", *q))
2924 /* decode priority name */
2927 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2929 /* Ignore trailing spaces. */
2930 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2933 pri = decode(buf, prioritynames);
2936 (void)snprintf(ebuf, sizeof(ebuf),
2937 "unknown priority name \"%s\"", buf);
2944 pri_cmp = UniquePriority ? PRI_EQ : (PRI_EQ | PRI_GT);
2946 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2948 /* scan facilities */
2949 while (*p != '\0' && !strchr("\t.; ", *p)) {
2950 for (bp = buf; *p != '\0' && !strchr("\t,;. ", *p); )
2955 for (i = 0; i < LOG_NFACILITIES; i++) {
2956 f->f_pmask[i] = pri;
2957 f->f_pcmp[i] = pri_cmp;
2960 i = decode(buf, facilitynames);
2963 (void)snprintf(ebuf, sizeof(ebuf),
2964 "unknown facility name \"%s\"",
2970 f->f_pmask[i >> 3] = pri;
2971 f->f_pcmp[i >> 3] = pri_cmp;
2973 while (*p == ',' || *p == ' ')
2980 parse_action(const char *p, struct filed *f)
2982 struct addrinfo hints, *res;
2999 * scan forward to see if there is a port defined.
3000 * so we can't use strlcpy..
3002 i = sizeof(f->fu_forw_hname);
3003 tp = f->fu_forw_hname;
3007 * an ipv6 address should start with a '[' in that case
3008 * we should scan for a ']'
3014 while (*p && (*p != endkey) && (i-- > 0)) {
3017 if (endkey == ']' && *p == endkey)
3021 /* See if we copied a domain and have a port */
3027 hints = (struct addrinfo){
3028 .ai_family = family,
3029 .ai_socktype = SOCK_DGRAM
3031 error = getaddrinfo(f->fu_forw_hname,
3032 p ? p : "syslog", &hints, &res);
3034 logerror(gai_strerror(error));
3037 f->fu_forw_addr = res;
3042 if ((f->f_file = open(p, logflags, 0600)) < 0) {
3043 f->f_type = F_UNUSED;
3048 f->f_flags |= FFLAG_SYNC;
3049 if (isatty(f->f_file)) {
3050 if (strcmp(p, _PATH_CONSOLE) == 0)
3051 f->f_type = F_CONSOLE;
3054 (void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
3055 sizeof(f->fu_fname));
3057 (void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
3064 (void)strlcpy(f->fu_pipe_pname, p + 1,
3065 sizeof(f->fu_pipe_pname));
3074 for (i = 0; i < MAXUNAMES && *p; i++) {
3075 for (q = p; *q && *q != ','; )
3077 (void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
3078 if ((q - p) >= MAXLOGNAME)
3079 f->fu_uname[i][MAXLOGNAME - 1] = '\0';
3081 f->fu_uname[i][q - p] = '\0';
3082 while (*q == ',' || *q == ' ')
3086 f->f_type = F_USERS;
3092 * Crack a configuration file line
3095 cfline(const char *line, const char *prog, const char *host,
3096 const char *pfilter)
3101 dprintf("cfline(\"%s\", f, \"%s\", \"%s\", \"%s\")\n", line, prog,
3104 f = calloc(1, sizeof(*f));
3109 errno = 0; /* keep strerror() stuff out of logerror messages */
3111 for (int i = 0; i <= LOG_NFACILITIES; i++)
3112 f->f_pmask[i] = INTERNAL_NOPRI;
3114 /* save hostname if any */
3115 if (host && *host == '*')
3120 f->f_host = strdup(host);
3121 if (f->f_host == NULL) {
3125 hl = strlen(f->f_host);
3126 if (hl > 0 && f->f_host[hl-1] == '.')
3127 f->f_host[--hl] = '\0';
3128 /* RFC 5424 prefers logging FQDNs. */
3129 if (RFC3164OutputFormat)
3130 trimdomain(f->f_host, hl);
3133 /* save program name if any */
3134 if (prog && *prog == '*')
3137 f->f_program = strdup(prog);
3138 if (f->f_program == NULL) {
3145 f->f_prop_filter = prop_filter_compile(pfilter);
3146 if (f->f_prop_filter == NULL) {
3147 logerror("filter compile error");
3152 /* scan through the list of selectors */
3153 for (p = line; *p != '\0' && *p != '\t' && *p != ' ';)
3154 p = parse_selector(p, f);
3156 /* skip to action part */
3157 while (*p == '\t' || *p == ' ')
3161 STAILQ_INSERT_TAIL(&fhead, f, next);
3165 * Decode a symbolic name to a numeric value
3168 decode(const char *name, const CODE *codetab)
3174 return (atoi(name));
3176 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3178 *p = tolower(*name);
3183 for (c = codetab; c->c_name; c++)
3184 if (!strcmp(buf, c->c_name))
3194 struct deadq_entry *dq, *dq0;
3196 now = time((time_t *)NULL);
3197 MarkSeq += TIMERINTVL;
3198 if (MarkSeq >= MarkInterval) {
3199 logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
3200 "-- MARK --", MARK);
3204 STAILQ_FOREACH(f, &fhead, next) {
3205 if (f->f_prevcount && now >= REPEATTIME(f)) {
3206 dprintf("flush %s: repeated %d times, %d sec.\n",
3207 TypeNames[f->f_type], f->f_prevcount,
3208 repeatinterval[f->f_repeatcount]);
3209 fprintlog_successive(f, 0);
3214 /* Walk the dead queue, and see if we should signal somebody. */
3215 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
3216 switch (dq->dq_timeout) {
3218 /* Already signalled once, try harder now. */
3219 (void)pdkill(dq->dq_procdesc, SIGKILL);
3220 (void)deadq_remove(dq);
3224 if (pdkill(dq->dq_procdesc, SIGTERM) != 0)
3225 (void)deadq_remove(dq);
3233 (void)alarm(TIMERINTVL);
3237 * fork off and become a daemon, but wait for the child to come online
3238 * before returning to the parent, or we get disk thrashing at boot etc.
3241 waitdaemon(int maxwait)
3243 struct pollfd pollfd;
3244 int events, pipefd[2], status;
3247 if (pipe(pipefd) == -1) {
3248 warn("failed to daemonize, pipe");
3253 warn("failed to daemonize, fork");
3255 } else if (pid > 0) {
3257 pollfd.fd = pipefd[0];
3258 pollfd.events = POLLHUP;
3259 events = poll(&pollfd, 1, maxwait * 1000);
3261 err(1, "failed to daemonize, poll");
3262 else if (events == 0)
3263 errx(1, "timed out waiting for child");
3264 if (waitpid(pid, &status, WNOHANG) > 0) {
3265 if (WIFEXITED(status))
3266 errx(1, "child pid %d exited with return code %d",
3267 pid, WEXITSTATUS(status));
3268 if (WIFSIGNALED(status))
3269 errx(1, "child pid %d exited on signal %d%s",
3270 pid, WTERMSIG(status),
3271 WCOREDUMP(status) ? " (core dumped)" : "");
3276 if (setsid() == -1) {
3277 warn("failed to daemonize, setsid");
3281 (void)dup2(nulldesc, STDIN_FILENO);
3282 (void)dup2(nulldesc, STDOUT_FILENO);
3283 (void)dup2(nulldesc, STDERR_FILENO);
3288 * Add `s' to the list of allowable peer addresses to accept messages
3291 * `s' is a string in the form:
3293 * [*]domainname[:{servicename|portnumber|*}]
3297 * netaddr/maskbits[:{servicename|portnumber|*}]
3299 * Returns false on error, true if the argument was valid.
3302 #if defined(INET) || defined(INET6)
3305 allowaddr(char *s __unused)
3308 #if defined(INET) || defined(INET6)
3310 struct allowedpeer *ap;
3313 struct addrinfo hints, *res = NULL;
3315 in_addr_t *addrp, *maskp;
3318 uint32_t *addr6p, *mask6p;
3320 char ip[NI_MAXHOST];
3322 ap = calloc(1, sizeof(*ap));
3324 err(1, "malloc failed");
3327 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
3330 if ((cp1 = strrchr(cp1, ':'))) {
3331 /* service/port provided */
3333 if (strlen(cp1) == 1 && *cp1 == '*')
3334 /* any port allowed */
3336 else if ((se = getservbyname(cp1, "udp"))) {
3337 ap->port = ntohs(se->s_port);
3339 ap->port = strtol(cp1, &cp2, 0);
3340 /* port not numeric */
3345 if ((se = getservbyname("syslog", "udp")))
3346 ap->port = ntohs(se->s_port);
3348 /* sanity, should not happen */
3352 if ((cp1 = strchr(s, '/')) != NULL &&
3353 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
3355 if ((masklen = atoi(cp1 + 1)) < 0)
3360 cp2 = s + strlen(s) - 1;
3371 hints = (struct addrinfo){
3372 .ai_family = PF_UNSPEC,
3373 .ai_socktype = SOCK_DGRAM,
3374 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3376 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
3377 ap->isnumeric = true;
3378 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
3379 ap->a_mask = (struct sockaddr_storage){
3380 .ss_family = res->ai_family,
3381 .ss_len = res->ai_addrlen
3383 switch (res->ai_family) {
3386 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
3387 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
3389 /* use default netmask */
3390 if (IN_CLASSA(ntohl(*addrp)))
3391 *maskp = htonl(IN_CLASSA_NET);
3392 else if (IN_CLASSB(ntohl(*addrp)))
3393 *maskp = htonl(IN_CLASSB_NET);
3395 *maskp = htonl(IN_CLASSC_NET);
3396 } else if (masklen == 0) {
3398 } else if (masklen <= 32) {
3399 /* convert masklen to netmask */
3400 *maskp = htonl(~((1 << (32 - masklen)) - 1));
3404 /* Lose any host bits in the network number. */
3415 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
3416 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
3417 /* convert masklen to netmask */
3418 while (masklen > 0) {
3421 htonl(~(0xffffffff >> masklen));
3425 *mask6p++ = 0xffffffff;
3437 /* arg `s' is domain name */
3438 ap->isnumeric = false;
3449 STAILQ_INSERT_TAIL(&aphead, ap, next);
3452 printf("allowaddr: rule ");
3453 if (ap->isnumeric) {
3454 printf("numeric, ");
3455 getnameinfo(sstosa(&ap->a_addr),
3456 (sstosa(&ap->a_addr))->sa_len,
3457 ip, sizeof(ip), NULL, 0, NI_NUMERICHOST);
3458 printf("addr = %s, ", ip);
3459 getnameinfo(sstosa(&ap->a_mask),
3460 (sstosa(&ap->a_mask))->sa_len,
3461 ip, sizeof(ip), NULL, 0, NI_NUMERICHOST);
3462 printf("mask = %s; ", ip);
3464 printf("domainname = %s; ", ap->a_name);
3466 printf("port = %d\n", ap->port);
3479 * Validate that the remote peer has permission to log to us.
3482 validate(struct sockaddr *sa, const char *hname)
3485 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3486 struct allowedpeer *ap;
3488 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3491 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3493 struct addrinfo hints, *res;
3496 /* traditional behaviour, allow everything */
3497 if (STAILQ_EMPTY(&aphead))
3500 (void)strlcpy(name, hname, sizeof(name));
3501 hints = (struct addrinfo){
3502 .ai_family = PF_UNSPEC,
3503 .ai_socktype = SOCK_DGRAM,
3504 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3506 if (getaddrinfo(name, NULL, &hints, &res) == 0)
3508 else if (strchr(name, '.') == NULL) {
3509 strlcat(name, ".", sizeof(name));
3510 strlcat(name, LocalDomain, sizeof(name));
3512 if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
3513 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3514 return (false); /* for safety, should not occur */
3515 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3519 /* now, walk down the list */
3521 STAILQ_FOREACH(ap, &aphead, next) {
3523 if (ap->port != 0 && ap->port != sport) {
3524 dprintf("rejected in rule %d due to port mismatch.\n",
3529 if (ap->isnumeric) {
3530 if (ap->a_addr.ss_family != sa->sa_family) {
3531 dprintf("rejected in rule %d due to address family mismatch.\n", i);
3535 else if (ap->a_addr.ss_family == AF_INET) {
3537 a4p = satosin(&ap->a_addr);
3538 m4p = satosin(&ap->a_mask);
3539 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3540 != a4p->sin_addr.s_addr) {
3541 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3547 else if (ap->a_addr.ss_family == AF_INET6) {
3548 sin6 = satosin6(sa);
3549 a6p = satosin6(&ap->a_addr);
3550 m6p = satosin6(&ap->a_mask);
3551 if (a6p->sin6_scope_id != 0 &&
3552 sin6->sin6_scope_id != a6p->sin6_scope_id) {
3553 dprintf("rejected in rule %d due to scope mismatch.\n", i);
3556 if (!IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3557 &a6p->sin6_addr, &m6p->sin6_addr)) {
3558 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3566 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3568 dprintf("rejected in rule %d due to name "
3573 dprintf("accepted in rule %d.\n", i);
3574 return (true); /* hooray! */
3580 * Fairly similar to popen(3), but returns an open descriptor, as
3581 * opposed to a FILE *.
3584 p_open(const char *prog, int *rpd)
3586 struct sigaction act = { };
3589 char *argv[4]; /* sh -c cmd NULL */
3592 if (pipe(pfd) == -1)
3595 switch ((pid = pdfork(&pd, PD_CLOEXEC))) {
3600 (void)setsid(); /* Avoid catching SIGHUPs. */
3601 argv[0] = strdup("sh");
3602 argv[1] = strdup("-c");
3603 argv[2] = strdup(prog);
3605 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
3611 act.sa_handler = SIG_DFL;
3612 for (size_t i = 0; i < nitems(sigcatch); ++i) {
3613 if (sigaction(sigcatch[i], &act, NULL) == -1) {
3614 logerror("sigaction");
3619 dup2(pfd[0], STDIN_FILENO);
3620 dup2(nulldesc, STDOUT_FILENO);
3621 dup2(nulldesc, STDERR_FILENO);
3622 closefrom(STDERR_FILENO + 1);
3624 (void)execvp(_PATH_BSHELL, argv);
3629 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
3630 * supposed to get an EWOULDBLOCK on writev(2), which is
3631 * caught by the logic above anyway, which will in turn close
3632 * the pipe, and fork a new logging subprocess if necessary.
3633 * The stale subprocess will be killed some time later unless
3634 * it terminated itself due to closing its input pipe (so we
3635 * get rid of really dead puppies).
3637 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3639 (void)snprintf(errmsg, sizeof(errmsg),
3640 "Warning: cannot change pipe to PID %d to "
3641 "non-blocking behaviour.",
3652 struct deadq_entry *dq;
3657 dq = malloc(sizeof(*dq));
3663 dq->dq_procdesc = pd;
3664 dq->dq_timeout = DQ_TIMO_INIT;
3665 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3669 deadq_remove(struct deadq_entry *dq)
3671 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3672 close(dq->dq_procdesc);
3676 static struct socklist *
3677 socksetup(struct addrinfo *ai, const char *name, mode_t mode)
3679 struct socklist *sl;
3680 int (*sl_recv)(struct socklist *);
3683 if (ai->ai_family != AF_LOCAL && SecureMode > 1) {
3684 /* Only AF_LOCAL in secure mode. */
3687 if (family != AF_UNSPEC && ai->ai_family != AF_LOCAL &&
3688 ai->ai_family != family)
3691 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3697 if (ai->ai_family == AF_INET6) {
3698 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &optval,
3700 logerror("setsockopt(IPV6_V6ONLY)");
3706 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval,
3708 logerror("setsockopt(SO_REUSEADDR)");
3714 * Bind INET and UNIX-domain sockets.
3716 * A UNIX-domain socket is always bound to a pathname
3717 * regardless of -N flag.
3719 * For INET sockets, RFC 3164 recommends that client
3720 * side message should come from the privileged syslogd port.
3722 * If the system administrator chooses not to obey
3723 * this, we can skip the bind() step so that the
3724 * system will choose a port for us.
3726 if (ai->ai_family == AF_LOCAL)
3728 if (ai->ai_family == AF_LOCAL || NoBind == 0 || name != NULL) {
3729 if (bind(s, ai->ai_addr, ai->ai_addrlen) < 0) {
3734 if (ai->ai_family == AF_LOCAL || SecureMode == 0)
3737 if (ai->ai_family == AF_LOCAL && chmod(name, mode) < 0) {
3738 dprintf("chmod %s: %s\n", name, strerror(errno));
3742 dprintf("new socket fd is %d\n", s);
3743 sl_recv = socklist_recv_sock;
3744 #if defined(INET) || defined(INET6)
3745 if (SecureMode && (ai->ai_family == AF_INET ||
3746 ai->ai_family == AF_INET6)) {
3747 dprintf("shutdown\n");
3748 /* Forbid communication in secure mode. */
3749 if (shutdown(s, SHUT_RD) < 0 && errno != ENOTCONN) {
3750 logerror("shutdown");
3757 dprintf("listening on socket\n");
3758 dprintf("sending on socket\n");
3759 /* Copy *ai->ai_addr to the tail of struct socklist if any. */
3760 sl = calloc(1, sizeof(*sl) + ai->ai_addrlen);
3762 err(1, "malloc failed");
3764 if (ai->ai_family == AF_LOCAL) {
3765 char *name2 = strdup(name);
3767 err(1, "strdup failed");
3768 sl->sl_name = strdup(basename(name2));
3769 sl->sl_dirfd = open(dirname(name2), O_DIRECTORY);
3770 if (sl->sl_name == NULL || sl->sl_dirfd == -1)
3771 err(1, "failed to save dir info for %s", name);
3774 sl->sl_recv = sl_recv;
3775 (void)memcpy(&sl->sl_ai, ai, sizeof(*ai));
3776 if (ai->ai_addrlen > 0) {
3777 (void)memcpy((sl + 1), ai->ai_addr, ai->ai_addrlen);
3778 sl->sl_sa = (struct sockaddr *)(sl + 1);
3786 increase_rcvbuf(int fd)
3790 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3791 &(socklen_t){sizeof(len)}) == 0) {
3792 if (len < RCVBUF_MINSIZE) {
3793 len = RCVBUF_MINSIZE;
3794 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));