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