sys/vfs/autofs: Cleanup autofs_mount()
[dragonfly.git] / usr.sbin / syslogd / syslogd.c
blob40ffb7e3ff8959555a7d53e22acd5570144885a4
1 /*
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
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
29 * @(#)syslogd.c 8.3 (Berkeley) 4/4/94
30 * $FreeBSD: head/usr.sbin/syslogd/syslogd.c 258077 2013-11-13 01:04:02Z ian $
34 * syslogd -- log system messages
36 * This program implements a system log. It takes a series of lines.
37 * Each line may have a priority, signified as "<n>" as
38 * the first characters of the line. If this is
39 * not present, a default priority is used.
41 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
42 * cause it to reread its configuration file.
44 * Defined Constants:
46 * MAXLINE -- the maximum line length that can be handled.
47 * DEFUPRI -- the default priority for user messages
48 * DEFSPRI -- the default priority for kernel messages
50 * Author: Eric Allman
51 * extensive changes by Ralph Campbell
52 * more extensive changes by Eric Allman (again)
53 * Extension to log by program name as well as facility and priority
54 * by Peter da Silva.
55 * -u and -v by Harlan Stenn.
56 * Priority comparison code by Harlan Stenn.
59 #define MAXLINE 1024 /* maximum line length */
60 #define MAXSVLINE 120 /* maximum saved line length */
61 #define DEFUPRI (LOG_USER|LOG_NOTICE)
62 #define DEFSPRI (LOG_KERN|LOG_CRIT)
63 #define TIMERINTVL 30 /* interval for checking flush, mark */
64 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
65 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
67 #include <sys/param.h>
68 #include <sys/ioctl.h>
69 #include <sys/mman.h>
70 #include <sys/stat.h>
71 #include <sys/wait.h>
72 #include <sys/socket.h>
73 #include <sys/queue.h>
74 #include <sys/uio.h>
75 #include <sys/un.h>
76 #include <sys/time.h>
77 #include <sys/resource.h>
78 #include <sys/syslimits.h>
79 #include <sys/types.h>
81 #include <netinet/in.h>
82 #include <netdb.h>
83 #include <arpa/inet.h>
85 #include <ctype.h>
86 #include <err.h>
87 #include <errno.h>
88 #include <fcntl.h>
89 #include <libutil.h>
90 #include <limits.h>
91 #include <paths.h>
92 #include <signal.h>
93 #include <stdio.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #include <sysexits.h>
97 #include <unistd.h>
98 #include <utmpx.h>
100 #include "pathnames.h"
101 #include "ttymsg.h"
103 #define SYSLOG_NAMES
104 #include <sys/syslog.h>
106 const char *ConfFile = _PATH_LOGCONF;
107 const char *PidFile = _PATH_LOGPID;
108 const char ctty[] = _PATH_CONSOLE;
110 #define dprintf if (Debug) printf
112 #define MAXUNAMES 20 /* maximum number of user names */
115 * Unix sockets.
116 * We have two default sockets, one with 666 permissions,
117 * and one for privileged programs.
119 struct funix {
120 int s;
121 const char *name;
122 mode_t mode;
123 STAILQ_ENTRY(funix) next;
125 struct funix funix_secure = { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
126 { NULL } };
127 struct funix funix_default = { -1, _PATH_LOG, DEFFILEMODE,
128 { &funix_secure } };
130 STAILQ_HEAD(, funix) funixes = { &funix_default,
131 &(funix_secure.next.stqe_next) };
134 * Flags to logmsg().
137 #define IGN_CONS 0x001 /* don't print on console */
138 #define SYNC_FILE 0x002 /* do fsync on file after printing */
139 #define ADDDATE 0x004 /* add a date to the message */
140 #define MARK 0x008 /* this message is a mark */
141 #define ISKERNEL 0x010 /* kernel generated message */
144 * This structure represents the files that will have log
145 * copies printed.
146 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
147 * or if f_type if F_PIPE and f_pid > 0.
150 struct filed {
151 struct filed *f_next; /* next in linked list */
152 short f_type; /* entry type, see below */
153 short f_file; /* file descriptor */
154 time_t f_time; /* time this was last written */
155 char *f_host; /* host from which to recd. */
156 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
157 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
158 #define PRI_LT 0x1
159 #define PRI_EQ 0x2
160 #define PRI_GT 0x4
161 char *f_program; /* program this applies to */
162 union {
163 char f_uname[MAXUNAMES][MAXLOGNAME];
164 struct {
165 char f_hname[MAXHOSTNAMELEN];
166 struct addrinfo *f_addr;
168 } f_forw; /* forwarding address */
169 char f_fname[MAXPATHLEN];
170 struct {
171 char f_pname[MAXPATHLEN];
172 pid_t f_pid;
173 } f_pipe;
174 } f_un;
175 char f_prevline[MAXSVLINE]; /* last message logged */
176 char f_lasttime[16]; /* time of last occurrence */
177 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
178 int f_prevpri; /* pri of f_prevline */
179 int f_prevlen; /* length of f_prevline */
180 int f_prevcount; /* repetition cnt of prevline */
181 u_int f_repeatcount; /* number of "repeated" msgs */
182 int f_flags; /* file-specific flags */
183 #define FFLAG_SYNC 0x01
184 #define FFLAG_NEEDSYNC 0x02
188 * Queue of about-to-be dead processes we should watch out for.
191 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
192 struct stailhead *deadq_headp;
194 struct deadq_entry {
195 pid_t dq_pid;
196 int dq_timeout;
197 TAILQ_ENTRY(deadq_entry) dq_entries;
201 * The timeout to apply to processes waiting on the dead queue. Unit
202 * of measure is `mark intervals', i.e. 20 minutes by default.
203 * Processes on the dead queue will be terminated after that time.
206 #define DQ_TIMO_INIT 2
208 typedef struct deadq_entry *dq_t;
212 * Struct to hold records of network addresses that are allowed to log
213 * to us.
215 struct allowedpeer {
216 int isnumeric;
217 u_short port;
218 union {
219 struct {
220 struct sockaddr_storage addr;
221 struct sockaddr_storage mask;
222 } numeric;
223 char *name;
224 } u;
225 #define a_addr u.numeric.addr
226 #define a_mask u.numeric.mask
227 #define a_name u.name
232 * Intervals at which we flush out "message repeated" messages,
233 * in seconds after previous message is logged. After each flush,
234 * we move to the next interval until we reach the largest.
236 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
237 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
238 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
239 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
240 (f)->f_repeatcount = MAXREPEAT; \
243 /* values for f_type */
244 #define F_UNUSED 0 /* unused entry */
245 #define F_FILE 1 /* regular file */
246 #define F_TTY 2 /* terminal */
247 #define F_CONSOLE 3 /* console terminal */
248 #define F_FORW 4 /* remote machine */
249 #define F_USERS 5 /* list of users */
250 #define F_WALL 6 /* everyone logged on */
251 #define F_PIPE 7 /* pipe to program */
253 const char *TypeNames[8] = {
254 "UNUSED", "FILE", "TTY", "CONSOLE",
255 "FORW", "USERS", "WALL", "PIPE"
258 static struct filed *Files; /* Log files that we write to */
259 static struct filed consfile; /* Console */
261 static int Debug; /* debug flag */
262 static int resolve = 1; /* resolve hostname */
263 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
264 static const char *LocalDomain; /* our local domain name */
265 static int *finet; /* Internet datagram socket */
266 static int fklog = -1; /* /dev/klog */
267 static int Initialized; /* set when we have initialized ourselves */
268 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
269 static int MarkSeq; /* mark sequence number */
270 static int NoBind; /* don't bind() as suggested by RFC 3164 */
271 static int SecureMode; /* when true, receive only unix domain socks */
272 #ifdef INET6
273 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
274 #else
275 static int family = PF_INET; /* protocol family (IPv4 only) */
276 #endif
277 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
278 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
279 static int use_bootfile; /* log entire bootfile for every kern msg */
280 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
281 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
283 static char bootfile[MAXLINE+1]; /* booted kernel file */
285 struct allowedpeer *AllowedPeers; /* List of allowed peers */
286 static int NumAllowed; /* Number of entries in AllowedPeers */
287 static int RemoteAddDate; /* Always set the date on remote messages */
289 static int UniquePriority; /* Only log specified priority? */
290 static int LogFacPri; /* Put facility and priority in log message: */
291 /* 0=no, 1=numeric, 2=names */
292 static int KeepKernFac; /* Keep remotely logged kernel facility */
293 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
294 static struct pidfh *pfh;
296 volatile sig_atomic_t MarkSet, WantDie;
298 static int allowaddr(char *);
299 static void cfline(const char *, struct filed *,
300 const char *, const char *);
301 static const char *cvthname(struct sockaddr *);
302 static void deadq_enter(pid_t, const char *);
303 static int deadq_remove(pid_t);
304 static int decode(const char *, const CODE *);
305 static void die(int);
306 static void dodie(int);
307 static void dofsync(void);
308 static void domark(int);
309 static void fprintlog(struct filed *, int, const char *);
310 static int *socksetup(int, char *);
311 static void init(int);
312 static void logerror(const char *);
313 static void logmsg(int, const char *, const char *, int);
314 static void log_deadchild(pid_t, int, const char *);
315 static void markit(void);
316 static int skip_message(const char *, const char *, int);
317 static void printline(const char *, char *, int);
318 static void printsys(char *);
319 static int p_open(const char *, pid_t *);
320 static void readklog(void);
321 static void reapchild(int);
322 static void usage(void);
323 static int validate(struct sockaddr *, const char *);
324 static void unmapped(struct sockaddr *);
325 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
326 static int waitdaemon(int, int, int);
327 static void timedout(int);
328 static void increase_rcvbuf(int);
331 main(int argc, char *argv[])
333 int ch, i, fdsrmax = 0, l;
334 struct sockaddr_un sunx, fromunix;
335 struct sockaddr_storage frominet;
336 fd_set *fdsr = NULL;
337 char line[MAXLINE + 1];
338 char *bindhostname;
339 const char *hname;
340 struct timeval tv, *tvp;
341 struct sigaction sact;
342 struct funix *fx, *fx1;
343 sigset_t mask;
344 pid_t ppid = 1, spid;
345 socklen_t len;
347 bindhostname = NULL;
348 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nNop:P:sS:Tuv"))
349 != -1)
350 switch (ch) {
351 case '4':
352 family = PF_INET;
353 break;
354 #ifdef INET6
355 case '6':
356 family = PF_INET6;
357 break;
358 #endif
359 case '8':
360 mask_C1 = 0;
361 break;
362 case 'A':
363 send_to_all++;
364 break;
365 case 'a': /* allow specific network addresses only */
366 if (allowaddr(optarg) == -1)
367 usage();
368 break;
369 case 'b':
370 bindhostname = optarg;
371 break;
372 case 'c':
373 no_compress++;
374 break;
375 case 'C':
376 logflags |= O_CREAT;
377 break;
378 case 'd': /* debug */
379 Debug++;
380 break;
381 case 'f': /* configuration file */
382 ConfFile = optarg;
383 break;
384 case 'k': /* keep remote kern fac */
385 KeepKernFac = 1;
386 break;
387 case 'l':
389 long perml;
390 mode_t mode;
391 char *name, *ep;
393 if (optarg[0] == '/') {
394 mode = DEFFILEMODE;
395 name = optarg;
396 } else if ((name = strchr(optarg, ':')) != NULL) {
397 *name++ = '\0';
398 if (name[0] != '/')
399 errx(1, "socket name must be absolute "
400 "path");
401 if (isdigit(*optarg)) {
402 perml = strtol(optarg, &ep, 8);
403 if (*ep || perml < 0 ||
404 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
405 errx(1, "invalid mode %s, exiting",
406 optarg);
407 mode = (mode_t )perml;
408 } else
409 errx(1, "invalid mode %s, exiting",
410 optarg);
411 } else /* doesn't begin with '/', and no ':' */
412 errx(1, "can't parse path %s", optarg);
414 if (strlen(name) >= sizeof(sunx.sun_path))
415 errx(1, "%s path too long, exiting", name);
416 if ((fx = malloc(sizeof(struct funix))) == NULL)
417 errx(1, "malloc failed");
418 fx->s = -1;
419 fx->name = name;
420 fx->mode = mode;
421 STAILQ_INSERT_TAIL(&funixes, fx, next);
422 break;
424 case 'm': /* mark interval */
425 MarkInterval = atoi(optarg) * 60;
426 break;
427 case 'N':
428 NoBind = 1;
429 SecureMode = 1;
430 break;
431 case 'n':
432 resolve = 0;
433 break;
434 case 'o':
435 use_bootfile = 1;
436 break;
437 case 'p': /* path */
438 if (strlen(optarg) >= sizeof(sunx.sun_path))
439 errx(1, "%s path too long, exiting", optarg);
440 funix_default.name = optarg;
441 break;
442 case 'P': /* path for alt. PID */
443 PidFile = optarg;
444 break;
445 case 's': /* no network mode */
446 SecureMode++;
447 break;
448 case 'S': /* path for privileged originator */
449 if (strlen(optarg) >= sizeof(sunx.sun_path))
450 errx(1, "%s path too long, exiting", optarg);
451 funix_secure.name = optarg;
452 break;
453 case 'T':
454 RemoteAddDate = 1;
455 break;
456 case 'u': /* only log specified priority */
457 UniquePriority++;
458 break;
459 case 'v': /* log facility and priority */
460 LogFacPri++;
461 break;
462 default:
463 usage();
465 if ((argc -= optind) != 0)
466 usage();
468 pfh = pidfile_open(PidFile, 0600, &spid);
469 if (pfh == NULL) {
470 if (errno == EEXIST)
471 errx(1, "syslogd already running, pid: %d", spid);
472 warn("cannot open pid file");
475 if (!Debug) {
476 ppid = waitdaemon(0, 0, 30);
477 if (ppid < 0) {
478 warn("could not become daemon");
479 pidfile_remove(pfh);
480 exit(1);
482 } else {
483 setlinebuf(stdout);
486 if (NumAllowed)
487 endservent();
489 consfile.f_type = F_CONSOLE;
490 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
491 sizeof(consfile.f_un.f_fname));
492 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
493 (void)signal(SIGTERM, dodie);
494 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
495 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
497 * We don't want the SIGCHLD and SIGHUP handlers to interfere
498 * with each other; they are likely candidates for being called
499 * simultaneously (SIGHUP closes pipe descriptor, process dies,
500 * SIGCHLD happens).
502 sigemptyset(&mask);
503 sigaddset(&mask, SIGHUP);
504 sact.sa_handler = reapchild;
505 sact.sa_mask = mask;
506 sact.sa_flags = SA_RESTART;
507 (void)sigaction(SIGCHLD, &sact, NULL);
508 (void)signal(SIGALRM, domark);
509 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
510 (void)alarm(TIMERINTVL);
512 TAILQ_INIT(&deadq_head);
514 #ifndef SUN_LEN
515 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
516 #endif
517 STAILQ_FOREACH_MUTABLE(fx, &funixes, next, fx1) {
518 (void)unlink(fx->name);
519 memset(&sunx, 0, sizeof(sunx));
520 sunx.sun_family = AF_LOCAL;
521 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
522 fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
523 if (fx->s < 0 ||
524 bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
525 chmod(fx->name, fx->mode) < 0) {
526 (void)snprintf(line, sizeof line,
527 "cannot create %s", fx->name);
528 logerror(line);
529 dprintf("cannot create %s (%d)\n", fx->name, errno);
530 if (fx == &funix_default || fx == &funix_secure)
531 die(0);
532 else {
533 STAILQ_REMOVE(&funixes, fx, funix, next);
534 continue;
537 increase_rcvbuf(fx->s);
539 if (SecureMode <= 1)
540 finet = socksetup(family, bindhostname);
542 if (finet) {
543 if (SecureMode) {
544 for (i = 0; i < *finet; i++) {
545 if (shutdown(finet[i+1], SHUT_RD) < 0) {
546 logerror("shutdown");
547 if (!Debug)
548 die(0);
551 } else {
552 dprintf("listening on inet and/or inet6 socket\n");
554 dprintf("sending on inet and/or inet6 socket\n");
557 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
558 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
559 fklog = -1;
560 if (fklog < 0)
561 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
563 /* tuck my process id away */
564 pidfile_write(pfh);
566 dprintf("off & running....\n");
568 init(0);
569 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
570 sigemptyset(&mask);
571 sigaddset(&mask, SIGCHLD);
572 sact.sa_handler = init;
573 sact.sa_mask = mask;
574 sact.sa_flags = SA_RESTART;
575 (void)sigaction(SIGHUP, &sact, NULL);
577 tvp = &tv;
578 tv.tv_sec = tv.tv_usec = 0;
580 if (fklog != -1 && fklog > fdsrmax)
581 fdsrmax = fklog;
582 if (finet && !SecureMode) {
583 for (i = 0; i < *finet; i++) {
584 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
585 fdsrmax = finet[i+1];
588 STAILQ_FOREACH(fx, &funixes, next)
589 if (fx->s > fdsrmax)
590 fdsrmax = fx->s;
592 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
593 sizeof(fd_mask));
594 if (fdsr == NULL)
595 errx(1, "calloc fd_set");
597 for (;;) {
598 if (MarkSet)
599 markit();
600 if (WantDie)
601 die(WantDie);
603 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
604 sizeof(fd_mask));
606 if (fklog != -1)
607 FD_SET(fklog, fdsr);
608 if (finet && !SecureMode) {
609 for (i = 0; i < *finet; i++) {
610 if (finet[i+1] != -1)
611 FD_SET(finet[i+1], fdsr);
614 STAILQ_FOREACH(fx, &funixes, next)
615 FD_SET(fx->s, fdsr);
617 i = select(fdsrmax+1, fdsr, NULL, NULL,
618 needdofsync ? &tv : tvp);
619 switch (i) {
620 case 0:
621 dofsync();
622 needdofsync = 0;
623 if (tvp) {
624 tvp = NULL;
625 if (ppid != 1)
626 kill(ppid, SIGALRM);
628 continue;
629 case -1:
630 if (errno != EINTR)
631 logerror("select");
632 continue;
634 if (fklog != -1 && FD_ISSET(fklog, fdsr))
635 readklog();
636 if (finet && !SecureMode) {
637 for (i = 0; i < *finet; i++) {
638 if (FD_ISSET(finet[i+1], fdsr)) {
639 len = sizeof(frominet);
640 l = recvfrom(finet[i+1], line, MAXLINE,
641 0, (struct sockaddr *)&frominet,
642 &len);
643 if (l > 0) {
644 line[l] = '\0';
645 hname = cvthname((struct sockaddr *)&frominet);
646 unmapped((struct sockaddr *)&frominet);
647 if (validate((struct sockaddr *)&frominet, hname))
648 printline(hname, line, RemoteAddDate ? ADDDATE : 0);
649 } else if (l < 0 && errno != EINTR)
650 logerror("recvfrom inet");
654 STAILQ_FOREACH(fx, &funixes, next) {
655 if (FD_ISSET(fx->s, fdsr)) {
656 len = sizeof(fromunix);
657 l = recvfrom(fx->s, line, MAXLINE, 0,
658 (struct sockaddr *)&fromunix, &len);
659 if (l > 0) {
660 line[l] = '\0';
661 printline(LocalHostName, line, 0);
662 } else if (l < 0 && errno != EINTR)
663 logerror("recvfrom unix");
667 if (fdsr)
668 free(fdsr);
671 static void
672 unmapped(struct sockaddr *sa)
674 struct sockaddr_in6 *sin6;
675 struct sockaddr_in sin4;
677 if (sa->sa_family != AF_INET6)
678 return;
679 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
680 sizeof(sin4) > sa->sa_len)
681 return;
682 sin6 = (struct sockaddr_in6 *)sa;
683 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
684 return;
686 memset(&sin4, 0, sizeof(sin4));
687 sin4.sin_family = AF_INET;
688 sin4.sin_len = sizeof(struct sockaddr_in);
689 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
690 sizeof(sin4.sin_addr));
691 sin4.sin_port = sin6->sin6_port;
693 memcpy(sa, &sin4, sin4.sin_len);
696 static void
697 usage(void)
700 fprintf(stderr, "%s\n%s\n%s\n%s\n",
701 "usage: syslogd [-468ACcdknosTuv] [-a allowed_peer]",
702 " [-b bind_address] [-f config_file]",
703 " [-l [mode:]path] [-m mark_interval]",
704 " [-P pid_file] [-p log_socket]");
705 exit(1);
709 * Take a raw input line, decode the message, and print the message
710 * on the appropriate log files.
712 static void
713 printline(const char *hname, char *msg, int flags)
715 char *p, *q;
716 long n;
717 int c, pri;
718 char line[MAXLINE + 1];
720 /* test for special codes */
721 p = msg;
722 pri = DEFUPRI;
723 if (*p == '<') {
724 errno = 0;
725 n = strtol(p + 1, &q, 10);
726 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
727 p = q + 1;
728 pri = n;
731 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
732 pri = DEFUPRI;
735 * Don't allow users to log kernel messages.
736 * NOTE: since LOG_KERN == 0 this will also match
737 * messages with no facility specified.
739 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
740 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
742 q = line;
744 while ((c = (unsigned char)*p++) != '\0' &&
745 q < &line[sizeof(line) - 4]) {
746 if (mask_C1 && (c & 0x80) && c < 0xA0) {
747 c &= 0x7F;
748 *q++ = 'M';
749 *q++ = '-';
751 if (isascii(c) && iscntrl(c)) {
752 if (c == '\n') {
753 *q++ = ' ';
754 } else if (c == '\t') {
755 *q++ = '\t';
756 } else {
757 *q++ = '^';
758 *q++ = c ^ 0100;
760 } else {
761 *q++ = c;
764 *q = '\0';
766 logmsg(pri, line, hname, flags);
770 * Read /dev/klog while data are available, split into lines.
772 static void
773 readklog(void)
775 char *p, *q, line[MAXLINE + 1];
776 int len, i;
778 len = 0;
779 for (;;) {
780 i = read(fklog, line + len, MAXLINE - 1 - len);
781 if (i > 0) {
782 line[i + len] = '\0';
783 } else {
784 if (i < 0 && errno != EINTR && errno != EAGAIN) {
785 logerror("klog");
786 fklog = -1;
788 break;
791 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
792 *q = '\0';
793 printsys(p);
795 len = strlen(p);
796 if (len >= MAXLINE - 1) {
797 printsys(p);
798 len = 0;
800 if (len > 0)
801 memmove(line, p, len + 1);
803 if (len > 0)
804 printsys(line);
808 * Take a raw input line from /dev/klog, format similar to syslog().
810 static void
811 printsys(char *msg)
813 char *p, *q;
814 long n;
815 int flags, isprintf, pri;
817 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
818 p = msg;
819 pri = DEFSPRI;
820 isprintf = 1;
821 if (*p == '<') {
822 errno = 0;
823 n = strtol(p + 1, &q, 10);
824 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
825 p = q + 1;
826 pri = n;
827 isprintf = 0;
831 * Kernel printf's and LOG_CONSOLE messages have been displayed
832 * on the console already.
834 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
835 flags |= IGN_CONS;
836 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
837 pri = DEFSPRI;
838 logmsg(pri, p, LocalHostName, flags);
841 static time_t now;
844 * Match a program or host name against a specification.
845 * Return a non-0 value if the message must be ignored
846 * based on the specification.
848 static int
849 skip_message(const char *name, const char *spec, int checkcase)
851 const char *s;
852 char prev, next;
853 int exclude = 0;
854 /* Behaviour on explicit match */
856 if (spec == NULL)
857 return 0;
858 switch (*spec) {
859 case '-':
860 exclude = 1;
861 /*FALLTHROUGH*/
862 case '+':
863 spec++;
864 break;
865 default:
866 break;
868 if (checkcase)
869 s = strstr (spec, name);
870 else
871 s = strcasestr (spec, name);
873 if (s != NULL) {
874 prev = (s == spec ? ',' : *(s - 1));
875 next = *(s + strlen (name));
877 if (prev == ',' && (next == '\0' || next == ','))
878 /* Explicit match: skip iff the spec is an
879 exclusive one. */
880 return exclude;
883 /* No explicit match for this name: skip the message iff
884 the spec is an inclusive one. */
885 return !exclude;
889 * Log a message to the appropriate log files, users, etc. based on
890 * the priority.
892 static void
893 logmsg(int pri, const char *msg, const char *from, int flags)
895 struct filed *f;
896 int i, fac, msglen, omask, prilev;
897 const char *timestamp;
898 char prog[NAME_MAX+1];
899 char buf[MAXLINE+1];
901 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
902 pri, flags, from, msg);
904 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
907 * Check to see if msg looks non-standard.
909 msglen = strlen(msg);
910 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
911 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
912 flags |= ADDDATE;
914 (void)time(&now);
915 if (flags & ADDDATE) {
916 timestamp = ctime(&now) + 4;
917 } else {
918 timestamp = msg;
919 msg += 16;
920 msglen -= 16;
923 /* skip leading blanks */
924 while (isspace(*msg)) {
925 msg++;
926 msglen--;
929 /* extract facility and priority level */
930 if (flags & MARK)
931 fac = LOG_NFACILITIES;
932 else
933 fac = LOG_FAC(pri);
935 /* Check maximum facility number. */
936 if (fac > LOG_NFACILITIES) {
937 (void)sigsetmask(omask);
938 return;
941 prilev = LOG_PRI(pri);
943 /* extract program name */
944 for (i = 0; i < NAME_MAX; i++) {
945 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
946 msg[i] == '/' || isspace(msg[i]))
947 break;
948 prog[i] = msg[i];
950 prog[i] = 0;
952 /* add kernel prefix for kernel messages */
953 if (flags & ISKERNEL) {
954 snprintf(buf, sizeof(buf), "%s: %s",
955 use_bootfile ? bootfile : "kernel", msg);
956 msg = buf;
957 msglen = strlen(buf);
960 /* log the message to the particular outputs */
961 if (!Initialized) {
962 f = &consfile;
964 * Open in non-blocking mode to avoid hangs during open
965 * and close(waiting for the port to drain).
967 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
969 if (f->f_file >= 0) {
970 (void)strlcpy(f->f_lasttime, timestamp,
971 sizeof(f->f_lasttime));
972 fprintlog(f, flags, msg);
973 (void)close(f->f_file);
975 (void)sigsetmask(omask);
976 return;
978 for (f = Files; f; f = f->f_next) {
979 /* skip messages that are incorrect priority */
980 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
981 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
982 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
984 || f->f_pmask[fac] == INTERNAL_NOPRI)
985 continue;
987 /* skip messages with the incorrect hostname */
988 if (skip_message(from, f->f_host, 0))
989 continue;
991 /* skip messages with the incorrect program name */
992 if (skip_message(prog, f->f_program, 1))
993 continue;
995 /* skip message to console if it has already been printed */
996 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
997 continue;
999 /* don't output marks to recently written files */
1000 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1001 continue;
1004 * suppress duplicate lines to this file
1006 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1007 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1008 f->f_prevline && !strcmp(msg, f->f_prevline) &&
1009 !strcasecmp(from, f->f_prevhost)) {
1010 (void)strlcpy(f->f_lasttime, timestamp,
1011 sizeof(f->f_lasttime));
1012 f->f_prevcount++;
1013 dprintf("msg repeated %d times, %ld sec of %d\n",
1014 f->f_prevcount, (long)(now - f->f_time),
1015 repeatinterval[f->f_repeatcount]);
1017 * If domark would have logged this by now,
1018 * flush it now (so we don't hold isolated messages),
1019 * but back off so we'll flush less often
1020 * in the future.
1022 if (now > REPEATTIME(f)) {
1023 fprintlog(f, flags, NULL);
1024 BACKOFF(f);
1026 } else {
1027 /* new line, save it */
1028 if (f->f_prevcount)
1029 fprintlog(f, 0, NULL);
1030 f->f_repeatcount = 0;
1031 f->f_prevpri = pri;
1032 (void)strlcpy(f->f_lasttime, timestamp,
1033 sizeof(f->f_lasttime));
1034 (void)strlcpy(f->f_prevhost, from,
1035 sizeof(f->f_prevhost));
1036 if (msglen < MAXSVLINE) {
1037 f->f_prevlen = msglen;
1038 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1039 fprintlog(f, flags, NULL);
1040 } else {
1041 f->f_prevline[0] = 0;
1042 f->f_prevlen = 0;
1043 fprintlog(f, flags, msg);
1047 (void)sigsetmask(omask);
1050 static void
1051 dofsync(void)
1053 struct filed *f;
1055 for (f = Files; f; f = f->f_next) {
1056 if ((f->f_type == F_FILE) &&
1057 (f->f_flags & FFLAG_NEEDSYNC)) {
1058 f->f_flags &= ~FFLAG_NEEDSYNC;
1059 (void)fsync(f->f_file);
1064 #define IOV_SIZE 7
1065 static void
1066 fprintlog(struct filed *f, int flags, const char *msg)
1068 struct iovec iov[IOV_SIZE];
1069 struct iovec *v;
1070 struct addrinfo *r;
1071 int i, l, lsent = 0;
1072 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1073 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1074 const char *msgret;
1076 v = iov;
1077 if (f->f_type == F_WALL) {
1078 v->iov_base = greetings;
1079 /* The time displayed is not synchornized with the other log
1080 * destinations (like messages). Following fragment was using
1081 * ctime(&now), which was updating the time every 30 sec.
1082 * With f_lasttime, time is synchronized correctly.
1084 v->iov_len = snprintf(greetings, sizeof greetings,
1085 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1086 f->f_prevhost, f->f_lasttime);
1087 if (v->iov_len >= sizeof greetings)
1088 v->iov_len = sizeof greetings - 1;
1089 v++;
1090 v->iov_base = nul;
1091 v->iov_len = 0;
1092 v++;
1093 } else {
1094 v->iov_base = f->f_lasttime;
1095 v->iov_len = strlen(f->f_lasttime);
1096 v++;
1097 v->iov_base = space;
1098 v->iov_len = 1;
1099 v++;
1102 if (LogFacPri) {
1103 static char fp_buf[30]; /* Hollow laugh */
1104 int fac = f->f_prevpri & LOG_FACMASK;
1105 int pri = LOG_PRI(f->f_prevpri);
1106 const char *f_s = NULL;
1107 char f_n[5]; /* Hollow laugh */
1108 const char *p_s = NULL;
1109 char p_n[5]; /* Hollow laugh */
1111 if (LogFacPri > 1) {
1112 const CODE *c;
1114 for (c = facilitynames; c->c_name; c++) {
1115 if (c->c_val == fac) {
1116 f_s = c->c_name;
1117 break;
1120 for (c = prioritynames; c->c_name; c++) {
1121 if (c->c_val == pri) {
1122 p_s = c->c_name;
1123 break;
1127 if (!f_s) {
1128 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1129 f_s = f_n;
1131 if (!p_s) {
1132 snprintf(p_n, sizeof p_n, "%d", pri);
1133 p_s = p_n;
1135 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1136 v->iov_base = fp_buf;
1137 v->iov_len = strlen(fp_buf);
1138 } else {
1139 v->iov_base = nul;
1140 v->iov_len = 0;
1142 v++;
1144 v->iov_base = f->f_prevhost;
1145 v->iov_len = strlen(v->iov_base);
1146 v++;
1147 v->iov_base = space;
1148 v->iov_len = 1;
1149 v++;
1151 if (msg) {
1152 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1153 if (wmsg == NULL) {
1154 logerror("strdup");
1155 exit(1);
1157 v->iov_base = wmsg;
1158 v->iov_len = strlen(msg);
1159 } else if (f->f_prevcount > 1) {
1160 v->iov_base = repbuf;
1161 v->iov_len = snprintf(repbuf, sizeof repbuf,
1162 "last message repeated %d times", f->f_prevcount);
1163 } else if (f->f_prevline) {
1164 v->iov_base = f->f_prevline;
1165 v->iov_len = f->f_prevlen;
1166 } else {
1167 return;
1169 v++;
1171 dprintf("Logging to %s", TypeNames[f->f_type]);
1172 f->f_time = now;
1174 switch (f->f_type) {
1175 int port;
1176 case F_UNUSED:
1177 dprintf("\n");
1178 break;
1180 case F_FORW:
1181 port = (int)ntohs(((struct sockaddr_in *)
1182 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1183 if (port != 514) {
1184 dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1185 } else {
1186 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1188 /* check for local vs remote messages */
1189 if (strcasecmp(f->f_prevhost, LocalHostName))
1190 l = snprintf(line, sizeof line - 1,
1191 "<%d>%.15s Forwarded from %s: %s",
1192 f->f_prevpri, (char *)iov[0].iov_base,
1193 f->f_prevhost, (char *)iov[5].iov_base);
1194 else
1195 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1196 f->f_prevpri, (char *)iov[0].iov_base,
1197 (char *)iov[5].iov_base);
1198 if (l < 0)
1199 l = 0;
1200 else if (l > MAXLINE)
1201 l = MAXLINE;
1203 if (finet) {
1204 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1205 for (i = 0; i < *finet; i++) {
1206 #if 0
1208 * should we check AF first, or just
1209 * trial and error? FWD
1211 if (r->ai_family ==
1212 address_family_of(finet[i+1]))
1213 #endif
1214 lsent = sendto(finet[i+1], line, l, 0,
1215 r->ai_addr, r->ai_addrlen);
1216 if (lsent == l)
1217 break;
1219 if (lsent == l && !send_to_all)
1220 break;
1222 dprintf("lsent/l: %d/%d\n", lsent, l);
1223 if (lsent != l) {
1224 int e = errno;
1225 logerror("sendto");
1226 errno = e;
1227 switch (errno) {
1228 case ENOBUFS:
1229 case ENETDOWN:
1230 case ENETUNREACH:
1231 case EHOSTUNREACH:
1232 case EHOSTDOWN:
1233 case EADDRNOTAVAIL:
1234 break;
1235 /* case EBADF: */
1236 /* case EACCES: */
1237 /* case ENOTSOCK: */
1238 /* case EFAULT: */
1239 /* case EMSGSIZE: */
1240 /* case EAGAIN: */
1241 /* case ENOBUFS: */
1242 /* case ECONNREFUSED: */
1243 default:
1244 dprintf("removing entry: errno=%d\n", e);
1245 f->f_type = F_UNUSED;
1246 break;
1250 break;
1252 case F_FILE:
1253 dprintf(" %s\n", f->f_un.f_fname);
1254 v->iov_base = lf;
1255 v->iov_len = 1;
1256 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1258 * If writev(2) fails for potentially transient errors
1259 * like the filesystem being full, ignore it.
1260 * Otherwise remove this logfile from the list.
1262 if (errno != ENOSPC) {
1263 int e = errno;
1264 (void)close(f->f_file);
1265 f->f_type = F_UNUSED;
1266 errno = e;
1267 logerror(f->f_un.f_fname);
1269 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1270 f->f_flags |= FFLAG_NEEDSYNC;
1271 needdofsync = 1;
1273 break;
1275 case F_PIPE:
1276 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1277 v->iov_base = lf;
1278 v->iov_len = 1;
1279 if (f->f_un.f_pipe.f_pid == 0) {
1280 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1281 &f->f_un.f_pipe.f_pid)) < 0) {
1282 f->f_type = F_UNUSED;
1283 logerror(f->f_un.f_pipe.f_pname);
1284 break;
1287 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1288 int e = errno;
1289 (void)close(f->f_file);
1290 if (f->f_un.f_pipe.f_pid > 0)
1291 deadq_enter(f->f_un.f_pipe.f_pid,
1292 f->f_un.f_pipe.f_pname);
1293 f->f_un.f_pipe.f_pid = 0;
1294 errno = e;
1295 logerror(f->f_un.f_pipe.f_pname);
1297 break;
1299 case F_CONSOLE:
1300 if (flags & IGN_CONS) {
1301 dprintf(" (ignored)\n");
1302 break;
1304 /* FALLTHROUGH */
1306 case F_TTY:
1307 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1308 v->iov_base = crlf;
1309 v->iov_len = 2;
1311 errno = 0; /* ttymsg() only sometimes returns an errno */
1312 if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1313 f->f_type = F_UNUSED;
1314 logerror(msgret);
1316 break;
1318 case F_USERS:
1319 case F_WALL:
1320 dprintf("\n");
1321 v->iov_base = crlf;
1322 v->iov_len = 2;
1323 wallmsg(f, iov, IOV_SIZE);
1324 break;
1326 f->f_prevcount = 0;
1327 free(wmsg);
1331 * WALLMSG -- Write a message to the world at large
1333 * Write the specified message to either the entire
1334 * world, or a list of approved users.
1336 static void
1337 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1339 static int reenter; /* avoid calling ourselves */
1340 struct utmpx *ut;
1341 int i;
1342 const char *p;
1344 if (reenter++)
1345 return;
1346 setutxent();
1347 /* NOSTRICT */
1348 while ((ut = getutxent()) != NULL) {
1349 if (ut->ut_type != USER_PROCESS)
1350 continue;
1351 if (f->f_type == F_WALL) {
1352 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1353 TTYMSGTIME)) != NULL) {
1354 errno = 0; /* already in msg */
1355 logerror(p);
1357 continue;
1359 /* should we send the message to this user? */
1360 for (i = 0; i < MAXUNAMES; i++) {
1361 if (!f->f_un.f_uname[i][0])
1362 break;
1363 if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1364 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1365 TTYMSGTIME)) != NULL) {
1366 errno = 0; /* already in msg */
1367 logerror(p);
1369 break;
1373 endutxent();
1374 reenter = 0;
1377 static void
1378 reapchild(int signo __unused)
1380 int status;
1381 pid_t pid;
1382 struct filed *f;
1384 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
1385 if (!Initialized)
1386 /* Don't tell while we are initting. */
1387 continue;
1389 /* First, look if it's a process from the dead queue. */
1390 if (deadq_remove(pid))
1391 continue;
1393 /* Now, look in list of active processes. */
1394 for (f = Files; f; f = f->f_next) {
1395 if (f->f_type == F_PIPE &&
1396 f->f_un.f_pipe.f_pid == pid) {
1397 (void)close(f->f_file);
1398 f->f_un.f_pipe.f_pid = 0;
1399 log_deadchild(pid, status,
1400 f->f_un.f_pipe.f_pname);
1401 break;
1408 * Return a printable representation of a host address.
1410 static const char *
1411 cvthname(struct sockaddr *f)
1413 int error, hl;
1414 sigset_t omask, nmask;
1415 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1417 error = getnameinfo((struct sockaddr *)f,
1418 ((struct sockaddr *)f)->sa_len,
1419 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1420 dprintf("cvthname(%s)\n", ip);
1422 if (error) {
1423 dprintf("Malformed from address %s\n", gai_strerror(error));
1424 return ("???");
1426 if (!resolve)
1427 return (ip);
1429 sigemptyset(&nmask);
1430 sigaddset(&nmask, SIGHUP);
1431 sigprocmask(SIG_BLOCK, &nmask, &omask);
1432 error = getnameinfo((struct sockaddr *)f,
1433 ((struct sockaddr *)f)->sa_len,
1434 hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1435 sigprocmask(SIG_SETMASK, &omask, NULL);
1436 if (error) {
1437 dprintf("Host name for your address (%s) unknown\n", ip);
1438 return (ip);
1440 hl = strlen(hname);
1441 if (hl > 0 && hname[hl-1] == '.')
1442 hname[--hl] = '\0';
1443 trimdomain(hname, hl);
1444 return (hname);
1447 static void
1448 dodie(int signo)
1451 WantDie = signo;
1454 static void
1455 domark(int signo __unused)
1458 MarkSet = 1;
1462 * Print syslogd errors some place.
1464 static void
1465 logerror(const char *type)
1467 char buf[512];
1468 static int recursed = 0;
1470 /* If there's an error while trying to log an error, give up. */
1471 if (recursed)
1472 return;
1473 recursed++;
1474 if (errno)
1475 (void)snprintf(buf,
1476 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1477 else
1478 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1479 errno = 0;
1480 dprintf("%s\n", buf);
1481 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1482 recursed--;
1485 static void
1486 die(int signo)
1488 struct filed *f;
1489 struct funix *fx;
1490 int was_initialized;
1491 char buf[100];
1493 was_initialized = Initialized;
1494 Initialized = 0; /* Don't log SIGCHLDs. */
1495 for (f = Files; f != NULL; f = f->f_next) {
1496 /* flush any pending output */
1497 if (f->f_prevcount)
1498 fprintlog(f, 0, NULL);
1499 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1500 (void)close(f->f_file);
1501 f->f_un.f_pipe.f_pid = 0;
1504 Initialized = was_initialized;
1505 if (signo) {
1506 dprintf("syslogd: exiting on signal %d\n", signo);
1507 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1508 errno = 0;
1509 logerror(buf);
1511 STAILQ_FOREACH(fx, &funixes, next)
1512 (void)unlink(fx->name);
1513 pidfile_remove(pfh);
1515 exit(1);
1519 * INIT -- Initialize syslogd from configuration table
1521 static void
1522 init(int signo)
1524 int i;
1525 FILE *cf;
1526 struct filed *f, *next, **nextp;
1527 char *p;
1528 char cline[LINE_MAX];
1529 char prog[NAME_MAX+1];
1530 char host[MAXHOSTNAMELEN];
1531 char oldLocalHostName[MAXHOSTNAMELEN];
1532 char hostMsg[2*MAXHOSTNAMELEN+40];
1533 char bootfileMsg[LINE_MAX];
1535 dprintf("init\n");
1538 * Load hostname (may have changed).
1540 if (signo != 0)
1541 (void)strlcpy(oldLocalHostName, LocalHostName,
1542 sizeof(oldLocalHostName));
1543 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1544 err(EX_OSERR, "gethostname() failed");
1545 if ((p = strchr(LocalHostName, '.')) != NULL) {
1546 *p++ = '\0';
1547 LocalDomain = p;
1548 } else {
1549 LocalDomain = "";
1553 * Close all open log files.
1555 Initialized = 0;
1556 for (f = Files; f != NULL; f = next) {
1557 /* flush any pending output */
1558 if (f->f_prevcount)
1559 fprintlog(f, 0, NULL);
1561 switch (f->f_type) {
1562 case F_FILE:
1563 case F_FORW:
1564 case F_CONSOLE:
1565 case F_TTY:
1566 (void)close(f->f_file);
1567 break;
1568 case F_PIPE:
1569 if (f->f_un.f_pipe.f_pid > 0) {
1570 (void)close(f->f_file);
1571 deadq_enter(f->f_un.f_pipe.f_pid,
1572 f->f_un.f_pipe.f_pname);
1574 f->f_un.f_pipe.f_pid = 0;
1575 break;
1577 next = f->f_next;
1578 if (f->f_program) free(f->f_program);
1579 if (f->f_host) free(f->f_host);
1580 free((char *)f);
1582 Files = NULL;
1583 nextp = &Files;
1585 /* open the configuration file */
1586 if ((cf = fopen(ConfFile, "r")) == NULL) {
1587 dprintf("cannot open %s\n", ConfFile);
1588 *nextp = (struct filed *)calloc(1, sizeof(*f));
1589 if (*nextp == NULL) {
1590 logerror("calloc");
1591 exit(1);
1593 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1594 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1595 if ((*nextp)->f_next == NULL) {
1596 logerror("calloc");
1597 exit(1);
1599 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1600 Initialized = 1;
1601 return;
1605 * Foreach line in the conf table, open that file.
1607 f = NULL;
1608 (void)strlcpy(host, "*", sizeof(host));
1609 (void)strlcpy(prog, "*", sizeof(prog));
1610 while (fgets(cline, sizeof(cline), cf) != NULL) {
1612 * check for end-of-section, comments, strip off trailing
1613 * spaces and newline character. #!prog is treated specially:
1614 * following lines apply only to that program.
1616 for (p = cline; isspace(*p); ++p)
1617 continue;
1618 if (*p == 0)
1619 continue;
1620 if (*p == '#') {
1621 p++;
1622 if (*p != '!' && *p != '+' && *p != '-')
1623 continue;
1625 if (*p == '+' || *p == '-') {
1626 host[0] = *p++;
1627 while (isspace(*p))
1628 p++;
1629 if ((!*p) || (*p == '*')) {
1630 (void)strlcpy(host, "*", sizeof(host));
1631 continue;
1633 if (*p == '@')
1634 p = LocalHostName;
1635 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1636 if (!isalnum(*p) && *p != '.' && *p != '-'
1637 && *p != ',' && *p != ':' && *p != '%')
1638 break;
1639 host[i] = *p++;
1641 host[i] = '\0';
1642 continue;
1644 if (*p == '!') {
1645 p++;
1646 while (isspace(*p)) p++;
1647 if ((!*p) || (*p == '*')) {
1648 (void)strlcpy(prog, "*", sizeof(prog));
1649 continue;
1651 for (i = 0; i < NAME_MAX; i++) {
1652 if (!isprint(p[i]) || isspace(p[i]))
1653 break;
1654 prog[i] = p[i];
1656 prog[i] = 0;
1657 continue;
1659 for (p = cline + 1; *p != '\0'; p++) {
1660 if (*p != '#')
1661 continue;
1662 if (*(p - 1) == '\\') {
1663 strcpy(p - 1, p);
1664 p--;
1665 continue;
1667 *p = '\0';
1668 break;
1670 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1671 cline[i] = '\0';
1672 f = (struct filed *)calloc(1, sizeof(*f));
1673 if (f == NULL) {
1674 logerror("calloc");
1675 exit(1);
1677 *nextp = f;
1678 nextp = &f->f_next;
1679 cfline(cline, f, prog, host);
1682 /* close the configuration file */
1683 (void)fclose(cf);
1685 Initialized = 1;
1687 if (Debug) {
1688 int port;
1689 for (f = Files; f; f = f->f_next) {
1690 for (i = 0; i <= LOG_NFACILITIES; i++)
1691 if (f->f_pmask[i] == INTERNAL_NOPRI)
1692 printf("X ");
1693 else
1694 printf("%d ", f->f_pmask[i]);
1695 printf("%s: ", TypeNames[f->f_type]);
1696 switch (f->f_type) {
1697 case F_FILE:
1698 printf("%s", f->f_un.f_fname);
1699 break;
1701 case F_CONSOLE:
1702 case F_TTY:
1703 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1704 break;
1706 case F_FORW:
1707 port = (int)ntohs(((struct sockaddr_in *)
1708 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1709 if (port != 514) {
1710 printf("%s:%d",
1711 f->f_un.f_forw.f_hname, port);
1712 } else {
1713 printf("%s", f->f_un.f_forw.f_hname);
1715 break;
1717 case F_PIPE:
1718 printf("%s", f->f_un.f_pipe.f_pname);
1719 break;
1721 case F_USERS:
1722 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1723 printf("%s, ", f->f_un.f_uname[i]);
1724 break;
1726 if (f->f_program)
1727 printf(" (%s)", f->f_program);
1728 printf("\n");
1732 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1733 dprintf("syslogd: restarted\n");
1735 * Log a change in hostname, but only on a restart.
1737 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1738 (void)snprintf(hostMsg, sizeof(hostMsg),
1739 "syslogd: hostname changed, \"%s\" to \"%s\"",
1740 oldLocalHostName, LocalHostName);
1741 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1742 dprintf("%s\n", hostMsg);
1745 * Log the kernel boot file if we aren't going to use it as
1746 * the prefix, and if this is *not* a restart.
1748 if (signo == 0 && !use_bootfile) {
1749 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1750 "syslogd: kernel boot file is %s", bootfile);
1751 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1752 dprintf("%s\n", bootfileMsg);
1757 * Crack a configuration file line
1759 static void
1760 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1762 struct addrinfo hints, *res;
1763 int error, i, pri, syncfile;
1764 const char *p, *q;
1765 char *bp;
1766 char buf[MAXLINE], ebuf[100];
1768 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1770 errno = 0; /* keep strerror() stuff out of logerror messages */
1772 /* clear out file entry */
1773 memset(f, 0, sizeof(*f));
1774 for (i = 0; i <= LOG_NFACILITIES; i++)
1775 f->f_pmask[i] = INTERNAL_NOPRI;
1777 /* save hostname if any */
1778 if (host && *host == '*')
1779 host = NULL;
1780 if (host) {
1781 int hl;
1783 f->f_host = strdup(host);
1784 if (f->f_host == NULL) {
1785 logerror("strdup");
1786 exit(1);
1788 hl = strlen(f->f_host);
1789 if (hl > 0 && f->f_host[hl-1] == '.')
1790 f->f_host[--hl] = '\0';
1791 trimdomain(f->f_host, hl);
1794 /* save program name if any */
1795 if (prog && *prog == '*')
1796 prog = NULL;
1797 if (prog) {
1798 f->f_program = strdup(prog);
1799 if (f->f_program == NULL) {
1800 logerror("strdup");
1801 exit(1);
1805 /* scan through the list of selectors */
1806 for (p = line; *p && *p != '\t' && *p != ' ';) {
1807 int pri_done;
1808 int pri_cmp;
1809 int pri_invert;
1811 /* find the end of this facility name list */
1812 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1813 continue;
1815 /* get the priority comparison */
1816 pri_cmp = 0;
1817 pri_done = 0;
1818 pri_invert = 0;
1819 if (*q == '!') {
1820 pri_invert = 1;
1821 q++;
1823 while (!pri_done) {
1824 switch (*q) {
1825 case '<':
1826 pri_cmp |= PRI_LT;
1827 q++;
1828 break;
1829 case '=':
1830 pri_cmp |= PRI_EQ;
1831 q++;
1832 break;
1833 case '>':
1834 pri_cmp |= PRI_GT;
1835 q++;
1836 break;
1837 default:
1838 pri_done++;
1839 break;
1843 /* collect priority name */
1844 for (bp = buf; *q && !strchr("\t,; ", *q); )
1845 *bp++ = *q++;
1846 *bp = '\0';
1848 /* skip cruft */
1849 while (strchr(",;", *q))
1850 q++;
1852 /* decode priority name */
1853 if (*buf == '*') {
1854 pri = LOG_PRIMASK;
1855 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1856 } else {
1857 /* Ignore trailing spaces. */
1858 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1859 buf[i] = '\0';
1861 pri = decode(buf, prioritynames);
1862 if (pri < 0) {
1863 errno = 0;
1864 (void)snprintf(ebuf, sizeof ebuf,
1865 "unknown priority name \"%s\"", buf);
1866 logerror(ebuf);
1867 return;
1870 if (!pri_cmp)
1871 pri_cmp = (UniquePriority)
1872 ? (PRI_EQ)
1873 : (PRI_EQ | PRI_GT)
1875 if (pri_invert)
1876 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1878 /* scan facilities */
1879 while (*p && !strchr("\t.; ", *p)) {
1880 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1881 *bp++ = *p++;
1882 *bp = '\0';
1884 if (*buf == '*') {
1885 for (i = 0; i < LOG_NFACILITIES; i++) {
1886 f->f_pmask[i] = pri;
1887 f->f_pcmp[i] = pri_cmp;
1889 } else {
1890 i = decode(buf, facilitynames);
1891 if (i < 0) {
1892 errno = 0;
1893 (void)snprintf(ebuf, sizeof ebuf,
1894 "unknown facility name \"%s\"",
1895 buf);
1896 logerror(ebuf);
1897 return;
1899 f->f_pmask[i >> 3] = pri;
1900 f->f_pcmp[i >> 3] = pri_cmp;
1902 while (*p == ',' || *p == ' ')
1903 p++;
1906 p = q;
1909 /* skip to action part */
1910 while (*p == '\t' || *p == ' ')
1911 p++;
1913 if (*p == '-') {
1914 syncfile = 0;
1915 p++;
1916 } else
1917 syncfile = 1;
1919 switch (*p) {
1920 case '@':
1922 char *tp;
1923 char endkey = ':';
1925 * scan forward to see if there is a port defined.
1926 * so we can't use strlcpy..
1928 i = sizeof(f->f_un.f_forw.f_hname);
1929 tp = f->f_un.f_forw.f_hname;
1930 p++;
1933 * an ipv6 address should start with a '[' in that case
1934 * we should scan for a ']'
1936 if (*p == '[') {
1937 p++;
1938 endkey = ']';
1940 while (*p && (*p != endkey) && (i-- > 0)) {
1941 *tp++ = *p++;
1943 if (endkey == ']' && *p == endkey)
1944 p++;
1945 *tp = '\0';
1947 /* See if we copied a domain and have a port */
1948 if (*p == ':')
1949 p++;
1950 else
1951 p = NULL;
1953 memset(&hints, 0, sizeof(hints));
1954 hints.ai_family = family;
1955 hints.ai_socktype = SOCK_DGRAM;
1956 error = getaddrinfo(f->f_un.f_forw.f_hname,
1957 p ? p : "syslog", &hints, &res);
1958 if (error) {
1959 logerror(gai_strerror(error));
1960 break;
1962 f->f_un.f_forw.f_addr = res;
1963 f->f_type = F_FORW;
1964 break;
1966 case '/':
1967 if ((f->f_file = open(p, logflags, 0600)) < 0) {
1968 f->f_type = F_UNUSED;
1969 logerror(p);
1970 break;
1972 if (syncfile)
1973 f->f_flags |= FFLAG_SYNC;
1974 if (isatty(f->f_file)) {
1975 if (strcmp(p, ctty) == 0)
1976 f->f_type = F_CONSOLE;
1977 else
1978 f->f_type = F_TTY;
1979 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1980 sizeof(f->f_un.f_fname));
1981 } else {
1982 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1983 f->f_type = F_FILE;
1985 break;
1987 case '|':
1988 f->f_un.f_pipe.f_pid = 0;
1989 (void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
1990 sizeof(f->f_un.f_pipe.f_pname));
1991 f->f_type = F_PIPE;
1992 break;
1994 case '*':
1995 f->f_type = F_WALL;
1996 break;
1998 default:
1999 for (i = 0; i < MAXUNAMES && *p; i++) {
2000 for (q = p; *q && *q != ','; )
2001 q++;
2002 (void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2003 if ((q - p) >= MAXLOGNAME)
2004 f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2005 else
2006 f->f_un.f_uname[i][q - p] = '\0';
2007 while (*q == ',' || *q == ' ')
2008 q++;
2009 p = q;
2011 f->f_type = F_USERS;
2012 break;
2018 * Decode a symbolic name to a numeric value
2020 static int
2021 decode(const char *name, const CODE *codetab)
2023 const CODE *c;
2024 char *p, buf[40];
2026 if (isdigit(*name))
2027 return (atoi(name));
2029 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2030 if (isupper(*name))
2031 *p = tolower(*name);
2032 else
2033 *p = *name;
2035 *p = '\0';
2036 for (c = codetab; c->c_name; c++)
2037 if (!strcmp(buf, c->c_name))
2038 return (c->c_val);
2040 return (-1);
2043 static void
2044 markit(void)
2046 struct filed *f;
2047 dq_t q, next;
2049 now = time(NULL);
2050 MarkSeq += TIMERINTVL;
2051 if (MarkSeq >= MarkInterval) {
2052 logmsg(LOG_INFO, "-- MARK --",
2053 LocalHostName, ADDDATE|MARK);
2054 MarkSeq = 0;
2057 for (f = Files; f; f = f->f_next) {
2058 if (f->f_prevcount && now >= REPEATTIME(f)) {
2059 dprintf("flush %s: repeated %d times, %d sec.\n",
2060 TypeNames[f->f_type], f->f_prevcount,
2061 repeatinterval[f->f_repeatcount]);
2062 fprintlog(f, 0, NULL);
2063 BACKOFF(f);
2067 /* Walk the dead queue, and see if we should signal somebody. */
2068 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2069 next = TAILQ_NEXT(q, dq_entries);
2071 switch (q->dq_timeout) {
2072 case 0:
2073 /* Already signalled once, try harder now. */
2074 if (kill(q->dq_pid, SIGKILL) != 0)
2075 (void)deadq_remove(q->dq_pid);
2076 break;
2078 case 1:
2080 * Timed out on dead queue, send terminate
2081 * signal. Note that we leave the removal
2082 * from the dead queue to reapchild(), which
2083 * will also log the event (unless the process
2084 * didn't even really exist, in case we simply
2085 * drop it from the dead queue).
2087 if (kill(q->dq_pid, SIGTERM) != 0)
2088 (void)deadq_remove(q->dq_pid);
2089 /* FALLTHROUGH */
2091 default:
2092 q->dq_timeout--;
2095 MarkSet = 0;
2096 (void)alarm(TIMERINTVL);
2100 * fork off and become a daemon, but wait for the child to come online
2101 * before returing to the parent, or we get disk thrashing at boot etc.
2102 * Set a timer so we don't hang forever if it wedges.
2104 static int
2105 waitdaemon(int nochdir, int noclose, int maxwait)
2107 int fd;
2108 int status;
2109 pid_t pid, childpid;
2111 switch (childpid = fork()) {
2112 case -1:
2113 return (-1);
2114 case 0:
2115 break;
2116 default:
2117 signal(SIGALRM, timedout);
2118 alarm(maxwait);
2119 while ((pid = wait3(&status, 0, NULL)) != -1) {
2120 if (WIFEXITED(status))
2121 errx(1, "child pid %d exited with return code %d",
2122 pid, WEXITSTATUS(status));
2123 if (WIFSIGNALED(status))
2124 errx(1, "child pid %d exited on signal %d%s",
2125 pid, WTERMSIG(status),
2126 WCOREDUMP(status) ? " (core dumped)" :
2127 "");
2128 if (pid == childpid) /* it's gone... */
2129 break;
2131 exit(0);
2134 if (setsid() == -1)
2135 return (-1);
2137 if (!nochdir)
2138 (void)chdir("/");
2140 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2141 (void)dup2(fd, STDIN_FILENO);
2142 (void)dup2(fd, STDOUT_FILENO);
2143 (void)dup2(fd, STDERR_FILENO);
2144 if (fd > 2)
2145 (void)close (fd);
2147 return (getppid());
2151 * We get a SIGALRM from the child when it's running and finished doing it's
2152 * fsync()'s or O_SYNC writes for all the boot messages.
2154 * We also get a signal from the kernel if the timer expires, so check to
2155 * see what happened.
2157 static void
2158 timedout(int sig __unused)
2160 int left;
2161 left = alarm(0);
2162 signal(SIGALRM, SIG_DFL);
2163 if (left == 0)
2164 errx(1, "timed out waiting for child");
2165 else
2166 _exit(0);
2170 * Add `s' to the list of allowable peer addresses to accept messages
2171 * from.
2173 * `s' is a string in the form:
2175 * [*]domainname[:{servicename|portnumber|*}]
2177 * or
2179 * netaddr/maskbits[:{servicename|portnumber|*}]
2181 * Returns -1 on error, 0 if the argument was valid.
2183 static int
2184 allowaddr(char *s)
2186 char *cp1, *cp2;
2187 struct allowedpeer ap;
2188 struct servent *se;
2189 int masklen = -1;
2190 struct addrinfo hints, *res;
2191 struct in_addr *addrp, *maskp;
2192 #ifdef INET6
2193 int i;
2194 u_int32_t *addr6p, *mask6p;
2195 #endif
2196 char ip[NI_MAXHOST];
2198 #ifdef INET6
2199 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2200 #endif
2201 cp1 = s;
2202 if ((cp1 = strrchr(cp1, ':'))) {
2203 /* service/port provided */
2204 *cp1++ = '\0';
2205 if (strlen(cp1) == 1 && *cp1 == '*')
2206 /* any port allowed */
2207 ap.port = 0;
2208 else if ((se = getservbyname(cp1, "udp"))) {
2209 ap.port = ntohs(se->s_port);
2210 } else {
2211 ap.port = strtol(cp1, &cp2, 0);
2212 if (*cp2 != '\0')
2213 return (-1); /* port not numeric */
2215 } else {
2216 if ((se = getservbyname("syslog", "udp")))
2217 ap.port = ntohs(se->s_port);
2218 else
2219 /* sanity, should not happen */
2220 ap.port = 514;
2223 if ((cp1 = strchr(s, '/')) != NULL &&
2224 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2225 *cp1 = '\0';
2226 if ((masklen = atoi(cp1 + 1)) < 0)
2227 return (-1);
2229 #ifdef INET6
2230 if (*s == '[') {
2231 cp2 = s + strlen(s) - 1;
2232 if (*cp2 == ']') {
2233 ++s;
2234 *cp2 = '\0';
2235 } else {
2236 cp2 = NULL;
2238 } else {
2239 cp2 = NULL;
2241 #endif
2242 memset(&hints, 0, sizeof(hints));
2243 hints.ai_family = PF_UNSPEC;
2244 hints.ai_socktype = SOCK_DGRAM;
2245 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2246 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2247 ap.isnumeric = 1;
2248 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2249 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2250 ap.a_mask.ss_family = res->ai_family;
2251 if (res->ai_family == AF_INET) {
2252 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2253 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2254 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2255 if (masklen < 0) {
2256 /* use default netmask */
2257 if (IN_CLASSA(ntohl(addrp->s_addr)))
2258 maskp->s_addr = htonl(IN_CLASSA_NET);
2259 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2260 maskp->s_addr = htonl(IN_CLASSB_NET);
2261 else
2262 maskp->s_addr = htonl(IN_CLASSC_NET);
2263 } else if (masklen <= 32) {
2264 /* convert masklen to netmask */
2265 if (masklen == 0)
2266 maskp->s_addr = 0;
2267 else
2268 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2269 } else {
2270 freeaddrinfo(res);
2271 return (-1);
2273 /* Lose any host bits in the network number. */
2274 addrp->s_addr &= maskp->s_addr;
2276 #ifdef INET6
2277 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2278 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2279 if (masklen < 0)
2280 masklen = 128;
2281 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2282 /* convert masklen to netmask */
2283 while (masklen > 0) {
2284 if (masklen < 32) {
2285 *mask6p = htonl(~(0xffffffff >> masklen));
2286 break;
2288 *mask6p++ = 0xffffffff;
2289 masklen -= 32;
2291 /* Lose any host bits in the network number. */
2292 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2293 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2294 for (i = 0; i < 4; i++)
2295 addr6p[i] &= mask6p[i];
2297 #endif
2298 else {
2299 freeaddrinfo(res);
2300 return (-1);
2302 freeaddrinfo(res);
2303 } else {
2304 /* arg `s' is domain name */
2305 ap.isnumeric = 0;
2306 ap.a_name = s;
2307 if (cp1)
2308 *cp1 = '/';
2309 #ifdef INET6
2310 if (cp2) {
2311 *cp2 = ']';
2312 --s;
2314 #endif
2317 if (Debug) {
2318 printf("allowaddr: rule %d: ", NumAllowed);
2319 if (ap.isnumeric) {
2320 printf("numeric, ");
2321 getnameinfo((struct sockaddr *)&ap.a_addr,
2322 ((struct sockaddr *)&ap.a_addr)->sa_len,
2323 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2324 printf("addr = %s, ", ip);
2325 getnameinfo((struct sockaddr *)&ap.a_mask,
2326 ((struct sockaddr *)&ap.a_mask)->sa_len,
2327 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2328 printf("mask = %s; ", ip);
2329 } else {
2330 printf("domainname = %s; ", ap.a_name);
2332 printf("port = %d\n", ap.port);
2335 if ((AllowedPeers = realloc(AllowedPeers,
2336 ++NumAllowed * sizeof(struct allowedpeer)))
2337 == NULL) {
2338 logerror("realloc");
2339 exit(1);
2341 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2342 return (0);
2346 * Validate that the remote peer has permission to log to us.
2348 static int
2349 validate(struct sockaddr *sa, const char *hname)
2351 int i;
2352 size_t l1, l2;
2353 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2354 struct allowedpeer *ap;
2355 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2356 #ifdef INET6
2357 int j, reject;
2358 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2359 #endif
2360 struct addrinfo hints, *res;
2361 u_short sport;
2363 if (NumAllowed == 0)
2364 /* traditional behaviour, allow everything */
2365 return (1);
2367 (void)strlcpy(name, hname, sizeof(name));
2368 memset(&hints, 0, sizeof(hints));
2369 hints.ai_family = PF_UNSPEC;
2370 hints.ai_socktype = SOCK_DGRAM;
2371 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2372 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2373 freeaddrinfo(res);
2374 else if (strchr(name, '.') == NULL) {
2375 strlcat(name, ".", sizeof name);
2376 strlcat(name, LocalDomain, sizeof name);
2378 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2379 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2380 return (0); /* for safety, should not occur */
2381 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2382 ip, port, name);
2383 sport = atoi(port);
2385 /* now, walk down the list */
2386 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2387 if (ap->port != 0 && ap->port != sport) {
2388 dprintf("rejected in rule %d due to port mismatch.\n", i);
2389 continue;
2392 if (ap->isnumeric) {
2393 if (ap->a_addr.ss_family != sa->sa_family) {
2394 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2395 continue;
2397 if (ap->a_addr.ss_family == AF_INET) {
2398 sin4 = (struct sockaddr_in *)sa;
2399 a4p = (struct sockaddr_in *)&ap->a_addr;
2400 m4p = (struct sockaddr_in *)&ap->a_mask;
2401 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2402 != a4p->sin_addr.s_addr) {
2403 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2404 continue;
2407 #ifdef INET6
2408 else if (ap->a_addr.ss_family == AF_INET6) {
2409 sin6 = (struct sockaddr_in6 *)sa;
2410 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2411 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2412 if (a6p->sin6_scope_id != 0 &&
2413 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2414 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2415 continue;
2417 reject = 0;
2418 for (j = 0; j < 16; j += 4) {
2419 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2420 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2421 ++reject;
2422 break;
2425 if (reject) {
2426 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2427 continue;
2430 #endif
2431 else
2432 continue;
2433 } else {
2434 cp = ap->a_name;
2435 l1 = strlen(name);
2436 if (*cp == '*') {
2437 /* allow wildmatch */
2438 cp++;
2439 l2 = strlen(cp);
2440 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2441 dprintf("rejected in rule %d due to name mismatch.\n", i);
2442 continue;
2444 } else {
2445 /* exact match */
2446 l2 = strlen(cp);
2447 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2448 dprintf("rejected in rule %d due to name mismatch.\n", i);
2449 continue;
2453 dprintf("accepted in rule %d.\n", i);
2454 return (1); /* hooray! */
2456 return (0);
2460 * Fairly similar to popen(3), but returns an open descriptor, as
2461 * opposed to a FILE *.
2463 static int
2464 p_open(const char *prog, pid_t *rpid)
2466 int pfd[2], nulldesc;
2467 pid_t pid;
2468 sigset_t omask, mask;
2469 char *argv[4]; /* sh -c cmd NULL */
2470 char errmsg[200];
2472 if (pipe(pfd) == -1)
2473 return (-1);
2474 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2475 /* we are royally screwed anyway */
2476 return (-1);
2478 sigemptyset(&mask);
2479 sigaddset(&mask, SIGALRM);
2480 sigaddset(&mask, SIGHUP);
2481 sigprocmask(SIG_BLOCK, &mask, &omask);
2482 switch ((pid = fork())) {
2483 case -1:
2484 sigprocmask(SIG_SETMASK, &omask, 0);
2485 close(nulldesc);
2486 return (-1);
2488 case 0:
2489 argv[0] = strdup("sh");
2490 argv[1] = strdup("-c");
2491 argv[2] = strdup(prog);
2492 argv[3] = NULL;
2493 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2494 logerror("strdup");
2495 exit(1);
2498 alarm(0);
2499 (void)setsid(); /* Avoid catching SIGHUPs. */
2502 * Throw away pending signals, and reset signal
2503 * behaviour to standard values.
2505 signal(SIGALRM, SIG_IGN);
2506 signal(SIGHUP, SIG_IGN);
2507 sigprocmask(SIG_SETMASK, &omask, 0);
2508 signal(SIGPIPE, SIG_DFL);
2509 signal(SIGQUIT, SIG_DFL);
2510 signal(SIGALRM, SIG_DFL);
2511 signal(SIGHUP, SIG_DFL);
2513 dup2(pfd[0], STDIN_FILENO);
2514 dup2(nulldesc, STDOUT_FILENO);
2515 dup2(nulldesc, STDERR_FILENO);
2516 closefrom(3);
2518 (void)execvp(_PATH_BSHELL, argv);
2519 _exit(255);
2522 sigprocmask(SIG_SETMASK, &omask, 0);
2523 close(nulldesc);
2524 close(pfd[0]);
2526 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2527 * supposed to get an EWOULDBLOCK on writev(2), which is
2528 * caught by the logic above anyway, which will in turn close
2529 * the pipe, and fork a new logging subprocess if necessary.
2530 * The stale subprocess will be killed some time later unless
2531 * it terminated itself due to closing its input pipe (so we
2532 * get rid of really dead puppies).
2534 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2535 /* This is bad. */
2536 (void)snprintf(errmsg, sizeof errmsg,
2537 "Warning: cannot change pipe to PID %d to "
2538 "non-blocking behaviour.",
2539 (int)pid);
2540 logerror(errmsg);
2542 *rpid = pid;
2543 return (pfd[1]);
2546 static void
2547 deadq_enter(pid_t pid, const char *name)
2549 dq_t p;
2550 int status;
2553 * Be paranoid, if we can't signal the process, don't enter it
2554 * into the dead queue (perhaps it's already dead). If possible,
2555 * we try to fetch and log the child's status.
2557 if (kill(pid, 0) != 0) {
2558 if (waitpid(pid, &status, WNOHANG) > 0)
2559 log_deadchild(pid, status, name);
2560 return;
2563 p = malloc(sizeof(struct deadq_entry));
2564 if (p == NULL) {
2565 logerror("malloc");
2566 exit(1);
2569 p->dq_pid = pid;
2570 p->dq_timeout = DQ_TIMO_INIT;
2571 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2574 static int
2575 deadq_remove(pid_t pid)
2577 dq_t q;
2579 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2580 if (q->dq_pid == pid) {
2581 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2582 free(q);
2583 return (1);
2587 return (0);
2590 static void
2591 log_deadchild(pid_t pid, int status, const char *name)
2593 int code;
2594 char buf[256];
2595 const char *reason;
2597 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2598 if (WIFSIGNALED(status)) {
2599 reason = "due to signal";
2600 code = WTERMSIG(status);
2601 } else {
2602 reason = "with status";
2603 code = WEXITSTATUS(status);
2604 if (code == 0)
2605 return;
2607 (void)snprintf(buf, sizeof buf,
2608 "Logging subprocess %d (%s) exited %s %d.",
2609 pid, name, reason, code);
2610 logerror(buf);
2613 static int *
2614 socksetup(int af, char *bindhostname)
2616 struct addrinfo hints, *res, *r;
2617 const char *bindservice;
2618 char *cp;
2619 int error, maxs, *s, *socks;
2622 * We have to handle this case for backwards compatibility:
2623 * If there are two (or more) colons but no '[' and ']',
2624 * assume this is an inet6 address without a service.
2626 bindservice = "syslog";
2627 if (bindhostname != NULL) {
2628 #ifdef INET6
2629 if (*bindhostname == '[' &&
2630 (cp = strchr(bindhostname + 1, ']')) != NULL) {
2631 ++bindhostname;
2632 *cp = '\0';
2633 if (cp[1] == ':' && cp[2] != '\0')
2634 bindservice = cp + 2;
2635 } else {
2636 #endif
2637 cp = strchr(bindhostname, ':');
2638 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2639 *cp = '\0';
2640 if (cp[1] != '\0')
2641 bindservice = cp + 1;
2642 if (cp == bindhostname)
2643 bindhostname = NULL;
2645 #ifdef INET6
2647 #endif
2650 memset(&hints, 0, sizeof(hints));
2651 hints.ai_flags = AI_PASSIVE;
2652 hints.ai_family = af;
2653 hints.ai_socktype = SOCK_DGRAM;
2654 error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2655 if (error) {
2656 logerror(gai_strerror(error));
2657 errno = 0;
2658 die(0);
2661 /* Count max number of sockets we may open */
2662 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2663 socks = malloc((maxs+1) * sizeof(int));
2664 if (socks == NULL) {
2665 logerror("couldn't allocate memory for sockets");
2666 die(0);
2669 *socks = 0; /* num of sockets counter at start of array */
2670 s = socks + 1;
2671 for (r = res; r; r = r->ai_next) {
2672 int on = 1;
2673 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2674 if (*s < 0) {
2675 logerror("socket");
2676 continue;
2678 #ifdef INET6
2679 if (r->ai_family == AF_INET6) {
2680 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2681 (char *)&on, sizeof (on)) < 0) {
2682 logerror("setsockopt");
2683 close(*s);
2684 continue;
2687 #endif
2688 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2689 (char *)&on, sizeof (on)) < 0) {
2690 logerror("setsockopt");
2691 close(*s);
2692 continue;
2695 * RFC 3164 recommends that client side message
2696 * should come from the privileged syslogd port.
2698 * If the system administrator choose not to obey
2699 * this, we can skip the bind() step so that the
2700 * system will choose a port for us.
2702 if (!NoBind) {
2703 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2704 logerror("bind");
2705 close(*s);
2706 continue;
2709 if (!SecureMode)
2710 increase_rcvbuf(*s);
2713 (*socks)++;
2714 s++;
2717 if (*socks == 0) {
2718 free(socks);
2719 if (Debug)
2720 return (NULL);
2721 else
2722 die(0);
2724 if (res)
2725 freeaddrinfo(res);
2727 return (socks);
2730 static void
2731 increase_rcvbuf(int fd)
2733 socklen_t len, slen;
2735 slen = sizeof(len);
2737 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2738 if (len < RCVBUF_MINSIZE) {
2739 len = RCVBUF_MINSIZE;
2740 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));