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
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
35 The Regents of the University of California. All rights reserved.\n";
40 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
48 * syslogd -- log system messages
50 * This program implements a system log. It takes a series of lines.
51 * Each line may have a priority, signified as "<n>" as
52 * the first characters of the line. If this is
53 * not present, a default priority is used.
55 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
56 * cause it to reread its configuration file.
60 * MAXLINE -- the maximum line length that can be handled.
61 * DEFUPRI -- the default priority for user messages
62 * DEFSPRI -- the default priority for kernel messages
65 * extensive changes by Ralph Campbell
66 * more extensive changes by Eric Allman (again)
67 * Extension to log by program name as well as facility and priority
69 * -u and -v by Harlan Stenn.
70 * Priority comparison code by Harlan Stenn.
73 /* Maximum number of characters in time of last occurrence */
75 #define MAXLINE 1024 /* maximum line length */
76 #define MAXSVLINE MAXLINE /* maximum saved line length */
77 #define DEFUPRI (LOG_USER|LOG_NOTICE)
78 #define DEFSPRI (LOG_KERN|LOG_CRIT)
79 #define TIMERINTVL 30 /* interval for checking flush, mark */
80 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
81 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
83 #include <sys/param.h>
84 #include <sys/ioctl.h>
86 #include <sys/queue.h>
87 #include <sys/resource.h>
88 #include <sys/socket.h>
90 #include <sys/syslimits.h>
96 #if defined(INET) || defined(INET6)
97 #include <netinet/in.h>
98 #include <arpa/inet.h>
115 #include <sysexits.h>
119 #include "pathnames.h"
123 #include <sys/syslog.h>
125 static const char *ConfFile = _PATH_LOGCONF;
126 static const char *PidFile = _PATH_LOGPID;
127 static const char ctty[] = _PATH_CONSOLE;
128 static const char include_str[] = "include";
129 static const char include_ext[] = ".conf";
131 #define dprintf if (Debug) printf
133 #define MAXUNAMES 20 /* maximum number of user names */
135 #define sstosa(ss) ((struct sockaddr *)(ss))
137 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss))
138 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa))
141 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss))
142 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa))
143 #define s6_addr32 __u6_addr.__u6_addr32
144 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \
145 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
146 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
147 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
148 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
151 * List of peers and sockets for binding.
157 STAILQ_ENTRY(peer) next;
159 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
162 struct sockaddr_storage sl_ss;
164 struct peer *sl_peer;
165 int (*sl_recv)(struct socklist *);
166 STAILQ_ENTRY(socklist) next;
168 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
174 #define IGN_CONS 0x001 /* don't print on console */
175 #define SYNC_FILE 0x002 /* do fsync on file after printing */
176 #define MARK 0x008 /* this message is a mark */
177 #define ISKERNEL 0x010 /* kernel generated message */
180 * This structure represents the files that will have log
182 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
183 * or if f_type if F_PIPE and f_pid > 0.
187 STAILQ_ENTRY(filed) next; /* next in linked list */
188 short f_type; /* entry type, see below */
189 short f_file; /* file descriptor */
190 time_t f_time; /* time this was last written */
191 char *f_host; /* host from which to recd. */
192 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
193 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
197 char *f_program; /* program this applies to */
199 char f_uname[MAXUNAMES][MAXLOGNAME];
201 char f_hname[MAXHOSTNAMELEN];
202 struct addrinfo *f_addr;
204 } f_forw; /* forwarding address */
205 char f_fname[MAXPATHLEN];
207 char f_pname[MAXPATHLEN];
211 #define fu_uname f_un.f_uname
212 #define fu_forw_hname f_un.f_forw.f_hname
213 #define fu_forw_addr f_un.f_forw.f_addr
214 #define fu_fname f_un.f_fname
215 #define fu_pipe_pname f_un.f_pipe.f_pname
216 #define fu_pipe_pid f_un.f_pipe.f_pid
217 char f_prevline[MAXSVLINE]; /* last message logged */
218 char f_lasttime[MAXDATELEN]; /* time of last occurrence */
219 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
220 int f_prevpri; /* pri of f_prevline */
221 int f_prevlen; /* length of f_prevline */
222 int f_prevcount; /* repetition cnt of prevline */
223 u_int f_repeatcount; /* number of "repeated" msgs */
224 int f_flags; /* file-specific flags */
225 #define FFLAG_SYNC 0x01
226 #define FFLAG_NEEDSYNC 0x02
230 * Queue of about-to-be dead processes we should watch out for.
235 TAILQ_ENTRY(deadq_entry) dq_entries;
237 static TAILQ_HEAD(, deadq_entry) deadq_head =
238 TAILQ_HEAD_INITIALIZER(deadq_head);
241 * The timeout to apply to processes waiting on the dead queue. Unit
242 * of measure is `mark intervals', i.e. 20 minutes by default.
243 * Processes on the dead queue will be terminated after that time.
246 #define DQ_TIMO_INIT 2
249 * Struct to hold records of network addresses that are allowed to log
257 struct sockaddr_storage addr;
258 struct sockaddr_storage mask;
262 #define a_addr u.numeric.addr
263 #define a_mask u.numeric.mask
264 #define a_name u.name
265 STAILQ_ENTRY(allowedpeer) next;
267 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
271 * Intervals at which we flush out "message repeated" messages,
272 * in seconds after previous message is logged. After each flush,
273 * we move to the next interval until we reach the largest.
275 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
276 #define MAXREPEAT (nitems(repeatinterval) - 1)
277 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
278 #define BACKOFF(f) do { \
279 if (++(f)->f_repeatcount > MAXREPEAT) \
280 (f)->f_repeatcount = MAXREPEAT; \
283 /* values for f_type */
284 #define F_UNUSED 0 /* unused entry */
285 #define F_FILE 1 /* regular file */
286 #define F_TTY 2 /* terminal */
287 #define F_CONSOLE 3 /* console terminal */
288 #define F_FORW 4 /* remote machine */
289 #define F_USERS 5 /* list of users */
290 #define F_WALL 6 /* everyone logged on */
291 #define F_PIPE 7 /* pipe to program */
293 static const char *TypeNames[] = {
294 "UNUSED", "FILE", "TTY", "CONSOLE",
295 "FORW", "USERS", "WALL", "PIPE"
298 static STAILQ_HEAD(, filed) fhead =
299 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */
300 static struct filed consfile; /* Console */
302 static int Debug; /* debug flag */
303 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
304 static int resolve = 1; /* resolve hostname */
305 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
306 static const char *LocalDomain; /* our local domain name */
307 static int Initialized; /* set when we have initialized ourselves */
308 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
309 static int MarkSeq; /* mark sequence number */
310 static int NoBind; /* don't bind() as suggested by RFC 3164 */
311 static int SecureMode; /* when true, receive only unix domain socks */
313 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
315 static int family = PF_INET; /* protocol family (IPv4 only) */
317 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
318 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
319 static int use_bootfile; /* log entire bootfile for every kern msg */
320 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
321 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
323 static char bootfile[MAXLINE+1]; /* booted kernel file */
325 static int RemoteAddDate; /* Always set the date on remote messages */
326 static int RemoteHostname; /* Log remote hostname from the message */
328 static int UniquePriority; /* Only log specified priority? */
329 static int LogFacPri; /* Put facility and priority in log message: */
330 /* 0=no, 1=numeric, 2=names */
331 static int KeepKernFac; /* Keep remotely logged kernel facility */
332 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
333 static struct pidfh *pfh;
334 static int sigpipe[2]; /* Pipe to catch a signal during select(). */
336 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
338 static int allowaddr(char *);
339 static int addfile(struct filed *);
340 static int addpeer(struct peer *);
341 static int addsock(struct sockaddr *, socklen_t, struct socklist *);
342 static struct filed *cfline(const char *, const char *, const char *);
343 static const char *cvthname(struct sockaddr *);
344 static void deadq_enter(pid_t, const char *);
345 static int deadq_remove(struct deadq_entry *);
346 static int deadq_removebypid(pid_t);
347 static int decode(const char *, const CODE *);
348 static void die(int) __dead2;
349 static void dodie(int);
350 static void dofsync(void);
351 static void domark(int);
352 static void fprintlog(struct filed *, int, const char *);
353 static void init(int);
354 static void logerror(const char *);
355 static void logmsg(int, const char *, const char *, const char *, int);
356 static void log_deadchild(pid_t, int, const char *);
357 static void markit(void);
358 static int socksetup(struct peer *);
359 static int socklist_recv_file(struct socklist *);
360 static int socklist_recv_sock(struct socklist *);
361 static int socklist_recv_signal(struct socklist *);
362 static void sighandler(int);
363 static int skip_message(const char *, const char *, int);
364 static void parsemsg(const char *, char *);
365 static void printsys(char *);
366 static int p_open(const char *, pid_t *);
367 static void reapchild(int);
368 static const char *ttymsg_check(struct iovec *, int, char *, int);
369 static void usage(void);
370 static int validate(struct sockaddr *, const char *);
371 static void unmapped(struct sockaddr *);
372 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
373 static int waitdaemon(int);
374 static void timedout(int);
375 static void increase_rcvbuf(int);
378 close_filed(struct filed *f)
381 if (f == NULL || f->f_file == -1)
389 f->f_type = F_UNUSED;
395 (void)close(f->f_file);
400 addfile(struct filed *f0)
404 f = calloc(1, sizeof(*f));
406 err(1, "malloc failed");
408 STAILQ_INSERT_TAIL(&fhead, f, next);
414 addpeer(struct peer *pe0)
418 pe = calloc(1, sizeof(*pe));
420 err(1, "malloc failed");
422 STAILQ_INSERT_TAIL(&pqueue, pe, next);
428 addsock(struct sockaddr *sa, socklen_t sa_len, struct socklist *sl0)
432 sl = calloc(1, sizeof(*sl));
434 err(1, "malloc failed");
436 if (sa != NULL && sa_len > 0)
437 memcpy(&sl->sl_ss, sa, sa_len);
438 STAILQ_INSERT_TAIL(&shead, sl, next);
444 main(int argc, char *argv[])
446 int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
448 struct timeval tv, *tvp;
451 pid_t ppid = 1, spid;
454 if (madvise(NULL, 0, MADV_PROTECT) != 0)
455 dprintf("madvise() failed: %s\n", strerror(errno));
457 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:m:nNop:P:sS:Tuv"))
476 case 'a': /* allow specific network addresses only */
477 if (allowaddr(optarg) == -1)
482 p = strchr(optarg, ']');
484 p = strchr(p + 1, ':');
486 p = strchr(optarg, ':');
487 if (p != NULL && strchr(p + 1, ':') != NULL)
488 p = NULL; /* backward compatibility */
491 /* A hostname or filename only. */
492 addpeer(&(struct peer){
497 /* The case of "name:service". */
499 addpeer(&(struct peer){
501 .pe_name = (strlen(optarg) == 0) ?
512 case 'd': /* debug */
515 case 'f': /* configuration file */
518 case 'F': /* run in foreground instead of daemon */
524 case 'k': /* keep remote kern fac */
537 else if (ch == 'p') {
540 } else if (ch == 'S') {
541 mode = S_IRUSR | S_IWUSR;
544 if (optarg[0] == '/')
546 else if ((name = strchr(optarg, ':')) != NULL) {
549 errx(1, "socket name must be absolute "
551 if (isdigit(*optarg)) {
552 perml = strtol(optarg, &ep, 8);
553 if (*ep || perml < 0 ||
554 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
555 errx(1, "invalid mode %s, exiting",
557 mode = (mode_t )perml;
559 errx(1, "invalid mode %s, exiting",
562 errx(1, "invalid filename %s, exiting",
564 addpeer(&(struct peer){
570 case 'm': /* mark interval */
571 MarkInterval = atoi(optarg) * 60;
583 case 'P': /* path for alt. PID */
586 case 's': /* no network mode */
592 case 'u': /* only log specified priority */
595 case 'v': /* log facility and priority */
601 if ((argc -= optind) != 0)
604 /* Pipe to catch a signal during select(). */
605 s = pipe2(sigpipe, O_CLOEXEC);
607 err(1, "cannot open a pipe for signals");
609 addsock(NULL, 0, &(struct socklist){
610 .sl_socket = sigpipe[0],
611 .sl_recv = socklist_recv_signal
615 /* Listen by default: /dev/klog. */
616 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
618 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
620 addsock(NULL, 0, &(struct socklist){
622 .sl_recv = socklist_recv_file,
625 /* Listen by default: *:514 if no -b flag. */
627 addpeer(&(struct peer){
630 /* Listen by default: /var/run/log if no -p flag. */
632 addpeer(&(struct peer){
633 .pe_name = _PATH_LOG,
634 .pe_mode = DEFFILEMODE,
636 /* Listen by default: /var/run/logpriv if no -S flag. */
638 addpeer(&(struct peer){
639 .pe_name = _PATH_LOG_PRIV,
640 .pe_mode = S_IRUSR | S_IWUSR,
642 STAILQ_FOREACH(pe, &pqueue, next)
645 pfh = pidfile_open(PidFile, 0600, &spid);
648 errx(1, "syslogd already running, pid: %d", spid);
649 warn("cannot open pid file");
652 if ((!Foreground) && (!Debug)) {
653 ppid = waitdaemon(30);
655 warn("could not become daemon");
662 consfile.f_type = F_CONSOLE;
663 (void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
664 sizeof(consfile.fu_fname));
665 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
666 (void)signal(SIGTERM, dodie);
667 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
668 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
669 (void)signal(SIGHUP, sighandler);
670 (void)signal(SIGCHLD, sighandler);
671 (void)signal(SIGALRM, domark);
672 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
673 (void)alarm(TIMERINTVL);
675 /* tuck my process id away */
678 dprintf("off & running....\n");
681 tv.tv_sec = tv.tv_usec = 0;
683 STAILQ_FOREACH(sl, &shead, next) {
684 if (sl->sl_socket > fdsrmax)
685 fdsrmax = sl->sl_socket;
687 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
690 errx(1, "calloc fd_set");
693 if (Initialized == 0)
695 else if (WantInitialize)
696 init(WantInitialize);
698 reapchild(WantReapchild);
706 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
709 STAILQ_FOREACH(sl, &shead, next) {
710 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
711 FD_SET(sl->sl_socket, fdsr);
713 i = select(fdsrmax + 1, fdsr, NULL, NULL,
714 needdofsync ? &tv : tvp);
730 STAILQ_FOREACH(sl, &shead, next) {
731 if (FD_ISSET(sl->sl_socket, fdsr))
739 socklist_recv_signal(struct socklist *sl __unused)
744 if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
745 logerror("ioctl(FIONREAD)");
746 err(1, "signal pipe read failed");
748 nsig = i / sizeof(signo);
749 dprintf("# of received signals = %d\n", nsig);
750 for (i = 0; i < nsig; i++) {
751 len = read(sigpipe[0], &signo, sizeof(signo));
752 if (len != sizeof(signo)) {
753 logerror("signal pipe read failed");
754 err(1, "signal pipe read failed");
756 dprintf("Received signal: %d from fd=%d\n", signo,
771 socklist_recv_sock(struct socklist *sl)
773 struct sockaddr_storage ss;
774 struct sockaddr *sa = (struct sockaddr *)&ss;
777 char line[MAXLINE + 1];
781 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
782 dprintf("received sa_len = %d\n", sslen);
787 logerror("recvfrom");
790 /* Received valid data. */
792 if (sl->sl_ss.ss_family == AF_LOCAL)
793 hname = LocalHostName;
795 hname = cvthname(sa);
797 if (validate(sa, hname) == 0) {
798 dprintf("Message from %s was ignored.", hname);
802 parsemsg(hname, line);
808 unmapped(struct sockaddr *sa)
810 #if defined(INET) && defined(INET6)
811 struct sockaddr_in6 *sin6;
812 struct sockaddr_in sin;
815 sa->sa_family != AF_INET6 ||
816 sa->sa_len != sizeof(*sin6))
819 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
821 sin = (struct sockaddr_in){
822 .sin_family = AF_INET,
823 .sin_len = sizeof(sin),
824 .sin_port = sin6->sin6_port
826 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
827 sizeof(sin.sin_addr));
828 memcpy(sa, &sin, sizeof(sin));
839 fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
840 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]",
841 " [-b bind_address] [-f config_file]",
842 " [-l [mode:]path] [-m mark_interval]",
843 " [-P pid_file] [-p log_socket]",
844 " [-S logpriv_socket]");
849 * Take a raw input line, extract PRI, TIMESTAMP and HOSTNAME from the message,
850 * and print the message on the appropriate log files.
853 parsemsg(const char *from, char *msg)
855 const char *timestamp;
858 int i, c, pri, msglen;
859 char line[MAXLINE + 1];
862 if (msg[0] != '<' || !isdigit(msg[1])) {
863 dprintf("Invalid PRI from %s\n", from);
866 for (i = 2; i <= 4; i++) {
869 if (!isdigit(msg[i])) {
870 dprintf("Invalid PRI header from %s\n", from);
875 dprintf("Invalid PRI header from %s\n", from);
879 n = strtol(msg + 1, &q, 10);
880 if (errno != 0 || *q != msg[i] || n < 0 || n >= INT_MAX) {
881 dprintf("Invalid PRI %ld from %s: %s\n",
882 n, from, strerror(errno));
886 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
890 * Don't allow users to log kernel messages.
891 * NOTE: since LOG_KERN == 0 this will also match
892 * messages with no facility specified.
894 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
895 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
898 * The TIMESTAMP field is the local time and is in the format of
899 * "Mmm dd hh:mm:ss" (without the quote marks).
900 * A single space character MUST follow the TIMESTAMP field.
902 * XXXGL: the check can be improved.
905 msglen = strlen(msg);
906 if (msglen < MAXDATELEN || msg[3] != ' ' || msg[6] != ' ' ||
907 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
908 dprintf("Invalid TIMESTAMP from %s: %s\n", from, msg);
917 msglen -= MAXDATELEN;
920 * A single space character MUST also follow the HOSTNAME field.
922 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
924 if (RemoteHostname) {
932 * Support non RFC compliant messages, without hostname.
937 if (i == MIN(MAXHOSTNAMELEN, msglen)) {
938 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
943 while ((c = (unsigned char)*msg++) != '\0' &&
944 q < &line[sizeof(line) - 4]) {
945 if (mask_C1 && (c & 0x80) && c < 0xA0) {
950 if (isascii(c) && iscntrl(c)) {
953 } else if (c == '\t') {
965 logmsg(pri, timestamp, line, from, 0);
969 * Read /dev/klog while data are available, split into lines.
972 socklist_recv_file(struct socklist *sl)
974 char *p, *q, line[MAXLINE + 1];
979 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
981 line[i + len] = '\0';
983 if (i < 0 && errno != EINTR && errno != EAGAIN) {
985 close(sl->sl_socket);
991 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
996 if (len >= MAXLINE - 1) {
1001 memmove(line, p, len + 1);
1010 * Take a raw input line from /dev/klog, format similar to syslog().
1017 int flags, isprintf, pri;
1019 flags = ISKERNEL | SYNC_FILE; /* fsync after write */
1025 n = strtol(p + 1, &q, 10);
1026 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1033 * Kernel printf's and LOG_CONSOLE messages have been displayed
1034 * on the console already.
1036 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1038 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1040 logmsg(pri, NULL, p, LocalHostName, flags);
1046 * Match a program or host name against a specification.
1047 * Return a non-0 value if the message must be ignored
1048 * based on the specification.
1051 skip_message(const char *name, const char *spec, int checkcase)
1056 /* Behaviour on explicit match */
1071 s = strstr (spec, name);
1073 s = strcasestr (spec, name);
1076 prev = (s == spec ? ',' : *(s - 1));
1077 next = *(s + strlen (name));
1079 if (prev == ',' && (next == '\0' || next == ','))
1080 /* Explicit match: skip iff the spec is an
1085 /* No explicit match for this name: skip the message iff
1086 the spec is an inclusive one. */
1091 * Log a message to the appropriate log files, users, etc. based on
1095 logmsg(int pri, const char *timestamp, const char *msg, const char *from,
1099 int i, fac, msglen, prilev;
1100 char prog[NAME_MAX+1];
1101 char buf[MAXLINE+1];
1103 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1104 pri, flags, from, msg);
1107 if (timestamp == NULL)
1108 timestamp = ctime(&now) + 4;
1110 /* extract facility and priority level */
1112 fac = LOG_NFACILITIES;
1116 /* Check maximum facility number. */
1117 if (fac > LOG_NFACILITIES)
1120 prilev = LOG_PRI(pri);
1122 /* Extract TAG part of the message (usually program name). */
1123 for (i = 0; i < NAME_MAX; i++) {
1124 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
1125 msg[i] == '/' || isspace(msg[i]))
1131 /* add kernel prefix for kernel messages */
1132 if (flags & ISKERNEL) {
1133 snprintf(buf, sizeof(buf), "%s: %s",
1134 use_bootfile ? bootfile : "kernel", msg);
1137 msglen = strlen(msg);
1139 /* log the message to the particular outputs */
1143 * Open in non-blocking mode to avoid hangs during open
1144 * and close(waiting for the port to drain).
1146 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1148 if (f->f_file >= 0) {
1149 (void)strlcpy(f->f_lasttime, timestamp,
1150 sizeof(f->f_lasttime));
1151 fprintlog(f, flags, msg);
1157 STAILQ_FOREACH(f, &fhead, next) {
1158 /* skip messages that are incorrect priority */
1159 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1160 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1161 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1163 || f->f_pmask[fac] == INTERNAL_NOPRI)
1166 /* skip messages with the incorrect hostname */
1167 if (skip_message(from, f->f_host, 0))
1170 /* skip messages with the incorrect program name */
1171 if (skip_message(prog, f->f_program, 1))
1174 /* skip message to console if it has already been printed */
1175 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1178 /* don't output marks to recently written files */
1179 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1183 * suppress duplicate lines to this file
1185 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1186 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1187 !strcmp(msg, f->f_prevline) &&
1188 !strcasecmp(from, f->f_prevhost)) {
1189 (void)strlcpy(f->f_lasttime, timestamp,
1190 sizeof(f->f_lasttime));
1192 dprintf("msg repeated %d times, %ld sec of %d\n",
1193 f->f_prevcount, (long)(now - f->f_time),
1194 repeatinterval[f->f_repeatcount]);
1196 * If domark would have logged this by now,
1197 * flush it now (so we don't hold isolated messages),
1198 * but back off so we'll flush less often
1201 if (now > REPEATTIME(f)) {
1202 fprintlog(f, flags, (char *)NULL);
1206 /* new line, save it */
1208 fprintlog(f, 0, (char *)NULL);
1209 f->f_repeatcount = 0;
1211 (void)strlcpy(f->f_lasttime, timestamp,
1212 sizeof(f->f_lasttime));
1213 (void)strlcpy(f->f_prevhost, from,
1214 sizeof(f->f_prevhost));
1215 if (msglen < MAXSVLINE) {
1216 f->f_prevlen = msglen;
1217 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1218 fprintlog(f, flags, (char *)NULL);
1220 f->f_prevline[0] = 0;
1222 fprintlog(f, flags, msg);
1233 STAILQ_FOREACH(f, &fhead, next) {
1234 if ((f->f_type == F_FILE) &&
1235 (f->f_flags & FFLAG_NEEDSYNC)) {
1236 f->f_flags &= ~FFLAG_NEEDSYNC;
1237 (void)fsync(f->f_file);
1244 fprintlog(struct filed *f, int flags, const char *msg)
1246 struct iovec iov[IOV_SIZE];
1249 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1250 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1253 if (f->f_type == F_WALL) {
1254 /* The time displayed is not synchornized with the other log
1255 * destinations (like messages). Following fragment was using
1256 * ctime(&now), which was updating the time every 30 sec.
1257 * With f_lasttime, time is synchronized correctly.
1259 iov[0] = (struct iovec){
1260 .iov_base = greetings,
1261 .iov_len = snprintf(greetings, sizeof(greetings),
1262 "\r\n\7Message from syslogd@%s "
1264 f->f_prevhost, f->f_lasttime)
1266 if (iov[0].iov_len >= sizeof(greetings))
1267 iov[0].iov_len = sizeof(greetings) - 1;
1268 iov[1] = (struct iovec){
1273 iov[0] = (struct iovec){
1274 .iov_base = f->f_lasttime,
1275 .iov_len = strlen(f->f_lasttime)
1277 iov[1] = (struct iovec){
1284 static char fp_buf[30]; /* Hollow laugh */
1285 int fac = f->f_prevpri & LOG_FACMASK;
1286 int pri = LOG_PRI(f->f_prevpri);
1287 const char *f_s = NULL;
1288 char f_n[5]; /* Hollow laugh */
1289 const char *p_s = NULL;
1290 char p_n[5]; /* Hollow laugh */
1292 if (LogFacPri > 1) {
1295 for (c = facilitynames; c->c_name; c++) {
1296 if (c->c_val == fac) {
1301 for (c = prioritynames; c->c_name; c++) {
1302 if (c->c_val == pri) {
1309 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1313 snprintf(p_n, sizeof p_n, "%d", pri);
1316 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1317 iov[2] = (struct iovec){
1319 .iov_len = strlen(fp_buf)
1322 iov[2] = (struct iovec){
1327 iov[3] = (struct iovec){
1328 .iov_base = f->f_prevhost,
1329 .iov_len = strlen(f->f_prevhost)
1331 iov[4] = (struct iovec){
1336 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1341 iov[5] = (struct iovec){
1343 .iov_len = strlen(msg)
1345 } else if (f->f_prevcount > 1) {
1346 iov[5] = (struct iovec){
1348 .iov_len = snprintf(repbuf, sizeof(repbuf),
1349 "last message repeated %d times", f->f_prevcount)
1352 iov[5] = (struct iovec){
1353 .iov_base = f->f_prevline,
1354 .iov_len = f->f_prevlen
1357 dprintf("Logging to %s", TypeNames[f->f_type]);
1360 switch (f->f_type) {
1366 dprintf(" %s", f->fu_forw_hname);
1367 switch (f->fu_forw_addr->ai_addr->sa_family) {
1371 ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1377 ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1383 /* check for local vs remote messages */
1384 if (strcasecmp(f->f_prevhost, LocalHostName))
1385 l = snprintf(line, sizeof line - 1,
1386 "<%d>%.15s Forwarded from %s: %s",
1387 f->f_prevpri, (char *)iov[0].iov_base,
1388 f->f_prevhost, (char *)iov[5].iov_base);
1390 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1391 f->f_prevpri, (char *)iov[0].iov_base,
1392 (char *)iov[5].iov_base);
1395 else if (l > MAXLINE)
1398 for (r = f->fu_forw_addr; r; r = r->ai_next) {
1399 struct socklist *sl;
1401 STAILQ_FOREACH(sl, &shead, next) {
1402 if (sl->sl_ss.ss_family == AF_LOCAL ||
1403 sl->sl_ss.ss_family == AF_UNSPEC ||
1406 lsent = sendto(sl->sl_socket, line, l, 0,
1407 r->ai_addr, r->ai_addrlen);
1411 if (lsent == l && !send_to_all)
1414 dprintf("lsent/l: %d/%d\n", lsent, l);
1429 /* case ENOTSOCK: */
1431 /* case EMSGSIZE: */
1434 /* case ECONNREFUSED: */
1436 dprintf("removing entry: errno=%d\n", e);
1437 f->f_type = F_UNUSED;
1444 dprintf(" %s\n", f->fu_fname);
1445 iov[6] = (struct iovec){
1449 if (writev(f->f_file, iov, nitems(iov)) < 0) {
1451 * If writev(2) fails for potentially transient errors
1452 * like the filesystem being full, ignore it.
1453 * Otherwise remove this logfile from the list.
1455 if (errno != ENOSPC) {
1459 logerror(f->fu_fname);
1461 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1462 f->f_flags |= FFLAG_NEEDSYNC;
1468 dprintf(" %s\n", f->fu_pipe_pname);
1469 iov[6] = (struct iovec){
1473 if (f->fu_pipe_pid == 0) {
1474 if ((f->f_file = p_open(f->fu_pipe_pname,
1475 &f->fu_pipe_pid)) < 0) {
1476 logerror(f->fu_pipe_pname);
1480 if (writev(f->f_file, iov, nitems(iov)) < 0) {
1483 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1486 logerror(f->fu_pipe_pname);
1491 if (flags & IGN_CONS) {
1492 dprintf(" (ignored)\n");
1498 dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1499 iov[6] = (struct iovec){
1503 errno = 0; /* ttymsg() only sometimes returns an errno */
1504 if ((msgret = ttymsg(iov, nitems(iov), f->fu_fname, 10))) {
1505 f->f_type = F_UNUSED;
1513 iov[6] = (struct iovec){
1517 wallmsg(f, iov, nitems(iov));
1525 * WALLMSG -- Write a message to the world at large
1527 * Write the specified message to either the entire
1528 * world, or a list of approved users.
1531 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1533 static int reenter; /* avoid calling ourselves */
1542 while ((ut = getutxent()) != NULL) {
1543 if (ut->ut_type != USER_PROCESS)
1545 if (f->f_type == F_WALL) {
1546 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1547 TTYMSGTIME)) != NULL) {
1548 errno = 0; /* already in msg */
1553 /* should we send the message to this user? */
1554 for (i = 0; i < MAXUNAMES; i++) {
1555 if (!f->fu_uname[i][0])
1557 if (!strcmp(f->fu_uname[i], ut->ut_user)) {
1558 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
1559 TTYMSGTIME)) != NULL) {
1560 errno = 0; /* already in msg */
1572 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
1575 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
1577 static char device[1024];
1578 static char errbuf[1024];
1581 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
1583 if (stat(device, &sb) < 0) {
1584 (void) snprintf(errbuf, sizeof(errbuf),
1585 "%s: %s", device, strerror(errno));
1588 if ((sb.st_mode & S_IWGRP) == 0)
1589 /* Messages disabled. */
1591 return ttymsg(iov, iovcnt, line, tmout);
1595 reapchild(int signo __unused)
1601 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1602 /* First, look if it's a process from the dead queue. */
1603 if (deadq_removebypid(pid))
1606 /* Now, look in list of active processes. */
1607 STAILQ_FOREACH(f, &fhead, next) {
1608 if (f->f_type == F_PIPE &&
1609 f->fu_pipe_pid == pid) {
1611 log_deadchild(pid, status, f->fu_pipe_pname);
1620 * Return a printable representation of a host address.
1623 cvthname(struct sockaddr *f)
1626 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1628 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
1629 error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
1632 dprintf("Malformed from address %s\n", gai_strerror(error));
1635 dprintf("cvthname(%s)\n", ip);
1640 error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
1641 NULL, 0, NI_NAMEREQD);
1643 dprintf("Host name for your address (%s) unknown\n", ip);
1647 if (hl > 0 && hname[hl-1] == '.')
1649 trimdomain(hname, hl);
1661 domark(int signo __unused)
1668 * Print syslogd errors some place.
1671 logerror(const char *type)
1674 static int recursed = 0;
1676 /* If there's an error while trying to log an error, give up. */
1682 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1684 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1686 dprintf("%s\n", buf);
1687 logmsg(LOG_SYSLOG|LOG_ERR, NULL, buf, LocalHostName, 0);
1695 struct socklist *sl;
1698 STAILQ_FOREACH(f, &fhead, next) {
1699 /* flush any pending output */
1701 fprintlog(f, 0, (char *)NULL);
1702 if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
1706 dprintf("syslogd: exiting on signal %d\n", signo);
1707 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1711 STAILQ_FOREACH(sl, &shead, next) {
1712 if (sl->sl_ss.ss_family == AF_LOCAL)
1713 unlink(sl->sl_peer->pe_name);
1715 pidfile_remove(pfh);
1721 configfiles(const struct dirent *dp)
1726 if (dp->d_name[0] == '.')
1729 ext_len = sizeof(include_ext) -1;
1731 if (dp->d_namlen <= ext_len)
1734 p = &dp->d_name[dp->d_namlen - ext_len];
1735 if (strcmp(p, include_ext) != 0)
1742 readconfigfile(FILE *cf, int allow_includes)
1746 struct dirent **ent;
1747 char cline[LINE_MAX];
1748 char host[MAXHOSTNAMELEN];
1749 char prog[LINE_MAX];
1750 char file[MAXPATHLEN];
1756 * Foreach line in the conf table, open that file.
1758 include_len = sizeof(include_str) -1;
1759 (void)strlcpy(host, "*", sizeof(host));
1760 (void)strlcpy(prog, "*", sizeof(prog));
1761 while (fgets(cline, sizeof(cline), cf) != NULL) {
1763 * check for end-of-section, comments, strip off trailing
1764 * spaces and newline character. #!prog is treated specially:
1765 * following lines apply only to that program.
1767 for (p = cline; isspace(*p); ++p)
1771 if (allow_includes &&
1772 strncmp(p, include_str, include_len) == 0 &&
1773 isspace(p[include_len])) {
1778 while (*tmp != '\0' && !isspace(*tmp))
1781 dprintf("Trying to include files in '%s'\n", p);
1782 nents = scandir(p, &ent, configfiles, alphasort);
1784 dprintf("Unable to open '%s': %s\n", p,
1788 for (i = 0; i < nents; i++) {
1789 if (snprintf(file, sizeof(file), "%s/%s", p,
1790 ent[i]->d_name) >= (int)sizeof(file)) {
1791 dprintf("ignoring path too long: "
1792 "'%s/%s'\n", p, ent[i]->d_name);
1797 cf2 = fopen(file, "r");
1800 dprintf("reading %s\n", file);
1801 readconfigfile(cf2, 0);
1809 if (*p != '!' && *p != '+' && *p != '-')
1812 if (*p == '+' || *p == '-') {
1816 if ((!*p) || (*p == '*')) {
1817 (void)strlcpy(host, "*", sizeof(host));
1822 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1823 if (!isalnum(*p) && *p != '.' && *p != '-'
1824 && *p != ',' && *p != ':' && *p != '%')
1833 while (isspace(*p)) p++;
1834 if ((!*p) || (*p == '*')) {
1835 (void)strlcpy(prog, "*", sizeof(prog));
1838 for (i = 0; i < LINE_MAX - 1; i++) {
1839 if (!isprint(p[i]) || isspace(p[i]))
1846 for (p = cline + 1; *p != '\0'; p++) {
1849 if (*(p - 1) == '\\') {
1857 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1859 f = cfline(cline, prog, host);
1866 sighandler(int signo)
1869 /* Send an wake-up signal to the select() loop. */
1870 write(sigpipe[1], &signo, sizeof(signo));
1874 * INIT -- Initialize syslogd from configuration table
1883 char oldLocalHostName[MAXHOSTNAMELEN];
1884 char hostMsg[2*MAXHOSTNAMELEN+40];
1885 char bootfileMsg[LINE_MAX];
1891 * Load hostname (may have changed).
1894 (void)strlcpy(oldLocalHostName, LocalHostName,
1895 sizeof(oldLocalHostName));
1896 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1897 err(EX_OSERR, "gethostname() failed");
1898 if ((p = strchr(LocalHostName, '.')) != NULL) {
1906 * Load / reload timezone data (in case it changed).
1908 * Just calling tzset() again does not work, the timezone code
1909 * caches the result. However, by setting the TZ variable, one
1910 * can defeat the caching and have the timezone code really
1911 * reload the timezone data. Respect any initial setting of
1912 * TZ, in case the system is configured specially.
1914 dprintf("loading timezone data via tzset()\n");
1918 setenv("TZ", ":/etc/localtime", 1);
1924 * Close all open log files.
1927 STAILQ_FOREACH(f, &fhead, next) {
1928 /* flush any pending output */
1930 fprintlog(f, 0, (char *)NULL);
1932 switch (f->f_type) {
1940 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1945 while(!STAILQ_EMPTY(&fhead)) {
1946 f = STAILQ_FIRST(&fhead);
1947 STAILQ_REMOVE_HEAD(&fhead, next);
1953 /* open the configuration file */
1954 if ((cf = fopen(ConfFile, "r")) == NULL) {
1955 dprintf("cannot open %s\n", ConfFile);
1956 f = cfline("*.ERR\t/dev/console", "*", "*");
1959 f = cfline("*.PANIC\t*", "*", "*");
1967 readconfigfile(cf, 1);
1969 /* close the configuration file */
1976 STAILQ_FOREACH(f, &fhead, next) {
1977 for (i = 0; i <= LOG_NFACILITIES; i++)
1978 if (f->f_pmask[i] == INTERNAL_NOPRI)
1981 printf("%d ", f->f_pmask[i]);
1982 printf("%s: ", TypeNames[f->f_type]);
1983 switch (f->f_type) {
1985 printf("%s", f->fu_fname);
1990 printf("%s%s", _PATH_DEV, f->fu_fname);
1994 switch (f->fu_forw_addr->ai_addr->sa_family) {
1997 port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2002 port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2010 f->fu_forw_hname, port);
2012 printf("%s", f->fu_forw_hname);
2017 printf("%s", f->fu_pipe_pname);
2021 for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2022 printf("%s, ", f->fu_uname[i]);
2026 printf(" (%s)", f->f_program);
2031 logmsg(LOG_SYSLOG|LOG_INFO, NULL, "syslogd: restart", LocalHostName, 0);
2032 dprintf("syslogd: restarted\n");
2034 * Log a change in hostname, but only on a restart.
2036 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
2037 (void)snprintf(hostMsg, sizeof(hostMsg),
2038 "syslogd: hostname changed, \"%s\" to \"%s\"",
2039 oldLocalHostName, LocalHostName);
2040 logmsg(LOG_SYSLOG|LOG_INFO, NULL, hostMsg, LocalHostName, 0);
2041 dprintf("%s\n", hostMsg);
2044 * Log the kernel boot file if we aren't going to use it as
2045 * the prefix, and if this is *not* a restart.
2047 if (signo == 0 && !use_bootfile) {
2048 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2049 "syslogd: kernel boot file is %s", bootfile);
2050 logmsg(LOG_KERN|LOG_INFO, NULL, bootfileMsg, LocalHostName, 0);
2051 dprintf("%s\n", bootfileMsg);
2056 * Crack a configuration file line
2058 static struct filed *
2059 cfline(const char *line, const char *prog, const char *host)
2062 struct addrinfo hints, *res;
2063 int error, i, pri, syncfile;
2066 char buf[MAXLINE], ebuf[100];
2068 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
2070 f = calloc(1, sizeof(*f));
2075 errno = 0; /* keep strerror() stuff out of logerror messages */
2077 for (i = 0; i <= LOG_NFACILITIES; i++)
2078 f->f_pmask[i] = INTERNAL_NOPRI;
2080 /* save hostname if any */
2081 if (host && *host == '*')
2086 f->f_host = strdup(host);
2087 if (f->f_host == NULL) {
2091 hl = strlen(f->f_host);
2092 if (hl > 0 && f->f_host[hl-1] == '.')
2093 f->f_host[--hl] = '\0';
2094 trimdomain(f->f_host, hl);
2097 /* save program name if any */
2098 if (prog && *prog == '*')
2101 f->f_program = strdup(prog);
2102 if (f->f_program == NULL) {
2108 /* scan through the list of selectors */
2109 for (p = line; *p && *p != '\t' && *p != ' ';) {
2114 /* find the end of this facility name list */
2115 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2118 /* get the priority comparison */
2146 /* collect priority name */
2147 for (bp = buf; *q && !strchr("\t,; ", *q); )
2152 while (strchr(",;", *q))
2155 /* decode priority name */
2158 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2160 /* Ignore trailing spaces. */
2161 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2164 pri = decode(buf, prioritynames);
2167 (void)snprintf(ebuf, sizeof ebuf,
2168 "unknown priority name \"%s\"", buf);
2175 pri_cmp = (UniquePriority)
2180 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2182 /* scan facilities */
2183 while (*p && !strchr("\t.; ", *p)) {
2184 for (bp = buf; *p && !strchr("\t,;. ", *p); )
2189 for (i = 0; i < LOG_NFACILITIES; i++) {
2190 f->f_pmask[i] = pri;
2191 f->f_pcmp[i] = pri_cmp;
2194 i = decode(buf, facilitynames);
2197 (void)snprintf(ebuf, sizeof ebuf,
2198 "unknown facility name \"%s\"",
2204 f->f_pmask[i >> 3] = pri;
2205 f->f_pcmp[i >> 3] = pri_cmp;
2207 while (*p == ',' || *p == ' ')
2214 /* skip to action part */
2215 while (*p == '\t' || *p == ' ')
2230 * scan forward to see if there is a port defined.
2231 * so we can't use strlcpy..
2233 i = sizeof(f->fu_forw_hname);
2234 tp = f->fu_forw_hname;
2238 * an ipv6 address should start with a '[' in that case
2239 * we should scan for a ']'
2245 while (*p && (*p != endkey) && (i-- > 0)) {
2248 if (endkey == ']' && *p == endkey)
2252 /* See if we copied a domain and have a port */
2258 hints = (struct addrinfo){
2259 .ai_family = family,
2260 .ai_socktype = SOCK_DGRAM
2262 error = getaddrinfo(f->fu_forw_hname,
2263 p ? p : "syslog", &hints, &res);
2265 logerror(gai_strerror(error));
2268 f->fu_forw_addr = res;
2273 if ((f->f_file = open(p, logflags, 0600)) < 0) {
2274 f->f_type = F_UNUSED;
2279 f->f_flags |= FFLAG_SYNC;
2280 if (isatty(f->f_file)) {
2281 if (strcmp(p, ctty) == 0)
2282 f->f_type = F_CONSOLE;
2285 (void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
2286 sizeof(f->fu_fname));
2288 (void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
2295 (void)strlcpy(f->fu_pipe_pname, p + 1,
2296 sizeof(f->fu_pipe_pname));
2305 for (i = 0; i < MAXUNAMES && *p; i++) {
2306 for (q = p; *q && *q != ','; )
2308 (void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
2309 if ((q - p) >= MAXLOGNAME)
2310 f->fu_uname[i][MAXLOGNAME - 1] = '\0';
2312 f->fu_uname[i][q - p] = '\0';
2313 while (*q == ',' || *q == ' ')
2317 f->f_type = F_USERS;
2325 * Decode a symbolic name to a numeric value
2328 decode(const char *name, const CODE *codetab)
2334 return (atoi(name));
2336 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2338 *p = tolower(*name);
2343 for (c = codetab; c->c_name; c++)
2344 if (!strcmp(buf, c->c_name))
2354 struct deadq_entry *dq, *dq0;
2356 now = time((time_t *)NULL);
2357 MarkSeq += TIMERINTVL;
2358 if (MarkSeq >= MarkInterval) {
2359 logmsg(LOG_INFO, NULL, "-- MARK --", LocalHostName, MARK);
2363 STAILQ_FOREACH(f, &fhead, next) {
2364 if (f->f_prevcount && now >= REPEATTIME(f)) {
2365 dprintf("flush %s: repeated %d times, %d sec.\n",
2366 TypeNames[f->f_type], f->f_prevcount,
2367 repeatinterval[f->f_repeatcount]);
2368 fprintlog(f, 0, (char *)NULL);
2373 /* Walk the dead queue, and see if we should signal somebody. */
2374 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
2375 switch (dq->dq_timeout) {
2377 /* Already signalled once, try harder now. */
2378 if (kill(dq->dq_pid, SIGKILL) != 0)
2379 (void)deadq_remove(dq);
2384 * Timed out on dead queue, send terminate
2385 * signal. Note that we leave the removal
2386 * from the dead queue to reapchild(), which
2387 * will also log the event (unless the process
2388 * didn't even really exist, in case we simply
2389 * drop it from the dead queue).
2391 if (kill(dq->dq_pid, SIGTERM) != 0)
2392 (void)deadq_remove(dq);
2401 (void)alarm(TIMERINTVL);
2405 * fork off and become a daemon, but wait for the child to come online
2406 * before returning to the parent, or we get disk thrashing at boot etc.
2407 * Set a timer so we don't hang forever if it wedges.
2410 waitdaemon(int maxwait)
2414 pid_t pid, childpid;
2416 switch (childpid = fork()) {
2422 signal(SIGALRM, timedout);
2424 while ((pid = wait3(&status, 0, NULL)) != -1) {
2425 if (WIFEXITED(status))
2426 errx(1, "child pid %d exited with return code %d",
2427 pid, WEXITSTATUS(status));
2428 if (WIFSIGNALED(status))
2429 errx(1, "child pid %d exited on signal %d%s",
2430 pid, WTERMSIG(status),
2431 WCOREDUMP(status) ? " (core dumped)" :
2433 if (pid == childpid) /* it's gone... */
2443 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2444 (void)dup2(fd, STDIN_FILENO);
2445 (void)dup2(fd, STDOUT_FILENO);
2446 (void)dup2(fd, STDERR_FILENO);
2447 if (fd > STDERR_FILENO)
2454 * We get a SIGALRM from the child when it's running and finished doing it's
2455 * fsync()'s or O_SYNC writes for all the boot messages.
2457 * We also get a signal from the kernel if the timer expires, so check to
2458 * see what happened.
2461 timedout(int sig __unused)
2465 signal(SIGALRM, SIG_DFL);
2467 errx(1, "timed out waiting for child");
2473 * Add `s' to the list of allowable peer addresses to accept messages
2476 * `s' is a string in the form:
2478 * [*]domainname[:{servicename|portnumber|*}]
2482 * netaddr/maskbits[:{servicename|portnumber|*}]
2484 * Returns -1 on error, 0 if the argument was valid.
2489 #if defined(INET) || defined(INET6)
2491 struct allowedpeer *ap;
2494 struct addrinfo hints, *res = NULL;
2496 in_addr_t *addrp, *maskp;
2499 uint32_t *addr6p, *mask6p;
2501 char ip[NI_MAXHOST];
2503 ap = calloc(1, sizeof(*ap));
2505 err(1, "malloc failed");
2508 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2511 if ((cp1 = strrchr(cp1, ':'))) {
2512 /* service/port provided */
2514 if (strlen(cp1) == 1 && *cp1 == '*')
2515 /* any port allowed */
2517 else if ((se = getservbyname(cp1, "udp"))) {
2518 ap->port = ntohs(se->s_port);
2520 ap->port = strtol(cp1, &cp2, 0);
2521 /* port not numeric */
2526 if ((se = getservbyname("syslog", "udp")))
2527 ap->port = ntohs(se->s_port);
2529 /* sanity, should not happen */
2533 if ((cp1 = strchr(s, '/')) != NULL &&
2534 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2536 if ((masklen = atoi(cp1 + 1)) < 0)
2541 cp2 = s + strlen(s) - 1;
2552 hints = (struct addrinfo){
2553 .ai_family = PF_UNSPEC,
2554 .ai_socktype = SOCK_DGRAM,
2555 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
2557 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2559 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
2560 ap->a_mask = (struct sockaddr_storage){
2561 .ss_family = res->ai_family,
2562 .ss_len = res->ai_addrlen
2564 switch (res->ai_family) {
2567 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
2568 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
2570 /* use default netmask */
2571 if (IN_CLASSA(ntohl(*addrp)))
2572 *maskp = htonl(IN_CLASSA_NET);
2573 else if (IN_CLASSB(ntohl(*addrp)))
2574 *maskp = htonl(IN_CLASSB_NET);
2576 *maskp = htonl(IN_CLASSC_NET);
2577 } else if (masklen == 0) {
2579 } else if (masklen <= 32) {
2580 /* convert masklen to netmask */
2581 *maskp = htonl(~((1 << (32 - masklen)) - 1));
2585 /* Lose any host bits in the network number. */
2596 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
2597 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
2598 /* convert masklen to netmask */
2599 while (masklen > 0) {
2602 htonl(~(0xffffffff >> masklen));
2606 *mask6p++ = 0xffffffff;
2618 /* arg `s' is domain name */
2630 STAILQ_INSERT_TAIL(&aphead, ap, next);
2633 printf("allowaddr: rule ");
2634 if (ap->isnumeric) {
2635 printf("numeric, ");
2636 getnameinfo(sstosa(&ap->a_addr),
2637 (sstosa(&ap->a_addr))->sa_len,
2638 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2639 printf("addr = %s, ", ip);
2640 getnameinfo(sstosa(&ap->a_mask),
2641 (sstosa(&ap->a_mask))->sa_len,
2642 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2643 printf("mask = %s; ", ip);
2645 printf("domainname = %s; ", ap->a_name);
2647 printf("port = %d\n", ap->port);
2660 * Validate that the remote peer has permission to log to us.
2663 validate(struct sockaddr *sa, const char *hname)
2666 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2667 struct allowedpeer *ap;
2669 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2672 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2674 struct addrinfo hints, *res;
2678 STAILQ_FOREACH(ap, &aphead, next) {
2681 dprintf("# of validation rule: %d\n", num);
2683 /* traditional behaviour, allow everything */
2686 (void)strlcpy(name, hname, sizeof(name));
2687 hints = (struct addrinfo){
2688 .ai_family = PF_UNSPEC,
2689 .ai_socktype = SOCK_DGRAM,
2690 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
2692 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2694 else if (strchr(name, '.') == NULL) {
2695 strlcat(name, ".", sizeof name);
2696 strlcat(name, LocalDomain, sizeof name);
2698 if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
2699 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2700 return (0); /* for safety, should not occur */
2701 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2705 /* now, walk down the list */
2707 STAILQ_FOREACH(ap, &aphead, next) {
2709 if (ap->port != 0 && ap->port != sport) {
2710 dprintf("rejected in rule %d due to port mismatch.\n",
2715 if (ap->isnumeric) {
2716 if (ap->a_addr.ss_family != sa->sa_family) {
2717 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2721 else if (ap->a_addr.ss_family == AF_INET) {
2723 a4p = satosin(&ap->a_addr);
2724 m4p = satosin(&ap->a_mask);
2725 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2726 != a4p->sin_addr.s_addr) {
2727 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2733 else if (ap->a_addr.ss_family == AF_INET6) {
2734 sin6 = satosin6(sa);
2735 a6p = satosin6(&ap->a_addr);
2736 m6p = satosin6(&ap->a_mask);
2737 if (a6p->sin6_scope_id != 0 &&
2738 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2739 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2742 if (IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
2743 &a6p->sin6_addr, &m6p->sin6_addr) != 0) {
2744 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2752 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
2754 dprintf("rejected in rule %d due to name "
2759 dprintf("accepted in rule %d.\n", i);
2760 return (1); /* hooray! */
2766 * Fairly similar to popen(3), but returns an open descriptor, as
2767 * opposed to a FILE *.
2770 p_open(const char *prog, pid_t *rpid)
2772 int pfd[2], nulldesc;
2774 char *argv[4]; /* sh -c cmd NULL */
2777 if (pipe(pfd) == -1)
2779 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2780 /* we are royally screwed anyway */
2783 switch ((pid = fork())) {
2789 (void)setsid(); /* Avoid catching SIGHUPs. */
2790 argv[0] = strdup("sh");
2791 argv[1] = strdup("-c");
2792 argv[2] = strdup(prog);
2794 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2801 /* Restore signals marked as SIG_IGN. */
2802 (void)signal(SIGINT, SIG_DFL);
2803 (void)signal(SIGQUIT, SIG_DFL);
2804 (void)signal(SIGPIPE, SIG_DFL);
2806 dup2(pfd[0], STDIN_FILENO);
2807 dup2(nulldesc, STDOUT_FILENO);
2808 dup2(nulldesc, STDERR_FILENO);
2809 closefrom(STDERR_FILENO + 1);
2811 (void)execvp(_PATH_BSHELL, argv);
2817 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2818 * supposed to get an EWOULDBLOCK on writev(2), which is
2819 * caught by the logic above anyway, which will in turn close
2820 * the pipe, and fork a new logging subprocess if necessary.
2821 * The stale subprocess will be killed some time later unless
2822 * it terminated itself due to closing its input pipe (so we
2823 * get rid of really dead puppies).
2825 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2827 (void)snprintf(errmsg, sizeof errmsg,
2828 "Warning: cannot change pipe to PID %d to "
2829 "non-blocking behaviour.",
2838 deadq_enter(pid_t pid, const char *name)
2840 struct deadq_entry *dq;
2846 * Be paranoid, if we can't signal the process, don't enter it
2847 * into the dead queue (perhaps it's already dead). If possible,
2848 * we try to fetch and log the child's status.
2850 if (kill(pid, 0) != 0) {
2851 if (waitpid(pid, &status, WNOHANG) > 0)
2852 log_deadchild(pid, status, name);
2856 dq = malloc(sizeof(*dq));
2861 *dq = (struct deadq_entry){
2863 .dq_timeout = DQ_TIMO_INIT
2865 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
2869 deadq_remove(struct deadq_entry *dq)
2872 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
2881 deadq_removebypid(pid_t pid)
2883 struct deadq_entry *dq;
2885 TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
2886 if (dq->dq_pid == pid)
2889 return (deadq_remove(dq));
2893 log_deadchild(pid_t pid, int status, const char *name)
2899 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2900 if (WIFSIGNALED(status)) {
2901 reason = "due to signal";
2902 code = WTERMSIG(status);
2904 reason = "with status";
2905 code = WEXITSTATUS(status);
2909 (void)snprintf(buf, sizeof buf,
2910 "Logging subprocess %d (%s) exited %s %d.",
2911 pid, name, reason, code);
2916 socksetup(struct peer *pe)
2918 struct addrinfo hints, *res, *res0;
2921 int (*sl_recv)(struct socklist *);
2923 * We have to handle this case for backwards compatibility:
2924 * If there are two (or more) colons but no '[' and ']',
2925 * assume this is an inet6 address without a service.
2927 if (pe->pe_name != NULL) {
2929 if (pe->pe_name[0] == '[' &&
2930 (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
2931 pe->pe_name = &pe->pe_name[1];
2933 if (cp[1] == ':' && cp[2] != '\0')
2934 pe->pe_serv = cp + 2;
2937 cp = strchr(pe->pe_name, ':');
2938 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2941 pe->pe_serv = cp + 1;
2942 if (cp == pe->pe_name)
2949 hints = (struct addrinfo){
2950 .ai_family = AF_UNSPEC,
2951 .ai_socktype = SOCK_DGRAM,
2952 .ai_flags = AI_PASSIVE
2954 if (pe->pe_name != NULL)
2955 dprintf("Trying peer: %s\n", pe->pe_name);
2956 if (pe->pe_serv == NULL)
2957 pe->pe_serv = "syslog";
2958 error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
2962 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
2963 pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
2964 gai_strerror(error));
2967 logerror(gai_strerror(error));
2973 for (res = res0; res != NULL; res = res->ai_next) {
2976 if (res->ai_family != AF_LOCAL &&
2978 /* Only AF_LOCAL in secure mode. */
2981 if (family != AF_UNSPEC &&
2982 res->ai_family != AF_LOCAL && res->ai_family != family)
2985 s = socket(res->ai_family, res->ai_socktype,
2993 if (res->ai_family == AF_INET6) {
2994 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
2995 &(int){1}, sizeof(int)) < 0) {
2996 logerror("setsockopt(IPV6_V6ONLY)");
3003 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
3004 &(int){1}, sizeof(int)) < 0) {
3005 logerror("setsockopt(SO_REUSEADDR)");
3012 * Bind INET and UNIX-domain sockets.
3014 * A UNIX-domain socket is always bound to a pathname
3015 * regardless of -N flag.
3017 * For INET sockets, RFC 3164 recommends that client
3018 * side message should come from the privileged syslogd port.
3020 * If the system administrator chooses not to obey
3021 * this, we can skip the bind() step so that the
3022 * system will choose a port for us.
3024 if (res->ai_family == AF_LOCAL)
3025 unlink(pe->pe_name);
3026 if (res->ai_family == AF_LOCAL ||
3027 NoBind == 0 || pe->pe_name != NULL) {
3028 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
3034 if (res->ai_family == AF_LOCAL ||
3038 if (res->ai_family == AF_LOCAL &&
3039 chmod(pe->pe_name, pe->pe_mode) < 0) {
3040 dprintf("chmod %s: %s\n", pe->pe_name,
3046 dprintf("new socket fd is %d\n", s);
3047 if (res->ai_socktype != SOCK_DGRAM) {
3050 sl_recv = socklist_recv_sock;
3051 #if defined(INET) || defined(INET6)
3052 if (SecureMode && (res->ai_family == AF_INET ||
3053 res->ai_family == AF_INET6)) {
3054 dprintf("shutdown\n");
3055 /* Forbid communication in secure mode. */
3056 if (shutdown(s, SHUT_RD) < 0 &&
3057 errno != ENOTCONN) {
3058 logerror("shutdown");
3065 dprintf("listening on socket\n");
3066 dprintf("sending on socket\n");
3067 addsock(res->ai_addr, res->ai_addrlen,
3080 increase_rcvbuf(int fd)
3084 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3085 &(socklen_t){sizeof(len)}) == 0) {
3086 if (len < RCVBUF_MINSIZE) {
3087 len = RCVBUF_MINSIZE;
3088 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));