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