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>
147 #include "pathnames.h"
151 #include <sys/syslog.h>
153 static const char *ConfFile = _PATH_LOGCONF;
154 static const char *PidFile = _PATH_LOGPID;
155 static const char ctty[] = _PATH_CONSOLE;
156 static const char include_str[] = "include";
157 static const char include_ext[] = ".conf";
159 #define dprintf if (Debug) printf
161 #define MAXUNAMES 20 /* maximum number of user names */
163 #define sstosa(ss) ((struct sockaddr *)(ss))
165 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss))
166 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa))
169 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss))
170 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa))
171 #define s6_addr32 __u6_addr.__u6_addr32
172 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \
173 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
174 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
175 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
176 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
179 * List of peers and sockets for binding.
185 STAILQ_ENTRY(peer) next;
187 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
190 struct sockaddr_storage sl_ss;
192 struct peer *sl_peer;
193 int (*sl_recv)(struct socklist *);
194 STAILQ_ENTRY(socklist) next;
196 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
202 #define IGN_CONS 0x001 /* don't print on console */
203 #define SYNC_FILE 0x002 /* do fsync on file after printing */
204 #define MARK 0x008 /* this message is a mark */
206 /* Timestamps of log entries. */
212 /* Traditional syslog timestamp format. */
213 #define RFC3164_DATELEN 15
214 #define RFC3164_DATEFMT "%b %e %H:%M:%S"
217 * This structure represents the files that will have log
219 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
220 * or if f_type is F_PIPE and f_pid > 0.
224 STAILQ_ENTRY(filed) next; /* next in linked list */
225 short f_type; /* entry type, see below */
226 short f_file; /* file descriptor */
227 time_t f_time; /* time this was last written */
228 char *f_host; /* host from which to recd. */
229 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
230 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
234 char *f_program; /* program this applies to */
236 char f_uname[MAXUNAMES][MAXLOGNAME];
238 char f_hname[MAXHOSTNAMELEN];
239 struct addrinfo *f_addr;
241 } f_forw; /* forwarding address */
242 char f_fname[MAXPATHLEN];
244 char f_pname[MAXPATHLEN];
248 #define fu_uname f_un.f_uname
249 #define fu_forw_hname f_un.f_forw.f_hname
250 #define fu_forw_addr f_un.f_forw.f_addr
251 #define fu_fname f_un.f_fname
252 #define fu_pipe_pname f_un.f_pipe.f_pname
253 #define fu_pipe_pid f_un.f_pipe.f_pid
254 char f_prevline[MAXSVLINE]; /* last message logged */
255 struct logtime f_lasttime; /* time of last occurrence */
256 int f_prevpri; /* pri of f_prevline */
257 size_t f_prevlen; /* length of f_prevline */
258 int f_prevcount; /* repetition cnt of prevline */
259 u_int f_repeatcount; /* number of "repeated" msgs */
260 int f_flags; /* file-specific flags */
261 #define FFLAG_SYNC 0x01
262 #define FFLAG_NEEDSYNC 0x02
266 * Queue of about-to-be dead processes we should watch out for.
271 TAILQ_ENTRY(deadq_entry) dq_entries;
273 static TAILQ_HEAD(, deadq_entry) deadq_head =
274 TAILQ_HEAD_INITIALIZER(deadq_head);
277 * The timeout to apply to processes waiting on the dead queue. Unit
278 * of measure is `mark intervals', i.e. 20 minutes by default.
279 * Processes on the dead queue will be terminated after that time.
282 #define DQ_TIMO_INIT 2
285 * Struct to hold records of network addresses that are allowed to log
293 struct sockaddr_storage addr;
294 struct sockaddr_storage mask;
298 #define a_addr u.numeric.addr
299 #define a_mask u.numeric.mask
300 #define a_name u.name
301 STAILQ_ENTRY(allowedpeer) next;
303 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
307 * Intervals at which we flush out "message repeated" messages,
308 * in seconds after previous message is logged. After each flush,
309 * we move to the next interval until we reach the largest.
311 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
312 #define MAXREPEAT (nitems(repeatinterval) - 1)
313 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
314 #define BACKOFF(f) do { \
315 if (++(f)->f_repeatcount > MAXREPEAT) \
316 (f)->f_repeatcount = MAXREPEAT; \
319 /* values for f_type */
320 #define F_UNUSED 0 /* unused entry */
321 #define F_FILE 1 /* regular file */
322 #define F_TTY 2 /* terminal */
323 #define F_CONSOLE 3 /* console terminal */
324 #define F_FORW 4 /* remote machine */
325 #define F_USERS 5 /* list of users */
326 #define F_WALL 6 /* everyone logged on */
327 #define F_PIPE 7 /* pipe to program */
329 static const char *TypeNames[] = {
330 "UNUSED", "FILE", "TTY", "CONSOLE",
331 "FORW", "USERS", "WALL", "PIPE"
334 static STAILQ_HEAD(, filed) fhead =
335 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */
336 static struct filed consfile; /* Console */
338 static int Debug; /* debug flag */
339 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
340 static int resolve = 1; /* resolve hostname */
341 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
342 static const char *LocalDomain; /* our local domain name */
343 static int Initialized; /* set when we have initialized ourselves */
344 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
345 static int MarkSeq; /* mark sequence number */
346 static int NoBind; /* don't bind() as suggested by RFC 3164 */
347 static int SecureMode; /* when true, receive only unix domain socks */
349 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
351 static int family = PF_INET; /* protocol family (IPv4 only) */
353 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
354 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
355 static int use_bootfile; /* log entire bootfile for every kern msg */
356 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
357 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
359 static char bootfile[MAXLINE+1]; /* booted kernel file */
361 static int RemoteAddDate; /* Always set the date on remote messages */
362 static int RemoteHostname; /* Log remote hostname from the message */
364 static int UniquePriority; /* Only log specified priority? */
365 static int LogFacPri; /* Put facility and priority in log message: */
366 /* 0=no, 1=numeric, 2=names */
367 static int KeepKernFac; /* Keep remotely logged kernel facility */
368 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
369 static struct pidfh *pfh;
370 static int sigpipe[2]; /* Pipe to catch a signal during select(). */
371 static bool RFC3164OutputFormat = true; /* Use legacy format by default. */
373 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
377 static int allowaddr(char *);
378 static int addfile(struct filed *);
379 static int addpeer(struct peer *);
380 static int addsock(struct sockaddr *, socklen_t, struct socklist *);
381 static struct filed *cfline(const char *, const char *, const char *);
382 static const char *cvthname(struct sockaddr *);
383 static void deadq_enter(pid_t, const char *);
384 static int deadq_remove(struct deadq_entry *);
385 static int deadq_removebypid(pid_t);
386 static int decode(const char *, const CODE *);
387 static void die(int) __dead2;
388 static void dodie(int);
389 static void dofsync(void);
390 static void domark(int);
391 static void fprintlog_first(struct filed *, const char *, const char *,
392 const char *, const char *, const char *, const char *, int);
393 static void fprintlog_write(struct filed *, struct iovlist *, int);
394 static void fprintlog_successive(struct filed *, int);
395 static void init(int);
396 static void logerror(const char *);
397 static void logmsg(int, const struct logtime *, const char *, const char *,
398 const char *, const char *, const char *, const char *, int);
399 static void log_deadchild(pid_t, int, const char *);
400 static void markit(void);
401 static int socksetup(struct peer *);
402 static int socklist_recv_file(struct socklist *);
403 static int socklist_recv_sock(struct socklist *);
404 static int socklist_recv_signal(struct socklist *);
405 static void sighandler(int);
406 static int skip_message(const char *, const char *, int);
407 static void parsemsg(const char *, char *);
408 static void printsys(char *);
409 static int p_open(const char *, pid_t *);
410 static void reapchild(int);
411 static const char *ttymsg_check(struct iovec *, int, char *, int);
412 static void usage(void);
413 static int validate(struct sockaddr *, const char *);
414 static void unmapped(struct sockaddr *);
415 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
416 static int waitdaemon(int);
417 static void timedout(int);
418 static void increase_rcvbuf(int);
421 close_filed(struct filed *f)
424 if (f == NULL || f->f_file == -1)
429 if (f->f_un.f_forw.f_addr) {
430 freeaddrinfo(f->f_un.f_forw.f_addr);
431 f->f_un.f_forw.f_addr = NULL;
438 f->f_type = F_UNUSED;
444 (void)close(f->f_file);
449 addfile(struct filed *f0)
453 f = calloc(1, sizeof(*f));
455 err(1, "malloc failed");
457 STAILQ_INSERT_TAIL(&fhead, f, next);
463 addpeer(struct peer *pe0)
467 pe = calloc(1, sizeof(*pe));
469 err(1, "malloc failed");
471 STAILQ_INSERT_TAIL(&pqueue, pe, next);
477 addsock(struct sockaddr *sa, socklen_t sa_len, struct socklist *sl0)
481 sl = calloc(1, sizeof(*sl));
483 err(1, "malloc failed");
485 if (sa != NULL && sa_len > 0)
486 memcpy(&sl->sl_ss, sa, sa_len);
487 STAILQ_INSERT_TAIL(&shead, sl, next);
493 main(int argc, char *argv[])
495 int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
497 struct timeval tv, *tvp;
500 pid_t ppid = 1, spid;
503 if (madvise(NULL, 0, MADV_PROTECT) != 0)
504 dprintf("madvise() failed: %s\n", strerror(errno));
506 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:m:nNoO:p:P:sS:Tuv"))
525 case 'a': /* allow specific network addresses only */
526 if (allowaddr(optarg) == -1)
531 p = strchr(optarg, ']');
533 p = strchr(p + 1, ':');
535 p = strchr(optarg, ':');
536 if (p != NULL && strchr(p + 1, ':') != NULL)
537 p = NULL; /* backward compatibility */
540 /* A hostname or filename only. */
541 addpeer(&(struct peer){
546 /* The case of "name:service". */
548 addpeer(&(struct peer){
550 .pe_name = (strlen(optarg) == 0) ?
561 case 'd': /* debug */
564 case 'f': /* configuration file */
567 case 'F': /* run in foreground instead of daemon */
573 case 'k': /* keep remote kern fac */
586 else if (ch == 'p') {
590 mode = S_IRUSR | S_IWUSR;
593 if (optarg[0] == '/')
595 else if ((name = strchr(optarg, ':')) != NULL) {
598 errx(1, "socket name must be absolute "
600 if (isdigit(*optarg)) {
601 perml = strtol(optarg, &ep, 8);
602 if (*ep || perml < 0 ||
603 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
604 errx(1, "invalid mode %s, exiting",
606 mode = (mode_t )perml;
608 errx(1, "invalid mode %s, exiting",
611 errx(1, "invalid filename %s, exiting",
613 addpeer(&(struct peer){
619 case 'm': /* mark interval */
620 MarkInterval = atoi(optarg) * 60;
630 if (strcmp(optarg, "bsd") == 0 ||
631 strcmp(optarg, "rfc3164") == 0)
632 RFC3164OutputFormat = true;
633 else if (strcmp(optarg, "syslog") == 0 ||
634 strcmp(optarg, "rfc5424") == 0)
635 RFC3164OutputFormat = false;
642 case 'P': /* path for alt. PID */
645 case 's': /* no network mode */
651 case 'u': /* only log specified priority */
654 case 'v': /* log facility and priority */
660 if ((argc -= optind) != 0)
663 /* Pipe to catch a signal during select(). */
664 s = pipe2(sigpipe, O_CLOEXEC);
666 err(1, "cannot open a pipe for signals");
668 addsock(NULL, 0, &(struct socklist){
669 .sl_socket = sigpipe[0],
670 .sl_recv = socklist_recv_signal
674 /* Listen by default: /dev/klog. */
675 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
677 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
679 addsock(NULL, 0, &(struct socklist){
681 .sl_recv = socklist_recv_file,
684 /* Listen by default: *:514 if no -b flag. */
686 addpeer(&(struct peer){
689 /* Listen by default: /var/run/log if no -p flag. */
691 addpeer(&(struct peer){
692 .pe_name = _PATH_LOG,
693 .pe_mode = DEFFILEMODE,
695 /* Listen by default: /var/run/logpriv if no -S flag. */
697 addpeer(&(struct peer){
698 .pe_name = _PATH_LOG_PRIV,
699 .pe_mode = S_IRUSR | S_IWUSR,
701 STAILQ_FOREACH(pe, &pqueue, next)
704 pfh = pidfile_open(PidFile, 0600, &spid);
707 errx(1, "syslogd already running, pid: %d", spid);
708 warn("cannot open pid file");
711 if ((!Foreground) && (!Debug)) {
712 ppid = waitdaemon(30);
714 warn("could not become daemon");
721 consfile.f_type = F_CONSOLE;
722 (void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
723 sizeof(consfile.fu_fname));
724 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
725 (void)signal(SIGTERM, dodie);
726 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
727 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
728 (void)signal(SIGHUP, sighandler);
729 (void)signal(SIGCHLD, sighandler);
730 (void)signal(SIGALRM, domark);
731 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
732 (void)alarm(TIMERINTVL);
734 /* tuck my process id away */
737 dprintf("off & running....\n");
740 tv.tv_sec = tv.tv_usec = 0;
742 STAILQ_FOREACH(sl, &shead, next) {
743 if (sl->sl_socket > fdsrmax)
744 fdsrmax = sl->sl_socket;
746 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
749 errx(1, "calloc fd_set");
752 if (Initialized == 0)
754 else if (WantInitialize)
755 init(WantInitialize);
757 reapchild(WantReapchild);
765 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
768 STAILQ_FOREACH(sl, &shead, next) {
769 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
770 FD_SET(sl->sl_socket, fdsr);
772 i = select(fdsrmax + 1, fdsr, NULL, NULL,
773 needdofsync ? &tv : tvp);
789 STAILQ_FOREACH(sl, &shead, next) {
790 if (FD_ISSET(sl->sl_socket, fdsr))
798 socklist_recv_signal(struct socklist *sl __unused)
803 if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
804 logerror("ioctl(FIONREAD)");
805 err(1, "signal pipe read failed");
807 nsig = i / sizeof(signo);
808 dprintf("# of received signals = %d\n", nsig);
809 for (i = 0; i < nsig; i++) {
810 len = read(sigpipe[0], &signo, sizeof(signo));
811 if (len != sizeof(signo)) {
812 logerror("signal pipe read failed");
813 err(1, "signal pipe read failed");
815 dprintf("Received signal: %d from fd=%d\n", signo,
830 socklist_recv_sock(struct socklist *sl)
832 struct sockaddr_storage ss;
833 struct sockaddr *sa = (struct sockaddr *)&ss;
836 char line[MAXLINE + 1];
840 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
841 dprintf("received sa_len = %d\n", sslen);
846 logerror("recvfrom");
849 /* Received valid data. */
851 if (sl->sl_ss.ss_family == AF_LOCAL)
852 hname = LocalHostName;
854 hname = cvthname(sa);
856 if (validate(sa, hname) == 0) {
857 dprintf("Message from %s was ignored.", hname);
861 parsemsg(hname, line);
867 unmapped(struct sockaddr *sa)
869 #if defined(INET) && defined(INET6)
870 struct sockaddr_in6 *sin6;
871 struct sockaddr_in sin;
874 sa->sa_family != AF_INET6 ||
875 sa->sa_len != sizeof(*sin6))
878 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
880 sin = (struct sockaddr_in){
881 .sin_family = AF_INET,
882 .sin_len = sizeof(sin),
883 .sin_port = sin6->sin6_port
885 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
886 sizeof(sin.sin_addr));
887 memcpy(sa, &sin, sizeof(sin));
899 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n"
900 " [-b bind_address] [-f config_file]\n"
901 " [-l [mode:]path] [-m mark_interval]\n"
902 " [-O format] [-P pid_file] [-p log_socket]\n"
903 " [-S logpriv_socket]\n");
908 * Removes characters from log messages that are unsafe to display.
909 * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
912 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
918 while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
919 if (mask_C1 && (c & 0x80) && c < 0xA0) {
924 if (isascii(c) && iscntrl(c)) {
927 } else if (c == '\t') {
941 * Parses a syslog message according to RFC 5424, assuming that PRI and
942 * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
943 * parsed result is passed to logmsg().
946 parsemsg_rfc5424(const char *from, int pri, char *msg)
948 const struct logtime *timestamp;
949 struct logtime timestamp_remote;
950 const char *omsg, *hostname, *app_name, *procid, *msgid,
952 char line[MAXLINE + 1];
954 #define FAIL_IF(field, expr) do { \
956 dprintf("Failed to parse " field " from %s: %s\n", \
961 #define PARSE_CHAR(field, sep) do { \
962 FAIL_IF(field, *msg != sep); \
965 #define IF_NOT_NILVALUE(var) \
966 if (msg[0] == '-' && msg[1] == ' ') { \
969 } else if (msg[0] == '-' && msg[1] == '\0') { \
975 IF_NOT_NILVALUE(timestamp) {
976 /* Parse RFC 3339-like timestamp. */
977 #define PARSE_NUMBER(dest, length, min, max) do { \
981 for (i = 0; i < length; ++i) { \
982 FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9'); \
983 v = v * 10 + *msg++ - '0'; \
985 FAIL_IF("TIMESTAMP", v < min || v > max); \
989 memset(×tamp_remote, 0, sizeof(timestamp_remote));
990 PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
991 timestamp_remote.tm.tm_year -= 1900;
992 PARSE_CHAR("TIMESTAMP", '-');
993 PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
994 --timestamp_remote.tm.tm_mon;
995 PARSE_CHAR("TIMESTAMP", '-');
996 PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
997 PARSE_CHAR("TIMESTAMP", 'T');
998 PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
999 PARSE_CHAR("TIMESTAMP", ':');
1000 PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
1001 PARSE_CHAR("TIMESTAMP", ':');
1002 PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
1003 /* Perform normalization. */
1004 timegm(×tamp_remote.tm);
1005 /* Optional: fractional seconds. */
1006 if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
1010 for (i = 100000; i != 0; i /= 10) {
1011 if (*msg < '0' || *msg > '9')
1013 timestamp_remote.usec += (*msg++ - '0') * i;
1021 int sign, tz_hour, tz_min;
1023 /* Local time zone offset. */
1024 FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1025 sign = *msg++ == '-' ? -1 : 1;
1026 PARSE_NUMBER(tz_hour, 2, 0, 23);
1027 PARSE_CHAR("TIMESTAMP", ':');
1028 PARSE_NUMBER(tz_min, 2, 0, 59);
1029 timestamp_remote.tm.tm_gmtoff =
1030 sign * (tz_hour * 3600 + tz_min * 60);
1033 PARSE_CHAR("TIMESTAMP", ' ');
1034 timestamp = RemoteAddDate ? NULL : ×tamp_remote;
1037 /* String fields part of the HEADER. */
1038 #define PARSE_STRING(field, var) \
1039 IF_NOT_NILVALUE(var) { \
1041 while (*msg >= '!' && *msg <= '~') \
1043 FAIL_IF(field, var == msg); \
1044 PARSE_CHAR(field, ' '); \
1047 PARSE_STRING("HOSTNAME", hostname);
1048 if (hostname == NULL || !RemoteHostname)
1050 PARSE_STRING("APP-NAME", app_name);
1051 PARSE_STRING("PROCID", procid);
1052 PARSE_STRING("MSGID", msgid);
1055 /* Structured data. */
1056 #define PARSE_SD_NAME() do { \
1057 const char *start; \
1060 while (*msg >= '!' && *msg <= '~' && *msg != '=' && \
1061 *msg != ']' && *msg != '"') \
1063 FAIL_IF("STRUCTURED-NAME", start == msg); \
1065 IF_NOT_NILVALUE(structured_data) {
1067 while (*msg == '[') {
1072 while (*msg == ' ') {
1076 PARSE_CHAR("STRUCTURED-NAME", '=');
1077 PARSE_CHAR("STRUCTURED-NAME", '"');
1078 while (*msg != '"') {
1079 FAIL_IF("STRUCTURED-NAME",
1081 if (*msg++ == '\\') {
1082 FAIL_IF("STRUCTURED-NAME",
1089 PARSE_CHAR("STRUCTURED-NAME", ']');
1091 PARSE_CHAR("STRUCTURED-NAME", ' ');
1094 #undef PARSE_SD_NAME
1098 #undef IF_NOT_NILVALUE
1100 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1101 logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1102 structured_data, line, 0);
1106 * Trims the application name ("TAG" in RFC 3164 terminology) and
1107 * process ID from a message if present.
1110 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1111 const char **procid) {
1112 char *m, *app_name_begin, *procid_begin;
1113 size_t app_name_length, procid_length;
1117 /* Application name. */
1119 app_name_length = strspn(m,
1120 "abcdefghijklmnopqrstuvwxyz"
1121 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1124 if (app_name_length == 0)
1126 m += app_name_length;
1128 /* Process identifier (optional). */
1131 procid_length = strspn(m, "0123456789");
1132 if (procid_length == 0)
1138 procid_begin = NULL;
1143 if (m[0] != ':' || m[1] != ' ')
1146 /* Split strings from input. */
1147 app_name_begin[app_name_length] = '\0';
1148 if (procid_begin != 0)
1149 procid_begin[procid_length] = '\0';
1152 *app_name = app_name_begin;
1153 *procid = procid_begin;
1161 * Parses a syslog message according to RFC 3164, assuming that PRI
1162 * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1163 * result is passed to logmsg().
1166 parsemsg_rfc3164(const char *from, int pri, char *msg)
1168 struct tm tm_parsed;
1169 const struct logtime *timestamp;
1170 struct logtime timestamp_remote;
1171 const char *app_name, *procid;
1173 char line[MAXLINE + 1];
1176 * Parse the TIMESTAMP provided by the remote side. If none is
1177 * found, assume this is not an RFC 3164 formatted message,
1178 * only containing a TAG and a MSG.
1181 if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) ==
1182 msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') {
1183 msg += RFC3164_DATELEN + 1;
1184 if (!RemoteAddDate) {
1190 * As the timestamp does not contain the year
1191 * number, daylight saving time information, nor
1192 * a time zone, attempt to infer it. Due to
1193 * clock skews, the timestamp may even be part
1194 * of the next year. Use the last year for which
1195 * the timestamp is at most one week in the
1198 * This loop can only run for at most three
1199 * iterations before terminating.
1202 localtime_r(&t_now, &tm_now);
1203 for (year = tm_now.tm_year + 1;; --year) {
1204 assert(year >= tm_now.tm_year - 1);
1205 timestamp_remote.tm = tm_parsed;
1206 timestamp_remote.tm.tm_year = year;
1207 timestamp_remote.tm.tm_isdst = -1;
1208 timestamp_remote.usec = 0;
1209 if (mktime(×tamp_remote.tm) <
1210 t_now + 7 * 24 * 60 * 60)
1213 timestamp = ×tamp_remote;
1217 * A single space character MUST also follow the HOSTNAME field.
1219 msglen = strlen(msg);
1220 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1221 if (msg[i] == ' ') {
1222 if (RemoteHostname) {
1230 * Support non RFC compliant messages, without hostname.
1235 if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1236 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1241 /* Remove the TAG, if present. */
1242 parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1243 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1244 logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1248 * Takes a raw input line, extracts PRI and determines whether the
1249 * message is formatted according to RFC 3164 or RFC 5424. Continues
1250 * parsing of addition fields in the message according to those
1251 * standards and prints the message on the appropriate log files.
1254 parsemsg(const char *from, char *msg)
1262 if (msg[0] != '<' || !isdigit(msg[1])) {
1263 dprintf("Invalid PRI from %s\n", from);
1266 for (i = 2; i <= 4; i++) {
1269 if (!isdigit(msg[i])) {
1270 dprintf("Invalid PRI header from %s\n", from);
1274 if (msg[i] != '>') {
1275 dprintf("Invalid PRI header from %s\n", from);
1279 n = strtol(msg + 1, &q, 10);
1280 if (errno != 0 || *q != msg[i] || n < 0 || n >= INT_MAX) {
1281 dprintf("Invalid PRI %ld from %s: %s\n",
1282 n, from, strerror(errno));
1286 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1290 * Don't allow users to log kernel messages.
1291 * NOTE: since LOG_KERN == 0 this will also match
1292 * messages with no facility specified.
1294 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1295 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1297 /* Parse VERSION. */
1299 if (msg[0] == '1' && msg[1] == ' ')
1300 parsemsg_rfc5424(from, pri, msg + 2);
1302 parsemsg_rfc3164(from, pri, msg);
1306 * Read /dev/klog while data are available, split into lines.
1309 socklist_recv_file(struct socklist *sl)
1311 char *p, *q, line[MAXLINE + 1];
1316 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1318 line[i + len] = '\0';
1320 if (i < 0 && errno != EINTR && errno != EAGAIN) {
1322 close(sl->sl_socket);
1328 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1333 if (len >= MAXLINE - 1) {
1338 memmove(line, p, len + 1);
1347 * Take a raw input line from /dev/klog, format similar to syslog().
1354 int flags, isprintf, pri;
1356 flags = SYNC_FILE; /* fsync after write */
1362 n = strtol(p + 1, &q, 10);
1363 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1370 * Kernel printf's and LOG_CONSOLE messages have been displayed
1371 * on the console already.
1373 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1375 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1377 logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1383 * Match a program or host name against a specification.
1384 * Return a non-0 value if the message must be ignored
1385 * based on the specification.
1388 skip_message(const char *name, const char *spec, int checkcase)
1393 /* Behaviour on explicit match */
1408 s = strstr (spec, name);
1410 s = strcasestr (spec, name);
1413 prev = (s == spec ? ',' : *(s - 1));
1414 next = *(s + strlen (name));
1416 if (prev == ',' && (next == '\0' || next == ','))
1417 /* Explicit match: skip iff the spec is an
1422 /* No explicit match for this name: skip the message iff
1423 the spec is an inclusive one. */
1428 * Logs a message to the appropriate log files, users, etc. based on the
1429 * priority. Log messages are always formatted according to RFC 3164,
1430 * even if they were in RFC 5424 format originally, The MSGID and
1431 * STRUCTURED-DATA fields are thus discarded for the time being.
1434 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1435 const char *app_name, const char *procid, const char *msgid,
1436 const char *structured_data, const char *msg, int flags)
1439 struct logtime timestamp_now;
1443 char saved[MAXSVLINE];
1445 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1446 pri, flags, hostname, msg);
1448 (void)gettimeofday(&tv, NULL);
1450 if (timestamp == NULL) {
1451 localtime_r(&now, ×tamp_now.tm);
1452 timestamp_now.usec = tv.tv_usec;
1453 timestamp = ×tamp_now;
1456 /* extract facility and priority level */
1458 fac = LOG_NFACILITIES;
1462 /* Check maximum facility number. */
1463 if (fac > LOG_NFACILITIES)
1466 prilev = LOG_PRI(pri);
1468 /* log the message to the particular outputs */
1472 * Open in non-blocking mode to avoid hangs during open
1473 * and close(waiting for the port to drain).
1475 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1477 if (f->f_file >= 0) {
1478 f->f_lasttime = *timestamp;
1479 fprintlog_first(f, hostname, app_name, procid, msgid,
1480 structured_data, msg, flags);
1488 * Store all of the fields of the message, except the timestamp,
1489 * in a single string. This string is used to detect duplicate
1492 assert(hostname != NULL);
1493 assert(msg != NULL);
1494 savedlen = snprintf(saved, sizeof(saved),
1495 "%d %s %s %s %s %s %s", pri, hostname,
1496 app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1497 msgid == NULL ? "-" : msgid,
1498 structured_data == NULL ? "-" : structured_data, msg);
1500 STAILQ_FOREACH(f, &fhead, next) {
1501 /* skip messages that are incorrect priority */
1502 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1503 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1504 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1506 || f->f_pmask[fac] == INTERNAL_NOPRI)
1509 /* skip messages with the incorrect hostname */
1510 if (skip_message(hostname, f->f_host, 0))
1513 /* skip messages with the incorrect program name */
1514 if (skip_message(app_name == NULL ? "" : app_name,
1518 /* skip message to console if it has already been printed */
1519 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1522 /* don't output marks to recently written files */
1523 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1527 * suppress duplicate lines to this file
1529 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1530 (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1531 strcmp(saved, f->f_prevline) == 0) {
1532 f->f_lasttime = *timestamp;
1534 dprintf("msg repeated %d times, %ld sec of %d\n",
1535 f->f_prevcount, (long)(now - f->f_time),
1536 repeatinterval[f->f_repeatcount]);
1538 * If domark would have logged this by now,
1539 * flush it now (so we don't hold isolated messages),
1540 * but back off so we'll flush less often
1543 if (now > REPEATTIME(f)) {
1544 fprintlog_successive(f, flags);
1548 /* new line, save it */
1550 fprintlog_successive(f, 0);
1551 f->f_repeatcount = 0;
1553 f->f_lasttime = *timestamp;
1554 static_assert(sizeof(f->f_prevline) == sizeof(saved),
1555 "Space to store saved line incorrect");
1556 (void)strcpy(f->f_prevline, saved);
1557 f->f_prevlen = savedlen;
1558 fprintlog_first(f, hostname, app_name, procid, msgid,
1559 structured_data, msg, flags);
1569 STAILQ_FOREACH(f, &fhead, next) {
1570 if ((f->f_type == F_FILE) &&
1571 (f->f_flags & FFLAG_NEEDSYNC)) {
1572 f->f_flags &= ~FFLAG_NEEDSYNC;
1573 (void)fsync(f->f_file);
1579 * List of iovecs to which entries can be appended.
1580 * Used for constructing the message to be logged.
1583 struct iovec iov[TTYMSG_IOV_MAX];
1589 iovlist_init(struct iovlist *il)
1597 iovlist_append(struct iovlist *il, const char *str)
1601 /* Discard components if we've run out of iovecs. */
1602 if (il->iovcnt < nitems(il->iov)) {
1604 il->iov[il->iovcnt++] = (struct iovec){
1605 .iov_base = __DECONST(char *, str),
1608 il->totalsize += size;
1613 iovlist_truncate(struct iovlist *il, size_t size)
1618 while (il->totalsize > size) {
1619 diff = il->totalsize - size;
1620 last = &il->iov[il->iovcnt - 1];
1621 if (diff >= last->iov_len) {
1622 /* Remove the last iovec entirely. */
1624 il->totalsize -= last->iov_len;
1626 /* Remove the last iovec partially. */
1627 last->iov_len -= diff;
1628 il->totalsize -= diff;
1634 fprintlog_write(struct filed *f, struct iovlist *il, int flags)
1636 struct msghdr msghdr;
1638 struct socklist *sl;
1642 switch (f->f_type) {
1644 /* Truncate messages to RFC 5426 recommended size. */
1645 dprintf(" %s", f->fu_forw_hname);
1646 switch (f->fu_forw_addr->ai_addr->sa_family) {
1650 ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1651 iovlist_truncate(il, 480);
1657 ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1658 iovlist_truncate(il, 1180);
1666 for (r = f->fu_forw_addr; r; r = r->ai_next) {
1667 memset(&msghdr, 0, sizeof(msghdr));
1668 msghdr.msg_name = r->ai_addr;
1669 msghdr.msg_namelen = r->ai_addrlen;
1670 msghdr.msg_iov = il->iov;
1671 msghdr.msg_iovlen = il->iovcnt;
1672 STAILQ_FOREACH(sl, &shead, next) {
1673 if (sl->sl_ss.ss_family == AF_LOCAL ||
1674 sl->sl_ss.ss_family == AF_UNSPEC ||
1677 lsent = sendmsg(sl->sl_socket, &msghdr, 0);
1678 if (lsent == (ssize_t)il->totalsize)
1681 if (lsent == (ssize_t)il->totalsize && !send_to_all)
1684 dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize);
1685 if (lsent != (ssize_t)il->totalsize) {
1699 /* case ENOTSOCK: */
1701 /* case EMSGSIZE: */
1704 /* case ECONNREFUSED: */
1706 dprintf("removing entry: errno=%d\n", e);
1707 f->f_type = F_UNUSED;
1714 dprintf(" %s\n", f->fu_fname);
1715 iovlist_append(il, "\n");
1716 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1718 * If writev(2) fails for potentially transient errors
1719 * like the filesystem being full, ignore it.
1720 * Otherwise remove this logfile from the list.
1722 if (errno != ENOSPC) {
1726 logerror(f->fu_fname);
1728 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1729 f->f_flags |= FFLAG_NEEDSYNC;
1735 dprintf(" %s\n", f->fu_pipe_pname);
1736 iovlist_append(il, "\n");
1737 if (f->fu_pipe_pid == 0) {
1738 if ((f->f_file = p_open(f->fu_pipe_pname,
1739 &f->fu_pipe_pid)) < 0) {
1740 logerror(f->fu_pipe_pname);
1744 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1747 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1750 logerror(f->fu_pipe_pname);
1755 if (flags & IGN_CONS) {
1756 dprintf(" (ignored)\n");
1762 dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1763 iovlist_append(il, "\r\n");
1764 errno = 0; /* ttymsg() only sometimes returns an errno */
1765 if ((msgret = ttymsg(il->iov, il->iovcnt, f->fu_fname, 10))) {
1766 f->f_type = F_UNUSED;
1774 iovlist_append(il, "\r\n");
1775 wallmsg(f, il->iov, il->iovcnt);
1781 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name,
1782 const char *procid, const char *msgid, const char *structured_data,
1783 const char *msg, int flags)
1788 char timebuf[33], priority_number[5];
1791 if (f->f_type == F_WALL)
1792 iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n");
1793 iovlist_append(&il, "<");
1794 snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri);
1795 iovlist_append(&il, priority_number);
1796 iovlist_append(&il, ">1 ");
1797 if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z",
1798 &f->f_lasttime.tm) == sizeof(timebuf) - 2) {
1799 /* Add colon to the time zone offset, which %z doesn't do. */
1801 timebuf[31] = timebuf[30];
1802 timebuf[30] = timebuf[29];
1805 /* Overwrite space for microseconds with actual value. */
1806 usec = f->f_lasttime.usec;
1807 for (i = 25; i >= 20; --i) {
1808 timebuf[i] = usec % 10 + '0';
1811 iovlist_append(&il, timebuf);
1813 iovlist_append(&il, "-");
1814 iovlist_append(&il, " ");
1815 iovlist_append(&il, hostname);
1816 iovlist_append(&il, " ");
1817 iovlist_append(&il, app_name == NULL ? "-" : app_name);
1818 iovlist_append(&il, " ");
1819 iovlist_append(&il, procid == NULL ? "-" : procid);
1820 iovlist_append(&il, " ");
1821 iovlist_append(&il, msgid == NULL ? "-" : msgid);
1822 iovlist_append(&il, " ");
1823 iovlist_append(&il, structured_data == NULL ? "-" : structured_data);
1824 iovlist_append(&il, " ");
1825 iovlist_append(&il, msg);
1827 fprintlog_write(f, &il, flags);
1831 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name,
1832 const char *procid, const char *msg, int flags)
1836 int facility, priority;
1837 char timebuf[RFC3164_DATELEN + 1], facility_number[5],
1839 bool facility_found, priority_found;
1841 if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
1842 &f->f_lasttime.tm) == 0)
1846 switch (f->f_type) {
1848 /* Message forwarded over the network. */
1849 iovlist_append(&il, "<");
1850 snprintf(priority_number, sizeof(priority_number), "%d",
1852 iovlist_append(&il, priority_number);
1853 iovlist_append(&il, ">");
1854 iovlist_append(&il, timebuf);
1855 if (strcasecmp(hostname, LocalHostName) != 0) {
1856 iovlist_append(&il, " Forwarded from ");
1857 iovlist_append(&il, hostname);
1858 iovlist_append(&il, ":");
1860 iovlist_append(&il, " ");
1864 /* Message written to terminals. */
1865 iovlist_append(&il, "\r\n\aMessage from syslogd@");
1866 iovlist_append(&il, hostname);
1867 iovlist_append(&il, " at ");
1868 iovlist_append(&il, timebuf);
1869 iovlist_append(&il, " ...\r\n");
1873 /* Message written to files. */
1874 iovlist_append(&il, timebuf);
1875 iovlist_append(&il, " ");
1878 iovlist_append(&il, "<");
1880 facility = f->f_prevpri & LOG_FACMASK;
1881 facility_found = false;
1882 if (LogFacPri > 1) {
1883 for (c = facilitynames; c->c_name; c++) {
1884 if (c->c_val == facility) {
1885 iovlist_append(&il, c->c_name);
1886 facility_found = true;
1891 if (!facility_found) {
1892 snprintf(facility_number,
1893 sizeof(facility_number), "%d",
1895 iovlist_append(&il, facility_number);
1898 iovlist_append(&il, ".");
1900 priority = LOG_PRI(f->f_prevpri);
1901 priority_found = false;
1902 if (LogFacPri > 1) {
1903 for (c = prioritynames; c->c_name; c++) {
1904 if (c->c_val == priority) {
1905 iovlist_append(&il, c->c_name);
1906 priority_found = true;
1911 if (!priority_found) {
1912 snprintf(priority_number,
1913 sizeof(priority_number), "%d", priority);
1914 iovlist_append(&il, priority_number);
1917 iovlist_append(&il, "> ");
1920 iovlist_append(&il, hostname);
1921 iovlist_append(&il, " ");
1925 /* Message body with application name and process ID prefixed. */
1926 if (app_name != NULL) {
1927 iovlist_append(&il, app_name);
1928 if (procid != NULL) {
1929 iovlist_append(&il, "[");
1930 iovlist_append(&il, procid);
1931 iovlist_append(&il, "]");
1933 iovlist_append(&il, ": ");
1935 iovlist_append(&il, msg);
1937 fprintlog_write(f, &il, flags);
1941 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
1942 const char *procid, const char *msgid __unused,
1943 const char *structured_data __unused, const char *msg, int flags)
1946 dprintf("Logging to %s", TypeNames[f->f_type]);
1949 if (f->f_type == F_UNUSED) {
1954 if (RFC3164OutputFormat)
1955 fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags);
1957 fprintlog_rfc5424(f, hostname, app_name, procid, msgid,
1958 structured_data, msg, flags);
1962 * Prints a message to a log file that the previously logged message was
1963 * received multiple times.
1966 fprintlog_successive(struct filed *f, int flags)
1970 assert(f->f_prevcount > 0);
1971 snprintf(msg, sizeof(msg), "last message repeated %d times",
1973 fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
1978 * WALLMSG -- Write a message to the world at large
1980 * Write the specified message to either the entire
1981 * world, or a list of approved users.
1984 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1986 static int reenter; /* avoid calling ourselves */
1995 while ((ut = getutxent()) != NULL) {
1996 if (ut->ut_type != USER_PROCESS)
1998 if (f->f_type == F_WALL) {
1999 if ((p = ttymsg(iov, iovlen, ut->ut_line,
2000 TTYMSGTIME)) != NULL) {
2001 errno = 0; /* already in msg */
2006 /* should we send the message to this user? */
2007 for (i = 0; i < MAXUNAMES; i++) {
2008 if (!f->fu_uname[i][0])
2010 if (!strcmp(f->fu_uname[i], ut->ut_user)) {
2011 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
2012 TTYMSGTIME)) != NULL) {
2013 errno = 0; /* already in msg */
2025 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
2028 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
2030 static char device[1024];
2031 static char errbuf[1024];
2034 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
2036 if (stat(device, &sb) < 0) {
2037 (void) snprintf(errbuf, sizeof(errbuf),
2038 "%s: %s", device, strerror(errno));
2041 if ((sb.st_mode & S_IWGRP) == 0)
2042 /* Messages disabled. */
2044 return ttymsg(iov, iovcnt, line, tmout);
2048 reapchild(int signo __unused)
2054 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
2055 /* First, look if it's a process from the dead queue. */
2056 if (deadq_removebypid(pid))
2059 /* Now, look in list of active processes. */
2060 STAILQ_FOREACH(f, &fhead, next) {
2061 if (f->f_type == F_PIPE &&
2062 f->fu_pipe_pid == pid) {
2064 log_deadchild(pid, status, f->fu_pipe_pname);
2073 * Return a printable representation of a host address.
2076 cvthname(struct sockaddr *f)
2079 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
2081 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
2082 error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
2085 dprintf("Malformed from address %s\n", gai_strerror(error));
2088 dprintf("cvthname(%s)\n", ip);
2093 error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
2094 NULL, 0, NI_NAMEREQD);
2096 dprintf("Host name for your address (%s) unknown\n", ip);
2100 if (hl > 0 && hname[hl-1] == '.')
2102 trimdomain(hname, hl);
2114 domark(int signo __unused)
2121 * Print syslogd errors some place.
2124 logerror(const char *msg)
2127 static int recursed = 0;
2129 /* If there's an error while trying to log an error, give up. */
2134 (void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2139 dprintf("%s\n", buf);
2140 logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2149 struct socklist *sl;
2152 STAILQ_FOREACH(f, &fhead, next) {
2153 /* flush any pending output */
2155 fprintlog_successive(f, 0);
2156 if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
2160 dprintf("syslogd: exiting on signal %d\n", signo);
2161 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2165 STAILQ_FOREACH(sl, &shead, next) {
2166 if (sl->sl_ss.ss_family == AF_LOCAL)
2167 unlink(sl->sl_peer->pe_name);
2169 pidfile_remove(pfh);
2175 configfiles(const struct dirent *dp)
2180 if (dp->d_name[0] == '.')
2183 ext_len = sizeof(include_ext) -1;
2185 if (dp->d_namlen <= ext_len)
2188 p = &dp->d_name[dp->d_namlen - ext_len];
2189 if (strcmp(p, include_ext) != 0)
2196 readconfigfile(FILE *cf, int allow_includes)
2200 struct dirent **ent;
2201 char cline[LINE_MAX];
2202 char host[MAXHOSTNAMELEN];
2203 char prog[LINE_MAX];
2204 char file[MAXPATHLEN];
2210 * Foreach line in the conf table, open that file.
2212 include_len = sizeof(include_str) -1;
2213 (void)strlcpy(host, "*", sizeof(host));
2214 (void)strlcpy(prog, "*", sizeof(prog));
2215 while (fgets(cline, sizeof(cline), cf) != NULL) {
2217 * check for end-of-section, comments, strip off trailing
2218 * spaces and newline character. #!prog is treated specially:
2219 * following lines apply only to that program.
2221 for (p = cline; isspace(*p); ++p)
2225 if (allow_includes &&
2226 strncmp(p, include_str, include_len) == 0 &&
2227 isspace(p[include_len])) {
2232 while (*tmp != '\0' && !isspace(*tmp))
2235 dprintf("Trying to include files in '%s'\n", p);
2236 nents = scandir(p, &ent, configfiles, alphasort);
2238 dprintf("Unable to open '%s': %s\n", p,
2242 for (i = 0; i < nents; i++) {
2243 if (snprintf(file, sizeof(file), "%s/%s", p,
2244 ent[i]->d_name) >= (int)sizeof(file)) {
2245 dprintf("ignoring path too long: "
2246 "'%s/%s'\n", p, ent[i]->d_name);
2251 cf2 = fopen(file, "r");
2254 dprintf("reading %s\n", file);
2255 readconfigfile(cf2, 0);
2263 if (*p != '!' && *p != '+' && *p != '-')
2266 if (*p == '+' || *p == '-') {
2270 if ((!*p) || (*p == '*')) {
2271 (void)strlcpy(host, "*", sizeof(host));
2276 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2277 if (!isalnum(*p) && *p != '.' && *p != '-'
2278 && *p != ',' && *p != ':' && *p != '%')
2287 while (isspace(*p)) p++;
2288 if ((!*p) || (*p == '*')) {
2289 (void)strlcpy(prog, "*", sizeof(prog));
2292 for (i = 0; i < LINE_MAX - 1; i++) {
2293 if (!isprint(p[i]) || isspace(p[i]))
2300 for (p = cline + 1; *p != '\0'; p++) {
2303 if (*(p - 1) == '\\') {
2311 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2313 f = cfline(cline, prog, host);
2321 sighandler(int signo)
2324 /* Send an wake-up signal to the select() loop. */
2325 write(sigpipe[1], &signo, sizeof(signo));
2329 * INIT -- Initialize syslogd from configuration table
2338 char oldLocalHostName[MAXHOSTNAMELEN];
2339 char hostMsg[2*MAXHOSTNAMELEN+40];
2340 char bootfileMsg[LINE_MAX];
2346 * Load hostname (may have changed).
2349 (void)strlcpy(oldLocalHostName, LocalHostName,
2350 sizeof(oldLocalHostName));
2351 if (gethostname(LocalHostName, sizeof(LocalHostName)))
2352 err(EX_OSERR, "gethostname() failed");
2353 if ((p = strchr(LocalHostName, '.')) != NULL) {
2354 /* RFC 5424 prefers logging FQDNs. */
2355 if (RFC3164OutputFormat)
2357 LocalDomain = p + 1;
2363 * Load / reload timezone data (in case it changed).
2365 * Just calling tzset() again does not work, the timezone code
2366 * caches the result. However, by setting the TZ variable, one
2367 * can defeat the caching and have the timezone code really
2368 * reload the timezone data. Respect any initial setting of
2369 * TZ, in case the system is configured specially.
2371 dprintf("loading timezone data via tzset()\n");
2375 setenv("TZ", ":/etc/localtime", 1);
2381 * Close all open log files.
2384 STAILQ_FOREACH(f, &fhead, next) {
2385 /* flush any pending output */
2387 fprintlog_successive(f, 0);
2389 switch (f->f_type) {
2397 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
2402 while(!STAILQ_EMPTY(&fhead)) {
2403 f = STAILQ_FIRST(&fhead);
2404 STAILQ_REMOVE_HEAD(&fhead, next);
2410 /* open the configuration file */
2411 if ((cf = fopen(ConfFile, "r")) == NULL) {
2412 dprintf("cannot open %s\n", ConfFile);
2413 f = cfline("*.ERR\t/dev/console", "*", "*");
2417 f = cfline("*.PANIC\t*", "*", "*");
2426 readconfigfile(cf, 1);
2428 /* close the configuration file */
2435 STAILQ_FOREACH(f, &fhead, next) {
2436 for (i = 0; i <= LOG_NFACILITIES; i++)
2437 if (f->f_pmask[i] == INTERNAL_NOPRI)
2440 printf("%d ", f->f_pmask[i]);
2441 printf("%s: ", TypeNames[f->f_type]);
2442 switch (f->f_type) {
2444 printf("%s", f->fu_fname);
2449 printf("%s%s", _PATH_DEV, f->fu_fname);
2453 switch (f->fu_forw_addr->ai_addr->sa_family) {
2456 port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2461 port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2469 f->fu_forw_hname, port);
2471 printf("%s", f->fu_forw_hname);
2476 printf("%s", f->fu_pipe_pname);
2480 for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2481 printf("%s, ", f->fu_uname[i]);
2485 printf(" (%s)", f->f_program);
2490 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2491 NULL, NULL, "restart", 0);
2492 dprintf("syslogd: restarted\n");
2494 * Log a change in hostname, but only on a restart.
2496 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
2497 (void)snprintf(hostMsg, sizeof(hostMsg),
2498 "hostname changed, \"%s\" to \"%s\"",
2499 oldLocalHostName, LocalHostName);
2500 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2501 NULL, NULL, NULL, hostMsg, 0);
2502 dprintf("%s\n", hostMsg);
2505 * Log the kernel boot file if we aren't going to use it as
2506 * the prefix, and if this is *not* a restart.
2508 if (signo == 0 && !use_bootfile) {
2509 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2510 "kernel boot file is %s", bootfile);
2511 logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2512 NULL, NULL, NULL, bootfileMsg, 0);
2513 dprintf("%s\n", bootfileMsg);
2518 * Crack a configuration file line
2520 static struct filed *
2521 cfline(const char *line, const char *prog, const char *host)
2524 struct addrinfo hints, *res;
2525 int error, i, pri, syncfile;
2528 char buf[MAXLINE], ebuf[100];
2530 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
2532 f = calloc(1, sizeof(*f));
2537 errno = 0; /* keep strerror() stuff out of logerror messages */
2539 for (i = 0; i <= LOG_NFACILITIES; i++)
2540 f->f_pmask[i] = INTERNAL_NOPRI;
2542 /* save hostname if any */
2543 if (host && *host == '*')
2548 f->f_host = strdup(host);
2549 if (f->f_host == NULL) {
2553 hl = strlen(f->f_host);
2554 if (hl > 0 && f->f_host[hl-1] == '.')
2555 f->f_host[--hl] = '\0';
2556 trimdomain(f->f_host, hl);
2559 /* save program name if any */
2560 if (prog && *prog == '*')
2563 f->f_program = strdup(prog);
2564 if (f->f_program == NULL) {
2570 /* scan through the list of selectors */
2571 for (p = line; *p && *p != '\t' && *p != ' ';) {
2576 /* find the end of this facility name list */
2577 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2580 /* get the priority comparison */
2608 /* collect priority name */
2609 for (bp = buf; *q && !strchr("\t,; ", *q); )
2614 while (strchr(",;", *q))
2617 /* decode priority name */
2620 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2622 /* Ignore trailing spaces. */
2623 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2626 pri = decode(buf, prioritynames);
2629 (void)snprintf(ebuf, sizeof ebuf,
2630 "unknown priority name \"%s\"", buf);
2637 pri_cmp = (UniquePriority)
2642 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2644 /* scan facilities */
2645 while (*p && !strchr("\t.; ", *p)) {
2646 for (bp = buf; *p && !strchr("\t,;. ", *p); )
2651 for (i = 0; i < LOG_NFACILITIES; i++) {
2652 f->f_pmask[i] = pri;
2653 f->f_pcmp[i] = pri_cmp;
2656 i = decode(buf, facilitynames);
2659 (void)snprintf(ebuf, sizeof ebuf,
2660 "unknown facility name \"%s\"",
2666 f->f_pmask[i >> 3] = pri;
2667 f->f_pcmp[i >> 3] = pri_cmp;
2669 while (*p == ',' || *p == ' ')
2676 /* skip to action part */
2677 while (*p == '\t' || *p == ' ')
2692 * scan forward to see if there is a port defined.
2693 * so we can't use strlcpy..
2695 i = sizeof(f->fu_forw_hname);
2696 tp = f->fu_forw_hname;
2700 * an ipv6 address should start with a '[' in that case
2701 * we should scan for a ']'
2707 while (*p && (*p != endkey) && (i-- > 0)) {
2710 if (endkey == ']' && *p == endkey)
2714 /* See if we copied a domain and have a port */
2720 hints = (struct addrinfo){
2721 .ai_family = family,
2722 .ai_socktype = SOCK_DGRAM
2724 error = getaddrinfo(f->fu_forw_hname,
2725 p ? p : "syslog", &hints, &res);
2727 logerror(gai_strerror(error));
2730 f->fu_forw_addr = res;
2735 if ((f->f_file = open(p, logflags, 0600)) < 0) {
2736 f->f_type = F_UNUSED;
2741 f->f_flags |= FFLAG_SYNC;
2742 if (isatty(f->f_file)) {
2743 if (strcmp(p, ctty) == 0)
2744 f->f_type = F_CONSOLE;
2747 (void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
2748 sizeof(f->fu_fname));
2750 (void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
2757 (void)strlcpy(f->fu_pipe_pname, p + 1,
2758 sizeof(f->fu_pipe_pname));
2767 for (i = 0; i < MAXUNAMES && *p; i++) {
2768 for (q = p; *q && *q != ','; )
2770 (void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
2771 if ((q - p) >= MAXLOGNAME)
2772 f->fu_uname[i][MAXLOGNAME - 1] = '\0';
2774 f->fu_uname[i][q - p] = '\0';
2775 while (*q == ',' || *q == ' ')
2779 f->f_type = F_USERS;
2787 * Decode a symbolic name to a numeric value
2790 decode(const char *name, const CODE *codetab)
2796 return (atoi(name));
2798 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2800 *p = tolower(*name);
2805 for (c = codetab; c->c_name; c++)
2806 if (!strcmp(buf, c->c_name))
2816 struct deadq_entry *dq, *dq0;
2818 now = time((time_t *)NULL);
2819 MarkSeq += TIMERINTVL;
2820 if (MarkSeq >= MarkInterval) {
2821 logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
2822 "-- MARK --", MARK);
2826 STAILQ_FOREACH(f, &fhead, next) {
2827 if (f->f_prevcount && now >= REPEATTIME(f)) {
2828 dprintf("flush %s: repeated %d times, %d sec.\n",
2829 TypeNames[f->f_type], f->f_prevcount,
2830 repeatinterval[f->f_repeatcount]);
2831 fprintlog_successive(f, 0);
2836 /* Walk the dead queue, and see if we should signal somebody. */
2837 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
2838 switch (dq->dq_timeout) {
2840 /* Already signalled once, try harder now. */
2841 if (kill(dq->dq_pid, SIGKILL) != 0)
2842 (void)deadq_remove(dq);
2847 * Timed out on dead queue, send terminate
2848 * signal. Note that we leave the removal
2849 * from the dead queue to reapchild(), which
2850 * will also log the event (unless the process
2851 * didn't even really exist, in case we simply
2852 * drop it from the dead queue).
2854 if (kill(dq->dq_pid, SIGTERM) != 0)
2855 (void)deadq_remove(dq);
2864 (void)alarm(TIMERINTVL);
2868 * fork off and become a daemon, but wait for the child to come online
2869 * before returning to the parent, or we get disk thrashing at boot etc.
2870 * Set a timer so we don't hang forever if it wedges.
2873 waitdaemon(int maxwait)
2877 pid_t pid, childpid;
2879 switch (childpid = fork()) {
2885 signal(SIGALRM, timedout);
2887 while ((pid = wait3(&status, 0, NULL)) != -1) {
2888 if (WIFEXITED(status))
2889 errx(1, "child pid %d exited with return code %d",
2890 pid, WEXITSTATUS(status));
2891 if (WIFSIGNALED(status))
2892 errx(1, "child pid %d exited on signal %d%s",
2893 pid, WTERMSIG(status),
2894 WCOREDUMP(status) ? " (core dumped)" :
2896 if (pid == childpid) /* it's gone... */
2906 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2907 (void)dup2(fd, STDIN_FILENO);
2908 (void)dup2(fd, STDOUT_FILENO);
2909 (void)dup2(fd, STDERR_FILENO);
2910 if (fd > STDERR_FILENO)
2917 * We get a SIGALRM from the child when it's running and finished doing it's
2918 * fsync()'s or O_SYNC writes for all the boot messages.
2920 * We also get a signal from the kernel if the timer expires, so check to
2921 * see what happened.
2924 timedout(int sig __unused)
2928 signal(SIGALRM, SIG_DFL);
2930 errx(1, "timed out waiting for child");
2936 * Add `s' to the list of allowable peer addresses to accept messages
2939 * `s' is a string in the form:
2941 * [*]domainname[:{servicename|portnumber|*}]
2945 * netaddr/maskbits[:{servicename|portnumber|*}]
2947 * Returns -1 on error, 0 if the argument was valid.
2952 #if defined(INET) || defined(INET6)
2954 struct allowedpeer *ap;
2957 struct addrinfo hints, *res = NULL;
2959 in_addr_t *addrp, *maskp;
2962 uint32_t *addr6p, *mask6p;
2964 char ip[NI_MAXHOST];
2966 ap = calloc(1, sizeof(*ap));
2968 err(1, "malloc failed");
2971 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2974 if ((cp1 = strrchr(cp1, ':'))) {
2975 /* service/port provided */
2977 if (strlen(cp1) == 1 && *cp1 == '*')
2978 /* any port allowed */
2980 else if ((se = getservbyname(cp1, "udp"))) {
2981 ap->port = ntohs(se->s_port);
2983 ap->port = strtol(cp1, &cp2, 0);
2984 /* port not numeric */
2989 if ((se = getservbyname("syslog", "udp")))
2990 ap->port = ntohs(se->s_port);
2992 /* sanity, should not happen */
2996 if ((cp1 = strchr(s, '/')) != NULL &&
2997 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2999 if ((masklen = atoi(cp1 + 1)) < 0)
3004 cp2 = s + strlen(s) - 1;
3015 hints = (struct addrinfo){
3016 .ai_family = PF_UNSPEC,
3017 .ai_socktype = SOCK_DGRAM,
3018 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3020 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
3022 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
3023 ap->a_mask = (struct sockaddr_storage){
3024 .ss_family = res->ai_family,
3025 .ss_len = res->ai_addrlen
3027 switch (res->ai_family) {
3030 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
3031 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
3033 /* use default netmask */
3034 if (IN_CLASSA(ntohl(*addrp)))
3035 *maskp = htonl(IN_CLASSA_NET);
3036 else if (IN_CLASSB(ntohl(*addrp)))
3037 *maskp = htonl(IN_CLASSB_NET);
3039 *maskp = htonl(IN_CLASSC_NET);
3040 } else if (masklen == 0) {
3042 } else if (masklen <= 32) {
3043 /* convert masklen to netmask */
3044 *maskp = htonl(~((1 << (32 - masklen)) - 1));
3048 /* Lose any host bits in the network number. */
3059 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
3060 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
3061 /* convert masklen to netmask */
3062 while (masklen > 0) {
3065 htonl(~(0xffffffff >> masklen));
3069 *mask6p++ = 0xffffffff;
3081 /* arg `s' is domain name */
3093 STAILQ_INSERT_TAIL(&aphead, ap, next);
3096 printf("allowaddr: rule ");
3097 if (ap->isnumeric) {
3098 printf("numeric, ");
3099 getnameinfo(sstosa(&ap->a_addr),
3100 (sstosa(&ap->a_addr))->sa_len,
3101 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3102 printf("addr = %s, ", ip);
3103 getnameinfo(sstosa(&ap->a_mask),
3104 (sstosa(&ap->a_mask))->sa_len,
3105 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3106 printf("mask = %s; ", ip);
3108 printf("domainname = %s; ", ap->a_name);
3110 printf("port = %d\n", ap->port);
3123 * Validate that the remote peer has permission to log to us.
3126 validate(struct sockaddr *sa, const char *hname)
3129 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3130 struct allowedpeer *ap;
3132 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3135 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3137 struct addrinfo hints, *res;
3141 STAILQ_FOREACH(ap, &aphead, next) {
3144 dprintf("# of validation rule: %d\n", num);
3146 /* traditional behaviour, allow everything */
3149 (void)strlcpy(name, hname, sizeof(name));
3150 hints = (struct addrinfo){
3151 .ai_family = PF_UNSPEC,
3152 .ai_socktype = SOCK_DGRAM,
3153 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3155 if (getaddrinfo(name, NULL, &hints, &res) == 0)
3157 else if (strchr(name, '.') == NULL) {
3158 strlcat(name, ".", sizeof name);
3159 strlcat(name, LocalDomain, sizeof name);
3161 if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
3162 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3163 return (0); /* for safety, should not occur */
3164 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3168 /* now, walk down the list */
3170 STAILQ_FOREACH(ap, &aphead, next) {
3172 if (ap->port != 0 && ap->port != sport) {
3173 dprintf("rejected in rule %d due to port mismatch.\n",
3178 if (ap->isnumeric) {
3179 if (ap->a_addr.ss_family != sa->sa_family) {
3180 dprintf("rejected in rule %d due to address family mismatch.\n", i);
3184 else if (ap->a_addr.ss_family == AF_INET) {
3186 a4p = satosin(&ap->a_addr);
3187 m4p = satosin(&ap->a_mask);
3188 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3189 != a4p->sin_addr.s_addr) {
3190 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3196 else if (ap->a_addr.ss_family == AF_INET6) {
3197 sin6 = satosin6(sa);
3198 a6p = satosin6(&ap->a_addr);
3199 m6p = satosin6(&ap->a_mask);
3200 if (a6p->sin6_scope_id != 0 &&
3201 sin6->sin6_scope_id != a6p->sin6_scope_id) {
3202 dprintf("rejected in rule %d due to scope mismatch.\n", i);
3205 if (IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3206 &a6p->sin6_addr, &m6p->sin6_addr) != 0) {
3207 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3215 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3217 dprintf("rejected in rule %d due to name "
3222 dprintf("accepted in rule %d.\n", i);
3223 return (1); /* hooray! */
3229 * Fairly similar to popen(3), but returns an open descriptor, as
3230 * opposed to a FILE *.
3233 p_open(const char *prog, pid_t *rpid)
3235 int pfd[2], nulldesc;
3237 char *argv[4]; /* sh -c cmd NULL */
3240 if (pipe(pfd) == -1)
3242 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
3243 /* we are royally screwed anyway */
3246 switch ((pid = fork())) {
3252 (void)setsid(); /* Avoid catching SIGHUPs. */
3253 argv[0] = strdup("sh");
3254 argv[1] = strdup("-c");
3255 argv[2] = strdup(prog);
3257 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
3264 /* Restore signals marked as SIG_IGN. */
3265 (void)signal(SIGINT, SIG_DFL);
3266 (void)signal(SIGQUIT, SIG_DFL);
3267 (void)signal(SIGPIPE, SIG_DFL);
3269 dup2(pfd[0], STDIN_FILENO);
3270 dup2(nulldesc, STDOUT_FILENO);
3271 dup2(nulldesc, STDERR_FILENO);
3272 closefrom(STDERR_FILENO + 1);
3274 (void)execvp(_PATH_BSHELL, argv);
3280 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
3281 * supposed to get an EWOULDBLOCK on writev(2), which is
3282 * caught by the logic above anyway, which will in turn close
3283 * the pipe, and fork a new logging subprocess if necessary.
3284 * The stale subprocess will be killed some time later unless
3285 * it terminated itself due to closing its input pipe (so we
3286 * get rid of really dead puppies).
3288 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3290 (void)snprintf(errmsg, sizeof errmsg,
3291 "Warning: cannot change pipe to PID %d to "
3292 "non-blocking behaviour.",
3301 deadq_enter(pid_t pid, const char *name)
3303 struct deadq_entry *dq;
3309 * Be paranoid, if we can't signal the process, don't enter it
3310 * into the dead queue (perhaps it's already dead). If possible,
3311 * we try to fetch and log the child's status.
3313 if (kill(pid, 0) != 0) {
3314 if (waitpid(pid, &status, WNOHANG) > 0)
3315 log_deadchild(pid, status, name);
3319 dq = malloc(sizeof(*dq));
3324 *dq = (struct deadq_entry){
3326 .dq_timeout = DQ_TIMO_INIT
3328 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3332 deadq_remove(struct deadq_entry *dq)
3335 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3344 deadq_removebypid(pid_t pid)
3346 struct deadq_entry *dq;
3348 TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
3349 if (dq->dq_pid == pid)
3352 return (deadq_remove(dq));
3356 log_deadchild(pid_t pid, int status, const char *name)
3362 errno = 0; /* Keep strerror() stuff out of logerror messages. */
3363 if (WIFSIGNALED(status)) {
3364 reason = "due to signal";
3365 code = WTERMSIG(status);
3367 reason = "with status";
3368 code = WEXITSTATUS(status);
3372 (void)snprintf(buf, sizeof buf,
3373 "Logging subprocess %d (%s) exited %s %d.",
3374 pid, name, reason, code);
3379 socksetup(struct peer *pe)
3381 struct addrinfo hints, *res, *res0;
3384 int (*sl_recv)(struct socklist *);
3386 * We have to handle this case for backwards compatibility:
3387 * If there are two (or more) colons but no '[' and ']',
3388 * assume this is an inet6 address without a service.
3390 if (pe->pe_name != NULL) {
3392 if (pe->pe_name[0] == '[' &&
3393 (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
3394 pe->pe_name = &pe->pe_name[1];
3396 if (cp[1] == ':' && cp[2] != '\0')
3397 pe->pe_serv = cp + 2;
3400 cp = strchr(pe->pe_name, ':');
3401 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
3404 pe->pe_serv = cp + 1;
3405 if (cp == pe->pe_name)
3412 hints = (struct addrinfo){
3413 .ai_family = AF_UNSPEC,
3414 .ai_socktype = SOCK_DGRAM,
3415 .ai_flags = AI_PASSIVE
3417 if (pe->pe_name != NULL)
3418 dprintf("Trying peer: %s\n", pe->pe_name);
3419 if (pe->pe_serv == NULL)
3420 pe->pe_serv = "syslog";
3421 error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
3425 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
3426 pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
3427 gai_strerror(error));
3430 logerror(gai_strerror(error));
3436 for (res = res0; res != NULL; res = res->ai_next) {
3439 if (res->ai_family != AF_LOCAL &&
3441 /* Only AF_LOCAL in secure mode. */
3444 if (family != AF_UNSPEC &&
3445 res->ai_family != AF_LOCAL && res->ai_family != family)
3448 s = socket(res->ai_family, res->ai_socktype,
3456 if (res->ai_family == AF_INET6) {
3457 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
3458 &(int){1}, sizeof(int)) < 0) {
3459 logerror("setsockopt(IPV6_V6ONLY)");
3466 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
3467 &(int){1}, sizeof(int)) < 0) {
3468 logerror("setsockopt(SO_REUSEADDR)");
3475 * Bind INET and UNIX-domain sockets.
3477 * A UNIX-domain socket is always bound to a pathname
3478 * regardless of -N flag.
3480 * For INET sockets, RFC 3164 recommends that client
3481 * side message should come from the privileged syslogd port.
3483 * If the system administrator chooses not to obey
3484 * this, we can skip the bind() step so that the
3485 * system will choose a port for us.
3487 if (res->ai_family == AF_LOCAL)
3488 unlink(pe->pe_name);
3489 if (res->ai_family == AF_LOCAL ||
3490 NoBind == 0 || pe->pe_name != NULL) {
3491 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
3497 if (res->ai_family == AF_LOCAL ||
3501 if (res->ai_family == AF_LOCAL &&
3502 chmod(pe->pe_name, pe->pe_mode) < 0) {
3503 dprintf("chmod %s: %s\n", pe->pe_name,
3509 dprintf("new socket fd is %d\n", s);
3510 if (res->ai_socktype != SOCK_DGRAM) {
3513 sl_recv = socklist_recv_sock;
3514 #if defined(INET) || defined(INET6)
3515 if (SecureMode && (res->ai_family == AF_INET ||
3516 res->ai_family == AF_INET6)) {
3517 dprintf("shutdown\n");
3518 /* Forbid communication in secure mode. */
3519 if (shutdown(s, SHUT_RD) < 0 &&
3520 errno != ENOTCONN) {
3521 logerror("shutdown");
3528 dprintf("listening on socket\n");
3529 dprintf("sending on socket\n");
3530 addsock(res->ai_addr, res->ai_addrlen,
3543 increase_rcvbuf(int fd)
3547 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3548 &(socklen_t){sizeof(len)}) == 0) {
3549 if (len < RCVBUF_MINSIZE) {
3550 len = RCVBUF_MINSIZE;
3551 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));