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 /* Maximum number of characters in time of last occurrence */
73 #define MAXLINE 1024 /* maximum line length */
74 #define MAXSVLINE MAXLINE /* maximum saved line length */
75 #define DEFUPRI (LOG_USER|LOG_NOTICE)
76 #define DEFSPRI (LOG_KERN|LOG_CRIT)
77 #define TIMERINTVL 30 /* interval for checking flush, mark */
78 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
79 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
81 #include <sys/param.h>
82 #include <sys/ioctl.h>
84 #include <sys/queue.h>
85 #include <sys/resource.h>
86 #include <sys/socket.h>
88 #include <sys/syslimits.h>
93 #include <sys/types.h>
95 #include <netinet/in.h>
97 #include <arpa/inet.h>
111 #include <sysexits.h>
115 #include "pathnames.h"
119 #include <sys/syslog.h>
121 const char *ConfFile = _PATH_LOGCONF;
122 const char *PidFile = _PATH_LOGPID;
123 const char ctty[] = _PATH_CONSOLE;
124 static const char include_str[] = "include";
125 static const char include_ext[] = ".conf";
127 #define dprintf if (Debug) printf
129 #define MAXUNAMES 20 /* maximum number of user names */
133 * We have two default sockets, one with 666 permissions,
134 * and one for privileged programs.
140 STAILQ_ENTRY(funix) next;
142 struct funix funix_secure = { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
144 struct funix funix_default = { -1, _PATH_LOG, DEFFILEMODE,
147 STAILQ_HEAD(, funix) funixes = { &funix_default,
148 &(funix_secure.next.stqe_next) };
154 #define IGN_CONS 0x001 /* don't print on console */
155 #define SYNC_FILE 0x002 /* do fsync on file after printing */
156 #define ADDDATE 0x004 /* add a date to the message */
157 #define MARK 0x008 /* this message is a mark */
158 #define ISKERNEL 0x010 /* kernel generated message */
161 * This structure represents the files that will have log
163 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
164 * or if f_type if F_PIPE and f_pid > 0.
168 struct filed *f_next; /* next in linked list */
169 short f_type; /* entry type, see below */
170 short f_file; /* file descriptor */
171 time_t f_time; /* time this was last written */
172 char *f_host; /* host from which to recd. */
173 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
174 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
178 char *f_program; /* program this applies to */
180 char f_uname[MAXUNAMES][MAXLOGNAME];
182 char f_hname[MAXHOSTNAMELEN];
183 struct addrinfo *f_addr;
185 } f_forw; /* forwarding address */
186 char f_fname[MAXPATHLEN];
188 char f_pname[MAXPATHLEN];
192 char f_prevline[MAXSVLINE]; /* last message logged */
193 char f_lasttime[MAXDATELEN]; /* time of last occurrence */
194 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
195 int f_prevpri; /* pri of f_prevline */
196 int f_prevlen; /* length of f_prevline */
197 int f_prevcount; /* repetition cnt of prevline */
198 u_int f_repeatcount; /* number of "repeated" msgs */
199 int f_flags; /* file-specific flags */
200 #define FFLAG_SYNC 0x01
201 #define FFLAG_NEEDSYNC 0x02
205 * Queue of about-to-be dead processes we should watch out for.
208 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
209 struct stailhead *deadq_headp;
214 TAILQ_ENTRY(deadq_entry) dq_entries;
218 * The timeout to apply to processes waiting on the dead queue. Unit
219 * of measure is `mark intervals', i.e. 20 minutes by default.
220 * Processes on the dead queue will be terminated after that time.
223 #define DQ_TIMO_INIT 2
225 typedef struct deadq_entry *dq_t;
229 * Struct to hold records of network addresses that are allowed to log
237 struct sockaddr_storage addr;
238 struct sockaddr_storage mask;
242 #define a_addr u.numeric.addr
243 #define a_mask u.numeric.mask
244 #define a_name u.name
249 * Intervals at which we flush out "message repeated" messages,
250 * in seconds after previous message is logged. After each flush,
251 * we move to the next interval until we reach the largest.
253 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
254 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
255 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
256 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
257 (f)->f_repeatcount = MAXREPEAT; \
260 /* values for f_type */
261 #define F_UNUSED 0 /* unused entry */
262 #define F_FILE 1 /* regular file */
263 #define F_TTY 2 /* terminal */
264 #define F_CONSOLE 3 /* console terminal */
265 #define F_FORW 4 /* remote machine */
266 #define F_USERS 5 /* list of users */
267 #define F_WALL 6 /* everyone logged on */
268 #define F_PIPE 7 /* pipe to program */
270 const char *TypeNames[8] = {
271 "UNUSED", "FILE", "TTY", "CONSOLE",
272 "FORW", "USERS", "WALL", "PIPE"
275 static struct filed *Files; /* Log files that we write to */
276 static struct filed consfile; /* Console */
278 static int Debug; /* debug flag */
279 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
280 static int resolve = 1; /* resolve hostname */
281 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
282 static const char *LocalDomain; /* our local domain name */
283 static int *finet; /* Internet datagram socket */
284 static int fklog = -1; /* /dev/klog */
285 static int Initialized; /* set when we have initialized ourselves */
286 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
287 static int MarkSeq; /* mark sequence number */
288 static int NoBind; /* don't bind() as suggested by RFC 3164 */
289 static int SecureMode; /* when true, receive only unix domain socks */
291 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
293 static int family = PF_INET; /* protocol family (IPv4 only) */
295 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
296 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
297 static int use_bootfile; /* log entire bootfile for every kern msg */
298 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
299 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
301 static char bootfile[MAXLINE+1]; /* booted kernel file */
303 struct allowedpeer *AllowedPeers; /* List of allowed peers */
304 static int NumAllowed; /* Number of entries in AllowedPeers */
305 static int RemoteAddDate; /* Always set the date on remote messages */
307 static int UniquePriority; /* Only log specified priority? */
308 static int LogFacPri; /* Put facility and priority in log message: */
309 /* 0=no, 1=numeric, 2=names */
310 static int KeepKernFac; /* Keep remotely logged kernel facility */
311 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
312 static struct pidfh *pfh;
314 volatile sig_atomic_t MarkSet, WantDie;
316 static int allowaddr(char *);
317 static void cfline(const char *, struct filed *,
318 const char *, const char *);
319 static const char *cvthname(struct sockaddr *);
320 static void deadq_enter(pid_t, const char *);
321 static int deadq_remove(pid_t);
322 static int decode(const char *, const CODE *);
323 static void die(int);
324 static void dodie(int);
325 static void dofsync(void);
326 static void domark(int);
327 static void fprintlog(struct filed *, int, const char *);
328 static int *socksetup(int, char *);
329 static void init(int);
330 static void logerror(const char *);
331 static void logmsg(int, const char *, const char *, int);
332 static void log_deadchild(pid_t, int, const char *);
333 static void markit(void);
334 static int skip_message(const char *, const char *, int);
335 static void printline(const char *, char *, int);
336 static void printsys(char *);
337 static int p_open(const char *, pid_t *);
338 static void readklog(void);
339 static void reapchild(int);
340 static void usage(void);
341 static int validate(struct sockaddr *, const char *);
342 static void unmapped(struct sockaddr *);
343 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
344 static int waitdaemon(int, int, int);
345 static void timedout(int);
346 static void increase_rcvbuf(int);
349 close_filed(struct filed *f)
352 if (f == NULL || f->f_file == -1)
355 (void)close(f->f_file);
357 f->f_type = F_UNUSED;
361 main(int argc, char *argv[])
363 int ch, i, fdsrmax = 0, l;
364 struct sockaddr_un sunx, fromunix;
365 struct sockaddr_storage frominet;
367 char line[MAXLINE + 1];
370 struct timeval tv, *tvp;
371 struct sigaction sact;
372 struct funix *fx, *fx1;
374 pid_t ppid = 1, spid;
377 if (madvise(NULL, 0, MADV_PROTECT) != 0)
378 dprintf("madvise() failed: %s\n", strerror(errno));
381 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:Fkl:m:nNop:P:sS:Tuv"))
398 case 'a': /* allow specific network addresses only */
399 if (allowaddr(optarg) == -1)
403 bindhostname = optarg;
411 case 'd': /* debug */
414 case 'f': /* configuration file */
417 case 'F': /* run in foreground instead of daemon */
420 case 'k': /* keep remote kern fac */
429 if (optarg[0] == '/') {
432 } else if ((name = strchr(optarg, ':')) != NULL) {
435 errx(1, "socket name must be absolute "
437 if (isdigit(*optarg)) {
438 perml = strtol(optarg, &ep, 8);
439 if (*ep || perml < 0 ||
440 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
441 errx(1, "invalid mode %s, exiting",
443 mode = (mode_t )perml;
445 errx(1, "invalid mode %s, exiting",
447 } else /* doesn't begin with '/', and no ':' */
448 errx(1, "can't parse path %s", optarg);
450 if (strlen(name) >= sizeof(sunx.sun_path))
451 errx(1, "%s path too long, exiting", name);
452 if ((fx = malloc(sizeof(struct funix))) == NULL)
453 errx(1, "malloc failed");
457 STAILQ_INSERT_TAIL(&funixes, fx, next);
460 case 'm': /* mark interval */
461 MarkInterval = atoi(optarg) * 60;
474 if (strlen(optarg) >= sizeof(sunx.sun_path))
475 errx(1, "%s path too long, exiting", optarg);
476 funix_default.name = optarg;
478 case 'P': /* path for alt. PID */
481 case 's': /* no network mode */
484 case 'S': /* path for privileged originator */
485 if (strlen(optarg) >= sizeof(sunx.sun_path))
486 errx(1, "%s path too long, exiting", optarg);
487 funix_secure.name = optarg;
492 case 'u': /* only log specified priority */
495 case 'v': /* log facility and priority */
501 if ((argc -= optind) != 0)
504 pfh = pidfile_open(PidFile, 0600, &spid);
507 errx(1, "syslogd already running, pid: %d", spid);
508 warn("cannot open pid file");
511 if ((!Foreground) && (!Debug)) {
512 ppid = waitdaemon(0, 0, 30);
514 warn("could not become daemon");
525 consfile.f_type = F_CONSOLE;
526 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
527 sizeof(consfile.f_un.f_fname));
528 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
529 (void)signal(SIGTERM, dodie);
530 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
531 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
533 * We don't want the SIGCHLD and SIGHUP handlers to interfere
534 * with each other; they are likely candidates for being called
535 * simultaneously (SIGHUP closes pipe descriptor, process dies,
539 sigaddset(&mask, SIGHUP);
540 sact.sa_handler = reapchild;
542 sact.sa_flags = SA_RESTART;
543 (void)sigaction(SIGCHLD, &sact, NULL);
544 (void)signal(SIGALRM, domark);
545 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
546 (void)alarm(TIMERINTVL);
548 TAILQ_INIT(&deadq_head);
551 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
553 STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
554 (void)unlink(fx->name);
555 memset(&sunx, 0, sizeof(sunx));
556 sunx.sun_family = AF_LOCAL;
557 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
558 fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
560 bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
561 chmod(fx->name, fx->mode) < 0) {
562 (void)snprintf(line, sizeof line,
563 "cannot create %s", fx->name);
565 dprintf("cannot create %s (%d)\n", fx->name, errno);
566 if (fx == &funix_default || fx == &funix_secure)
569 STAILQ_REMOVE(&funixes, fx, funix, next);
573 increase_rcvbuf(fx->s);
576 finet = socksetup(family, bindhostname);
580 for (i = 0; i < *finet; i++) {
581 if (shutdown(finet[i+1], SHUT_RD) < 0 &&
583 logerror("shutdown");
589 dprintf("listening on inet and/or inet6 socket\n");
591 dprintf("sending on inet and/or inet6 socket\n");
594 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
595 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
598 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
600 /* tuck my process id away */
603 dprintf("off & running....\n");
606 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
608 sigaddset(&mask, SIGCHLD);
609 sact.sa_handler = init;
611 sact.sa_flags = SA_RESTART;
612 (void)sigaction(SIGHUP, &sact, NULL);
615 tv.tv_sec = tv.tv_usec = 0;
617 if (fklog != -1 && fklog > fdsrmax)
619 if (finet && !SecureMode) {
620 for (i = 0; i < *finet; i++) {
621 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
622 fdsrmax = finet[i+1];
625 STAILQ_FOREACH(fx, &funixes, next)
629 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
632 errx(1, "calloc fd_set");
640 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
645 if (finet && !SecureMode) {
646 for (i = 0; i < *finet; i++) {
647 if (finet[i+1] != -1)
648 FD_SET(finet[i+1], fdsr);
651 STAILQ_FOREACH(fx, &funixes, next)
654 i = select(fdsrmax+1, fdsr, NULL, NULL,
655 needdofsync ? &tv : tvp);
671 if (fklog != -1 && FD_ISSET(fklog, fdsr))
673 if (finet && !SecureMode) {
674 for (i = 0; i < *finet; i++) {
675 if (FD_ISSET(finet[i+1], fdsr)) {
676 len = sizeof(frominet);
677 l = recvfrom(finet[i+1], line, MAXLINE,
678 0, (struct sockaddr *)&frominet,
682 hname = cvthname((struct sockaddr *)&frominet);
683 unmapped((struct sockaddr *)&frominet);
684 if (validate((struct sockaddr *)&frominet, hname))
685 printline(hname, line, RemoteAddDate ? ADDDATE : 0);
686 } else if (l < 0 && errno != EINTR)
687 logerror("recvfrom inet");
691 STAILQ_FOREACH(fx, &funixes, next) {
692 if (FD_ISSET(fx->s, fdsr)) {
693 len = sizeof(fromunix);
694 l = recvfrom(fx->s, line, MAXLINE, 0,
695 (struct sockaddr *)&fromunix, &len);
698 printline(LocalHostName, line, 0);
699 } else if (l < 0 && errno != EINTR)
700 logerror("recvfrom unix");
709 unmapped(struct sockaddr *sa)
711 struct sockaddr_in6 *sin6;
712 struct sockaddr_in sin4;
714 if (sa->sa_family != AF_INET6)
716 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
717 sizeof(sin4) > sa->sa_len)
719 sin6 = (struct sockaddr_in6 *)sa;
720 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
723 memset(&sin4, 0, sizeof(sin4));
724 sin4.sin_family = AF_INET;
725 sin4.sin_len = sizeof(struct sockaddr_in);
726 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
727 sizeof(sin4.sin_addr));
728 sin4.sin_port = sin6->sin6_port;
730 memcpy(sa, &sin4, sin4.sin_len);
737 fprintf(stderr, "%s\n%s\n%s\n%s\n",
738 "usage: syslogd [-468ACcdFknosTuv] [-a allowed_peer]",
739 " [-b bind_address] [-f config_file]",
740 " [-l [mode:]path] [-m mark_interval]",
741 " [-P pid_file] [-p log_socket]");
746 * Take a raw input line, decode the message, and print the message
747 * on the appropriate log files.
750 printline(const char *hname, char *msg, int flags)
755 char line[MAXLINE + 1];
757 /* test for special codes */
762 n = strtol(p + 1, &q, 10);
763 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
768 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
772 * Don't allow users to log kernel messages.
773 * NOTE: since LOG_KERN == 0 this will also match
774 * messages with no facility specified.
776 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
777 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
781 while ((c = (unsigned char)*p++) != '\0' &&
782 q < &line[sizeof(line) - 4]) {
783 if (mask_C1 && (c & 0x80) && c < 0xA0) {
788 if (isascii(c) && iscntrl(c)) {
791 } else if (c == '\t') {
803 logmsg(pri, line, hname, flags);
807 * Read /dev/klog while data are available, split into lines.
812 char *p, *q, line[MAXLINE + 1];
817 i = read(fklog, line + len, MAXLINE - 1 - len);
819 line[i + len] = '\0';
821 if (i < 0 && errno != EINTR && errno != EAGAIN) {
828 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
833 if (len >= MAXLINE - 1) {
838 memmove(line, p, len + 1);
845 * Take a raw input line from /dev/klog, format similar to syslog().
852 int flags, isprintf, pri;
854 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
860 n = strtol(p + 1, &q, 10);
861 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
868 * Kernel printf's and LOG_CONSOLE messages have been displayed
869 * on the console already.
871 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
873 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
875 logmsg(pri, p, LocalHostName, flags);
881 * Match a program or host name against a specification.
882 * Return a non-0 value if the message must be ignored
883 * based on the specification.
886 skip_message(const char *name, const char *spec, int checkcase)
891 /* Behaviour on explicit match */
906 s = strstr (spec, name);
908 s = strcasestr (spec, name);
911 prev = (s == spec ? ',' : *(s - 1));
912 next = *(s + strlen (name));
914 if (prev == ',' && (next == '\0' || next == ','))
915 /* Explicit match: skip iff the spec is an
920 /* No explicit match for this name: skip the message iff
921 the spec is an inclusive one. */
926 * Log a message to the appropriate log files, users, etc. based on
930 logmsg(int pri, const char *msg, const char *from, int flags)
933 int i, fac, msglen, omask, prilev;
934 const char *timestamp;
935 char prog[NAME_MAX+1];
938 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
939 pri, flags, from, msg);
941 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
944 * Check to see if msg looks non-standard.
946 msglen = strlen(msg);
947 if (msglen < MAXDATELEN || msg[3] != ' ' || msg[6] != ' ' ||
948 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
952 if (flags & ADDDATE) {
953 timestamp = ctime(&now) + 4;
957 msglen -= MAXDATELEN;
960 /* skip leading blanks */
961 while (isspace(*msg)) {
966 /* extract facility and priority level */
968 fac = LOG_NFACILITIES;
972 /* Check maximum facility number. */
973 if (fac > LOG_NFACILITIES) {
974 (void)sigsetmask(omask);
978 prilev = LOG_PRI(pri);
980 /* extract program name */
981 for (i = 0; i < NAME_MAX; i++) {
982 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
983 msg[i] == '/' || isspace(msg[i]))
989 /* add kernel prefix for kernel messages */
990 if (flags & ISKERNEL) {
991 snprintf(buf, sizeof(buf), "%s: %s",
992 use_bootfile ? bootfile : "kernel", msg);
994 msglen = strlen(buf);
997 /* log the message to the particular outputs */
1001 * Open in non-blocking mode to avoid hangs during open
1002 * and close(waiting for the port to drain).
1004 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1006 if (f->f_file >= 0) {
1007 (void)strlcpy(f->f_lasttime, timestamp,
1008 sizeof(f->f_lasttime));
1009 fprintlog(f, flags, msg);
1013 (void)sigsetmask(omask);
1016 for (f = Files; f; f = f->f_next) {
1017 /* skip messages that are incorrect priority */
1018 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1019 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1020 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1022 || f->f_pmask[fac] == INTERNAL_NOPRI)
1025 /* skip messages with the incorrect hostname */
1026 if (skip_message(from, f->f_host, 0))
1029 /* skip messages with the incorrect program name */
1030 if (skip_message(prog, f->f_program, 1))
1033 /* skip message to console if it has already been printed */
1034 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1037 /* don't output marks to recently written files */
1038 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1042 * suppress duplicate lines to this file
1044 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1045 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1046 !strcmp(msg, f->f_prevline) &&
1047 !strcasecmp(from, f->f_prevhost)) {
1048 (void)strlcpy(f->f_lasttime, timestamp,
1049 sizeof(f->f_lasttime));
1051 dprintf("msg repeated %d times, %ld sec of %d\n",
1052 f->f_prevcount, (long)(now - f->f_time),
1053 repeatinterval[f->f_repeatcount]);
1055 * If domark would have logged this by now,
1056 * flush it now (so we don't hold isolated messages),
1057 * but back off so we'll flush less often
1060 if (now > REPEATTIME(f)) {
1061 fprintlog(f, flags, (char *)NULL);
1065 /* new line, save it */
1067 fprintlog(f, 0, (char *)NULL);
1068 f->f_repeatcount = 0;
1070 (void)strlcpy(f->f_lasttime, timestamp,
1071 sizeof(f->f_lasttime));
1072 (void)strlcpy(f->f_prevhost, from,
1073 sizeof(f->f_prevhost));
1074 if (msglen < MAXSVLINE) {
1075 f->f_prevlen = msglen;
1076 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1077 fprintlog(f, flags, (char *)NULL);
1079 f->f_prevline[0] = 0;
1081 fprintlog(f, flags, msg);
1085 (void)sigsetmask(omask);
1093 for (f = Files; f; f = f->f_next) {
1094 if ((f->f_type == F_FILE) &&
1095 (f->f_flags & FFLAG_NEEDSYNC)) {
1096 f->f_flags &= ~FFLAG_NEEDSYNC;
1097 (void)fsync(f->f_file);
1104 fprintlog(struct filed *f, int flags, const char *msg)
1106 struct iovec iov[IOV_SIZE];
1109 int i, l, lsent = 0;
1110 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1111 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1115 if (f->f_type == F_WALL) {
1116 v->iov_base = greetings;
1117 /* The time displayed is not synchornized with the other log
1118 * destinations (like messages). Following fragment was using
1119 * ctime(&now), which was updating the time every 30 sec.
1120 * With f_lasttime, time is synchronized correctly.
1122 v->iov_len = snprintf(greetings, sizeof greetings,
1123 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1124 f->f_prevhost, f->f_lasttime);
1125 if (v->iov_len >= sizeof greetings)
1126 v->iov_len = sizeof greetings - 1;
1132 v->iov_base = f->f_lasttime;
1133 v->iov_len = strlen(f->f_lasttime);
1135 v->iov_base = space;
1141 static char fp_buf[30]; /* Hollow laugh */
1142 int fac = f->f_prevpri & LOG_FACMASK;
1143 int pri = LOG_PRI(f->f_prevpri);
1144 const char *f_s = NULL;
1145 char f_n[5]; /* Hollow laugh */
1146 const char *p_s = NULL;
1147 char p_n[5]; /* Hollow laugh */
1149 if (LogFacPri > 1) {
1152 for (c = facilitynames; c->c_name; c++) {
1153 if (c->c_val == fac) {
1158 for (c = prioritynames; c->c_name; c++) {
1159 if (c->c_val == pri) {
1166 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1170 snprintf(p_n, sizeof p_n, "%d", pri);
1173 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1174 v->iov_base = fp_buf;
1175 v->iov_len = strlen(fp_buf);
1182 v->iov_base = f->f_prevhost;
1183 v->iov_len = strlen(v->iov_base);
1185 v->iov_base = space;
1190 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1196 v->iov_len = strlen(msg);
1197 } else if (f->f_prevcount > 1) {
1198 v->iov_base = repbuf;
1199 v->iov_len = snprintf(repbuf, sizeof repbuf,
1200 "last message repeated %d times", f->f_prevcount);
1202 v->iov_base = f->f_prevline;
1203 v->iov_len = f->f_prevlen;
1207 dprintf("Logging to %s", TypeNames[f->f_type]);
1210 switch (f->f_type) {
1217 port = (int)ntohs(((struct sockaddr_in *)
1218 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1220 dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1222 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1224 /* check for local vs remote messages */
1225 if (strcasecmp(f->f_prevhost, LocalHostName))
1226 l = snprintf(line, sizeof line - 1,
1227 "<%d>%.15s Forwarded from %s: %s",
1228 f->f_prevpri, (char *)iov[0].iov_base,
1229 f->f_prevhost, (char *)iov[5].iov_base);
1231 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1232 f->f_prevpri, (char *)iov[0].iov_base,
1233 (char *)iov[5].iov_base);
1236 else if (l > MAXLINE)
1240 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1241 for (i = 0; i < *finet; i++) {
1244 * should we check AF first, or just
1245 * trial and error? FWD
1248 address_family_of(finet[i+1]))
1250 lsent = sendto(finet[i+1], line, l, 0,
1251 r->ai_addr, r->ai_addrlen);
1255 if (lsent == l && !send_to_all)
1258 dprintf("lsent/l: %d/%d\n", lsent, l);
1273 /* case ENOTSOCK: */
1275 /* case EMSGSIZE: */
1278 /* case ECONNREFUSED: */
1280 dprintf("removing entry: errno=%d\n", e);
1281 f->f_type = F_UNUSED;
1289 dprintf(" %s\n", f->f_un.f_fname);
1292 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1294 * If writev(2) fails for potentially transient errors
1295 * like the filesystem being full, ignore it.
1296 * Otherwise remove this logfile from the list.
1298 if (errno != ENOSPC) {
1302 logerror(f->f_un.f_fname);
1304 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1305 f->f_flags |= FFLAG_NEEDSYNC;
1311 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1314 if (f->f_un.f_pipe.f_pid == 0) {
1315 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1316 &f->f_un.f_pipe.f_pid)) < 0) {
1317 f->f_type = F_UNUSED;
1318 logerror(f->f_un.f_pipe.f_pname);
1322 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1325 if (f->f_un.f_pipe.f_pid > 0)
1326 deadq_enter(f->f_un.f_pipe.f_pid,
1327 f->f_un.f_pipe.f_pname);
1328 f->f_un.f_pipe.f_pid = 0;
1330 logerror(f->f_un.f_pipe.f_pname);
1335 if (flags & IGN_CONS) {
1336 dprintf(" (ignored)\n");
1342 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1346 errno = 0; /* ttymsg() only sometimes returns an errno */
1347 if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1348 f->f_type = F_UNUSED;
1358 wallmsg(f, iov, IOV_SIZE);
1366 * WALLMSG -- Write a message to the world at large
1368 * Write the specified message to either the entire
1369 * world, or a list of approved users.
1372 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1374 static int reenter; /* avoid calling ourselves */
1383 while ((ut = getutxent()) != NULL) {
1384 if (ut->ut_type != USER_PROCESS)
1386 if (f->f_type == F_WALL) {
1387 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1388 TTYMSGTIME)) != NULL) {
1389 errno = 0; /* already in msg */
1394 /* should we send the message to this user? */
1395 for (i = 0; i < MAXUNAMES; i++) {
1396 if (!f->f_un.f_uname[i][0])
1398 if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1399 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1400 TTYMSGTIME)) != NULL) {
1401 errno = 0; /* already in msg */
1413 reapchild(int signo __unused)
1419 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1421 /* Don't tell while we are initting. */
1424 /* First, look if it's a process from the dead queue. */
1425 if (deadq_remove(pid))
1428 /* Now, look in list of active processes. */
1429 for (f = Files; f; f = f->f_next)
1430 if (f->f_type == F_PIPE &&
1431 f->f_un.f_pipe.f_pid == pid) {
1433 f->f_un.f_pipe.f_pid = 0;
1434 log_deadchild(pid, status,
1435 f->f_un.f_pipe.f_pname);
1444 * Return a printable representation of a host address.
1447 cvthname(struct sockaddr *f)
1450 sigset_t omask, nmask;
1451 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1453 error = getnameinfo((struct sockaddr *)f,
1454 ((struct sockaddr *)f)->sa_len,
1455 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1456 dprintf("cvthname(%s)\n", ip);
1459 dprintf("Malformed from address %s\n", gai_strerror(error));
1465 sigemptyset(&nmask);
1466 sigaddset(&nmask, SIGHUP);
1467 sigprocmask(SIG_BLOCK, &nmask, &omask);
1468 error = getnameinfo((struct sockaddr *)f,
1469 ((struct sockaddr *)f)->sa_len,
1470 hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1471 sigprocmask(SIG_SETMASK, &omask, NULL);
1473 dprintf("Host name for your address (%s) unknown\n", ip);
1477 if (hl > 0 && hname[hl-1] == '.')
1479 trimdomain(hname, hl);
1491 domark(int signo __unused)
1498 * Print syslogd errors some place.
1501 logerror(const char *type)
1504 static int recursed = 0;
1506 /* If there's an error while trying to log an error, give up. */
1512 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1514 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1516 dprintf("%s\n", buf);
1517 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1526 int was_initialized;
1529 was_initialized = Initialized;
1530 Initialized = 0; /* Don't log SIGCHLDs. */
1531 for (f = Files; f != NULL; f = f->f_next) {
1532 /* flush any pending output */
1534 fprintlog(f, 0, (char *)NULL);
1535 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1537 f->f_un.f_pipe.f_pid = 0;
1540 Initialized = was_initialized;
1542 dprintf("syslogd: exiting on signal %d\n", signo);
1543 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1547 STAILQ_FOREACH(fx, &funixes, next)
1548 (void)unlink(fx->name);
1549 pidfile_remove(pfh);
1555 configfiles(const struct dirent *dp)
1560 if (dp->d_name[0] == '.')
1563 ext_len = sizeof(include_ext) -1;
1565 if (dp->d_namlen <= ext_len)
1568 p = &dp->d_name[dp->d_namlen - ext_len];
1569 if (strcmp(p, include_ext) != 0)
1576 readconfigfile(FILE *cf, struct filed **nextp, int allow_includes)
1580 struct dirent **ent;
1581 char cline[LINE_MAX];
1582 char host[MAXHOSTNAMELEN];
1583 char prog[LINE_MAX];
1584 char file[MAXPATHLEN];
1590 * Foreach line in the conf table, open that file.
1593 include_len = sizeof(include_str) -1;
1594 (void)strlcpy(host, "*", sizeof(host));
1595 (void)strlcpy(prog, "*", sizeof(prog));
1596 while (fgets(cline, sizeof(cline), cf) != NULL) {
1598 * check for end-of-section, comments, strip off trailing
1599 * spaces and newline character. #!prog is treated specially:
1600 * following lines apply only to that program.
1602 for (p = cline; isspace(*p); ++p)
1606 if (allow_includes &&
1607 strncmp(p, include_str, include_len) == 0 &&
1608 isspace(p[include_len])) {
1613 while (*tmp != '\0' && !isspace(*tmp))
1616 dprintf("Trying to include files in '%s'\n", p);
1617 nents = scandir(p, &ent, configfiles, alphasort);
1619 dprintf("Unable to open '%s': %s\n", p,
1623 for (i = 0; i < nents; i++) {
1624 if (snprintf(file, sizeof(file), "%s/%s", p,
1625 ent[i]->d_name) >= (int)sizeof(file)) {
1626 dprintf("ignoring path too long: "
1627 "'%s/%s'\n", p, ent[i]->d_name);
1632 cf2 = fopen(file, "r");
1635 dprintf("reading %s\n", file);
1636 readconfigfile(cf2, nextp, 0);
1644 if (*p != '!' && *p != '+' && *p != '-')
1647 if (*p == '+' || *p == '-') {
1651 if ((!*p) || (*p == '*')) {
1652 (void)strlcpy(host, "*", sizeof(host));
1657 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1658 if (!isalnum(*p) && *p != '.' && *p != '-'
1659 && *p != ',' && *p != ':' && *p != '%')
1668 while (isspace(*p)) p++;
1669 if ((!*p) || (*p == '*')) {
1670 (void)strlcpy(prog, "*", sizeof(prog));
1673 for (i = 0; i < LINE_MAX - 1; i++) {
1674 if (!isprint(p[i]) || isspace(p[i]))
1681 for (p = cline + 1; *p != '\0'; p++) {
1684 if (*(p - 1) == '\\') {
1692 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1694 f = (struct filed *)calloc(1, sizeof(*f));
1701 cfline(cline, f, prog, host);
1706 * INIT -- Initialize syslogd from configuration table
1713 struct filed *f, *next, **nextp;
1715 char oldLocalHostName[MAXHOSTNAMELEN];
1716 char hostMsg[2*MAXHOSTNAMELEN+40];
1717 char bootfileMsg[LINE_MAX];
1722 * Load hostname (may have changed).
1725 (void)strlcpy(oldLocalHostName, LocalHostName,
1726 sizeof(oldLocalHostName));
1727 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1728 err(EX_OSERR, "gethostname() failed");
1729 if ((p = strchr(LocalHostName, '.')) != NULL) {
1737 * Close all open log files.
1740 for (f = Files; f != NULL; f = next) {
1741 /* flush any pending output */
1743 fprintlog(f, 0, (char *)NULL);
1745 switch (f->f_type) {
1753 if (f->f_un.f_pipe.f_pid > 0) {
1755 deadq_enter(f->f_un.f_pipe.f_pid,
1756 f->f_un.f_pipe.f_pname);
1758 f->f_un.f_pipe.f_pid = 0;
1762 if (f->f_program) free(f->f_program);
1763 if (f->f_host) free(f->f_host);
1768 /* open the configuration file */
1769 if ((cf = fopen(ConfFile, "r")) == NULL) {
1770 dprintf("cannot open %s\n", ConfFile);
1771 *nextp = (struct filed *)calloc(1, sizeof(*f));
1772 if (*nextp == NULL) {
1776 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1777 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1778 if ((*nextp)->f_next == NULL) {
1782 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1787 readconfigfile(cf, &Files, 1);
1789 /* close the configuration file */
1796 for (f = Files; f; f = f->f_next) {
1797 for (i = 0; i <= LOG_NFACILITIES; i++)
1798 if (f->f_pmask[i] == INTERNAL_NOPRI)
1801 printf("%d ", f->f_pmask[i]);
1802 printf("%s: ", TypeNames[f->f_type]);
1803 switch (f->f_type) {
1805 printf("%s", f->f_un.f_fname);
1810 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1814 port = (int)ntohs(((struct sockaddr_in *)
1815 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1818 f->f_un.f_forw.f_hname, port);
1820 printf("%s", f->f_un.f_forw.f_hname);
1825 printf("%s", f->f_un.f_pipe.f_pname);
1829 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1830 printf("%s, ", f->f_un.f_uname[i]);
1834 printf(" (%s)", f->f_program);
1839 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1840 dprintf("syslogd: restarted\n");
1842 * Log a change in hostname, but only on a restart.
1844 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1845 (void)snprintf(hostMsg, sizeof(hostMsg),
1846 "syslogd: hostname changed, \"%s\" to \"%s\"",
1847 oldLocalHostName, LocalHostName);
1848 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1849 dprintf("%s\n", hostMsg);
1852 * Log the kernel boot file if we aren't going to use it as
1853 * the prefix, and if this is *not* a restart.
1855 if (signo == 0 && !use_bootfile) {
1856 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1857 "syslogd: kernel boot file is %s", bootfile);
1858 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1859 dprintf("%s\n", bootfileMsg);
1864 * Crack a configuration file line
1867 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1869 struct addrinfo hints, *res;
1870 int error, i, pri, syncfile;
1873 char buf[MAXLINE], ebuf[100];
1875 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1877 errno = 0; /* keep strerror() stuff out of logerror messages */
1879 /* clear out file entry */
1880 memset(f, 0, sizeof(*f));
1881 for (i = 0; i <= LOG_NFACILITIES; i++)
1882 f->f_pmask[i] = INTERNAL_NOPRI;
1884 /* save hostname if any */
1885 if (host && *host == '*')
1890 f->f_host = strdup(host);
1891 if (f->f_host == NULL) {
1895 hl = strlen(f->f_host);
1896 if (hl > 0 && f->f_host[hl-1] == '.')
1897 f->f_host[--hl] = '\0';
1898 trimdomain(f->f_host, hl);
1901 /* save program name if any */
1902 if (prog && *prog == '*')
1905 f->f_program = strdup(prog);
1906 if (f->f_program == NULL) {
1912 /* scan through the list of selectors */
1913 for (p = line; *p && *p != '\t' && *p != ' ';) {
1918 /* find the end of this facility name list */
1919 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1922 /* get the priority comparison */
1950 /* collect priority name */
1951 for (bp = buf; *q && !strchr("\t,; ", *q); )
1956 while (strchr(",;", *q))
1959 /* decode priority name */
1962 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1964 /* Ignore trailing spaces. */
1965 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1968 pri = decode(buf, prioritynames);
1971 (void)snprintf(ebuf, sizeof ebuf,
1972 "unknown priority name \"%s\"", buf);
1978 pri_cmp = (UniquePriority)
1983 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1985 /* scan facilities */
1986 while (*p && !strchr("\t.; ", *p)) {
1987 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1992 for (i = 0; i < LOG_NFACILITIES; i++) {
1993 f->f_pmask[i] = pri;
1994 f->f_pcmp[i] = pri_cmp;
1997 i = decode(buf, facilitynames);
2000 (void)snprintf(ebuf, sizeof ebuf,
2001 "unknown facility name \"%s\"",
2006 f->f_pmask[i >> 3] = pri;
2007 f->f_pcmp[i >> 3] = pri_cmp;
2009 while (*p == ',' || *p == ' ')
2016 /* skip to action part */
2017 while (*p == '\t' || *p == ' ')
2032 * scan forward to see if there is a port defined.
2033 * so we can't use strlcpy..
2035 i = sizeof(f->f_un.f_forw.f_hname);
2036 tp = f->f_un.f_forw.f_hname;
2040 * an ipv6 address should start with a '[' in that case
2041 * we should scan for a ']'
2047 while (*p && (*p != endkey) && (i-- > 0)) {
2050 if (endkey == ']' && *p == endkey)
2054 /* See if we copied a domain and have a port */
2060 memset(&hints, 0, sizeof(hints));
2061 hints.ai_family = family;
2062 hints.ai_socktype = SOCK_DGRAM;
2063 error = getaddrinfo(f->f_un.f_forw.f_hname,
2064 p ? p : "syslog", &hints, &res);
2066 logerror(gai_strerror(error));
2069 f->f_un.f_forw.f_addr = res;
2074 if ((f->f_file = open(p, logflags, 0600)) < 0) {
2075 f->f_type = F_UNUSED;
2080 f->f_flags |= FFLAG_SYNC;
2081 if (isatty(f->f_file)) {
2082 if (strcmp(p, ctty) == 0)
2083 f->f_type = F_CONSOLE;
2086 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
2087 sizeof(f->f_un.f_fname));
2089 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2095 f->f_un.f_pipe.f_pid = 0;
2096 (void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2097 sizeof(f->f_un.f_pipe.f_pname));
2106 for (i = 0; i < MAXUNAMES && *p; i++) {
2107 for (q = p; *q && *q != ','; )
2109 (void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2110 if ((q - p) >= MAXLOGNAME)
2111 f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2113 f->f_un.f_uname[i][q - p] = '\0';
2114 while (*q == ',' || *q == ' ')
2118 f->f_type = F_USERS;
2125 * Decode a symbolic name to a numeric value
2128 decode(const char *name, const CODE *codetab)
2134 return (atoi(name));
2136 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2138 *p = tolower(*name);
2143 for (c = codetab; c->c_name; c++)
2144 if (!strcmp(buf, c->c_name))
2156 now = time((time_t *)NULL);
2157 MarkSeq += TIMERINTVL;
2158 if (MarkSeq >= MarkInterval) {
2159 logmsg(LOG_INFO, "-- MARK --",
2160 LocalHostName, ADDDATE|MARK);
2164 for (f = Files; f; f = f->f_next) {
2165 if (f->f_prevcount && now >= REPEATTIME(f)) {
2166 dprintf("flush %s: repeated %d times, %d sec.\n",
2167 TypeNames[f->f_type], f->f_prevcount,
2168 repeatinterval[f->f_repeatcount]);
2169 fprintlog(f, 0, (char *)NULL);
2174 /* Walk the dead queue, and see if we should signal somebody. */
2175 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2176 next = TAILQ_NEXT(q, dq_entries);
2178 switch (q->dq_timeout) {
2180 /* Already signalled once, try harder now. */
2181 if (kill(q->dq_pid, SIGKILL) != 0)
2182 (void)deadq_remove(q->dq_pid);
2187 * Timed out on dead queue, send terminate
2188 * signal. Note that we leave the removal
2189 * from the dead queue to reapchild(), which
2190 * will also log the event (unless the process
2191 * didn't even really exist, in case we simply
2192 * drop it from the dead queue).
2194 if (kill(q->dq_pid, SIGTERM) != 0)
2195 (void)deadq_remove(q->dq_pid);
2203 (void)alarm(TIMERINTVL);
2207 * fork off and become a daemon, but wait for the child to come online
2208 * before returning to the parent, or we get disk thrashing at boot etc.
2209 * Set a timer so we don't hang forever if it wedges.
2212 waitdaemon(int nochdir, int noclose, int maxwait)
2216 pid_t pid, childpid;
2218 switch (childpid = fork()) {
2224 signal(SIGALRM, timedout);
2226 while ((pid = wait3(&status, 0, NULL)) != -1) {
2227 if (WIFEXITED(status))
2228 errx(1, "child pid %d exited with return code %d",
2229 pid, WEXITSTATUS(status));
2230 if (WIFSIGNALED(status))
2231 errx(1, "child pid %d exited on signal %d%s",
2232 pid, WTERMSIG(status),
2233 WCOREDUMP(status) ? " (core dumped)" :
2235 if (pid == childpid) /* it's gone... */
2247 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2248 (void)dup2(fd, STDIN_FILENO);
2249 (void)dup2(fd, STDOUT_FILENO);
2250 (void)dup2(fd, STDERR_FILENO);
2258 * We get a SIGALRM from the child when it's running and finished doing it's
2259 * fsync()'s or O_SYNC writes for all the boot messages.
2261 * We also get a signal from the kernel if the timer expires, so check to
2262 * see what happened.
2265 timedout(int sig __unused)
2269 signal(SIGALRM, SIG_DFL);
2271 errx(1, "timed out waiting for child");
2277 * Add `s' to the list of allowable peer addresses to accept messages
2280 * `s' is a string in the form:
2282 * [*]domainname[:{servicename|portnumber|*}]
2286 * netaddr/maskbits[:{servicename|portnumber|*}]
2288 * Returns -1 on error, 0 if the argument was valid.
2294 struct allowedpeer ap;
2297 struct addrinfo hints, *res;
2298 struct in_addr *addrp, *maskp;
2301 u_int32_t *addr6p, *mask6p;
2303 char ip[NI_MAXHOST];
2306 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2309 if ((cp1 = strrchr(cp1, ':'))) {
2310 /* service/port provided */
2312 if (strlen(cp1) == 1 && *cp1 == '*')
2313 /* any port allowed */
2315 else if ((se = getservbyname(cp1, "udp"))) {
2316 ap.port = ntohs(se->s_port);
2318 ap.port = strtol(cp1, &cp2, 0);
2320 return (-1); /* port not numeric */
2323 if ((se = getservbyname("syslog", "udp")))
2324 ap.port = ntohs(se->s_port);
2326 /* sanity, should not happen */
2330 if ((cp1 = strchr(s, '/')) != NULL &&
2331 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2333 if ((masklen = atoi(cp1 + 1)) < 0)
2338 cp2 = s + strlen(s) - 1;
2349 memset(&hints, 0, sizeof(hints));
2350 hints.ai_family = PF_UNSPEC;
2351 hints.ai_socktype = SOCK_DGRAM;
2352 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2353 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2355 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2356 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2357 ap.a_mask.ss_family = res->ai_family;
2358 if (res->ai_family == AF_INET) {
2359 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2360 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2361 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2363 /* use default netmask */
2364 if (IN_CLASSA(ntohl(addrp->s_addr)))
2365 maskp->s_addr = htonl(IN_CLASSA_NET);
2366 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2367 maskp->s_addr = htonl(IN_CLASSB_NET);
2369 maskp->s_addr = htonl(IN_CLASSC_NET);
2370 } else if (masklen <= 32) {
2371 /* convert masklen to netmask */
2375 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2380 /* Lose any host bits in the network number. */
2381 addrp->s_addr &= maskp->s_addr;
2384 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2385 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2388 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2389 /* convert masklen to netmask */
2390 while (masklen > 0) {
2392 *mask6p = htonl(~(0xffffffff >> masklen));
2395 *mask6p++ = 0xffffffff;
2398 /* Lose any host bits in the network number. */
2399 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2400 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2401 for (i = 0; i < 4; i++)
2402 addr6p[i] &= mask6p[i];
2411 /* arg `s' is domain name */
2425 printf("allowaddr: rule %d: ", NumAllowed);
2427 printf("numeric, ");
2428 getnameinfo((struct sockaddr *)&ap.a_addr,
2429 ((struct sockaddr *)&ap.a_addr)->sa_len,
2430 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2431 printf("addr = %s, ", ip);
2432 getnameinfo((struct sockaddr *)&ap.a_mask,
2433 ((struct sockaddr *)&ap.a_mask)->sa_len,
2434 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2435 printf("mask = %s; ", ip);
2437 printf("domainname = %s; ", ap.a_name);
2439 printf("port = %d\n", ap.port);
2442 if ((AllowedPeers = realloc(AllowedPeers,
2443 ++NumAllowed * sizeof(struct allowedpeer)))
2445 logerror("realloc");
2448 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2453 * Validate that the remote peer has permission to log to us.
2456 validate(struct sockaddr *sa, const char *hname)
2460 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2461 struct allowedpeer *ap;
2462 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2465 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2467 struct addrinfo hints, *res;
2470 if (NumAllowed == 0)
2471 /* traditional behaviour, allow everything */
2474 (void)strlcpy(name, hname, sizeof(name));
2475 memset(&hints, 0, sizeof(hints));
2476 hints.ai_family = PF_UNSPEC;
2477 hints.ai_socktype = SOCK_DGRAM;
2478 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2479 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2481 else if (strchr(name, '.') == NULL) {
2482 strlcat(name, ".", sizeof name);
2483 strlcat(name, LocalDomain, sizeof name);
2485 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2486 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2487 return (0); /* for safety, should not occur */
2488 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2492 /* now, walk down the list */
2493 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2494 if (ap->port != 0 && ap->port != sport) {
2495 dprintf("rejected in rule %d due to port mismatch.\n", i);
2499 if (ap->isnumeric) {
2500 if (ap->a_addr.ss_family != sa->sa_family) {
2501 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2504 if (ap->a_addr.ss_family == AF_INET) {
2505 sin4 = (struct sockaddr_in *)sa;
2506 a4p = (struct sockaddr_in *)&ap->a_addr;
2507 m4p = (struct sockaddr_in *)&ap->a_mask;
2508 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2509 != a4p->sin_addr.s_addr) {
2510 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2515 else if (ap->a_addr.ss_family == AF_INET6) {
2516 sin6 = (struct sockaddr_in6 *)sa;
2517 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2518 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2519 if (a6p->sin6_scope_id != 0 &&
2520 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2521 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2525 for (j = 0; j < 16; j += 4) {
2526 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2527 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2533 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2544 /* allow wildmatch */
2547 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2548 dprintf("rejected in rule %d due to name mismatch.\n", i);
2554 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2555 dprintf("rejected in rule %d due to name mismatch.\n", i);
2560 dprintf("accepted in rule %d.\n", i);
2561 return (1); /* hooray! */
2567 * Fairly similar to popen(3), but returns an open descriptor, as
2568 * opposed to a FILE *.
2571 p_open(const char *prog, pid_t *rpid)
2573 int pfd[2], nulldesc;
2575 sigset_t omask, mask;
2576 char *argv[4]; /* sh -c cmd NULL */
2579 if (pipe(pfd) == -1)
2581 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2582 /* we are royally screwed anyway */
2586 sigaddset(&mask, SIGALRM);
2587 sigaddset(&mask, SIGHUP);
2588 sigprocmask(SIG_BLOCK, &mask, &omask);
2589 switch ((pid = fork())) {
2591 sigprocmask(SIG_SETMASK, &omask, 0);
2596 argv[0] = strdup("sh");
2597 argv[1] = strdup("-c");
2598 argv[2] = strdup(prog);
2600 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2606 (void)setsid(); /* Avoid catching SIGHUPs. */
2609 * Throw away pending signals, and reset signal
2610 * behaviour to standard values.
2612 signal(SIGALRM, SIG_IGN);
2613 signal(SIGHUP, SIG_IGN);
2614 sigprocmask(SIG_SETMASK, &omask, 0);
2615 signal(SIGPIPE, SIG_DFL);
2616 signal(SIGQUIT, SIG_DFL);
2617 signal(SIGALRM, SIG_DFL);
2618 signal(SIGHUP, SIG_DFL);
2620 dup2(pfd[0], STDIN_FILENO);
2621 dup2(nulldesc, STDOUT_FILENO);
2622 dup2(nulldesc, STDERR_FILENO);
2625 (void)execvp(_PATH_BSHELL, argv);
2629 sigprocmask(SIG_SETMASK, &omask, 0);
2633 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2634 * supposed to get an EWOULDBLOCK on writev(2), which is
2635 * caught by the logic above anyway, which will in turn close
2636 * the pipe, and fork a new logging subprocess if necessary.
2637 * The stale subprocess will be killed some time later unless
2638 * it terminated itself due to closing its input pipe (so we
2639 * get rid of really dead puppies).
2641 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2643 (void)snprintf(errmsg, sizeof errmsg,
2644 "Warning: cannot change pipe to PID %d to "
2645 "non-blocking behaviour.",
2654 deadq_enter(pid_t pid, const char *name)
2660 * Be paranoid, if we can't signal the process, don't enter it
2661 * into the dead queue (perhaps it's already dead). If possible,
2662 * we try to fetch and log the child's status.
2664 if (kill(pid, 0) != 0) {
2665 if (waitpid(pid, &status, WNOHANG) > 0)
2666 log_deadchild(pid, status, name);
2670 p = malloc(sizeof(struct deadq_entry));
2677 p->dq_timeout = DQ_TIMO_INIT;
2678 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2682 deadq_remove(pid_t pid)
2686 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2687 if (q->dq_pid == pid) {
2688 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2698 log_deadchild(pid_t pid, int status, const char *name)
2704 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2705 if (WIFSIGNALED(status)) {
2706 reason = "due to signal";
2707 code = WTERMSIG(status);
2709 reason = "with status";
2710 code = WEXITSTATUS(status);
2714 (void)snprintf(buf, sizeof buf,
2715 "Logging subprocess %d (%s) exited %s %d.",
2716 pid, name, reason, code);
2721 socksetup(int af, char *bindhostname)
2723 struct addrinfo hints, *res, *r;
2724 const char *bindservice;
2726 int error, maxs, *s, *socks;
2729 * We have to handle this case for backwards compatibility:
2730 * If there are two (or more) colons but no '[' and ']',
2731 * assume this is an inet6 address without a service.
2733 bindservice = "syslog";
2734 if (bindhostname != NULL) {
2736 if (*bindhostname == '[' &&
2737 (cp = strchr(bindhostname + 1, ']')) != NULL) {
2740 if (cp[1] == ':' && cp[2] != '\0')
2741 bindservice = cp + 2;
2744 cp = strchr(bindhostname, ':');
2745 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2748 bindservice = cp + 1;
2749 if (cp == bindhostname)
2750 bindhostname = NULL;
2757 memset(&hints, 0, sizeof(hints));
2758 hints.ai_flags = AI_PASSIVE;
2759 hints.ai_family = af;
2760 hints.ai_socktype = SOCK_DGRAM;
2761 error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2763 logerror(gai_strerror(error));
2768 /* Count max number of sockets we may open */
2769 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2770 socks = malloc((maxs+1) * sizeof(int));
2771 if (socks == NULL) {
2772 logerror("couldn't allocate memory for sockets");
2776 *socks = 0; /* num of sockets counter at start of array */
2778 for (r = res; r; r = r->ai_next) {
2780 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2786 if (r->ai_family == AF_INET6) {
2787 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2788 (char *)&on, sizeof (on)) < 0) {
2789 logerror("setsockopt");
2795 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2796 (char *)&on, sizeof (on)) < 0) {
2797 logerror("setsockopt");
2802 * RFC 3164 recommends that client side message
2803 * should come from the privileged syslogd port.
2805 * If the system administrator choose not to obey
2806 * this, we can skip the bind() step so that the
2807 * system will choose a port for us.
2810 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2817 increase_rcvbuf(*s);
2838 increase_rcvbuf(int fd)
2840 socklen_t len, slen;
2844 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2845 if (len < RCVBUF_MINSIZE) {
2846 len = RCVBUF_MINSIZE;
2847 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));