]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/syslogd/syslogd.c
This commit was generated by cvs2svn to compensate for changes in r163299,
[FreeBSD/FreeBSD.git] / usr.sbin / syslogd / syslogd.c
1 /*
2  * Copyright (c) 1983, 1988, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
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  * 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.
16  *
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.
28  */
29
30 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
33         The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)syslogd.c   8.3 (Berkeley) 4/4/94";
39 #endif
40 #endif /* not lint */
41
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 /*
46  *  syslogd -- log system messages
47  *
48  * This program implements a system log. It takes a series of lines.
49  * Each line may have a priority, signified as "<n>" as
50  * the first characters of the line.  If this is
51  * not present, a default priority is used.
52  *
53  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
54  * cause it to reread its configuration file.
55  *
56  * Defined Constants:
57  *
58  * MAXLINE -- the maximum line length that can be handled.
59  * DEFUPRI -- the default priority for user messages
60  * DEFSPRI -- the default priority for kernel messages
61  *
62  * Author: Eric Allman
63  * extensive changes by Ralph Campbell
64  * more extensive changes by Eric Allman (again)
65  * Extension to log by program name as well as facility and priority
66  *   by Peter da Silva.
67  * -u and -v by Harlan Stenn.
68  * Priority comparison code by Harlan Stenn.
69  */
70
71 #define MAXLINE         1024            /* maximum line length */
72 #define MAXSVLINE       120             /* maximum saved line length */
73 #define DEFUPRI         (LOG_USER|LOG_NOTICE)
74 #define DEFSPRI         (LOG_KERN|LOG_CRIT)
75 #define TIMERINTVL      30              /* interval for checking flush, mark */
76 #define TTYMSGTIME      1               /* timeout passed to ttymsg */
77
78 #include <sys/param.h>
79 #include <sys/ioctl.h>
80 #include <sys/stat.h>
81 #include <sys/wait.h>
82 #include <sys/socket.h>
83 #include <sys/queue.h>
84 #include <sys/uio.h>
85 #include <sys/un.h>
86 #include <sys/time.h>
87 #include <sys/resource.h>
88 #include <sys/syslimits.h>
89 #include <sys/types.h>
90
91 #include <netinet/in.h>
92 #include <netdb.h>
93 #include <arpa/inet.h>
94
95 #include <ctype.h>
96 #include <err.h>
97 #include <errno.h>
98 #include <fcntl.h>
99 #include <libutil.h>
100 #include <limits.h>
101 #include <paths.h>
102 #include <signal.h>
103 #include <stdio.h>
104 #include <stdlib.h>
105 #include <string.h>
106 #include <sysexits.h>
107 #include <unistd.h>
108 #include <utmp.h>
109
110 #include "pathnames.h"
111 #include "ttymsg.h"
112
113 #define SYSLOG_NAMES
114 #include <sys/syslog.h>
115
116 const char      *ConfFile = _PATH_LOGCONF;
117 const char      *PidFile = _PATH_LOGPID;
118 const char      ctty[] = _PATH_CONSOLE;
119
120 #define dprintf         if (Debug) printf
121
122 #define MAXUNAMES       20      /* maximum number of user names */
123
124 /*
125  * Unix sockets.
126  * We have two default sockets, one with 666 permissions,
127  * and one for privileged programs.
128  */
129 struct funix {
130         int                     s;
131         char                    *name;
132         mode_t                  mode;
133         STAILQ_ENTRY(funix)     next;
134 };
135 struct funix funix_secure =     { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
136                                 { NULL } };
137 struct funix funix_default =    { -1, _PATH_LOG, DEFFILEMODE,
138                                 { &funix_secure } };
139
140 STAILQ_HEAD(, funix) funixes =  { &funix_default,
141                                 &(funix_secure.next.stqe_next) };
142
143 /*
144  * Flags to logmsg().
145  */
146
147 #define IGN_CONS        0x001   /* don't print on console */
148 #define SYNC_FILE       0x002   /* do fsync on file after printing */
149 #define ADDDATE         0x004   /* add a date to the message */
150 #define MARK            0x008   /* this message is a mark */
151 #define ISKERNEL        0x010   /* kernel generated message */
152
153 /*
154  * This structure represents the files that will have log
155  * copies printed.
156  * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
157  * or if f_type if F_PIPE and f_pid > 0.
158  */
159
160 struct filed {
161         struct  filed *f_next;          /* next in linked list */
162         short   f_type;                 /* entry type, see below */
163         short   f_file;                 /* file descriptor */
164         time_t  f_time;                 /* time this was last written */
165         char    *f_host;                /* host from which to recd. */
166         u_char  f_pmask[LOG_NFACILITIES+1];     /* priority mask */
167         u_char  f_pcmp[LOG_NFACILITIES+1];      /* compare priority */
168 #define PRI_LT  0x1
169 #define PRI_EQ  0x2
170 #define PRI_GT  0x4
171         char    *f_program;             /* program this applies to */
172         union {
173                 char    f_uname[MAXUNAMES][UT_NAMESIZE+1];
174                 struct {
175                         char    f_hname[MAXHOSTNAMELEN];
176                         struct addrinfo *f_addr;
177
178                 } f_forw;               /* forwarding address */
179                 char    f_fname[MAXPATHLEN];
180                 struct {
181                         char    f_pname[MAXPATHLEN];
182                         pid_t   f_pid;
183                 } f_pipe;
184         } f_un;
185         char    f_prevline[MAXSVLINE];          /* last message logged */
186         char    f_lasttime[16];                 /* time of last occurrence */
187         char    f_prevhost[MAXHOSTNAMELEN];     /* host from which recd. */
188         int     f_prevpri;                      /* pri of f_prevline */
189         int     f_prevlen;                      /* length of f_prevline */
190         int     f_prevcount;                    /* repetition cnt of prevline */
191         u_int   f_repeatcount;                  /* number of "repeated" msgs */
192         int     f_flags;                        /* file-specific flags */
193 #define FFLAG_SYNC 0x01
194 #define FFLAG_NEEDSYNC  0x02
195 };
196
197 /*
198  * Queue of about-to-be dead processes we should watch out for.
199  */
200
201 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
202 struct stailhead *deadq_headp;
203
204 struct deadq_entry {
205         pid_t                           dq_pid;
206         int                             dq_timeout;
207         TAILQ_ENTRY(deadq_entry)        dq_entries;
208 };
209
210 /*
211  * The timeout to apply to processes waiting on the dead queue.  Unit
212  * of measure is `mark intervals', i.e. 20 minutes by default.
213  * Processes on the dead queue will be terminated after that time.
214  */
215
216 #define DQ_TIMO_INIT    2
217
218 typedef struct deadq_entry *dq_t;
219
220
221 /*
222  * Struct to hold records of network addresses that are allowed to log
223  * to us.
224  */
225 struct allowedpeer {
226         int isnumeric;
227         u_short port;
228         union {
229                 struct {
230                         struct sockaddr_storage addr;
231                         struct sockaddr_storage mask;
232                 } numeric;
233                 char *name;
234         } u;
235 #define a_addr u.numeric.addr
236 #define a_mask u.numeric.mask
237 #define a_name u.name
238 };
239
240
241 /*
242  * Intervals at which we flush out "message repeated" messages,
243  * in seconds after previous message is logged.  After each flush,
244  * we move to the next interval until we reach the largest.
245  */
246 int     repeatinterval[] = { 30, 120, 600 };    /* # of secs before flush */
247 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
248 #define REPEATTIME(f)   ((f)->f_time + repeatinterval[(f)->f_repeatcount])
249 #define BACKOFF(f)      { if (++(f)->f_repeatcount > MAXREPEAT) \
250                                  (f)->f_repeatcount = MAXREPEAT; \
251                         }
252
253 /* values for f_type */
254 #define F_UNUSED        0               /* unused entry */
255 #define F_FILE          1               /* regular file */
256 #define F_TTY           2               /* terminal */
257 #define F_CONSOLE       3               /* console terminal */
258 #define F_FORW          4               /* remote machine */
259 #define F_USERS         5               /* list of users */
260 #define F_WALL          6               /* everyone logged on */
261 #define F_PIPE          7               /* pipe to program */
262
263 const char *TypeNames[8] = {
264         "UNUSED",       "FILE",         "TTY",          "CONSOLE",
265         "FORW",         "USERS",        "WALL",         "PIPE"
266 };
267
268 static struct filed *Files;     /* Log files that we write to */
269 static struct filed consfile;   /* Console */
270
271 static int      Debug;          /* debug flag */
272 static int      resolve = 1;    /* resolve hostname */
273 static char     LocalHostName[MAXHOSTNAMELEN];  /* our hostname */
274 static const char *LocalDomain; /* our local domain name */
275 static int      *finet;         /* Internet datagram socket */
276 static int      fklog = -1;     /* /dev/klog */
277 static int      Initialized;    /* set when we have initialized ourselves */
278 static int      MarkInterval = 20 * 60; /* interval between marks in seconds */
279 static int      MarkSeq;        /* mark sequence number */
280 static int      SecureMode;     /* when true, receive only unix domain socks */
281 #ifdef INET6
282 static int      family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
283 #else
284 static int      family = PF_INET; /* protocol family (IPv4 only) */
285 #endif
286 static int      send_to_all;    /* send message to all IPv4/IPv6 addresses */
287 static int      use_bootfile;   /* log entire bootfile for every kern msg */
288 static int      no_compress;    /* don't compress messages (1=pipes, 2=all) */
289 static int      logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
290
291 static char     bootfile[MAXLINE+1]; /* booted kernel file */
292
293 struct allowedpeer *AllowedPeers; /* List of allowed peers */
294 static int      NumAllowed;     /* Number of entries in AllowedPeers */
295
296 static int      UniquePriority; /* Only log specified priority? */
297 static int      LogFacPri;      /* Put facility and priority in log message: */
298                                 /* 0=no, 1=numeric, 2=names */
299 static int      KeepKernFac;    /* Keep remotely logged kernel facility */
300 static int      needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
301 static struct pidfh *pfh;
302
303 volatile sig_atomic_t MarkSet, WantDie;
304
305 static int      allowaddr(char *);
306 static void     cfline(const char *, struct filed *,
307                     const char *, const char *);
308 static const char *cvthname(struct sockaddr *);
309 static void     deadq_enter(pid_t, const char *);
310 static int      deadq_remove(pid_t);
311 static int      decode(const char *, CODE *);
312 static void     die(int);
313 static void     dodie(int);
314 static void     dofsync(void);
315 static void     domark(int);
316 static void     fprintlog(struct filed *, int, const char *);
317 static int      *socksetup(int, const char *);
318 static void     init(int);
319 static void     logerror(const char *);
320 static void     logmsg(int, const char *, const char *, int);
321 static void     log_deadchild(pid_t, int, const char *);
322 static void     markit(void);
323 static int      skip_message(const char *, const char *, int);
324 static void     printline(const char *, char *);
325 static void     printsys(char *);
326 static int      p_open(const char *, pid_t *);
327 static void     readklog(void);
328 static void     reapchild(int);
329 static void     usage(void);
330 static int      validate(struct sockaddr *, const char *);
331 static void     unmapped(struct sockaddr *);
332 static void     wallmsg(struct filed *, struct iovec *);
333 static int      waitdaemon(int, int, int);
334 static void     timedout(int);
335 static void     double_rbuf(int);
336
337 int
338 main(int argc, char *argv[])
339 {
340         int ch, i, fdsrmax = 0, l;
341         struct sockaddr_un sunx, fromunix;
342         struct sockaddr_storage frominet;
343         fd_set *fdsr = NULL;
344         char line[MAXLINE + 1];
345         const char *bindhostname, *hname;
346         struct timeval tv, *tvp;
347         struct sigaction sact;
348         struct funix *fx, *fx1;
349         sigset_t mask;
350         pid_t ppid = 1, spid;
351         socklen_t len;
352
353         bindhostname = NULL;
354         while ((ch = getopt(argc, argv, "46Aa:b:cCdf:kl:m:nop:P:sS:uv")) != -1)
355                 switch (ch) {
356                 case '4':
357                         family = PF_INET;
358                         break;
359 #ifdef INET6
360                 case '6':
361                         family = PF_INET6;
362                         break;
363 #endif
364                 case 'A':
365                         send_to_all++;
366                         break;
367                 case 'a':               /* allow specific network addresses only */
368                         if (allowaddr(optarg) == -1)
369                                 usage();
370                         break;
371                 case 'b':
372                         bindhostname = optarg;
373                         break;
374                 case 'c':
375                         no_compress++;
376                         break;
377                 case 'C':
378                         logflags |= O_CREAT;
379                         break;
380                 case 'd':               /* debug */
381                         Debug++;
382                         break;
383                 case 'f':               /* configuration file */
384                         ConfFile = optarg;
385                         break;
386                 case 'k':               /* keep remote kern fac */
387                         KeepKernFac = 1;
388                         break;
389                 case 'l':
390                     {
391                         long    perml;
392                         mode_t  mode;
393                         char    *name, *ep;
394
395                         if (optarg[0] == '/') {
396                                 mode = DEFFILEMODE;
397                                 name = optarg;
398                         } else if ((name = strchr(optarg, ':')) != NULL) {
399                                 *name++ = '\0';
400                                 if (name[0] != '/')
401                                         errx(1, "socket name must be absolute "
402                                             "path");
403                                 if (isdigit(*optarg)) {
404                                         perml = strtol(optarg, &ep, 8);
405                                     if (*ep || perml < 0 ||
406                                         perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
407                                             errx(1, "invalid mode %s, exiting",
408                                                 optarg);
409                                     mode = (mode_t )perml;
410                                 } else
411                                         errx(1, "invalid mode %s, exiting",
412                                             optarg);
413                         } else  /* doesn't begin with '/', and no ':' */
414                                 errx(1, "can't parse path %s", optarg);
415
416                         if (strlen(name) >= sizeof(sunx.sun_path))
417                                 errx(1, "%s path too long, exiting", name);
418                         if ((fx = malloc(sizeof(struct funix))) == NULL)
419                                 errx(1, "malloc failed");
420                         fx->s = -1;
421                         fx->name = name;
422                         fx->mode = mode;
423                         STAILQ_INSERT_TAIL(&funixes, fx, next);
424                         break;
425                    }
426                 case 'm':               /* mark interval */
427                         MarkInterval = atoi(optarg) * 60;
428                         break;
429                 case 'n':
430                         resolve = 0;
431                         break;
432                 case 'o':
433                         use_bootfile = 1;
434                         break;
435                 case 'p':               /* path */
436                         if (strlen(optarg) >= sizeof(sunx.sun_path))
437                                 errx(1, "%s path too long, exiting", optarg);
438                         funix_default.name = optarg;
439                         break;
440                 case 'P':               /* path for alt. PID */
441                         PidFile = optarg;
442                         break;
443                 case 's':               /* no network mode */
444                         SecureMode++;
445                         break;
446                 case 'S':               /* path for privileged originator */
447                         if (strlen(optarg) >= sizeof(sunx.sun_path))
448                                 errx(1, "%s path too long, exiting", optarg);
449                         funix_secure.name = optarg;
450                         break;
451                 case 'u':               /* only log specified priority */
452                         UniquePriority++;
453                         break;
454                 case 'v':               /* log facility and priority */
455                         LogFacPri++;
456                         break;
457                 default:
458                         usage();
459                 }
460         if ((argc -= optind) != 0)
461                 usage();
462
463         pfh = pidfile_open(PidFile, 0600, &spid);
464         if (pfh == NULL) {
465                 if (errno == EEXIST)
466                         errx(1, "syslogd already running, pid: %d", spid);
467                 warn("cannot open pid file");
468         }
469
470         if (!Debug) {
471                 ppid = waitdaemon(0, 0, 30);
472                 if (ppid < 0) {
473                         warn("could not become daemon");
474                         pidfile_remove(pfh);
475                         exit(1);
476                 }
477         } else {
478                 setlinebuf(stdout);
479         }
480
481         if (NumAllowed)
482                 endservent();
483
484         consfile.f_type = F_CONSOLE;
485         (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
486             sizeof(consfile.f_un.f_fname));
487         (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
488         (void)signal(SIGTERM, dodie);
489         (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
490         (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
491         /*
492          * We don't want the SIGCHLD and SIGHUP handlers to interfere
493          * with each other; they are likely candidates for being called
494          * simultaneously (SIGHUP closes pipe descriptor, process dies,
495          * SIGCHLD happens).
496          */
497         sigemptyset(&mask);
498         sigaddset(&mask, SIGHUP);
499         sact.sa_handler = reapchild;
500         sact.sa_mask = mask;
501         sact.sa_flags = SA_RESTART;
502         (void)sigaction(SIGCHLD, &sact, NULL);
503         (void)signal(SIGALRM, domark);
504         (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
505         (void)alarm(TIMERINTVL);
506
507         TAILQ_INIT(&deadq_head);
508
509 #ifndef SUN_LEN
510 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
511 #endif
512         STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
513                 (void)unlink(fx->name);
514                 memset(&sunx, 0, sizeof(sunx));
515                 sunx.sun_family = AF_UNIX;
516                 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
517                 fx->s = socket(AF_UNIX, SOCK_DGRAM, 0);
518                 if (fx->s < 0 ||
519                     bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
520                     chmod(fx->name, fx->mode) < 0) {
521                         (void)snprintf(line, sizeof line,
522                                         "cannot create %s", fx->name);
523                         logerror(line);
524                         dprintf("cannot create %s (%d)\n", fx->name, errno);
525                         if (fx == &funix_default || fx == &funix_secure)
526                                 die(0);
527                         else {
528                                 STAILQ_REMOVE(&funixes, fx, funix, next);
529                                 continue;
530                         }
531                         double_rbuf(fx->s);
532                 }
533         }
534         if (SecureMode <= 1)
535                 finet = socksetup(family, bindhostname);
536
537         if (finet) {
538                 if (SecureMode) {
539                         for (i = 0; i < *finet; i++) {
540                                 if (shutdown(finet[i+1], SHUT_RD) < 0) {
541                                         logerror("shutdown");
542                                         if (!Debug)
543                                                 die(0);
544                                 }
545                         }
546                 } else {
547                         dprintf("listening on inet and/or inet6 socket\n");
548                 }
549                 dprintf("sending on inet and/or inet6 socket\n");
550         }
551
552         if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
553                 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
554                         fklog = -1;
555         if (fklog < 0)
556                 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
557
558         /* tuck my process id away */
559         pidfile_write(pfh);
560
561         dprintf("off & running....\n");
562
563         init(0);
564         /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
565         sigemptyset(&mask);
566         sigaddset(&mask, SIGCHLD);
567         sact.sa_handler = init;
568         sact.sa_mask = mask;
569         sact.sa_flags = SA_RESTART;
570         (void)sigaction(SIGHUP, &sact, NULL);
571
572         tvp = &tv;
573         tv.tv_sec = tv.tv_usec = 0;
574
575         if (fklog != -1 && fklog > fdsrmax)
576                 fdsrmax = fklog;
577         if (finet && !SecureMode) {
578                 for (i = 0; i < *finet; i++) {
579                     if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
580                         fdsrmax = finet[i+1];
581                 }
582         }
583         STAILQ_FOREACH(fx, &funixes, next)
584                 if (fx->s > fdsrmax)
585                         fdsrmax = fx->s;
586
587         fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
588             sizeof(fd_mask));
589         if (fdsr == NULL)
590                 errx(1, "calloc fd_set");
591
592         for (;;) {
593                 if (MarkSet)
594                         markit();
595                 if (WantDie)
596                         die(WantDie);
597
598                 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
599                     sizeof(fd_mask));
600
601                 if (fklog != -1)
602                         FD_SET(fklog, fdsr);
603                 if (finet && !SecureMode) {
604                         for (i = 0; i < *finet; i++) {
605                                 if (finet[i+1] != -1)
606                                         FD_SET(finet[i+1], fdsr);
607                         }
608                 }
609                 STAILQ_FOREACH(fx, &funixes, next)
610                         FD_SET(fx->s, fdsr);
611
612                 i = select(fdsrmax+1, fdsr, NULL, NULL,
613                     needdofsync ? &tv : tvp);
614                 switch (i) {
615                 case 0:
616                         dofsync();
617                         needdofsync = 0;
618                         if (tvp) {
619                                 tvp = NULL;
620                                 if (ppid != 1)
621                                         kill(ppid, SIGALRM);
622                         }
623                         continue;
624                 case -1:
625                         if (errno != EINTR)
626                                 logerror("select");
627                         continue;
628                 }
629                 if (fklog != -1 && FD_ISSET(fklog, fdsr))
630                         readklog();
631                 if (finet && !SecureMode) {
632                         for (i = 0; i < *finet; i++) {
633                                 if (FD_ISSET(finet[i+1], fdsr)) {
634                                         len = sizeof(frominet);
635                                         l = recvfrom(finet[i+1], line, MAXLINE,
636                                              0, (struct sockaddr *)&frominet,
637                                              &len);
638                                         if (l > 0) {
639                                                 line[l] = '\0';
640                                                 hname = cvthname((struct sockaddr *)&frominet);
641                                                 unmapped((struct sockaddr *)&frominet);
642                                                 if (validate((struct sockaddr *)&frominet, hname))
643                                                         printline(hname, line);
644                                         } else if (l < 0 && errno != EINTR)
645                                                 logerror("recvfrom inet");
646                                 }
647                         }
648                 }
649                 STAILQ_FOREACH(fx, &funixes, next) {
650                         if (FD_ISSET(fx->s, fdsr)) {
651                                 len = sizeof(fromunix);
652                                 l = recvfrom(fx->s, line, MAXLINE, 0,
653                                     (struct sockaddr *)&fromunix, &len);
654                                 if (l > 0) {
655                                         line[l] = '\0';
656                                         printline(LocalHostName, line);
657                                 } else if (l < 0 && errno != EINTR)
658                                         logerror("recvfrom unix");
659                         }
660                 }
661         }
662         if (fdsr)
663                 free(fdsr);
664 }
665
666 static void
667 unmapped(struct sockaddr *sa)
668 {
669         struct sockaddr_in6 *sin6;
670         struct sockaddr_in sin4;
671
672         if (sa->sa_family != AF_INET6)
673                 return;
674         if (sa->sa_len != sizeof(struct sockaddr_in6) ||
675             sizeof(sin4) > sa->sa_len)
676                 return;
677         sin6 = (struct sockaddr_in6 *)sa;
678         if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
679                 return;
680
681         memset(&sin4, 0, sizeof(sin4));
682         sin4.sin_family = AF_INET;
683         sin4.sin_len = sizeof(struct sockaddr_in);
684         memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
685                sizeof(sin4.sin_addr));
686         sin4.sin_port = sin6->sin6_port;
687
688         memcpy(sa, &sin4, sin4.sin_len);
689 }
690
691 static void
692 usage(void)
693 {
694
695         fprintf(stderr, "%s\n%s\n%s\n%s\n",
696                 "usage: syslogd [-46ACcdknosuv] [-a allowed_peer]",
697                 "               [-b bind_address] [-f config_file]",
698                 "               [-l [mode:]path] [-m mark_interval]",
699                 "               [-P pid_file] [-p log_socket]");
700         exit(1);
701 }
702
703 /*
704  * Take a raw input line, decode the message, and print the message
705  * on the appropriate log files.
706  */
707 static void
708 printline(const char *hname, char *msg)
709 {
710         char *p, *q;
711         long n;
712         int c, pri;
713         char line[MAXLINE + 1];
714
715         /* test for special codes */
716         p = msg;
717         pri = DEFUPRI;
718         if (*p == '<') {
719                 errno = 0;
720                 n = strtol(p + 1, &q, 10);
721                 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
722                         p = q + 1;
723                         pri = n;
724                 }
725         }
726         if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
727                 pri = DEFUPRI;
728
729         /*
730          * Don't allow users to log kernel messages.
731          * NOTE: since LOG_KERN == 0 this will also match
732          *       messages with no facility specified.
733          */
734         if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
735                 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
736
737         q = line;
738
739         while ((c = (unsigned char)*p++) != '\0' &&
740             q < &line[sizeof(line) - 4]) {
741                 if ((c & 0x80) && c < 0xA0) {
742                         c &= 0x7F;
743                         *q++ = 'M';
744                         *q++ = '-';
745                 }
746                 if (isascii(c) && iscntrl(c)) {
747                         if (c == '\n') {
748                                 *q++ = ' ';
749                         } else if (c == '\t') {
750                                 *q++ = '\t';
751                         } else {
752                                 *q++ = '^';
753                                 *q++ = c ^ 0100;
754                         }
755                 } else {
756                         *q++ = c;
757                 }
758         }
759         *q = '\0';
760
761         logmsg(pri, line, hname, 0);
762 }
763
764 /*
765  * Read /dev/klog while data are available, split into lines.
766  */
767 static void
768 readklog(void)
769 {
770         char *p, *q, line[MAXLINE + 1];
771         int len, i;
772
773         len = 0;
774         for (;;) {
775                 i = read(fklog, line + len, MAXLINE - 1 - len);
776                 if (i > 0) {
777                         line[i + len] = '\0';
778                 } else {
779                         if (i < 0 && errno != EINTR && errno != EAGAIN) {
780                                 logerror("klog");
781                                 fklog = -1;
782                         }
783                         break;
784                 }
785
786                 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
787                         *q = '\0';
788                         printsys(p);
789                 }
790                 len = strlen(p);
791                 if (len >= MAXLINE - 1) {
792                         printsys(p);
793                         len = 0;
794                 }
795                 if (len > 0)
796                         memmove(line, p, len + 1);
797         }
798         if (len > 0)
799                 printsys(line);
800 }
801
802 /*
803  * Take a raw input line from /dev/klog, format similar to syslog().
804  */
805 static void
806 printsys(char *msg)
807 {
808         char *p, *q;
809         long n;
810         int flags, isprintf, pri;
811
812         flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
813         p = msg;
814         pri = DEFSPRI;
815         isprintf = 1;
816         if (*p == '<') {
817                 errno = 0;
818                 n = strtol(p + 1, &q, 10);
819                 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
820                         p = q + 1;
821                         pri = n;
822                         isprintf = 0;
823                 }
824         }
825         /*
826          * Kernel printf's and LOG_CONSOLE messages have been displayed
827          * on the console already.
828          */
829         if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
830                 flags |= IGN_CONS;
831         if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
832                 pri = DEFSPRI;
833         logmsg(pri, p, LocalHostName, flags);
834 }
835
836 static time_t   now;
837
838 /*
839  * Match a program or host name against a specification.
840  * Return a non-0 value if the message must be ignored
841  * based on the specification.
842  */
843 static int
844 skip_message(const char *name, const char *spec, int checkcase)
845 {
846         const char *s;
847         char prev, next;
848         int exclude = 0;
849         /* Behaviour on explicit match */
850
851         if (spec == NULL)
852                 return 0;
853         switch (*spec) {
854         case '-':
855                 exclude = 1;
856                 /*FALLTHROUGH*/
857         case '+':
858                 spec++;
859                 break;
860         default:
861                 break;
862         }
863         if (checkcase)
864                 s = strstr (spec, name);
865         else
866                 s = strcasestr (spec, name);
867
868         if (s != NULL) {
869                 prev = (s == spec ? ',' : *(s - 1));
870                 next = *(s + strlen (name));
871
872                 if (prev == ',' && (next == '\0' || next == ','))
873                         /* Explicit match: skip iff the spec is an
874                            exclusive one. */
875                         return exclude;
876         }
877
878         /* No explicit match for this name: skip the message iff
879            the spec is an inclusive one. */
880         return !exclude;
881 }
882
883 /*
884  * Log a message to the appropriate log files, users, etc. based on
885  * the priority.
886  */
887 static void
888 logmsg(int pri, const char *msg, const char *from, int flags)
889 {
890         struct filed *f;
891         int i, fac, msglen, omask, prilev;
892         const char *timestamp;
893         char prog[NAME_MAX+1];
894         char buf[MAXLINE+1];
895
896         dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
897             pri, flags, from, msg);
898
899         omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
900
901         /*
902          * Check to see if msg looks non-standard.
903          */
904         msglen = strlen(msg);
905         if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
906             msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
907                 flags |= ADDDATE;
908
909         (void)time(&now);
910         if (flags & ADDDATE) {
911                 timestamp = ctime(&now) + 4;
912         } else {
913                 timestamp = msg;
914                 msg += 16;
915                 msglen -= 16;
916         }
917
918         /* skip leading blanks */
919         while (isspace(*msg)) {
920                 msg++;
921                 msglen--;
922         }
923
924         /* extract facility and priority level */
925         if (flags & MARK)
926                 fac = LOG_NFACILITIES;
927         else
928                 fac = LOG_FAC(pri);
929
930         /* Check maximum facility number. */
931         if (fac > LOG_NFACILITIES) {
932                 (void)sigsetmask(omask);
933                 return;
934         }
935
936         prilev = LOG_PRI(pri);
937
938         /* extract program name */
939         for (i = 0; i < NAME_MAX; i++) {
940                 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
941                     msg[i] == '/' || isspace(msg[i]))
942                         break;
943                 prog[i] = msg[i];
944         }
945         prog[i] = 0;
946
947         /* add kernel prefix for kernel messages */
948         if (flags & ISKERNEL) {
949                 snprintf(buf, sizeof(buf), "%s: %s",
950                     use_bootfile ? bootfile : "kernel", msg);
951                 msg = buf;
952                 msglen = strlen(buf);
953         }
954
955         /* log the message to the particular outputs */
956         if (!Initialized) {
957                 f = &consfile;
958                 f->f_file = open(ctty, O_WRONLY, 0);
959
960                 if (f->f_file >= 0) {
961                         (void)strlcpy(f->f_lasttime, timestamp,
962                                 sizeof(f->f_lasttime));
963                         fprintlog(f, flags, msg);
964                         (void)close(f->f_file);
965                 }
966                 (void)sigsetmask(omask);
967                 return;
968         }
969         for (f = Files; f; f = f->f_next) {
970                 /* skip messages that are incorrect priority */
971                 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
972                      ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
973                      ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
974                      )
975                     || f->f_pmask[fac] == INTERNAL_NOPRI)
976                         continue;
977
978                 /* skip messages with the incorrect hostname */
979                 if (skip_message(from, f->f_host, 0))
980                         continue;
981
982                 /* skip messages with the incorrect program name */
983                 if (skip_message(prog, f->f_program, 1))
984                         continue;
985
986                 /* skip message to console if it has already been printed */
987                 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
988                         continue;
989
990                 /* don't output marks to recently written files */
991                 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
992                         continue;
993
994                 /*
995                  * suppress duplicate lines to this file
996                  */
997                 if (no_compress - (f->f_type != F_PIPE) < 1 &&
998                     (flags & MARK) == 0 && msglen == f->f_prevlen &&
999                     !strcmp(msg, f->f_prevline) &&
1000                     !strcasecmp(from, f->f_prevhost)) {
1001                         (void)strlcpy(f->f_lasttime, timestamp,
1002                                 sizeof(f->f_lasttime));
1003                         f->f_prevcount++;
1004                         dprintf("msg repeated %d times, %ld sec of %d\n",
1005                             f->f_prevcount, (long)(now - f->f_time),
1006                             repeatinterval[f->f_repeatcount]);
1007                         /*
1008                          * If domark would have logged this by now,
1009                          * flush it now (so we don't hold isolated messages),
1010                          * but back off so we'll flush less often
1011                          * in the future.
1012                          */
1013                         if (now > REPEATTIME(f)) {
1014                                 fprintlog(f, flags, (char *)NULL);
1015                                 BACKOFF(f);
1016                         }
1017                 } else {
1018                         /* new line, save it */
1019                         if (f->f_prevcount)
1020                                 fprintlog(f, 0, (char *)NULL);
1021                         f->f_repeatcount = 0;
1022                         f->f_prevpri = pri;
1023                         (void)strlcpy(f->f_lasttime, timestamp,
1024                                 sizeof(f->f_lasttime));
1025                         (void)strlcpy(f->f_prevhost, from,
1026                             sizeof(f->f_prevhost));
1027                         if (msglen < MAXSVLINE) {
1028                                 f->f_prevlen = msglen;
1029                                 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1030                                 fprintlog(f, flags, (char *)NULL);
1031                         } else {
1032                                 f->f_prevline[0] = 0;
1033                                 f->f_prevlen = 0;
1034                                 fprintlog(f, flags, msg);
1035                         }
1036                 }
1037         }
1038         (void)sigsetmask(omask);
1039 }
1040
1041 static void
1042 dofsync(void)
1043 {
1044         struct filed *f;
1045
1046         for (f = Files; f; f = f->f_next) {
1047                 if ((f->f_type == F_FILE) &&
1048                     (f->f_flags & FFLAG_NEEDSYNC)) {
1049                         f->f_flags &= ~FFLAG_NEEDSYNC;
1050                         (void)fsync(f->f_file);
1051                 }
1052         }
1053 }
1054
1055 static void
1056 fprintlog(struct filed *f, int flags, const char *msg)
1057 {
1058         struct iovec iov[7];
1059         struct iovec *v;
1060         struct addrinfo *r;
1061         int i, l, lsent = 0;
1062         char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1063         char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1064         const char *msgret;
1065
1066         v = iov;
1067         if (f->f_type == F_WALL) {
1068                 v->iov_base = greetings;
1069                 v->iov_len = snprintf(greetings, sizeof greetings,
1070                     "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1071                     f->f_prevhost, ctime(&now));
1072                 if (v->iov_len > 0)
1073                         v++;
1074                 v->iov_base = nul;
1075                 v->iov_len = 0;
1076                 v++;
1077         } else {
1078                 v->iov_base = f->f_lasttime;
1079                 v->iov_len = 15;
1080                 v++;
1081                 v->iov_base = space;
1082                 v->iov_len = 1;
1083                 v++;
1084         }
1085
1086         if (LogFacPri) {
1087                 static char fp_buf[30]; /* Hollow laugh */
1088                 int fac = f->f_prevpri & LOG_FACMASK;
1089                 int pri = LOG_PRI(f->f_prevpri);
1090                 const char *f_s = NULL;
1091                 char f_n[5];    /* Hollow laugh */
1092                 const char *p_s = NULL;
1093                 char p_n[5];    /* Hollow laugh */
1094
1095                 if (LogFacPri > 1) {
1096                   CODE *c;
1097
1098                   for (c = facilitynames; c->c_name; c++) {
1099                     if (c->c_val == fac) {
1100                       f_s = c->c_name;
1101                       break;
1102                     }
1103                   }
1104                   for (c = prioritynames; c->c_name; c++) {
1105                     if (c->c_val == pri) {
1106                       p_s = c->c_name;
1107                       break;
1108                     }
1109                   }
1110                 }
1111                 if (!f_s) {
1112                   snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1113                   f_s = f_n;
1114                 }
1115                 if (!p_s) {
1116                   snprintf(p_n, sizeof p_n, "%d", pri);
1117                   p_s = p_n;
1118                 }
1119                 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1120                 v->iov_base = fp_buf;
1121                 v->iov_len = strlen(fp_buf);
1122         } else {
1123                 v->iov_base = nul;
1124                 v->iov_len = 0;
1125         }
1126         v++;
1127
1128         v->iov_base = f->f_prevhost;
1129         v->iov_len = strlen(v->iov_base);
1130         v++;
1131         v->iov_base = space;
1132         v->iov_len = 1;
1133         v++;
1134
1135         if (msg) {
1136                 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1137                 if (wmsg == NULL) {
1138                         logerror("strdup");
1139                         exit(1);
1140                 }
1141                 v->iov_base = wmsg;
1142                 v->iov_len = strlen(msg);
1143         } else if (f->f_prevcount > 1) {
1144                 v->iov_base = repbuf;
1145                 v->iov_len = snprintf(repbuf, sizeof repbuf,
1146                     "last message repeated %d times", f->f_prevcount);
1147         } else {
1148                 v->iov_base = f->f_prevline;
1149                 v->iov_len = f->f_prevlen;
1150         }
1151         v++;
1152
1153         dprintf("Logging to %s", TypeNames[f->f_type]);
1154         f->f_time = now;
1155
1156         switch (f->f_type) {
1157                 int port;
1158         case F_UNUSED:
1159                 dprintf("\n");
1160                 break;
1161
1162         case F_FORW:
1163                 port = (int)ntohs(((struct sockaddr_in *)
1164                             (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1165                 if (port != 514) {
1166                         dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1167                 } else {
1168                         dprintf(" %s\n", f->f_un.f_forw.f_hname);
1169                 }
1170                 /* check for local vs remote messages */
1171                 if (strcasecmp(f->f_prevhost, LocalHostName))
1172                         l = snprintf(line, sizeof line - 1,
1173                             "<%d>%.15s Forwarded from %s: %s",
1174                             f->f_prevpri, (char *)iov[0].iov_base,
1175                             f->f_prevhost, (char *)iov[5].iov_base);
1176                 else
1177                         l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1178                              f->f_prevpri, (char *)iov[0].iov_base,
1179                             (char *)iov[5].iov_base);
1180                 if (l < 0)
1181                         l = 0;
1182                 else if (l > MAXLINE)
1183                         l = MAXLINE;
1184
1185                 if (finet) {
1186                         for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1187                                 for (i = 0; i < *finet; i++) {
1188 #if 0
1189                                         /*
1190                                          * should we check AF first, or just
1191                                          * trial and error? FWD
1192                                          */
1193                                         if (r->ai_family ==
1194                                             address_family_of(finet[i+1]))
1195 #endif
1196                                         lsent = sendto(finet[i+1], line, l, 0,
1197                                             r->ai_addr, r->ai_addrlen);
1198                                         if (lsent == l)
1199                                                 break;
1200                                 }
1201                                 if (lsent == l && !send_to_all)
1202                                         break;
1203                         }
1204                         dprintf("lsent/l: %d/%d\n", lsent, l);
1205                         if (lsent != l) {
1206                                 int e = errno;
1207                                 logerror("sendto");
1208                                 errno = e;
1209                                 switch (errno) {
1210                                 case ENOBUFS:
1211                                 case ENETDOWN:
1212                                 case EHOSTUNREACH:
1213                                 case EHOSTDOWN:
1214                                         break;
1215                                 /* case EBADF: */
1216                                 /* case EACCES: */
1217                                 /* case ENOTSOCK: */
1218                                 /* case EFAULT: */
1219                                 /* case EMSGSIZE: */
1220                                 /* case EAGAIN: */
1221                                 /* case ENOBUFS: */
1222                                 /* case ECONNREFUSED: */
1223                                 default:
1224                                         dprintf("removing entry\n");
1225                                         f->f_type = F_UNUSED;
1226                                         break;
1227                                 }
1228                         }
1229                 }
1230                 break;
1231
1232         case F_FILE:
1233                 dprintf(" %s\n", f->f_un.f_fname);
1234                 v->iov_base = lf;
1235                 v->iov_len = 1;
1236                 if (writev(f->f_file, iov, 7) < 0) {
1237                         /*
1238                          * If writev(2) fails for potentially transient errors
1239                          * like the * filesystem being full, ignore it.
1240                          * Otherwise remove * this logfile from the list.
1241                          */
1242                         if (errno != ENOSPC) {
1243                                 int e = errno;
1244                                 (void)close(f->f_file);
1245                                 f->f_type = F_UNUSED;
1246                                 errno = e;
1247                                 logerror(f->f_un.f_fname);
1248                         }
1249                 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1250                         f->f_flags |= FFLAG_NEEDSYNC;
1251                         needdofsync = 1;
1252                 }
1253                 break;
1254
1255         case F_PIPE:
1256                 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1257                 v->iov_base = lf;
1258                 v->iov_len = 1;
1259                 if (f->f_un.f_pipe.f_pid == 0) {
1260                         if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1261                                                 &f->f_un.f_pipe.f_pid)) < 0) {
1262                                 f->f_type = F_UNUSED;
1263                                 logerror(f->f_un.f_pipe.f_pname);
1264                                 break;
1265                         }
1266                 }
1267                 if (writev(f->f_file, iov, 7) < 0) {
1268                         int e = errno;
1269                         (void)close(f->f_file);
1270                         if (f->f_un.f_pipe.f_pid > 0)
1271                                 deadq_enter(f->f_un.f_pipe.f_pid,
1272                                             f->f_un.f_pipe.f_pname);
1273                         f->f_un.f_pipe.f_pid = 0;
1274                         errno = e;
1275                         logerror(f->f_un.f_pipe.f_pname);
1276                 }
1277                 break;
1278
1279         case F_CONSOLE:
1280                 if (flags & IGN_CONS) {
1281                         dprintf(" (ignored)\n");
1282                         break;
1283                 }
1284                 /* FALLTHROUGH */
1285
1286         case F_TTY:
1287                 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1288                 v->iov_base = crlf;
1289                 v->iov_len = 2;
1290
1291                 errno = 0;      /* ttymsg() only sometimes returns an errno */
1292                 if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) {
1293                         f->f_type = F_UNUSED;
1294                         logerror(msgret);
1295                 }
1296                 break;
1297
1298         case F_USERS:
1299         case F_WALL:
1300                 dprintf("\n");
1301                 v->iov_base = crlf;
1302                 v->iov_len = 2;
1303                 wallmsg(f, iov);
1304                 break;
1305         }
1306         f->f_prevcount = 0;
1307         if (msg)
1308                 free(wmsg);
1309 }
1310
1311 /*
1312  *  WALLMSG -- Write a message to the world at large
1313  *
1314  *      Write the specified message to either the entire
1315  *      world, or a list of approved users.
1316  */
1317 static void
1318 wallmsg(struct filed *f, struct iovec *iov)
1319 {
1320         static int reenter;                     /* avoid calling ourselves */
1321         FILE *uf;
1322         struct utmp ut;
1323         int i;
1324         const char *p;
1325         char line[sizeof(ut.ut_line) + 1];
1326
1327         if (reenter++)
1328                 return;
1329         if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1330                 logerror(_PATH_UTMP);
1331                 reenter = 0;
1332                 return;
1333         }
1334         /* NOSTRICT */
1335         while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1336                 if (ut.ut_name[0] == '\0')
1337                         continue;
1338                 /* We must use strncpy since ut_* may not be NUL terminated. */
1339                 strncpy(line, ut.ut_line, sizeof(line) - 1);
1340                 line[sizeof(line) - 1] = '\0';
1341                 if (f->f_type == F_WALL) {
1342                         if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) {
1343                                 errno = 0;      /* already in msg */
1344                                 logerror(p);
1345                         }
1346                         continue;
1347                 }
1348                 /* should we send the message to this user? */
1349                 for (i = 0; i < MAXUNAMES; i++) {
1350                         if (!f->f_un.f_uname[i][0])
1351                                 break;
1352                         if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1353                             UT_NAMESIZE)) {
1354                                 if ((p = ttymsg(iov, 7, line, TTYMSGTIME))
1355                                                                 != NULL) {
1356                                         errno = 0;      /* already in msg */
1357                                         logerror(p);
1358                                 }
1359                                 break;
1360                         }
1361                 }
1362         }
1363         (void)fclose(uf);
1364         reenter = 0;
1365 }
1366
1367 static void
1368 reapchild(int signo __unused)
1369 {
1370         int status;
1371         pid_t pid;
1372         struct filed *f;
1373
1374         while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1375                 if (!Initialized)
1376                         /* Don't tell while we are initting. */
1377                         continue;
1378
1379                 /* First, look if it's a process from the dead queue. */
1380                 if (deadq_remove(pid))
1381                         goto oncemore;
1382
1383                 /* Now, look in list of active processes. */
1384                 for (f = Files; f; f = f->f_next)
1385                         if (f->f_type == F_PIPE &&
1386                             f->f_un.f_pipe.f_pid == pid) {
1387                                 (void)close(f->f_file);
1388                                 f->f_un.f_pipe.f_pid = 0;
1389                                 log_deadchild(pid, status,
1390                                               f->f_un.f_pipe.f_pname);
1391                                 break;
1392                         }
1393           oncemore:
1394                 continue;
1395         }
1396 }
1397
1398 /*
1399  * Return a printable representation of a host address.
1400  */
1401 static const char *
1402 cvthname(struct sockaddr *f)
1403 {
1404         int error, hl;
1405         sigset_t omask, nmask;
1406         static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1407
1408         error = getnameinfo((struct sockaddr *)f,
1409                             ((struct sockaddr *)f)->sa_len,
1410                             ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1411         dprintf("cvthname(%s)\n", ip);
1412
1413         if (error) {
1414                 dprintf("Malformed from address %s\n", gai_strerror(error));
1415                 return ("???");
1416         }
1417         if (!resolve)
1418                 return (ip);
1419
1420         sigemptyset(&nmask);
1421         sigaddset(&nmask, SIGHUP);
1422         sigprocmask(SIG_BLOCK, &nmask, &omask);
1423         error = getnameinfo((struct sockaddr *)f,
1424                             ((struct sockaddr *)f)->sa_len,
1425                             hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1426         sigprocmask(SIG_SETMASK, &omask, NULL);
1427         if (error) {
1428                 dprintf("Host name for your address (%s) unknown\n", ip);
1429                 return (ip);
1430         }
1431         hl = strlen(hname);
1432         if (hl > 0 && hname[hl-1] == '.')
1433                 hname[--hl] = '\0';
1434         trimdomain(hname, hl);
1435         return (hname);
1436 }
1437
1438 static void
1439 dodie(int signo)
1440 {
1441
1442         WantDie = signo;
1443 }
1444
1445 static void
1446 domark(int signo __unused)
1447 {
1448
1449         MarkSet = 1;
1450 }
1451
1452 /*
1453  * Print syslogd errors some place.
1454  */
1455 static void
1456 logerror(const char *type)
1457 {
1458         char buf[512];
1459         static int recursed = 0;
1460
1461         /* If there's an error while trying to log an error, give up. */
1462         if (recursed)
1463                 return;
1464         recursed++;
1465         if (errno)
1466                 (void)snprintf(buf,
1467                     sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1468         else
1469                 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1470         errno = 0;
1471         dprintf("%s\n", buf);
1472         logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1473         recursed--;
1474 }
1475
1476 static void
1477 die(int signo)
1478 {
1479         struct filed *f;
1480         struct funix *fx;
1481         int was_initialized;
1482         char buf[100];
1483
1484         was_initialized = Initialized;
1485         Initialized = 0;        /* Don't log SIGCHLDs. */
1486         for (f = Files; f != NULL; f = f->f_next) {
1487                 /* flush any pending output */
1488                 if (f->f_prevcount)
1489                         fprintlog(f, 0, (char *)NULL);
1490                 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1491                         (void)close(f->f_file);
1492                         f->f_un.f_pipe.f_pid = 0;
1493                 }
1494         }
1495         Initialized = was_initialized;
1496         if (signo) {
1497                 dprintf("syslogd: exiting on signal %d\n", signo);
1498                 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1499                 errno = 0;
1500                 logerror(buf);
1501         }
1502         STAILQ_FOREACH(fx, &funixes, next)
1503                 (void)unlink(fx->name);
1504         pidfile_remove(pfh);
1505
1506         exit(1);
1507 }
1508
1509 /*
1510  *  INIT -- Initialize syslogd from configuration table
1511  */
1512 static void
1513 init(int signo)
1514 {
1515         int i;
1516         FILE *cf;
1517         struct filed *f, *next, **nextp;
1518         char *p;
1519         char cline[LINE_MAX];
1520         char prog[NAME_MAX+1];
1521         char host[MAXHOSTNAMELEN];
1522         char oldLocalHostName[MAXHOSTNAMELEN];
1523         char hostMsg[2*MAXHOSTNAMELEN+40];
1524         char bootfileMsg[LINE_MAX];
1525
1526         dprintf("init\n");
1527
1528         /*
1529          * Load hostname (may have changed).
1530          */
1531         if (signo != 0)
1532                 (void)strlcpy(oldLocalHostName, LocalHostName,
1533                     sizeof(oldLocalHostName));
1534         if (gethostname(LocalHostName, sizeof(LocalHostName)))
1535                 err(EX_OSERR, "gethostname() failed");
1536         if ((p = strchr(LocalHostName, '.')) != NULL) {
1537                 *p++ = '\0';
1538                 LocalDomain = p;
1539         } else {
1540                 LocalDomain = "";
1541         }
1542
1543         /*
1544          *  Close all open log files.
1545          */
1546         Initialized = 0;
1547         for (f = Files; f != NULL; f = next) {
1548                 /* flush any pending output */
1549                 if (f->f_prevcount)
1550                         fprintlog(f, 0, (char *)NULL);
1551
1552                 switch (f->f_type) {
1553                 case F_FILE:
1554                 case F_FORW:
1555                 case F_CONSOLE:
1556                 case F_TTY:
1557                         (void)close(f->f_file);
1558                         break;
1559                 case F_PIPE:
1560                         if (f->f_un.f_pipe.f_pid > 0) {
1561                                 (void)close(f->f_file);
1562                                 deadq_enter(f->f_un.f_pipe.f_pid,
1563                                             f->f_un.f_pipe.f_pname);
1564                         }
1565                         f->f_un.f_pipe.f_pid = 0;
1566                         break;
1567                 }
1568                 next = f->f_next;
1569                 if (f->f_program) free(f->f_program);
1570                 if (f->f_host) free(f->f_host);
1571                 free((char *)f);
1572         }
1573         Files = NULL;
1574         nextp = &Files;
1575
1576         /* open the configuration file */
1577         if ((cf = fopen(ConfFile, "r")) == NULL) {
1578                 dprintf("cannot open %s\n", ConfFile);
1579                 *nextp = (struct filed *)calloc(1, sizeof(*f));
1580                 if (*nextp == NULL) {
1581                         logerror("calloc");
1582                         exit(1);
1583                 }
1584                 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1585                 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1586                 if ((*nextp)->f_next == NULL) {
1587                         logerror("calloc");
1588                         exit(1);
1589                 }
1590                 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1591                 Initialized = 1;
1592                 return;
1593         }
1594
1595         /*
1596          *  Foreach line in the conf table, open that file.
1597          */
1598         f = NULL;
1599         (void)strlcpy(host, "*", sizeof(host));
1600         (void)strlcpy(prog, "*", sizeof(prog));
1601         while (fgets(cline, sizeof(cline), cf) != NULL) {
1602                 /*
1603                  * check for end-of-section, comments, strip off trailing
1604                  * spaces and newline character. #!prog is treated specially:
1605                  * following lines apply only to that program.
1606                  */
1607                 for (p = cline; isspace(*p); ++p)
1608                         continue;
1609                 if (*p == 0)
1610                         continue;
1611                 if (*p == '#') {
1612                         p++;
1613                         if (*p != '!' && *p != '+' && *p != '-')
1614                                 continue;
1615                 }
1616                 if (*p == '+' || *p == '-') {
1617                         host[0] = *p++;
1618                         while (isspace(*p))
1619                                 p++;
1620                         if ((!*p) || (*p == '*')) {
1621                                 (void)strlcpy(host, "*", sizeof(host));
1622                                 continue;
1623                         }
1624                         if (*p == '@')
1625                                 p = LocalHostName;
1626                         for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1627                                 if (!isalnum(*p) && *p != '.' && *p != '-'
1628                                     && *p != ',' && *p != ':' && *p != '%')
1629                                         break;
1630                                 host[i] = *p++;
1631                         }
1632                         host[i] = '\0';
1633                         continue;
1634                 }
1635                 if (*p == '!') {
1636                         p++;
1637                         while (isspace(*p)) p++;
1638                         if ((!*p) || (*p == '*')) {
1639                                 (void)strlcpy(prog, "*", sizeof(prog));
1640                                 continue;
1641                         }
1642                         for (i = 0; i < NAME_MAX; i++) {
1643                                 if (!isprint(p[i]) || isspace(p[i]))
1644                                         break;
1645                                 prog[i] = p[i];
1646                         }
1647                         prog[i] = 0;
1648                         continue;
1649                 }
1650                 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1651                         cline[i] = '\0';
1652                 f = (struct filed *)calloc(1, sizeof(*f));
1653                 if (f == NULL) {
1654                         logerror("calloc");
1655                         exit(1);
1656                 }
1657                 *nextp = f;
1658                 nextp = &f->f_next;
1659                 cfline(cline, f, prog, host);
1660         }
1661
1662         /* close the configuration file */
1663         (void)fclose(cf);
1664
1665         Initialized = 1;
1666
1667         if (Debug) {
1668                 int port;
1669                 for (f = Files; f; f = f->f_next) {
1670                         for (i = 0; i <= LOG_NFACILITIES; i++)
1671                                 if (f->f_pmask[i] == INTERNAL_NOPRI)
1672                                         printf("X ");
1673                                 else
1674                                         printf("%d ", f->f_pmask[i]);
1675                         printf("%s: ", TypeNames[f->f_type]);
1676                         switch (f->f_type) {
1677                         case F_FILE:
1678                                 printf("%s", f->f_un.f_fname);
1679                                 break;
1680
1681                         case F_CONSOLE:
1682                         case F_TTY:
1683                                 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1684                                 break;
1685
1686                         case F_FORW:
1687                                 port = (int)ntohs(((struct sockaddr_in *)
1688                                     (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1689                                 if (port != 514) {
1690                                         printf("%s:%d",
1691                                                 f->f_un.f_forw.f_hname, port);
1692                                 } else {
1693                                         printf("%s", f->f_un.f_forw.f_hname);
1694                                 }
1695                                 break;
1696
1697                         case F_PIPE:
1698                                 printf("%s", f->f_un.f_pipe.f_pname);
1699                                 break;
1700
1701                         case F_USERS:
1702                                 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1703                                         printf("%s, ", f->f_un.f_uname[i]);
1704                                 break;
1705                         }
1706                         if (f->f_program)
1707                                 printf(" (%s)", f->f_program);
1708                         printf("\n");
1709                 }
1710         }
1711
1712         logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1713         dprintf("syslogd: restarted\n");
1714         /*
1715          * Log a change in hostname, but only on a restart.
1716          */
1717         if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1718                 (void)snprintf(hostMsg, sizeof(hostMsg),
1719                     "syslogd: hostname changed, \"%s\" to \"%s\"",
1720                     oldLocalHostName, LocalHostName);
1721                 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1722                 dprintf("%s\n", hostMsg);
1723         }
1724         /*
1725          * Log the kernel boot file if we aren't going to use it as
1726          * the prefix, and if this is *not* a restart.
1727          */
1728         if (signo == 0 && !use_bootfile) {
1729                 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1730                     "syslogd: kernel boot file is %s", bootfile);
1731                 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1732                 dprintf("%s\n", bootfileMsg);
1733         }
1734 }
1735
1736 /*
1737  * Crack a configuration file line
1738  */
1739 static void
1740 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1741 {
1742         struct addrinfo hints, *res;
1743         int error, i, pri, syncfile;
1744         const char *p, *q;
1745         char *bp;
1746         char buf[MAXLINE], ebuf[100];
1747
1748         dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1749
1750         errno = 0;      /* keep strerror() stuff out of logerror messages */
1751
1752         /* clear out file entry */
1753         memset(f, 0, sizeof(*f));
1754         for (i = 0; i <= LOG_NFACILITIES; i++)
1755                 f->f_pmask[i] = INTERNAL_NOPRI;
1756
1757         /* save hostname if any */
1758         if (host && *host == '*')
1759                 host = NULL;
1760         if (host) {
1761                 int hl;
1762
1763                 f->f_host = strdup(host);
1764                 if (f->f_host == NULL) {
1765                         logerror("strdup");
1766                         exit(1);
1767                 }
1768                 hl = strlen(f->f_host);
1769                 if (hl > 0 && f->f_host[hl-1] == '.')
1770                         f->f_host[--hl] = '\0';
1771                 trimdomain(f->f_host, hl);
1772         }
1773
1774         /* save program name if any */
1775         if (prog && *prog == '*')
1776                 prog = NULL;
1777         if (prog) {
1778                 f->f_program = strdup(prog);
1779                 if (f->f_program == NULL) {
1780                         logerror("strdup");
1781                         exit(1);
1782                 }
1783         }
1784
1785         /* scan through the list of selectors */
1786         for (p = line; *p && *p != '\t' && *p != ' ';) {
1787                 int pri_done;
1788                 int pri_cmp;
1789                 int pri_invert;
1790
1791                 /* find the end of this facility name list */
1792                 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1793                         continue;
1794
1795                 /* get the priority comparison */
1796                 pri_cmp = 0;
1797                 pri_done = 0;
1798                 pri_invert = 0;
1799                 if (*q == '!') {
1800                         pri_invert = 1;
1801                         q++;
1802                 }
1803                 while (!pri_done) {
1804                         switch (*q) {
1805                         case '<':
1806                                 pri_cmp |= PRI_LT;
1807                                 q++;
1808                                 break;
1809                         case '=':
1810                                 pri_cmp |= PRI_EQ;
1811                                 q++;
1812                                 break;
1813                         case '>':
1814                                 pri_cmp |= PRI_GT;
1815                                 q++;
1816                                 break;
1817                         default:
1818                                 pri_done++;
1819                                 break;
1820                         }
1821                 }
1822
1823                 /* collect priority name */
1824                 for (bp = buf; *q && !strchr("\t,; ", *q); )
1825                         *bp++ = *q++;
1826                 *bp = '\0';
1827
1828                 /* skip cruft */
1829                 while (strchr(",;", *q))
1830                         q++;
1831
1832                 /* decode priority name */
1833                 if (*buf == '*') {
1834                         pri = LOG_PRIMASK + 1;
1835                         pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1836                 } else {
1837                         /* Ignore trailing spaces. */
1838                         for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1839                                 buf[i] = '\0';
1840
1841                         pri = decode(buf, prioritynames);
1842                         if (pri < 0) {
1843                                 (void)snprintf(ebuf, sizeof ebuf,
1844                                     "unknown priority name \"%s\"", buf);
1845                                 logerror(ebuf);
1846                                 return;
1847                         }
1848                 }
1849                 if (!pri_cmp)
1850                         pri_cmp = (UniquePriority)
1851                                   ? (PRI_EQ)
1852                                   : (PRI_EQ | PRI_GT)
1853                                   ;
1854                 if (pri_invert)
1855                         pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1856
1857                 /* scan facilities */
1858                 while (*p && !strchr("\t.; ", *p)) {
1859                         for (bp = buf; *p && !strchr("\t,;. ", *p); )
1860                                 *bp++ = *p++;
1861                         *bp = '\0';
1862
1863                         if (*buf == '*') {
1864                                 for (i = 0; i < LOG_NFACILITIES; i++) {
1865                                         f->f_pmask[i] = pri;
1866                                         f->f_pcmp[i] = pri_cmp;
1867                                 }
1868                         } else {
1869                                 i = decode(buf, facilitynames);
1870                                 if (i < 0) {
1871                                         (void)snprintf(ebuf, sizeof ebuf,
1872                                             "unknown facility name \"%s\"",
1873                                             buf);
1874                                         logerror(ebuf);
1875                                         return;
1876                                 }
1877                                 f->f_pmask[i >> 3] = pri;
1878                                 f->f_pcmp[i >> 3] = pri_cmp;
1879                         }
1880                         while (*p == ',' || *p == ' ')
1881                                 p++;
1882                 }
1883
1884                 p = q;
1885         }
1886
1887         /* skip to action part */
1888         while (*p == '\t' || *p == ' ')
1889                 p++;
1890
1891         if (*p == '-') {
1892                 syncfile = 0;
1893                 p++;
1894         } else
1895                 syncfile = 1;
1896
1897         switch (*p) {
1898         case '@':
1899                 {
1900                         char *tp;
1901                         /*
1902                          * scan forward to see if there is a port defined.
1903                          * so we can't use strlcpy..
1904                          */
1905                         i = sizeof(f->f_un.f_forw.f_hname);
1906                         tp = f->f_un.f_forw.f_hname;
1907                         p++;
1908
1909                         while (*p && (*p != ':') && (i-- > 0)) {
1910                                 *tp++ = *p++;
1911                         }
1912                         *tp = '\0';
1913                 }
1914                 /* See if we copied a domain and have a port */
1915                 if (*p == ':')
1916                         p++;
1917                 else
1918                         p = NULL;
1919                 
1920                 memset(&hints, 0, sizeof(hints));
1921                 hints.ai_family = family;
1922                 hints.ai_socktype = SOCK_DGRAM;
1923                 error = getaddrinfo(f->f_un.f_forw.f_hname,
1924                                 p ? p: "syslog", &hints, &res); 
1925                 if (error) {
1926                         logerror(gai_strerror(error));
1927                         break;
1928                 }
1929                 f->f_un.f_forw.f_addr = res;
1930                 f->f_type = F_FORW;
1931                 break;
1932
1933         case '/':
1934                 if ((f->f_file = open(p, logflags, 0600)) < 0) {
1935                         f->f_type = F_UNUSED;
1936                         logerror(p);
1937                         break;
1938                 }
1939                 if (syncfile)
1940                         f->f_flags |= FFLAG_SYNC;
1941                 if (isatty(f->f_file)) {
1942                         if (strcmp(p, ctty) == 0)
1943                                 f->f_type = F_CONSOLE;
1944                         else
1945                                 f->f_type = F_TTY;
1946                         (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1947                             sizeof(f->f_un.f_fname));
1948                 } else {
1949                         (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1950                         f->f_type = F_FILE;
1951                 }
1952                 break;
1953
1954         case '|':
1955                 f->f_un.f_pipe.f_pid = 0;
1956                 (void)strlcpy(f->f_un.f_fname, p + 1, sizeof(f->f_un.f_fname));
1957                 f->f_type = F_PIPE;
1958                 break;
1959
1960         case '*':
1961                 f->f_type = F_WALL;
1962                 break;
1963
1964         default:
1965                 for (i = 0; i < MAXUNAMES && *p; i++) {
1966                         for (q = p; *q && *q != ','; )
1967                                 q++;
1968                         (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1969                         if ((q - p) > UT_NAMESIZE)
1970                                 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1971                         else
1972                                 f->f_un.f_uname[i][q - p] = '\0';
1973                         while (*q == ',' || *q == ' ')
1974                                 q++;
1975                         p = q;
1976                 }
1977                 f->f_type = F_USERS;
1978                 break;
1979         }
1980 }
1981
1982
1983 /*
1984  *  Decode a symbolic name to a numeric value
1985  */
1986 static int
1987 decode(const char *name, CODE *codetab)
1988 {
1989         CODE *c;
1990         char *p, buf[40];
1991
1992         if (isdigit(*name))
1993                 return (atoi(name));
1994
1995         for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1996                 if (isupper(*name))
1997                         *p = tolower(*name);
1998                 else
1999                         *p = *name;
2000         }
2001         *p = '\0';
2002         for (c = codetab; c->c_name; c++)
2003                 if (!strcmp(buf, c->c_name))
2004                         return (c->c_val);
2005
2006         return (-1);
2007 }
2008
2009 static void
2010 markit(void)
2011 {
2012         struct filed *f;
2013         dq_t q, next;
2014
2015         now = time((time_t *)NULL);
2016         MarkSeq += TIMERINTVL;
2017         if (MarkSeq >= MarkInterval) {
2018                 logmsg(LOG_INFO, "-- MARK --",
2019                     LocalHostName, ADDDATE|MARK);
2020                 MarkSeq = 0;
2021         }
2022
2023         for (f = Files; f; f = f->f_next) {
2024                 if (f->f_prevcount && now >= REPEATTIME(f)) {
2025                         dprintf("flush %s: repeated %d times, %d sec.\n",
2026                             TypeNames[f->f_type], f->f_prevcount,
2027                             repeatinterval[f->f_repeatcount]);
2028                         fprintlog(f, 0, (char *)NULL);
2029                         BACKOFF(f);
2030                 }
2031         }
2032
2033         /* Walk the dead queue, and see if we should signal somebody. */
2034         for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2035                 next = TAILQ_NEXT(q, dq_entries);
2036
2037                 switch (q->dq_timeout) {
2038                 case 0:
2039                         /* Already signalled once, try harder now. */
2040                         if (kill(q->dq_pid, SIGKILL) != 0)
2041                                 (void)deadq_remove(q->dq_pid);
2042                         break;
2043
2044                 case 1:
2045                         /*
2046                          * Timed out on dead queue, send terminate
2047                          * signal.  Note that we leave the removal
2048                          * from the dead queue to reapchild(), which
2049                          * will also log the event (unless the process
2050                          * didn't even really exist, in case we simply
2051                          * drop it from the dead queue).
2052                          */
2053                         if (kill(q->dq_pid, SIGTERM) != 0)
2054                                 (void)deadq_remove(q->dq_pid);
2055                         /* FALLTHROUGH */
2056
2057                 default:
2058                         q->dq_timeout--;
2059                 }
2060         }
2061         MarkSet = 0;
2062         (void)alarm(TIMERINTVL);
2063 }
2064
2065 /*
2066  * fork off and become a daemon, but wait for the child to come online
2067  * before returing to the parent, or we get disk thrashing at boot etc.
2068  * Set a timer so we don't hang forever if it wedges.
2069  */
2070 static int
2071 waitdaemon(int nochdir, int noclose, int maxwait)
2072 {
2073         int fd;
2074         int status;
2075         pid_t pid, childpid;
2076
2077         switch (childpid = fork()) {
2078         case -1:
2079                 return (-1);
2080         case 0:
2081                 break;
2082         default:
2083                 signal(SIGALRM, timedout);
2084                 alarm(maxwait);
2085                 while ((pid = wait3(&status, 0, NULL)) != -1) {
2086                         if (WIFEXITED(status))
2087                                 errx(1, "child pid %d exited with return code %d",
2088                                         pid, WEXITSTATUS(status));
2089                         if (WIFSIGNALED(status))
2090                                 errx(1, "child pid %d exited on signal %d%s",
2091                                         pid, WTERMSIG(status),
2092                                         WCOREDUMP(status) ? " (core dumped)" :
2093                                         "");
2094                         if (pid == childpid)    /* it's gone... */
2095                                 break;
2096                 }
2097                 exit(0);
2098         }
2099
2100         if (setsid() == -1)
2101                 return (-1);
2102
2103         if (!nochdir)
2104                 (void)chdir("/");
2105
2106         if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2107                 (void)dup2(fd, STDIN_FILENO);
2108                 (void)dup2(fd, STDOUT_FILENO);
2109                 (void)dup2(fd, STDERR_FILENO);
2110                 if (fd > 2)
2111                         (void)close (fd);
2112         }
2113         return (getppid());
2114 }
2115
2116 /*
2117  * We get a SIGALRM from the child when it's running and finished doing it's
2118  * fsync()'s or O_SYNC writes for all the boot messages.
2119  *
2120  * We also get a signal from the kernel if the timer expires, so check to
2121  * see what happened.
2122  */
2123 static void
2124 timedout(int sig __unused)
2125 {
2126         int left;
2127         left = alarm(0);
2128         signal(SIGALRM, SIG_DFL);
2129         if (left == 0)
2130                 errx(1, "timed out waiting for child");
2131         else
2132                 _exit(0);
2133 }
2134
2135 /*
2136  * Add `s' to the list of allowable peer addresses to accept messages
2137  * from.
2138  *
2139  * `s' is a string in the form:
2140  *
2141  *    [*]domainname[:{servicename|portnumber|*}]
2142  *
2143  * or
2144  *
2145  *    netaddr/maskbits[:{servicename|portnumber|*}]
2146  *
2147  * Returns -1 on error, 0 if the argument was valid.
2148  */
2149 static int
2150 allowaddr(char *s)
2151 {
2152         char *cp1, *cp2;
2153         struct allowedpeer ap;
2154         struct servent *se;
2155         int masklen = -1, i;
2156         struct addrinfo hints, *res;
2157         struct in_addr *addrp, *maskp;
2158         u_int32_t *addr6p, *mask6p;
2159         char ip[NI_MAXHOST];
2160
2161 #ifdef INET6
2162         if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2163 #endif
2164                 cp1 = s;
2165         if ((cp1 = strrchr(cp1, ':'))) {
2166                 /* service/port provided */
2167                 *cp1++ = '\0';
2168                 if (strlen(cp1) == 1 && *cp1 == '*')
2169                         /* any port allowed */
2170                         ap.port = 0;
2171                 else if ((se = getservbyname(cp1, "udp"))) {
2172                         ap.port = ntohs(se->s_port);
2173                 } else {
2174                         ap.port = strtol(cp1, &cp2, 0);
2175                         if (*cp2 != '\0')
2176                                 return (-1); /* port not numeric */
2177                 }
2178         } else {
2179                 if ((se = getservbyname("syslog", "udp")))
2180                         ap.port = ntohs(se->s_port);
2181                 else
2182                         /* sanity, should not happen */
2183                         ap.port = 514;
2184         }
2185
2186         if ((cp1 = strchr(s, '/')) != NULL &&
2187             strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2188                 *cp1 = '\0';
2189                 if ((masklen = atoi(cp1 + 1)) < 0)
2190                         return (-1);
2191         }
2192 #ifdef INET6
2193         if (*s == '[') {
2194                 cp2 = s + strlen(s) - 1;
2195                 if (*cp2 == ']') {
2196                         ++s;
2197                         *cp2 = '\0';
2198                 } else {
2199                         cp2 = NULL;
2200                 }
2201         } else {
2202                 cp2 = NULL;
2203         }
2204 #endif
2205         memset(&hints, 0, sizeof(hints));
2206         hints.ai_family = PF_UNSPEC;
2207         hints.ai_socktype = SOCK_DGRAM;
2208         hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2209         if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2210                 ap.isnumeric = 1;
2211                 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2212                 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2213                 ap.a_mask.ss_family = res->ai_family;
2214                 if (res->ai_family == AF_INET) {
2215                         ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2216                         maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2217                         addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2218                         if (masklen < 0) {
2219                                 /* use default netmask */
2220                                 if (IN_CLASSA(ntohl(addrp->s_addr)))
2221                                         maskp->s_addr = htonl(IN_CLASSA_NET);
2222                                 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2223                                         maskp->s_addr = htonl(IN_CLASSB_NET);
2224                                 else
2225                                         maskp->s_addr = htonl(IN_CLASSC_NET);
2226                         } else if (masklen <= 32) {
2227                                 /* convert masklen to netmask */
2228                                 if (masklen == 0)
2229                                         maskp->s_addr = 0;
2230                                 else
2231                                         maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2232                         } else {
2233                                 freeaddrinfo(res);
2234                                 return (-1);
2235                         }
2236                         /* Lose any host bits in the network number. */
2237                         addrp->s_addr &= maskp->s_addr;
2238                 }
2239 #ifdef INET6
2240                 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2241                         ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2242                         if (masklen < 0)
2243                                 masklen = 128;
2244                         mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2245                         /* convert masklen to netmask */
2246                         while (masklen > 0) {
2247                                 if (masklen < 32) {
2248                                         *mask6p = htonl(~(0xffffffff >> masklen));
2249                                         break;
2250                                 }
2251                                 *mask6p++ = 0xffffffff;
2252                                 masklen -= 32;
2253                         }
2254                         /* Lose any host bits in the network number. */
2255                         mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2256                         addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2257                         for (i = 0; i < 4; i++)
2258                                 addr6p[i] &= mask6p[i];
2259                 }
2260 #endif
2261                 else {
2262                         freeaddrinfo(res);
2263                         return (-1);
2264                 }
2265                 freeaddrinfo(res);
2266         } else {
2267                 /* arg `s' is domain name */
2268                 ap.isnumeric = 0;
2269                 ap.a_name = s;
2270                 if (cp1)
2271                         *cp1 = '/';
2272 #ifdef INET6
2273                 if (cp2) {
2274                         *cp2 = ']';
2275                         --s;
2276                 }
2277 #endif
2278         }
2279
2280         if (Debug) {
2281                 printf("allowaddr: rule %d: ", NumAllowed);
2282                 if (ap.isnumeric) {
2283                         printf("numeric, ");
2284                         getnameinfo((struct sockaddr *)&ap.a_addr,
2285                                     ((struct sockaddr *)&ap.a_addr)->sa_len,
2286                                     ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2287                         printf("addr = %s, ", ip);
2288                         getnameinfo((struct sockaddr *)&ap.a_mask,
2289                                     ((struct sockaddr *)&ap.a_mask)->sa_len,
2290                                     ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2291                         printf("mask = %s; ", ip);
2292                 } else {
2293                         printf("domainname = %s; ", ap.a_name);
2294                 }
2295                 printf("port = %d\n", ap.port);
2296         }
2297
2298         if ((AllowedPeers = realloc(AllowedPeers,
2299                                     ++NumAllowed * sizeof(struct allowedpeer)))
2300             == NULL) {
2301                 logerror("realloc");
2302                 exit(1);
2303         }
2304         memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2305         return (0);
2306 }
2307
2308 /*
2309  * Validate that the remote peer has permission to log to us.
2310  */
2311 static int
2312 validate(struct sockaddr *sa, const char *hname)
2313 {
2314         int i, j, reject;
2315         size_t l1, l2;
2316         char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2317         struct allowedpeer *ap;
2318         struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2319         struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2320         struct addrinfo hints, *res;
2321         u_short sport;
2322
2323         if (NumAllowed == 0)
2324                 /* traditional behaviour, allow everything */
2325                 return (1);
2326
2327         (void)strlcpy(name, hname, sizeof(name));
2328         memset(&hints, 0, sizeof(hints));
2329         hints.ai_family = PF_UNSPEC;
2330         hints.ai_socktype = SOCK_DGRAM;
2331         hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2332         if (getaddrinfo(name, NULL, &hints, &res) == 0)
2333                 freeaddrinfo(res);
2334         else if (strchr(name, '.') == NULL) {
2335                 strlcat(name, ".", sizeof name);
2336                 strlcat(name, LocalDomain, sizeof name);
2337         }
2338         if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2339                         NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2340                 return (0);     /* for safety, should not occur */
2341         dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2342                 ip, port, name);
2343         sport = atoi(port);
2344
2345         /* now, walk down the list */
2346         for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2347                 if (ap->port != 0 && ap->port != sport) {
2348                         dprintf("rejected in rule %d due to port mismatch.\n", i);
2349                         continue;
2350                 }
2351
2352                 if (ap->isnumeric) {
2353                         if (ap->a_addr.ss_family != sa->sa_family) {
2354                                 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2355                                 continue;
2356                         }
2357                         if (ap->a_addr.ss_family == AF_INET) {
2358                                 sin4 = (struct sockaddr_in *)sa;
2359                                 a4p = (struct sockaddr_in *)&ap->a_addr;
2360                                 m4p = (struct sockaddr_in *)&ap->a_mask;
2361                                 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2362                                     != a4p->sin_addr.s_addr) {
2363                                         dprintf("rejected in rule %d due to IP mismatch.\n", i);
2364                                         continue;
2365                                 }
2366                         }
2367 #ifdef INET6
2368                         else if (ap->a_addr.ss_family == AF_INET6) {
2369                                 sin6 = (struct sockaddr_in6 *)sa;
2370                                 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2371                                 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2372                                 if (a6p->sin6_scope_id != 0 &&
2373                                     sin6->sin6_scope_id != a6p->sin6_scope_id) {
2374                                         dprintf("rejected in rule %d due to scope mismatch.\n", i);
2375                                         continue;
2376                                 }
2377                                 reject = 0;
2378                                 for (j = 0; j < 16; j += 4) {
2379                                         if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2380                                             != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2381                                                 ++reject;
2382                                                 break;
2383                                         }
2384                                 }
2385                                 if (reject) {
2386                                         dprintf("rejected in rule %d due to IP mismatch.\n", i);
2387                                         continue;
2388                                 }
2389                         }
2390 #endif
2391                         else
2392                                 continue;
2393                 } else {
2394                         cp = ap->a_name;
2395                         l1 = strlen(name);
2396                         if (*cp == '*') {
2397                                 /* allow wildmatch */
2398                                 cp++;
2399                                 l2 = strlen(cp);
2400                                 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2401                                         dprintf("rejected in rule %d due to name mismatch.\n", i);
2402                                         continue;
2403                                 }
2404                         } else {
2405                                 /* exact match */
2406                                 l2 = strlen(cp);
2407                                 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2408                                         dprintf("rejected in rule %d due to name mismatch.\n", i);
2409                                         continue;
2410                                 }
2411                         }
2412                 }
2413                 dprintf("accepted in rule %d.\n", i);
2414                 return (1);     /* hooray! */
2415         }
2416         return (0);
2417 }
2418
2419 /*
2420  * Fairly similar to popen(3), but returns an open descriptor, as
2421  * opposed to a FILE *.
2422  */
2423 static int
2424 p_open(const char *prog, pid_t *rpid)
2425 {
2426         int pfd[2], nulldesc, i;
2427         pid_t pid;
2428         sigset_t omask, mask;
2429         char *argv[4]; /* sh -c cmd NULL */
2430         char errmsg[200];
2431
2432         if (pipe(pfd) == -1)
2433                 return (-1);
2434         if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2435                 /* we are royally screwed anyway */
2436                 return (-1);
2437
2438         sigemptyset(&mask);
2439         sigaddset(&mask, SIGALRM);
2440         sigaddset(&mask, SIGHUP);
2441         sigprocmask(SIG_BLOCK, &mask, &omask);
2442         switch ((pid = fork())) {
2443         case -1:
2444                 sigprocmask(SIG_SETMASK, &omask, 0);
2445                 close(nulldesc);
2446                 return (-1);
2447
2448         case 0:
2449                 argv[0] = strdup("sh");
2450                 argv[1] = strdup("-c");
2451                 argv[2] = strdup(prog);
2452                 argv[3] = NULL;
2453                 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2454                         logerror("strdup");
2455                         exit(1);
2456                 }
2457
2458                 alarm(0);
2459                 (void)setsid(); /* Avoid catching SIGHUPs. */
2460
2461                 /*
2462                  * Throw away pending signals, and reset signal
2463                  * behaviour to standard values.
2464                  */
2465                 signal(SIGALRM, SIG_IGN);
2466                 signal(SIGHUP, SIG_IGN);
2467                 sigprocmask(SIG_SETMASK, &omask, 0);
2468                 signal(SIGPIPE, SIG_DFL);
2469                 signal(SIGQUIT, SIG_DFL);
2470                 signal(SIGALRM, SIG_DFL);
2471                 signal(SIGHUP, SIG_DFL);
2472
2473                 dup2(pfd[0], STDIN_FILENO);
2474                 dup2(nulldesc, STDOUT_FILENO);
2475                 dup2(nulldesc, STDERR_FILENO);
2476                 for (i = getdtablesize(); i > 2; i--)
2477                         (void)close(i);
2478
2479                 (void)execvp(_PATH_BSHELL, argv);
2480                 _exit(255);
2481         }
2482
2483         sigprocmask(SIG_SETMASK, &omask, 0);
2484         close(nulldesc);
2485         close(pfd[0]);
2486         /*
2487          * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2488          * supposed to get an EWOULDBLOCK on writev(2), which is
2489          * caught by the logic above anyway, which will in turn close
2490          * the pipe, and fork a new logging subprocess if necessary.
2491          * The stale subprocess will be killed some time later unless
2492          * it terminated itself due to closing its input pipe (so we
2493          * get rid of really dead puppies).
2494          */
2495         if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2496                 /* This is bad. */
2497                 (void)snprintf(errmsg, sizeof errmsg,
2498                                "Warning: cannot change pipe to PID %d to "
2499                                "non-blocking behaviour.",
2500                                (int)pid);
2501                 logerror(errmsg);
2502         }
2503         *rpid = pid;
2504         return (pfd[1]);
2505 }
2506
2507 static void
2508 deadq_enter(pid_t pid, const char *name)
2509 {
2510         dq_t p;
2511         int status;
2512
2513         /*
2514          * Be paranoid, if we can't signal the process, don't enter it
2515          * into the dead queue (perhaps it's already dead).  If possible,
2516          * we try to fetch and log the child's status.
2517          */
2518         if (kill(pid, 0) != 0) {
2519                 if (waitpid(pid, &status, WNOHANG) > 0)
2520                         log_deadchild(pid, status, name);
2521                 return;
2522         }
2523
2524         p = malloc(sizeof(struct deadq_entry));
2525         if (p == NULL) {
2526                 logerror("malloc");
2527                 exit(1);
2528         }
2529
2530         p->dq_pid = pid;
2531         p->dq_timeout = DQ_TIMO_INIT;
2532         TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2533 }
2534
2535 static int
2536 deadq_remove(pid_t pid)
2537 {
2538         dq_t q;
2539
2540         TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2541                 if (q->dq_pid == pid) {
2542                         TAILQ_REMOVE(&deadq_head, q, dq_entries);
2543                                 free(q);
2544                                 return (1);
2545                 }
2546         }
2547
2548         return (0);
2549 }
2550
2551 static void
2552 log_deadchild(pid_t pid, int status, const char *name)
2553 {
2554         int code;
2555         char buf[256];
2556         const char *reason;
2557
2558         errno = 0; /* Keep strerror() stuff out of logerror messages. */
2559         if (WIFSIGNALED(status)) {
2560                 reason = "due to signal";
2561                 code = WTERMSIG(status);
2562         } else {
2563                 reason = "with status";
2564                 code = WEXITSTATUS(status);
2565                 if (code == 0)
2566                         return;
2567         }
2568         (void)snprintf(buf, sizeof buf,
2569                        "Logging subprocess %d (%s) exited %s %d.",
2570                        pid, name, reason, code);
2571         logerror(buf);
2572 }
2573
2574 static int *
2575 socksetup(int af, const char *bindhostname)
2576 {
2577         struct addrinfo hints, *res, *r;
2578         int error, maxs, *s, *socks;
2579
2580         memset(&hints, 0, sizeof(hints));
2581         hints.ai_flags = AI_PASSIVE;
2582         hints.ai_family = af;
2583         hints.ai_socktype = SOCK_DGRAM;
2584         error = getaddrinfo(bindhostname, "syslog", &hints, &res);
2585         if (error) {
2586                 logerror(gai_strerror(error));
2587                 errno = 0;
2588                 die(0);
2589         }
2590
2591         /* Count max number of sockets we may open */
2592         for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2593         socks = malloc((maxs+1) * sizeof(int));
2594         if (socks == NULL) {
2595                 logerror("couldn't allocate memory for sockets");
2596                 die(0);
2597         }
2598
2599         *socks = 0;   /* num of sockets counter at start of array */
2600         s = socks + 1;
2601         for (r = res; r; r = r->ai_next) {
2602                 int on = 1;
2603                 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2604                 if (*s < 0) {
2605                         logerror("socket");
2606                         continue;
2607                 }
2608                 if (r->ai_family == AF_INET6) {
2609                         if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2610                                        (char *)&on, sizeof (on)) < 0) {
2611                                 logerror("setsockopt");
2612                                 close(*s);
2613                                 continue;
2614                         }
2615                 }
2616                 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2617                                (char *)&on, sizeof (on)) < 0) {
2618                         logerror("setsockopt");
2619                         close(*s);
2620                         continue;
2621                 }
2622                 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2623                         close(*s);
2624                         logerror("bind");
2625                         continue;
2626                 }
2627
2628                 double_rbuf(*s);
2629
2630                 (*socks)++;
2631                 s++;
2632         }
2633
2634         if (*socks == 0) {
2635                 free(socks);
2636                 if (Debug)
2637                         return (NULL);
2638                 else
2639                         die(0);
2640         }
2641         if (res)
2642                 freeaddrinfo(res);
2643
2644         return (socks);
2645 }
2646
2647 static void
2648 double_rbuf(int fd)
2649 {
2650         socklen_t slen, len;
2651
2652         if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2653                 len *= 2;
2654                 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen);
2655         }
2656 }