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 * 4. 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 #define MAXLINE 1024 /* maximum line length */
72 #define MAXSVLINE 120 /* maximum saved line length */
73 #define DEFUPRI (LOG_USER|LOG_NOTICE)
74 #define DEFSPRI (LOG_KERN|LOG_CRIT)
75 #define TIMERINTVL 30 /* interval for checking flush, mark */
76 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
78 #include <sys/param.h>
79 #include <sys/ioctl.h>
83 #include <sys/socket.h>
84 #include <sys/queue.h>
88 #include <sys/resource.h>
89 #include <sys/syslimits.h>
90 #include <sys/types.h>
92 #include <netinet/in.h>
94 #include <arpa/inet.h>
107 #include <sysexits.h>
111 #include "pathnames.h"
115 #include <sys/syslog.h>
117 const char *ConfFile = _PATH_LOGCONF;
118 const char *PidFile = _PATH_LOGPID;
119 const char ctty[] = _PATH_CONSOLE;
121 #define dprintf if (Debug) printf
123 #define MAXUNAMES 20 /* maximum number of user names */
127 * We have two default sockets, one with 666 permissions,
128 * and one for privileged programs.
134 STAILQ_ENTRY(funix) next;
136 struct funix funix_secure = { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
138 struct funix funix_default = { -1, _PATH_LOG, DEFFILEMODE,
141 STAILQ_HEAD(, funix) funixes = { &funix_default,
142 &(funix_secure.next.stqe_next) };
148 #define IGN_CONS 0x001 /* don't print on console */
149 #define SYNC_FILE 0x002 /* do fsync on file after printing */
150 #define ADDDATE 0x004 /* add a date to the message */
151 #define MARK 0x008 /* this message is a mark */
152 #define ISKERNEL 0x010 /* kernel generated message */
155 * This structure represents the files that will have log
157 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
158 * or if f_type if F_PIPE and f_pid > 0.
162 struct filed *f_next; /* next in linked list */
163 short f_type; /* entry type, see below */
164 short f_file; /* file descriptor */
165 time_t f_time; /* time this was last written */
166 char *f_host; /* host from which to recd. */
167 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
168 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
172 char *f_program; /* program this applies to */
174 char f_uname[MAXUNAMES][UT_NAMESIZE+1];
176 char f_hname[MAXHOSTNAMELEN];
177 struct addrinfo *f_addr;
179 } f_forw; /* forwarding address */
180 char f_fname[MAXPATHLEN];
182 char f_pname[MAXPATHLEN];
186 char f_prevline[MAXSVLINE]; /* last message logged */
187 char f_lasttime[16]; /* time of last occurrence */
188 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
189 int f_prevpri; /* pri of f_prevline */
190 int f_prevlen; /* length of f_prevline */
191 int f_prevcount; /* repetition cnt of prevline */
192 u_int f_repeatcount; /* number of "repeated" msgs */
193 int f_flags; /* file-specific flags */
194 #define FFLAG_SYNC 0x01
195 #define FFLAG_NEEDSYNC 0x02
199 * Queue of about-to-be dead processes we should watch out for.
202 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
203 struct stailhead *deadq_headp;
208 TAILQ_ENTRY(deadq_entry) dq_entries;
212 * The timeout to apply to processes waiting on the dead queue. Unit
213 * of measure is `mark intervals', i.e. 20 minutes by default.
214 * Processes on the dead queue will be terminated after that time.
217 #define DQ_TIMO_INIT 2
219 typedef struct deadq_entry *dq_t;
223 * Struct to hold records of network addresses that are allowed to log
231 struct sockaddr_storage addr;
232 struct sockaddr_storage mask;
236 #define a_addr u.numeric.addr
237 #define a_mask u.numeric.mask
238 #define a_name u.name
243 * Intervals at which we flush out "message repeated" messages,
244 * in seconds after previous message is logged. After each flush,
245 * we move to the next interval until we reach the largest.
247 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
248 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
249 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
250 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
251 (f)->f_repeatcount = MAXREPEAT; \
254 /* values for f_type */
255 #define F_UNUSED 0 /* unused entry */
256 #define F_FILE 1 /* regular file */
257 #define F_TTY 2 /* terminal */
258 #define F_CONSOLE 3 /* console terminal */
259 #define F_FORW 4 /* remote machine */
260 #define F_USERS 5 /* list of users */
261 #define F_WALL 6 /* everyone logged on */
262 #define F_PIPE 7 /* pipe to program */
264 const char *TypeNames[8] = {
265 "UNUSED", "FILE", "TTY", "CONSOLE",
266 "FORW", "USERS", "WALL", "PIPE"
269 static struct filed *Files; /* Log files that we write to */
270 static struct filed consfile; /* Console */
272 static int Debug; /* debug flag */
273 static int resolve = 1; /* resolve hostname */
274 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
275 static const char *LocalDomain; /* our local domain name */
276 static int *finet; /* Internet datagram socket */
277 static int fklog = -1; /* /dev/klog */
278 static int Initialized; /* set when we have initialized ourselves */
279 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
280 static int MarkSeq; /* mark sequence number */
281 static int SecureMode; /* when true, receive only unix domain socks */
283 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
285 static int family = PF_INET; /* protocol family (IPv4 only) */
287 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
288 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
289 static int use_bootfile; /* log entire bootfile for every kern msg */
290 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
291 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
293 static char bootfile[MAXLINE+1]; /* booted kernel file */
295 struct allowedpeer *AllowedPeers; /* List of allowed peers */
296 static int NumAllowed; /* Number of entries in AllowedPeers */
297 static int RemoteAddDate; /* Always set the date on remote messages */
299 static int UniquePriority; /* Only log specified priority? */
300 static int LogFacPri; /* Put facility and priority in log message: */
301 /* 0=no, 1=numeric, 2=names */
302 static int KeepKernFac; /* Keep remotely logged kernel facility */
303 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
304 static struct pidfh *pfh;
306 volatile sig_atomic_t MarkSet, WantDie;
308 static int allowaddr(char *);
309 static void cfline(const char *, struct filed *,
310 const char *, const char *);
311 static const char *cvthname(struct sockaddr *);
312 static void deadq_enter(pid_t, const char *);
313 static int deadq_remove(pid_t);
314 static int decode(const char *, CODE *);
315 static void die(int);
316 static void dodie(int);
317 static void dofsync(void);
318 static void domark(int);
319 static void fprintlog(struct filed *, int, const char *);
320 static int *socksetup(int, const char *);
321 static void init(int);
322 static void logerror(const char *);
323 static void logmsg(int, const char *, const char *, int);
324 static void log_deadchild(pid_t, int, const char *);
325 static void markit(void);
326 static int skip_message(const char *, const char *, int);
327 static void printline(const char *, char *, int);
328 static void printsys(char *);
329 static int p_open(const char *, pid_t *);
330 static void readklog(void);
331 static void reapchild(int);
332 static void usage(void);
333 static int validate(struct sockaddr *, const char *);
334 static void unmapped(struct sockaddr *);
335 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
336 static int waitdaemon(int, int, int);
337 static void timedout(int);
338 static void double_rbuf(int);
341 main(int argc, char *argv[])
343 int ch, i, fdsrmax = 0, l;
344 struct sockaddr_un sunx, fromunix;
345 struct sockaddr_storage frominet;
347 char line[MAXLINE + 1];
348 const char *bindhostname, *hname;
349 struct timeval tv, *tvp;
350 struct sigaction sact;
351 struct funix *fx, *fx1;
353 pid_t ppid = 1, spid;
356 if (madvise(NULL, 0, MADV_PROTECT) != 0)
357 dprintf("madvise() failed: %s\n", strerror(errno));
360 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nop:P:sS:Tuv"))
377 case 'a': /* allow specific network addresses only */
378 if (allowaddr(optarg) == -1)
382 bindhostname = optarg;
390 case 'd': /* debug */
393 case 'f': /* configuration file */
396 case 'k': /* keep remote kern fac */
405 if (optarg[0] == '/') {
408 } else if ((name = strchr(optarg, ':')) != NULL) {
411 errx(1, "socket name must be absolute "
413 if (isdigit(*optarg)) {
414 perml = strtol(optarg, &ep, 8);
415 if (*ep || perml < 0 ||
416 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
417 errx(1, "invalid mode %s, exiting",
419 mode = (mode_t )perml;
421 errx(1, "invalid mode %s, exiting",
423 } else /* doesn't begin with '/', and no ':' */
424 errx(1, "can't parse path %s", optarg);
426 if (strlen(name) >= sizeof(sunx.sun_path))
427 errx(1, "%s path too long, exiting", name);
428 if ((fx = malloc(sizeof(struct funix))) == NULL)
429 errx(1, "malloc failed");
433 STAILQ_INSERT_TAIL(&funixes, fx, next);
436 case 'm': /* mark interval */
437 MarkInterval = atoi(optarg) * 60;
446 if (strlen(optarg) >= sizeof(sunx.sun_path))
447 errx(1, "%s path too long, exiting", optarg);
448 funix_default.name = optarg;
450 case 'P': /* path for alt. PID */
453 case 's': /* no network mode */
456 case 'S': /* path for privileged originator */
457 if (strlen(optarg) >= sizeof(sunx.sun_path))
458 errx(1, "%s path too long, exiting", optarg);
459 funix_secure.name = optarg;
464 case 'u': /* only log specified priority */
467 case 'v': /* log facility and priority */
473 if ((argc -= optind) != 0)
476 pfh = pidfile_open(PidFile, 0600, &spid);
479 errx(1, "syslogd already running, pid: %d", spid);
480 warn("cannot open pid file");
484 ppid = waitdaemon(0, 0, 30);
486 warn("could not become daemon");
497 consfile.f_type = F_CONSOLE;
498 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
499 sizeof(consfile.f_un.f_fname));
500 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
501 (void)signal(SIGTERM, dodie);
502 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
503 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
505 * We don't want the SIGCHLD and SIGHUP handlers to interfere
506 * with each other; they are likely candidates for being called
507 * simultaneously (SIGHUP closes pipe descriptor, process dies,
511 sigaddset(&mask, SIGHUP);
512 sact.sa_handler = reapchild;
514 sact.sa_flags = SA_RESTART;
515 (void)sigaction(SIGCHLD, &sact, NULL);
516 (void)signal(SIGALRM, domark);
517 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
518 (void)alarm(TIMERINTVL);
520 TAILQ_INIT(&deadq_head);
523 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
525 STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
526 (void)unlink(fx->name);
527 memset(&sunx, 0, sizeof(sunx));
528 sunx.sun_family = AF_LOCAL;
529 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
530 fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
532 bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
533 chmod(fx->name, fx->mode) < 0) {
534 (void)snprintf(line, sizeof line,
535 "cannot create %s", fx->name);
537 dprintf("cannot create %s (%d)\n", fx->name, errno);
538 if (fx == &funix_default || fx == &funix_secure)
541 STAILQ_REMOVE(&funixes, fx, funix, next);
548 finet = socksetup(family, bindhostname);
552 for (i = 0; i < *finet; i++) {
553 if (shutdown(finet[i+1], SHUT_RD) < 0) {
554 logerror("shutdown");
560 dprintf("listening on inet and/or inet6 socket\n");
562 dprintf("sending on inet and/or inet6 socket\n");
565 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
566 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
569 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
571 /* tuck my process id away */
574 dprintf("off & running....\n");
577 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
579 sigaddset(&mask, SIGCHLD);
580 sact.sa_handler = init;
582 sact.sa_flags = SA_RESTART;
583 (void)sigaction(SIGHUP, &sact, NULL);
586 tv.tv_sec = tv.tv_usec = 0;
588 if (fklog != -1 && fklog > fdsrmax)
590 if (finet && !SecureMode) {
591 for (i = 0; i < *finet; i++) {
592 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
593 fdsrmax = finet[i+1];
596 STAILQ_FOREACH(fx, &funixes, next)
600 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
603 errx(1, "calloc fd_set");
611 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
616 if (finet && !SecureMode) {
617 for (i = 0; i < *finet; i++) {
618 if (finet[i+1] != -1)
619 FD_SET(finet[i+1], fdsr);
622 STAILQ_FOREACH(fx, &funixes, next)
625 i = select(fdsrmax+1, fdsr, NULL, NULL,
626 needdofsync ? &tv : tvp);
642 if (fklog != -1 && FD_ISSET(fklog, fdsr))
644 if (finet && !SecureMode) {
645 for (i = 0; i < *finet; i++) {
646 if (FD_ISSET(finet[i+1], fdsr)) {
647 len = sizeof(frominet);
648 l = recvfrom(finet[i+1], line, MAXLINE,
649 0, (struct sockaddr *)&frominet,
653 hname = cvthname((struct sockaddr *)&frominet);
654 unmapped((struct sockaddr *)&frominet);
655 if (validate((struct sockaddr *)&frominet, hname))
656 printline(hname, line, RemoteAddDate ? ADDDATE : 0);
657 } else if (l < 0 && errno != EINTR)
658 logerror("recvfrom inet");
662 STAILQ_FOREACH(fx, &funixes, next) {
663 if (FD_ISSET(fx->s, fdsr)) {
664 len = sizeof(fromunix);
665 l = recvfrom(fx->s, line, MAXLINE, 0,
666 (struct sockaddr *)&fromunix, &len);
669 printline(LocalHostName, line, 0);
670 } else if (l < 0 && errno != EINTR)
671 logerror("recvfrom unix");
680 unmapped(struct sockaddr *sa)
682 struct sockaddr_in6 *sin6;
683 struct sockaddr_in sin4;
685 if (sa->sa_family != AF_INET6)
687 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
688 sizeof(sin4) > sa->sa_len)
690 sin6 = (struct sockaddr_in6 *)sa;
691 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
694 memset(&sin4, 0, sizeof(sin4));
695 sin4.sin_family = AF_INET;
696 sin4.sin_len = sizeof(struct sockaddr_in);
697 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
698 sizeof(sin4.sin_addr));
699 sin4.sin_port = sin6->sin6_port;
701 memcpy(sa, &sin4, sin4.sin_len);
708 fprintf(stderr, "%s\n%s\n%s\n%s\n",
709 "usage: syslogd [-468ACcdknosTuv] [-a allowed_peer]",
710 " [-b bind_address] [-f config_file]",
711 " [-l [mode:]path] [-m mark_interval]",
712 " [-P pid_file] [-p log_socket]");
717 * Take a raw input line, decode the message, and print the message
718 * on the appropriate log files.
721 printline(const char *hname, char *msg, int flags)
726 char line[MAXLINE + 1];
728 /* test for special codes */
733 n = strtol(p + 1, &q, 10);
734 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
739 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
743 * Don't allow users to log kernel messages.
744 * NOTE: since LOG_KERN == 0 this will also match
745 * messages with no facility specified.
747 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
748 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
752 while ((c = (unsigned char)*p++) != '\0' &&
753 q < &line[sizeof(line) - 4]) {
754 if (mask_C1 && (c & 0x80) && c < 0xA0) {
759 if (isascii(c) && iscntrl(c)) {
762 } else if (c == '\t') {
774 logmsg(pri, line, hname, flags);
778 * Read /dev/klog while data are available, split into lines.
783 char *p, *q, line[MAXLINE + 1];
788 i = read(fklog, line + len, MAXLINE - 1 - len);
790 line[i + len] = '\0';
792 if (i < 0 && errno != EINTR && errno != EAGAIN) {
799 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
804 if (len >= MAXLINE - 1) {
809 memmove(line, p, len + 1);
816 * Take a raw input line from /dev/klog, format similar to syslog().
823 int flags, isprintf, pri;
825 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
831 n = strtol(p + 1, &q, 10);
832 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
839 * Kernel printf's and LOG_CONSOLE messages have been displayed
840 * on the console already.
842 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
844 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
846 logmsg(pri, p, LocalHostName, flags);
852 * Match a program or host name against a specification.
853 * Return a non-0 value if the message must be ignored
854 * based on the specification.
857 skip_message(const char *name, const char *spec, int checkcase)
862 /* Behaviour on explicit match */
877 s = strstr (spec, name);
879 s = strcasestr (spec, name);
882 prev = (s == spec ? ',' : *(s - 1));
883 next = *(s + strlen (name));
885 if (prev == ',' && (next == '\0' || next == ','))
886 /* Explicit match: skip iff the spec is an
891 /* No explicit match for this name: skip the message iff
892 the spec is an inclusive one. */
897 * Log a message to the appropriate log files, users, etc. based on
901 logmsg(int pri, const char *msg, const char *from, int flags)
904 int i, fac, msglen, omask, prilev;
905 const char *timestamp;
906 char prog[NAME_MAX+1];
909 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
910 pri, flags, from, msg);
912 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
915 * Check to see if msg looks non-standard.
917 msglen = strlen(msg);
918 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
919 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
923 if (flags & ADDDATE) {
924 timestamp = ctime(&now) + 4;
931 /* skip leading blanks */
932 while (isspace(*msg)) {
937 /* extract facility and priority level */
939 fac = LOG_NFACILITIES;
943 /* Check maximum facility number. */
944 if (fac > LOG_NFACILITIES) {
945 (void)sigsetmask(omask);
949 prilev = LOG_PRI(pri);
951 /* extract program name */
952 for (i = 0; i < NAME_MAX; i++) {
953 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
954 msg[i] == '/' || isspace(msg[i]))
960 /* add kernel prefix for kernel messages */
961 if (flags & ISKERNEL) {
962 snprintf(buf, sizeof(buf), "%s: %s",
963 use_bootfile ? bootfile : "kernel", msg);
965 msglen = strlen(buf);
968 /* log the message to the particular outputs */
972 * Open in non-blocking mode to avoid hangs during open
973 * and close(waiting for the port to drain).
975 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
977 if (f->f_file >= 0) {
978 (void)strlcpy(f->f_lasttime, timestamp,
979 sizeof(f->f_lasttime));
980 fprintlog(f, flags, msg);
981 (void)close(f->f_file);
983 (void)sigsetmask(omask);
986 for (f = Files; f; f = f->f_next) {
987 /* skip messages that are incorrect priority */
988 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
989 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
990 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
992 || f->f_pmask[fac] == INTERNAL_NOPRI)
995 /* skip messages with the incorrect hostname */
996 if (skip_message(from, f->f_host, 0))
999 /* skip messages with the incorrect program name */
1000 if (skip_message(prog, f->f_program, 1))
1003 /* skip message to console if it has already been printed */
1004 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1007 /* don't output marks to recently written files */
1008 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1012 * suppress duplicate lines to this file
1014 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1015 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1016 f->f_prevline && !strcmp(msg, f->f_prevline) &&
1017 !strcasecmp(from, f->f_prevhost)) {
1018 (void)strlcpy(f->f_lasttime, timestamp,
1019 sizeof(f->f_lasttime));
1021 dprintf("msg repeated %d times, %ld sec of %d\n",
1022 f->f_prevcount, (long)(now - f->f_time),
1023 repeatinterval[f->f_repeatcount]);
1025 * If domark would have logged this by now,
1026 * flush it now (so we don't hold isolated messages),
1027 * but back off so we'll flush less often
1030 if (now > REPEATTIME(f)) {
1031 fprintlog(f, flags, (char *)NULL);
1035 /* new line, save it */
1037 fprintlog(f, 0, (char *)NULL);
1038 f->f_repeatcount = 0;
1040 (void)strlcpy(f->f_lasttime, timestamp,
1041 sizeof(f->f_lasttime));
1042 (void)strlcpy(f->f_prevhost, from,
1043 sizeof(f->f_prevhost));
1044 if (msglen < MAXSVLINE) {
1045 f->f_prevlen = msglen;
1046 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1047 fprintlog(f, flags, (char *)NULL);
1049 f->f_prevline[0] = 0;
1051 fprintlog(f, flags, msg);
1055 (void)sigsetmask(omask);
1063 for (f = Files; f; f = f->f_next) {
1064 if ((f->f_type == F_FILE) &&
1065 (f->f_flags & FFLAG_NEEDSYNC)) {
1066 f->f_flags &= ~FFLAG_NEEDSYNC;
1067 (void)fsync(f->f_file);
1074 fprintlog(struct filed *f, int flags, const char *msg)
1076 struct iovec iov[IOV_SIZE];
1079 int i, l, lsent = 0;
1080 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1081 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1085 if (f->f_type == F_WALL) {
1086 v->iov_base = greetings;
1087 /* The time displayed is not synchornized with the other log
1088 * destinations (like messages). Following fragment was using
1089 * ctime(&now), which was updating the time every 30 sec.
1090 * With f_lasttime, time is synchronized correctly.
1092 v->iov_len = snprintf(greetings, sizeof greetings,
1093 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1094 f->f_prevhost, f->f_lasttime);
1101 v->iov_base = f->f_lasttime;
1102 v->iov_len = strlen(f->f_lasttime);
1104 v->iov_base = space;
1110 static char fp_buf[30]; /* Hollow laugh */
1111 int fac = f->f_prevpri & LOG_FACMASK;
1112 int pri = LOG_PRI(f->f_prevpri);
1113 const char *f_s = NULL;
1114 char f_n[5]; /* Hollow laugh */
1115 const char *p_s = NULL;
1116 char p_n[5]; /* Hollow laugh */
1118 if (LogFacPri > 1) {
1121 for (c = facilitynames; c->c_name; c++) {
1122 if (c->c_val == fac) {
1127 for (c = prioritynames; c->c_name; c++) {
1128 if (c->c_val == pri) {
1135 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1139 snprintf(p_n, sizeof p_n, "%d", pri);
1142 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1143 v->iov_base = fp_buf;
1144 v->iov_len = strlen(fp_buf);
1151 v->iov_base = f->f_prevhost;
1152 v->iov_len = strlen(v->iov_base);
1154 v->iov_base = space;
1159 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1165 v->iov_len = strlen(msg);
1166 } else if (f->f_prevcount > 1) {
1167 v->iov_base = repbuf;
1168 v->iov_len = snprintf(repbuf, sizeof repbuf,
1169 "last message repeated %d times", f->f_prevcount);
1170 } else if (f->f_prevline) {
1171 v->iov_base = f->f_prevline;
1172 v->iov_len = f->f_prevlen;
1178 dprintf("Logging to %s", TypeNames[f->f_type]);
1181 switch (f->f_type) {
1188 port = (int)ntohs(((struct sockaddr_in *)
1189 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1191 dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1193 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1195 /* check for local vs remote messages */
1196 if (strcasecmp(f->f_prevhost, LocalHostName))
1197 l = snprintf(line, sizeof line - 1,
1198 "<%d>%.15s Forwarded from %s: %s",
1199 f->f_prevpri, (char *)iov[0].iov_base,
1200 f->f_prevhost, (char *)iov[5].iov_base);
1202 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1203 f->f_prevpri, (char *)iov[0].iov_base,
1204 (char *)iov[5].iov_base);
1207 else if (l > MAXLINE)
1211 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1212 for (i = 0; i < *finet; i++) {
1215 * should we check AF first, or just
1216 * trial and error? FWD
1219 address_family_of(finet[i+1]))
1221 lsent = sendto(finet[i+1], line, l, 0,
1222 r->ai_addr, r->ai_addrlen);
1226 if (lsent == l && !send_to_all)
1229 dprintf("lsent/l: %d/%d\n", lsent, l);
1242 /* case ENOTSOCK: */
1244 /* case EMSGSIZE: */
1247 /* case ECONNREFUSED: */
1249 dprintf("removing entry\n");
1250 f->f_type = F_UNUSED;
1258 dprintf(" %s\n", f->f_un.f_fname);
1261 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1263 * If writev(2) fails for potentially transient errors
1264 * like the filesystem being full, ignore it.
1265 * Otherwise remove this logfile from the list.
1267 if (errno != ENOSPC) {
1269 (void)close(f->f_file);
1270 f->f_type = F_UNUSED;
1272 logerror(f->f_un.f_fname);
1274 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1275 f->f_flags |= FFLAG_NEEDSYNC;
1281 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1284 if (f->f_un.f_pipe.f_pid == 0) {
1285 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1286 &f->f_un.f_pipe.f_pid)) < 0) {
1287 f->f_type = F_UNUSED;
1288 logerror(f->f_un.f_pipe.f_pname);
1292 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1294 (void)close(f->f_file);
1295 if (f->f_un.f_pipe.f_pid > 0)
1296 deadq_enter(f->f_un.f_pipe.f_pid,
1297 f->f_un.f_pipe.f_pname);
1298 f->f_un.f_pipe.f_pid = 0;
1300 logerror(f->f_un.f_pipe.f_pname);
1305 if (flags & IGN_CONS) {
1306 dprintf(" (ignored)\n");
1312 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1316 errno = 0; /* ttymsg() only sometimes returns an errno */
1317 if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1318 f->f_type = F_UNUSED;
1328 wallmsg(f, iov, IOV_SIZE);
1336 * WALLMSG -- Write a message to the world at large
1338 * Write the specified message to either the entire
1339 * world, or a list of approved users.
1342 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1344 static int reenter; /* avoid calling ourselves */
1349 char line[sizeof(ut.ut_line) + 1];
1353 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1354 logerror(_PATH_UTMP);
1359 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1360 if (ut.ut_name[0] == '\0')
1362 /* We must use strncpy since ut_* may not be NUL terminated. */
1363 strncpy(line, ut.ut_line, sizeof(line) - 1);
1364 line[sizeof(line) - 1] = '\0';
1365 if (f->f_type == F_WALL) {
1366 if ((p = ttymsg(iov, iovlen, line, TTYMSGTIME)) !=
1368 errno = 0; /* already in msg */
1373 /* should we send the message to this user? */
1374 for (i = 0; i < MAXUNAMES; i++) {
1375 if (!f->f_un.f_uname[i][0])
1377 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1379 if ((p = ttymsg(iov, iovlen, line, TTYMSGTIME))
1381 errno = 0; /* already in msg */
1393 reapchild(int signo __unused)
1399 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1401 /* Don't tell while we are initting. */
1404 /* First, look if it's a process from the dead queue. */
1405 if (deadq_remove(pid))
1408 /* Now, look in list of active processes. */
1409 for (f = Files; f; f = f->f_next)
1410 if (f->f_type == F_PIPE &&
1411 f->f_un.f_pipe.f_pid == pid) {
1412 (void)close(f->f_file);
1413 f->f_un.f_pipe.f_pid = 0;
1414 log_deadchild(pid, status,
1415 f->f_un.f_pipe.f_pname);
1424 * Return a printable representation of a host address.
1427 cvthname(struct sockaddr *f)
1430 sigset_t omask, nmask;
1431 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1433 error = getnameinfo((struct sockaddr *)f,
1434 ((struct sockaddr *)f)->sa_len,
1435 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1436 dprintf("cvthname(%s)\n", ip);
1439 dprintf("Malformed from address %s\n", gai_strerror(error));
1445 sigemptyset(&nmask);
1446 sigaddset(&nmask, SIGHUP);
1447 sigprocmask(SIG_BLOCK, &nmask, &omask);
1448 error = getnameinfo((struct sockaddr *)f,
1449 ((struct sockaddr *)f)->sa_len,
1450 hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1451 sigprocmask(SIG_SETMASK, &omask, NULL);
1453 dprintf("Host name for your address (%s) unknown\n", ip);
1457 if (hl > 0 && hname[hl-1] == '.')
1459 trimdomain(hname, hl);
1471 domark(int signo __unused)
1478 * Print syslogd errors some place.
1481 logerror(const char *type)
1484 static int recursed = 0;
1486 /* If there's an error while trying to log an error, give up. */
1492 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1494 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1496 dprintf("%s\n", buf);
1497 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1506 int was_initialized;
1509 was_initialized = Initialized;
1510 Initialized = 0; /* Don't log SIGCHLDs. */
1511 for (f = Files; f != NULL; f = f->f_next) {
1512 /* flush any pending output */
1514 fprintlog(f, 0, (char *)NULL);
1515 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1516 (void)close(f->f_file);
1517 f->f_un.f_pipe.f_pid = 0;
1520 Initialized = was_initialized;
1522 dprintf("syslogd: exiting on signal %d\n", signo);
1523 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1527 STAILQ_FOREACH(fx, &funixes, next)
1528 (void)unlink(fx->name);
1529 pidfile_remove(pfh);
1535 * INIT -- Initialize syslogd from configuration table
1542 struct filed *f, *next, **nextp;
1544 char cline[LINE_MAX];
1545 char prog[NAME_MAX+1];
1546 char host[MAXHOSTNAMELEN];
1547 char oldLocalHostName[MAXHOSTNAMELEN];
1548 char hostMsg[2*MAXHOSTNAMELEN+40];
1549 char bootfileMsg[LINE_MAX];
1554 * Load hostname (may have changed).
1557 (void)strlcpy(oldLocalHostName, LocalHostName,
1558 sizeof(oldLocalHostName));
1559 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1560 err(EX_OSERR, "gethostname() failed");
1561 if ((p = strchr(LocalHostName, '.')) != NULL) {
1569 * Close all open log files.
1572 for (f = Files; f != NULL; f = next) {
1573 /* flush any pending output */
1575 fprintlog(f, 0, (char *)NULL);
1577 switch (f->f_type) {
1582 (void)close(f->f_file);
1585 if (f->f_un.f_pipe.f_pid > 0) {
1586 (void)close(f->f_file);
1587 deadq_enter(f->f_un.f_pipe.f_pid,
1588 f->f_un.f_pipe.f_pname);
1590 f->f_un.f_pipe.f_pid = 0;
1594 if (f->f_program) free(f->f_program);
1595 if (f->f_host) free(f->f_host);
1601 /* open the configuration file */
1602 if ((cf = fopen(ConfFile, "r")) == NULL) {
1603 dprintf("cannot open %s\n", ConfFile);
1604 *nextp = (struct filed *)calloc(1, sizeof(*f));
1605 if (*nextp == NULL) {
1609 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1610 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1611 if ((*nextp)->f_next == NULL) {
1615 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1621 * Foreach line in the conf table, open that file.
1624 (void)strlcpy(host, "*", sizeof(host));
1625 (void)strlcpy(prog, "*", sizeof(prog));
1626 while (fgets(cline, sizeof(cline), cf) != NULL) {
1628 * check for end-of-section, comments, strip off trailing
1629 * spaces and newline character. #!prog is treated specially:
1630 * following lines apply only to that program.
1632 for (p = cline; isspace(*p); ++p)
1638 if (*p != '!' && *p != '+' && *p != '-')
1641 if (*p == '+' || *p == '-') {
1645 if ((!*p) || (*p == '*')) {
1646 (void)strlcpy(host, "*", sizeof(host));
1651 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1652 if (!isalnum(*p) && *p != '.' && *p != '-'
1653 && *p != ',' && *p != ':' && *p != '%')
1662 while (isspace(*p)) p++;
1663 if ((!*p) || (*p == '*')) {
1664 (void)strlcpy(prog, "*", sizeof(prog));
1667 for (i = 0; i < NAME_MAX; i++) {
1668 if (!isprint(p[i]) || isspace(p[i]))
1675 for (p = cline + 1; *p != '\0'; p++) {
1678 if (*(p - 1) == '\\') {
1686 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1688 f = (struct filed *)calloc(1, sizeof(*f));
1695 cfline(cline, f, prog, host);
1698 /* close the configuration file */
1705 for (f = Files; f; f = f->f_next) {
1706 for (i = 0; i <= LOG_NFACILITIES; i++)
1707 if (f->f_pmask[i] == INTERNAL_NOPRI)
1710 printf("%d ", f->f_pmask[i]);
1711 printf("%s: ", TypeNames[f->f_type]);
1712 switch (f->f_type) {
1714 printf("%s", f->f_un.f_fname);
1719 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1723 port = (int)ntohs(((struct sockaddr_in *)
1724 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1727 f->f_un.f_forw.f_hname, port);
1729 printf("%s", f->f_un.f_forw.f_hname);
1734 printf("%s", f->f_un.f_pipe.f_pname);
1738 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1739 printf("%s, ", f->f_un.f_uname[i]);
1743 printf(" (%s)", f->f_program);
1748 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1749 dprintf("syslogd: restarted\n");
1751 * Log a change in hostname, but only on a restart.
1753 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1754 (void)snprintf(hostMsg, sizeof(hostMsg),
1755 "syslogd: hostname changed, \"%s\" to \"%s\"",
1756 oldLocalHostName, LocalHostName);
1757 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1758 dprintf("%s\n", hostMsg);
1761 * Log the kernel boot file if we aren't going to use it as
1762 * the prefix, and if this is *not* a restart.
1764 if (signo == 0 && !use_bootfile) {
1765 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1766 "syslogd: kernel boot file is %s", bootfile);
1767 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1768 dprintf("%s\n", bootfileMsg);
1773 * Crack a configuration file line
1776 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1778 struct addrinfo hints, *res;
1779 int error, i, pri, syncfile;
1782 char buf[MAXLINE], ebuf[100];
1784 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1786 errno = 0; /* keep strerror() stuff out of logerror messages */
1788 /* clear out file entry */
1789 memset(f, 0, sizeof(*f));
1790 for (i = 0; i <= LOG_NFACILITIES; i++)
1791 f->f_pmask[i] = INTERNAL_NOPRI;
1793 /* save hostname if any */
1794 if (host && *host == '*')
1799 f->f_host = strdup(host);
1800 if (f->f_host == NULL) {
1804 hl = strlen(f->f_host);
1805 if (hl > 0 && f->f_host[hl-1] == '.')
1806 f->f_host[--hl] = '\0';
1807 trimdomain(f->f_host, hl);
1810 /* save program name if any */
1811 if (prog && *prog == '*')
1814 f->f_program = strdup(prog);
1815 if (f->f_program == NULL) {
1821 /* scan through the list of selectors */
1822 for (p = line; *p && *p != '\t' && *p != ' ';) {
1827 /* find the end of this facility name list */
1828 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1831 /* get the priority comparison */
1859 /* collect priority name */
1860 for (bp = buf; *q && !strchr("\t,; ", *q); )
1865 while (strchr(",;", *q))
1868 /* decode priority name */
1871 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1873 /* Ignore trailing spaces. */
1874 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1877 pri = decode(buf, prioritynames);
1879 (void)snprintf(ebuf, sizeof ebuf,
1880 "unknown priority name \"%s\"", buf);
1886 pri_cmp = (UniquePriority)
1891 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1893 /* scan facilities */
1894 while (*p && !strchr("\t.; ", *p)) {
1895 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1900 for (i = 0; i < LOG_NFACILITIES; i++) {
1901 f->f_pmask[i] = pri;
1902 f->f_pcmp[i] = pri_cmp;
1905 i = decode(buf, facilitynames);
1907 (void)snprintf(ebuf, sizeof ebuf,
1908 "unknown facility name \"%s\"",
1913 f->f_pmask[i >> 3] = pri;
1914 f->f_pcmp[i >> 3] = pri_cmp;
1916 while (*p == ',' || *p == ' ')
1923 /* skip to action part */
1924 while (*p == '\t' || *p == ' ')
1938 * scan forward to see if there is a port defined.
1939 * so we can't use strlcpy..
1941 i = sizeof(f->f_un.f_forw.f_hname);
1942 tp = f->f_un.f_forw.f_hname;
1945 while (*p && (*p != ':') && (i-- > 0)) {
1950 /* See if we copied a domain and have a port */
1956 memset(&hints, 0, sizeof(hints));
1957 hints.ai_family = family;
1958 hints.ai_socktype = SOCK_DGRAM;
1959 error = getaddrinfo(f->f_un.f_forw.f_hname,
1960 p ? p : "syslog", &hints, &res);
1962 logerror(gai_strerror(error));
1965 f->f_un.f_forw.f_addr = res;
1970 if ((f->f_file = open(p, logflags, 0600)) < 0) {
1971 f->f_type = F_UNUSED;
1976 f->f_flags |= FFLAG_SYNC;
1977 if (isatty(f->f_file)) {
1978 if (strcmp(p, ctty) == 0)
1979 f->f_type = F_CONSOLE;
1982 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1983 sizeof(f->f_un.f_fname));
1985 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1991 f->f_un.f_pipe.f_pid = 0;
1992 (void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
1993 sizeof(f->f_un.f_pipe.f_pname));
2002 for (i = 0; i < MAXUNAMES && *p; i++) {
2003 for (q = p; *q && *q != ','; )
2005 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
2006 if ((q - p) > UT_NAMESIZE)
2007 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
2009 f->f_un.f_uname[i][q - p] = '\0';
2010 while (*q == ',' || *q == ' ')
2014 f->f_type = F_USERS;
2021 * Decode a symbolic name to a numeric value
2024 decode(const char *name, CODE *codetab)
2030 return (atoi(name));
2032 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2034 *p = tolower(*name);
2039 for (c = codetab; c->c_name; c++)
2040 if (!strcmp(buf, c->c_name))
2052 now = time((time_t *)NULL);
2053 MarkSeq += TIMERINTVL;
2054 if (MarkSeq >= MarkInterval) {
2055 logmsg(LOG_INFO, "-- MARK --",
2056 LocalHostName, ADDDATE|MARK);
2060 for (f = Files; f; f = f->f_next) {
2061 if (f->f_prevcount && now >= REPEATTIME(f)) {
2062 dprintf("flush %s: repeated %d times, %d sec.\n",
2063 TypeNames[f->f_type], f->f_prevcount,
2064 repeatinterval[f->f_repeatcount]);
2065 fprintlog(f, 0, (char *)NULL);
2070 /* Walk the dead queue, and see if we should signal somebody. */
2071 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2072 next = TAILQ_NEXT(q, dq_entries);
2074 switch (q->dq_timeout) {
2076 /* Already signalled once, try harder now. */
2077 if (kill(q->dq_pid, SIGKILL) != 0)
2078 (void)deadq_remove(q->dq_pid);
2083 * Timed out on dead queue, send terminate
2084 * signal. Note that we leave the removal
2085 * from the dead queue to reapchild(), which
2086 * will also log the event (unless the process
2087 * didn't even really exist, in case we simply
2088 * drop it from the dead queue).
2090 if (kill(q->dq_pid, SIGTERM) != 0)
2091 (void)deadq_remove(q->dq_pid);
2099 (void)alarm(TIMERINTVL);
2103 * fork off and become a daemon, but wait for the child to come online
2104 * before returing to the parent, or we get disk thrashing at boot etc.
2105 * Set a timer so we don't hang forever if it wedges.
2108 waitdaemon(int nochdir, int noclose, int maxwait)
2112 pid_t pid, childpid;
2114 switch (childpid = fork()) {
2120 signal(SIGALRM, timedout);
2122 while ((pid = wait3(&status, 0, NULL)) != -1) {
2123 if (WIFEXITED(status))
2124 errx(1, "child pid %d exited with return code %d",
2125 pid, WEXITSTATUS(status));
2126 if (WIFSIGNALED(status))
2127 errx(1, "child pid %d exited on signal %d%s",
2128 pid, WTERMSIG(status),
2129 WCOREDUMP(status) ? " (core dumped)" :
2131 if (pid == childpid) /* it's gone... */
2143 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2144 (void)dup2(fd, STDIN_FILENO);
2145 (void)dup2(fd, STDOUT_FILENO);
2146 (void)dup2(fd, STDERR_FILENO);
2154 * We get a SIGALRM from the child when it's running and finished doing it's
2155 * fsync()'s or O_SYNC writes for all the boot messages.
2157 * We also get a signal from the kernel if the timer expires, so check to
2158 * see what happened.
2161 timedout(int sig __unused)
2165 signal(SIGALRM, SIG_DFL);
2167 errx(1, "timed out waiting for child");
2173 * Add `s' to the list of allowable peer addresses to accept messages
2176 * `s' is a string in the form:
2178 * [*]domainname[:{servicename|portnumber|*}]
2182 * netaddr/maskbits[:{servicename|portnumber|*}]
2184 * Returns -1 on error, 0 if the argument was valid.
2190 struct allowedpeer ap;
2193 struct addrinfo hints, *res;
2194 struct in_addr *addrp, *maskp;
2197 u_int32_t *addr6p, *mask6p;
2199 char ip[NI_MAXHOST];
2202 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2205 if ((cp1 = strrchr(cp1, ':'))) {
2206 /* service/port provided */
2208 if (strlen(cp1) == 1 && *cp1 == '*')
2209 /* any port allowed */
2211 else if ((se = getservbyname(cp1, "udp"))) {
2212 ap.port = ntohs(se->s_port);
2214 ap.port = strtol(cp1, &cp2, 0);
2216 return (-1); /* port not numeric */
2219 if ((se = getservbyname("syslog", "udp")))
2220 ap.port = ntohs(se->s_port);
2222 /* sanity, should not happen */
2226 if ((cp1 = strchr(s, '/')) != NULL &&
2227 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2229 if ((masklen = atoi(cp1 + 1)) < 0)
2234 cp2 = s + strlen(s) - 1;
2245 memset(&hints, 0, sizeof(hints));
2246 hints.ai_family = PF_UNSPEC;
2247 hints.ai_socktype = SOCK_DGRAM;
2248 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2249 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2251 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2252 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2253 ap.a_mask.ss_family = res->ai_family;
2254 if (res->ai_family == AF_INET) {
2255 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2256 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2257 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2259 /* use default netmask */
2260 if (IN_CLASSA(ntohl(addrp->s_addr)))
2261 maskp->s_addr = htonl(IN_CLASSA_NET);
2262 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2263 maskp->s_addr = htonl(IN_CLASSB_NET);
2265 maskp->s_addr = htonl(IN_CLASSC_NET);
2266 } else if (masklen <= 32) {
2267 /* convert masklen to netmask */
2271 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2276 /* Lose any host bits in the network number. */
2277 addrp->s_addr &= maskp->s_addr;
2280 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2281 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2284 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2285 /* convert masklen to netmask */
2286 while (masklen > 0) {
2288 *mask6p = htonl(~(0xffffffff >> masklen));
2291 *mask6p++ = 0xffffffff;
2294 /* Lose any host bits in the network number. */
2295 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2296 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2297 for (i = 0; i < 4; i++)
2298 addr6p[i] &= mask6p[i];
2307 /* arg `s' is domain name */
2321 printf("allowaddr: rule %d: ", NumAllowed);
2323 printf("numeric, ");
2324 getnameinfo((struct sockaddr *)&ap.a_addr,
2325 ((struct sockaddr *)&ap.a_addr)->sa_len,
2326 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2327 printf("addr = %s, ", ip);
2328 getnameinfo((struct sockaddr *)&ap.a_mask,
2329 ((struct sockaddr *)&ap.a_mask)->sa_len,
2330 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2331 printf("mask = %s; ", ip);
2333 printf("domainname = %s; ", ap.a_name);
2335 printf("port = %d\n", ap.port);
2338 if ((AllowedPeers = realloc(AllowedPeers,
2339 ++NumAllowed * sizeof(struct allowedpeer)))
2341 logerror("realloc");
2344 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2349 * Validate that the remote peer has permission to log to us.
2352 validate(struct sockaddr *sa, const char *hname)
2356 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2357 struct allowedpeer *ap;
2358 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2361 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2363 struct addrinfo hints, *res;
2366 if (NumAllowed == 0)
2367 /* traditional behaviour, allow everything */
2370 (void)strlcpy(name, hname, sizeof(name));
2371 memset(&hints, 0, sizeof(hints));
2372 hints.ai_family = PF_UNSPEC;
2373 hints.ai_socktype = SOCK_DGRAM;
2374 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2375 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2377 else if (strchr(name, '.') == NULL) {
2378 strlcat(name, ".", sizeof name);
2379 strlcat(name, LocalDomain, sizeof name);
2381 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2382 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2383 return (0); /* for safety, should not occur */
2384 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2388 /* now, walk down the list */
2389 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2390 if (ap->port != 0 && ap->port != sport) {
2391 dprintf("rejected in rule %d due to port mismatch.\n", i);
2395 if (ap->isnumeric) {
2396 if (ap->a_addr.ss_family != sa->sa_family) {
2397 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2400 if (ap->a_addr.ss_family == AF_INET) {
2401 sin4 = (struct sockaddr_in *)sa;
2402 a4p = (struct sockaddr_in *)&ap->a_addr;
2403 m4p = (struct sockaddr_in *)&ap->a_mask;
2404 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2405 != a4p->sin_addr.s_addr) {
2406 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2411 else if (ap->a_addr.ss_family == AF_INET6) {
2412 sin6 = (struct sockaddr_in6 *)sa;
2413 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2414 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2415 if (a6p->sin6_scope_id != 0 &&
2416 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2417 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2421 for (j = 0; j < 16; j += 4) {
2422 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2423 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2429 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2440 /* allow wildmatch */
2443 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2444 dprintf("rejected in rule %d due to name mismatch.\n", i);
2450 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2451 dprintf("rejected in rule %d due to name mismatch.\n", i);
2456 dprintf("accepted in rule %d.\n", i);
2457 return (1); /* hooray! */
2463 * Fairly similar to popen(3), but returns an open descriptor, as
2464 * opposed to a FILE *.
2467 p_open(const char *prog, pid_t *rpid)
2469 int pfd[2], nulldesc, i;
2471 sigset_t omask, mask;
2472 char *argv[4]; /* sh -c cmd NULL */
2475 if (pipe(pfd) == -1)
2477 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2478 /* we are royally screwed anyway */
2482 sigaddset(&mask, SIGALRM);
2483 sigaddset(&mask, SIGHUP);
2484 sigprocmask(SIG_BLOCK, &mask, &omask);
2485 switch ((pid = fork())) {
2487 sigprocmask(SIG_SETMASK, &omask, 0);
2492 argv[0] = strdup("sh");
2493 argv[1] = strdup("-c");
2494 argv[2] = strdup(prog);
2496 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2502 (void)setsid(); /* Avoid catching SIGHUPs. */
2505 * Throw away pending signals, and reset signal
2506 * behaviour to standard values.
2508 signal(SIGALRM, SIG_IGN);
2509 signal(SIGHUP, SIG_IGN);
2510 sigprocmask(SIG_SETMASK, &omask, 0);
2511 signal(SIGPIPE, SIG_DFL);
2512 signal(SIGQUIT, SIG_DFL);
2513 signal(SIGALRM, SIG_DFL);
2514 signal(SIGHUP, SIG_DFL);
2516 dup2(pfd[0], STDIN_FILENO);
2517 dup2(nulldesc, STDOUT_FILENO);
2518 dup2(nulldesc, STDERR_FILENO);
2519 for (i = getdtablesize(); i > 2; i--)
2522 (void)execvp(_PATH_BSHELL, argv);
2526 sigprocmask(SIG_SETMASK, &omask, 0);
2530 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2531 * supposed to get an EWOULDBLOCK on writev(2), which is
2532 * caught by the logic above anyway, which will in turn close
2533 * the pipe, and fork a new logging subprocess if necessary.
2534 * The stale subprocess will be killed some time later unless
2535 * it terminated itself due to closing its input pipe (so we
2536 * get rid of really dead puppies).
2538 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2540 (void)snprintf(errmsg, sizeof errmsg,
2541 "Warning: cannot change pipe to PID %d to "
2542 "non-blocking behaviour.",
2551 deadq_enter(pid_t pid, const char *name)
2557 * Be paranoid, if we can't signal the process, don't enter it
2558 * into the dead queue (perhaps it's already dead). If possible,
2559 * we try to fetch and log the child's status.
2561 if (kill(pid, 0) != 0) {
2562 if (waitpid(pid, &status, WNOHANG) > 0)
2563 log_deadchild(pid, status, name);
2567 p = malloc(sizeof(struct deadq_entry));
2574 p->dq_timeout = DQ_TIMO_INIT;
2575 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2579 deadq_remove(pid_t pid)
2583 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2584 if (q->dq_pid == pid) {
2585 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2595 log_deadchild(pid_t pid, int status, const char *name)
2601 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2602 if (WIFSIGNALED(status)) {
2603 reason = "due to signal";
2604 code = WTERMSIG(status);
2606 reason = "with status";
2607 code = WEXITSTATUS(status);
2611 (void)snprintf(buf, sizeof buf,
2612 "Logging subprocess %d (%s) exited %s %d.",
2613 pid, name, reason, code);
2618 socksetup(int af, const char *bindhostname)
2620 struct addrinfo hints, *res, *r;
2621 int error, maxs, *s, *socks;
2623 memset(&hints, 0, sizeof(hints));
2624 hints.ai_flags = AI_PASSIVE;
2625 hints.ai_family = af;
2626 hints.ai_socktype = SOCK_DGRAM;
2627 error = getaddrinfo(bindhostname, "syslog", &hints, &res);
2629 logerror(gai_strerror(error));
2634 /* Count max number of sockets we may open */
2635 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2636 socks = malloc((maxs+1) * sizeof(int));
2637 if (socks == NULL) {
2638 logerror("couldn't allocate memory for sockets");
2642 *socks = 0; /* num of sockets counter at start of array */
2644 for (r = res; r; r = r->ai_next) {
2646 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2651 if (r->ai_family == AF_INET6) {
2652 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2653 (char *)&on, sizeof (on)) < 0) {
2654 logerror("setsockopt");
2659 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2660 (char *)&on, sizeof (on)) < 0) {
2661 logerror("setsockopt");
2665 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2693 socklen_t slen, len;
2695 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2697 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen);