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
29 * @(#)syslogd.c 8.3 (Berkeley) 4/4/94
30 * $FreeBSD: src/usr.sbin/syslogd/syslogd.c,v 1.163 2008/12/19 18:27:51 delphij Exp $
31 * $DragonFly: src/usr.sbin/syslogd/syslogd.c,v 1.6 2007/08/09 02:17:46 dillon Exp $
35 * syslogd -- log system messages
37 * This program implements a system log. It takes a series of lines.
38 * Each line may have a priority, signified as "<n>" as
39 * the first characters of the line. If this is
40 * not present, a default priority is used.
42 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
43 * cause it to reread its configuration file.
47 * MAXLINE -- the maximum line length that can be handled.
48 * DEFUPRI -- the default priority for user messages
49 * DEFSPRI -- the default priority for kernel messages
52 * extensive changes by Ralph Campbell
53 * more extensive changes by Eric Allman (again)
54 * Extension to log by program name as well as facility and priority
56 * -u and -v by Harlan Stenn.
57 * Priority comparison code by Harlan Stenn.
58 * Ring buffer code by Jeff Wheelhouse.
61 #define MAXLINE 1024 /* maximum line length */
62 #define MAXSVLINE 120 /* maximum saved line length */
63 #define DEFUPRI (LOG_USER|LOG_NOTICE)
64 #define DEFSPRI (LOG_KERN|LOG_CRIT)
65 #define TIMERINTVL 30 /* interval for checking flush, mark */
66 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
68 #include <sys/param.h>
69 #include <sys/ioctl.h>
72 #include <sys/socket.h>
73 #include <sys/queue.h>
77 #include <sys/resource.h>
78 #include <sys/syslimits.h>
80 #include <sys/types.h>
82 #include <netinet/in.h>
84 #include <arpa/inet.h>
99 #include "utmpentry.h"
101 #include "pathnames.h"
103 #include "../clog/clog.h"
104 #include "../nscd/pidfile.h"
107 #include <sys/syslog.h>
109 const char *ConfFile
= _PATH_LOGCONF
;
110 const char *PidFile
= _PATH_LOGPID
;
111 const char ctty
[] = _PATH_CONSOLE
;
112 const char ring_magic
[] = "CLOG";
114 #define dprintf if (Debug) printf
116 #define MAXUNAMES 20 /* maximum number of user names */
120 * We have two default sockets, one with 666 permissions,
121 * and one for privileged programs.
127 STAILQ_ENTRY(funix
) next
;
129 struct funix funix_secure
= { -1, _PATH_LOG_PRIV
, S_IRUSR
| S_IWUSR
,
131 struct funix funix_default
= { -1, _PATH_LOG
, DEFFILEMODE
,
134 STAILQ_HEAD(, funix
) funixes
= { &funix_default
,
135 &(funix_secure
.next
.stqe_next
) };
141 #define IGN_CONS 0x001 /* don't print on console */
142 #define SYNC_FILE 0x002 /* do fsync on file after printing */
143 #define ADDDATE 0x004 /* add a date to the message */
144 #define MARK 0x008 /* this message is a mark */
145 #define ISKERNEL 0x010 /* kernel generated message */
148 * This structure represents the files that will have log
150 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
151 * or if f_type if F_PIPE and f_pid > 0.
155 struct filed
*f_next
; /* next in linked list */
156 short f_type
; /* entry type, see below */
157 short f_file
; /* file descriptor */
158 time_t f_time
; /* time this was last written */
159 char *f_host
; /* host from which to recd. */
160 u_char f_pmask
[LOG_NFACILITIES
+1]; /* priority mask */
161 u_char f_pcmp
[LOG_NFACILITIES
+1]; /* compare priority */
165 char *f_program
; /* program this applies to */
167 char f_uname
[MAXUNAMES
][32+1];
169 char f_hname
[MAXHOSTNAMELEN
];
170 struct addrinfo
*f_addr
;
172 } f_forw
; /* forwarding address */
173 char f_fname
[MAXPATHLEN
];
175 char f_pname
[MAXPATHLEN
];
179 char f_rname
[MAXPATHLEN
];
180 struct clog_footer
*f_footer
;
184 char f_prevline
[MAXSVLINE
]; /* last message logged */
185 char f_lasttime
[16]; /* time of last occurrence */
186 char f_prevhost
[MAXHOSTNAMELEN
]; /* host from which recd. */
187 int f_prevpri
; /* pri of f_prevline */
188 int f_prevlen
; /* length of f_prevline */
189 int f_prevcount
; /* repetition cnt of prevline */
190 u_int f_repeatcount
; /* number of "repeated" msgs */
191 int f_flags
; /* file-specific flags */
192 #define FFLAG_SYNC 0x01
193 #define FFLAG_NEEDSYNC 0x02
197 * Queue of about-to-be dead processes we should watch out for.
200 TAILQ_HEAD(stailhead
, deadq_entry
) deadq_head
;
201 struct stailhead
*deadq_headp
;
206 TAILQ_ENTRY(deadq_entry
) dq_entries
;
210 * The timeout to apply to processes waiting on the dead queue. Unit
211 * of measure is `mark intervals', i.e. 20 minutes by default.
212 * Processes on the dead queue will be terminated after that time.
215 #define DQ_TIMO_INIT 2
217 typedef struct deadq_entry
*dq_t
;
221 * Struct to hold records of network addresses that are allowed to log
229 struct sockaddr_storage addr
;
230 struct sockaddr_storage mask
;
234 #define a_addr u.numeric.addr
235 #define a_mask u.numeric.mask
236 #define a_name u.name
241 * Intervals at which we flush out "message repeated" messages,
242 * in seconds after previous message is logged. After each flush,
243 * we move to the next interval until we reach the largest.
245 int repeatinterval
[] = { 30, 120, 600 }; /* # of secs before flush */
246 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
247 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
248 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
249 (f)->f_repeatcount = MAXREPEAT; \
252 /* values for f_type */
253 #define F_UNUSED 0 /* unused entry */
254 #define F_FILE 1 /* regular file */
255 #define F_TTY 2 /* terminal */
256 #define F_CONSOLE 3 /* console terminal */
257 #define F_FORW 4 /* remote machine */
258 #define F_USERS 5 /* list of users */
259 #define F_WALL 6 /* everyone logged on */
260 #define F_PIPE 7 /* pipe to program */
261 #define F_RING 8 /* ring buffer (circular log) */
263 const char *TypeNames
[] = {
264 "UNUSED", "FILE", "TTY", "CONSOLE",
265 "FORW", "USERS", "WALL", "PIPE",
269 static struct filed
*Files
; /* Log files that we write to */
270 static struct filed consfile
; /* Console */
272 static int Debug
; /* debug flag */
273 static int resolve
= 1; /* resolve hostname */
274 static char LocalHostName
[MAXHOSTNAMELEN
]; /* our hostname */
275 static const char *LocalDomain
; /* our local domain name */
276 static int *finet
; /* Internet datagram socket */
277 static int fklog
= -1; /* /dev/klog */
278 static int Initialized
; /* set when we have initialized ourselves */
279 static int MarkInterval
= 20 * 60; /* interval between marks in seconds */
280 static int MarkSeq
; /* mark sequence number */
281 static int SecureMode
; /* when true, receive only unix domain socks */
283 static int family
= PF_UNSPEC
; /* protocol family (IPv4, IPv6 or both) */
285 static int family
= PF_INET
; /* protocol family (IPv4 only) */
287 static int mask_C1
= 1; /* mask characters from 0x80 - 0x9F */
288 static int send_to_all
; /* send message to all IPv4/IPv6 addresses */
289 static int use_bootfile
; /* log entire bootfile for every kern msg */
290 static int no_compress
; /* don't compress messages (1=pipes, 2=all) */
291 static int logflags
= O_WRONLY
|O_APPEND
; /* flags used to open log files */
293 static char bootfile
[MAXLINE
+1]; /* booted kernel file */
295 struct allowedpeer
*AllowedPeers
; /* List of allowed peers */
296 static int NumAllowed
; /* Number of entries in AllowedPeers */
297 static int RemoteAddDate
; /* Always set the date on remote messages */
299 static int UniquePriority
; /* Only log specified priority? */
300 static int LogFacPri
; /* Put facility and priority in log message: */
301 /* 0=no, 1=numeric, 2=names */
302 static int KeepKernFac
; /* Keep remotely logged kernel facility */
303 static int needdofsync
= 0; /* Are any file(s) waiting to be fsynced? */
304 static struct pidfh
*pfh
;
306 volatile sig_atomic_t MarkSet
, WantDie
;
308 static int allowaddr(char *);
309 static void cfline(const char *, struct filed
*,
310 const char *, const char *);
311 static const char *cvthname(struct sockaddr
*);
312 static void deadq_enter(pid_t
, const char *);
313 static int deadq_remove(pid_t
);
314 static int decode(const char *, CODE
*);
315 static void die(int);
316 static void dodie(int);
317 static void dofsync(void);
318 static void domark(int);
319 static void fprintlog(struct filed
*, int, const char *);
320 static int *socksetup(int, const char *);
321 static void init(int);
322 static void logerror(const char *);
323 static void logmsg(int, const char *, const char *, int);
324 static void log_deadchild(pid_t
, int, const char *);
325 static void markit(void);
326 static int skip_message(const char *, const char *, int);
327 static void printline(const char *, char *, int);
328 static void printsys(char *);
329 static int p_open(const char *, pid_t
*);
330 ssize_t
rbwrite(struct filed
*, char *, size_t);
331 ssize_t
rbwritev(struct filed
*, struct iovec
*, int);
332 static void readklog(void);
333 static void reapchild(int);
334 static void usage(void);
335 static int validate(struct sockaddr
*, const char *);
336 static void unmapped(struct sockaddr
*);
337 static void wallmsg(struct filed
*, struct iovec
*, const int iovlen
);
338 static int waitdaemon(int, int, int);
339 static void timedout(int);
340 static void double_rbuf(int);
343 main(int argc
, char *argv
[])
345 int ch
, i
, fdsrmax
= 0, l
;
346 struct sockaddr_un sunx
, fromunix
;
347 struct sockaddr_storage frominet
;
349 char line
[MAXLINE
+ 1];
350 const char *bindhostname
, *hname
;
351 struct timeval tv
, *tvp
;
352 struct sigaction sact
;
353 struct funix
*fx
, *fx1
;
355 pid_t ppid
= 1, spid
;
359 while ((ch
= getopt(argc
, argv
, "468Aa:b:cCdf:kl:m:nop:P:sS:Tuv"))
376 case 'a': /* allow specific network addresses only */
377 if (allowaddr(optarg
) == -1)
381 bindhostname
= optarg
;
389 case 'd': /* debug */
392 case 'f': /* configuration file */
395 case 'k': /* keep remote kern fac */
404 if (optarg
[0] == '/') {
407 } else if ((name
= strchr(optarg
, ':')) != NULL
) {
410 errx(1, "socket name must be absolute "
412 if (isdigit(*optarg
)) {
413 perml
= strtol(optarg
, &ep
, 8);
414 if (*ep
|| perml
< 0 ||
415 perml
& ~(S_IRWXU
|S_IRWXG
|S_IRWXO
))
416 errx(1, "invalid mode %s, exiting",
418 mode
= (mode_t
)perml
;
420 errx(1, "invalid mode %s, exiting",
422 } else /* doesn't begin with '/', and no ':' */
423 errx(1, "can't parse path %s", optarg
);
425 if (strlen(name
) >= sizeof(sunx
.sun_path
))
426 errx(1, "%s path too long, exiting", name
);
427 if ((fx
= malloc(sizeof(struct funix
))) == NULL
)
428 errx(1, "malloc failed");
432 STAILQ_INSERT_TAIL(&funixes
, fx
, next
);
435 case 'm': /* mark interval */
436 MarkInterval
= atoi(optarg
) * 60;
445 if (strlen(optarg
) >= sizeof(sunx
.sun_path
))
446 errx(1, "%s path too long, exiting", optarg
);
447 funix_default
.name
= optarg
;
449 case 'P': /* path for alt. PID */
452 case 's': /* no network mode */
455 case 'S': /* path for privileged originator */
456 if (strlen(optarg
) >= sizeof(sunx
.sun_path
))
457 errx(1, "%s path too long, exiting", optarg
);
458 funix_secure
.name
= optarg
;
463 case 'u': /* only log specified priority */
466 case 'v': /* log facility and priority */
472 if ((argc
-= optind
) != 0)
475 pfh
= pidfile_open(PidFile
, 0600, &spid
);
478 errx(1, "syslogd already running, pid: %d", spid
);
479 warn("cannot open pid file");
483 ppid
= waitdaemon(0, 0, 30);
485 warn("could not become daemon");
496 consfile
.f_type
= F_CONSOLE
;
497 strlcpy(consfile
.f_un
.f_fname
, ctty
+ sizeof _PATH_DEV
- 1,
498 sizeof(consfile
.f_un
.f_fname
));
499 strlcpy(bootfile
, getbootfile(), sizeof(bootfile
));
500 signal(SIGTERM
, dodie
);
501 signal(SIGINT
, Debug
? dodie
: SIG_IGN
);
502 signal(SIGQUIT
, Debug
? dodie
: SIG_IGN
);
504 * We don't want the SIGCHLD and SIGHUP handlers to interfere
505 * with each other; they are likely candidates for being called
506 * simultaneously (SIGHUP closes pipe descriptor, process dies,
510 sigaddset(&mask
, SIGHUP
);
511 sact
.sa_handler
= reapchild
;
513 sact
.sa_flags
= SA_RESTART
;
514 sigaction(SIGCHLD
, &sact
, NULL
);
515 signal(SIGALRM
, domark
);
516 signal(SIGPIPE
, SIG_IGN
); /* We'll catch EPIPE instead. */
519 TAILQ_INIT(&deadq_head
);
522 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
524 STAILQ_FOREACH_MUTABLE(fx
, &funixes
, next
, fx1
) {
526 memset(&sunx
, 0, sizeof(sunx
));
527 sunx
.sun_family
= AF_LOCAL
;
528 strlcpy(sunx
.sun_path
, fx
->name
, sizeof(sunx
.sun_path
));
529 fx
->s
= socket(PF_LOCAL
, SOCK_DGRAM
, 0);
531 bind(fx
->s
, (struct sockaddr
*)&sunx
, SUN_LEN(&sunx
)) < 0 ||
532 chmod(fx
->name
, fx
->mode
) < 0) {
533 snprintf(line
, sizeof line
,
534 "cannot create %s", fx
->name
);
536 dprintf("cannot create %s (%d)\n", fx
->name
, errno
);
537 if (fx
== &funix_default
|| fx
== &funix_secure
)
540 STAILQ_REMOVE(&funixes
, fx
, funix
, next
);
547 finet
= socksetup(family
, bindhostname
);
551 for (i
= 0; i
< *finet
; i
++) {
552 if (shutdown(finet
[i
+1], SHUT_RD
) < 0) {
553 logerror("shutdown");
559 dprintf("listening on inet and/or inet6 socket\n");
561 dprintf("sending on inet and/or inet6 socket\n");
564 if ((fklog
= open(_PATH_KLOG
, O_RDONLY
, 0)) >= 0)
565 if (fcntl(fklog
, F_SETFL
, O_NONBLOCK
) < 0)
568 dprintf("can't open %s (%d)\n", _PATH_KLOG
, errno
);
570 /* tuck my process id away */
573 dprintf("off & running....\n");
576 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
578 sigaddset(&mask
, SIGCHLD
);
579 sact
.sa_handler
= init
;
581 sact
.sa_flags
= SA_RESTART
;
582 sigaction(SIGHUP
, &sact
, NULL
);
585 tv
.tv_sec
= tv
.tv_usec
= 0;
587 if (fklog
!= -1 && fklog
> fdsrmax
)
589 if (finet
&& !SecureMode
) {
590 for (i
= 0; i
< *finet
; i
++) {
591 if (finet
[i
+1] != -1 && finet
[i
+1] > fdsrmax
)
592 fdsrmax
= finet
[i
+1];
595 STAILQ_FOREACH(fx
, &funixes
, next
)
599 fdsr
= (fd_set
*)calloc(howmany(fdsrmax
+1, NFDBITS
),
602 errx(1, "calloc fd_set");
610 bzero(fdsr
, howmany(fdsrmax
+1, NFDBITS
) *
615 if (finet
&& !SecureMode
) {
616 for (i
= 0; i
< *finet
; i
++) {
617 if (finet
[i
+1] != -1)
618 FD_SET(finet
[i
+1], fdsr
);
621 STAILQ_FOREACH(fx
, &funixes
, next
)
624 i
= select(fdsrmax
+1, fdsr
, NULL
, NULL
,
625 needdofsync
? &tv
: tvp
);
641 if (fklog
!= -1 && FD_ISSET(fklog
, fdsr
))
643 if (finet
&& !SecureMode
) {
644 for (i
= 0; i
< *finet
; i
++) {
645 if (FD_ISSET(finet
[i
+1], fdsr
)) {
646 len
= sizeof(frominet
);
647 l
= recvfrom(finet
[i
+1], line
, MAXLINE
,
648 0, (struct sockaddr
*)&frominet
,
652 hname
= cvthname((struct sockaddr
*)&frominet
);
653 unmapped((struct sockaddr
*)&frominet
);
654 if (validate((struct sockaddr
*)&frominet
, hname
))
655 printline(hname
, line
, RemoteAddDate
? ADDDATE
: 0);
656 } else if (l
< 0 && errno
!= EINTR
)
657 logerror("recvfrom inet");
661 STAILQ_FOREACH(fx
, &funixes
, next
) {
662 if (FD_ISSET(fx
->s
, fdsr
)) {
663 len
= sizeof(fromunix
);
664 l
= recvfrom(fx
->s
, line
, MAXLINE
, 0,
665 (struct sockaddr
*)&fromunix
, &len
);
668 printline(LocalHostName
, line
, 0);
669 } else if (l
< 0 && errno
!= EINTR
)
670 logerror("recvfrom unix");
679 unmapped(struct sockaddr
*sa
)
681 struct sockaddr_in6
*sin6
;
682 struct sockaddr_in sin4
;
684 if (sa
->sa_family
!= AF_INET6
)
686 if (sa
->sa_len
!= sizeof(struct sockaddr_in6
) ||
687 sizeof(sin4
) > sa
->sa_len
)
689 sin6
= (struct sockaddr_in6
*)sa
;
690 if (!IN6_IS_ADDR_V4MAPPED(&sin6
->sin6_addr
))
693 memset(&sin4
, 0, sizeof(sin4
));
694 sin4
.sin_family
= AF_INET
;
695 sin4
.sin_len
= sizeof(struct sockaddr_in
);
696 memcpy(&sin4
.sin_addr
, &sin6
->sin6_addr
.s6_addr
[12],
697 sizeof(sin4
.sin_addr
));
698 sin4
.sin_port
= sin6
->sin6_port
;
700 memcpy(sa
, &sin4
, sin4
.sin_len
);
707 fprintf(stderr
, "%s\n%s\n%s\n%s\n",
708 "usage: syslogd [-468ACcdknosTuv] [-a allowed_peer]",
709 " [-b bind_address] [-f config_file]",
710 " [-l [mode:]path] [-m mark_interval]",
711 " [-P pid_file] [-p log_socket]");
716 * Take a raw input line, decode the message, and print the message
717 * on the appropriate log files.
720 printline(const char *hname
, char *msg
, int flags
)
725 char line
[MAXLINE
+ 1];
727 /* test for special codes */
732 n
= strtol(p
+ 1, &q
, 10);
733 if (*q
== '>' && n
>= 0 && n
< INT_MAX
&& errno
== 0) {
738 if (pri
&~ (LOG_FACMASK
|LOG_PRIMASK
))
742 * Don't allow users to log kernel messages.
743 * NOTE: since LOG_KERN == 0 this will also match
744 * messages with no facility specified.
746 if ((pri
& LOG_FACMASK
) == LOG_KERN
&& !KeepKernFac
)
747 pri
= LOG_MAKEPRI(LOG_USER
, LOG_PRI(pri
));
751 while ((c
= (unsigned char)*p
++) != '\0' &&
752 q
< &line
[sizeof(line
) - 4]) {
753 if (mask_C1
&& (c
& 0x80) && c
< 0xA0) {
758 if (isascii(c
) && iscntrl(c
)) {
761 } else if (c
== '\t') {
773 logmsg(pri
, line
, hname
, flags
);
777 * Read /dev/klog while data are available, split into lines.
782 char *p
, *q
, line
[MAXLINE
+ 1];
787 i
= read(fklog
, line
+ len
, MAXLINE
- 1 - len
);
789 line
[i
+ len
] = '\0';
791 if (i
< 0 && errno
!= EINTR
&& errno
!= EAGAIN
) {
798 for (p
= line
; (q
= strchr(p
, '\n')) != NULL
; p
= q
+ 1) {
803 if (len
>= MAXLINE
- 1) {
808 memmove(line
, p
, len
+ 1);
815 * Take a raw input line from /dev/klog, format similar to syslog().
822 int flags
, isprintf
, pri
;
824 flags
= ISKERNEL
| SYNC_FILE
| ADDDATE
; /* fsync after write */
830 n
= strtol(p
+ 1, &q
, 10);
831 if (*q
== '>' && n
>= 0 && n
< INT_MAX
&& errno
== 0) {
838 * Kernel printf's and LOG_CONSOLE messages have been displayed
839 * on the console already.
841 if (isprintf
|| (pri
& LOG_FACMASK
) == LOG_CONSOLE
)
843 if (pri
&~ (LOG_FACMASK
|LOG_PRIMASK
))
845 logmsg(pri
, p
, LocalHostName
, flags
);
851 * Match a program or host name against a specification.
852 * Return a non-0 value if the message must be ignored
853 * based on the specification.
856 skip_message(const char *name
, const char *spec
, int checkcase
)
861 /* Behaviour on explicit match */
876 s
= strstr (spec
, name
);
878 s
= strcasestr (spec
, name
);
881 prev
= (s
== spec
? ',' : *(s
- 1));
882 next
= *(s
+ strlen (name
));
884 if (prev
== ',' && (next
== '\0' || next
== ','))
885 /* Explicit match: skip iff the spec is an
890 /* No explicit match for this name: skip the message iff
891 the spec is an inclusive one. */
896 * Log a message to the appropriate log files, users, etc. based on
900 logmsg(int pri
, const char *msg
, const char *from
, int flags
)
903 int i
, fac
, msglen
, omask
, prilev
;
904 const char *timestamp
;
905 char prog
[NAME_MAX
+1];
908 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
909 pri
, flags
, from
, msg
);
911 omask
= sigblock(sigmask(SIGHUP
)|sigmask(SIGALRM
));
914 * Check to see if msg looks non-standard.
916 msglen
= strlen(msg
);
917 if (msglen
< 16 || msg
[3] != ' ' || msg
[6] != ' ' ||
918 msg
[9] != ':' || msg
[12] != ':' || msg
[15] != ' ')
922 if (flags
& ADDDATE
) {
923 timestamp
= ctime(&now
) + 4;
930 /* skip leading blanks */
931 while (isspace(*msg
)) {
936 /* extract facility and priority level */
938 fac
= LOG_NFACILITIES
;
942 /* Check maximum facility number. */
943 if (fac
> LOG_NFACILITIES
) {
948 prilev
= LOG_PRI(pri
);
950 /* extract program name */
951 for (i
= 0; i
< NAME_MAX
; i
++) {
952 if (!isprint(msg
[i
]) || msg
[i
] == ':' || msg
[i
] == '[' ||
953 msg
[i
] == '/' || isspace(msg
[i
]))
959 /* add kernel prefix for kernel messages */
960 if (flags
& ISKERNEL
) {
961 snprintf(buf
, sizeof(buf
), "%s: %s",
962 use_bootfile
? bootfile
: "kernel", msg
);
964 msglen
= strlen(buf
);
967 /* log the message to the particular outputs */
971 * Open in non-blocking mode to avoid hangs during open
972 * and close(waiting for the port to drain).
974 f
->f_file
= open(ctty
, O_WRONLY
| O_NONBLOCK
, 0);
976 if (f
->f_file
>= 0) {
977 strlcpy(f
->f_lasttime
, timestamp
,
978 sizeof(f
->f_lasttime
));
979 fprintlog(f
, flags
, msg
);
985 for (f
= Files
; f
; f
= f
->f_next
) {
986 /* skip messages that are incorrect priority */
987 if (!(((f
->f_pcmp
[fac
] & PRI_EQ
) && (f
->f_pmask
[fac
] == prilev
))
988 ||((f
->f_pcmp
[fac
] & PRI_LT
) && (f
->f_pmask
[fac
] < prilev
))
989 ||((f
->f_pcmp
[fac
] & PRI_GT
) && (f
->f_pmask
[fac
] > prilev
))
991 || f
->f_pmask
[fac
] == INTERNAL_NOPRI
)
994 /* skip messages with the incorrect hostname */
995 if (skip_message(from
, f
->f_host
, 0))
998 /* skip messages with the incorrect program name */
999 if (skip_message(prog
, f
->f_program
, 1))
1002 /* skip message to console if it has already been printed */
1003 if (f
->f_type
== F_CONSOLE
&& (flags
& IGN_CONS
))
1006 /* don't output marks to recently written files */
1007 if ((flags
& MARK
) && (now
- f
->f_time
) < MarkInterval
/ 2)
1011 * suppress duplicate lines to this file
1013 if (no_compress
- (f
->f_type
!= F_PIPE
) < 1 &&
1014 (flags
& MARK
) == 0 && msglen
== f
->f_prevlen
&&
1015 f
->f_prevline
&& !strcmp(msg
, f
->f_prevline
) &&
1016 !strcasecmp(from
, f
->f_prevhost
)) {
1017 strlcpy(f
->f_lasttime
, timestamp
,
1018 sizeof(f
->f_lasttime
));
1020 dprintf("msg repeated %d times, %ld sec of %d\n",
1021 f
->f_prevcount
, (long)(now
- f
->f_time
),
1022 repeatinterval
[f
->f_repeatcount
]);
1024 * If domark would have logged this by now,
1025 * flush it now (so we don't hold isolated messages),
1026 * but back off so we'll flush less often
1029 if (now
> REPEATTIME(f
)) {
1030 fprintlog(f
, flags
, NULL
);
1034 /* new line, save it */
1036 fprintlog(f
, 0, NULL
);
1037 f
->f_repeatcount
= 0;
1039 strlcpy(f
->f_lasttime
, timestamp
,
1040 sizeof(f
->f_lasttime
));
1041 strlcpy(f
->f_prevhost
, from
, sizeof(f
->f_prevhost
));
1042 if (msglen
< MAXSVLINE
) {
1043 f
->f_prevlen
= msglen
;
1044 strlcpy(f
->f_prevline
, msg
, sizeof(f
->f_prevline
));
1045 fprintlog(f
, flags
, NULL
);
1047 f
->f_prevline
[0] = 0;
1049 fprintlog(f
, flags
, msg
);
1061 for (f
= Files
; f
; f
= f
->f_next
) {
1062 if ((f
->f_type
== F_FILE
) &&
1063 (f
->f_flags
& FFLAG_NEEDSYNC
)) {
1064 f
->f_flags
&= ~FFLAG_NEEDSYNC
;
1072 fprintlog(struct filed
*f
, int flags
, const char *msg
)
1074 struct iovec iov
[IOV_SIZE
];
1077 int i
, l
, lsent
= 0;
1078 char line
[MAXLINE
+ 1], repbuf
[80], greetings
[200], *wmsg
= NULL
;
1079 char nul
[] = "", space
[] = " ", lf
[] = "\n", crlf
[] = "\r\n";
1083 if (f
->f_type
== F_WALL
) {
1084 v
->iov_base
= greetings
;
1085 /* The time displayed is not synchornized with the other log
1086 * destinations (like messages). Following fragment was using
1087 * ctime(&now), which was updating the time every 30 sec.
1088 * With f_lasttime, time is synchronized correctly.
1090 v
->iov_len
= snprintf(greetings
, sizeof greetings
,
1091 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1092 f
->f_prevhost
, f
->f_lasttime
);
1099 v
->iov_base
= f
->f_lasttime
;
1100 v
->iov_len
= strlen(f
->f_lasttime
);
1102 v
->iov_base
= space
;
1108 static char fp_buf
[30]; /* Hollow laugh */
1109 int fac
= f
->f_prevpri
& LOG_FACMASK
;
1110 int pri
= LOG_PRI(f
->f_prevpri
);
1111 const char *f_s
= NULL
;
1112 char f_n
[5]; /* Hollow laugh */
1113 const char *p_s
= NULL
;
1114 char p_n
[5]; /* Hollow laugh */
1116 if (LogFacPri
> 1) {
1119 for (c
= facilitynames
; c
->c_name
; c
++) {
1120 if (c
->c_val
== fac
) {
1125 for (c
= prioritynames
; c
->c_name
; c
++) {
1126 if (c
->c_val
== pri
) {
1133 snprintf(f_n
, sizeof f_n
, "%d", LOG_FAC(fac
));
1137 snprintf(p_n
, sizeof p_n
, "%d", pri
);
1140 snprintf(fp_buf
, sizeof fp_buf
, "<%s.%s> ", f_s
, p_s
);
1141 v
->iov_base
= fp_buf
;
1142 v
->iov_len
= strlen(fp_buf
);
1149 v
->iov_base
= f
->f_prevhost
;
1150 v
->iov_len
= strlen(v
->iov_base
);
1152 v
->iov_base
= space
;
1157 wmsg
= strdup(msg
); /* XXX iov_base needs a `const' sibling. */
1163 v
->iov_len
= strlen(msg
);
1164 } else if (f
->f_prevcount
> 1) {
1165 v
->iov_base
= repbuf
;
1166 v
->iov_len
= snprintf(repbuf
, sizeof repbuf
,
1167 "last message repeated %d times", f
->f_prevcount
);
1168 } else if (f
->f_prevline
) {
1169 v
->iov_base
= f
->f_prevline
;
1170 v
->iov_len
= f
->f_prevlen
;
1176 dprintf("Logging to %s", TypeNames
[f
->f_type
]);
1179 switch (f
->f_type
) {
1186 port
= (int)ntohs(((struct sockaddr_in
*)
1187 (f
->f_un
.f_forw
.f_addr
->ai_addr
))->sin_port
);
1189 dprintf(" %s:%d\n", f
->f_un
.f_forw
.f_hname
, port
);
1191 dprintf(" %s\n", f
->f_un
.f_forw
.f_hname
);
1193 /* check for local vs remote messages */
1194 if (strcasecmp(f
->f_prevhost
, LocalHostName
))
1195 l
= snprintf(line
, sizeof line
- 1,
1196 "<%d>%.15s Forwarded from %s: %s",
1197 f
->f_prevpri
, (char *)iov
[0].iov_base
,
1198 f
->f_prevhost
, (char *)iov
[5].iov_base
);
1200 l
= snprintf(line
, sizeof line
- 1, "<%d>%.15s %s",
1201 f
->f_prevpri
, (char *)iov
[0].iov_base
,
1202 (char *)iov
[5].iov_base
);
1205 else if (l
> MAXLINE
)
1209 for (r
= f
->f_un
.f_forw
.f_addr
; r
; r
= r
->ai_next
) {
1210 for (i
= 0; i
< *finet
; i
++) {
1213 * should we check AF first, or just
1214 * trial and error? FWD
1217 address_family_of(finet
[i
+1]))
1219 lsent
= sendto(finet
[i
+1], line
, l
, 0,
1220 r
->ai_addr
, r
->ai_addrlen
);
1224 if (lsent
== l
&& !send_to_all
)
1227 dprintf("lsent/l: %d/%d\n", lsent
, l
);
1240 /* case ENOTSOCK: */
1242 /* case EMSGSIZE: */
1245 /* case ECONNREFUSED: */
1247 dprintf("removing entry\n");
1248 f
->f_type
= F_UNUSED
;
1256 dprintf(" %s\n", f
->f_un
.f_fname
);
1259 if (writev(f
->f_file
, iov
, IOV_SIZE
) < 0) {
1261 * If writev(2) fails for potentially transient errors
1262 * like the filesystem being full, ignore it.
1263 * Otherwise remove this logfile from the list.
1265 if (errno
!= ENOSPC
) {
1268 f
->f_type
= F_UNUSED
;
1270 logerror(f
->f_un
.f_fname
);
1272 } else if ((flags
& SYNC_FILE
) && (f
->f_flags
& FFLAG_SYNC
)) {
1273 f
->f_flags
|= FFLAG_NEEDSYNC
;
1279 dprintf(" %s\n", f
->f_un
.f_ring
.f_rname
);
1282 if (rbwritev(f
, iov
, 7) == -1) {
1284 munmap(f
->f_un
.f_ring
.f_footer
,
1285 sizeof(struct clog_footer
));
1287 f
->f_type
= F_UNUSED
;
1289 logerror(f
->f_un
.f_fname
);
1294 dprintf(" %s\n", f
->f_un
.f_pipe
.f_pname
);
1297 if (f
->f_un
.f_pipe
.f_pid
== 0) {
1298 if ((f
->f_file
= p_open(f
->f_un
.f_pipe
.f_pname
,
1299 &f
->f_un
.f_pipe
.f_pid
)) < 0) {
1300 f
->f_type
= F_UNUSED
;
1301 logerror(f
->f_un
.f_pipe
.f_pname
);
1305 if (writev(f
->f_file
, iov
, IOV_SIZE
) < 0) {
1308 if (f
->f_un
.f_pipe
.f_pid
> 0)
1309 deadq_enter(f
->f_un
.f_pipe
.f_pid
,
1310 f
->f_un
.f_pipe
.f_pname
);
1311 f
->f_un
.f_pipe
.f_pid
= 0;
1313 logerror(f
->f_un
.f_pipe
.f_pname
);
1318 if (flags
& IGN_CONS
) {
1319 dprintf(" (ignored)\n");
1325 dprintf(" %s%s\n", _PATH_DEV
, f
->f_un
.f_fname
);
1329 errno
= 0; /* ttymsg() only sometimes returns an errno */
1330 if ((msgret
= ttymsg(iov
, IOV_SIZE
, f
->f_un
.f_fname
, 10))) {
1331 f
->f_type
= F_UNUSED
;
1341 wallmsg(f
, iov
, IOV_SIZE
);
1349 * WALLMSG -- Write a message to the world at large
1351 * Write the specified message to either the entire
1352 * world, or a list of approved users.
1355 wallmsg(struct filed
*f
, struct iovec
*iov
, const int iovlen
)
1357 static int reenter
; /* avoid calling ourselves */
1359 struct utmpentry
*ep
;
1366 getutentries(NULL
, &ep
);
1368 logerror("getutentries");
1373 for (; ep
; ep
= ep
->next
) {
1374 /* We must use strncpy since ut_* may not be NUL terminated. */
1375 if (f
->f_type
== F_WALL
) {
1376 if ((p
= ttymsg(iov
, iovlen
, ep
->line
, TTYMSGTIME
)) !=
1378 errno
= 0; /* already in msg */
1383 /* should we send the message to this user? */
1384 for (i
= 0; i
< MAXUNAMES
; i
++) {
1385 if (!f
->f_un
.f_uname
[i
][0])
1387 if (!strcmp(f
->f_un
.f_uname
[i
], ep
->name
)) {
1388 if ((p
= ttymsg(iov
, iovlen
, ep
->line
, TTYMSGTIME
))
1390 errno
= 0; /* already in msg */
1401 reapchild(int signo __unused
)
1407 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0) {
1409 /* Don't tell while we are initting. */
1412 /* First, look if it's a process from the dead queue. */
1413 if (deadq_remove(pid
))
1416 /* Now, look in list of active processes. */
1417 for (f
= Files
; f
; f
= f
->f_next
)
1418 if (f
->f_type
== F_PIPE
&&
1419 f
->f_un
.f_pipe
.f_pid
== pid
) {
1421 f
->f_un
.f_pipe
.f_pid
= 0;
1422 log_deadchild(pid
, status
,
1423 f
->f_un
.f_pipe
.f_pname
);
1432 * Return a printable representation of a host address.
1435 cvthname(struct sockaddr
*f
)
1438 sigset_t omask
, nmask
;
1439 static char hname
[NI_MAXHOST
], ip
[NI_MAXHOST
];
1441 error
= getnameinfo((struct sockaddr
*)f
,
1442 ((struct sockaddr
*)f
)->sa_len
,
1443 ip
, sizeof ip
, NULL
, 0, NI_NUMERICHOST
);
1444 dprintf("cvthname(%s)\n", ip
);
1447 dprintf("Malformed from address %s\n", gai_strerror(error
));
1453 sigemptyset(&nmask
);
1454 sigaddset(&nmask
, SIGHUP
);
1455 sigprocmask(SIG_BLOCK
, &nmask
, &omask
);
1456 error
= getnameinfo((struct sockaddr
*)f
,
1457 ((struct sockaddr
*)f
)->sa_len
,
1458 hname
, sizeof hname
, NULL
, 0, NI_NAMEREQD
);
1459 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
1461 dprintf("Host name for your address (%s) unknown\n", ip
);
1465 if (hl
> 0 && hname
[hl
-1] == '.')
1467 trimdomain(hname
, hl
);
1479 domark(int signo __unused
)
1486 * Print syslogd errors some place.
1489 logerror(const char *type
)
1492 static int recursed
= 0;
1494 /* If there's an error while trying to log an error, give up. */
1500 sizeof buf
, "syslogd: %s: %s", type
, strerror(errno
));
1502 snprintf(buf
, sizeof buf
, "syslogd: %s", type
);
1504 dprintf("%s\n", buf
);
1505 logmsg(LOG_SYSLOG
|LOG_ERR
, buf
, LocalHostName
, ADDDATE
);
1514 int was_initialized
;
1517 was_initialized
= Initialized
;
1518 Initialized
= 0; /* Don't log SIGCHLDs. */
1519 for (f
= Files
; f
!= NULL
; f
= f
->f_next
) {
1520 /* flush any pending output */
1522 fprintlog(f
, 0, NULL
);
1523 if (f
->f_type
== F_PIPE
&& f
->f_un
.f_pipe
.f_pid
> 0) {
1525 f
->f_un
.f_pipe
.f_pid
= 0;
1528 Initialized
= was_initialized
;
1530 dprintf("syslogd: exiting on signal %d\n", signo
);
1531 snprintf(buf
, sizeof(buf
), "exiting on signal %d", signo
);
1535 STAILQ_FOREACH(fx
, &funixes
, next
)
1537 pidfile_remove(pfh
);
1543 * INIT -- Initialize syslogd from configuration table
1550 struct filed
*f
, *next
, **nextp
;
1552 char cline
[LINE_MAX
];
1553 char prog
[NAME_MAX
+1];
1554 char host
[MAXHOSTNAMELEN
];
1555 char oldLocalHostName
[MAXHOSTNAMELEN
];
1556 char hostMsg
[2*MAXHOSTNAMELEN
+40];
1557 char bootfileMsg
[LINE_MAX
];
1562 * Load hostname (may have changed).
1565 strlcpy(oldLocalHostName
, LocalHostName
,
1566 sizeof(oldLocalHostName
));
1567 if (gethostname(LocalHostName
, sizeof(LocalHostName
)))
1568 err(EX_OSERR
, "gethostname() failed");
1569 if ((p
= strchr(LocalHostName
, '.')) != NULL
) {
1577 * Close all open log files.
1580 for (f
= Files
; f
!= NULL
; f
= next
) {
1581 /* flush any pending output */
1583 fprintlog(f
, 0, NULL
);
1585 switch (f
->f_type
) {
1593 if (f
->f_un
.f_pipe
.f_pid
> 0) {
1595 deadq_enter(f
->f_un
.f_pipe
.f_pid
,
1596 f
->f_un
.f_pipe
.f_pname
);
1598 f
->f_un
.f_pipe
.f_pid
= 0;
1601 munmap(f
->f_un
.f_ring
.f_footer
,
1602 sizeof(struct clog_footer
));
1607 if (f
->f_program
) free(f
->f_program
);
1608 if (f
->f_host
) free(f
->f_host
);
1614 /* open the configuration file */
1615 if ((cf
= fopen(ConfFile
, "r")) == NULL
) {
1616 dprintf("cannot open %s\n", ConfFile
);
1617 *nextp
= (struct filed
*)calloc(1, sizeof(*f
));
1618 if (*nextp
== NULL
) {
1622 cfline("*.ERR\t/dev/console", *nextp
, "*", "*");
1623 (*nextp
)->f_next
= (struct filed
*)calloc(1, sizeof(*f
));
1624 if ((*nextp
)->f_next
== NULL
) {
1628 cfline("*.PANIC\t*", (*nextp
)->f_next
, "*", "*");
1634 * Foreach line in the conf table, open that file.
1637 strlcpy(host
, "*", sizeof(host
));
1638 strlcpy(prog
, "*", sizeof(prog
));
1639 while (fgets(cline
, sizeof(cline
), cf
) != NULL
) {
1641 * check for end-of-section, comments, strip off trailing
1642 * spaces and newline character. #!prog is treated specially:
1643 * following lines apply only to that program.
1645 for (p
= cline
; isspace(*p
); ++p
)
1651 if (*p
!= '!' && *p
!= '+' && *p
!= '-')
1654 if (*p
== '+' || *p
== '-') {
1658 if ((!*p
) || (*p
== '*')) {
1659 strlcpy(host
, "*", sizeof(host
));
1664 for (i
= 1; i
< MAXHOSTNAMELEN
- 1; i
++) {
1665 if (!isalnum(*p
) && *p
!= '.' && *p
!= '-'
1666 && *p
!= ',' && *p
!= ':' && *p
!= '%')
1675 while (isspace(*p
)) p
++;
1676 if ((!*p
) || (*p
== '*')) {
1677 strlcpy(prog
, "*", sizeof(prog
));
1680 for (i
= 0; i
< NAME_MAX
; i
++) {
1681 if (!isprint(p
[i
]) || isspace(p
[i
]))
1688 for (p
= cline
+ 1; *p
!= '\0'; p
++) {
1691 if (*(p
- 1) == '\\') {
1699 for (i
= strlen(cline
) - 1; i
>= 0 && isspace(cline
[i
]); i
--)
1701 f
= (struct filed
*)calloc(1, sizeof(*f
));
1708 cfline(cline
, f
, prog
, host
);
1711 /* close the configuration file */
1718 for (f
= Files
; f
; f
= f
->f_next
) {
1719 for (i
= 0; i
<= LOG_NFACILITIES
; i
++)
1720 if (f
->f_pmask
[i
] == INTERNAL_NOPRI
)
1723 printf("%d ", f
->f_pmask
[i
]);
1724 printf("%s: ", TypeNames
[f
->f_type
]);
1725 switch (f
->f_type
) {
1727 printf("%s", f
->f_un
.f_fname
);
1732 printf("%s%s", _PATH_DEV
, f
->f_un
.f_fname
);
1736 port
= (int)ntohs(((struct sockaddr_in
*)
1737 (f
->f_un
.f_forw
.f_addr
->ai_addr
))->sin_port
);
1740 f
->f_un
.f_forw
.f_hname
, port
);
1742 printf("%s", f
->f_un
.f_forw
.f_hname
);
1747 printf("%s", f
->f_un
.f_ring
.f_rname
);
1751 printf("%s", f
->f_un
.f_pipe
.f_pname
);
1755 for (i
= 0; i
< MAXUNAMES
&& *f
->f_un
.f_uname
[i
]; i
++)
1756 printf("%s, ", f
->f_un
.f_uname
[i
]);
1760 printf(" (%s)", f
->f_program
);
1765 logmsg(LOG_SYSLOG
|LOG_INFO
, "syslogd: restart", LocalHostName
, ADDDATE
);
1766 dprintf("syslogd: restarted\n");
1768 * Log a change in hostname, but only on a restart.
1770 if (signo
!= 0 && strcmp(oldLocalHostName
, LocalHostName
) != 0) {
1771 snprintf(hostMsg
, sizeof(hostMsg
),
1772 "syslogd: hostname changed, \"%s\" to \"%s\"",
1773 oldLocalHostName
, LocalHostName
);
1774 logmsg(LOG_SYSLOG
|LOG_INFO
, hostMsg
, LocalHostName
, ADDDATE
);
1775 dprintf("%s\n", hostMsg
);
1778 * Log the kernel boot file if we aren't going to use it as
1779 * the prefix, and if this is *not* a restart.
1781 if (signo
== 0 && !use_bootfile
) {
1782 snprintf(bootfileMsg
, sizeof(bootfileMsg
),
1783 "syslogd: kernel boot file is %s", bootfile
);
1784 logmsg(LOG_KERN
|LOG_INFO
, bootfileMsg
, LocalHostName
, ADDDATE
);
1785 dprintf("%s\n", bootfileMsg
);
1790 * Crack a configuration file line
1793 cfline(const char *line
, struct filed
*f
, const char *prog
, const char *host
)
1795 struct addrinfo hints
, *res
;
1796 int error
, i
, pri
, syncfile
;
1799 char buf
[MAXLINE
], ebuf
[100];
1802 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line
, prog
, host
);
1804 errno
= 0; /* keep strerror() stuff out of logerror messages */
1806 /* clear out file entry */
1807 memset(f
, 0, sizeof(*f
));
1808 for (i
= 0; i
<= LOG_NFACILITIES
; i
++)
1809 f
->f_pmask
[i
] = INTERNAL_NOPRI
;
1811 /* save hostname if any */
1812 if (host
&& *host
== '*')
1817 f
->f_host
= strdup(host
);
1818 if (f
->f_host
== NULL
) {
1822 hl
= strlen(f
->f_host
);
1823 if (hl
> 0 && f
->f_host
[hl
-1] == '.')
1824 f
->f_host
[--hl
] = '\0';
1825 trimdomain(f
->f_host
, hl
);
1828 /* save program name if any */
1829 if (prog
&& *prog
== '*')
1832 f
->f_program
= strdup(prog
);
1833 if (f
->f_program
== NULL
) {
1839 /* scan through the list of selectors */
1840 for (p
= line
; *p
&& *p
!= '\t' && *p
!= ' ';) {
1845 /* find the end of this facility name list */
1846 for (q
= p
; *q
&& *q
!= '\t' && *q
!= ' ' && *q
++ != '.'; )
1849 /* get the priority comparison */
1877 /* collect priority name */
1878 for (bp
= buf
; *q
&& !strchr("\t,; ", *q
); )
1883 while (strchr(",;", *q
))
1886 /* decode priority name */
1889 pri_cmp
= PRI_LT
| PRI_EQ
| PRI_GT
;
1891 /* Ignore trailing spaces. */
1892 for (i
= strlen(buf
) - 1; i
>= 0 && buf
[i
] == ' '; i
--)
1895 pri
= decode(buf
, prioritynames
);
1897 snprintf(ebuf
, sizeof ebuf
,
1898 "unknown priority name \"%s\"", buf
);
1904 pri_cmp
= (UniquePriority
)
1909 pri_cmp
^= PRI_LT
| PRI_EQ
| PRI_GT
;
1911 /* scan facilities */
1912 while (*p
&& !strchr("\t.; ", *p
)) {
1913 for (bp
= buf
; *p
&& !strchr("\t,;. ", *p
); )
1918 for (i
= 0; i
< LOG_NFACILITIES
; i
++) {
1919 f
->f_pmask
[i
] = pri
;
1920 f
->f_pcmp
[i
] = pri_cmp
;
1923 i
= decode(buf
, facilitynames
);
1925 snprintf(ebuf
, sizeof ebuf
,
1926 "unknown facility name \"%s\"",
1931 f
->f_pmask
[i
>> 3] = pri
;
1932 f
->f_pcmp
[i
>> 3] = pri_cmp
;
1934 while (*p
== ',' || *p
== ' ')
1941 /* skip to action part */
1942 while (*p
== '\t' || *p
== ' ')
1956 * scan forward to see if there is a port defined.
1957 * so we can't use strlcpy..
1959 i
= sizeof(f
->f_un
.f_forw
.f_hname
);
1960 tp
= f
->f_un
.f_forw
.f_hname
;
1963 while (*p
&& (*p
!= ':') && (i
-- > 0)) {
1968 /* See if we copied a domain and have a port */
1974 memset(&hints
, 0, sizeof(hints
));
1975 hints
.ai_family
= family
;
1976 hints
.ai_socktype
= SOCK_DGRAM
;
1977 error
= getaddrinfo(f
->f_un
.f_forw
.f_hname
,
1978 p
? p
: "syslog", &hints
, &res
);
1980 logerror(gai_strerror(error
));
1983 f
->f_un
.f_forw
.f_addr
= res
;
1988 if ((f
->f_file
= open(p
, logflags
, 0600)) < 0) {
1989 f
->f_type
= F_UNUSED
;
1994 f
->f_flags
|= FFLAG_SYNC
;
1995 if (isatty(f
->f_file
)) {
1996 if (strcmp(p
, ctty
) == 0)
1997 f
->f_type
= F_CONSOLE
;
2000 strlcpy(f
->f_un
.f_fname
, p
+ sizeof(_PATH_DEV
) - 1,
2001 sizeof(f
->f_un
.f_fname
));
2003 strlcpy(f
->f_un
.f_fname
, p
, sizeof(f
->f_un
.f_fname
));
2009 if ((f
->f_file
= open(p
+ 1, O_RDWR
, 0 )) < 0) {
2010 f
->f_type
= F_UNUSED
;
2014 if (fstat(f
->f_file
,&sb
) < 0) {
2016 f
->f_type
= F_UNUSED
;
2020 f
->f_un
.f_ring
.f_footer
=
2021 mmap(NULL
, sizeof(struct clog_footer
),
2022 PROT_READ
|PROT_WRITE
, MAP_SHARED
,
2023 f
->f_file
, sb
.st_size
-sizeof(struct clog_footer
));
2024 if (f
->f_un
.f_ring
.f_footer
== NULL
) {
2026 f
->f_type
= F_UNUSED
;
2030 if (memcmp(&(f
->f_un
.f_ring
.f_footer
->cf_magic
), MAGIC_CONST
, 4) != 0) {
2031 munmap(f
->f_un
.f_ring
.f_footer
,
2032 sizeof(struct clog_footer
));
2034 f
->f_type
= F_UNUSED
;
2039 f
->f_un
.f_ring
.f_size
= sb
.st_size
;
2040 strcpy(f
->f_un
.f_ring
.f_rname
, p
+ 1);
2045 f
->f_un
.f_pipe
.f_pid
= 0;
2046 strlcpy(f
->f_un
.f_pipe
.f_pname
, p
+ 1,
2047 sizeof(f
->f_un
.f_pipe
.f_pname
));
2056 for (i
= 0; i
< MAXUNAMES
&& *p
; i
++) {
2057 for (q
= p
; *q
&& *q
!= ','; )
2059 strncpy(f
->f_un
.f_uname
[i
], p
, 32);
2061 f
->f_un
.f_uname
[i
][32] = '\0';
2063 f
->f_un
.f_uname
[i
][q
- p
] = '\0';
2064 while (*q
== ',' || *q
== ' ')
2068 f
->f_type
= F_USERS
;
2075 * Decode a symbolic name to a numeric value
2078 decode(const char *name
, CODE
*codetab
)
2084 return (atoi(name
));
2086 for (p
= buf
; *name
&& p
< &buf
[sizeof(buf
) - 1]; p
++, name
++) {
2088 *p
= tolower(*name
);
2093 for (c
= codetab
; c
->c_name
; c
++)
2094 if (!strcmp(buf
, c
->c_name
))
2107 MarkSeq
+= TIMERINTVL
;
2108 if (MarkSeq
>= MarkInterval
) {
2109 logmsg(LOG_INFO
, "-- MARK --",
2110 LocalHostName
, ADDDATE
|MARK
);
2114 for (f
= Files
; f
; f
= f
->f_next
) {
2115 if (f
->f_prevcount
&& now
>= REPEATTIME(f
)) {
2116 dprintf("flush %s: repeated %d times, %d sec.\n",
2117 TypeNames
[f
->f_type
], f
->f_prevcount
,
2118 repeatinterval
[f
->f_repeatcount
]);
2119 fprintlog(f
, 0, NULL
);
2124 /* Walk the dead queue, and see if we should signal somebody. */
2125 for (q
= TAILQ_FIRST(&deadq_head
); q
!= NULL
; q
= next
) {
2126 next
= TAILQ_NEXT(q
, dq_entries
);
2128 switch (q
->dq_timeout
) {
2130 /* Already signalled once, try harder now. */
2131 if (kill(q
->dq_pid
, SIGKILL
) != 0)
2132 deadq_remove(q
->dq_pid
);
2137 * Timed out on dead queue, send terminate
2138 * signal. Note that we leave the removal
2139 * from the dead queue to reapchild(), which
2140 * will also log the event (unless the process
2141 * didn't even really exist, in case we simply
2142 * drop it from the dead queue).
2144 if (kill(q
->dq_pid
, SIGTERM
) != 0)
2145 deadq_remove(q
->dq_pid
);
2157 * fork off and become a daemon, but wait for the child to come online
2158 * before returing to the parent, or we get disk thrashing at boot etc.
2159 * Set a timer so we don't hang forever if it wedges.
2162 waitdaemon(int nochdir
, int noclose
, int maxwait
)
2166 pid_t pid
, childpid
;
2168 switch (childpid
= fork()) {
2174 signal(SIGALRM
, timedout
);
2176 while ((pid
= wait3(&status
, 0, NULL
)) != -1) {
2177 if (WIFEXITED(status
))
2178 errx(1, "child pid %d exited with return code %d",
2179 pid
, WEXITSTATUS(status
));
2180 if (WIFSIGNALED(status
))
2181 errx(1, "child pid %d exited on signal %d%s",
2182 pid
, WTERMSIG(status
),
2183 WCOREDUMP(status
) ? " (core dumped)" :
2185 if (pid
== childpid
) /* it's gone... */
2197 if (!noclose
&& (fd
= open(_PATH_DEVNULL
, O_RDWR
, 0)) != -1) {
2198 dup2(fd
, STDIN_FILENO
);
2199 dup2(fd
, STDOUT_FILENO
);
2200 dup2(fd
, STDERR_FILENO
);
2208 * We get a SIGALRM from the child when it's running and finished doing it's
2209 * fsync()'s or O_SYNC writes for all the boot messages.
2211 * We also get a signal from the kernel if the timer expires, so check to
2212 * see what happened.
2215 timedout(int sig __unused
)
2219 signal(SIGALRM
, SIG_DFL
);
2221 errx(1, "timed out waiting for child");
2227 * Add `s' to the list of allowable peer addresses to accept messages
2230 * `s' is a string in the form:
2232 * [*]domainname[:{servicename|portnumber|*}]
2236 * netaddr/maskbits[:{servicename|portnumber|*}]
2238 * Returns -1 on error, 0 if the argument was valid.
2244 struct allowedpeer ap
;
2247 struct addrinfo hints
, *res
;
2248 struct in_addr
*addrp
, *maskp
;
2251 u_int32_t
*addr6p
, *mask6p
;
2253 char ip
[NI_MAXHOST
];
2256 if (*s
!= '[' || (cp1
= strchr(s
+ 1, ']')) == NULL
)
2259 if ((cp1
= strrchr(cp1
, ':'))) {
2260 /* service/port provided */
2262 if (strlen(cp1
) == 1 && *cp1
== '*')
2263 /* any port allowed */
2265 else if ((se
= getservbyname(cp1
, "udp"))) {
2266 ap
.port
= ntohs(se
->s_port
);
2268 ap
.port
= strtol(cp1
, &cp2
, 0);
2270 return (-1); /* port not numeric */
2273 if ((se
= getservbyname("syslog", "udp")))
2274 ap
.port
= ntohs(se
->s_port
);
2276 /* sanity, should not happen */
2280 if ((cp1
= strchr(s
, '/')) != NULL
&&
2281 strspn(cp1
+ 1, "0123456789") == strlen(cp1
+ 1)) {
2283 if ((masklen
= atoi(cp1
+ 1)) < 0)
2288 cp2
= s
+ strlen(s
) - 1;
2299 memset(&hints
, 0, sizeof(hints
));
2300 hints
.ai_family
= PF_UNSPEC
;
2301 hints
.ai_socktype
= SOCK_DGRAM
;
2302 hints
.ai_flags
= AI_PASSIVE
| AI_NUMERICHOST
;
2303 if (getaddrinfo(s
, NULL
, &hints
, &res
) == 0) {
2305 memcpy(&ap
.a_addr
, res
->ai_addr
, res
->ai_addrlen
);
2306 memset(&ap
.a_mask
, 0, sizeof(ap
.a_mask
));
2307 ap
.a_mask
.ss_family
= res
->ai_family
;
2308 if (res
->ai_family
== AF_INET
) {
2309 ap
.a_mask
.ss_len
= sizeof(struct sockaddr_in
);
2310 maskp
= &((struct sockaddr_in
*)&ap
.a_mask
)->sin_addr
;
2311 addrp
= &((struct sockaddr_in
*)&ap
.a_addr
)->sin_addr
;
2313 /* use default netmask */
2314 if (IN_CLASSA(ntohl(addrp
->s_addr
)))
2315 maskp
->s_addr
= htonl(IN_CLASSA_NET
);
2316 else if (IN_CLASSB(ntohl(addrp
->s_addr
)))
2317 maskp
->s_addr
= htonl(IN_CLASSB_NET
);
2319 maskp
->s_addr
= htonl(IN_CLASSC_NET
);
2320 } else if (masklen
<= 32) {
2321 /* convert masklen to netmask */
2325 maskp
->s_addr
= htonl(~((1 << (32 - masklen
)) - 1));
2330 /* Lose any host bits in the network number. */
2331 addrp
->s_addr
&= maskp
->s_addr
;
2334 else if (res
->ai_family
== AF_INET6
&& masklen
<= 128) {
2335 ap
.a_mask
.ss_len
= sizeof(struct sockaddr_in6
);
2338 mask6p
= (u_int32_t
*)&((struct sockaddr_in6
*)&ap
.a_mask
)->sin6_addr
;
2339 /* convert masklen to netmask */
2340 while (masklen
> 0) {
2342 *mask6p
= htonl(~(0xffffffff >> masklen
));
2345 *mask6p
++ = 0xffffffff;
2348 /* Lose any host bits in the network number. */
2349 mask6p
= (u_int32_t
*)&((struct sockaddr_in6
*)&ap
.a_mask
)->sin6_addr
;
2350 addr6p
= (u_int32_t
*)&((struct sockaddr_in6
*)&ap
.a_addr
)->sin6_addr
;
2351 for (i
= 0; i
< 4; i
++)
2352 addr6p
[i
] &= mask6p
[i
];
2361 /* arg `s' is domain name */
2375 printf("allowaddr: rule %d: ", NumAllowed
);
2377 printf("numeric, ");
2378 getnameinfo((struct sockaddr
*)&ap
.a_addr
,
2379 ((struct sockaddr
*)&ap
.a_addr
)->sa_len
,
2380 ip
, sizeof ip
, NULL
, 0, NI_NUMERICHOST
);
2381 printf("addr = %s, ", ip
);
2382 getnameinfo((struct sockaddr
*)&ap
.a_mask
,
2383 ((struct sockaddr
*)&ap
.a_mask
)->sa_len
,
2384 ip
, sizeof ip
, NULL
, 0, NI_NUMERICHOST
);
2385 printf("mask = %s; ", ip
);
2387 printf("domainname = %s; ", ap
.a_name
);
2389 printf("port = %d\n", ap
.port
);
2392 if ((AllowedPeers
= realloc(AllowedPeers
,
2393 ++NumAllowed
* sizeof(struct allowedpeer
)))
2395 logerror("realloc");
2398 memcpy(&AllowedPeers
[NumAllowed
- 1], &ap
, sizeof(struct allowedpeer
));
2403 * Validate that the remote peer has permission to log to us.
2406 validate(struct sockaddr
*sa
, const char *hname
)
2410 char *cp
, name
[NI_MAXHOST
], ip
[NI_MAXHOST
], port
[NI_MAXSERV
];
2411 struct allowedpeer
*ap
;
2412 struct sockaddr_in
*sin4
, *a4p
= NULL
, *m4p
= NULL
;
2415 struct sockaddr_in6
*sin6
, *a6p
= NULL
, *m6p
= NULL
;
2417 struct addrinfo hints
, *res
;
2420 if (NumAllowed
== 0)
2421 /* traditional behaviour, allow everything */
2424 strlcpy(name
, hname
, sizeof(name
));
2425 memset(&hints
, 0, sizeof(hints
));
2426 hints
.ai_family
= PF_UNSPEC
;
2427 hints
.ai_socktype
= SOCK_DGRAM
;
2428 hints
.ai_flags
= AI_PASSIVE
| AI_NUMERICHOST
;
2429 if (getaddrinfo(name
, NULL
, &hints
, &res
) == 0)
2431 else if (strchr(name
, '.') == NULL
) {
2432 strlcat(name
, ".", sizeof name
);
2433 strlcat(name
, LocalDomain
, sizeof name
);
2435 if (getnameinfo(sa
, sa
->sa_len
, ip
, sizeof ip
, port
, sizeof port
,
2436 NI_NUMERICHOST
| NI_NUMERICSERV
) != 0)
2437 return (0); /* for safety, should not occur */
2438 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2442 /* now, walk down the list */
2443 for (i
= 0, ap
= AllowedPeers
; i
< NumAllowed
; i
++, ap
++) {
2444 if (ap
->port
!= 0 && ap
->port
!= sport
) {
2445 dprintf("rejected in rule %d due to port mismatch.\n", i
);
2449 if (ap
->isnumeric
) {
2450 if (ap
->a_addr
.ss_family
!= sa
->sa_family
) {
2451 dprintf("rejected in rule %d due to address family mismatch.\n", i
);
2454 if (ap
->a_addr
.ss_family
== AF_INET
) {
2455 sin4
= (struct sockaddr_in
*)sa
;
2456 a4p
= (struct sockaddr_in
*)&ap
->a_addr
;
2457 m4p
= (struct sockaddr_in
*)&ap
->a_mask
;
2458 if ((sin4
->sin_addr
.s_addr
& m4p
->sin_addr
.s_addr
)
2459 != a4p
->sin_addr
.s_addr
) {
2460 dprintf("rejected in rule %d due to IP mismatch.\n", i
);
2465 else if (ap
->a_addr
.ss_family
== AF_INET6
) {
2466 sin6
= (struct sockaddr_in6
*)sa
;
2467 a6p
= (struct sockaddr_in6
*)&ap
->a_addr
;
2468 m6p
= (struct sockaddr_in6
*)&ap
->a_mask
;
2469 if (a6p
->sin6_scope_id
!= 0 &&
2470 sin6
->sin6_scope_id
!= a6p
->sin6_scope_id
) {
2471 dprintf("rejected in rule %d due to scope mismatch.\n", i
);
2475 for (j
= 0; j
< 16; j
+= 4) {
2476 if ((*(u_int32_t
*)&sin6
->sin6_addr
.s6_addr
[j
] & *(u_int32_t
*)&m6p
->sin6_addr
.s6_addr
[j
])
2477 != *(u_int32_t
*)&a6p
->sin6_addr
.s6_addr
[j
]) {
2483 dprintf("rejected in rule %d due to IP mismatch.\n", i
);
2494 /* allow wildmatch */
2497 if (l2
> l1
|| memcmp(cp
, &name
[l1
- l2
], l2
) != 0) {
2498 dprintf("rejected in rule %d due to name mismatch.\n", i
);
2504 if (l2
!= l1
|| memcmp(cp
, name
, l1
) != 0) {
2505 dprintf("rejected in rule %d due to name mismatch.\n", i
);
2510 dprintf("accepted in rule %d.\n", i
);
2511 return (1); /* hooray! */
2517 * Fairly similar to popen(3), but returns an open descriptor, as
2518 * opposed to a FILE *.
2521 p_open(const char *prog
, pid_t
*rpid
)
2523 int pfd
[2], nulldesc
, i
;
2525 sigset_t omask
, mask
;
2526 char *argv
[4]; /* sh -c cmd NULL */
2529 if (pipe(pfd
) == -1)
2531 if ((nulldesc
= open(_PATH_DEVNULL
, O_RDWR
)) == -1)
2532 /* we are royally screwed anyway */
2536 sigaddset(&mask
, SIGALRM
);
2537 sigaddset(&mask
, SIGHUP
);
2538 sigprocmask(SIG_BLOCK
, &mask
, &omask
);
2539 switch ((pid
= fork())) {
2541 sigprocmask(SIG_SETMASK
, &omask
, 0);
2546 argv
[0] = strdup("sh");
2547 argv
[1] = strdup("-c");
2548 argv
[2] = strdup(prog
);
2550 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] == NULL
) {
2556 setsid(); /* Avoid catching SIGHUPs. */
2559 * Throw away pending signals, and reset signal
2560 * behaviour to standard values.
2562 signal(SIGALRM
, SIG_IGN
);
2563 signal(SIGHUP
, SIG_IGN
);
2564 sigprocmask(SIG_SETMASK
, &omask
, 0);
2565 signal(SIGPIPE
, SIG_DFL
);
2566 signal(SIGQUIT
, SIG_DFL
);
2567 signal(SIGALRM
, SIG_DFL
);
2568 signal(SIGHUP
, SIG_DFL
);
2570 dup2(pfd
[0], STDIN_FILENO
);
2571 dup2(nulldesc
, STDOUT_FILENO
);
2572 dup2(nulldesc
, STDERR_FILENO
);
2573 for (i
= getdtablesize(); i
> 2; i
--)
2576 execvp(_PATH_BSHELL
, argv
);
2580 sigprocmask(SIG_SETMASK
, &omask
, 0);
2584 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2585 * supposed to get an EWOULDBLOCK on writev(2), which is
2586 * caught by the logic above anyway, which will in turn close
2587 * the pipe, and fork a new logging subprocess if necessary.
2588 * The stale subprocess will be killed some time later unless
2589 * it terminated itself due to closing its input pipe (so we
2590 * get rid of really dead puppies).
2592 if (fcntl(pfd
[1], F_SETFL
, O_NONBLOCK
) == -1) {
2594 snprintf(errmsg
, sizeof errmsg
,
2595 "Warning: cannot change pipe to PID %d to "
2596 "non-blocking behaviour.",
2605 deadq_enter(pid_t pid
, const char *name
)
2611 * Be paranoid, if we can't signal the process, don't enter it
2612 * into the dead queue (perhaps it's already dead). If possible,
2613 * we try to fetch and log the child's status.
2615 if (kill(pid
, 0) != 0) {
2616 if (waitpid(pid
, &status
, WNOHANG
) > 0)
2617 log_deadchild(pid
, status
, name
);
2621 p
= malloc(sizeof(struct deadq_entry
));
2628 p
->dq_timeout
= DQ_TIMO_INIT
;
2629 TAILQ_INSERT_TAIL(&deadq_head
, p
, dq_entries
);
2633 deadq_remove(pid_t pid
)
2637 TAILQ_FOREACH(q
, &deadq_head
, dq_entries
) {
2638 if (q
->dq_pid
== pid
) {
2639 TAILQ_REMOVE(&deadq_head
, q
, dq_entries
);
2649 log_deadchild(pid_t pid
, int status
, const char *name
)
2655 errno
= 0; /* Keep strerror() stuff out of logerror messages. */
2656 if (WIFSIGNALED(status
)) {
2657 reason
= "due to signal";
2658 code
= WTERMSIG(status
);
2660 reason
= "with status";
2661 code
= WEXITSTATUS(status
);
2665 snprintf(buf
, sizeof buf
,
2666 "Logging subprocess %d (%s) exited %s %d.",
2667 pid
, name
, reason
, code
);
2672 socksetup(int af
, const char *bindhostname
)
2674 struct addrinfo hints
, *res
, *r
;
2675 int error
, maxs
, *s
, *socks
;
2677 memset(&hints
, 0, sizeof(hints
));
2678 hints
.ai_flags
= AI_PASSIVE
;
2679 hints
.ai_family
= af
;
2680 hints
.ai_socktype
= SOCK_DGRAM
;
2681 error
= getaddrinfo(bindhostname
, "syslog", &hints
, &res
);
2683 logerror(gai_strerror(error
));
2688 /* Count max number of sockets we may open */
2689 for (maxs
= 0, r
= res
; r
; r
= r
->ai_next
, maxs
++);
2690 socks
= malloc((maxs
+1) * sizeof(int));
2691 if (socks
== NULL
) {
2692 logerror("couldn't allocate memory for sockets");
2696 *socks
= 0; /* num of sockets counter at start of array */
2698 for (r
= res
; r
; r
= r
->ai_next
) {
2700 *s
= socket(r
->ai_family
, r
->ai_socktype
, r
->ai_protocol
);
2705 if (r
->ai_family
== AF_INET6
) {
2706 if (setsockopt(*s
, IPPROTO_IPV6
, IPV6_V6ONLY
,
2707 (char *)&on
, sizeof (on
)) < 0) {
2708 logerror("setsockopt");
2713 if (setsockopt(*s
, SOL_SOCKET
, SO_REUSEADDR
,
2714 (char *)&on
, sizeof (on
)) < 0) {
2715 logerror("setsockopt");
2719 if (bind(*s
, r
->ai_addr
, r
->ai_addrlen
) < 0) {
2745 rbwritev(struct filed
*f
, struct iovec
*iov
, int iovcnt
)
2751 for (i
= 0; i
< iovcnt
; i
++) {
2752 error
= rbwrite(f
, iov
[i
].iov_base
, iov
[i
].iov_len
);
2762 rbwrite(struct filed
*f
, char *buf
, size_t nbytes
)
2768 maxwrite
= f
->f_un
.f_ring
.f_footer
->cf_max
-
2769 f
->f_un
.f_ring
.f_footer
->cf_next
;
2772 f
->f_un
.f_ring
.f_footer
->cf_lock
= 1;
2773 while (nbytes
> 0) {
2774 maxwrite
= f
->f_un
.f_ring
.f_footer
->cf_max
-
2775 f
->f_un
.f_ring
.f_footer
->cf_next
;
2776 if (maxwrite
> nbytes
)
2778 error
= pwrite(f
->f_file
, buf
, maxwrite
,
2779 f
->f_un
.f_ring
.f_footer
->cf_next
);
2781 f
->f_un
.f_ring
.f_footer
->cf_lock
= 0;
2787 f
->f_un
.f_ring
.f_footer
->cf_next
+= error
;
2788 if (f
->f_un
.f_ring
.f_footer
->cf_next
==
2789 f
->f_un
.f_ring
.f_footer
->cf_max
) {
2790 f
->f_un
.f_ring
.f_footer
->cf_next
= 0;
2791 f
->f_un
.f_ring
.f_footer
->cf_wrap
= 1;
2795 f
->f_un
.f_ring
.f_footer
->cf_lock
= 0;
2802 socklen_t slen
, len
;
2804 if (getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &len
, &slen
) == 0) {
2806 setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &len
, slen
);