2 * Copyright (c) 1983, 1988, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
33 The Regents of the University of California. All rights reserved.\n";
38 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
46 * syslogd -- log system messages
48 * This program implements a system log. It takes a series of lines.
49 * Each line may have a priority, signified as "<n>" as
50 * the first characters of the line. If this is
51 * not present, a default priority is used.
53 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
54 * cause it to reread its configuration file.
58 * MAXLINE -- the maximum line length that can be handled.
59 * DEFUPRI -- the default priority for user messages
60 * DEFSPRI -- the default priority for kernel messages
63 * extensive changes by Ralph Campbell
64 * more extensive changes by Eric Allman (again)
65 * Extension to log by program name as well as facility and priority
67 * -u and -v by Harlan Stenn.
68 * Priority comparison code by Harlan Stenn.
71 /* Maximum number of characters in time of last occurrence */
73 #define MAXLINE 1024 /* maximum line length */
74 #define MAXSVLINE MAXLINE /* maximum saved line length */
75 #define DEFUPRI (LOG_USER|LOG_NOTICE)
76 #define DEFSPRI (LOG_KERN|LOG_CRIT)
77 #define TIMERINTVL 30 /* interval for checking flush, mark */
78 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
79 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
81 #include <sys/param.h>
82 #include <sys/ioctl.h>
84 #include <sys/queue.h>
85 #include <sys/resource.h>
86 #include <sys/socket.h>
88 #include <sys/syslimits.h>
94 #if defined(INET) || defined(INET6)
95 #include <netinet/in.h>
96 #include <arpa/inet.h>
113 #include <sysexits.h>
117 #include "pathnames.h"
121 #include <sys/syslog.h>
123 static const char *ConfFile = _PATH_LOGCONF;
124 static const char *PidFile = _PATH_LOGPID;
125 static const char ctty[] = _PATH_CONSOLE;
126 static const char include_str[] = "include";
127 static const char include_ext[] = ".conf";
129 #define dprintf if (Debug) printf
131 #define MAXUNAMES 20 /* maximum number of user names */
133 #define sstosa(ss) ((struct sockaddr *)(ss))
135 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss))
136 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa))
139 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss))
140 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa))
141 #define s6_addr32 __u6_addr.__u6_addr32
142 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \
143 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
144 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
145 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
146 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
149 * List of peers and sockets for binding.
155 STAILQ_ENTRY(peer) next;
157 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
160 struct sockaddr_storage sl_ss;
162 struct peer *sl_peer;
163 int (*sl_recv)(struct socklist *);
164 STAILQ_ENTRY(socklist) next;
166 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
172 #define IGN_CONS 0x001 /* don't print on console */
173 #define SYNC_FILE 0x002 /* do fsync on file after printing */
174 #define ADDDATE 0x004 /* add a date to the message */
175 #define MARK 0x008 /* this message is a mark */
176 #define ISKERNEL 0x010 /* kernel generated message */
179 * This structure represents the files that will have log
181 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
182 * or if f_type if F_PIPE and f_pid > 0.
186 STAILQ_ENTRY(filed) next; /* next in linked list */
187 short f_type; /* entry type, see below */
188 short f_file; /* file descriptor */
189 time_t f_time; /* time this was last written */
190 char *f_host; /* host from which to recd. */
191 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
192 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
196 char *f_program; /* program this applies to */
198 char f_uname[MAXUNAMES][MAXLOGNAME];
200 char f_hname[MAXHOSTNAMELEN];
201 struct addrinfo *f_addr;
203 } f_forw; /* forwarding address */
204 char f_fname[MAXPATHLEN];
206 char f_pname[MAXPATHLEN];
210 #define fu_uname f_un.f_uname
211 #define fu_forw_hname f_un.f_forw.f_hname
212 #define fu_forw_addr f_un.f_forw.f_addr
213 #define fu_fname f_un.f_fname
214 #define fu_pipe_pname f_un.f_pipe.f_pname
215 #define fu_pipe_pid f_un.f_pipe.f_pid
216 char f_prevline[MAXSVLINE]; /* last message logged */
217 char f_lasttime[MAXDATELEN]; /* time of last occurrence */
218 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
219 int f_prevpri; /* pri of f_prevline */
220 int f_prevlen; /* length of f_prevline */
221 int f_prevcount; /* repetition cnt of prevline */
222 u_int f_repeatcount; /* number of "repeated" msgs */
223 int f_flags; /* file-specific flags */
224 #define FFLAG_SYNC 0x01
225 #define FFLAG_NEEDSYNC 0x02
229 * Queue of about-to-be dead processes we should watch out for.
234 TAILQ_ENTRY(deadq_entry) dq_entries;
236 static TAILQ_HEAD(, deadq_entry) deadq_head =
237 TAILQ_HEAD_INITIALIZER(deadq_head);
240 * The timeout to apply to processes waiting on the dead queue. Unit
241 * of measure is `mark intervals', i.e. 20 minutes by default.
242 * Processes on the dead queue will be terminated after that time.
245 #define DQ_TIMO_INIT 2
248 * Struct to hold records of network addresses that are allowed to log
256 struct sockaddr_storage addr;
257 struct sockaddr_storage mask;
261 #define a_addr u.numeric.addr
262 #define a_mask u.numeric.mask
263 #define a_name u.name
264 STAILQ_ENTRY(allowedpeer) next;
266 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
270 * Intervals at which we flush out "message repeated" messages,
271 * in seconds after previous message is logged. After each flush,
272 * we move to the next interval until we reach the largest.
274 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
275 #define MAXREPEAT (nitems(repeatinterval) - 1)
276 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
277 #define BACKOFF(f) do { \
278 if (++(f)->f_repeatcount > MAXREPEAT) \
279 (f)->f_repeatcount = MAXREPEAT; \
282 /* values for f_type */
283 #define F_UNUSED 0 /* unused entry */
284 #define F_FILE 1 /* regular file */
285 #define F_TTY 2 /* terminal */
286 #define F_CONSOLE 3 /* console terminal */
287 #define F_FORW 4 /* remote machine */
288 #define F_USERS 5 /* list of users */
289 #define F_WALL 6 /* everyone logged on */
290 #define F_PIPE 7 /* pipe to program */
292 static const char *TypeNames[] = {
293 "UNUSED", "FILE", "TTY", "CONSOLE",
294 "FORW", "USERS", "WALL", "PIPE"
297 static STAILQ_HEAD(, filed) fhead =
298 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */
299 static struct filed consfile; /* Console */
301 static int Debug; /* debug flag */
302 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
303 static int resolve = 1; /* resolve hostname */
304 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
305 static const char *LocalDomain; /* our local domain name */
306 static int Initialized; /* set when we have initialized ourselves */
307 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
308 static int MarkSeq; /* mark sequence number */
309 static int NoBind; /* don't bind() as suggested by RFC 3164 */
310 static int SecureMode; /* when true, receive only unix domain socks */
312 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
314 static int family = PF_INET; /* protocol family (IPv4 only) */
316 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
317 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
318 static int use_bootfile; /* log entire bootfile for every kern msg */
319 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
320 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
322 static char bootfile[MAXLINE+1]; /* booted kernel file */
324 static int RemoteAddDate; /* Always set the date on remote messages */
326 static int UniquePriority; /* Only log specified priority? */
327 static int LogFacPri; /* Put facility and priority in log message: */
328 /* 0=no, 1=numeric, 2=names */
329 static int KeepKernFac; /* Keep remotely logged kernel facility */
330 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
331 static struct pidfh *pfh;
332 static int sigpipe[2]; /* Pipe to catch a signal during select(). */
334 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
336 static int allowaddr(char *);
337 static int addfile(struct filed *);
338 static int addpeer(struct peer *);
339 static int addsock(struct sockaddr *, socklen_t, struct socklist *);
340 static struct filed *cfline(const char *, const char *, const char *);
341 static const char *cvthname(struct sockaddr *);
342 static void deadq_enter(pid_t, const char *);
343 static int deadq_remove(struct deadq_entry *);
344 static int deadq_removebypid(pid_t);
345 static int decode(const char *, const CODE *);
346 static void die(int) __dead2;
347 static void dodie(int);
348 static void dofsync(void);
349 static void domark(int);
350 static void fprintlog(struct filed *, int, const char *);
351 static void init(int);
352 static void logerror(const char *);
353 static void logmsg(int, const char *, const char *, int);
354 static void log_deadchild(pid_t, int, const char *);
355 static void markit(void);
356 static int socksetup(struct peer *);
357 static int socklist_recv_file(struct socklist *);
358 static int socklist_recv_sock(struct socklist *);
359 static int socklist_recv_signal(struct socklist *);
360 static void sighandler(int);
361 static int skip_message(const char *, const char *, int);
362 static void printline(const char *, char *, int);
363 static void printsys(char *);
364 static int p_open(const char *, pid_t *);
365 static void reapchild(int);
366 static const char *ttymsg_check(struct iovec *, int, char *, int);
367 static void usage(void);
368 static int validate(struct sockaddr *, const char *);
369 static void unmapped(struct sockaddr *);
370 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
371 static int waitdaemon(int);
372 static void timedout(int);
373 static void increase_rcvbuf(int);
376 close_filed(struct filed *f)
379 if (f == NULL || f->f_file == -1)
387 f->f_type = F_UNUSED;
393 (void)close(f->f_file);
398 addfile(struct filed *f0)
402 f = calloc(1, sizeof(*f));
404 err(1, "malloc failed");
406 STAILQ_INSERT_TAIL(&fhead, f, next);
412 addpeer(struct peer *pe0)
416 pe = calloc(1, sizeof(*pe));
418 err(1, "malloc failed");
420 STAILQ_INSERT_TAIL(&pqueue, pe, next);
426 addsock(struct sockaddr *sa, socklen_t sa_len, struct socklist *sl0)
430 sl = calloc(1, sizeof(*sl));
432 err(1, "malloc failed");
434 if (sa != NULL && sa_len > 0)
435 memcpy(&sl->sl_ss, sa, sa_len);
436 STAILQ_INSERT_TAIL(&shead, sl, next);
442 main(int argc, char *argv[])
444 int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
446 struct timeval tv, *tvp;
449 pid_t ppid = 1, spid;
452 if (madvise(NULL, 0, MADV_PROTECT) != 0)
453 dprintf("madvise() failed: %s\n", strerror(errno));
455 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:Fkl:m:nNop:P:sS:Tuv"))
474 case 'a': /* allow specific network addresses only */
475 if (allowaddr(optarg) == -1)
480 p = strchr(optarg, ']');
482 p = strchr(p + 1, ':');
484 p = strchr(optarg, ':');
485 if (p != NULL && strchr(p + 1, ':') != NULL)
486 p = NULL; /* backward compatibility */
489 /* A hostname or filename only. */
490 addpeer(&(struct peer){
495 /* The case of "name:service". */
497 addpeer(&(struct peer){
499 .pe_name = (strlen(optarg) == 0) ?
510 case 'd': /* debug */
513 case 'f': /* configuration file */
516 case 'F': /* run in foreground instead of daemon */
519 case 'k': /* keep remote kern fac */
532 else if (ch == 'p') {
535 } else if (ch == 'S') {
536 mode = S_IRUSR | S_IWUSR;
539 if (optarg[0] == '/')
541 else if ((name = strchr(optarg, ':')) != NULL) {
544 errx(1, "socket name must be absolute "
546 if (isdigit(*optarg)) {
547 perml = strtol(optarg, &ep, 8);
548 if (*ep || perml < 0 ||
549 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
550 errx(1, "invalid mode %s, exiting",
552 mode = (mode_t )perml;
554 errx(1, "invalid mode %s, exiting",
557 errx(1, "invalid filename %s, exiting",
559 addpeer(&(struct peer){
565 case 'm': /* mark interval */
566 MarkInterval = atoi(optarg) * 60;
578 case 'P': /* path for alt. PID */
581 case 's': /* no network mode */
587 case 'u': /* only log specified priority */
590 case 'v': /* log facility and priority */
596 if ((argc -= optind) != 0)
599 /* Pipe to catch a signal during select(). */
600 s = pipe2(sigpipe, O_CLOEXEC);
602 err(1, "cannot open a pipe for signals");
604 addsock(NULL, 0, &(struct socklist){
605 .sl_socket = sigpipe[0],
606 .sl_recv = socklist_recv_signal
610 /* Listen by default: /dev/klog. */
611 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
613 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
615 addsock(NULL, 0, &(struct socklist){
617 .sl_recv = socklist_recv_file,
620 /* Listen by default: *:514 if no -b flag. */
622 addpeer(&(struct peer){
625 /* Listen by default: /var/run/log if no -p flag. */
627 addpeer(&(struct peer){
628 .pe_name = _PATH_LOG,
629 .pe_mode = DEFFILEMODE,
631 /* Listen by default: /var/run/logpriv if no -S flag. */
633 addpeer(&(struct peer){
634 .pe_name = _PATH_LOG_PRIV,
635 .pe_mode = S_IRUSR | S_IWUSR,
637 STAILQ_FOREACH(pe, &pqueue, next)
640 pfh = pidfile_open(PidFile, 0600, &spid);
643 errx(1, "syslogd already running, pid: %d", spid);
644 warn("cannot open pid file");
647 if ((!Foreground) && (!Debug)) {
648 ppid = waitdaemon(30);
650 warn("could not become daemon");
657 consfile.f_type = F_CONSOLE;
658 (void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
659 sizeof(consfile.fu_fname));
660 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
661 (void)signal(SIGTERM, dodie);
662 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
663 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
664 (void)signal(SIGHUP, sighandler);
665 (void)signal(SIGCHLD, sighandler);
666 (void)signal(SIGALRM, domark);
667 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
668 (void)alarm(TIMERINTVL);
670 /* tuck my process id away */
673 dprintf("off & running....\n");
676 tv.tv_sec = tv.tv_usec = 0;
678 STAILQ_FOREACH(sl, &shead, next) {
679 if (sl->sl_socket > fdsrmax)
680 fdsrmax = sl->sl_socket;
682 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
685 errx(1, "calloc fd_set");
688 if (Initialized == 0)
690 else if (WantInitialize)
691 init(WantInitialize);
693 reapchild(WantReapchild);
701 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
704 STAILQ_FOREACH(sl, &shead, next) {
705 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
706 FD_SET(sl->sl_socket, fdsr);
708 i = select(fdsrmax + 1, fdsr, NULL, NULL,
709 needdofsync ? &tv : tvp);
725 STAILQ_FOREACH(sl, &shead, next) {
726 if (FD_ISSET(sl->sl_socket, fdsr))
734 socklist_recv_signal(struct socklist *sl __unused)
739 if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
740 logerror("ioctl(FIONREAD)");
741 err(1, "signal pipe read failed");
743 nsig = i / sizeof(signo);
744 dprintf("# of received signals = %d\n", nsig);
745 for (i = 0; i < nsig; i++) {
746 len = read(sigpipe[0], &signo, sizeof(signo));
747 if (len != sizeof(signo)) {
748 logerror("signal pipe read failed");
749 err(1, "signal pipe read failed");
751 dprintf("Received signal: %d from fd=%d\n", signo,
766 socklist_recv_sock(struct socklist *sl)
768 struct sockaddr_storage ss;
769 struct sockaddr *sa = (struct sockaddr *)&ss;
772 char line[MAXLINE + 1];
776 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
777 dprintf("received sa_len = %d\n", sslen);
782 logerror("recvfrom");
785 /* Received valid data. */
787 if (sl->sl_ss.ss_family == AF_LOCAL) {
788 hname = LocalHostName;
791 hname = cvthname(sa);
793 if (validate(sa, hname) == 0)
795 date = RemoteAddDate ? ADDDATE : 0;
798 printline(hname, line, date);
800 dprintf("Invalid msg from %s was ignored.", hname);
806 unmapped(struct sockaddr *sa)
808 #if defined(INET) && defined(INET6)
809 struct sockaddr_in6 *sin6;
810 struct sockaddr_in sin;
813 sa->sa_family != AF_INET6 ||
814 sa->sa_len != sizeof(*sin6))
817 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
819 sin = (struct sockaddr_in){
820 .sin_family = AF_INET,
821 .sin_len = sizeof(sin),
822 .sin_port = sin6->sin6_port
824 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
825 sizeof(sin.sin_addr));
826 memcpy(sa, &sin, sizeof(sin));
837 fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
838 "usage: syslogd [-468ACcdFknosTuv] [-a allowed_peer]",
839 " [-b bind_address] [-f config_file]",
840 " [-l [mode:]path] [-m mark_interval]",
841 " [-P pid_file] [-p log_socket]",
842 " [-S logpriv_socket]");
847 * Take a raw input line, decode the message, and print the message
848 * on the appropriate log files.
851 printline(const char *hname, char *msg, int flags)
856 char line[MAXLINE + 1];
858 /* test for special codes */
863 n = strtol(p + 1, &q, 10);
864 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
869 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
873 * Don't allow users to log kernel messages.
874 * NOTE: since LOG_KERN == 0 this will also match
875 * messages with no facility specified.
877 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
878 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
882 while ((c = (unsigned char)*p++) != '\0' &&
883 q < &line[sizeof(line) - 4]) {
884 if (mask_C1 && (c & 0x80) && c < 0xA0) {
889 if (isascii(c) && iscntrl(c)) {
892 } else if (c == '\t') {
904 logmsg(pri, line, hname, flags);
908 * Read /dev/klog while data are available, split into lines.
911 socklist_recv_file(struct socklist *sl)
913 char *p, *q, line[MAXLINE + 1];
918 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
920 line[i + len] = '\0';
922 if (i < 0 && errno != EINTR && errno != EAGAIN) {
924 close(sl->sl_socket);
930 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
935 if (len >= MAXLINE - 1) {
940 memmove(line, p, len + 1);
949 * Take a raw input line from /dev/klog, format similar to syslog().
956 int flags, isprintf, pri;
958 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
964 n = strtol(p + 1, &q, 10);
965 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
972 * Kernel printf's and LOG_CONSOLE messages have been displayed
973 * on the console already.
975 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
977 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
979 logmsg(pri, p, LocalHostName, flags);
985 * Match a program or host name against a specification.
986 * Return a non-0 value if the message must be ignored
987 * based on the specification.
990 skip_message(const char *name, const char *spec, int checkcase)
995 /* Behaviour on explicit match */
1010 s = strstr (spec, name);
1012 s = strcasestr (spec, name);
1015 prev = (s == spec ? ',' : *(s - 1));
1016 next = *(s + strlen (name));
1018 if (prev == ',' && (next == '\0' || next == ','))
1019 /* Explicit match: skip iff the spec is an
1024 /* No explicit match for this name: skip the message iff
1025 the spec is an inclusive one. */
1030 * Log a message to the appropriate log files, users, etc. based on
1034 logmsg(int pri, const char *msg, const char *from, int flags)
1037 int i, fac, msglen, prilev;
1038 const char *timestamp;
1039 char prog[NAME_MAX+1];
1040 char buf[MAXLINE+1];
1042 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1043 pri, flags, from, msg);
1046 * Check to see if msg looks non-standard.
1048 msglen = strlen(msg);
1049 if (msglen < MAXDATELEN || msg[3] != ' ' || msg[6] != ' ' ||
1050 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
1054 if (flags & ADDDATE) {
1055 timestamp = ctime(&now) + 4;
1059 msglen -= MAXDATELEN;
1062 /* skip leading blanks */
1063 while (isspace(*msg)) {
1068 /* extract facility and priority level */
1070 fac = LOG_NFACILITIES;
1074 /* Check maximum facility number. */
1075 if (fac > LOG_NFACILITIES)
1078 prilev = LOG_PRI(pri);
1080 /* extract program name */
1081 for (i = 0; i < NAME_MAX; i++) {
1082 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
1083 msg[i] == '/' || isspace(msg[i]))
1089 /* add kernel prefix for kernel messages */
1090 if (flags & ISKERNEL) {
1091 snprintf(buf, sizeof(buf), "%s: %s",
1092 use_bootfile ? bootfile : "kernel", msg);
1094 msglen = strlen(buf);
1097 /* log the message to the particular outputs */
1101 * Open in non-blocking mode to avoid hangs during open
1102 * and close(waiting for the port to drain).
1104 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1106 if (f->f_file >= 0) {
1107 (void)strlcpy(f->f_lasttime, timestamp,
1108 sizeof(f->f_lasttime));
1109 fprintlog(f, flags, msg);
1115 STAILQ_FOREACH(f, &fhead, next) {
1116 /* skip messages that are incorrect priority */
1117 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1118 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1119 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1121 || f->f_pmask[fac] == INTERNAL_NOPRI)
1124 /* skip messages with the incorrect hostname */
1125 if (skip_message(from, f->f_host, 0))
1128 /* skip messages with the incorrect program name */
1129 if (skip_message(prog, f->f_program, 1))
1132 /* skip message to console if it has already been printed */
1133 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1136 /* don't output marks to recently written files */
1137 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1141 * suppress duplicate lines to this file
1143 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1144 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1145 !strcmp(msg, f->f_prevline) &&
1146 !strcasecmp(from, f->f_prevhost)) {
1147 (void)strlcpy(f->f_lasttime, timestamp,
1148 sizeof(f->f_lasttime));
1150 dprintf("msg repeated %d times, %ld sec of %d\n",
1151 f->f_prevcount, (long)(now - f->f_time),
1152 repeatinterval[f->f_repeatcount]);
1154 * If domark would have logged this by now,
1155 * flush it now (so we don't hold isolated messages),
1156 * but back off so we'll flush less often
1159 if (now > REPEATTIME(f)) {
1160 fprintlog(f, flags, (char *)NULL);
1164 /* new line, save it */
1166 fprintlog(f, 0, (char *)NULL);
1167 f->f_repeatcount = 0;
1169 (void)strlcpy(f->f_lasttime, timestamp,
1170 sizeof(f->f_lasttime));
1171 (void)strlcpy(f->f_prevhost, from,
1172 sizeof(f->f_prevhost));
1173 if (msglen < MAXSVLINE) {
1174 f->f_prevlen = msglen;
1175 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1176 fprintlog(f, flags, (char *)NULL);
1178 f->f_prevline[0] = 0;
1180 fprintlog(f, flags, msg);
1191 STAILQ_FOREACH(f, &fhead, next) {
1192 if ((f->f_type == F_FILE) &&
1193 (f->f_flags & FFLAG_NEEDSYNC)) {
1194 f->f_flags &= ~FFLAG_NEEDSYNC;
1195 (void)fsync(f->f_file);
1202 fprintlog(struct filed *f, int flags, const char *msg)
1204 struct iovec iov[IOV_SIZE];
1207 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1208 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1211 if (f->f_type == F_WALL) {
1212 /* The time displayed is not synchornized with the other log
1213 * destinations (like messages). Following fragment was using
1214 * ctime(&now), which was updating the time every 30 sec.
1215 * With f_lasttime, time is synchronized correctly.
1217 iov[0] = (struct iovec){
1218 .iov_base = greetings,
1219 .iov_len = snprintf(greetings, sizeof(greetings),
1220 "\r\n\7Message from syslogd@%s "
1222 f->f_prevhost, f->f_lasttime)
1224 if (iov[0].iov_len >= sizeof(greetings))
1225 iov[0].iov_len = sizeof(greetings) - 1;
1226 iov[1] = (struct iovec){
1231 iov[0] = (struct iovec){
1232 .iov_base = f->f_lasttime,
1233 .iov_len = strlen(f->f_lasttime)
1235 iov[1] = (struct iovec){
1242 static char fp_buf[30]; /* Hollow laugh */
1243 int fac = f->f_prevpri & LOG_FACMASK;
1244 int pri = LOG_PRI(f->f_prevpri);
1245 const char *f_s = NULL;
1246 char f_n[5]; /* Hollow laugh */
1247 const char *p_s = NULL;
1248 char p_n[5]; /* Hollow laugh */
1250 if (LogFacPri > 1) {
1253 for (c = facilitynames; c->c_name; c++) {
1254 if (c->c_val == fac) {
1259 for (c = prioritynames; c->c_name; c++) {
1260 if (c->c_val == pri) {
1267 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1271 snprintf(p_n, sizeof p_n, "%d", pri);
1274 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1275 iov[2] = (struct iovec){
1277 .iov_len = strlen(fp_buf)
1280 iov[2] = (struct iovec){
1285 iov[3] = (struct iovec){
1286 .iov_base = f->f_prevhost,
1287 .iov_len = strlen(f->f_prevhost)
1289 iov[4] = (struct iovec){
1294 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1299 iov[5] = (struct iovec){
1301 .iov_len = strlen(msg)
1303 } else if (f->f_prevcount > 1) {
1304 iov[5] = (struct iovec){
1306 .iov_len = snprintf(repbuf, sizeof(repbuf),
1307 "last message repeated %d times", f->f_prevcount)
1310 iov[5] = (struct iovec){
1311 .iov_base = f->f_prevline,
1312 .iov_len = f->f_prevlen
1315 dprintf("Logging to %s", TypeNames[f->f_type]);
1318 switch (f->f_type) {
1324 dprintf(" %s", f->fu_forw_hname);
1325 switch (f->fu_forw_addr->ai_addr->sa_family) {
1329 ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1335 ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1341 /* check for local vs remote messages */
1342 if (strcasecmp(f->f_prevhost, LocalHostName))
1343 l = snprintf(line, sizeof line - 1,
1344 "<%d>%.15s Forwarded from %s: %s",
1345 f->f_prevpri, (char *)iov[0].iov_base,
1346 f->f_prevhost, (char *)iov[5].iov_base);
1348 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1349 f->f_prevpri, (char *)iov[0].iov_base,
1350 (char *)iov[5].iov_base);
1353 else if (l > MAXLINE)
1356 for (r = f->fu_forw_addr; r; r = r->ai_next) {
1357 struct socklist *sl;
1359 STAILQ_FOREACH(sl, &shead, next) {
1360 if (sl->sl_ss.ss_family == AF_LOCAL ||
1361 sl->sl_ss.ss_family == AF_UNSPEC ||
1364 lsent = sendto(sl->sl_socket, line, l, 0,
1365 r->ai_addr, r->ai_addrlen);
1369 if (lsent == l && !send_to_all)
1372 dprintf("lsent/l: %d/%d\n", lsent, l);
1387 /* case ENOTSOCK: */
1389 /* case EMSGSIZE: */
1392 /* case ECONNREFUSED: */
1394 dprintf("removing entry: errno=%d\n", e);
1395 f->f_type = F_UNUSED;
1402 dprintf(" %s\n", f->fu_fname);
1403 iov[6] = (struct iovec){
1407 if (writev(f->f_file, iov, nitems(iov)) < 0) {
1409 * If writev(2) fails for potentially transient errors
1410 * like the filesystem being full, ignore it.
1411 * Otherwise remove this logfile from the list.
1413 if (errno != ENOSPC) {
1417 logerror(f->fu_fname);
1419 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1420 f->f_flags |= FFLAG_NEEDSYNC;
1426 dprintf(" %s\n", f->fu_pipe_pname);
1427 iov[6] = (struct iovec){
1431 if (f->fu_pipe_pid == 0) {
1432 if ((f->f_file = p_open(f->fu_pipe_pname,
1433 &f->fu_pipe_pid)) < 0) {
1434 logerror(f->fu_pipe_pname);
1438 if (writev(f->f_file, iov, nitems(iov)) < 0) {
1441 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1444 logerror(f->fu_pipe_pname);
1449 if (flags & IGN_CONS) {
1450 dprintf(" (ignored)\n");
1456 dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1457 iov[6] = (struct iovec){
1461 errno = 0; /* ttymsg() only sometimes returns an errno */
1462 if ((msgret = ttymsg(iov, nitems(iov), f->fu_fname, 10))) {
1463 f->f_type = F_UNUSED;
1471 iov[6] = (struct iovec){
1475 wallmsg(f, iov, nitems(iov));
1483 * WALLMSG -- Write a message to the world at large
1485 * Write the specified message to either the entire
1486 * world, or a list of approved users.
1489 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1491 static int reenter; /* avoid calling ourselves */
1500 while ((ut = getutxent()) != NULL) {
1501 if (ut->ut_type != USER_PROCESS)
1503 if (f->f_type == F_WALL) {
1504 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1505 TTYMSGTIME)) != NULL) {
1506 errno = 0; /* already in msg */
1511 /* should we send the message to this user? */
1512 for (i = 0; i < MAXUNAMES; i++) {
1513 if (!f->fu_uname[i][0])
1515 if (!strcmp(f->fu_uname[i], ut->ut_user)) {
1516 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
1517 TTYMSGTIME)) != NULL) {
1518 errno = 0; /* already in msg */
1530 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
1533 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
1535 static char device[1024];
1536 static char errbuf[1024];
1539 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
1541 if (stat(device, &sb) < 0) {
1542 (void) snprintf(errbuf, sizeof(errbuf),
1543 "%s: %s", device, strerror(errno));
1546 if ((sb.st_mode & S_IWGRP) == 0)
1547 /* Messages disabled. */
1549 return ttymsg(iov, iovcnt, line, tmout);
1553 reapchild(int signo __unused)
1559 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1560 /* First, look if it's a process from the dead queue. */
1561 if (deadq_removebypid(pid))
1564 /* Now, look in list of active processes. */
1565 STAILQ_FOREACH(f, &fhead, next) {
1566 if (f->f_type == F_PIPE &&
1567 f->fu_pipe_pid == pid) {
1569 log_deadchild(pid, status, f->fu_pipe_pname);
1578 * Return a printable representation of a host address.
1581 cvthname(struct sockaddr *f)
1584 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1586 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
1587 error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
1590 dprintf("Malformed from address %s\n", gai_strerror(error));
1593 dprintf("cvthname(%s)\n", ip);
1598 error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
1599 NULL, 0, NI_NAMEREQD);
1601 dprintf("Host name for your address (%s) unknown\n", ip);
1605 if (hl > 0 && hname[hl-1] == '.')
1607 trimdomain(hname, hl);
1619 domark(int signo __unused)
1626 * Print syslogd errors some place.
1629 logerror(const char *type)
1632 static int recursed = 0;
1634 /* If there's an error while trying to log an error, give up. */
1640 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1642 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1644 dprintf("%s\n", buf);
1645 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1653 struct socklist *sl;
1656 STAILQ_FOREACH(f, &fhead, next) {
1657 /* flush any pending output */
1659 fprintlog(f, 0, (char *)NULL);
1660 if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
1664 dprintf("syslogd: exiting on signal %d\n", signo);
1665 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1669 STAILQ_FOREACH(sl, &shead, next) {
1670 if (sl->sl_ss.ss_family == AF_LOCAL)
1671 unlink(sl->sl_peer->pe_name);
1673 pidfile_remove(pfh);
1679 configfiles(const struct dirent *dp)
1684 if (dp->d_name[0] == '.')
1687 ext_len = sizeof(include_ext) -1;
1689 if (dp->d_namlen <= ext_len)
1692 p = &dp->d_name[dp->d_namlen - ext_len];
1693 if (strcmp(p, include_ext) != 0)
1700 readconfigfile(FILE *cf, int allow_includes)
1704 struct dirent **ent;
1705 char cline[LINE_MAX];
1706 char host[MAXHOSTNAMELEN];
1707 char prog[LINE_MAX];
1708 char file[MAXPATHLEN];
1714 * Foreach line in the conf table, open that file.
1716 include_len = sizeof(include_str) -1;
1717 (void)strlcpy(host, "*", sizeof(host));
1718 (void)strlcpy(prog, "*", sizeof(prog));
1719 while (fgets(cline, sizeof(cline), cf) != NULL) {
1721 * check for end-of-section, comments, strip off trailing
1722 * spaces and newline character. #!prog is treated specially:
1723 * following lines apply only to that program.
1725 for (p = cline; isspace(*p); ++p)
1729 if (allow_includes &&
1730 strncmp(p, include_str, include_len) == 0 &&
1731 isspace(p[include_len])) {
1736 while (*tmp != '\0' && !isspace(*tmp))
1739 dprintf("Trying to include files in '%s'\n", p);
1740 nents = scandir(p, &ent, configfiles, alphasort);
1742 dprintf("Unable to open '%s': %s\n", p,
1746 for (i = 0; i < nents; i++) {
1747 if (snprintf(file, sizeof(file), "%s/%s", p,
1748 ent[i]->d_name) >= (int)sizeof(file)) {
1749 dprintf("ignoring path too long: "
1750 "'%s/%s'\n", p, ent[i]->d_name);
1755 cf2 = fopen(file, "r");
1758 dprintf("reading %s\n", file);
1759 readconfigfile(cf2, 0);
1767 if (*p != '!' && *p != '+' && *p != '-')
1770 if (*p == '+' || *p == '-') {
1774 if ((!*p) || (*p == '*')) {
1775 (void)strlcpy(host, "*", sizeof(host));
1780 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1781 if (!isalnum(*p) && *p != '.' && *p != '-'
1782 && *p != ',' && *p != ':' && *p != '%')
1791 while (isspace(*p)) p++;
1792 if ((!*p) || (*p == '*')) {
1793 (void)strlcpy(prog, "*", sizeof(prog));
1796 for (i = 0; i < LINE_MAX - 1; i++) {
1797 if (!isprint(p[i]) || isspace(p[i]))
1804 for (p = cline + 1; *p != '\0'; p++) {
1807 if (*(p - 1) == '\\') {
1815 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1817 f = cfline(cline, prog, host);
1824 sighandler(int signo)
1827 /* Send an wake-up signal to the select() loop. */
1828 write(sigpipe[1], &signo, sizeof(signo));
1832 * INIT -- Initialize syslogd from configuration table
1841 char oldLocalHostName[MAXHOSTNAMELEN];
1842 char hostMsg[2*MAXHOSTNAMELEN+40];
1843 char bootfileMsg[LINE_MAX];
1849 * Load hostname (may have changed).
1852 (void)strlcpy(oldLocalHostName, LocalHostName,
1853 sizeof(oldLocalHostName));
1854 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1855 err(EX_OSERR, "gethostname() failed");
1856 if ((p = strchr(LocalHostName, '.')) != NULL) {
1864 * Load / reload timezone data (in case it changed).
1866 * Just calling tzset() again does not work, the timezone code
1867 * caches the result. However, by setting the TZ variable, one
1868 * can defeat the caching and have the timezone code really
1869 * reload the timezone data. Respect any initial setting of
1870 * TZ, in case the system is configured specially.
1872 dprintf("loading timezone data via tzset()\n");
1876 setenv("TZ", ":/etc/localtime", 1);
1882 * Close all open log files.
1885 STAILQ_FOREACH(f, &fhead, next) {
1886 /* flush any pending output */
1888 fprintlog(f, 0, (char *)NULL);
1890 switch (f->f_type) {
1898 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1903 while(!STAILQ_EMPTY(&fhead)) {
1904 f = STAILQ_FIRST(&fhead);
1905 STAILQ_REMOVE_HEAD(&fhead, next);
1911 /* open the configuration file */
1912 if ((cf = fopen(ConfFile, "r")) == NULL) {
1913 dprintf("cannot open %s\n", ConfFile);
1914 f = cfline("*.ERR\t/dev/console", "*", "*");
1917 f = cfline("*.PANIC\t*", "*", "*");
1925 readconfigfile(cf, 1);
1927 /* close the configuration file */
1934 STAILQ_FOREACH(f, &fhead, next) {
1935 for (i = 0; i <= LOG_NFACILITIES; i++)
1936 if (f->f_pmask[i] == INTERNAL_NOPRI)
1939 printf("%d ", f->f_pmask[i]);
1940 printf("%s: ", TypeNames[f->f_type]);
1941 switch (f->f_type) {
1943 printf("%s", f->fu_fname);
1948 printf("%s%s", _PATH_DEV, f->fu_fname);
1952 switch (f->fu_forw_addr->ai_addr->sa_family) {
1955 port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
1960 port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
1968 f->fu_forw_hname, port);
1970 printf("%s", f->fu_forw_hname);
1975 printf("%s", f->fu_pipe_pname);
1979 for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
1980 printf("%s, ", f->fu_uname[i]);
1984 printf(" (%s)", f->f_program);
1989 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1990 dprintf("syslogd: restarted\n");
1992 * Log a change in hostname, but only on a restart.
1994 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1995 (void)snprintf(hostMsg, sizeof(hostMsg),
1996 "syslogd: hostname changed, \"%s\" to \"%s\"",
1997 oldLocalHostName, LocalHostName);
1998 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1999 dprintf("%s\n", hostMsg);
2002 * Log the kernel boot file if we aren't going to use it as
2003 * the prefix, and if this is *not* a restart.
2005 if (signo == 0 && !use_bootfile) {
2006 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2007 "syslogd: kernel boot file is %s", bootfile);
2008 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
2009 dprintf("%s\n", bootfileMsg);
2014 * Crack a configuration file line
2016 static struct filed *
2017 cfline(const char *line, const char *prog, const char *host)
2020 struct addrinfo hints, *res;
2021 int error, i, pri, syncfile;
2024 char buf[MAXLINE], ebuf[100];
2026 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
2028 f = calloc(1, sizeof(*f));
2033 errno = 0; /* keep strerror() stuff out of logerror messages */
2035 for (i = 0; i <= LOG_NFACILITIES; i++)
2036 f->f_pmask[i] = INTERNAL_NOPRI;
2038 /* save hostname if any */
2039 if (host && *host == '*')
2044 f->f_host = strdup(host);
2045 if (f->f_host == NULL) {
2049 hl = strlen(f->f_host);
2050 if (hl > 0 && f->f_host[hl-1] == '.')
2051 f->f_host[--hl] = '\0';
2052 trimdomain(f->f_host, hl);
2055 /* save program name if any */
2056 if (prog && *prog == '*')
2059 f->f_program = strdup(prog);
2060 if (f->f_program == NULL) {
2066 /* scan through the list of selectors */
2067 for (p = line; *p && *p != '\t' && *p != ' ';) {
2072 /* find the end of this facility name list */
2073 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2076 /* get the priority comparison */
2104 /* collect priority name */
2105 for (bp = buf; *q && !strchr("\t,; ", *q); )
2110 while (strchr(",;", *q))
2113 /* decode priority name */
2116 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2118 /* Ignore trailing spaces. */
2119 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2122 pri = decode(buf, prioritynames);
2125 (void)snprintf(ebuf, sizeof ebuf,
2126 "unknown priority name \"%s\"", buf);
2133 pri_cmp = (UniquePriority)
2138 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2140 /* scan facilities */
2141 while (*p && !strchr("\t.; ", *p)) {
2142 for (bp = buf; *p && !strchr("\t,;. ", *p); )
2147 for (i = 0; i < LOG_NFACILITIES; i++) {
2148 f->f_pmask[i] = pri;
2149 f->f_pcmp[i] = pri_cmp;
2152 i = decode(buf, facilitynames);
2155 (void)snprintf(ebuf, sizeof ebuf,
2156 "unknown facility name \"%s\"",
2162 f->f_pmask[i >> 3] = pri;
2163 f->f_pcmp[i >> 3] = pri_cmp;
2165 while (*p == ',' || *p == ' ')
2172 /* skip to action part */
2173 while (*p == '\t' || *p == ' ')
2188 * scan forward to see if there is a port defined.
2189 * so we can't use strlcpy..
2191 i = sizeof(f->fu_forw_hname);
2192 tp = f->fu_forw_hname;
2196 * an ipv6 address should start with a '[' in that case
2197 * we should scan for a ']'
2203 while (*p && (*p != endkey) && (i-- > 0)) {
2206 if (endkey == ']' && *p == endkey)
2210 /* See if we copied a domain and have a port */
2216 hints = (struct addrinfo){
2217 .ai_family = family,
2218 .ai_socktype = SOCK_DGRAM
2220 error = getaddrinfo(f->fu_forw_hname,
2221 p ? p : "syslog", &hints, &res);
2223 logerror(gai_strerror(error));
2226 f->fu_forw_addr = res;
2231 if ((f->f_file = open(p, logflags, 0600)) < 0) {
2232 f->f_type = F_UNUSED;
2237 f->f_flags |= FFLAG_SYNC;
2238 if (isatty(f->f_file)) {
2239 if (strcmp(p, ctty) == 0)
2240 f->f_type = F_CONSOLE;
2243 (void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
2244 sizeof(f->fu_fname));
2246 (void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
2253 (void)strlcpy(f->fu_pipe_pname, p + 1,
2254 sizeof(f->fu_pipe_pname));
2263 for (i = 0; i < MAXUNAMES && *p; i++) {
2264 for (q = p; *q && *q != ','; )
2266 (void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
2267 if ((q - p) >= MAXLOGNAME)
2268 f->fu_uname[i][MAXLOGNAME - 1] = '\0';
2270 f->fu_uname[i][q - p] = '\0';
2271 while (*q == ',' || *q == ' ')
2275 f->f_type = F_USERS;
2283 * Decode a symbolic name to a numeric value
2286 decode(const char *name, const CODE *codetab)
2292 return (atoi(name));
2294 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2296 *p = tolower(*name);
2301 for (c = codetab; c->c_name; c++)
2302 if (!strcmp(buf, c->c_name))
2312 struct deadq_entry *dq, *dq0;
2314 now = time((time_t *)NULL);
2315 MarkSeq += TIMERINTVL;
2316 if (MarkSeq >= MarkInterval) {
2317 logmsg(LOG_INFO, "-- MARK --",
2318 LocalHostName, ADDDATE|MARK);
2322 STAILQ_FOREACH(f, &fhead, next) {
2323 if (f->f_prevcount && now >= REPEATTIME(f)) {
2324 dprintf("flush %s: repeated %d times, %d sec.\n",
2325 TypeNames[f->f_type], f->f_prevcount,
2326 repeatinterval[f->f_repeatcount]);
2327 fprintlog(f, 0, (char *)NULL);
2332 /* Walk the dead queue, and see if we should signal somebody. */
2333 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
2334 switch (dq->dq_timeout) {
2336 /* Already signalled once, try harder now. */
2337 if (kill(dq->dq_pid, SIGKILL) != 0)
2338 (void)deadq_remove(dq);
2343 * Timed out on dead queue, send terminate
2344 * signal. Note that we leave the removal
2345 * from the dead queue to reapchild(), which
2346 * will also log the event (unless the process
2347 * didn't even really exist, in case we simply
2348 * drop it from the dead queue).
2350 if (kill(dq->dq_pid, SIGTERM) != 0)
2351 (void)deadq_remove(dq);
2360 (void)alarm(TIMERINTVL);
2364 * fork off and become a daemon, but wait for the child to come online
2365 * before returning to the parent, or we get disk thrashing at boot etc.
2366 * Set a timer so we don't hang forever if it wedges.
2369 waitdaemon(int maxwait)
2373 pid_t pid, childpid;
2375 switch (childpid = fork()) {
2381 signal(SIGALRM, timedout);
2383 while ((pid = wait3(&status, 0, NULL)) != -1) {
2384 if (WIFEXITED(status))
2385 errx(1, "child pid %d exited with return code %d",
2386 pid, WEXITSTATUS(status));
2387 if (WIFSIGNALED(status))
2388 errx(1, "child pid %d exited on signal %d%s",
2389 pid, WTERMSIG(status),
2390 WCOREDUMP(status) ? " (core dumped)" :
2392 if (pid == childpid) /* it's gone... */
2402 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2403 (void)dup2(fd, STDIN_FILENO);
2404 (void)dup2(fd, STDOUT_FILENO);
2405 (void)dup2(fd, STDERR_FILENO);
2406 if (fd > STDERR_FILENO)
2413 * We get a SIGALRM from the child when it's running and finished doing it's
2414 * fsync()'s or O_SYNC writes for all the boot messages.
2416 * We also get a signal from the kernel if the timer expires, so check to
2417 * see what happened.
2420 timedout(int sig __unused)
2424 signal(SIGALRM, SIG_DFL);
2426 errx(1, "timed out waiting for child");
2432 * Add `s' to the list of allowable peer addresses to accept messages
2435 * `s' is a string in the form:
2437 * [*]domainname[:{servicename|portnumber|*}]
2441 * netaddr/maskbits[:{servicename|portnumber|*}]
2443 * Returns -1 on error, 0 if the argument was valid.
2448 #if defined(INET) || defined(INET6)
2450 struct allowedpeer *ap;
2453 struct addrinfo hints, *res = NULL;
2455 in_addr_t *addrp, *maskp;
2458 uint32_t *addr6p, *mask6p;
2460 char ip[NI_MAXHOST];
2462 ap = calloc(1, sizeof(*ap));
2464 err(1, "malloc failed");
2467 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2470 if ((cp1 = strrchr(cp1, ':'))) {
2471 /* service/port provided */
2473 if (strlen(cp1) == 1 && *cp1 == '*')
2474 /* any port allowed */
2476 else if ((se = getservbyname(cp1, "udp"))) {
2477 ap->port = ntohs(se->s_port);
2479 ap->port = strtol(cp1, &cp2, 0);
2480 /* port not numeric */
2485 if ((se = getservbyname("syslog", "udp")))
2486 ap->port = ntohs(se->s_port);
2488 /* sanity, should not happen */
2492 if ((cp1 = strchr(s, '/')) != NULL &&
2493 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2495 if ((masklen = atoi(cp1 + 1)) < 0)
2500 cp2 = s + strlen(s) - 1;
2511 hints = (struct addrinfo){
2512 .ai_family = PF_UNSPEC,
2513 .ai_socktype = SOCK_DGRAM,
2514 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
2516 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2518 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
2519 ap->a_mask = (struct sockaddr_storage){
2520 .ss_family = res->ai_family,
2521 .ss_len = res->ai_addrlen
2523 switch (res->ai_family) {
2526 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
2527 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
2529 /* use default netmask */
2530 if (IN_CLASSA(ntohl(*addrp)))
2531 *maskp = htonl(IN_CLASSA_NET);
2532 else if (IN_CLASSB(ntohl(*addrp)))
2533 *maskp = htonl(IN_CLASSB_NET);
2535 *maskp = htonl(IN_CLASSC_NET);
2536 } else if (masklen == 0) {
2538 } else if (masklen <= 32) {
2539 /* convert masklen to netmask */
2540 *maskp = htonl(~((1 << (32 - masklen)) - 1));
2544 /* Lose any host bits in the network number. */
2555 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
2556 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
2557 /* convert masklen to netmask */
2558 while (masklen > 0) {
2561 htonl(~(0xffffffff >> masklen));
2565 *mask6p++ = 0xffffffff;
2577 /* arg `s' is domain name */
2589 STAILQ_INSERT_TAIL(&aphead, ap, next);
2592 printf("allowaddr: rule ");
2593 if (ap->isnumeric) {
2594 printf("numeric, ");
2595 getnameinfo(sstosa(&ap->a_addr),
2596 (sstosa(&ap->a_addr))->sa_len,
2597 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2598 printf("addr = %s, ", ip);
2599 getnameinfo(sstosa(&ap->a_mask),
2600 (sstosa(&ap->a_mask))->sa_len,
2601 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2602 printf("mask = %s; ", ip);
2604 printf("domainname = %s; ", ap->a_name);
2606 printf("port = %d\n", ap->port);
2619 * Validate that the remote peer has permission to log to us.
2622 validate(struct sockaddr *sa, const char *hname)
2625 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2626 struct allowedpeer *ap;
2628 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2631 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2633 struct addrinfo hints, *res;
2637 STAILQ_FOREACH(ap, &aphead, next) {
2640 dprintf("# of validation rule: %d\n", num);
2642 /* traditional behaviour, allow everything */
2645 (void)strlcpy(name, hname, sizeof(name));
2646 hints = (struct addrinfo){
2647 .ai_family = PF_UNSPEC,
2648 .ai_socktype = SOCK_DGRAM,
2649 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
2651 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2653 else if (strchr(name, '.') == NULL) {
2654 strlcat(name, ".", sizeof name);
2655 strlcat(name, LocalDomain, sizeof name);
2657 if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
2658 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2659 return (0); /* for safety, should not occur */
2660 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2664 /* now, walk down the list */
2666 STAILQ_FOREACH(ap, &aphead, next) {
2668 if (ap->port != 0 && ap->port != sport) {
2669 dprintf("rejected in rule %d due to port mismatch.\n",
2674 if (ap->isnumeric) {
2675 if (ap->a_addr.ss_family != sa->sa_family) {
2676 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2680 else if (ap->a_addr.ss_family == AF_INET) {
2682 a4p = satosin(&ap->a_addr);
2683 m4p = satosin(&ap->a_mask);
2684 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2685 != a4p->sin_addr.s_addr) {
2686 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2692 else if (ap->a_addr.ss_family == AF_INET6) {
2693 sin6 = satosin6(sa);
2694 a6p = satosin6(&ap->a_addr);
2695 m6p = satosin6(&ap->a_mask);
2696 if (a6p->sin6_scope_id != 0 &&
2697 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2698 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2701 if (IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
2702 &a6p->sin6_addr, &m6p->sin6_addr) != 0) {
2703 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2711 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
2713 dprintf("rejected in rule %d due to name "
2718 dprintf("accepted in rule %d.\n", i);
2719 return (1); /* hooray! */
2725 * Fairly similar to popen(3), but returns an open descriptor, as
2726 * opposed to a FILE *.
2729 p_open(const char *prog, pid_t *rpid)
2731 int pfd[2], nulldesc;
2733 char *argv[4]; /* sh -c cmd NULL */
2736 if (pipe(pfd) == -1)
2738 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2739 /* we are royally screwed anyway */
2742 switch ((pid = fork())) {
2748 (void)setsid(); /* Avoid catching SIGHUPs. */
2749 argv[0] = strdup("sh");
2750 argv[1] = strdup("-c");
2751 argv[2] = strdup(prog);
2753 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2760 /* Restore signals marked as SIG_IGN. */
2761 (void)signal(SIGINT, SIG_DFL);
2762 (void)signal(SIGQUIT, SIG_DFL);
2763 (void)signal(SIGPIPE, SIG_DFL);
2765 dup2(pfd[0], STDIN_FILENO);
2766 dup2(nulldesc, STDOUT_FILENO);
2767 dup2(nulldesc, STDERR_FILENO);
2768 closefrom(STDERR_FILENO + 1);
2770 (void)execvp(_PATH_BSHELL, argv);
2776 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2777 * supposed to get an EWOULDBLOCK on writev(2), which is
2778 * caught by the logic above anyway, which will in turn close
2779 * the pipe, and fork a new logging subprocess if necessary.
2780 * The stale subprocess will be killed some time later unless
2781 * it terminated itself due to closing its input pipe (so we
2782 * get rid of really dead puppies).
2784 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2786 (void)snprintf(errmsg, sizeof errmsg,
2787 "Warning: cannot change pipe to PID %d to "
2788 "non-blocking behaviour.",
2797 deadq_enter(pid_t pid, const char *name)
2799 struct deadq_entry *dq;
2805 * Be paranoid, if we can't signal the process, don't enter it
2806 * into the dead queue (perhaps it's already dead). If possible,
2807 * we try to fetch and log the child's status.
2809 if (kill(pid, 0) != 0) {
2810 if (waitpid(pid, &status, WNOHANG) > 0)
2811 log_deadchild(pid, status, name);
2815 dq = malloc(sizeof(*dq));
2820 *dq = (struct deadq_entry){
2822 .dq_timeout = DQ_TIMO_INIT
2824 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
2828 deadq_remove(struct deadq_entry *dq)
2831 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
2840 deadq_removebypid(pid_t pid)
2842 struct deadq_entry *dq;
2844 TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
2845 if (dq->dq_pid == pid)
2848 return (deadq_remove(dq));
2852 log_deadchild(pid_t pid, int status, const char *name)
2858 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2859 if (WIFSIGNALED(status)) {
2860 reason = "due to signal";
2861 code = WTERMSIG(status);
2863 reason = "with status";
2864 code = WEXITSTATUS(status);
2868 (void)snprintf(buf, sizeof buf,
2869 "Logging subprocess %d (%s) exited %s %d.",
2870 pid, name, reason, code);
2875 socksetup(struct peer *pe)
2877 struct addrinfo hints, *res, *res0;
2880 int (*sl_recv)(struct socklist *);
2882 * We have to handle this case for backwards compatibility:
2883 * If there are two (or more) colons but no '[' and ']',
2884 * assume this is an inet6 address without a service.
2886 if (pe->pe_name != NULL) {
2888 if (pe->pe_name[0] == '[' &&
2889 (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
2890 pe->pe_name = &pe->pe_name[1];
2892 if (cp[1] == ':' && cp[2] != '\0')
2893 pe->pe_serv = cp + 2;
2896 cp = strchr(pe->pe_name, ':');
2897 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2900 pe->pe_serv = cp + 1;
2901 if (cp == pe->pe_name)
2908 hints = (struct addrinfo){
2909 .ai_family = AF_UNSPEC,
2910 .ai_socktype = SOCK_DGRAM,
2911 .ai_flags = AI_PASSIVE
2913 if (pe->pe_name != NULL)
2914 dprintf("Trying peer: %s\n", pe->pe_name);
2915 if (pe->pe_serv == NULL)
2916 pe->pe_serv = "syslog";
2917 error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
2921 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
2922 pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
2923 gai_strerror(error));
2926 logerror(gai_strerror(error));
2932 for (res = res0; res != NULL; res = res->ai_next) {
2935 if (res->ai_family != AF_LOCAL &&
2937 /* Only AF_LOCAL in secure mode. */
2940 if (family != AF_UNSPEC &&
2941 res->ai_family != AF_LOCAL && res->ai_family != family)
2944 s = socket(res->ai_family, res->ai_socktype,
2952 if (res->ai_family == AF_INET6) {
2953 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
2954 &(int){1}, sizeof(int)) < 0) {
2955 logerror("setsockopt(IPV6_V6ONLY)");
2962 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
2963 &(int){1}, sizeof(int)) < 0) {
2964 logerror("setsockopt(SO_REUSEADDR)");
2971 * Bind INET and UNIX-domain sockets.
2973 * A UNIX-domain socket is always bound to a pathname
2974 * regardless of -N flag.
2976 * For INET sockets, RFC 3164 recommends that client
2977 * side message should come from the privileged syslogd port.
2979 * If the system administrator chooses not to obey
2980 * this, we can skip the bind() step so that the
2981 * system will choose a port for us.
2983 if (res->ai_family == AF_LOCAL)
2984 unlink(pe->pe_name);
2985 if (res->ai_family == AF_LOCAL ||
2986 NoBind == 0 || pe->pe_name != NULL) {
2987 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
2993 if (res->ai_family == AF_LOCAL ||
2997 if (res->ai_family == AF_LOCAL &&
2998 chmod(pe->pe_name, pe->pe_mode) < 0) {
2999 dprintf("chmod %s: %s\n", pe->pe_name,
3005 dprintf("new socket fd is %d\n", s);
3006 if (res->ai_socktype != SOCK_DGRAM) {
3009 sl_recv = socklist_recv_sock;
3010 #if defined(INET) || defined(INET6)
3011 if (SecureMode && (res->ai_family == AF_INET ||
3012 res->ai_family == AF_INET6)) {
3013 dprintf("shutdown\n");
3014 /* Forbid communication in secure mode. */
3015 if (shutdown(s, SHUT_RD) < 0 &&
3016 errno != ENOTCONN) {
3017 logerror("shutdown");
3024 dprintf("listening on socket\n");
3025 dprintf("sending on socket\n");
3026 addsock(res->ai_addr, res->ai_addrlen,
3039 increase_rcvbuf(int fd)
3043 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3044 &(socklen_t){sizeof(len)}) == 0) {
3045 if (len < RCVBUF_MINSIZE) {
3046 len = RCVBUF_MINSIZE;
3047 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));