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