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>
82 #include <sys/socket.h>
83 #include <sys/queue.h>
87 #include <sys/resource.h>
88 #include <sys/syslimits.h>
89 #include <sys/types.h>
91 #include <netinet/in.h>
93 #include <arpa/inet.h>
106 #include <sysexits.h>
110 #include "pathnames.h"
114 #include <sys/syslog.h>
116 const char *ConfFile = _PATH_LOGCONF;
117 const char *PidFile = _PATH_LOGPID;
118 const char ctty[] = _PATH_CONSOLE;
120 #define dprintf if (Debug) printf
122 #define MAXUNAMES 20 /* maximum number of user names */
126 * We have two default sockets, one with 666 permissions,
127 * and one for privileged programs.
133 STAILQ_ENTRY(funix) next;
135 struct funix funix_secure = { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
137 struct funix funix_default = { -1, _PATH_LOG, DEFFILEMODE,
140 STAILQ_HEAD(, funix) funixes = { &funix_default,
141 &(funix_secure.next.stqe_next) };
147 #define IGN_CONS 0x001 /* don't print on console */
148 #define SYNC_FILE 0x002 /* do fsync on file after printing */
149 #define ADDDATE 0x004 /* add a date to the message */
150 #define MARK 0x008 /* this message is a mark */
151 #define ISKERNEL 0x010 /* kernel generated message */
154 * This structure represents the files that will have log
156 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
157 * or if f_type if F_PIPE and f_pid > 0.
161 struct filed *f_next; /* next in linked list */
162 short f_type; /* entry type, see below */
163 short f_file; /* file descriptor */
164 time_t f_time; /* time this was last written */
165 char *f_host; /* host from which to recd. */
166 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
167 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
171 char *f_program; /* program this applies to */
173 char f_uname[MAXUNAMES][UT_NAMESIZE+1];
175 char f_hname[MAXHOSTNAMELEN];
176 struct addrinfo *f_addr;
178 } f_forw; /* forwarding address */
179 char f_fname[MAXPATHLEN];
181 char f_pname[MAXPATHLEN];
185 char f_prevline[MAXSVLINE]; /* last message logged */
186 char f_lasttime[16]; /* time of last occurrence */
187 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
188 int f_prevpri; /* pri of f_prevline */
189 int f_prevlen; /* length of f_prevline */
190 int f_prevcount; /* repetition cnt of prevline */
191 u_int f_repeatcount; /* number of "repeated" msgs */
192 int f_flags; /* file-specific flags */
193 #define FFLAG_SYNC 0x01
194 #define FFLAG_NEEDSYNC 0x02
198 * Queue of about-to-be dead processes we should watch out for.
201 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
202 struct stailhead *deadq_headp;
207 TAILQ_ENTRY(deadq_entry) dq_entries;
211 * The timeout to apply to processes waiting on the dead queue. Unit
212 * of measure is `mark intervals', i.e. 20 minutes by default.
213 * Processes on the dead queue will be terminated after that time.
216 #define DQ_TIMO_INIT 2
218 typedef struct deadq_entry *dq_t;
222 * Struct to hold records of network addresses that are allowed to log
230 struct sockaddr_storage addr;
231 struct sockaddr_storage mask;
235 #define a_addr u.numeric.addr
236 #define a_mask u.numeric.mask
237 #define a_name u.name
242 * Intervals at which we flush out "message repeated" messages,
243 * in seconds after previous message is logged. After each flush,
244 * we move to the next interval until we reach the largest.
246 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
247 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
248 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
249 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
250 (f)->f_repeatcount = MAXREPEAT; \
253 /* values for f_type */
254 #define F_UNUSED 0 /* unused entry */
255 #define F_FILE 1 /* regular file */
256 #define F_TTY 2 /* terminal */
257 #define F_CONSOLE 3 /* console terminal */
258 #define F_FORW 4 /* remote machine */
259 #define F_USERS 5 /* list of users */
260 #define F_WALL 6 /* everyone logged on */
261 #define F_PIPE 7 /* pipe to program */
263 const char *TypeNames[8] = {
264 "UNUSED", "FILE", "TTY", "CONSOLE",
265 "FORW", "USERS", "WALL", "PIPE"
268 static struct filed *Files; /* Log files that we write to */
269 static struct filed consfile; /* Console */
271 static int Debug; /* debug flag */
272 static int resolve = 1; /* resolve hostname */
273 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
274 static const char *LocalDomain; /* our local domain name */
275 static int *finet; /* Internet datagram socket */
276 static int fklog = -1; /* /dev/klog */
277 static int Initialized; /* set when we have initialized ourselves */
278 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
279 static int MarkSeq; /* mark sequence number */
280 static int SecureMode; /* when true, receive only unix domain socks */
282 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
284 static int family = PF_INET; /* protocol family (IPv4 only) */
286 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
287 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
288 static int use_bootfile; /* log entire bootfile for every kern msg */
289 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
290 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
292 static char bootfile[MAXLINE+1]; /* booted kernel file */
294 struct allowedpeer *AllowedPeers; /* List of allowed peers */
295 static int NumAllowed; /* Number of entries in AllowedPeers */
296 static int RemoteAddDate; /* Always set the date on remote messages */
298 static int UniquePriority; /* Only log specified priority? */
299 static int LogFacPri; /* Put facility and priority in log message: */
300 /* 0=no, 1=numeric, 2=names */
301 static int KeepKernFac; /* Keep remotely logged kernel facility */
302 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
303 static struct pidfh *pfh;
305 volatile sig_atomic_t MarkSet, WantDie;
307 static int allowaddr(char *);
308 static void cfline(const char *, struct filed *,
309 const char *, const char *);
310 static const char *cvthname(struct sockaddr *);
311 static void deadq_enter(pid_t, const char *);
312 static int deadq_remove(pid_t);
313 static int decode(const char *, CODE *);
314 static void die(int);
315 static void dodie(int);
316 static void dofsync(void);
317 static void domark(int);
318 static void fprintlog(struct filed *, int, const char *);
319 static int *socksetup(int, const char *);
320 static void init(int);
321 static void logerror(const char *);
322 static void logmsg(int, const char *, const char *, int);
323 static void log_deadchild(pid_t, int, const char *);
324 static void markit(void);
325 static int skip_message(const char *, const char *, int);
326 static void printline(const char *, char *, int);
327 static void printsys(char *);
328 static int p_open(const char *, pid_t *);
329 static void readklog(void);
330 static void reapchild(int);
331 static void usage(void);
332 static int validate(struct sockaddr *, const char *);
333 static void unmapped(struct sockaddr *);
334 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
335 static int waitdaemon(int, int, int);
336 static void timedout(int);
337 static void double_rbuf(int);
340 main(int argc, char *argv[])
342 int ch, i, fdsrmax = 0, l;
343 struct sockaddr_un sunx, fromunix;
344 struct sockaddr_storage frominet;
346 char line[MAXLINE + 1];
347 const char *bindhostname, *hname;
348 struct timeval tv, *tvp;
349 struct sigaction sact;
350 struct funix *fx, *fx1;
352 pid_t ppid = 1, spid;
356 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nop:P:sS:Tuv"))
373 case 'a': /* allow specific network addresses only */
374 if (allowaddr(optarg) == -1)
378 bindhostname = optarg;
386 case 'd': /* debug */
389 case 'f': /* configuration file */
392 case 'k': /* keep remote kern fac */
401 if (optarg[0] == '/') {
404 } else if ((name = strchr(optarg, ':')) != NULL) {
407 errx(1, "socket name must be absolute "
409 if (isdigit(*optarg)) {
410 perml = strtol(optarg, &ep, 8);
411 if (*ep || perml < 0 ||
412 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
413 errx(1, "invalid mode %s, exiting",
415 mode = (mode_t )perml;
417 errx(1, "invalid mode %s, exiting",
419 } else /* doesn't begin with '/', and no ':' */
420 errx(1, "can't parse path %s", optarg);
422 if (strlen(name) >= sizeof(sunx.sun_path))
423 errx(1, "%s path too long, exiting", name);
424 if ((fx = malloc(sizeof(struct funix))) == NULL)
425 errx(1, "malloc failed");
429 STAILQ_INSERT_TAIL(&funixes, fx, next);
432 case 'm': /* mark interval */
433 MarkInterval = atoi(optarg) * 60;
442 if (strlen(optarg) >= sizeof(sunx.sun_path))
443 errx(1, "%s path too long, exiting", optarg);
444 funix_default.name = optarg;
446 case 'P': /* path for alt. PID */
449 case 's': /* no network mode */
452 case 'S': /* path for privileged originator */
453 if (strlen(optarg) >= sizeof(sunx.sun_path))
454 errx(1, "%s path too long, exiting", optarg);
455 funix_secure.name = optarg;
460 case 'u': /* only log specified priority */
463 case 'v': /* log facility and priority */
469 if ((argc -= optind) != 0)
472 pfh = pidfile_open(PidFile, 0600, &spid);
475 errx(1, "syslogd already running, pid: %d", spid);
476 warn("cannot open pid file");
480 ppid = waitdaemon(0, 0, 30);
482 warn("could not become daemon");
493 consfile.f_type = F_CONSOLE;
494 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
495 sizeof(consfile.f_un.f_fname));
496 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
497 (void)signal(SIGTERM, dodie);
498 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
499 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
501 * We don't want the SIGCHLD and SIGHUP handlers to interfere
502 * with each other; they are likely candidates for being called
503 * simultaneously (SIGHUP closes pipe descriptor, process dies,
507 sigaddset(&mask, SIGHUP);
508 sact.sa_handler = reapchild;
510 sact.sa_flags = SA_RESTART;
511 (void)sigaction(SIGCHLD, &sact, NULL);
512 (void)signal(SIGALRM, domark);
513 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
514 (void)alarm(TIMERINTVL);
516 TAILQ_INIT(&deadq_head);
519 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
521 STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
522 (void)unlink(fx->name);
523 memset(&sunx, 0, sizeof(sunx));
524 sunx.sun_family = AF_LOCAL;
525 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
526 fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
528 bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
529 chmod(fx->name, fx->mode) < 0) {
530 (void)snprintf(line, sizeof line,
531 "cannot create %s", fx->name);
533 dprintf("cannot create %s (%d)\n", fx->name, errno);
534 if (fx == &funix_default || fx == &funix_secure)
537 STAILQ_REMOVE(&funixes, fx, funix, next);
544 finet = socksetup(family, bindhostname);
548 for (i = 0; i < *finet; i++) {
549 if (shutdown(finet[i+1], SHUT_RD) < 0) {
550 logerror("shutdown");
556 dprintf("listening on inet and/or inet6 socket\n");
558 dprintf("sending on inet and/or inet6 socket\n");
561 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
562 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
565 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
567 /* tuck my process id away */
570 dprintf("off & running....\n");
573 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
575 sigaddset(&mask, SIGCHLD);
576 sact.sa_handler = init;
578 sact.sa_flags = SA_RESTART;
579 (void)sigaction(SIGHUP, &sact, NULL);
582 tv.tv_sec = tv.tv_usec = 0;
584 if (fklog != -1 && fklog > fdsrmax)
586 if (finet && !SecureMode) {
587 for (i = 0; i < *finet; i++) {
588 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
589 fdsrmax = finet[i+1];
592 STAILQ_FOREACH(fx, &funixes, next)
596 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
599 errx(1, "calloc fd_set");
607 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
612 if (finet && !SecureMode) {
613 for (i = 0; i < *finet; i++) {
614 if (finet[i+1] != -1)
615 FD_SET(finet[i+1], fdsr);
618 STAILQ_FOREACH(fx, &funixes, next)
621 i = select(fdsrmax+1, fdsr, NULL, NULL,
622 needdofsync ? &tv : tvp);
638 if (fklog != -1 && FD_ISSET(fklog, fdsr))
640 if (finet && !SecureMode) {
641 for (i = 0; i < *finet; i++) {
642 if (FD_ISSET(finet[i+1], fdsr)) {
643 len = sizeof(frominet);
644 l = recvfrom(finet[i+1], line, MAXLINE,
645 0, (struct sockaddr *)&frominet,
649 hname = cvthname((struct sockaddr *)&frominet);
650 unmapped((struct sockaddr *)&frominet);
651 if (validate((struct sockaddr *)&frominet, hname))
652 printline(hname, line, RemoteAddDate ? ADDDATE : 0);
653 } else if (l < 0 && errno != EINTR)
654 logerror("recvfrom inet");
658 STAILQ_FOREACH(fx, &funixes, next) {
659 if (FD_ISSET(fx->s, fdsr)) {
660 len = sizeof(fromunix);
661 l = recvfrom(fx->s, line, MAXLINE, 0,
662 (struct sockaddr *)&fromunix, &len);
665 printline(LocalHostName, line, 0);
666 } else if (l < 0 && errno != EINTR)
667 logerror("recvfrom unix");
676 unmapped(struct sockaddr *sa)
678 struct sockaddr_in6 *sin6;
679 struct sockaddr_in sin4;
681 if (sa->sa_family != AF_INET6)
683 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
684 sizeof(sin4) > sa->sa_len)
686 sin6 = (struct sockaddr_in6 *)sa;
687 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
690 memset(&sin4, 0, sizeof(sin4));
691 sin4.sin_family = AF_INET;
692 sin4.sin_len = sizeof(struct sockaddr_in);
693 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
694 sizeof(sin4.sin_addr));
695 sin4.sin_port = sin6->sin6_port;
697 memcpy(sa, &sin4, sin4.sin_len);
704 fprintf(stderr, "%s\n%s\n%s\n%s\n",
705 "usage: syslogd [-468ACcdknosTuv] [-a allowed_peer]",
706 " [-b bind_address] [-f config_file]",
707 " [-l [mode:]path] [-m mark_interval]",
708 " [-P pid_file] [-p log_socket]");
713 * Take a raw input line, decode the message, and print the message
714 * on the appropriate log files.
717 printline(const char *hname, char *msg, int flags)
722 char line[MAXLINE + 1];
724 /* test for special codes */
729 n = strtol(p + 1, &q, 10);
730 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
735 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
739 * Don't allow users to log kernel messages.
740 * NOTE: since LOG_KERN == 0 this will also match
741 * messages with no facility specified.
743 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
744 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
748 while ((c = (unsigned char)*p++) != '\0' &&
749 q < &line[sizeof(line) - 4]) {
750 if (mask_C1 && (c & 0x80) && c < 0xA0) {
755 if (isascii(c) && iscntrl(c)) {
758 } else if (c == '\t') {
770 logmsg(pri, line, hname, flags);
774 * Read /dev/klog while data are available, split into lines.
779 char *p, *q, line[MAXLINE + 1];
784 i = read(fklog, line + len, MAXLINE - 1 - len);
786 line[i + len] = '\0';
788 if (i < 0 && errno != EINTR && errno != EAGAIN) {
795 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
800 if (len >= MAXLINE - 1) {
805 memmove(line, p, len + 1);
812 * Take a raw input line from /dev/klog, format similar to syslog().
819 int flags, isprintf, pri;
821 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
827 n = strtol(p + 1, &q, 10);
828 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
835 * Kernel printf's and LOG_CONSOLE messages have been displayed
836 * on the console already.
838 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
840 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
842 logmsg(pri, p, LocalHostName, flags);
848 * Match a program or host name against a specification.
849 * Return a non-0 value if the message must be ignored
850 * based on the specification.
853 skip_message(const char *name, const char *spec, int checkcase)
858 /* Behaviour on explicit match */
873 s = strstr (spec, name);
875 s = strcasestr (spec, name);
878 prev = (s == spec ? ',' : *(s - 1));
879 next = *(s + strlen (name));
881 if (prev == ',' && (next == '\0' || next == ','))
882 /* Explicit match: skip iff the spec is an
887 /* No explicit match for this name: skip the message iff
888 the spec is an inclusive one. */
893 * Log a message to the appropriate log files, users, etc. based on
897 logmsg(int pri, const char *msg, const char *from, int flags)
900 int i, fac, msglen, omask, prilev;
901 const char *timestamp;
902 char prog[NAME_MAX+1];
905 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
906 pri, flags, from, msg);
908 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
911 * Check to see if msg looks non-standard.
913 msglen = strlen(msg);
914 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
915 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
919 if (flags & ADDDATE) {
920 timestamp = ctime(&now) + 4;
927 /* skip leading blanks */
928 while (isspace(*msg)) {
933 /* extract facility and priority level */
935 fac = LOG_NFACILITIES;
939 /* Check maximum facility number. */
940 if (fac > LOG_NFACILITIES) {
941 (void)sigsetmask(omask);
945 prilev = LOG_PRI(pri);
947 /* extract program name */
948 for (i = 0; i < NAME_MAX; i++) {
949 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
950 msg[i] == '/' || isspace(msg[i]))
956 /* add kernel prefix for kernel messages */
957 if (flags & ISKERNEL) {
958 snprintf(buf, sizeof(buf), "%s: %s",
959 use_bootfile ? bootfile : "kernel", msg);
961 msglen = strlen(buf);
964 /* log the message to the particular outputs */
968 * Open in non-blocking mode to avoid hangs during open
969 * and close(waiting for the port to drain).
971 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
973 if (f->f_file >= 0) {
974 (void)strlcpy(f->f_lasttime, timestamp,
975 sizeof(f->f_lasttime));
976 fprintlog(f, flags, msg);
977 (void)close(f->f_file);
979 (void)sigsetmask(omask);
982 for (f = Files; f; f = f->f_next) {
983 /* skip messages that are incorrect priority */
984 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
985 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
986 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
988 || f->f_pmask[fac] == INTERNAL_NOPRI)
991 /* skip messages with the incorrect hostname */
992 if (skip_message(from, f->f_host, 0))
995 /* skip messages with the incorrect program name */
996 if (skip_message(prog, f->f_program, 1))
999 /* skip message to console if it has already been printed */
1000 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1003 /* don't output marks to recently written files */
1004 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1008 * suppress duplicate lines to this file
1010 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1011 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1012 f->f_prevline && !strcmp(msg, f->f_prevline) &&
1013 !strcasecmp(from, f->f_prevhost)) {
1014 (void)strlcpy(f->f_lasttime, timestamp,
1015 sizeof(f->f_lasttime));
1017 dprintf("msg repeated %d times, %ld sec of %d\n",
1018 f->f_prevcount, (long)(now - f->f_time),
1019 repeatinterval[f->f_repeatcount]);
1021 * If domark would have logged this by now,
1022 * flush it now (so we don't hold isolated messages),
1023 * but back off so we'll flush less often
1026 if (now > REPEATTIME(f)) {
1027 fprintlog(f, flags, (char *)NULL);
1031 /* new line, save it */
1033 fprintlog(f, 0, (char *)NULL);
1034 f->f_repeatcount = 0;
1036 (void)strlcpy(f->f_lasttime, timestamp,
1037 sizeof(f->f_lasttime));
1038 (void)strlcpy(f->f_prevhost, from,
1039 sizeof(f->f_prevhost));
1040 if (msglen < MAXSVLINE) {
1041 f->f_prevlen = msglen;
1042 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1043 fprintlog(f, flags, (char *)NULL);
1045 f->f_prevline[0] = 0;
1047 fprintlog(f, flags, msg);
1051 (void)sigsetmask(omask);
1059 for (f = Files; f; f = f->f_next) {
1060 if ((f->f_type == F_FILE) &&
1061 (f->f_flags & FFLAG_NEEDSYNC)) {
1062 f->f_flags &= ~FFLAG_NEEDSYNC;
1063 (void)fsync(f->f_file);
1070 fprintlog(struct filed *f, int flags, const char *msg)
1072 struct iovec iov[IOV_SIZE];
1075 int i, l, lsent = 0;
1076 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1077 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1081 if (f->f_type == F_WALL) {
1082 v->iov_base = greetings;
1083 /* The time displayed is not synchornized with the other log
1084 * destinations (like messages). Following fragment was using
1085 * ctime(&now), which was updating the time every 30 sec.
1086 * With f_lasttime, time is synchronized correctly.
1088 v->iov_len = snprintf(greetings, sizeof greetings,
1089 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1090 f->f_prevhost, f->f_lasttime);
1097 v->iov_base = f->f_lasttime;
1098 v->iov_len = strlen(f->f_lasttime);
1100 v->iov_base = space;
1106 static char fp_buf[30]; /* Hollow laugh */
1107 int fac = f->f_prevpri & LOG_FACMASK;
1108 int pri = LOG_PRI(f->f_prevpri);
1109 const char *f_s = NULL;
1110 char f_n[5]; /* Hollow laugh */
1111 const char *p_s = NULL;
1112 char p_n[5]; /* Hollow laugh */
1114 if (LogFacPri > 1) {
1117 for (c = facilitynames; c->c_name; c++) {
1118 if (c->c_val == fac) {
1123 for (c = prioritynames; c->c_name; c++) {
1124 if (c->c_val == pri) {
1131 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1135 snprintf(p_n, sizeof p_n, "%d", pri);
1138 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1139 v->iov_base = fp_buf;
1140 v->iov_len = strlen(fp_buf);
1147 v->iov_base = f->f_prevhost;
1148 v->iov_len = strlen(v->iov_base);
1150 v->iov_base = space;
1155 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1161 v->iov_len = strlen(msg);
1162 } else if (f->f_prevcount > 1) {
1163 v->iov_base = repbuf;
1164 v->iov_len = snprintf(repbuf, sizeof repbuf,
1165 "last message repeated %d times", f->f_prevcount);
1166 } else if (f->f_prevline) {
1167 v->iov_base = f->f_prevline;
1168 v->iov_len = f->f_prevlen;
1174 dprintf("Logging to %s", TypeNames[f->f_type]);
1177 switch (f->f_type) {
1184 port = (int)ntohs(((struct sockaddr_in *)
1185 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1187 dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1189 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1191 /* check for local vs remote messages */
1192 if (strcasecmp(f->f_prevhost, LocalHostName))
1193 l = snprintf(line, sizeof line - 1,
1194 "<%d>%.15s Forwarded from %s: %s",
1195 f->f_prevpri, (char *)iov[0].iov_base,
1196 f->f_prevhost, (char *)iov[5].iov_base);
1198 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1199 f->f_prevpri, (char *)iov[0].iov_base,
1200 (char *)iov[5].iov_base);
1203 else if (l > MAXLINE)
1207 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1208 for (i = 0; i < *finet; i++) {
1211 * should we check AF first, or just
1212 * trial and error? FWD
1215 address_family_of(finet[i+1]))
1217 lsent = sendto(finet[i+1], line, l, 0,
1218 r->ai_addr, r->ai_addrlen);
1222 if (lsent == l && !send_to_all)
1225 dprintf("lsent/l: %d/%d\n", lsent, l);
1238 /* case ENOTSOCK: */
1240 /* case EMSGSIZE: */
1243 /* case ECONNREFUSED: */
1245 dprintf("removing entry\n");
1246 f->f_type = F_UNUSED;
1254 dprintf(" %s\n", f->f_un.f_fname);
1257 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1259 * If writev(2) fails for potentially transient errors
1260 * like the filesystem being full, ignore it.
1261 * Otherwise remove this logfile from the list.
1263 if (errno != ENOSPC) {
1265 (void)close(f->f_file);
1266 f->f_type = F_UNUSED;
1268 logerror(f->f_un.f_fname);
1270 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1271 f->f_flags |= FFLAG_NEEDSYNC;
1277 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1280 if (f->f_un.f_pipe.f_pid == 0) {
1281 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1282 &f->f_un.f_pipe.f_pid)) < 0) {
1283 f->f_type = F_UNUSED;
1284 logerror(f->f_un.f_pipe.f_pname);
1288 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1290 (void)close(f->f_file);
1291 if (f->f_un.f_pipe.f_pid > 0)
1292 deadq_enter(f->f_un.f_pipe.f_pid,
1293 f->f_un.f_pipe.f_pname);
1294 f->f_un.f_pipe.f_pid = 0;
1296 logerror(f->f_un.f_pipe.f_pname);
1301 if (flags & IGN_CONS) {
1302 dprintf(" (ignored)\n");
1308 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1312 errno = 0; /* ttymsg() only sometimes returns an errno */
1313 if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1314 f->f_type = F_UNUSED;
1324 wallmsg(f, iov, IOV_SIZE);
1332 * WALLMSG -- Write a message to the world at large
1334 * Write the specified message to either the entire
1335 * world, or a list of approved users.
1338 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1340 static int reenter; /* avoid calling ourselves */
1345 char line[sizeof(ut.ut_line) + 1];
1349 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1350 logerror(_PATH_UTMP);
1355 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1356 if (ut.ut_name[0] == '\0')
1358 /* We must use strncpy since ut_* may not be NUL terminated. */
1359 strncpy(line, ut.ut_line, sizeof(line) - 1);
1360 line[sizeof(line) - 1] = '\0';
1361 if (f->f_type == F_WALL) {
1362 if ((p = ttymsg(iov, iovlen, line, TTYMSGTIME)) !=
1364 errno = 0; /* already in msg */
1369 /* should we send the message to this user? */
1370 for (i = 0; i < MAXUNAMES; i++) {
1371 if (!f->f_un.f_uname[i][0])
1373 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1375 if ((p = ttymsg(iov, iovlen, line, TTYMSGTIME))
1377 errno = 0; /* already in msg */
1389 reapchild(int signo __unused)
1395 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1397 /* Don't tell while we are initting. */
1400 /* First, look if it's a process from the dead queue. */
1401 if (deadq_remove(pid))
1404 /* Now, look in list of active processes. */
1405 for (f = Files; f; f = f->f_next)
1406 if (f->f_type == F_PIPE &&
1407 f->f_un.f_pipe.f_pid == pid) {
1408 (void)close(f->f_file);
1409 f->f_un.f_pipe.f_pid = 0;
1410 log_deadchild(pid, status,
1411 f->f_un.f_pipe.f_pname);
1420 * Return a printable representation of a host address.
1423 cvthname(struct sockaddr *f)
1426 sigset_t omask, nmask;
1427 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1429 error = getnameinfo((struct sockaddr *)f,
1430 ((struct sockaddr *)f)->sa_len,
1431 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1432 dprintf("cvthname(%s)\n", ip);
1435 dprintf("Malformed from address %s\n", gai_strerror(error));
1441 sigemptyset(&nmask);
1442 sigaddset(&nmask, SIGHUP);
1443 sigprocmask(SIG_BLOCK, &nmask, &omask);
1444 error = getnameinfo((struct sockaddr *)f,
1445 ((struct sockaddr *)f)->sa_len,
1446 hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1447 sigprocmask(SIG_SETMASK, &omask, NULL);
1449 dprintf("Host name for your address (%s) unknown\n", ip);
1453 if (hl > 0 && hname[hl-1] == '.')
1455 trimdomain(hname, hl);
1467 domark(int signo __unused)
1474 * Print syslogd errors some place.
1477 logerror(const char *type)
1480 static int recursed = 0;
1482 /* If there's an error while trying to log an error, give up. */
1488 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1490 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1492 dprintf("%s\n", buf);
1493 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1502 int was_initialized;
1505 was_initialized = Initialized;
1506 Initialized = 0; /* Don't log SIGCHLDs. */
1507 for (f = Files; f != NULL; f = f->f_next) {
1508 /* flush any pending output */
1510 fprintlog(f, 0, (char *)NULL);
1511 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1512 (void)close(f->f_file);
1513 f->f_un.f_pipe.f_pid = 0;
1516 Initialized = was_initialized;
1518 dprintf("syslogd: exiting on signal %d\n", signo);
1519 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1523 STAILQ_FOREACH(fx, &funixes, next)
1524 (void)unlink(fx->name);
1525 pidfile_remove(pfh);
1531 * INIT -- Initialize syslogd from configuration table
1538 struct filed *f, *next, **nextp;
1540 char cline[LINE_MAX];
1541 char prog[NAME_MAX+1];
1542 char host[MAXHOSTNAMELEN];
1543 char oldLocalHostName[MAXHOSTNAMELEN];
1544 char hostMsg[2*MAXHOSTNAMELEN+40];
1545 char bootfileMsg[LINE_MAX];
1550 * Load hostname (may have changed).
1553 (void)strlcpy(oldLocalHostName, LocalHostName,
1554 sizeof(oldLocalHostName));
1555 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1556 err(EX_OSERR, "gethostname() failed");
1557 if ((p = strchr(LocalHostName, '.')) != NULL) {
1565 * Close all open log files.
1568 for (f = Files; f != NULL; f = next) {
1569 /* flush any pending output */
1571 fprintlog(f, 0, (char *)NULL);
1573 switch (f->f_type) {
1578 (void)close(f->f_file);
1581 if (f->f_un.f_pipe.f_pid > 0) {
1582 (void)close(f->f_file);
1583 deadq_enter(f->f_un.f_pipe.f_pid,
1584 f->f_un.f_pipe.f_pname);
1586 f->f_un.f_pipe.f_pid = 0;
1590 if (f->f_program) free(f->f_program);
1591 if (f->f_host) free(f->f_host);
1597 /* open the configuration file */
1598 if ((cf = fopen(ConfFile, "r")) == NULL) {
1599 dprintf("cannot open %s\n", ConfFile);
1600 *nextp = (struct filed *)calloc(1, sizeof(*f));
1601 if (*nextp == NULL) {
1605 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1606 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1607 if ((*nextp)->f_next == NULL) {
1611 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1617 * Foreach line in the conf table, open that file.
1620 (void)strlcpy(host, "*", sizeof(host));
1621 (void)strlcpy(prog, "*", sizeof(prog));
1622 while (fgets(cline, sizeof(cline), cf) != NULL) {
1624 * check for end-of-section, comments, strip off trailing
1625 * spaces and newline character. #!prog is treated specially:
1626 * following lines apply only to that program.
1628 for (p = cline; isspace(*p); ++p)
1634 if (*p != '!' && *p != '+' && *p != '-')
1637 if (*p == '+' || *p == '-') {
1641 if ((!*p) || (*p == '*')) {
1642 (void)strlcpy(host, "*", sizeof(host));
1647 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1648 if (!isalnum(*p) && *p != '.' && *p != '-'
1649 && *p != ',' && *p != ':' && *p != '%')
1658 while (isspace(*p)) p++;
1659 if ((!*p) || (*p == '*')) {
1660 (void)strlcpy(prog, "*", sizeof(prog));
1663 for (i = 0; i < NAME_MAX; i++) {
1664 if (!isprint(p[i]) || isspace(p[i]))
1671 for (p = cline + 1; *p != '\0'; p++) {
1674 if (*(p - 1) == '\\') {
1682 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1684 f = (struct filed *)calloc(1, sizeof(*f));
1691 cfline(cline, f, prog, host);
1694 /* close the configuration file */
1701 for (f = Files; f; f = f->f_next) {
1702 for (i = 0; i <= LOG_NFACILITIES; i++)
1703 if (f->f_pmask[i] == INTERNAL_NOPRI)
1706 printf("%d ", f->f_pmask[i]);
1707 printf("%s: ", TypeNames[f->f_type]);
1708 switch (f->f_type) {
1710 printf("%s", f->f_un.f_fname);
1715 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1719 port = (int)ntohs(((struct sockaddr_in *)
1720 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1723 f->f_un.f_forw.f_hname, port);
1725 printf("%s", f->f_un.f_forw.f_hname);
1730 printf("%s", f->f_un.f_pipe.f_pname);
1734 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1735 printf("%s, ", f->f_un.f_uname[i]);
1739 printf(" (%s)", f->f_program);
1744 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1745 dprintf("syslogd: restarted\n");
1747 * Log a change in hostname, but only on a restart.
1749 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1750 (void)snprintf(hostMsg, sizeof(hostMsg),
1751 "syslogd: hostname changed, \"%s\" to \"%s\"",
1752 oldLocalHostName, LocalHostName);
1753 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1754 dprintf("%s\n", hostMsg);
1757 * Log the kernel boot file if we aren't going to use it as
1758 * the prefix, and if this is *not* a restart.
1760 if (signo == 0 && !use_bootfile) {
1761 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1762 "syslogd: kernel boot file is %s", bootfile);
1763 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1764 dprintf("%s\n", bootfileMsg);
1769 * Crack a configuration file line
1772 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1774 struct addrinfo hints, *res;
1775 int error, i, pri, syncfile;
1778 char buf[MAXLINE], ebuf[100];
1780 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1782 errno = 0; /* keep strerror() stuff out of logerror messages */
1784 /* clear out file entry */
1785 memset(f, 0, sizeof(*f));
1786 for (i = 0; i <= LOG_NFACILITIES; i++)
1787 f->f_pmask[i] = INTERNAL_NOPRI;
1789 /* save hostname if any */
1790 if (host && *host == '*')
1795 f->f_host = strdup(host);
1796 if (f->f_host == NULL) {
1800 hl = strlen(f->f_host);
1801 if (hl > 0 && f->f_host[hl-1] == '.')
1802 f->f_host[--hl] = '\0';
1803 trimdomain(f->f_host, hl);
1806 /* save program name if any */
1807 if (prog && *prog == '*')
1810 f->f_program = strdup(prog);
1811 if (f->f_program == NULL) {
1817 /* scan through the list of selectors */
1818 for (p = line; *p && *p != '\t' && *p != ' ';) {
1823 /* find the end of this facility name list */
1824 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1827 /* get the priority comparison */
1855 /* collect priority name */
1856 for (bp = buf; *q && !strchr("\t,; ", *q); )
1861 while (strchr(",;", *q))
1864 /* decode priority name */
1867 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1869 /* Ignore trailing spaces. */
1870 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1873 pri = decode(buf, prioritynames);
1875 (void)snprintf(ebuf, sizeof ebuf,
1876 "unknown priority name \"%s\"", buf);
1882 pri_cmp = (UniquePriority)
1887 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1889 /* scan facilities */
1890 while (*p && !strchr("\t.; ", *p)) {
1891 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1896 for (i = 0; i < LOG_NFACILITIES; i++) {
1897 f->f_pmask[i] = pri;
1898 f->f_pcmp[i] = pri_cmp;
1901 i = decode(buf, facilitynames);
1903 (void)snprintf(ebuf, sizeof ebuf,
1904 "unknown facility name \"%s\"",
1909 f->f_pmask[i >> 3] = pri;
1910 f->f_pcmp[i >> 3] = pri_cmp;
1912 while (*p == ',' || *p == ' ')
1919 /* skip to action part */
1920 while (*p == '\t' || *p == ' ')
1934 * scan forward to see if there is a port defined.
1935 * so we can't use strlcpy..
1937 i = sizeof(f->f_un.f_forw.f_hname);
1938 tp = f->f_un.f_forw.f_hname;
1941 while (*p && (*p != ':') && (i-- > 0)) {
1946 /* See if we copied a domain and have a port */
1952 memset(&hints, 0, sizeof(hints));
1953 hints.ai_family = family;
1954 hints.ai_socktype = SOCK_DGRAM;
1955 error = getaddrinfo(f->f_un.f_forw.f_hname,
1956 p ? p : "syslog", &hints, &res);
1958 logerror(gai_strerror(error));
1961 f->f_un.f_forw.f_addr = res;
1966 if ((f->f_file = open(p, logflags, 0600)) < 0) {
1967 f->f_type = F_UNUSED;
1972 f->f_flags |= FFLAG_SYNC;
1973 if (isatty(f->f_file)) {
1974 if (strcmp(p, ctty) == 0)
1975 f->f_type = F_CONSOLE;
1978 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1979 sizeof(f->f_un.f_fname));
1981 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1987 f->f_un.f_pipe.f_pid = 0;
1988 (void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
1989 sizeof(f->f_un.f_pipe.f_pname));
1998 for (i = 0; i < MAXUNAMES && *p; i++) {
1999 for (q = p; *q && *q != ','; )
2001 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
2002 if ((q - p) > UT_NAMESIZE)
2003 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
2005 f->f_un.f_uname[i][q - p] = '\0';
2006 while (*q == ',' || *q == ' ')
2010 f->f_type = F_USERS;
2017 * Decode a symbolic name to a numeric value
2020 decode(const char *name, CODE *codetab)
2026 return (atoi(name));
2028 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2030 *p = tolower(*name);
2035 for (c = codetab; c->c_name; c++)
2036 if (!strcmp(buf, c->c_name))
2048 now = time((time_t *)NULL);
2049 MarkSeq += TIMERINTVL;
2050 if (MarkSeq >= MarkInterval) {
2051 logmsg(LOG_INFO, "-- MARK --",
2052 LocalHostName, ADDDATE|MARK);
2056 for (f = Files; f; f = f->f_next) {
2057 if (f->f_prevcount && now >= REPEATTIME(f)) {
2058 dprintf("flush %s: repeated %d times, %d sec.\n",
2059 TypeNames[f->f_type], f->f_prevcount,
2060 repeatinterval[f->f_repeatcount]);
2061 fprintlog(f, 0, (char *)NULL);
2066 /* Walk the dead queue, and see if we should signal somebody. */
2067 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2068 next = TAILQ_NEXT(q, dq_entries);
2070 switch (q->dq_timeout) {
2072 /* Already signalled once, try harder now. */
2073 if (kill(q->dq_pid, SIGKILL) != 0)
2074 (void)deadq_remove(q->dq_pid);
2079 * Timed out on dead queue, send terminate
2080 * signal. Note that we leave the removal
2081 * from the dead queue to reapchild(), which
2082 * will also log the event (unless the process
2083 * didn't even really exist, in case we simply
2084 * drop it from the dead queue).
2086 if (kill(q->dq_pid, SIGTERM) != 0)
2087 (void)deadq_remove(q->dq_pid);
2095 (void)alarm(TIMERINTVL);
2099 * fork off and become a daemon, but wait for the child to come online
2100 * before returing to the parent, or we get disk thrashing at boot etc.
2101 * Set a timer so we don't hang forever if it wedges.
2104 waitdaemon(int nochdir, int noclose, int maxwait)
2108 pid_t pid, childpid;
2110 switch (childpid = fork()) {
2116 signal(SIGALRM, timedout);
2118 while ((pid = wait3(&status, 0, NULL)) != -1) {
2119 if (WIFEXITED(status))
2120 errx(1, "child pid %d exited with return code %d",
2121 pid, WEXITSTATUS(status));
2122 if (WIFSIGNALED(status))
2123 errx(1, "child pid %d exited on signal %d%s",
2124 pid, WTERMSIG(status),
2125 WCOREDUMP(status) ? " (core dumped)" :
2127 if (pid == childpid) /* it's gone... */
2139 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2140 (void)dup2(fd, STDIN_FILENO);
2141 (void)dup2(fd, STDOUT_FILENO);
2142 (void)dup2(fd, STDERR_FILENO);
2150 * We get a SIGALRM from the child when it's running and finished doing it's
2151 * fsync()'s or O_SYNC writes for all the boot messages.
2153 * We also get a signal from the kernel if the timer expires, so check to
2154 * see what happened.
2157 timedout(int sig __unused)
2161 signal(SIGALRM, SIG_DFL);
2163 errx(1, "timed out waiting for child");
2169 * Add `s' to the list of allowable peer addresses to accept messages
2172 * `s' is a string in the form:
2174 * [*]domainname[:{servicename|portnumber|*}]
2178 * netaddr/maskbits[:{servicename|portnumber|*}]
2180 * Returns -1 on error, 0 if the argument was valid.
2186 struct allowedpeer ap;
2189 struct addrinfo hints, *res;
2190 struct in_addr *addrp, *maskp;
2193 u_int32_t *addr6p, *mask6p;
2195 char ip[NI_MAXHOST];
2198 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2201 if ((cp1 = strrchr(cp1, ':'))) {
2202 /* service/port provided */
2204 if (strlen(cp1) == 1 && *cp1 == '*')
2205 /* any port allowed */
2207 else if ((se = getservbyname(cp1, "udp"))) {
2208 ap.port = ntohs(se->s_port);
2210 ap.port = strtol(cp1, &cp2, 0);
2212 return (-1); /* port not numeric */
2215 if ((se = getservbyname("syslog", "udp")))
2216 ap.port = ntohs(se->s_port);
2218 /* sanity, should not happen */
2222 if ((cp1 = strchr(s, '/')) != NULL &&
2223 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2225 if ((masklen = atoi(cp1 + 1)) < 0)
2230 cp2 = s + strlen(s) - 1;
2241 memset(&hints, 0, sizeof(hints));
2242 hints.ai_family = PF_UNSPEC;
2243 hints.ai_socktype = SOCK_DGRAM;
2244 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2245 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2247 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2248 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2249 ap.a_mask.ss_family = res->ai_family;
2250 if (res->ai_family == AF_INET) {
2251 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2252 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2253 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2255 /* use default netmask */
2256 if (IN_CLASSA(ntohl(addrp->s_addr)))
2257 maskp->s_addr = htonl(IN_CLASSA_NET);
2258 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2259 maskp->s_addr = htonl(IN_CLASSB_NET);
2261 maskp->s_addr = htonl(IN_CLASSC_NET);
2262 } else if (masklen <= 32) {
2263 /* convert masklen to netmask */
2267 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2272 /* Lose any host bits in the network number. */
2273 addrp->s_addr &= maskp->s_addr;
2276 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2277 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2280 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2281 /* convert masklen to netmask */
2282 while (masklen > 0) {
2284 *mask6p = htonl(~(0xffffffff >> masklen));
2287 *mask6p++ = 0xffffffff;
2290 /* Lose any host bits in the network number. */
2291 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2292 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2293 for (i = 0; i < 4; i++)
2294 addr6p[i] &= mask6p[i];
2303 /* arg `s' is domain name */
2317 printf("allowaddr: rule %d: ", NumAllowed);
2319 printf("numeric, ");
2320 getnameinfo((struct sockaddr *)&ap.a_addr,
2321 ((struct sockaddr *)&ap.a_addr)->sa_len,
2322 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2323 printf("addr = %s, ", ip);
2324 getnameinfo((struct sockaddr *)&ap.a_mask,
2325 ((struct sockaddr *)&ap.a_mask)->sa_len,
2326 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2327 printf("mask = %s; ", ip);
2329 printf("domainname = %s; ", ap.a_name);
2331 printf("port = %d\n", ap.port);
2334 if ((AllowedPeers = realloc(AllowedPeers,
2335 ++NumAllowed * sizeof(struct allowedpeer)))
2337 logerror("realloc");
2340 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2345 * Validate that the remote peer has permission to log to us.
2348 validate(struct sockaddr *sa, const char *hname)
2352 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2353 struct allowedpeer *ap;
2354 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2357 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2359 struct addrinfo hints, *res;
2362 if (NumAllowed == 0)
2363 /* traditional behaviour, allow everything */
2366 (void)strlcpy(name, hname, sizeof(name));
2367 memset(&hints, 0, sizeof(hints));
2368 hints.ai_family = PF_UNSPEC;
2369 hints.ai_socktype = SOCK_DGRAM;
2370 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2371 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2373 else if (strchr(name, '.') == NULL) {
2374 strlcat(name, ".", sizeof name);
2375 strlcat(name, LocalDomain, sizeof name);
2377 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2378 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2379 return (0); /* for safety, should not occur */
2380 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2384 /* now, walk down the list */
2385 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2386 if (ap->port != 0 && ap->port != sport) {
2387 dprintf("rejected in rule %d due to port mismatch.\n", i);
2391 if (ap->isnumeric) {
2392 if (ap->a_addr.ss_family != sa->sa_family) {
2393 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2396 if (ap->a_addr.ss_family == AF_INET) {
2397 sin4 = (struct sockaddr_in *)sa;
2398 a4p = (struct sockaddr_in *)&ap->a_addr;
2399 m4p = (struct sockaddr_in *)&ap->a_mask;
2400 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2401 != a4p->sin_addr.s_addr) {
2402 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2407 else if (ap->a_addr.ss_family == AF_INET6) {
2408 sin6 = (struct sockaddr_in6 *)sa;
2409 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2410 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2411 if (a6p->sin6_scope_id != 0 &&
2412 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2413 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2417 for (j = 0; j < 16; j += 4) {
2418 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2419 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2425 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2436 /* allow wildmatch */
2439 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2440 dprintf("rejected in rule %d due to name mismatch.\n", i);
2446 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2447 dprintf("rejected in rule %d due to name mismatch.\n", i);
2452 dprintf("accepted in rule %d.\n", i);
2453 return (1); /* hooray! */
2459 * Fairly similar to popen(3), but returns an open descriptor, as
2460 * opposed to a FILE *.
2463 p_open(const char *prog, pid_t *rpid)
2465 int pfd[2], nulldesc, i;
2467 sigset_t omask, mask;
2468 char *argv[4]; /* sh -c cmd NULL */
2471 if (pipe(pfd) == -1)
2473 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2474 /* we are royally screwed anyway */
2478 sigaddset(&mask, SIGALRM);
2479 sigaddset(&mask, SIGHUP);
2480 sigprocmask(SIG_BLOCK, &mask, &omask);
2481 switch ((pid = fork())) {
2483 sigprocmask(SIG_SETMASK, &omask, 0);
2488 argv[0] = strdup("sh");
2489 argv[1] = strdup("-c");
2490 argv[2] = strdup(prog);
2492 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2498 (void)setsid(); /* Avoid catching SIGHUPs. */
2501 * Throw away pending signals, and reset signal
2502 * behaviour to standard values.
2504 signal(SIGALRM, SIG_IGN);
2505 signal(SIGHUP, SIG_IGN);
2506 sigprocmask(SIG_SETMASK, &omask, 0);
2507 signal(SIGPIPE, SIG_DFL);
2508 signal(SIGQUIT, SIG_DFL);
2509 signal(SIGALRM, SIG_DFL);
2510 signal(SIGHUP, SIG_DFL);
2512 dup2(pfd[0], STDIN_FILENO);
2513 dup2(nulldesc, STDOUT_FILENO);
2514 dup2(nulldesc, STDERR_FILENO);
2515 for (i = getdtablesize(); i > 2; i--)
2518 (void)execvp(_PATH_BSHELL, argv);
2522 sigprocmask(SIG_SETMASK, &omask, 0);
2526 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2527 * supposed to get an EWOULDBLOCK on writev(2), which is
2528 * caught by the logic above anyway, which will in turn close
2529 * the pipe, and fork a new logging subprocess if necessary.
2530 * The stale subprocess will be killed some time later unless
2531 * it terminated itself due to closing its input pipe (so we
2532 * get rid of really dead puppies).
2534 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2536 (void)snprintf(errmsg, sizeof errmsg,
2537 "Warning: cannot change pipe to PID %d to "
2538 "non-blocking behaviour.",
2547 deadq_enter(pid_t pid, const char *name)
2553 * Be paranoid, if we can't signal the process, don't enter it
2554 * into the dead queue (perhaps it's already dead). If possible,
2555 * we try to fetch and log the child's status.
2557 if (kill(pid, 0) != 0) {
2558 if (waitpid(pid, &status, WNOHANG) > 0)
2559 log_deadchild(pid, status, name);
2563 p = malloc(sizeof(struct deadq_entry));
2570 p->dq_timeout = DQ_TIMO_INIT;
2571 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2575 deadq_remove(pid_t pid)
2579 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2580 if (q->dq_pid == pid) {
2581 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2591 log_deadchild(pid_t pid, int status, const char *name)
2597 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2598 if (WIFSIGNALED(status)) {
2599 reason = "due to signal";
2600 code = WTERMSIG(status);
2602 reason = "with status";
2603 code = WEXITSTATUS(status);
2607 (void)snprintf(buf, sizeof buf,
2608 "Logging subprocess %d (%s) exited %s %d.",
2609 pid, name, reason, code);
2614 socksetup(int af, const char *bindhostname)
2616 struct addrinfo hints, *res, *r;
2617 int error, maxs, *s, *socks;
2619 memset(&hints, 0, sizeof(hints));
2620 hints.ai_flags = AI_PASSIVE;
2621 hints.ai_family = af;
2622 hints.ai_socktype = SOCK_DGRAM;
2623 error = getaddrinfo(bindhostname, "syslog", &hints, &res);
2625 logerror(gai_strerror(error));
2630 /* Count max number of sockets we may open */
2631 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2632 socks = malloc((maxs+1) * sizeof(int));
2633 if (socks == NULL) {
2634 logerror("couldn't allocate memory for sockets");
2638 *socks = 0; /* num of sockets counter at start of array */
2640 for (r = res; r; r = r->ai_next) {
2642 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2647 if (r->ai_family == AF_INET6) {
2648 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2649 (char *)&on, sizeof (on)) < 0) {
2650 logerror("setsockopt");
2655 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2656 (char *)&on, sizeof (on)) < 0) {
2657 logerror("setsockopt");
2661 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2689 socklen_t slen, len;
2691 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2693 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen);