syslogd.c revision 1.144 1 /* $NetBSD: syslogd.c,v 1.144 2024/08/21 17:13:24 gutteridge Exp $ */
2
3 /*
4 * Copyright (c) 1983, 1988, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993, 1994\
35 The Regents of the University of California. All rights reserved.");
36 #endif /* not lint */
37
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
41 #else
42 __RCSID("$NetBSD: syslogd.c,v 1.144 2024/08/21 17:13:24 gutteridge Exp $");
43 #endif
44 #endif /* not lint */
45
46 /*
47 * syslogd -- log system messages
48 *
49 * This program implements a system log. It takes a series of lines.
50 * Each line may have a priority, signified as "<n>" as
51 * the first characters of the line. If this is
52 * not present, a default priority is used.
53 *
54 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
55 * cause it to reread its configuration file.
56 *
57 * Defined Constants:
58 *
59 * MAXLINE -- the maximimum line length that can be handled.
60 * DEFUPRI -- the default priority for user messages
61 * DEFSPRI -- the default priority for kernel messages
62 *
63 * Author: Eric Allman
64 * extensive changes by Ralph Campbell
65 * more extensive changes by Eric Allman (again)
66 * Extension to log by program name as well as facility and priority
67 * by Peter da Silva.
68 * -U and -v by Harlan Stenn.
69 * Priority comparison code by Harlan Stenn.
70 * TLS, syslog-protocol, and syslog-sign code by Martin Schuette.
71 */
72 #define SYSLOG_NAMES
73 #include <sys/stat.h>
74 #include <poll.h>
75 #include "syslogd.h"
76 #include "extern.h"
77
78 #ifndef DISABLE_SIGN
79 #include "sign.h"
80 struct sign_global_t GlobalSign = {
81 .rsid = 0,
82 .sig2_delims = STAILQ_HEAD_INITIALIZER(GlobalSign.sig2_delims)
83 };
84 #endif /* !DISABLE_SIGN */
85
86 #ifndef DISABLE_TLS
87 #include "tls.h"
88 #endif /* !DISABLE_TLS */
89
90 #ifdef LIBWRAP
91 int allow_severity = LOG_AUTH|LOG_INFO;
92 int deny_severity = LOG_AUTH|LOG_WARNING;
93 #endif
94
95 const char *ConfFile = _PATH_LOGCONF;
96 char ctty[] = _PATH_CONSOLE;
97
98 /*
99 * Queue of about-to-be-dead processes we should watch out for.
100 */
101 TAILQ_HEAD(, deadq_entry) deadq_head = TAILQ_HEAD_INITIALIZER(deadq_head);
102
103 typedef struct deadq_entry {
104 pid_t dq_pid;
105 int dq_timeout;
106 TAILQ_ENTRY(deadq_entry) dq_entries;
107 } *dq_t;
108
109 /*
110 * The timeout to apply to processes waiting on the dead queue. Unit
111 * of measure is "mark intervals", i.e. 20 minutes by default.
112 * Processes on the dead queue will be terminated after that time.
113 */
114 #define DQ_TIMO_INIT 2
115
116 #define RCVBUFLEN 16384
117 int buflen = RCVBUFLEN;
118 /*
119 * Intervals at which we flush out "message repeated" messages,
120 * in seconds after previous message is logged. After each flush,
121 * we move to the next interval until we reach the largest.
122 */
123 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
124 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
125 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
126 #define BACKOFF(f) { if ((size_t)(++(f)->f_repeatcount) > MAXREPEAT) \
127 (f)->f_repeatcount = MAXREPEAT; \
128 }
129
130 /* values for f_type */
131 #define F_UNUSED 0 /* unused entry */
132 #define F_FILE 1 /* regular file */
133 #define F_TTY 2 /* terminal */
134 #define F_CONSOLE 3 /* console terminal */
135 #define F_FORW 4 /* remote machine */
136 #define F_USERS 5 /* list of users */
137 #define F_WALL 6 /* everyone logged on */
138 #define F_PIPE 7 /* pipe to program */
139 #define F_FIFO 8 /* mkfifo(2) file */
140 #define F_TLS 9
141
142 struct TypeInfo {
143 const char *name;
144 char *queue_length_string;
145 const char *default_length_string;
146 char *queue_size_string;
147 const char *default_size_string;
148 int64_t queue_length;
149 int64_t queue_size;
150 int max_msg_length;
151 } TypeInfo[] = {
152 /* numeric values are set in init()
153 * -1 in length/size or max_msg_length means infinite */
154 {"UNUSED", NULL, "0", NULL, "0", 0, 0, 0},
155 {"FILE", NULL, "1024", NULL, "1M", 0, 0, 16384},
156 {"TTY", NULL, "0", NULL, "0", 0, 0, 1024},
157 {"CONSOLE", NULL, "0", NULL, "0", 0, 0, 1024},
158 {"FORW", NULL, "0", NULL, "1M", 0, 0, 16384},
159 {"USERS", NULL, "0", NULL, "0", 0, 0, 1024},
160 {"WALL", NULL, "0", NULL, "0", 0, 0, 1024},
161 {"PIPE", NULL, "1024", NULL, "1M", 0, 0, 16384},
162 {"FIFO", NULL, "1024", NULL, "1M", 0, 0, 16384},
163 #ifndef DISABLE_TLS
164 {"TLS", NULL, "-1", NULL, "16M", 0, 0, 16384}
165 #endif /* !DISABLE_TLS */
166 };
167
168 struct filed *Files = NULL;
169 struct filed consfile;
170
171 time_t now;
172 int Debug = D_NONE; /* debug flag */
173 int daemonized = 0; /* we are not daemonized yet */
174 char *LocalFQDN = NULL; /* our FQDN */
175 char *oldLocalFQDN = NULL; /* our previous FQDN */
176 char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
177 struct socketEvent *finet; /* Internet datagram sockets and events */
178 int *funix; /* Unix domain datagram sockets */
179 #ifndef DISABLE_TLS
180 struct socketEvent *TLS_Listen_Set; /* TLS/TCP sockets and events */
181 #endif /* !DISABLE_TLS */
182 int Initialized = 0; /* set when we have initialized ourselves */
183 int ShuttingDown; /* set when we die() */
184 int MarkInterval = 20 * 60; /* interval between marks in seconds */
185 int MarkSeq = 0; /* mark sequence number */
186 int SecureMode = 0; /* listen only on unix domain socks */
187 int UseNameService = 1; /* make domain name queries */
188 int NumForwards = 0; /* number of forwarding actions in conf file */
189 char **LogPaths; /* array of pathnames to read messages from */
190 int NoRepeat = 0; /* disable "repeated"; log always */
191 int RemoteAddDate = 0; /* always add date to messages from network */
192 int SyncKernel = 0; /* write kernel messages synchronously */
193 int UniquePriority = 0; /* only log specified priority */
194 int LogFacPri = 0; /* put facility and priority in log messages: */
195 /* 0=no, 1=numeric, 2=names */
196 int LogOverflow = 1; /* 0=no, any other value = yes */
197 bool BSDOutputFormat = true; /* if true emit traditional BSD Syslog lines,
198 * otherwise new syslog-protocol lines
199 *
200 * Open Issue: having a global flag is the
201 * easiest solution. If we get a more detailed
202 * config file this could/should be changed
203 * into a destination-specific flag.
204 * Most output code should be ready to handle
205 * this, it will only break some syslog-sign
206 * configurations (e.g. with SG="0").
207 */
208 bool KernXlat = true; /* translate kern.* -> user.* */
209 char appname[] = "syslogd";/* the APPNAME for own messages */
210 char *include_pid; /* include PID in own messages */
211 char include_pid_buf[11];
212
213
214 /* init and setup */
215 void usage(void) __attribute__((__noreturn__));
216 void set_debug(const char *);
217 void logpath_add(char ***, int *, int *, const char *);
218 void logpath_fileadd(char ***, int *, int *, const char *);
219 void init(int fd, short event, void *ev); /* SIGHUP kevent dispatch routine */
220 struct socketEvent*
221 socksetup(int, const char *);
222 int getmsgbufsize(void);
223 char *getLocalFQDN(void);
224 void trim_anydomain(char *);
225 /* pipe & subprocess handling */
226 int p_open(char *, pid_t *);
227 void deadq_enter(pid_t, const char *);
228 int deadq_remove(pid_t);
229 void log_deadchild(pid_t, int, const char *);
230 void reapchild(int fd, short event, void *ev); /* SIGCHLD kevent dispatch routine */
231 /* input message parsing & formatting */
232 const char *cvthname(struct sockaddr_storage *);
233 void printsys(char *);
234 struct buf_msg *printline_syslogprotocol(const char*, char*, int, int);
235 struct buf_msg *printline_bsdsyslog(const char*, char*, int, int);
236 struct buf_msg *printline_kernelprintf(const char*, char*, int, int);
237 size_t check_timestamp(unsigned char *, char **, bool, bool);
238 char *copy_utf8_ascii(char*, size_t);
239 uint_fast32_t get_utf8_value(const char*);
240 unsigned valid_utf8(const char *);
241 static unsigned check_sd(char*);
242 static unsigned check_msgid(char *);
243 /* event handling */
244 static void dispatch_read_klog(int fd, short event, void *ev);
245 static void dispatch_read_finet(int fd, short event, void *ev);
246 static void dispatch_read_funix(int fd, short event, void *ev);
247 static void domark(int fd, short event, void *ev); /* timer kevent dispatch routine */
248 /* log messages */
249 void logmsg_async(int, const char *, const char *, int);
250 void logmsg(struct buf_msg *);
251 int matches_spec(const char *, const char *,
252 char *(*)(const char *, const char *));
253 void udp_send(struct filed *, char *, size_t);
254 void wallmsg(struct filed *, struct iovec *, size_t);
255 /* buffer & queue functions */
256 size_t message_queue_purge(struct filed *f, size_t, int);
257 size_t message_allqueues_check(void);
258 static struct buf_queue *
259 find_qentry_to_delete(const struct buf_queue_head *, int, bool);
260 struct buf_queue *
261 message_queue_add(struct filed *, struct buf_msg *);
262 size_t buf_queue_obj_size(struct buf_queue*);
263 /* configuration & parsing */
264 void cfline(size_t, const char *, struct filed *, const char *,
265 const char *);
266 void read_config_file(FILE*, struct filed**);
267 void store_sign_delim_sg2(char*);
268 int decode(const char *, CODE *);
269 bool copy_config_value(const char *, char **, const char **,
270 const char *, int);
271 bool copy_config_value_word(char **, const char **);
272
273 /* config parsing */
274 #ifndef DISABLE_TLS
275 void free_cred_SLIST(struct peer_cred_head *);
276 static inline void
277 free_incoming_tls_sockets(void);
278 #endif /* !DISABLE_TLS */
279 static int writev1(int, struct iovec *, size_t);
280
281 static void setsockbuf(int, const char *);
282
283 /* for make_timestamp() */
284 char timestamp[MAX_TIMESTAMPLEN + 1];
285 /*
286 * Global line buffer. Since we only process one event at a time,
287 * a global one will do. But for klog, we use own buffer so that
288 * partial line at the end of buffer can be deferred.
289 */
290 char *linebuf, *klog_linebuf;
291 size_t linebufsize, klog_linebufoff;
292
293 static const char *bindhostname = NULL;
294
295 #ifndef DISABLE_TLS
296 struct TLS_Incoming TLS_Incoming_Head = \
297 SLIST_HEAD_INITIALIZER(TLS_Incoming_Head);
298 extern char *SSL_ERRCODE[];
299 struct tls_global_options_t tls_opt;
300 #endif /* !DISABLE_TLS */
301
302 int
303 main(int argc, char *argv[])
304 {
305 int ch, j, fklog;
306 int funixsize = 0, funixmaxsize = 0;
307 struct sockaddr_un sunx;
308 char **pp;
309 struct event *ev;
310 uid_t uid = 0;
311 gid_t gid = 0;
312 char *user = NULL;
313 char *group = NULL;
314 const char *root = "/";
315 char *endp;
316 struct group *gr;
317 struct passwd *pw;
318 unsigned long l;
319
320 /* should we set LC_TIME="C" to ensure correct timestamps&parsing? */
321 (void)setlocale(LC_ALL, "");
322
323 while ((ch = getopt(argc, argv, "b:B:d::knsSf:m:o:p:P:ru:g:t:TUvX")) != -1)
324 switch(ch) {
325 case 'b':
326 bindhostname = optarg;
327 break;
328 case 'B':
329 buflen = atoi(optarg);
330 if (buflen < RCVBUFLEN)
331 buflen = RCVBUFLEN;
332 break;
333 case 'd': /* debug */
334 if (optarg != NULL) {
335 /*
336 * getopt passes as optarg everything
337 * after 'd' in -darg, manually accept
338 * -d=arg too.
339 */
340 if (optarg[0] == '=')
341 ++optarg;
342 } else if (optind < argc) {
343 /*
344 * :: treats "-d ..." as missing
345 * optarg, so look ahead manually and
346 * pick up the next arg if it looks
347 * like one.
348 */
349 if (argv[optind][0] != '-') {
350 optarg = argv[optind];
351 ++optind;
352 }
353 }
354 set_debug(optarg);
355 break;
356 case 'f': /* configuration file */
357 ConfFile = optarg;
358 break;
359 case 'g':
360 group = optarg;
361 if (*group == '\0')
362 usage();
363 break;
364 case 'k': /* pass-through (remote) kern.* */
365 KernXlat = false;
366 break;
367 case 'm': /* mark interval */
368 MarkInterval = atoi(optarg) * 60;
369 break;
370 case 'n': /* turn off DNS queries */
371 UseNameService = 0;
372 break;
373 case 'o': /* message format */
374 #define EQ(a) (strncmp(optarg, # a, sizeof(# a) - 1) == 0)
375 if (EQ(bsd) || EQ(rfc3264))
376 BSDOutputFormat = true;
377 else if (EQ(syslog) || EQ(rfc5424))
378 BSDOutputFormat = false;
379 else
380 usage();
381 /* TODO: implement additional output option "osyslog"
382 * for old syslogd behaviour as introduced after
383 * FreeBSD PR#bin/7055.
384 */
385 break;
386 case 'p': /* path */
387 logpath_add(&LogPaths, &funixsize,
388 &funixmaxsize, optarg);
389 break;
390 case 'P': /* file of paths */
391 logpath_fileadd(&LogPaths, &funixsize,
392 &funixmaxsize, optarg);
393 break;
394 case 'r': /* disable "repeated" compression */
395 NoRepeat++;
396 break;
397 case 's': /* no network listen mode */
398 SecureMode++;
399 break;
400 case 'S':
401 SyncKernel = 1;
402 break;
403 case 't':
404 root = optarg;
405 if (*root == '\0')
406 usage();
407 break;
408 case 'T':
409 RemoteAddDate = 1;
410 break;
411 case 'u':
412 user = optarg;
413 if (*user == '\0')
414 usage();
415 break;
416 case 'U': /* only log specified priority */
417 UniquePriority = 1;
418 break;
419 case 'v': /* log facility and priority */
420 if (LogFacPri < 2)
421 LogFacPri++;
422 break;
423 case 'X':
424 LogOverflow = 0;
425 break;
426 default:
427 usage();
428 }
429 if ((argc -= optind) != 0)
430 usage();
431
432 setlinebuf(stdout);
433 tzset(); /* init TZ information for localtime. */
434
435 if (user != NULL) {
436 if (isdigit((unsigned char)*user)) {
437 errno = 0;
438 endp = NULL;
439 l = strtoul(user, &endp, 0);
440 if (errno || *endp != '\0')
441 goto getuser;
442 uid = (uid_t)l;
443 if (uid != l) {/* TODO: never executed */
444 errno = 0;
445 logerror("UID out of range");
446 die(0, 0, NULL);
447 }
448 } else {
449 getuser:
450 if ((pw = getpwnam(user)) != NULL) {
451 uid = pw->pw_uid;
452 } else {
453 errno = 0;
454 logerror("Cannot find user `%s'", user);
455 die(0, 0, NULL);
456 }
457 }
458 }
459
460 if (group != NULL) {
461 if (isdigit((unsigned char)*group)) {
462 errno = 0;
463 endp = NULL;
464 l = strtoul(group, &endp, 0);
465 if (errno || *endp != '\0')
466 goto getgroup;
467 gid = (gid_t)l;
468 if (gid != l) {/* TODO: never executed */
469 errno = 0;
470 logerror("GID out of range");
471 die(0, 0, NULL);
472 }
473 } else {
474 getgroup:
475 if ((gr = getgrnam(group)) != NULL) {
476 gid = gr->gr_gid;
477 } else {
478 errno = 0;
479 logerror("Cannot find group `%s'", group);
480 die(0, 0, NULL);
481 }
482 }
483 }
484
485 if (access(root, F_OK | R_OK)) {
486 logerror("Cannot access `%s'", root);
487 die(0, 0, NULL);
488 }
489
490 consfile.f_type = F_CONSOLE;
491 (void)strlcpy(consfile.f_un.f_fname, ctty,
492 sizeof(consfile.f_un.f_fname));
493 linebufsize = getmsgbufsize();
494 if (linebufsize < MAXLINE)
495 linebufsize = MAXLINE;
496 linebufsize++;
497
498 if (!(linebuf = malloc(linebufsize))) {
499 logerror("Couldn't allocate buffer");
500 die(0, 0, NULL);
501 }
502 if (!(klog_linebuf = malloc(linebufsize))) {
503 logerror("Couldn't allocate buffer for klog");
504 die(0, 0, NULL);
505 }
506
507
508 #ifndef SUN_LEN
509 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
510 #endif
511 if (funixsize == 0)
512 logpath_add(&LogPaths, &funixsize,
513 &funixmaxsize, _PATH_LOG);
514 funix = malloc(sizeof(*funix) * funixsize);
515 if (funix == NULL) {
516 logerror("Couldn't allocate funix descriptors");
517 die(0, 0, NULL);
518 }
519 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
520 DPRINTF(D_NET, "Making unix dgram socket `%s'\n", *pp);
521 unlink(*pp);
522 memset(&sunx, 0, sizeof(sunx));
523 sunx.sun_family = AF_LOCAL;
524 (void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
525 funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
526 if (funix[j] < 0 || bind(funix[j],
527 (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
528 chmod(*pp, 0666) < 0) {
529 logerror("Cannot create `%s'", *pp);
530 die(0, 0, NULL);
531 }
532 setsockbuf(funix[j], *pp);
533 DPRINTF(D_NET, "Listening on unix dgram socket `%s'\n", *pp);
534 }
535
536 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
537 DPRINTF(D_FILE, "Can't open `%s' (%d)\n", _PATH_KLOG, errno);
538 } else {
539 DPRINTF(D_FILE, "Listening on kernel log `%s' with fd %d\n",
540 _PATH_KLOG, fklog);
541 }
542
543 #if (!defined(DISABLE_TLS) && !defined(DISABLE_SIGN))
544 /* basic OpenSSL init */
545 SSL_load_error_strings();
546 (void) SSL_library_init();
547 OpenSSL_add_all_digests();
548 /* OpenSSL PRNG needs /dev/urandom, thus initialize before chroot() */
549 if (!RAND_status()) {
550 errno = 0;
551 logerror("Unable to initialize OpenSSL PRNG");
552 } else {
553 DPRINTF(D_TLS, "Initializing PRNG\n");
554 }
555 #endif /* (!defined(DISABLE_TLS) && !defined(DISABLE_SIGN)) */
556 #ifndef DISABLE_SIGN
557 /* initialize rsid -- we will use that later to determine
558 * whether sign_global_init() was already called */
559 GlobalSign.rsid = 0;
560 #endif /* !DISABLE_SIGN */
561 #if (IETF_NUM_PRIVALUES != (LOG_NFACILITIES<<3))
562 logerror("Warning: system defines %d priority values, but "
563 "syslog-protocol/syslog-sign specify %d values",
564 LOG_NFACILITIES, IETF_NUM_PRIVALUES>>3);
565 #endif
566
567 /*
568 * All files are open, we can drop privileges and chroot
569 */
570 DPRINTF(D_MISC, "Attempt to chroot to `%s'\n", root);
571 if (chroot(root) == -1) {
572 logerror("Failed to chroot to `%s'", root);
573 die(0, 0, NULL);
574 }
575 DPRINTF(D_MISC, "Attempt to set GID/EGID to `%d'\n", gid);
576 if (setgid(gid) || setegid(gid)) {
577 logerror("Failed to set gid to `%d'", gid);
578 die(0, 0, NULL);
579 }
580 DPRINTF(D_MISC, "Attempt to set UID/EUID to `%d'\n", uid);
581 if (setuid(uid) || seteuid(uid)) {
582 logerror("Failed to set uid to `%d'", uid);
583 die(0, 0, NULL);
584 }
585 /*
586 * We cannot detach from the terminal before we are sure we won't
587 * have a fatal error, because error message would not go to the
588 * terminal and would not be logged because syslogd dies.
589 * All die() calls are behind us, we can call daemon()
590 */
591 if (!Debug) {
592 (void)daemon(0, 0);
593 daemonized = 1;
594 /* tuck my process id away, if i'm not in debug mode */
595 #ifdef __NetBSD_Version__
596 pidfile(NULL);
597 #endif /* __NetBSD_Version__ */
598 }
599
600 include_pid = include_pid_buf;
601 snprintf(include_pid_buf, sizeof(include_pid_buf), "%d", getpid());
602
603 /*
604 * Create the global kernel event descriptor.
605 *
606 * NOTE: We MUST do this after daemon(), because the kqueue()
607 * API dictates that kqueue descriptors are not inherited
608 * across forks (lame!).
609 */
610 (void)event_init();
611
612 /*
613 * We must read the configuration file for the first time
614 * after the kqueue descriptor is created, because we install
615 * events during this process.
616 */
617 init(0, 0, NULL);
618
619 /*
620 * Always exit on SIGTERM. Also exit on SIGINT and SIGQUIT
621 * if we're debugging.
622 */
623 (void)signal(SIGTERM, SIG_IGN);
624 (void)signal(SIGINT, SIG_IGN);
625 (void)signal(SIGQUIT, SIG_IGN);
626
627 ev = allocev();
628 signal_set(ev, SIGTERM, die, ev);
629 EVENT_ADD(ev);
630
631 if (Debug) {
632 ev = allocev();
633 signal_set(ev, SIGINT, die, ev);
634 EVENT_ADD(ev);
635 ev = allocev();
636 signal_set(ev, SIGQUIT, die, ev);
637 EVENT_ADD(ev);
638 }
639
640 ev = allocev();
641 signal_set(ev, SIGCHLD, reapchild, ev);
642 EVENT_ADD(ev);
643
644 ev = allocev();
645 schedule_event(&ev,
646 &((struct timeval){TIMERINTVL, 0}),
647 domark, ev);
648
649 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
650
651 /* Re-read configuration on SIGHUP. */
652 (void) signal(SIGHUP, SIG_IGN);
653 ev = allocev();
654 signal_set(ev, SIGHUP, init, ev);
655 EVENT_ADD(ev);
656
657 #ifndef DISABLE_TLS
658 ev = allocev();
659 signal_set(ev, SIGUSR1, dispatch_force_tls_reconnect, ev);
660 EVENT_ADD(ev);
661 #endif /* !DISABLE_TLS */
662
663 if (fklog >= 0) {
664 ev = allocev();
665 DPRINTF(D_EVENT,
666 "register klog for fd %d with ev@%p\n", fklog, ev);
667 event_set(ev, fklog, EV_READ | EV_PERSIST,
668 dispatch_read_klog, ev);
669 EVENT_ADD(ev);
670 }
671 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
672 ev = allocev();
673 event_set(ev, funix[j], EV_READ | EV_PERSIST,
674 dispatch_read_funix, ev);
675 EVENT_ADD(ev);
676 }
677
678 DPRINTF(D_MISC, "Off & running....\n");
679
680 j = event_dispatch();
681 /* normal termination via die(), reaching this is an error */
682 DPRINTF(D_MISC, "event_dispatch() returned %d\n", j);
683 die(0, 0, NULL);
684 /*NOTREACHED*/
685 return 0;
686 }
687
688 void
689 usage(void)
690 {
691
692 (void)fprintf(stderr,
693 "usage: %s [-dknrSsTUvX] [-B buffer_length] [-b bind_address]\n"
694 "\t[-f config_file] [-g group]\n"
695 "\t[-m mark_interval] [-P file_list] [-p log_socket\n"
696 "\t[-p log_socket2 ...]] [-t chroot_dir] [-u user]\n",
697 getprogname());
698 exit(1);
699 }
700
701 static void
702 setsockbuf(int fd, const char *name)
703 {
704 int curbuflen;
705 socklen_t socklen = sizeof(buflen);
706
707 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &curbuflen, &socklen) == -1) {
708 logerror("getsockopt: SO_RCVBUF: `%s'", name);
709 return;
710 }
711 if (curbuflen >= buflen)
712 return;
713 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buflen, socklen) == -1) {
714 logerror("setsockopt: SO_RCVBUF: `%s'", name);
715 return;
716 }
717 }
718
719 /*
720 * Dispatch routine for reading /dev/klog
721 *
722 * Note: slightly different semantic in dispatch_read functions:
723 * - read_klog() might give multiple messages in linebuf and
724 * leaves the task of splitting them to printsys()
725 * - all other read functions receive one message and
726 * then call printline() with one buffer.
727 */
728 static void
729 dispatch_read_klog(int fd, short event, void *ev)
730 {
731 ssize_t rv;
732 size_t resid = linebufsize - klog_linebufoff;
733
734 DPRINTF((D_CALL|D_EVENT), "Kernel log active (%d, %d, %p)"
735 " with linebuf@%p, length %zu)\n", fd, event, ev,
736 klog_linebuf, linebufsize);
737
738 rv = read(fd, &klog_linebuf[klog_linebufoff], resid - 1);
739 if (rv > 0) {
740 klog_linebuf[klog_linebufoff + rv] = '\0';
741 printsys(klog_linebuf);
742 } else if (rv < 0 &&
743 errno != EINTR &&
744 (errno != ENOBUFS || LogOverflow))
745 {
746 /*
747 * /dev/klog has croaked. Disable the event
748 * so it won't bother us again.
749 */
750 logerror("klog failed");
751 event_del(ev);
752 }
753 }
754
755 /*
756 * Dispatch routine for reading Unix domain sockets.
757 */
758 static void
759 dispatch_read_funix(int fd, short event, void *ev)
760 {
761 struct sockaddr_un myname, fromunix;
762 ssize_t rv;
763 socklen_t sunlen;
764
765 sunlen = sizeof(myname);
766 if (getsockname(fd, (struct sockaddr *)&myname, &sunlen) != 0) {
767 /*
768 * This should never happen, so ensure that it doesn't
769 * happen again.
770 */
771 logerror("getsockname() unix failed");
772 event_del(ev);
773 return;
774 }
775
776 #define SUN_PATHLEN(su) \
777 ((su)->sun_len - (sizeof(*(su)) - sizeof((su)->sun_path)))
778
779 DPRINTF((D_CALL|D_EVENT|D_NET), "Unix socket (%.*s) active (%d, %d %p)"
780 " with linebuf@%p, size %zu)\n", (int)SUN_PATHLEN(&myname),
781 myname.sun_path, fd, event, ev, linebuf, linebufsize-1);
782
783 sunlen = sizeof(fromunix);
784 rv = recvfrom(fd, linebuf, linebufsize-1, 0,
785 (struct sockaddr *)&fromunix, &sunlen);
786 if (rv > 0) {
787 linebuf[rv] = '\0';
788 printline(LocalFQDN, linebuf, 0);
789 } else if (rv < 0 &&
790 errno != EINTR &&
791 (errno != ENOBUFS || LogOverflow))
792 {
793 logerror("recvfrom() unix `%.*s'",
794 (int)SUN_PATHLEN(&myname), myname.sun_path);
795 }
796 }
797
798 /*
799 * Dispatch routine for reading Internet sockets.
800 */
801 static void
802 dispatch_read_finet(int fd, short event, void *ev)
803 {
804 #ifdef LIBWRAP
805 struct request_info req;
806 #endif
807 struct sockaddr_storage frominet;
808 ssize_t rv;
809 socklen_t len;
810 int reject = 0;
811
812 DPRINTF((D_CALL|D_EVENT|D_NET), "inet socket active (%d, %d %p) "
813 " with linebuf@%p, size %zu)\n",
814 fd, event, ev, linebuf, linebufsize-1);
815
816 #ifdef LIBWRAP
817 request_init(&req, RQ_DAEMON, appname, RQ_FILE, fd, NULL);
818 fromhost(&req);
819 reject = !hosts_access(&req);
820 if (reject)
821 DPRINTF(D_NET, "access denied\n");
822 #endif
823
824 len = sizeof(frominet);
825 rv = recvfrom(fd, linebuf, linebufsize-1, 0,
826 (struct sockaddr *)&frominet, &len);
827 if (rv == 0 ||
828 (rv < 0 && (errno == EINTR ||
829 (errno == ENOBUFS && LogOverflow == 0))))
830 return;
831 else if (rv < 0) {
832 logerror("recvfrom inet");
833 return;
834 }
835
836 linebuf[rv] = '\0';
837 if (!reject)
838 printline(cvthname(&frominet), linebuf,
839 RemoteAddDate ? ADDDATE : 0);
840 }
841
842 /*
843 * given a pointer to an array of char *'s, a pointer to its current
844 * size and current allocated max size, and a new char * to add, add
845 * it, update everything as necessary, possibly allocating a new array
846 */
847 void
848 logpath_add(char ***lp, int *szp, int *maxszp, const char *new)
849 {
850 char **nlp;
851 int newmaxsz;
852
853 DPRINTF(D_FILE, "Adding `%s' to the %p logpath list\n", new, *lp);
854 if (*szp == *maxszp) {
855 if (*maxszp == 0) {
856 newmaxsz = 4; /* start of with enough for now */
857 *lp = NULL;
858 } else
859 newmaxsz = *maxszp * 2;
860 nlp = realloc(*lp, sizeof(char *) * (newmaxsz + 1));
861 if (nlp == NULL) {
862 logerror("Couldn't allocate line buffer");
863 die(0, 0, NULL);
864 }
865 *lp = nlp;
866 *maxszp = newmaxsz;
867 }
868 if (((*lp)[(*szp)++] = strdup(new)) == NULL) {
869 logerror("Couldn't allocate logpath");
870 die(0, 0, NULL);
871 }
872 (*lp)[(*szp)] = NULL; /* always keep it NULL terminated */
873 }
874
875 /* do a file of log sockets */
876 void
877 logpath_fileadd(char ***lp, int *szp, int *maxszp, const char *file)
878 {
879 FILE *fp;
880 char *line;
881 size_t len;
882
883 fp = fopen(file, "r");
884 if (fp == NULL) {
885 logerror("Could not open socket file list `%s'", file);
886 die(0, 0, NULL);
887 }
888
889 while ((line = fgetln(fp, &len)) != NULL) {
890 line[len - 1] = 0;
891 logpath_add(lp, szp, maxszp, line);
892 }
893 fclose(fp);
894 }
895
896 /*
897 * checks UTF-8 codepoint
898 * returns either its length in bytes or 0 if *input is invalid
899 */
900 unsigned
901 valid_utf8(const char *c) {
902 unsigned rc, nb;
903
904 /* first byte gives sequence length */
905 if ((*c & 0x80) == 0x00) return 1; /* 0bbbbbbb -- ASCII */
906 else if ((*c & 0xc0) == 0x80) return 0; /* 10bbbbbb -- trailing byte */
907 else if ((*c & 0xe0) == 0xc0) nb = 2; /* 110bbbbb */
908 else if ((*c & 0xf0) == 0xe0) nb = 3; /* 1110bbbb */
909 else if ((*c & 0xf8) == 0xf0) nb = 4; /* 11110bbb */
910 else return 0; /* UTF-8 allows only up to 4 bytes */
911
912 /* catch overlong encodings */
913 if ((*c & 0xfe) == 0xc0)
914 return 0; /* 1100000b ... */
915 else if (((*c & 0xff) == 0xe0) && ((*(c+1) & 0xe0) == 0x80))
916 return 0; /* 11100000 100bbbbb ... */
917 else if (((*c & 0xff) == 0xf0) && ((*(c+1) & 0xf0) == 0x80))
918 return 0; /* 11110000 1000bbbb ... ... */
919
920 /* and also filter UTF-16 surrogates (=invalid in UTF-8) */
921 if (((*c & 0xff) == 0xed) && ((*(c+1) & 0xe0) == 0xa0))
922 return 0; /* 11101101 101bbbbb ... */
923
924 rc = nb;
925 /* check trailing bytes */
926 switch (nb) {
927 default: return 0;
928 case 4: if ((*(c+3) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
929 case 3: if ((*(c+2) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
930 case 2: if ((*(c+1) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
931 }
932 return rc;
933 }
934 #define UTF8CHARMAX 4
935
936 /*
937 * read UTF-8 value
938 * returns a the codepoint number
939 */
940 uint_fast32_t
941 get_utf8_value(const char *c) {
942 uint_fast32_t sum;
943 unsigned nb, i;
944
945 /* first byte gives sequence length */
946 if ((*c & 0x80) == 0x00) return *c;/* 0bbbbbbb -- ASCII */
947 else if ((*c & 0xc0) == 0x80) return 0; /* 10bbbbbb -- trailing byte */
948 else if ((*c & 0xe0) == 0xc0) { /* 110bbbbb */
949 nb = 2;
950 sum = (*c & ~0xe0) & 0xff;
951 } else if ((*c & 0xf0) == 0xe0) { /* 1110bbbb */
952 nb = 3;
953 sum = (*c & ~0xf0) & 0xff;
954 } else if ((*c & 0xf8) == 0xf0) { /* 11110bbb */
955 nb = 4;
956 sum = (*c & ~0xf8) & 0xff;
957 } else return 0; /* UTF-8 allows only up to 4 bytes */
958
959 /* check trailing bytes -- 10bbbbbb */
960 i = 1;
961 while (i < nb) {
962 sum <<= 6;
963 sum |= ((*(c+i) & ~0xc0) & 0xff);
964 i++;
965 }
966 return sum;
967 }
968
969 /* note previous versions transscribe
970 * control characters, e.g. \007 --> "^G"
971 * did anyone rely on that?
972 *
973 * this new version works on only one buffer and
974 * replaces control characters with a space
975 */
976 #define NEXTFIELD(ptr) if (*(p) == ' ') (p)++; /* SP */ \
977 else { \
978 DPRINTF(D_DATA, "format error\n"); \
979 if (*(p) == '\0') start = (p); \
980 goto all_syslog_msg; \
981 }
982 #define FORCE2ASCII(c) ((iscntrl((unsigned char)(c)) && (c) != '\t') \
983 ? ((c) == '\n' ? ' ' : '?') \
984 : (c) & 0177)
985
986 /* following syslog-protocol */
987 #define printusascii(ch) (ch >= 33 && ch <= 126)
988 #define sdname(ch) (ch != '=' && ch != ' ' \
989 && ch != ']' && ch != '"' \
990 && printusascii(ch))
991
992 /* checks whether the first word of string p can be interpreted as
993 * a syslog-protocol MSGID and if so returns its length.
994 *
995 * otherwise returns 0
996 */
997 static unsigned
998 check_msgid(char *p)
999 {
1000 char *q = p;
1001
1002 /* consider the NILVALUE to be valid */
1003 if (*q == '-' && *(q+1) == ' ')
1004 return 1;
1005
1006 for (;;) {
1007 if (*q == ' ')
1008 return q - p;
1009 else if (*q == '\0' || !printusascii(*q) || q - p >= MSGID_MAX)
1010 return 0;
1011 else
1012 q++;
1013 }
1014 }
1015
1016 /*
1017 * returns number of chars found in SD at beginning of string p
1018 * thus returns 0 if no valid SD is found
1019 *
1020 * if ascii == true then substitute all non-ASCII chars
1021 * otherwise use syslog-protocol rules to allow UTF-8 in values
1022 * note: one pass for filtering and scanning, so a found SD
1023 * is always filtered, but an invalid one could be partially
1024 * filtered up to the format error.
1025 */
1026 static unsigned
1027 check_sd(char* p)
1028 {
1029 char *q = p;
1030 bool esc = false;
1031
1032 /* consider the NILVALUE to be valid */
1033 if (*q == '-' && (*(q+1) == ' ' || *(q+1) == '\0'))
1034 return 1;
1035
1036 for(;;) { /* SD-ELEMENT */
1037 if (*q++ != '[') return 0;
1038 /* SD-ID */
1039 if (!sdname(*q)) return 0;
1040 while (sdname(*q)) {
1041 *q = FORCE2ASCII(*q);
1042 q++;
1043 }
1044 for(;;) { /* SD-PARAM */
1045 if (*q == ']') {
1046 q++;
1047 if (*q == ' ' || *q == '\0') return q - p;
1048 else if (*q == '[') break;
1049 } else if (*q++ != ' ') return 0;
1050
1051 /* PARAM-NAME */
1052 if (!sdname(*q)) return 0;
1053 while (sdname(*q)) {
1054 *q = FORCE2ASCII(*q);
1055 q++;
1056 }
1057
1058 if (*q++ != '=') return 0;
1059 if (*q++ != '"') return 0;
1060
1061 for(;;) { /* PARAM-VALUE */
1062 if (esc) {
1063 esc = false;
1064 if (*q == '\\' || *q == '"' ||
1065 *q == ']') {
1066 q++;
1067 continue;
1068 }
1069 /* no else because invalid
1070 * escape sequences are accepted */
1071 }
1072 else if (*q == '"') break;
1073 else if (*q == '\0' || *q == ']') return 0;
1074 else if (*q == '\\') esc = true;
1075 else {
1076 int i;
1077 i = valid_utf8(q);
1078 if (i == 0)
1079 *q = '?';
1080 else if (i == 1)
1081 *q = FORCE2ASCII(*q);
1082 else /* multi byte char */
1083 q += (i-1);
1084 }
1085 q++;
1086 }
1087 q++;
1088 }
1089 }
1090 }
1091
1092 struct buf_msg *
1093 printline_syslogprotocol(const char *hname, char *msg,
1094 int flags, int pri)
1095 {
1096 struct buf_msg *buffer;
1097 char *p, *start;
1098 unsigned sdlen = 0, i = 0;
1099 bool utf8allowed = false; /* for some fields */
1100
1101 DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_syslogprotocol("
1102 "\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1103
1104 buffer = buf_msg_new(0);
1105 p = msg;
1106 p += check_timestamp((unsigned char*) p,
1107 &buffer->timestamp, true, !BSDOutputFormat);
1108 DPRINTF(D_DATA, "Got timestamp \"%s\"\n", buffer->timestamp);
1109
1110 if (flags & ADDDATE) {
1111 FREEPTR(buffer->timestamp);
1112 buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
1113 }
1114
1115 start = p;
1116 NEXTFIELD(p);
1117 /* extract host */
1118 for (start = p;; p++) {
1119 if ((*p == ' ' || *p == '\0')
1120 && start == p-1 && *(p-1) == '-') {
1121 /* NILVALUE */
1122 break;
1123 } else if ((*p == ' ' || *p == '\0')
1124 && (start != p-1 || *(p-1) != '-')) {
1125 buffer->host = strndup(start, p - start);
1126 break;
1127 } else {
1128 *p = FORCE2ASCII(*p);
1129 }
1130 }
1131 /* p @ SP after host */
1132 DPRINTF(D_DATA, "Got host \"%s\"\n", buffer->host);
1133
1134 /* extract app-name */
1135 NEXTFIELD(p);
1136 for (start = p;; p++) {
1137 if ((*p == ' ' || *p == '\0')
1138 && start == p-1 && *(p-1) == '-') {
1139 /* NILVALUE */
1140 break;
1141 } else if ((*p == ' ' || *p == '\0')
1142 && (start != p-1 || *(p-1) != '-')) {
1143 buffer->prog = strndup(start, p - start);
1144 break;
1145 } else {
1146 *p = FORCE2ASCII(*p);
1147 }
1148 }
1149 DPRINTF(D_DATA, "Got prog \"%s\"\n", buffer->prog);
1150
1151 /* extract procid */
1152 NEXTFIELD(p);
1153 for (start = p;; p++) {
1154 if ((*p == ' ' || *p == '\0')
1155 && start == p-1 && *(p-1) == '-') {
1156 /* NILVALUE */
1157 break;
1158 } else if ((*p == ' ' || *p == '\0')
1159 && (start != p-1 || *(p-1) != '-')) {
1160 buffer->pid = strndup(start, p - start);
1161 start = p;
1162 break;
1163 } else {
1164 *p = FORCE2ASCII(*p);
1165 }
1166 }
1167 DPRINTF(D_DATA, "Got pid \"%s\"\n", buffer->pid);
1168
1169 /* extract msgid */
1170 NEXTFIELD(p);
1171 for (start = p;; p++) {
1172 if ((*p == ' ' || *p == '\0')
1173 && start == p-1 && *(p-1) == '-') {
1174 /* NILVALUE */
1175 start = p+1;
1176 break;
1177 } else if ((*p == ' ' || *p == '\0')
1178 && (start != p-1 || *(p-1) != '-')) {
1179 buffer->msgid = strndup(start, p - start);
1180 start = p+1;
1181 break;
1182 } else {
1183 *p = FORCE2ASCII(*p);
1184 }
1185 }
1186 DPRINTF(D_DATA, "Got msgid \"%s\"\n", buffer->msgid);
1187
1188 /* extract SD */
1189 NEXTFIELD(p);
1190 start = p;
1191 sdlen = check_sd(p);
1192 DPRINTF(D_DATA, "check_sd(\"%s\") returned %d\n", p, sdlen);
1193
1194 if (sdlen == 1 && *p == '-') {
1195 /* NILVALUE */
1196 p++;
1197 } else if (sdlen > 1) {
1198 buffer->sd = strndup(p, sdlen);
1199 p += sdlen;
1200 } else {
1201 DPRINTF(D_DATA, "format error\n");
1202 }
1203 if (*p == '\0') start = p;
1204 else if (*p == ' ') start = ++p; /* SP */
1205 DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1206
1207 /* and now the message itself
1208 * note: move back to last start to check for BOM
1209 */
1210 all_syslog_msg:
1211 p = start;
1212
1213 /* check for UTF-8-BOM */
1214 if (IS_BOM(p)) {
1215 DPRINTF(D_DATA, "UTF-8 BOM\n");
1216 utf8allowed = true;
1217 p += 3;
1218 }
1219
1220 if (*p != '\0' && !utf8allowed) {
1221 size_t msglen;
1222
1223 msglen = strlen(p);
1224 assert(!buffer->msg);
1225 buffer->msg = copy_utf8_ascii(p, msglen);
1226 buffer->msgorig = buffer->msg;
1227 buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1228 } else if (*p != '\0' && utf8allowed) {
1229 while (*p != '\0') {
1230 i = valid_utf8(p);
1231 if (i == 0)
1232 *p++ = '?';
1233 else if (i == 1)
1234 *p = FORCE2ASCII(*p);
1235 p += i;
1236 }
1237 assert(p != start);
1238 assert(!buffer->msg);
1239 buffer->msg = strndup(start, p - start);
1240 buffer->msgorig = buffer->msg;
1241 buffer->msglen = buffer->msgsize = 1 + p - start;
1242 }
1243 DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1244
1245 buffer->recvhost = strdup(hname);
1246 buffer->pri = pri;
1247 buffer->flags = flags;
1248
1249 return buffer;
1250 }
1251
1252 /* copies an input into a new ASCII buffer
1253 * ASCII controls are converted to format "^X"
1254 * multi-byte UTF-8 chars are converted to format "<ab><cd>"
1255 */
1256 #define INIT_BUFSIZE 512
1257 char *
1258 copy_utf8_ascii(char *p, size_t p_len)
1259 {
1260 size_t idst = 0, isrc = 0, dstsize = INIT_BUFSIZE, i;
1261 char *dst, *tmp_dst;
1262
1263 MALLOC(dst, dstsize);
1264 while (isrc < p_len) {
1265 if (dstsize < idst + 10) {
1266 /* check for enough space for \0 and a UTF-8
1267 * conversion; longest possible is <U+123456> */
1268 tmp_dst = realloc(dst, dstsize + INIT_BUFSIZE);
1269 if (!tmp_dst)
1270 break;
1271 dst = tmp_dst;
1272 dstsize += INIT_BUFSIZE;
1273 }
1274
1275 i = valid_utf8(&p[isrc]);
1276 if (i == 0) { /* invalid encoding */
1277 dst[idst++] = '?';
1278 isrc++;
1279 } else if (i == 1) { /* check printable */
1280 if (iscntrl((unsigned char)p[isrc])
1281 && p[isrc] != '\t') {
1282 if (p[isrc] == '\n') {
1283 dst[idst++] = ' ';
1284 isrc++;
1285 } else {
1286 dst[idst++] = '^';
1287 dst[idst++] = p[isrc++] ^ 0100;
1288 }
1289 } else
1290 dst[idst++] = p[isrc++];
1291 } else { /* convert UTF-8 to ASCII */
1292 dst[idst++] = '<';
1293 idst += snprintf(&dst[idst], dstsize - idst, "U+%x",
1294 get_utf8_value(&p[isrc]));
1295 isrc += i;
1296 dst[idst++] = '>';
1297 }
1298 }
1299 dst[idst] = '\0';
1300
1301 /* shrink buffer to right size */
1302 tmp_dst = realloc(dst, idst+1);
1303 if (tmp_dst)
1304 return tmp_dst;
1305 else
1306 return dst;
1307 }
1308
1309 struct buf_msg *
1310 printline_bsdsyslog(const char *hname, char *msg,
1311 int flags, int pri)
1312 {
1313 struct buf_msg *buffer;
1314 char *p, *start;
1315 unsigned msgidlen = 0, sdlen = 0;
1316
1317 DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_bsdsyslog("
1318 "\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1319
1320 buffer = buf_msg_new(0);
1321 p = msg;
1322 p += check_timestamp((unsigned char*) p,
1323 &buffer->timestamp, false, !BSDOutputFormat);
1324 DPRINTF(D_DATA, "Got timestamp \"%s\"\n", buffer->timestamp);
1325
1326 if (flags & ADDDATE || !buffer->timestamp) {
1327 FREEPTR(buffer->timestamp);
1328 buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
1329 }
1330
1331 if (*p == ' ') p++; /* SP */
1332 else goto all_bsd_msg;
1333 /* in any error case we skip header parsing and
1334 * treat all following data as message content */
1335
1336 /* extract host */
1337 for (start = p;; p++) {
1338 if (*p == ' ' || *p == '\0') {
1339 buffer->host = strndup(start, p - start);
1340 break;
1341 } else if (*p == '[' || (*p == ':'
1342 && (*(p+1) == ' ' || *(p+1) == '\0'))) {
1343 /* no host in message */
1344 buffer->host = strdup(hname);
1345 buffer->prog = strndup(start, p - start);
1346 break;
1347 } else {
1348 *p = FORCE2ASCII(*p);
1349 }
1350 }
1351 DPRINTF(D_DATA, "Got host \"%s\"\n", buffer->host);
1352 /* p @ SP after host, or @ :/[ after prog */
1353
1354 /* extract program */
1355 if (!buffer->prog) {
1356 if (*p == ' ') p++; /* SP */
1357 else goto all_bsd_msg;
1358
1359 for (start = p;; p++) {
1360 if (*p == ' ' || *p == '\0') { /* error */
1361 goto all_bsd_msg;
1362 } else if (*p == '[' || (*p == ':'
1363 && (*(p+1) == ' ' || *(p+1) == '\0'))) {
1364 buffer->prog = strndup(start, p - start);
1365 break;
1366 } else {
1367 *p = FORCE2ASCII(*p);
1368 }
1369 }
1370 }
1371 DPRINTF(D_DATA, "Got prog \"%s\"\n", buffer->prog);
1372 start = p;
1373
1374 /* p @ :/[ after prog */
1375 if (*p == '[') {
1376 p++;
1377 if (*p == ' ') p++; /* SP */
1378 for (start = p;; p++) {
1379 if (*p == ' ' || *p == '\0') { /* error */
1380 goto all_bsd_msg;
1381 } else if (*p == ']') {
1382 buffer->pid = strndup(start, p - start);
1383 break;
1384 } else {
1385 *p = FORCE2ASCII(*p);
1386 }
1387 }
1388 }
1389 DPRINTF(D_DATA, "Got pid \"%s\"\n", buffer->pid);
1390
1391 if (*p == ']') p++;
1392 if (*p == ':') p++;
1393 if (*p == ' ') p++;
1394
1395 /* p @ msgid, @ opening [ of SD or @ first byte of message
1396 * accept either case and try to detect MSGID and SD fields
1397 *
1398 * only limitation: we do not accept UTF-8 data in
1399 * BSD Syslog messages -- so all SD values are ASCII-filtered
1400 *
1401 * I have found one scenario with 'unexpected' behaviour:
1402 * if there is only a SD intended, but a) it is short enough
1403 * to be a MSGID and b) the first word of the message can also
1404 * be parsed as an SD.
1405 * example:
1406 * "<35>Jul 6 12:39:08 tag[123]: [exampleSDID@0] - hello"
1407 * --> parsed as
1408 * MSGID = "[exampleSDID@0]"
1409 * SD = "-"
1410 * MSG = "hello"
1411 */
1412 start = p;
1413 msgidlen = check_msgid(p);
1414 if (msgidlen) /* check for SD in 2nd field */
1415 sdlen = check_sd(p+msgidlen+1);
1416
1417 if (msgidlen && sdlen) {
1418 /* MSGID in 1st and SD in 2nd field
1419 * now check for NILVALUEs and copy */
1420 if (msgidlen == 1 && *p == '-') {
1421 p++; /* - */
1422 p++; /* SP */
1423 DPRINTF(D_DATA, "Got MSGID \"-\"\n");
1424 } else {
1425 /* only has ASCII chars after check_msgid() */
1426 buffer->msgid = strndup(p, msgidlen);
1427 p += msgidlen;
1428 p++; /* SP */
1429 DPRINTF(D_DATA, "Got MSGID \"%s\"\n",
1430 buffer->msgid);
1431 }
1432 } else {
1433 /* either no msgid or no SD in 2nd field
1434 * --> check 1st field for SD */
1435 DPRINTF(D_DATA, "No MSGID\n");
1436 sdlen = check_sd(p);
1437 }
1438
1439 if (sdlen == 0) {
1440 DPRINTF(D_DATA, "No SD\n");
1441 } else if (sdlen > 1) {
1442 buffer->sd = copy_utf8_ascii(p, sdlen);
1443 DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1444 } else if (sdlen == 1 && *p == '-') {
1445 p++;
1446 DPRINTF(D_DATA, "Got SD \"-\"\n");
1447 } else {
1448 DPRINTF(D_DATA, "Error\n");
1449 }
1450
1451 if (*p == ' ') p++;
1452 start = p;
1453 /* and now the message itself
1454 * note: do not reset start, because we might come here
1455 * by goto and want to have the incomplete field as part
1456 * of the msg
1457 */
1458 all_bsd_msg:
1459 if (*p != '\0') {
1460 size_t msglen = strlen(p);
1461 buffer->msg = copy_utf8_ascii(p, msglen);
1462 buffer->msgorig = buffer->msg;
1463 buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1464 }
1465 DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1466
1467 buffer->recvhost = strdup(hname);
1468 buffer->pri = pri;
1469 buffer->flags = flags | BSDSYSLOG;
1470
1471 return buffer;
1472 }
1473
1474 struct buf_msg *
1475 printline_kernelprintf(const char *hname, char *msg,
1476 int flags, int pri)
1477 {
1478 struct buf_msg *buffer;
1479 char *p;
1480 unsigned sdlen = 0;
1481
1482 DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_kernelprintf("
1483 "\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1484
1485 buffer = buf_msg_new(0);
1486 buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
1487 buffer->pri = pri;
1488 buffer->flags = flags;
1489
1490 /* assume there is no MSGID but there might be SD */
1491 p = msg;
1492 sdlen = check_sd(p);
1493
1494 if (sdlen == 0) {
1495 DPRINTF(D_DATA, "No SD\n");
1496 } else if (sdlen > 1) {
1497 buffer->sd = copy_utf8_ascii(p, sdlen);
1498 DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1499 } else if (sdlen == 1 && *p == '-') {
1500 p++;
1501 DPRINTF(D_DATA, "Got SD \"-\"\n");
1502 } else {
1503 DPRINTF(D_DATA, "Error\n");
1504 }
1505
1506 if (*p == ' ') p++;
1507 if (*p != '\0') {
1508 size_t msglen = strlen(p);
1509 buffer->msg = copy_utf8_ascii(p, msglen);
1510 buffer->msgorig = buffer->msg;
1511 buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1512 }
1513 DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1514
1515 return buffer;
1516 }
1517
1518 /*
1519 * Take a raw input line, read priority and version, call the
1520 * right message parsing function, then call logmsg().
1521 */
1522 void
1523 printline(const char *hname, char *msg, int flags)
1524 {
1525 struct buf_msg *buffer;
1526 int pri;
1527 char *p, *q;
1528 long n;
1529 bool bsdsyslog = true;
1530
1531 DPRINTF((D_CALL|D_BUFFER|D_DATA),
1532 "printline(\"%s\", \"%s\", %d)\n", hname, msg, flags);
1533
1534 /* test for special codes */
1535 pri = DEFUPRI;
1536 p = msg;
1537 if (*p == '<') {
1538 errno = 0;
1539 n = strtol(p + 1, &q, 10);
1540 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1541 p = q + 1;
1542 pri = (int)n;
1543 /* check for syslog-protocol version */
1544 if (*p == '1' && p[1] == ' ') {
1545 p += 2; /* skip version and space */
1546 bsdsyslog = false;
1547 } else {
1548 bsdsyslog = true;
1549 }
1550 }
1551 }
1552 if (pri & ~(LOG_FACMASK|LOG_PRIMASK))
1553 pri = DEFUPRI;
1554
1555 /*
1556 * Don't (usually) allow users to log kernel messages.
1557 * NOTE: Since LOG_KERN == 0, this will also match
1558 * messages with no facility specified.
1559 */
1560 if ((pri & LOG_FACMASK) == LOG_KERN && KernXlat)
1561 pri = LOG_USER | LOG_PRI(pri);
1562
1563 if (bsdsyslog) {
1564 buffer = printline_bsdsyslog(hname, p, flags, pri);
1565 } else {
1566 buffer = printline_syslogprotocol(hname, p, flags, pri);
1567 }
1568 logmsg(buffer);
1569 DELREF(buffer);
1570 }
1571
1572 /*
1573 * Take a raw input line from /dev/klog, split and format similar to syslog().
1574 */
1575 void
1576 printsys(char *msg)
1577 {
1578 int n, is_printf, pri, flags;
1579 char *p, *q;
1580 struct buf_msg *buffer;
1581
1582 klog_linebufoff = 0;
1583 for (p = msg; *p != '\0'; ) {
1584 bool bsdsyslog = true;
1585
1586 is_printf = 1;
1587 flags = ISKERNEL | ADDDATE | BSDSYSLOG;
1588 if (SyncKernel)
1589 flags |= SYNC_FILE;
1590 if (is_printf) /* kernel printf's come out on console */
1591 flags |= IGN_CONS;
1592 pri = DEFSPRI;
1593
1594 if (*p == '<') {
1595 errno = 0;
1596 n = (int)strtol(p + 1, &q, 10);
1597 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1598 p = q + 1;
1599 is_printf = 0;
1600 pri = n;
1601 if (*p == '1') { /* syslog-protocol version */
1602 p += 2; /* skip version and space */
1603 bsdsyslog = false;
1604 } else {
1605 bsdsyslog = true;
1606 }
1607 }
1608 }
1609 for (q = p; *q != '\0' && *q != '\n'; q++)
1610 /* look for end of line; no further checks.
1611 * trust the kernel to send ASCII only */;
1612 if (*q != '\0')
1613 *q++ = '\0';
1614 else {
1615 memcpy(linebuf, p, klog_linebufoff = q - p);
1616 break;
1617 }
1618
1619 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1620 pri = DEFSPRI;
1621
1622 /* allow all kinds of input from kernel */
1623 if (is_printf)
1624 buffer = printline_kernelprintf(
1625 LocalFQDN, p, flags, pri);
1626 else {
1627 if (bsdsyslog)
1628 buffer = printline_bsdsyslog(
1629 LocalFQDN, p, flags, pri);
1630 else
1631 buffer = printline_syslogprotocol(
1632 LocalFQDN, p, flags, pri);
1633 }
1634
1635 /* set fields left open */
1636 if (!buffer->prog)
1637 buffer->prog = strdup(_PATH_UNIX);
1638 if (!buffer->host)
1639 buffer->host = LocalFQDN;
1640 if (!buffer->recvhost)
1641 buffer->recvhost = LocalFQDN;
1642
1643 logmsg(buffer);
1644 DELREF(buffer);
1645 p = q;
1646 }
1647 }
1648
1649 /*
1650 * Check to see if `name' matches the provided specification, using the
1651 * specified strstr function.
1652 */
1653 int
1654 matches_spec(const char *name, const char *spec,
1655 char *(*check)(const char *, const char *))
1656 {
1657 const char *s;
1658 const char *cursor;
1659 char prev, next;
1660 size_t len;
1661
1662 if (name[0] == '\0')
1663 return 0;
1664
1665 if (strchr(name, ',')) /* sanity */
1666 return 0;
1667
1668 len = strlen(name);
1669 cursor = spec;
1670 while ((s = (*check)(cursor, name)) != NULL) {
1671 prev = s == spec ? ',' : *(s - 1);
1672 cursor = s + len;
1673 next = *cursor;
1674
1675 if (prev == ',' && (next == '\0' || next == ','))
1676 return 1;
1677 }
1678
1679 return 0;
1680 }
1681
1682 /*
1683 * wrapper with old function signature,
1684 * keeps calling code shorter and hides buffer allocation
1685 */
1686 void
1687 logmsg_async(int pri, const char *sd, const char *msg, int flags)
1688 {
1689 struct buf_msg *buffer;
1690 size_t msglen;
1691
1692 DPRINTF((D_CALL|D_DATA), "logmsg_async(%d, \"%s\", \"%s\", %d)\n",
1693 pri, sd, msg, flags);
1694
1695 if (msg) {
1696 msglen = strlen(msg);
1697 msglen++; /* adds \0 */
1698 buffer = buf_msg_new(msglen);
1699 buffer->msglen = strlcpy(buffer->msg, msg, msglen) + 1;
1700 } else {
1701 buffer = buf_msg_new(0);
1702 }
1703 if (sd) buffer->sd = strdup(sd);
1704 buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
1705 buffer->prog = appname;
1706 buffer->pid = include_pid;
1707 buffer->recvhost = buffer->host = LocalFQDN;
1708 buffer->pri = pri;
1709 buffer->flags = flags;
1710
1711 logmsg(buffer);
1712 DELREF(buffer);
1713 }
1714
1715 /* read timestamp in from_buf, convert into a timestamp in to_buf
1716 *
1717 * returns length of timestamp found in from_buf (= number of bytes consumed)
1718 */
1719 size_t
1720 check_timestamp(unsigned char *from_buf, char **to_buf,
1721 bool from_iso, bool to_iso)
1722 {
1723 unsigned char *q;
1724 int p;
1725 bool found_ts = false;
1726
1727 DPRINTF((D_CALL|D_DATA), "check_timestamp(%p = \"%s\", from_iso=%d, "
1728 "to_iso=%d)\n", from_buf, from_buf, from_iso, to_iso);
1729
1730 if (!from_buf) return 0;
1731 /*
1732 * Check to see if msg looks non-standard.
1733 * looks at every char because we do not have a msg length yet
1734 */
1735 /* detailed checking adapted from Albert Mietus' sl_timestamp.c */
1736 if (from_iso) {
1737 if (from_buf[4] == '-' && from_buf[7] == '-'
1738 && from_buf[10] == 'T' && from_buf[13] == ':'
1739 && from_buf[16] == ':'
1740 && isdigit(from_buf[0]) && isdigit(from_buf[1])
1741 && isdigit(from_buf[2]) && isdigit(from_buf[3]) /* YYYY */
1742 && isdigit(from_buf[5]) && isdigit(from_buf[6])
1743 && isdigit(from_buf[8]) && isdigit(from_buf[9]) /* mm dd */
1744 && isdigit(from_buf[11]) && isdigit(from_buf[12]) /* HH */
1745 && isdigit(from_buf[14]) && isdigit(from_buf[15]) /* MM */
1746 && isdigit(from_buf[17]) && isdigit(from_buf[18]) /* SS */
1747 ) {
1748 /* time-secfrac */
1749 if (from_buf[19] == '.')
1750 for (p=20; isdigit(from_buf[p]); p++) /* NOP*/;
1751 else
1752 p = 19;
1753 /* time-offset */
1754 if (from_buf[p] == 'Z'
1755 || ((from_buf[p] == '+' || from_buf[p] == '-')
1756 && from_buf[p+3] == ':'
1757 && isdigit(from_buf[p+1]) && isdigit(from_buf[p+2])
1758 && isdigit(from_buf[p+4]) && isdigit(from_buf[p+5])
1759 ))
1760 found_ts = true;
1761 }
1762 } else {
1763 if (from_buf[3] == ' ' && from_buf[6] == ' '
1764 && from_buf[9] == ':' && from_buf[12] == ':'
1765 && (from_buf[4] == ' ' || isdigit(from_buf[4]))
1766 && isdigit(from_buf[5]) /* dd */
1767 && isdigit(from_buf[7]) && isdigit(from_buf[8]) /* HH */
1768 && isdigit(from_buf[10]) && isdigit(from_buf[11]) /* MM */
1769 && isdigit(from_buf[13]) && isdigit(from_buf[14]) /* SS */
1770 && isupper(from_buf[0]) && islower(from_buf[1]) /* month */
1771 && islower(from_buf[2]))
1772 found_ts = true;
1773 }
1774 if (!found_ts) {
1775 if (from_buf[0] == '-' && from_buf[1] == ' ') {
1776 /* NILVALUE */
1777 if (to_iso) {
1778 /* with ISO = syslog-protocol output leave
1779 * it as is, because it is better to have
1780 * no timestamp than a wrong one.
1781 */
1782 *to_buf = strdup("-");
1783 } else {
1784 /* with BSD Syslog the field is required
1785 * so replace it with current time
1786 */
1787 *to_buf = make_timestamp(NULL, false, 0);
1788 }
1789 return 2;
1790 }
1791 *to_buf = make_timestamp(NULL, false, 0);
1792 return 0;
1793 }
1794
1795 if (!from_iso && !to_iso) {
1796 /* copy BSD timestamp */
1797 DPRINTF(D_CALL, "check_timestamp(): copy BSD timestamp\n");
1798 *to_buf = strndup((char *)from_buf, BSD_TIMESTAMPLEN);
1799 return BSD_TIMESTAMPLEN;
1800 } else if (from_iso && to_iso) {
1801 /* copy ISO timestamp */
1802 DPRINTF(D_CALL, "check_timestamp(): copy ISO timestamp\n");
1803 if (!(q = (unsigned char *) strchr((char *)from_buf, ' ')))
1804 q = from_buf + strlen((char *)from_buf);
1805 *to_buf = strndup((char *)from_buf, q - from_buf);
1806 return q - from_buf;
1807 } else if (from_iso && !to_iso) {
1808 /* convert ISO->BSD */
1809 struct tm parsed;
1810 time_t timeval;
1811 char tsbuf[MAX_TIMESTAMPLEN];
1812 int i = 0, j;
1813
1814 DPRINTF(D_CALL, "check_timestamp(): convert ISO->BSD\n");
1815 for(i = 0; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1816 && from_buf[i] != '.' && from_buf[i] != ' '; i++)
1817 tsbuf[i] = from_buf[i]; /* copy date & time */
1818 j = i;
1819 for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1820 && from_buf[i] != '+' && from_buf[i] != '-'
1821 && from_buf[i] != 'Z' && from_buf[i] != ' '; i++)
1822 ; /* skip fraction digits */
1823 for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1824 && from_buf[i] != ':' && from_buf[i] != ' ' ; i++, j++)
1825 tsbuf[j] = from_buf[i]; /* copy TZ */
1826 if (from_buf[i] == ':') i++; /* skip colon */
1827 for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1828 && from_buf[i] != ' ' ; i++, j++)
1829 tsbuf[j] = from_buf[i]; /* copy TZ */
1830
1831 (void)memset(&parsed, 0, sizeof(parsed));
1832 (void)strptime(tsbuf, "%FT%T%z", &parsed);
1833 parsed.tm_isdst = -1;
1834 timeval = mktime(&parsed);
1835
1836 *to_buf = make_timestamp(&timeval, false, BSD_TIMESTAMPLEN);
1837 return i;
1838 } else if (!from_iso && to_iso) {
1839 /* convert BSD->ISO */
1840 struct tm parsed;
1841 struct tm *current;
1842 time_t timeval;
1843
1844 (void)memset(&parsed, 0, sizeof(parsed));
1845 parsed.tm_isdst = -1;
1846 DPRINTF(D_CALL, "check_timestamp(): convert BSD->ISO\n");
1847 strptime((char *)from_buf, "%b %d %T", &parsed);
1848 current = gmtime(&now);
1849
1850 /* use current year and timezone */
1851 parsed.tm_isdst = current->tm_isdst;
1852 parsed.tm_gmtoff = current->tm_gmtoff;
1853 parsed.tm_year = current->tm_year;
1854 if (current->tm_mon == 0 && parsed.tm_mon == 11)
1855 parsed.tm_year--;
1856
1857 timeval = mktime(&parsed);
1858 *to_buf = make_timestamp(&timeval, true, MAX_TIMESTAMPLEN - 1);
1859
1860 return BSD_TIMESTAMPLEN;
1861 } else {
1862 DPRINTF(D_MISC,
1863 "Executing unreachable code in check_timestamp()\n");
1864 return 0;
1865 }
1866 }
1867
1868 /*
1869 * Log a message to the appropriate log files, users, etc. based on
1870 * the priority.
1871 */
1872 void
1873 logmsg(struct buf_msg *buffer)
1874 {
1875 struct filed *f;
1876 int fac, omask, prilev;
1877
1878 DPRINTF((D_CALL|D_BUFFER), "logmsg: buffer@%p, pri 0%o/%d, flags 0x%x,"
1879 " timestamp \"%s\", from \"%s\", sd \"%s\", msg \"%s\"\n",
1880 buffer, buffer->pri, buffer->pri, buffer->flags,
1881 buffer->timestamp, buffer->recvhost, buffer->sd, buffer->msg);
1882
1883 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
1884
1885 /* sanity check */
1886 assert(buffer->refcount == 1);
1887 assert(buffer->msglen <= buffer->msgsize);
1888 assert(buffer->msgorig <= buffer->msg);
1889 assert((buffer->msg && buffer->msglen == strlen(buffer->msg)+1)
1890 || (!buffer->msg && !buffer->msglen));
1891 if (!buffer->msg && !buffer->sd && !buffer->msgid)
1892 DPRINTF(D_BUFFER, "Empty message?\n");
1893
1894 /* extract facility and priority level */
1895 if (buffer->flags & MARK)
1896 fac = LOG_NFACILITIES;
1897 else
1898 fac = LOG_FAC(buffer->pri);
1899 prilev = LOG_PRI(buffer->pri);
1900
1901 /* log the message to the particular outputs */
1902 if (!Initialized) {
1903 f = &consfile;
1904 f->f_file = open(ctty, O_WRONLY | O_NDELAY, 0);
1905
1906 if (f->f_file >= 0) {
1907 DELREF(f->f_prevmsg);
1908 f->f_prevmsg = NEWREF(buffer);
1909 fprintlog(f, NEWREF(buffer), NULL);
1910 DELREF(buffer);
1911 (void)close(f->f_file);
1912 }
1913 (void)sigsetmask(omask);
1914 return;
1915 }
1916
1917 for (f = Files; f; f = f->f_next) {
1918 char *h; /* host to use for comparing */
1919
1920 /* skip messages that are incorrect priority */
1921 if (!MATCH_PRI(f, fac, prilev)
1922 || f->f_pmask[fac] == INTERNAL_NOPRI)
1923 continue;
1924
1925 /* skip messages with the incorrect host name */
1926 /* compare with host (which is supposedly more correct), */
1927 /* but fallback to recvhost if host is NULL */
1928 h = (buffer->host != NULL) ? buffer->host : buffer->recvhost;
1929 if (f->f_host != NULL && h != NULL) {
1930 char shost[MAXHOSTNAMELEN + 1];
1931
1932 if (BSDOutputFormat) {
1933 (void)strlcpy(shost, h, sizeof(shost));
1934 trim_anydomain(shost);
1935 h = shost;
1936 }
1937 switch (f->f_host[0]) {
1938 case '+':
1939 if (! matches_spec(h, f->f_host + 1,
1940 strcasestr))
1941 continue;
1942 break;
1943 case '-':
1944 if (matches_spec(h, f->f_host + 1,
1945 strcasestr))
1946 continue;
1947 break;
1948 }
1949 }
1950
1951 /* skip messages with the incorrect program name */
1952 if (f->f_program != NULL && buffer->prog != NULL) {
1953 switch (f->f_program[0]) {
1954 case '+':
1955 if (!matches_spec(buffer->prog,
1956 f->f_program + 1, strstr))
1957 continue;
1958 break;
1959 case '-':
1960 if (matches_spec(buffer->prog,
1961 f->f_program + 1, strstr))
1962 continue;
1963 break;
1964 default:
1965 if (!matches_spec(buffer->prog,
1966 f->f_program, strstr))
1967 continue;
1968 break;
1969 }
1970 }
1971
1972 if (f->f_type == F_CONSOLE && (buffer->flags & IGN_CONS))
1973 continue;
1974
1975 /* don't output marks to recently written files */
1976 if ((buffer->flags & MARK)
1977 && (now - f->f_time) < MarkInterval / 2)
1978 continue;
1979
1980 /*
1981 * suppress duplicate lines to this file unless NoRepeat
1982 */
1983 #define MSG_FIELD_EQ(x) ((!buffer->x && !f->f_prevmsg->x) || \
1984 (buffer->x && f->f_prevmsg->x && !strcmp(buffer->x, f->f_prevmsg->x)))
1985
1986 if ((buffer->flags & MARK) == 0 &&
1987 f->f_prevmsg &&
1988 buffer->msglen == f->f_prevmsg->msglen &&
1989 !NoRepeat &&
1990 MSG_FIELD_EQ(host) &&
1991 MSG_FIELD_EQ(sd) &&
1992 MSG_FIELD_EQ(msg)
1993 ) {
1994 f->f_prevcount++;
1995 DPRINTF(D_DATA, "Msg repeated %d times, %ld sec of %d\n",
1996 f->f_prevcount, (long)(now - f->f_time),
1997 repeatinterval[f->f_repeatcount]);
1998 /*
1999 * If domark would have logged this by now,
2000 * flush it now (so we don't hold isolated messages),
2001 * but back off so we'll flush less often
2002 * in the future.
2003 */
2004 if (now > REPEATTIME(f)) {
2005 fprintlog(f, NEWREF(buffer), NULL);
2006 DELREF(buffer);
2007 BACKOFF(f);
2008 }
2009 } else {
2010 /* new line, save it */
2011 if (f->f_prevcount)
2012 fprintlog(f, NULL, NULL);
2013 f->f_repeatcount = 0;
2014 DELREF(f->f_prevmsg);
2015 f->f_prevmsg = NEWREF(buffer);
2016 fprintlog(f, NEWREF(buffer), NULL);
2017 DELREF(buffer);
2018 }
2019 }
2020 (void)sigsetmask(omask);
2021 }
2022
2023 /*
2024 * format one buffer into output format given by flag BSDOutputFormat
2025 * line is allocated and has to be free()d by caller
2026 * size_t pointers are optional, if not NULL then they will return
2027 * different lengths used for formatting and output
2028 */
2029 #define OUT(x) ((x)?(x):"-")
2030 bool
2031 format_buffer(struct buf_msg *buffer, char **line, size_t *ptr_linelen,
2032 size_t *ptr_msglen, size_t *ptr_tlsprefixlen, size_t *ptr_prilen)
2033 {
2034 #define FPBUFSIZE 30
2035 static char ascii_empty[] = "";
2036 char fp_buf[FPBUFSIZE] = "\0";
2037 char *hostname, *shorthostname = NULL;
2038 char *ascii_sd = ascii_empty;
2039 char *ascii_msg = ascii_empty;
2040 size_t linelen, msglen, tlsprefixlen, prilen, j;
2041
2042 DPRINTF(D_CALL, "format_buffer(%p)\n", buffer);
2043 if (!buffer) return false;
2044
2045 /* All buffer fields are set with strdup(). To avoid problems
2046 * on memory exhaustion we allow them to be empty and replace
2047 * the essential fields with already allocated generic values.
2048 */
2049 if (!buffer->timestamp)
2050 buffer->timestamp = timestamp;
2051 if (!buffer->host && !buffer->recvhost)
2052 buffer->host = LocalFQDN;
2053
2054 if (LogFacPri) {
2055 const char *f_s = NULL, *p_s = NULL;
2056 int fac = buffer->pri & LOG_FACMASK;
2057 int pri = LOG_PRI(buffer->pri);
2058 char f_n[5], p_n[5];
2059
2060 if (LogFacPri > 1) {
2061 CODE *c;
2062
2063 for (c = facilitynames; c->c_name != NULL; c++) {
2064 if (c->c_val == fac) {
2065 f_s = c->c_name;
2066 break;
2067 }
2068 }
2069 for (c = prioritynames; c->c_name != NULL; c++) {
2070 if (c->c_val == pri) {
2071 p_s = c->c_name;
2072 break;
2073 }
2074 }
2075 }
2076 if (f_s == NULL) {
2077 snprintf(f_n, sizeof(f_n), "%d", LOG_FAC(fac));
2078 f_s = f_n;
2079 }
2080 if (p_s == NULL) {
2081 snprintf(p_n, sizeof(p_n), "%d", pri);
2082 p_s = p_n;
2083 }
2084 snprintf(fp_buf, sizeof(fp_buf), "<%s.%s>", f_s, p_s);
2085 }
2086
2087 /* hostname or FQDN */
2088 hostname = (buffer->host ? buffer->host : buffer->recvhost);
2089 if (BSDOutputFormat
2090 && (shorthostname = strdup(hostname))) {
2091 /* if the previous BSD output format with "host [recvhost]:"
2092 * gets implemented, this is the right place to distinguish
2093 * between buffer->host and buffer->recvhost
2094 */
2095 trim_anydomain(shorthostname);
2096 hostname = shorthostname;
2097 }
2098
2099 /* new message formatting:
2100 * instead of using iov always assemble one complete TLS-ready line
2101 * with length and priority (depending on BSDOutputFormat either in
2102 * BSD Syslog or syslog-protocol format)
2103 *
2104 * additionally save the length of the prefixes,
2105 * so UDP destinations can skip the length prefix and
2106 * file/pipe/wall destinations can omit length and priority
2107 */
2108 /* first determine required space */
2109 if (BSDOutputFormat) {
2110 /* only output ASCII chars */
2111 if (buffer->sd)
2112 ascii_sd = copy_utf8_ascii(buffer->sd,
2113 strlen(buffer->sd));
2114 if (buffer->msg) {
2115 if (IS_BOM(buffer->msg))
2116 ascii_msg = copy_utf8_ascii(buffer->msg,
2117 buffer->msglen - 1);
2118 else /* assume already converted at input */
2119 ascii_msg = buffer->msg;
2120 }
2121 msglen = snprintf(NULL, 0, "<%d>%s%.15s %s %s%s%s%s: %s%s%s",
2122 buffer->pri, fp_buf, buffer->timestamp,
2123 hostname, OUT(buffer->prog),
2124 buffer->pid ? "[" : "",
2125 buffer->pid ? buffer->pid : "",
2126 buffer->pid ? "]" : "", ascii_sd,
2127 (buffer->sd && buffer->msg ? " ": ""), ascii_msg);
2128 } else
2129 msglen = snprintf(NULL, 0, "<%d>1 %s%s %s %s %s %s %s%s%s",
2130 buffer->pri, fp_buf, buffer->timestamp,
2131 hostname, OUT(buffer->prog), OUT(buffer->pid),
2132 OUT(buffer->msgid), OUT(buffer->sd),
2133 (buffer->msg ? " ": ""),
2134 (buffer->msg ? buffer->msg: ""));
2135 /* add space for length prefix */
2136 tlsprefixlen = 0;
2137 for (j = msglen; j; j /= 10)
2138 tlsprefixlen++;
2139 /* one more for the space */
2140 tlsprefixlen++;
2141
2142 prilen = snprintf(NULL, 0, "<%d>", buffer->pri);
2143 if (!BSDOutputFormat)
2144 prilen += 2; /* version char and space */
2145 MALLOC(*line, msglen + tlsprefixlen + 1);
2146 if (BSDOutputFormat)
2147 linelen = snprintf(*line,
2148 msglen + tlsprefixlen + 1,
2149 "%zu <%d>%s%.15s %s %s%s%s%s: %s%s%s",
2150 msglen, buffer->pri, fp_buf, buffer->timestamp,
2151 hostname, OUT(buffer->prog),
2152 (buffer->pid ? "[" : ""),
2153 (buffer->pid ? buffer->pid : ""),
2154 (buffer->pid ? "]" : ""), ascii_sd,
2155 (buffer->sd && buffer->msg ? " ": ""), ascii_msg);
2156 else
2157 linelen = snprintf(*line,
2158 msglen + tlsprefixlen + 1,
2159 "%zu <%d>1 %s%s %s %s %s %s %s%s%s",
2160 msglen, buffer->pri, fp_buf, buffer->timestamp,
2161 hostname, OUT(buffer->prog), OUT(buffer->pid),
2162 OUT(buffer->msgid), OUT(buffer->sd),
2163 (buffer->msg ? " ": ""),
2164 (buffer->msg ? buffer->msg: ""));
2165 DPRINTF(D_DATA, "formatted %zu octets to: '%.*s' (linelen %zu, "
2166 "msglen %zu, tlsprefixlen %zu, prilen %zu)\n", linelen,
2167 (int)linelen, *line, linelen, msglen, tlsprefixlen, prilen);
2168
2169 FREEPTR(shorthostname);
2170 if (ascii_sd != ascii_empty)
2171 FREEPTR(ascii_sd);
2172 if (ascii_msg != ascii_empty && ascii_msg != buffer->msg)
2173 FREEPTR(ascii_msg);
2174
2175 if (ptr_linelen) *ptr_linelen = linelen;
2176 if (ptr_msglen) *ptr_msglen = msglen;
2177 if (ptr_tlsprefixlen) *ptr_tlsprefixlen = tlsprefixlen;
2178 if (ptr_prilen) *ptr_prilen = prilen;
2179 return true;
2180 }
2181
2182 /*
2183 * if qentry == NULL: new message, if temporarily undeliverable it will be enqueued
2184 * if qentry != NULL: a temporarily undeliverable message will not be enqueued,
2185 * but after delivery be removed from the queue
2186 */
2187 void
2188 fprintlog(struct filed *f, struct buf_msg *passedbuffer, struct buf_queue *qentry)
2189 {
2190 static char crnl[] = "\r\n";
2191 struct buf_msg *buffer = passedbuffer;
2192 struct iovec iov[4];
2193 struct iovec *v = iov;
2194 bool error = false;
2195 int e = 0, len = 0;
2196 size_t msglen, linelen, tlsprefixlen, prilen;
2197 char *p, *line = NULL, *lineptr = NULL;
2198 #ifndef DISABLE_SIGN
2199 bool newhash = false;
2200 #endif
2201 #define REPBUFSIZE 80
2202 char greetings[200];
2203 #define ADDEV() do { v++; assert((size_t)(v - iov) < A_CNT(iov)); } while(/*CONSTCOND*/0)
2204
2205 DPRINTF(D_CALL, "fprintlog(%p, %p, %p)\n", f, buffer, qentry);
2206
2207 f->f_time = now;
2208
2209 /* increase refcount here and lower again at return.
2210 * this enables the buffer in the else branch to be freed
2211 * --> every branch needs one NEWREF() or buf_msg_new()! */
2212 if (buffer) {
2213 (void)NEWREF(buffer);
2214 } else {
2215 if (f->f_prevcount > 1) {
2216 /* possible syslog-sign incompatibility:
2217 * assume destinations f1 and f2 share one SG and
2218 * get the same message sequence.
2219 *
2220 * now both f1 and f2 generate "repeated" messages
2221 * "repeated" messages are different due to different
2222 * timestamps
2223 * the SG will get hashes for the two "repeated" messages
2224 *
2225 * now both f1 and f2 are just fine, but a verification
2226 * will report that each 'lost' a message, i.e. the
2227 * other's "repeated" message
2228 *
2229 * conditions for 'safe configurations':
2230 * - use NoRepeat option,
2231 * - use SG 3, or
2232 * - have exactly one destination for every PRI
2233 */
2234 buffer = buf_msg_new(REPBUFSIZE);
2235 buffer->msglen = snprintf(buffer->msg, REPBUFSIZE,
2236 "last message repeated %d times", f->f_prevcount);
2237 buffer->timestamp = make_timestamp(NULL,
2238 !BSDOutputFormat, 0);
2239 buffer->pri = f->f_prevmsg->pri;
2240 buffer->host = LocalFQDN;
2241 buffer->prog = appname;
2242 buffer->pid = include_pid;
2243
2244 } else {
2245 buffer = NEWREF(f->f_prevmsg);
2246 }
2247 }
2248
2249 /* no syslog-sign messages to tty/console/... */
2250 if ((buffer->flags & SIGN_MSG)
2251 && ((f->f_type == F_UNUSED)
2252 || (f->f_type == F_TTY)
2253 || (f->f_type == F_CONSOLE)
2254 || (f->f_type == F_USERS)
2255 || (f->f_type == F_WALL)
2256 || (f->f_type == F_FIFO))) {
2257 DELREF(buffer);
2258 return;
2259 }
2260
2261 /* buffering works only for few types */
2262 if (qentry
2263 && (f->f_type != F_TLS)
2264 && (f->f_type != F_PIPE)
2265 && (f->f_type != F_FILE)
2266 && (f->f_type != F_FIFO)) {
2267 errno = 0;
2268 logerror("Warning: unexpected message type %d in buffer",
2269 f->f_type);
2270 DELREF(buffer);
2271 return;
2272 }
2273
2274 if (!format_buffer(buffer, &line,
2275 &linelen, &msglen, &tlsprefixlen, &prilen)) {
2276 DPRINTF(D_CALL, "format_buffer() failed, skip message\n");
2277 DELREF(buffer);
2278 return;
2279 }
2280 /* assert maximum message length */
2281 if (TypeInfo[f->f_type].max_msg_length != -1
2282 && (size_t)TypeInfo[f->f_type].max_msg_length
2283 < linelen - tlsprefixlen - prilen) {
2284 linelen = TypeInfo[f->f_type].max_msg_length
2285 + tlsprefixlen + prilen;
2286 DPRINTF(D_DATA, "truncating oversized message to %zu octets\n",
2287 linelen);
2288 }
2289
2290 #ifndef DISABLE_SIGN
2291 /* keep state between appending the hash (before buffer is sent)
2292 * and possibly sending a SB (after buffer is sent): */
2293 /* get hash */
2294 if (!(buffer->flags & SIGN_MSG) && !qentry) {
2295 char *hash = NULL;
2296 struct signature_group_t *sg;
2297
2298 if ((sg = sign_get_sg(buffer->pri, f)) != NULL) {
2299 if (sign_msg_hash(line + tlsprefixlen, &hash))
2300 newhash = sign_append_hash(hash, sg);
2301 else
2302 DPRINTF(D_SIGN,
2303 "Unable to hash line \"%s\"\n", line);
2304 }
2305 }
2306 #endif /* !DISABLE_SIGN */
2307
2308 /* set start and length of buffer and/or fill iovec */
2309 switch (f->f_type) {
2310 case F_UNUSED:
2311 /* nothing */
2312 break;
2313 case F_TLS:
2314 /* nothing, as TLS uses whole buffer to send */
2315 lineptr = line;
2316 len = linelen;
2317 break;
2318 case F_FORW:
2319 lineptr = line + tlsprefixlen;
2320 len = linelen - tlsprefixlen;
2321 break;
2322 case F_PIPE:
2323 case F_FIFO:
2324 case F_FILE: /* fallthrough */
2325 if (f->f_flags & FFLAG_FULL) {
2326 v->iov_base = line + tlsprefixlen;
2327 v->iov_len = linelen - tlsprefixlen;
2328 } else {
2329 v->iov_base = line + tlsprefixlen + prilen;
2330 v->iov_len = linelen - tlsprefixlen - prilen;
2331 }
2332 ADDEV();
2333 v->iov_base = &crnl[1];
2334 v->iov_len = 1;
2335 ADDEV();
2336 break;
2337 case F_CONSOLE:
2338 case F_TTY:
2339 /* filter non-ASCII */
2340 p = line;
2341 while (*p) {
2342 *p = FORCE2ASCII(*p);
2343 p++;
2344 }
2345 v->iov_base = line + tlsprefixlen + prilen;
2346 v->iov_len = linelen - tlsprefixlen - prilen;
2347 ADDEV();
2348 v->iov_base = crnl;
2349 v->iov_len = 2;
2350 ADDEV();
2351 break;
2352 case F_WALL:
2353 v->iov_base = greetings;
2354 v->iov_len = snprintf(greetings, sizeof(greetings),
2355 "\r\n\7Message from syslogd@%s at %s ...\r\n",
2356 (buffer->host ? buffer->host : buffer->recvhost),
2357 buffer->timestamp);
2358 ADDEV();
2359 /* FALLTHROUGH */
2360 case F_USERS: /* fallthrough */
2361 /* filter non-ASCII */
2362 p = line;
2363 while (*p) {
2364 *p = FORCE2ASCII(*p);
2365 p++;
2366 }
2367 v->iov_base = line + tlsprefixlen + prilen;
2368 v->iov_len = linelen - tlsprefixlen - prilen;
2369 ADDEV();
2370 v->iov_base = &crnl[1];
2371 v->iov_len = 1;
2372 ADDEV();
2373 break;
2374 }
2375
2376 /* send */
2377 switch (f->f_type) {
2378 case F_UNUSED:
2379 DPRINTF(D_MISC, "Logging to %s\n", TypeInfo[f->f_type].name);
2380 break;
2381
2382 case F_FORW:
2383 DPRINTF(D_MISC, "Logging to %s %s\n",
2384 TypeInfo[f->f_type].name, f->f_un.f_forw.f_hname);
2385 udp_send(f, lineptr, len);
2386 break;
2387
2388 #ifndef DISABLE_TLS
2389 case F_TLS:
2390 DPRINTF(D_MISC, "Logging to %s %s\n",
2391 TypeInfo[f->f_type].name,
2392 f->f_un.f_tls.tls_conn->hostname);
2393 /* make sure every message gets queued once
2394 * it will be removed when sendmsg is sent and free()d */
2395 if (!qentry)
2396 qentry = message_queue_add(f, NEWREF(buffer));
2397 (void)tls_send(f, lineptr, len, qentry);
2398 break;
2399 #endif /* !DISABLE_TLS */
2400
2401 case F_PIPE:
2402 DPRINTF(D_MISC, "Logging to %s %s\n",
2403 TypeInfo[f->f_type].name, f->f_un.f_pipe.f_pname);
2404 if (f->f_un.f_pipe.f_pid == 0) {
2405 /* (re-)open */
2406 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
2407 &f->f_un.f_pipe.f_pid)) < 0) {
2408 f->f_type = F_UNUSED;
2409 logerror("%s", f->f_un.f_pipe.f_pname);
2410 message_queue_freeall(f);
2411 break;
2412 } else if (!qentry) /* prevent recursion */
2413 SEND_QUEUE(f);
2414 }
2415 if (writev(f->f_file, iov, v - iov) < 0) {
2416 e = errno;
2417 if (f->f_un.f_pipe.f_pid > 0) {
2418 (void) close(f->f_file);
2419 deadq_enter(f->f_un.f_pipe.f_pid,
2420 f->f_un.f_pipe.f_pname);
2421 }
2422 f->f_un.f_pipe.f_pid = 0;
2423 /*
2424 * If the error was EPIPE, then what is likely
2425 * has happened is we have a command that is
2426 * designed to take a single message line and
2427 * then exit, but we tried to feed it another
2428 * one before we reaped the child and thus
2429 * reset our state.
2430 *
2431 * Well, now we've reset our state, so try opening
2432 * the pipe and sending the message again if EPIPE
2433 * was the error.
2434 */
2435 if (e == EPIPE) {
2436 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
2437 &f->f_un.f_pipe.f_pid)) < 0) {
2438 f->f_type = F_UNUSED;
2439 logerror("%s", f->f_un.f_pipe.f_pname);
2440 message_queue_freeall(f);
2441 break;
2442 }
2443 if (writev(f->f_file, iov, v - iov) < 0) {
2444 e = errno;
2445 if (f->f_un.f_pipe.f_pid > 0) {
2446 (void) close(f->f_file);
2447 deadq_enter(f->f_un.f_pipe.f_pid,
2448 f->f_un.f_pipe.f_pname);
2449 }
2450 f->f_un.f_pipe.f_pid = 0;
2451 error = true; /* enqueue on return */
2452 } else
2453 e = 0;
2454 }
2455 if (e != 0 && !error) {
2456 errno = e;
2457 logerror("%s", f->f_un.f_pipe.f_pname);
2458 }
2459 }
2460 if (e == 0 && qentry) { /* sent buffered msg */
2461 message_queue_remove(f, qentry);
2462 }
2463 break;
2464
2465 case F_CONSOLE:
2466 if (buffer->flags & IGN_CONS) {
2467 DPRINTF(D_MISC, "Logging to %s (ignored)\n",
2468 TypeInfo[f->f_type].name);
2469 break;
2470 }
2471 /* FALLTHROUGH */
2472
2473 case F_TTY:
2474 case F_FILE:
2475 DPRINTF(D_MISC, "Logging to %s %s\n",
2476 TypeInfo[f->f_type].name, f->f_un.f_fname);
2477 again:
2478 if ((f->f_type == F_FILE ? writev(f->f_file, iov, v - iov) :
2479 writev1(f->f_file, iov, v - iov)) < 0) {
2480 e = errno;
2481 if (f->f_type == F_FILE && e == ENOSPC) {
2482 int lasterror = f->f_lasterror;
2483 f->f_lasterror = e;
2484 if (lasterror != e)
2485 logerror("%s", f->f_un.f_fname);
2486 error = true; /* enqueue on return */
2487 }
2488 (void)close(f->f_file);
2489 /*
2490 * Check for errors on TTY's due to loss of tty
2491 */
2492 if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
2493 f->f_file = open(f->f_un.f_fname,
2494 O_WRONLY|O_APPEND|O_NONBLOCK, 0);
2495 if (f->f_file < 0) {
2496 f->f_type = F_UNUSED;
2497 logerror("%s", f->f_un.f_fname);
2498 message_queue_freeall(f);
2499 } else
2500 goto again;
2501 } else {
2502 f->f_type = F_UNUSED;
2503 errno = e;
2504 f->f_lasterror = e;
2505 logerror("%s", f->f_un.f_fname);
2506 message_queue_freeall(f);
2507 }
2508 } else {
2509 f->f_lasterror = 0;
2510 if ((buffer->flags & SYNC_FILE)
2511 && (f->f_flags & FFLAG_SYNC))
2512 (void)fsync(f->f_file);
2513 /* Problem with files: We cannot check beforehand if
2514 * they would be writeable and call send_queue() first.
2515 * So we call send_queue() after a successful write,
2516 * which means the first message will be out of order.
2517 */
2518 if (!qentry) /* prevent recursion */
2519 SEND_QUEUE(f);
2520 else if (qentry) /* sent buffered msg */
2521 message_queue_remove(f, qentry);
2522 }
2523 break;
2524
2525 case F_FIFO:
2526 DPRINTF(D_MISC, "Logging to %s %s\n",
2527 TypeInfo[f->f_type].name, f->f_un.f_fname);
2528 if (f->f_file < 0) {
2529 f->f_file =
2530 open(f->f_un.f_fname, O_WRONLY|O_NONBLOCK, 0);
2531 e = errno;
2532 if (f->f_file < 0 && e == ENXIO) {
2533 /* Drop messages with no reader */
2534 if (qentry)
2535 message_queue_remove(f, qentry);
2536 break;
2537 }
2538 }
2539
2540 if (f->f_file >= 0 && writev(f->f_file, iov, v - iov) < 0) {
2541 e = errno;
2542
2543 /* Enqueue if the fifo buffer is full */
2544 if (e == EAGAIN) {
2545 if (f->f_lasterror != e)
2546 logerror("%s", f->f_un.f_fname);
2547 f->f_lasterror = e;
2548 error = true; /* enqueue on return */
2549 break;
2550 }
2551
2552 close(f->f_file);
2553 f->f_file = -1;
2554
2555 /* Drop messages with no reader */
2556 if (e == EPIPE) {
2557 if (qentry)
2558 message_queue_remove(f, qentry);
2559 break;
2560 }
2561 }
2562
2563 if (f->f_file < 0) {
2564 f->f_type = F_UNUSED;
2565 errno = e;
2566 f->f_lasterror = e;
2567 logerror("%s", f->f_un.f_fname);
2568 message_queue_freeall(f);
2569 break;
2570 }
2571
2572 f->f_lasterror = 0;
2573 if (!qentry) /* prevent recursion (see comment for F_FILE) */
2574 SEND_QUEUE(f);
2575 if (qentry) /* sent buffered msg */
2576 message_queue_remove(f, qentry);
2577 break;
2578
2579 case F_USERS:
2580 case F_WALL:
2581 DPRINTF(D_MISC, "Logging to %s\n", TypeInfo[f->f_type].name);
2582 wallmsg(f, iov, v - iov);
2583 break;
2584 }
2585 f->f_prevcount = 0;
2586
2587 if (error && !qentry)
2588 message_queue_add(f, NEWREF(buffer));
2589 #ifndef DISABLE_SIGN
2590 if (newhash) {
2591 struct signature_group_t *sg;
2592 sg = sign_get_sg(buffer->pri, f);
2593 (void)sign_send_signature_block(sg, false);
2594 }
2595 #endif /* !DISABLE_SIGN */
2596 /* this belongs to the ad-hoc buffer at the first if(buffer) */
2597 DELREF(buffer);
2598 /* TLS frees on its own */
2599 if (f->f_type != F_TLS)
2600 FREEPTR(line);
2601 }
2602
2603 /* send one line by UDP */
2604 void
2605 udp_send(struct filed *f, char *line, size_t len)
2606 {
2607 int lsent, fail, retry, j;
2608 struct addrinfo *r;
2609
2610 DPRINTF((D_NET|D_CALL), "udp_send(f=%p, line=\"%s\", "
2611 "len=%zu) to dest.\n", f, line, len);
2612
2613 if (!finet)
2614 return;
2615
2616 lsent = -1;
2617 fail = 0;
2618 assert(f->f_type == F_FORW);
2619 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
2620 retry = 0;
2621 for (j = 0; j < finet->fd; j++) {
2622 if (finet[j+1].af != r->ai_family)
2623 continue;
2624 sendagain:
2625 lsent = sendto(finet[j+1].fd, line, len, 0,
2626 r->ai_addr, r->ai_addrlen);
2627 if (lsent == -1) {
2628 switch (errno) {
2629 case ENOBUFS:
2630 /* wait/retry/drop */
2631 if (++retry < 5) {
2632 usleep(1000);
2633 goto sendagain;
2634 }
2635 break;
2636 case EHOSTDOWN:
2637 case EHOSTUNREACH:
2638 case ENETDOWN:
2639 /* drop */
2640 break;
2641 default:
2642 /* busted */
2643 fail++;
2644 break;
2645 }
2646 } else if ((size_t)lsent == len)
2647 break;
2648 }
2649 if ((size_t)lsent != len && fail) {
2650 f->f_type = F_UNUSED;
2651 logerror("sendto() failed");
2652 }
2653 }
2654 }
2655
2656 /*
2657 * WALLMSG -- Write a message to the world at large
2658 *
2659 * Write the specified message to either the entire
2660 * world, or a list of approved users.
2661 */
2662 void
2663 wallmsg(struct filed *f, struct iovec *iov, size_t iovcnt)
2664 {
2665 #ifdef __NetBSD_Version__
2666 static int reenter; /* avoid calling ourselves */
2667 int i;
2668 char *p;
2669 struct utmpentry *ep;
2670
2671 if (reenter++)
2672 return;
2673
2674 (void)getutentries(NULL, &ep);
2675 /* NOSTRICT */
2676 for (; ep; ep = ep->next) {
2677 if (f->f_type == F_WALL) {
2678 if ((p = ttymsg(iov, iovcnt, ep->line, TTYMSGTIME))
2679 != NULL) {
2680 errno = 0; /* already in msg */
2681 logerror("%s", p);
2682 }
2683 continue;
2684 }
2685 /* should we send the message to this user? */
2686 for (i = 0; i < MAXUNAMES; i++) {
2687 if (!f->f_un.f_uname[i][0])
2688 break;
2689 if (strcmp(f->f_un.f_uname[i], ep->name) == 0) {
2690 struct stat st;
2691 char tty[MAXPATHLEN];
2692 snprintf(tty, sizeof(tty), "%s/%s", _PATH_DEV,
2693 ep->line);
2694 if (stat(tty, &st) != -1 &&
2695 (st.st_mode & S_IWGRP) == 0)
2696 break;
2697
2698 if ((p = ttymsg(iov, iovcnt, ep->line,
2699 TTYMSGTIME)) != NULL) {
2700 errno = 0; /* already in msg */
2701 logerror("%s", p);
2702 }
2703 break;
2704 }
2705 }
2706 }
2707 reenter = 0;
2708 #endif /* __NetBSD_Version__ */
2709 }
2710
2711 void
2712 /*ARGSUSED*/
2713 reapchild(int fd, short event, void *ev)
2714 {
2715 int status;
2716 pid_t pid;
2717 struct filed *f;
2718
2719 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
2720 if (!Initialized || ShuttingDown) {
2721 /*
2722 * Be silent while we are initializing or
2723 * shutting down.
2724 */
2725 continue;
2726 }
2727
2728 if (deadq_remove(pid))
2729 continue;
2730
2731 /* Now, look in the list of active processes. */
2732 for (f = Files; f != NULL; f = f->f_next) {
2733 if (f->f_type == F_PIPE &&
2734 f->f_un.f_pipe.f_pid == pid) {
2735 (void) close(f->f_file);
2736 f->f_un.f_pipe.f_pid = 0;
2737 log_deadchild(pid, status,
2738 f->f_un.f_pipe.f_pname);
2739 break;
2740 }
2741 }
2742 }
2743 }
2744
2745 /*
2746 * Return a printable representation of a host address (FQDN if available)
2747 */
2748 const char *
2749 cvthname(struct sockaddr_storage *f)
2750 {
2751 int error;
2752 int niflag = NI_DGRAM;
2753 static char host[NI_MAXHOST], ip[NI_MAXHOST];
2754
2755 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
2756 ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
2757
2758 DPRINTF(D_CALL, "cvthname(%s)\n", ip);
2759
2760 if (error) {
2761 DPRINTF(D_NET, "Malformed from address %s\n",
2762 gai_strerror(error));
2763 return "???";
2764 }
2765
2766 if (!UseNameService)
2767 return ip;
2768
2769 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
2770 host, sizeof host, NULL, 0, niflag);
2771 if (error) {
2772 DPRINTF(D_NET, "Host name for your address (%s) unknown\n", ip);
2773 return ip;
2774 }
2775
2776 return host;
2777 }
2778
2779 void
2780 trim_anydomain(char *host)
2781 {
2782 bool onlydigits = true;
2783 int i;
2784
2785 if (!BSDOutputFormat)
2786 return;
2787
2788 /* if non-digits found, then assume hostname and cut at first dot (this
2789 * case also covers IPv6 addresses which should not contain dots),
2790 * if only digits then assume IPv4 address and do not cut at all */
2791 for (i = 0; host[i]; i++) {
2792 if (host[i] == '.' && !onlydigits)
2793 host[i] = '\0';
2794 else if (!isdigit((unsigned char)host[i]) && host[i] != '.')
2795 onlydigits = false;
2796 }
2797 }
2798
2799 static void
2800 /*ARGSUSED*/
2801 domark(int fd, short event, void *ev)
2802 {
2803 struct event *ev_pass = (struct event *)ev;
2804 struct filed *f;
2805 dq_t q, nextq;
2806 sigset_t newmask, omask;
2807
2808 schedule_event(&ev_pass,
2809 &((struct timeval){TIMERINTVL, 0}),
2810 domark, ev_pass);
2811 DPRINTF((D_CALL|D_EVENT), "domark()\n");
2812
2813 BLOCK_SIGNALS(omask, newmask);
2814 now = time(NULL);
2815 MarkSeq += TIMERINTVL;
2816 if (MarkSeq >= MarkInterval) {
2817 logmsg_async(LOG_INFO, NULL, "-- MARK --", ADDDATE|MARK);
2818 MarkSeq = 0;
2819 }
2820
2821 for (f = Files; f; f = f->f_next) {
2822 if (f->f_prevcount && now >= REPEATTIME(f)) {
2823 DPRINTF(D_DATA, "Flush %s: repeated %d times, %d sec.\n",
2824 TypeInfo[f->f_type].name, f->f_prevcount,
2825 repeatinterval[f->f_repeatcount]);
2826 fprintlog(f, NULL, NULL);
2827 BACKOFF(f);
2828 }
2829 }
2830 message_allqueues_check();
2831 RESTORE_SIGNALS(omask);
2832
2833 /* Walk the dead queue, and see if we should signal somebody. */
2834 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = nextq) {
2835 nextq = TAILQ_NEXT(q, dq_entries);
2836 switch (q->dq_timeout) {
2837 case 0:
2838 /* Already signalled once, try harder now. */
2839 if (kill(q->dq_pid, SIGKILL) != 0)
2840 (void) deadq_remove(q->dq_pid);
2841 break;
2842
2843 case 1:
2844 /*
2845 * Timed out on the dead queue, send terminate
2846 * signal. Note that we leave the removal from
2847 * the dead queue to reapchild(), which will
2848 * also log the event (unless the process
2849 * didn't even really exist, in case we simply
2850 * drop it from the dead queue).
2851 */
2852 if (kill(q->dq_pid, SIGTERM) != 0) {
2853 (void) deadq_remove(q->dq_pid);
2854 break;
2855 }
2856 /* FALLTHROUGH */
2857
2858 default:
2859 q->dq_timeout--;
2860 }
2861 }
2862 #ifndef DISABLE_SIGN
2863 if (GlobalSign.rsid) { /* check if initialized */
2864 struct signature_group_t *sg;
2865 STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
2866 sign_send_certificate_block(sg);
2867 }
2868 }
2869 #endif /* !DISABLE_SIGN */
2870 }
2871
2872 /*
2873 * Print syslogd errors some place.
2874 */
2875 void
2876 logerror(const char *fmt, ...)
2877 {
2878 static int logerror_running;
2879 va_list ap;
2880 char tmpbuf[BUFSIZ];
2881 char buf[BUFSIZ];
2882 char *outbuf;
2883
2884 /* If there's an error while trying to log an error, give up. */
2885 if (logerror_running)
2886 return;
2887 logerror_running = 1;
2888
2889 va_start(ap, fmt);
2890 (void)vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
2891 va_end(ap);
2892
2893 if (errno) {
2894 (void)snprintf(buf, sizeof(buf), "%s: %s",
2895 tmpbuf, strerror(errno));
2896 outbuf = buf;
2897 } else {
2898 (void)snprintf(buf, sizeof(buf), "%s", tmpbuf);
2899 outbuf = tmpbuf;
2900 }
2901
2902 if (daemonized)
2903 logmsg_async(LOG_SYSLOG|LOG_ERR, NULL, outbuf, ADDDATE);
2904 if (!daemonized && Debug)
2905 DPRINTF(D_MISC, "%s\n", outbuf);
2906 if (!daemonized && !Debug)
2907 printf("%s: %s\n", getprogname(), outbuf);
2908
2909 logerror_running = 0;
2910 }
2911
2912 /*
2913 * Print syslogd info some place.
2914 */
2915 void
2916 loginfo(const char *fmt, ...)
2917 {
2918 va_list ap;
2919 char buf[BUFSIZ];
2920
2921 va_start(ap, fmt);
2922 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
2923 va_end(ap);
2924
2925 DPRINTF(D_MISC, "%s\n", buf);
2926 logmsg_async(LOG_SYSLOG|LOG_INFO, NULL, buf, ADDDATE);
2927 }
2928
2929 #ifndef DISABLE_TLS
2930 static inline void
2931 free_incoming_tls_sockets(void)
2932 {
2933 struct TLS_Incoming_Conn *tls_in;
2934 int i;
2935
2936 /*
2937 * close all listening and connected TLS sockets
2938 */
2939 if (TLS_Listen_Set)
2940 for (i = 0; i < TLS_Listen_Set->fd; i++) {
2941 if (close(TLS_Listen_Set[i+1].fd) == -1)
2942 logerror("close() failed");
2943 DEL_EVENT(TLS_Listen_Set[i+1].ev);
2944 FREEPTR(TLS_Listen_Set[i+1].ev);
2945 }
2946 FREEPTR(TLS_Listen_Set);
2947 /* close/free incoming TLS connections */
2948 while (!SLIST_EMPTY(&TLS_Incoming_Head)) {
2949 tls_in = SLIST_FIRST(&TLS_Incoming_Head);
2950 SLIST_REMOVE_HEAD(&TLS_Incoming_Head, entries);
2951 FREEPTR(tls_in->inbuf);
2952 free_tls_conn(tls_in->tls_conn);
2953 free(tls_in);
2954 }
2955 }
2956 #endif /* !DISABLE_TLS */
2957
2958 void
2959 /*ARGSUSED*/
2960 die(int fd, short event, void *ev)
2961 {
2962 struct filed *f, *next;
2963 char **p;
2964 sigset_t newmask, omask;
2965 int i;
2966 size_t j;
2967
2968 ShuttingDown = 1; /* Don't log SIGCHLDs. */
2969 /* prevent recursive signals */
2970 BLOCK_SIGNALS(omask, newmask);
2971
2972 errno = 0;
2973 if (ev != NULL)
2974 logerror("Exiting on signal %d", fd);
2975 else
2976 logerror("Fatal error, exiting");
2977
2978 /*
2979 * flush any pending output
2980 */
2981 for (f = Files; f != NULL; f = f->f_next) {
2982 /* flush any pending output */
2983 if (f->f_prevcount)
2984 fprintlog(f, NULL, NULL);
2985 SEND_QUEUE(f);
2986 }
2987
2988 #ifndef DISABLE_TLS
2989 free_incoming_tls_sockets();
2990 #endif /* !DISABLE_TLS */
2991 #ifndef DISABLE_SIGN
2992 sign_global_free();
2993 #endif /* !DISABLE_SIGN */
2994
2995 /*
2996 * Close all open log files.
2997 */
2998 for (f = Files; f != NULL; f = next) {
2999 message_queue_freeall(f);
3000
3001 switch (f->f_type) {
3002 case F_FILE:
3003 case F_TTY:
3004 case F_CONSOLE:
3005 case F_FIFO:
3006 if (f->f_file >= 0)
3007 (void)close(f->f_file);
3008 break;
3009 case F_PIPE:
3010 if (f->f_un.f_pipe.f_pid > 0) {
3011 (void)close(f->f_file);
3012 }
3013 f->f_un.f_pipe.f_pid = 0;
3014 break;
3015 case F_FORW:
3016 if (f->f_un.f_forw.f_addr)
3017 freeaddrinfo(f->f_un.f_forw.f_addr);
3018 break;
3019 #ifndef DISABLE_TLS
3020 case F_TLS:
3021 free_tls_conn(f->f_un.f_tls.tls_conn);
3022 break;
3023 #endif /* !DISABLE_TLS */
3024 }
3025 next = f->f_next;
3026 DELREF(f->f_prevmsg);
3027 FREEPTR(f->f_program);
3028 FREEPTR(f->f_host);
3029 DEL_EVENT(f->f_sq_event);
3030 free((char *)f);
3031 }
3032
3033 /*
3034 * Close all open UDP sockets
3035 */
3036 if (finet) {
3037 for (i = 0; i < finet->fd; i++) {
3038 (void)close(finet[i+1].fd);
3039 DEL_EVENT(finet[i+1].ev);
3040 FREEPTR(finet[i+1].ev);
3041 }
3042 FREEPTR(finet);
3043 }
3044
3045 /* free config options */
3046 for (j = 0; j < A_CNT(TypeInfo); j++) {
3047 FREEPTR(TypeInfo[j].queue_length_string);
3048 FREEPTR(TypeInfo[j].queue_size_string);
3049 }
3050
3051 #ifndef DISABLE_TLS
3052 FREEPTR(tls_opt.CAdir);
3053 FREEPTR(tls_opt.CAfile);
3054 FREEPTR(tls_opt.keyfile);
3055 FREEPTR(tls_opt.certfile);
3056 FREEPTR(tls_opt.x509verify);
3057 FREEPTR(tls_opt.bindhost);
3058 FREEPTR(tls_opt.bindport);
3059 FREEPTR(tls_opt.server);
3060 FREEPTR(tls_opt.gen_cert);
3061 free_cred_SLIST(&tls_opt.cert_head);
3062 free_cred_SLIST(&tls_opt.fprint_head);
3063 FREE_SSL_CTX(tls_opt.global_TLS_CTX);
3064 #endif /* !DISABLE_TLS */
3065
3066 FREEPTR(funix);
3067 for (p = LogPaths; p && *p; p++)
3068 unlink(*p);
3069 exit(0);
3070 }
3071
3072 #ifndef DISABLE_SIGN
3073 /*
3074 * get one "sign_delim_sg2" item, convert and store in ordered queue
3075 */
3076 void
3077 store_sign_delim_sg2(char *tmp_buf)
3078 {
3079 struct string_queue *sqentry, *sqe1, *sqe2;
3080
3081 if(!(sqentry = malloc(sizeof(*sqentry)))) {
3082 logerror("Unable to allocate memory");
3083 return;
3084 }
3085 /*LINTED constcond/null effect */
3086 assert(sizeof(int64_t) == sizeof(uint_fast64_t));
3087 if (dehumanize_number(tmp_buf, (int64_t*) &(sqentry->key)) == -1
3088 || sqentry->key > (LOG_NFACILITIES<<3)) {
3089 DPRINTF(D_PARSE, "invalid sign_delim_sg2: %s\n", tmp_buf);
3090 free(sqentry);
3091 FREEPTR(tmp_buf);
3092 return;
3093 }
3094 sqentry->data = tmp_buf;
3095
3096 if (STAILQ_EMPTY(&GlobalSign.sig2_delims)) {
3097 STAILQ_INSERT_HEAD(&GlobalSign.sig2_delims,
3098 sqentry, entries);
3099 return;
3100 }
3101
3102 /* keep delimiters sorted */
3103 sqe1 = sqe2 = STAILQ_FIRST(&GlobalSign.sig2_delims);
3104 if (sqe1->key > sqentry->key) {
3105 STAILQ_INSERT_HEAD(&GlobalSign.sig2_delims,
3106 sqentry, entries);
3107 return;
3108 }
3109
3110 while ((sqe1 = sqe2)
3111 && (sqe2 = STAILQ_NEXT(sqe1, entries))) {
3112 if (sqe2->key > sqentry->key) {
3113 break;
3114 } else if (sqe2->key == sqentry->key) {
3115 DPRINTF(D_PARSE, "duplicate sign_delim_sg2: %s\n",
3116 tmp_buf);
3117 FREEPTR(sqentry);
3118 FREEPTR(tmp_buf);
3119 return;
3120 }
3121 }
3122 STAILQ_INSERT_AFTER(&GlobalSign.sig2_delims, sqe1, sqentry, entries);
3123 }
3124 #endif /* !DISABLE_SIGN */
3125
3126 /*
3127 * read syslog.conf
3128 */
3129 void
3130 read_config_file(FILE *cf, struct filed **f_ptr)
3131 {
3132 size_t linenum = 0;
3133 size_t i;
3134 struct filed *f, **nextp;
3135 char cline[LINE_MAX];
3136 char prog[NAME_MAX + 1];
3137 char host[MAXHOSTNAMELEN];
3138 const char *p;
3139 char *q;
3140 bool found_keyword;
3141 #ifndef DISABLE_TLS
3142 struct peer_cred *cred = NULL;
3143 struct peer_cred_head *credhead = NULL;
3144 #endif /* !DISABLE_TLS */
3145 #ifndef DISABLE_SIGN
3146 char *sign_sg_str = NULL;
3147 #endif /* !DISABLE_SIGN */
3148 #if (!defined(DISABLE_TLS) || !defined(DISABLE_SIGN))
3149 char *tmp_buf = NULL;
3150 #endif /* (!defined(DISABLE_TLS) || !defined(DISABLE_SIGN)) */
3151 /* central list of recognized configuration keywords
3152 * and an address for their values as strings */
3153 const struct config_keywords {
3154 const char *keyword;
3155 char **variable;
3156 } config_keywords[] = {
3157 #ifndef DISABLE_TLS
3158 /* TLS settings */
3159 {"tls_ca", &tls_opt.CAfile},
3160 {"tls_cadir", &tls_opt.CAdir},
3161 {"tls_cert", &tls_opt.certfile},
3162 {"tls_key", &tls_opt.keyfile},
3163 {"tls_verify", &tls_opt.x509verify},
3164 {"tls_bindport", &tls_opt.bindport},
3165 {"tls_bindhost", &tls_opt.bindhost},
3166 {"tls_server", &tls_opt.server},
3167 {"tls_gen_cert", &tls_opt.gen_cert},
3168 /* special cases in parsing */
3169 {"tls_allow_fingerprints",&tmp_buf},
3170 {"tls_allow_clientcerts", &tmp_buf},
3171 /* buffer settings */
3172 {"tls_queue_length", &TypeInfo[F_TLS].queue_length_string},
3173 {"tls_queue_size", &TypeInfo[F_TLS].queue_size_string},
3174 #endif /* !DISABLE_TLS */
3175 {"file_queue_length", &TypeInfo[F_FILE].queue_length_string},
3176 {"pipe_queue_length", &TypeInfo[F_PIPE].queue_length_string},
3177 {"fifo_queue_length", &TypeInfo[F_FIFO].queue_length_string},
3178 {"file_queue_size", &TypeInfo[F_FILE].queue_size_string},
3179 {"pipe_queue_size", &TypeInfo[F_PIPE].queue_size_string},
3180 {"fifo_queue_size", &TypeInfo[F_FIFO].queue_size_string},
3181 #ifndef DISABLE_SIGN
3182 /* syslog-sign setting */
3183 {"sign_sg", &sign_sg_str},
3184 /* also special case in parsing */
3185 {"sign_delim_sg2", &tmp_buf},
3186 #endif /* !DISABLE_SIGN */
3187 };
3188
3189 DPRINTF(D_CALL, "read_config_file()\n");
3190
3191 /* free all previous config options */
3192 for (i = 0; i < A_CNT(TypeInfo); i++) {
3193 if (TypeInfo[i].queue_length_string
3194 && TypeInfo[i].queue_length_string
3195 != TypeInfo[i].default_length_string) {
3196 FREEPTR(TypeInfo[i].queue_length_string);
3197 TypeInfo[i].queue_length_string =
3198 strdup(TypeInfo[i].default_length_string);
3199 }
3200 if (TypeInfo[i].queue_size_string
3201 && TypeInfo[i].queue_size_string
3202 != TypeInfo[i].default_size_string) {
3203 FREEPTR(TypeInfo[i].queue_size_string);
3204 TypeInfo[i].queue_size_string =
3205 strdup(TypeInfo[i].default_size_string);
3206 }
3207 }
3208 for (i = 0; i < A_CNT(config_keywords); i++)
3209 FREEPTR(*config_keywords[i].variable);
3210 /*
3211 * global settings
3212 */
3213 while (fgets(cline, sizeof(cline), cf) != NULL) {
3214 linenum++;
3215 for (p = cline; isspace((unsigned char)*p); ++p)
3216 continue;
3217 if ((*p == '\0') || (*p == '#'))
3218 continue;
3219
3220 for (i = 0; i < A_CNT(config_keywords); i++) {
3221 if (copy_config_value(config_keywords[i].keyword,
3222 config_keywords[i].variable, &p, ConfFile,
3223 linenum)) {
3224 DPRINTF((D_PARSE|D_MEM),
3225 "found option %s, saved @%p\n",
3226 config_keywords[i].keyword,
3227 *config_keywords[i].variable);
3228 #ifndef DISABLE_SIGN
3229 if (!strcmp("sign_delim_sg2",
3230 config_keywords[i].keyword))
3231 do {
3232 store_sign_delim_sg2(tmp_buf);
3233 } while (copy_config_value_word(
3234 &tmp_buf, &p));
3235
3236 #endif /* !DISABLE_SIGN */
3237
3238 #ifndef DISABLE_TLS
3239 /* special cases with multiple parameters */
3240 if (!strcmp("tls_allow_fingerprints",
3241 config_keywords[i].keyword))
3242 credhead = &tls_opt.fprint_head;
3243 else if (!strcmp("tls_allow_clientcerts",
3244 config_keywords[i].keyword))
3245 credhead = &tls_opt.cert_head;
3246
3247 if (credhead) do {
3248 if(!(cred = malloc(sizeof(*cred)))) {
3249 logerror("Unable to "
3250 "allocate memory");
3251 break;
3252 }
3253 cred->data = tmp_buf;
3254 tmp_buf = NULL;
3255 SLIST_INSERT_HEAD(credhead,
3256 cred, entries);
3257 } while /* additional values? */
3258 (copy_config_value_word(&tmp_buf, &p));
3259 credhead = NULL;
3260 break;
3261 #endif /* !DISABLE_TLS */
3262 }
3263 }
3264 }
3265 /* convert strings to integer values */
3266 for (i = 0; i < A_CNT(TypeInfo); i++) {
3267 if (!TypeInfo[i].queue_length_string
3268 || dehumanize_number(TypeInfo[i].queue_length_string,
3269 &TypeInfo[i].queue_length) == -1)
3270 if (dehumanize_number(TypeInfo[i].default_length_string,
3271 &TypeInfo[i].queue_length) == -1)
3272 abort();
3273 if (!TypeInfo[i].queue_size_string
3274 || dehumanize_number(TypeInfo[i].queue_size_string,
3275 &TypeInfo[i].queue_size) == -1)
3276 if (dehumanize_number(TypeInfo[i].default_size_string,
3277 &TypeInfo[i].queue_size) == -1)
3278 abort();
3279 }
3280
3281 #ifndef DISABLE_SIGN
3282 if (sign_sg_str) {
3283 if (sign_sg_str[1] == '\0'
3284 && (sign_sg_str[0] == '0' || sign_sg_str[0] == '1'
3285 || sign_sg_str[0] == '2' || sign_sg_str[0] == '3'))
3286 GlobalSign.sg = sign_sg_str[0] - '0';
3287 else {
3288 GlobalSign.sg = SIGN_SG;
3289 DPRINTF(D_MISC, "Invalid sign_sg value `%s', "
3290 "use default value `%d'\n",
3291 sign_sg_str, GlobalSign.sg);
3292 }
3293 } else /* disable syslog-sign */
3294 GlobalSign.sg = -1;
3295 #endif /* !DISABLE_SIGN */
3296
3297 rewind(cf);
3298 linenum = 0;
3299 /*
3300 * Foreach line in the conf table, open that file.
3301 */
3302 f = NULL;
3303 nextp = &f;
3304
3305 strcpy(prog, "*");
3306 strcpy(host, "*");
3307 while (fgets(cline, sizeof(cline), cf) != NULL) {
3308 linenum++;
3309 found_keyword = false;
3310 /*
3311 * check for end-of-section, comments, strip off trailing
3312 * spaces and newline character. #!prog is treated specially:
3313 * following lines apply only to that program.
3314 */
3315 for (p = cline; isspace((unsigned char)*p); ++p)
3316 continue;
3317 if (*p == '\0')
3318 continue;
3319 if (*p == '#') {
3320 p++;
3321 if (*p != '!' && *p != '+' && *p != '-')
3322 continue;
3323 }
3324
3325 for (i = 0; i < A_CNT(config_keywords); i++) {
3326 if (!strncasecmp(p, config_keywords[i].keyword,
3327 strlen(config_keywords[i].keyword))) {
3328 DPRINTF(D_PARSE,
3329 "skip cline %zu with keyword %s\n",
3330 linenum, config_keywords[i].keyword);
3331 found_keyword = true;
3332 }
3333 }
3334 if (found_keyword)
3335 continue;
3336
3337 if (*p == '+' || *p == '-') {
3338 host[0] = *p++;
3339 while (isspace((unsigned char)*p))
3340 p++;
3341 if (*p == '\0' || *p == '*') {
3342 strcpy(host, "*");
3343 continue;
3344 }
3345 /* the +hostname expression will continue
3346 * to use the LocalHostName, not the FQDN */
3347 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
3348 if (*p == '@') {
3349 (void)strncpy(&host[i], LocalHostName,
3350 sizeof(host) - 1 - i);
3351 host[sizeof(host) - 1] = '\0';
3352 i = strlen(host) - 1;
3353 p++;
3354 continue;
3355 }
3356 if (!isalnum((unsigned char)*p) &&
3357 *p != '.' && *p != '-' && *p != ',')
3358 break;
3359 host[i] = *p++;
3360 }
3361 host[i] = '\0';
3362 continue;
3363 }
3364 if (*p == '!') {
3365 p++;
3366 while (isspace((unsigned char)*p))
3367 p++;
3368 if (*p == '\0' || *p == '*') {
3369 strcpy(prog, "*");
3370 continue;
3371 }
3372 for (i = 0; i < NAME_MAX; i++) {
3373 if (!isprint((unsigned char)p[i]))
3374 break;
3375 prog[i] = p[i];
3376 }
3377 prog[i] = '\0';
3378 continue;
3379 }
3380 for (q = strchr(cline, '\0'); isspace((unsigned char)*--q);)
3381 continue;
3382 *++q = '\0';
3383 if ((f = calloc(1, sizeof(*f))) == NULL) {
3384 logerror("alloc failed");
3385 die(0, 0, NULL);
3386 }
3387 if (!*f_ptr) *f_ptr = f; /* return first node */
3388 *nextp = f;
3389 nextp = &f->f_next;
3390 cfline(linenum, cline, f, prog, host);
3391 }
3392 }
3393
3394 /*
3395 * INIT -- Initialize syslogd from configuration table
3396 */
3397 void
3398 /*ARGSUSED*/
3399 init(int fd, short event, void *ev)
3400 {
3401 FILE *cf;
3402 int i;
3403 struct filed *f, *newf, **nextp, *f2;
3404 char *p;
3405 sigset_t newmask, omask;
3406 #ifndef DISABLE_TLS
3407 char *tls_status_msg = NULL;
3408 struct peer_cred *cred = NULL;
3409 #endif /* !DISABLE_TLS */
3410
3411 /* prevent recursive signals */
3412 BLOCK_SIGNALS(omask, newmask);
3413
3414 DPRINTF((D_EVENT|D_CALL), "init\n");
3415
3416 /*
3417 * be careful about dependencies and order of actions:
3418 * 1. flush buffer queues
3419 * 2. flush -sign SBs
3420 * 3. flush/delete buffer queue again, in case an SB got there
3421 * 4. close files/connections
3422 */
3423
3424 /*
3425 * flush any pending output
3426 */
3427 for (f = Files; f != NULL; f = f->f_next) {
3428 /* flush any pending output */
3429 if (f->f_prevcount)
3430 fprintlog(f, NULL, NULL);
3431 SEND_QUEUE(f);
3432 }
3433 /* some actions only on SIGHUP and not on first start */
3434 if (Initialized) {
3435 #ifndef DISABLE_SIGN
3436 sign_global_free();
3437 #endif /* !DISABLE_SIGN */
3438 #ifndef DISABLE_TLS
3439 free_incoming_tls_sockets();
3440 #endif /* !DISABLE_TLS */
3441 Initialized = 0;
3442 }
3443 /*
3444 * Close all open log files.
3445 */
3446 for (f = Files; f != NULL; f = f->f_next) {
3447 switch (f->f_type) {
3448 case F_FILE:
3449 case F_TTY:
3450 case F_CONSOLE:
3451 (void)close(f->f_file);
3452 break;
3453 case F_PIPE:
3454 if (f->f_un.f_pipe.f_pid > 0) {
3455 (void)close(f->f_file);
3456 deadq_enter(f->f_un.f_pipe.f_pid,
3457 f->f_un.f_pipe.f_pname);
3458 }
3459 f->f_un.f_pipe.f_pid = 0;
3460 break;
3461 case F_FORW:
3462 if (f->f_un.f_forw.f_addr)
3463 freeaddrinfo(f->f_un.f_forw.f_addr);
3464 break;
3465 #ifndef DISABLE_TLS
3466 case F_TLS:
3467 free_tls_sslptr(f->f_un.f_tls.tls_conn);
3468 break;
3469 #endif /* !DISABLE_TLS */
3470 }
3471 }
3472
3473 /*
3474 * Close all open UDP sockets
3475 */
3476 if (finet) {
3477 for (i = 0; i < finet->fd; i++) {
3478 if (close(finet[i+1].fd) < 0) {
3479 logerror("close() failed");
3480 die(0, 0, NULL);
3481 }
3482 DEL_EVENT(finet[i+1].ev);
3483 FREEPTR(finet[i+1].ev);
3484 }
3485 FREEPTR(finet);
3486 }
3487
3488 /* get FQDN and hostname/domain */
3489 FREEPTR(oldLocalFQDN);
3490 oldLocalFQDN = LocalFQDN;
3491 LocalFQDN = getLocalFQDN();
3492 if ((p = strchr(LocalFQDN, '.')) != NULL)
3493 (void)strlcpy(LocalHostName, LocalFQDN, 1+p-LocalFQDN);
3494 else
3495 (void)strlcpy(LocalHostName, LocalFQDN, sizeof(LocalHostName));
3496
3497 /*
3498 * Reset counter of forwarding actions
3499 */
3500
3501 NumForwards=0;
3502
3503 /* new destination list to replace Files */
3504 newf = NULL;
3505 nextp = &newf;
3506
3507 /* open the configuration file */
3508 if ((cf = fopen(ConfFile, "r")) == NULL) {
3509 DPRINTF(D_FILE, "Cannot open `%s'\n", ConfFile);
3510 *nextp = (struct filed *)calloc(1, sizeof(*f));
3511 cfline(0, "*.ERR\t/dev/console", *nextp, "*", "*");
3512 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
3513 cfline(0, "*.PANIC\t*", (*nextp)->f_next, "*", "*");
3514 Initialized = 1;
3515 RESTORE_SIGNALS(omask);
3516 return;
3517 }
3518
3519 #ifndef DISABLE_TLS
3520 /* init with new TLS_CTX
3521 * as far as I see one cannot change the cert/key of an existing CTX
3522 */
3523 FREE_SSL_CTX(tls_opt.global_TLS_CTX);
3524
3525 free_cred_SLIST(&tls_opt.cert_head);
3526 free_cred_SLIST(&tls_opt.fprint_head);
3527 #endif /* !DISABLE_TLS */
3528
3529 /* read and close configuration file */
3530 read_config_file(cf, &newf);
3531 newf = *nextp;
3532 (void)fclose(cf);
3533 DPRINTF(D_MISC, "read_config_file() returned newf=%p\n", newf);
3534
3535 #define MOVE_QUEUE(dst, src) do { \
3536 struct buf_queue *buf; \
3537 STAILQ_CONCAT(&dst->f_qhead, &src->f_qhead); \
3538 STAILQ_FOREACH(buf, &dst->f_qhead, entries) { \
3539 dst->f_qelements++; \
3540 dst->f_qsize += buf_queue_obj_size(buf); \
3541 } \
3542 src->f_qsize = 0; \
3543 src->f_qelements = 0; \
3544 } while (0)
3545
3546 /*
3547 * Free old log files.
3548 */
3549 for (f = Files; f != NULL;) {
3550 struct filed *ftmp;
3551
3552 /* check if a new logfile is equal, if so pass the queue */
3553 for (f2 = newf; f2 != NULL; f2 = f2->f_next) {
3554 if (f->f_type == f2->f_type
3555 && ((f->f_type == F_PIPE
3556 && !strcmp(f->f_un.f_pipe.f_pname,
3557 f2->f_un.f_pipe.f_pname))
3558 #ifndef DISABLE_TLS
3559 || (f->f_type == F_TLS
3560 && !strcmp(f->f_un.f_tls.tls_conn->hostname,
3561 f2->f_un.f_tls.tls_conn->hostname)
3562 && !strcmp(f->f_un.f_tls.tls_conn->port,
3563 f2->f_un.f_tls.tls_conn->port))
3564 #endif /* !DISABLE_TLS */
3565 || (f->f_type == F_FORW
3566 && !strcmp(f->f_un.f_forw.f_hname,
3567 f2->f_un.f_forw.f_hname)))) {
3568 DPRINTF(D_BUFFER, "move queue from f@%p "
3569 "to f2@%p\n", f, f2);
3570 MOVE_QUEUE(f2, f);
3571 }
3572 }
3573 message_queue_freeall(f);
3574 DELREF(f->f_prevmsg);
3575 #ifndef DISABLE_TLS
3576 if (f->f_type == F_TLS)
3577 free_tls_conn(f->f_un.f_tls.tls_conn);
3578 #endif /* !DISABLE_TLS */
3579 FREEPTR(f->f_program);
3580 FREEPTR(f->f_host);
3581 DEL_EVENT(f->f_sq_event);
3582
3583 ftmp = f->f_next;
3584 free((char *)f);
3585 f = ftmp;
3586 }
3587 Files = newf;
3588 Initialized = 1;
3589
3590 if (Debug) {
3591 for (f = Files; f; f = f->f_next) {
3592 for (i = 0; i <= LOG_NFACILITIES; i++)
3593 if (f->f_pmask[i] == INTERNAL_NOPRI)
3594 printf("X ");
3595 else
3596 printf("%d ", f->f_pmask[i]);
3597 printf("%s: ", TypeInfo[f->f_type].name);
3598 switch (f->f_type) {
3599 case F_FILE:
3600 case F_TTY:
3601 case F_CONSOLE:
3602 case F_FIFO:
3603 printf("%s", f->f_un.f_fname);
3604 break;
3605
3606 case F_FORW:
3607 printf("%s", f->f_un.f_forw.f_hname);
3608 break;
3609 #ifndef DISABLE_TLS
3610 case F_TLS:
3611 printf("[%s]", f->f_un.f_tls.tls_conn->hostname);
3612 break;
3613 #endif /* !DISABLE_TLS */
3614 case F_PIPE:
3615 printf("%s", f->f_un.f_pipe.f_pname);
3616 break;
3617
3618 case F_USERS:
3619 for (i = 0;
3620 i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
3621 printf("%s, ", f->f_un.f_uname[i]);
3622 break;
3623 }
3624 if (f->f_program != NULL)
3625 printf(" (%s)", f->f_program);
3626 printf("\n");
3627 }
3628 }
3629
3630 finet = socksetup(PF_UNSPEC, bindhostname);
3631 if (finet) {
3632 if (SecureMode) {
3633 for (i = 0; i < finet->fd; i++) {
3634 if (shutdown(finet[i+1].fd, SHUT_RD) < 0) {
3635 logerror("shutdown() failed");
3636 die(0, 0, NULL);
3637 }
3638 }
3639 } else
3640 DPRINTF(D_NET, "Listening on inet and/or inet6 socket\n");
3641 DPRINTF(D_NET, "Sending on inet and/or inet6 socket\n");
3642 }
3643
3644 #ifndef DISABLE_TLS
3645 /* TLS setup -- after all local destinations opened */
3646 DPRINTF(D_PARSE, "Parsed options: tls_ca: %s, tls_cadir: %s, "
3647 "tls_cert: %s, tls_key: %s, tls_verify: %s, "
3648 "bind: %s:%s, max. queue_lengths: %"
3649 PRId64 ", %" PRId64 ", %" PRId64 ", "
3650 "max. queue_sizes: %"
3651 PRId64 ", %" PRId64 ", %" PRId64 "\n",
3652 tls_opt.CAfile, tls_opt.CAdir,
3653 tls_opt.certfile, tls_opt.keyfile, tls_opt.x509verify,
3654 tls_opt.bindhost, tls_opt.bindport,
3655 TypeInfo[F_TLS].queue_length, TypeInfo[F_FILE].queue_length,
3656 TypeInfo[F_PIPE].queue_length,
3657 TypeInfo[F_TLS].queue_size, TypeInfo[F_FILE].queue_size,
3658 TypeInfo[F_PIPE].queue_size);
3659 SLIST_FOREACH(cred, &tls_opt.cert_head, entries) {
3660 DPRINTF(D_PARSE, "Accepting peer certificate "
3661 "from file: \"%s\"\n", cred->data);
3662 }
3663 SLIST_FOREACH(cred, &tls_opt.fprint_head, entries) {
3664 DPRINTF(D_PARSE, "Accepting peer certificate with "
3665 "fingerprint: \"%s\"\n", cred->data);
3666 }
3667
3668 /* Note: The order of initialization is important because syslog-sign
3669 * should use the TLS cert for signing. -- So we check first if TLS
3670 * will be used and initialize it before starting -sign.
3671 *
3672 * This means that if we are a client without TLS destinations TLS
3673 * will not be initialized and syslog-sign will generate a new key.
3674 * -- Even if the user has set a usable tls_cert.
3675 * Is this the expected behaviour? The alternative would be to always
3676 * initialize the TLS structures, even if they will not be needed
3677 * (or only needed to read the DSA key for -sign).
3678 */
3679
3680 /* Initialize TLS only if used */
3681 if (tls_opt.server)
3682 tls_status_msg = init_global_TLS_CTX();
3683 else
3684 for (f = Files; f; f = f->f_next) {
3685 if (f->f_type != F_TLS)
3686 continue;
3687 tls_status_msg = init_global_TLS_CTX();
3688 break;
3689 }
3690
3691 #endif /* !DISABLE_TLS */
3692
3693 #ifndef DISABLE_SIGN
3694 /* only initialize -sign if actually used */
3695 if (GlobalSign.sg == 0 || GlobalSign.sg == 1 || GlobalSign.sg == 2)
3696 (void)sign_global_init(Files);
3697 else if (GlobalSign.sg == 3)
3698 for (f = Files; f; f = f->f_next)
3699 if (f->f_flags & FFLAG_SIGN) {
3700 (void)sign_global_init(Files);
3701 break;
3702 }
3703 #endif /* !DISABLE_SIGN */
3704
3705 #ifndef DISABLE_TLS
3706 if (tls_status_msg) {
3707 loginfo("%s", tls_status_msg);
3708 free(tls_status_msg);
3709 }
3710 DPRINTF((D_NET|D_TLS), "Preparing sockets for TLS\n");
3711 TLS_Listen_Set =
3712 socksetup_tls(PF_UNSPEC, tls_opt.bindhost, tls_opt.bindport);
3713
3714 for (f = Files; f; f = f->f_next) {
3715 if (f->f_type != F_TLS)
3716 continue;
3717 if (!tls_connect(f->f_un.f_tls.tls_conn)) {
3718 logerror("Unable to connect to TLS server %s",
3719 f->f_un.f_tls.tls_conn->hostname);
3720 /* Reconnect after x seconds */
3721 schedule_event(&f->f_un.f_tls.tls_conn->event,
3722 &((struct timeval){TLS_RECONNECT_SEC, 0}),
3723 tls_reconnect, f->f_un.f_tls.tls_conn);
3724 }
3725 }
3726 #endif /* !DISABLE_TLS */
3727
3728 loginfo("restart");
3729 /*
3730 * Log a change in hostname, but only on a restart (we detect this
3731 * by checking to see if we're passed a kevent).
3732 */
3733 if (oldLocalFQDN && strcmp(oldLocalFQDN, LocalFQDN) != 0)
3734 loginfo("host name changed, \"%s\" to \"%s\"",
3735 oldLocalFQDN, LocalFQDN);
3736
3737 RESTORE_SIGNALS(omask);
3738 }
3739
3740 /*
3741 * Crack a configuration file line
3742 */
3743 void
3744 cfline(size_t linenum, const char *line, struct filed *f, const char *prog,
3745 const char *host)
3746 {
3747 struct addrinfo hints, *res;
3748 int error, i, pri, syncfile;
3749 const char *p, *q;
3750 char *bp;
3751 char buf[MAXLINE];
3752 struct stat sb;
3753
3754 DPRINTF((D_CALL|D_PARSE),
3755 "cfline(%zu, \"%s\", f, \"%s\", \"%s\")\n",
3756 linenum, line, prog, host);
3757
3758 errno = 0; /* keep strerror() stuff out of logerror messages */
3759
3760 /* clear out file entry */
3761 memset(f, 0, sizeof(*f));
3762 for (i = 0; i <= LOG_NFACILITIES; i++)
3763 f->f_pmask[i] = INTERNAL_NOPRI;
3764 STAILQ_INIT(&f->f_qhead);
3765
3766 /*
3767 * There should not be any space before the log facility.
3768 * Check this is okay, complain and fix if it is not.
3769 */
3770 q = line;
3771 if (isblank((unsigned char)*line)) {
3772 errno = 0;
3773 logerror("Warning: `%s' space or tab before the log facility",
3774 line);
3775 /* Fix: strip all spaces/tabs before the log facility */
3776 while (*q++ && isblank((unsigned char)*q))
3777 /* skip blanks */;
3778 line = q;
3779 }
3780
3781 /*
3782 * q is now at the first char of the log facility
3783 * There should be at least one tab after the log facility
3784 * Check this is okay, and complain and fix if it is not.
3785 */
3786 q = line + strlen(line);
3787 while (!isblank((unsigned char)*q) && (q != line))
3788 q--;
3789 if ((q == line) && strlen(line)) {
3790 /* No tabs or space in a non empty line: complain */
3791 errno = 0;
3792 logerror(
3793 "Error: `%s' log facility or log target missing",
3794 line);
3795 return;
3796 }
3797
3798 /* save host name, if any */
3799 if (*host == '*')
3800 f->f_host = NULL;
3801 else {
3802 f->f_host = strdup(host);
3803 trim_anydomain(&f->f_host[1]); /* skip +/- at beginning */
3804 }
3805
3806 /* save program name, if any */
3807 if (*prog == '*')
3808 f->f_program = NULL;
3809 else
3810 f->f_program = strdup(prog);
3811
3812 /* scan through the list of selectors */
3813 for (p = line; *p && !isblank((unsigned char)*p);) {
3814 int pri_done, pri_cmp, pri_invert;
3815
3816 /* find the end of this facility name list */
3817 for (q = p; *q && !isblank((unsigned char)*q) && *q++ != '.'; )
3818 continue;
3819
3820 /* get the priority comparison */
3821 pri_cmp = 0;
3822 pri_done = 0;
3823 pri_invert = 0;
3824 if (*q == '!') {
3825 pri_invert = 1;
3826 q++;
3827 }
3828 while (! pri_done) {
3829 switch (*q) {
3830 case '<':
3831 pri_cmp = PRI_LT;
3832 q++;
3833 break;
3834 case '=':
3835 pri_cmp = PRI_EQ;
3836 q++;
3837 break;
3838 case '>':
3839 pri_cmp = PRI_GT;
3840 q++;
3841 break;
3842 default:
3843 pri_done = 1;
3844 break;
3845 }
3846 }
3847
3848 /* collect priority name */
3849 for (bp = buf; *q && !strchr("\t ,;", *q); )
3850 *bp++ = *q++;
3851 *bp = '\0';
3852
3853 /* skip cruft */
3854 while (strchr(",;", *q))
3855 q++;
3856
3857 /* decode priority name */
3858 if (*buf == '*') {
3859 pri = LOG_PRIMASK + 1;
3860 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
3861 } else {
3862 pri = decode(buf, prioritynames);
3863 if (pri < 0) {
3864 errno = 0;
3865 logerror("Unknown priority name `%s'", buf);
3866 return;
3867 }
3868 }
3869 if (pri_cmp == 0)
3870 pri_cmp = UniquePriority ? PRI_EQ
3871 : PRI_EQ | PRI_GT;
3872 if (pri_invert)
3873 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
3874
3875 /* scan facilities */
3876 while (*p && !strchr("\t .;", *p)) {
3877 for (bp = buf; *p && !strchr("\t ,;.", *p); )
3878 *bp++ = *p++;
3879 *bp = '\0';
3880 if (*buf == '*')
3881 for (i = 0; i < LOG_NFACILITIES; i++) {
3882 f->f_pmask[i] = pri;
3883 f->f_pcmp[i] = pri_cmp;
3884 }
3885 else {
3886 i = decode(buf, facilitynames);
3887 if (i < 0) {
3888 errno = 0;
3889 logerror("Unknown facility name `%s'",
3890 buf);
3891 return;
3892 }
3893 f->f_pmask[i >> 3] = pri;
3894 f->f_pcmp[i >> 3] = pri_cmp;
3895 }
3896 while (*p == ',' || *p == ' ')
3897 p++;
3898 }
3899
3900 p = q;
3901 }
3902
3903 /* skip to action part */
3904 while (isblank((unsigned char)*p))
3905 p++;
3906
3907 /*
3908 * should this be "#ifndef DISABLE_SIGN" or is it a general option?
3909 * '+' before file destination: write with PRI field for later
3910 * verification
3911 */
3912 if (*p == '+') {
3913 f->f_flags |= FFLAG_FULL;
3914 p++;
3915 }
3916 if (*p == '-') {
3917 syncfile = 0;
3918 p++;
3919 } else
3920 syncfile = 1;
3921
3922 switch (*p) {
3923 case '@':
3924 #ifndef DISABLE_SIGN
3925 if (GlobalSign.sg == 3)
3926 f->f_flags |= FFLAG_SIGN;
3927 #endif /* !DISABLE_SIGN */
3928 #ifndef DISABLE_TLS
3929 if (*(p+1) == '[') {
3930 /* TLS destination */
3931 if (!parse_tls_destination(p, f, linenum)) {
3932 logerror("Unable to parse action %s", p);
3933 break;
3934 }
3935 f->f_type = F_TLS;
3936 break;
3937 }
3938 #endif /* !DISABLE_TLS */
3939 (void)strlcpy(f->f_un.f_forw.f_hname, ++p,
3940 sizeof(f->f_un.f_forw.f_hname));
3941 memset(&hints, 0, sizeof(hints));
3942 hints.ai_family = AF_UNSPEC;
3943 hints.ai_socktype = SOCK_DGRAM;
3944 hints.ai_protocol = 0;
3945 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
3946 &res);
3947 if (error) {
3948 errno = 0;
3949 logerror("%s", gai_strerror(error));
3950 break;
3951 }
3952 f->f_un.f_forw.f_addr = res;
3953 f->f_type = F_FORW;
3954 NumForwards++;
3955 break;
3956
3957 case '/':
3958 #ifndef DISABLE_SIGN
3959 if (GlobalSign.sg == 3)
3960 f->f_flags |= FFLAG_SIGN;
3961 #endif /* !DISABLE_SIGN */
3962 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
3963 if ((f->f_file = open(p, O_WRONLY|O_APPEND|O_NONBLOCK, 0)) < 0)
3964 {
3965 f->f_type = F_UNUSED;
3966 logerror("%s", p);
3967 break;
3968 }
3969 if (!fstat(f->f_file, &sb) && S_ISFIFO(sb.st_mode)) {
3970 f->f_file = -1;
3971 f->f_type = F_FIFO;
3972 break;
3973 }
3974
3975 if (isatty(f->f_file)) {
3976 f->f_type = F_TTY;
3977 if (strcmp(p, ctty) == 0)
3978 f->f_type = F_CONSOLE;
3979 } else
3980 f->f_type = F_FILE;
3981
3982 if (syncfile)
3983 f->f_flags |= FFLAG_SYNC;
3984 break;
3985
3986 case '|':
3987 #ifndef DISABLE_SIGN
3988 if (GlobalSign.sg == 3)
3989 f->f_flags |= FFLAG_SIGN;
3990 #endif
3991 f->f_un.f_pipe.f_pid = 0;
3992 (void) strlcpy(f->f_un.f_pipe.f_pname, p + 1,
3993 sizeof(f->f_un.f_pipe.f_pname));
3994 f->f_type = F_PIPE;
3995 break;
3996
3997 case '*':
3998 f->f_type = F_WALL;
3999 break;
4000
4001 default:
4002 for (i = 0; i < MAXUNAMES && *p; i++) {
4003 for (q = p; *q && *q != ','; )
4004 q++;
4005 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
4006 if ((q - p) > UT_NAMESIZE)
4007 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
4008 else
4009 f->f_un.f_uname[i][q - p] = '\0';
4010 while (*q == ',' || *q == ' ')
4011 q++;
4012 p = q;
4013 }
4014 f->f_type = F_USERS;
4015 break;
4016 }
4017 }
4018
4019
4020 /*
4021 * Decode a symbolic name to a numeric value
4022 */
4023 int
4024 decode(const char *name, CODE *codetab)
4025 {
4026 CODE *c;
4027 char *p, buf[40];
4028
4029 if (isdigit((unsigned char)*name))
4030 return atoi(name);
4031
4032 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
4033 if (isupper((unsigned char)*name))
4034 *p = tolower((unsigned char)*name);
4035 else
4036 *p = *name;
4037 }
4038 *p = '\0';
4039 for (c = codetab; c->c_name; c++)
4040 if (!strcmp(buf, c->c_name))
4041 return c->c_val;
4042
4043 return -1;
4044 }
4045
4046 /*
4047 * Retrieve the size of the kernel message buffer, via sysctl.
4048 */
4049 int
4050 getmsgbufsize(void)
4051 {
4052 #ifdef __NetBSD_Version__
4053 int msgbufsize, mib[2];
4054 size_t size;
4055
4056 mib[0] = CTL_KERN;
4057 mib[1] = KERN_MSGBUFSIZE;
4058 size = sizeof msgbufsize;
4059 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
4060 DPRINTF(D_MISC, "Couldn't get kern.msgbufsize\n");
4061 return 0;
4062 }
4063 return msgbufsize;
4064 #else
4065 return MAXLINE;
4066 #endif /* __NetBSD_Version__ */
4067 }
4068
4069 /*
4070 * Retrieve the hostname, via sysctl.
4071 */
4072 char *
4073 getLocalFQDN(void)
4074 {
4075 int mib[2];
4076 char *hostname;
4077 size_t len;
4078
4079 mib[0] = CTL_KERN;
4080 mib[1] = KERN_HOSTNAME;
4081 sysctl(mib, 2, NULL, &len, NULL, 0);
4082
4083 if (!(hostname = malloc(len))) {
4084 logerror("Unable to allocate memory");
4085 die(0,0,NULL);
4086 } else if (sysctl(mib, 2, hostname, &len, NULL, 0) == -1) {
4087 DPRINTF(D_MISC, "Couldn't get kern.hostname\n");
4088 (void)gethostname(hostname, sizeof(len));
4089 }
4090 return hostname;
4091 }
4092
4093 struct socketEvent *
4094 socksetup(int af, const char *hostname)
4095 {
4096 struct addrinfo hints, *res, *r;
4097 int error, maxs;
4098 int on = 1;
4099 struct socketEvent *s, *socks;
4100
4101 if(SecureMode && !NumForwards)
4102 return NULL;
4103
4104 memset(&hints, 0, sizeof(hints));
4105 hints.ai_flags = AI_PASSIVE;
4106 hints.ai_family = af;
4107 hints.ai_socktype = SOCK_DGRAM;
4108 error = getaddrinfo(hostname, "syslog", &hints, &res);
4109 if (error) {
4110 errno = 0;
4111 logerror("%s", gai_strerror(error));
4112 die(0, 0, NULL);
4113 }
4114
4115 /* Count max number of sockets we may open */
4116 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
4117 continue;
4118 socks = calloc(maxs+1, sizeof(*socks));
4119 if (!socks) {
4120 logerror("Couldn't allocate memory for sockets");
4121 die(0, 0, NULL);
4122 }
4123
4124 socks->fd = 0; /* num of sockets counter at start of array */
4125 s = socks + 1;
4126 for (r = res; r; r = r->ai_next) {
4127 s->fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
4128 if (s->fd < 0) {
4129 logerror("socket() failed");
4130 continue;
4131 }
4132 s->af = r->ai_family;
4133 if (r->ai_family == AF_INET6 && setsockopt(s->fd, IPPROTO_IPV6,
4134 IPV6_V6ONLY, &on, sizeof(on)) < 0) {
4135 logerror("setsockopt(IPV6_V6ONLY) failed");
4136 close(s->fd);
4137 continue;
4138 }
4139
4140 if (!SecureMode) {
4141 if (bind(s->fd, r->ai_addr, r->ai_addrlen) < 0) {
4142 logerror("bind() failed");
4143 close(s->fd);
4144 continue;
4145 }
4146 s->ev = allocev();
4147 event_set(s->ev, s->fd, EV_READ | EV_PERSIST,
4148 dispatch_read_finet, s->ev);
4149 if (event_add(s->ev, NULL) == -1) {
4150 DPRINTF((D_EVENT|D_NET),
4151 "Failure in event_add()\n");
4152 } else {
4153 DPRINTF((D_EVENT|D_NET),
4154 "Listen on UDP port "
4155 "(event@%p)\n", s->ev);
4156 }
4157 }
4158
4159 socks->fd++; /* num counter */
4160 s++;
4161 }
4162
4163 if (res)
4164 freeaddrinfo(res);
4165 if (socks->fd == 0) {
4166 free (socks);
4167 if(Debug)
4168 return NULL;
4169 else
4170 die(0, 0, NULL);
4171 }
4172 return socks;
4173 }
4174
4175 /*
4176 * Fairly similar to popen(3), but returns an open descriptor, as opposed
4177 * to a FILE *.
4178 */
4179 int
4180 p_open(char *prog, pid_t *rpid)
4181 {
4182 static char sh[] = "sh", mc[] = "-c";
4183 int pfd[2], nulldesc, i;
4184 pid_t pid;
4185 char *argv[4]; /* sh -c cmd NULL */
4186
4187 if (pipe(pfd) == -1)
4188 return -1;
4189 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) {
4190 /* We are royally screwed anyway. */
4191 return -1;
4192 }
4193
4194 switch ((pid = fork())) {
4195 case -1:
4196 (void) close(nulldesc);
4197 return -1;
4198
4199 case 0:
4200 argv[0] = sh;
4201 argv[1] = mc;
4202 argv[2] = prog;
4203 argv[3] = NULL;
4204
4205 (void) setsid(); /* avoid catching SIGHUPs. */
4206
4207 /*
4208 * Reset ignored signals to their default behavior.
4209 */
4210 (void)signal(SIGTERM, SIG_DFL);
4211 (void)signal(SIGINT, SIG_DFL);
4212 (void)signal(SIGQUIT, SIG_DFL);
4213 (void)signal(SIGPIPE, SIG_DFL);
4214 (void)signal(SIGHUP, SIG_DFL);
4215
4216 dup2(pfd[0], STDIN_FILENO);
4217 dup2(nulldesc, STDOUT_FILENO);
4218 dup2(nulldesc, STDERR_FILENO);
4219 for (i = getdtablesize(); i > 2; i--)
4220 (void) close(i);
4221
4222 (void) execvp(_PATH_BSHELL, argv);
4223 _exit(255);
4224 }
4225
4226 (void) close(nulldesc);
4227 (void) close(pfd[0]);
4228
4229 /*
4230 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
4231 * supposed to get an EWOULDBLOCK on writev(2), which is
4232 * caught by the logic above anyway, which will in turn
4233 * close the pipe, and fork a new logging subprocess if
4234 * necessary. The stale subprocess will be killed some
4235 * time later unless it terminated itself due to closing
4236 * its input pipe.
4237 */
4238 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
4239 /* This is bad. */
4240 logerror("Warning: cannot change pipe to pid %d to "
4241 "non-blocking.", (int) pid);
4242 }
4243 *rpid = pid;
4244 return pfd[1];
4245 }
4246
4247 void
4248 deadq_enter(pid_t pid, const char *name)
4249 {
4250 dq_t p;
4251 int status;
4252
4253 /*
4254 * Be paranoid: if we can't signal the process, don't enter it
4255 * into the dead queue (perhaps it's already dead). If possible,
4256 * we try to fetch and log the child's status.
4257 */
4258 if (kill(pid, 0) != 0) {
4259 if (waitpid(pid, &status, WNOHANG) > 0)
4260 log_deadchild(pid, status, name);
4261 return;
4262 }
4263
4264 p = malloc(sizeof(*p));
4265 if (p == NULL) {
4266 logerror("panic: out of memory!");
4267 exit(1);
4268 }
4269
4270 p->dq_pid = pid;
4271 p->dq_timeout = DQ_TIMO_INIT;
4272 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
4273 }
4274
4275 int
4276 deadq_remove(pid_t pid)
4277 {
4278 dq_t q;
4279
4280 for (q = TAILQ_FIRST(&deadq_head); q != NULL;
4281 q = TAILQ_NEXT(q, dq_entries)) {
4282 if (q->dq_pid == pid) {
4283 TAILQ_REMOVE(&deadq_head, q, dq_entries);
4284 free(q);
4285 return 1;
4286 }
4287 }
4288 return 0;
4289 }
4290
4291 void
4292 log_deadchild(pid_t pid, int status, const char *name)
4293 {
4294 int code;
4295 char buf[256];
4296 const char *reason;
4297
4298 /* Keep strerror() struff out of logerror messages. */
4299 errno = 0;
4300 if (WIFSIGNALED(status)) {
4301 reason = "due to signal";
4302 code = WTERMSIG(status);
4303 } else {
4304 reason = "with status";
4305 code = WEXITSTATUS(status);
4306 if (code == 0)
4307 return;
4308 }
4309 (void) snprintf(buf, sizeof(buf),
4310 "Logging subprocess %d (%s) exited %s %d.",
4311 pid, name, reason, code);
4312 logerror("%s", buf);
4313 }
4314
4315 struct event *
4316 allocev(void)
4317 {
4318 struct event *ev;
4319
4320 if (!(ev = calloc(1, sizeof(*ev))))
4321 logerror("Unable to allocate memory");
4322 return ev;
4323 }
4324
4325 /* *ev is allocated if necessary */
4326 void
4327 schedule_event(struct event **ev, struct timeval *tv,
4328 void (*cb)(int, short, void *), void *arg)
4329 {
4330 if (!*ev && !(*ev = allocev())) {
4331 return;
4332 }
4333 event_set(*ev, 0, 0, cb, arg);
4334 DPRINTF(D_EVENT, "event_add(%s@%p)\n", "schedule_ev", *ev); \
4335 if (event_add(*ev, tv) == -1) {
4336 DPRINTF(D_EVENT, "Failure in event_add()\n");
4337 }
4338 }
4339
4340 #ifndef DISABLE_TLS
4341 /* abbreviation for freeing credential lists */
4342 void
4343 free_cred_SLIST(struct peer_cred_head *head)
4344 {
4345 struct peer_cred *cred;
4346
4347 while (!SLIST_EMPTY(head)) {
4348 cred = SLIST_FIRST(head);
4349 SLIST_REMOVE_HEAD(head, entries);
4350 FREEPTR(cred->data);
4351 free(cred);
4352 }
4353 }
4354 #endif /* !DISABLE_TLS */
4355
4356 /*
4357 * send message queue after reconnect
4358 */
4359 /*ARGSUSED*/
4360 void
4361 send_queue(int fd, short event, void *arg)
4362 {
4363 struct filed *f = (struct filed *) arg;
4364 struct buf_queue *qentry;
4365 #define SQ_CHUNK_SIZE 250
4366 size_t cnt = 0;
4367
4368 #ifndef DISABLE_TLS
4369 if (f->f_type == F_TLS) {
4370 /* use a flag to prevent recursive calls to send_queue() */
4371 if (f->f_un.f_tls.tls_conn->send_queue)
4372 return;
4373 else
4374 f->f_un.f_tls.tls_conn->send_queue = true;
4375 }
4376 DPRINTF((D_DATA|D_CALL), "send_queue(f@%p with %zu msgs, "
4377 "cnt@%p = %zu)\n", f, f->f_qelements, &cnt, cnt);
4378 #endif /* !DISABLE_TLS */
4379
4380 while ((qentry = STAILQ_FIRST(&f->f_qhead))) {
4381 #ifndef DISABLE_TLS
4382 /* send_queue() might be called with an unconnected destination
4383 * from init() or die() or one message might take longer,
4384 * leaving the connection in state ST_WAITING and thus not
4385 * ready for the next message.
4386 * this check is a shortcut to skip these unnecessary calls */
4387 if (f->f_type == F_TLS
4388 && f->f_un.f_tls.tls_conn->state != ST_TLS_EST) {
4389 DPRINTF(D_TLS, "abort send_queue(cnt@%p = %zu) "
4390 "on TLS connection in state %d\n",
4391 &cnt, cnt, f->f_un.f_tls.tls_conn->state);
4392 return;
4393 }
4394 #endif /* !DISABLE_TLS */
4395 fprintlog(f, qentry->msg, qentry);
4396
4397 /* Sending a long queue can take some time during which
4398 * SIGHUP and SIGALRM are blocked and no events are handled.
4399 * To avoid that we only send SQ_CHUNK_SIZE messages at once
4400 * and then reschedule ourselves to continue. Thus the control
4401 * will return first from all signal-protected functions so a
4402 * possible SIGHUP/SIGALRM is handled and then back to the
4403 * main loop which can handle possible input.
4404 */
4405 if (++cnt >= SQ_CHUNK_SIZE) {
4406 if (!f->f_sq_event) { /* alloc on demand */
4407 f->f_sq_event = allocev();
4408 event_set(f->f_sq_event, 0, 0, send_queue, f);
4409 }
4410 if (event_add(f->f_sq_event, &((struct timeval){0, 1})) == -1) {
4411 DPRINTF(D_EVENT, "Failure in event_add()\n");
4412 }
4413 break;
4414 }
4415 }
4416 #ifndef DISABLE_TLS
4417 if (f->f_type == F_TLS)
4418 f->f_un.f_tls.tls_conn->send_queue = false;
4419 #endif
4420
4421 }
4422
4423 /*
4424 * finds the next queue element to delete
4425 *
4426 * has stateful behaviour, before using it call once with reset = true
4427 * after that every call will return one next queue elemen to delete,
4428 * depending on strategy either the oldest or the one with the lowest priority
4429 */
4430 static struct buf_queue *
4431 find_qentry_to_delete(const struct buf_queue_head *head, int strategy,
4432 bool reset)
4433 {
4434 static int pri;
4435 static struct buf_queue *qentry_static;
4436
4437 struct buf_queue *qentry_tmp;
4438
4439 if (reset || STAILQ_EMPTY(head)) {
4440 pri = LOG_DEBUG;
4441 qentry_static = STAILQ_FIRST(head);
4442 return NULL;
4443 }
4444
4445 /* find elements to delete */
4446 if (strategy == PURGE_BY_PRIORITY) {
4447 qentry_tmp = qentry_static;
4448 if (!qentry_tmp) return NULL;
4449 while ((qentry_tmp = STAILQ_NEXT(qentry_tmp, entries)) != NULL)
4450 {
4451 if (LOG_PRI(qentry_tmp->msg->pri) == pri) {
4452 /* save the successor, because qentry_tmp
4453 * is probably deleted by the caller */
4454 qentry_static = STAILQ_NEXT(qentry_tmp, entries);
4455 return qentry_tmp;
4456 }
4457 }
4458 /* nothing found in while loop --> next pri */
4459 if (--pri)
4460 return find_qentry_to_delete(head, strategy, false);
4461 else
4462 return NULL;
4463 } else /* strategy == PURGE_OLDEST or other value */ {
4464 qentry_tmp = qentry_static;
4465 qentry_static = STAILQ_NEXT(qentry_tmp, entries);
4466 return qentry_tmp; /* is NULL on empty queue */
4467 }
4468 }
4469
4470 /* note on TAILQ: newest message added at TAIL,
4471 * oldest to be removed is FIRST
4472 */
4473 /*
4474 * checks length of a destination's message queue
4475 * if del_entries == 0 then assert queue length is
4476 * less or equal to configured number of queue elements
4477 * otherwise del_entries tells how many entries to delete
4478 *
4479 * returns the number of removed queue elements
4480 * (which not necessarily means free'd messages)
4481 *
4482 * strategy PURGE_OLDEST to delete oldest entry, e.g. after it was resent
4483 * strategy PURGE_BY_PRIORITY to delete messages with lowest priority first,
4484 * this is much slower but might be desirable when unsent messages have
4485 * to be deleted, e.g. in call from domark()
4486 */
4487 size_t
4488 message_queue_purge(struct filed *f, size_t del_entries, int strategy)
4489 {
4490 size_t removed = 0;
4491 struct buf_queue *qentry = NULL;
4492
4493 DPRINTF((D_CALL|D_BUFFER), "purge_message_queue(%p, %zu, %d) with "
4494 "f_qelements=%zu and f_qsize=%zu\n",
4495 f, del_entries, strategy,
4496 f->f_qelements, f->f_qsize);
4497
4498 /* reset state */
4499 (void)find_qentry_to_delete(&f->f_qhead, strategy, true);
4500
4501 while (removed < del_entries
4502 || (TypeInfo[f->f_type].queue_length != -1
4503 && (size_t)TypeInfo[f->f_type].queue_length <= f->f_qelements)
4504 || (TypeInfo[f->f_type].queue_size != -1
4505 && (size_t)TypeInfo[f->f_type].queue_size <= f->f_qsize)) {
4506 qentry = find_qentry_to_delete(&f->f_qhead, strategy, 0);
4507 if (message_queue_remove(f, qentry))
4508 removed++;
4509 else
4510 break;
4511 }
4512 return removed;
4513 }
4514
4515 /* run message_queue_purge() for all destinations to free memory */
4516 size_t
4517 message_allqueues_purge(void)
4518 {
4519 size_t sum = 0;
4520 struct filed *f;
4521
4522 for (f = Files; f; f = f->f_next)
4523 sum += message_queue_purge(f,
4524 f->f_qelements/10, PURGE_BY_PRIORITY);
4525
4526 DPRINTF(D_BUFFER,
4527 "message_allqueues_purge(): removed %zu buffer entries\n", sum);
4528 return sum;
4529 }
4530
4531 /* run message_queue_purge() for all destinations to check limits */
4532 size_t
4533 message_allqueues_check(void)
4534 {
4535 size_t sum = 0;
4536 struct filed *f;
4537
4538 for (f = Files; f; f = f->f_next)
4539 sum += message_queue_purge(f, 0, PURGE_BY_PRIORITY);
4540 DPRINTF(D_BUFFER,
4541 "message_allqueues_check(): removed %zu buffer entries\n", sum);
4542 return sum;
4543 }
4544
4545 struct buf_msg *
4546 buf_msg_new(const size_t len)
4547 {
4548 struct buf_msg *newbuf;
4549
4550 CALLOC(newbuf, sizeof(*newbuf));
4551
4552 if (len) { /* len = 0 is valid */
4553 MALLOC(newbuf->msg, len);
4554 newbuf->msgorig = newbuf->msg;
4555 newbuf->msgsize = len;
4556 }
4557 return NEWREF(newbuf);
4558 }
4559
4560 void
4561 buf_msg_free(struct buf_msg *buf)
4562 {
4563 if (!buf)
4564 return;
4565
4566 buf->refcount--;
4567 if (buf->refcount == 0) {
4568 FREEPTR(buf->timestamp);
4569 /* small optimizations: the host/recvhost may point to the
4570 * global HostName/FQDN. of course this must not be free()d
4571 * same goes for appname and include_pid
4572 */
4573 if (buf->recvhost != buf->host
4574 && buf->recvhost != LocalHostName
4575 && buf->recvhost != LocalFQDN
4576 && buf->recvhost != oldLocalFQDN)
4577 FREEPTR(buf->recvhost);
4578 if (buf->host != LocalHostName
4579 && buf->host != LocalFQDN
4580 && buf->host != oldLocalFQDN)
4581 FREEPTR(buf->host);
4582 if (buf->prog != appname)
4583 FREEPTR(buf->prog);
4584 if (buf->pid != include_pid)
4585 FREEPTR(buf->pid);
4586 FREEPTR(buf->msgid);
4587 FREEPTR(buf->sd);
4588 FREEPTR(buf->msgorig); /* instead of msg */
4589 FREEPTR(buf);
4590 }
4591 }
4592
4593 size_t
4594 buf_queue_obj_size(struct buf_queue *qentry)
4595 {
4596 size_t sum = 0;
4597
4598 if (!qentry)
4599 return 0;
4600 sum += sizeof(*qentry)
4601 + sizeof(*qentry->msg)
4602 + qentry->msg->msgsize
4603 + SAFEstrlen(qentry->msg->timestamp)+1
4604 + SAFEstrlen(qentry->msg->msgid)+1;
4605 if (qentry->msg->prog
4606 && qentry->msg->prog != include_pid)
4607 sum += strlen(qentry->msg->prog)+1;
4608 if (qentry->msg->pid
4609 && qentry->msg->pid != appname)
4610 sum += strlen(qentry->msg->pid)+1;
4611 if (qentry->msg->recvhost
4612 && qentry->msg->recvhost != LocalHostName
4613 && qentry->msg->recvhost != LocalFQDN
4614 && qentry->msg->recvhost != oldLocalFQDN)
4615 sum += strlen(qentry->msg->recvhost)+1;
4616 if (qentry->msg->host
4617 && qentry->msg->host != LocalHostName
4618 && qentry->msg->host != LocalFQDN
4619 && qentry->msg->host != oldLocalFQDN)
4620 sum += strlen(qentry->msg->host)+1;
4621
4622 return sum;
4623 }
4624
4625 bool
4626 message_queue_remove(struct filed *f, struct buf_queue *qentry)
4627 {
4628 if (!f || !qentry || !qentry->msg)
4629 return false;
4630
4631 assert(!STAILQ_EMPTY(&f->f_qhead));
4632 STAILQ_REMOVE(&f->f_qhead, qentry, buf_queue, entries);
4633 f->f_qelements--;
4634 f->f_qsize -= buf_queue_obj_size(qentry);
4635
4636 DPRINTF(D_BUFFER, "msg @%p removed from queue @%p, new qlen = %zu\n",
4637 qentry->msg, f, f->f_qelements);
4638 DELREF(qentry->msg);
4639 FREEPTR(qentry);
4640 return true;
4641 }
4642
4643 /*
4644 * returns *qentry on success and NULL on error
4645 */
4646 struct buf_queue *
4647 message_queue_add(struct filed *f, struct buf_msg *buffer)
4648 {
4649 struct buf_queue *qentry;
4650
4651 /* check on every call or only every n-th time? */
4652 message_queue_purge(f, 0, PURGE_BY_PRIORITY);
4653
4654 while (!(qentry = malloc(sizeof(*qentry)))
4655 && message_queue_purge(f, 1, PURGE_OLDEST))
4656 continue;
4657 if (!qentry) {
4658 logerror("Unable to allocate memory");
4659 DPRINTF(D_BUFFER, "queue empty, no memory, msg dropped\n");
4660 return NULL;
4661 } else {
4662 qentry->msg = buffer;
4663 f->f_qelements++;
4664 f->f_qsize += buf_queue_obj_size(qentry);
4665 STAILQ_INSERT_TAIL(&f->f_qhead, qentry, entries);
4666
4667 DPRINTF(D_BUFFER, "msg @%p queued @%p, qlen = %zu\n",
4668 buffer, f, f->f_qelements);
4669 return qentry;
4670 }
4671 }
4672
4673 void
4674 message_queue_freeall(struct filed *f)
4675 {
4676 struct buf_queue *qentry;
4677
4678 if (!f) return;
4679 DPRINTF(D_MEM, "message_queue_freeall(f@%p) with f_qhead@%p\n", f,
4680 &f->f_qhead);
4681
4682 while (!STAILQ_EMPTY(&f->f_qhead)) {
4683 qentry = STAILQ_FIRST(&f->f_qhead);
4684 STAILQ_REMOVE(&f->f_qhead, qentry, buf_queue, entries);
4685 DELREF(qentry->msg);
4686 FREEPTR(qentry);
4687 }
4688
4689 f->f_qelements = 0;
4690 f->f_qsize = 0;
4691 }
4692
4693 #ifndef DISABLE_TLS
4694 /* utility function for tls_reconnect() */
4695 struct filed *
4696 get_f_by_conninfo(struct tls_conn_settings *conn_info)
4697 {
4698 struct filed *f;
4699
4700 for (f = Files; f; f = f->f_next) {
4701 if ((f->f_type == F_TLS) && f->f_un.f_tls.tls_conn == conn_info)
4702 return f;
4703 }
4704 DPRINTF(D_TLS, "get_f_by_conninfo() called on invalid conn_info\n");
4705 return NULL;
4706 }
4707
4708 /*
4709 * Called on signal.
4710 * Lets the admin reconnect without waiting for the reconnect timer expires.
4711 */
4712 /*ARGSUSED*/
4713 void
4714 dispatch_force_tls_reconnect(int fd, short event, void *ev)
4715 {
4716 struct filed *f;
4717 DPRINTF((D_TLS|D_CALL|D_EVENT), "dispatch_force_tls_reconnect()\n");
4718 for (f = Files; f; f = f->f_next) {
4719 if (f->f_type == F_TLS &&
4720 f->f_un.f_tls.tls_conn->state == ST_NONE)
4721 tls_reconnect(fd, event, f->f_un.f_tls.tls_conn);
4722 }
4723 }
4724 #endif /* !DISABLE_TLS */
4725
4726 /*
4727 * return a timestamp in a static buffer,
4728 * either format the timestamp given by parameter in_now
4729 * or use the current time if in_now is NULL.
4730 */
4731 char *
4732 make_timestamp(time_t *in_now, bool iso, size_t tlen)
4733 {
4734 int frac_digits = 6;
4735 struct timeval tv;
4736 time_t mytime;
4737 struct tm ltime;
4738 int len = 0;
4739 int tzlen = 0;
4740 /* uses global var: time_t now; */
4741
4742 if (in_now) {
4743 mytime = *in_now;
4744 } else {
4745 gettimeofday(&tv, NULL);
4746 mytime = now = tv.tv_sec;
4747 }
4748
4749 if (!iso) {
4750 strlcpy(timestamp, ctime(&mytime) + 4, sizeof(timestamp));
4751 timestamp[BSD_TIMESTAMPLEN] = '\0';
4752 } else {
4753 localtime_r(&mytime, <ime);
4754 len += strftime(timestamp, sizeof(timestamp), "%FT%T", <ime);
4755 snprintf(×tamp[len], frac_digits + 2, ".%.*jd",
4756 frac_digits, (intmax_t)tv.tv_usec);
4757 len += frac_digits + 1;
4758 tzlen = strftime(×tamp[len], sizeof(timestamp) - len, "%z",
4759 <ime);
4760 len += tzlen;
4761
4762 if (tzlen == 5) {
4763 /* strftime gives "+0200", but we need "+02:00" */
4764 timestamp[len + 2] = '\0';
4765 timestamp[len + 1] = timestamp[len];
4766 timestamp[len] = timestamp[len - 1];
4767 timestamp[len - 1] = timestamp[len - 2];
4768 timestamp[len - 2] = ':';
4769 }
4770 }
4771
4772 switch (tlen) {
4773 case (size_t)-1:
4774 return timestamp;
4775 case 0:
4776 return strdup(timestamp);
4777 default:
4778 return strndup(timestamp, tlen);
4779 }
4780 }
4781
4782 /* auxiliary code to allocate memory and copy a string */
4783 bool
4784 copy_string(char **mem, const char *p, const char *q)
4785 {
4786 const size_t len = 1 + q - p;
4787 if (!(*mem = malloc(len))) {
4788 logerror("Unable to allocate memory for config");
4789 return false;
4790 }
4791 strlcpy(*mem, p, len);
4792 return true;
4793 }
4794
4795 /* keyword has to end with ", everything until next " is copied */
4796 bool
4797 copy_config_value_quoted(const char *keyword, char **mem, const char **p)
4798 {
4799 const char *q;
4800 if (strncasecmp(*p, keyword, strlen(keyword)))
4801 return false;
4802 q = *p += strlen(keyword);
4803 if (!(q = strchr(*p, '"'))) {
4804 errno = 0;
4805 logerror("unterminated \"\n");
4806 return false;
4807 }
4808 if (!(copy_string(mem, *p, q)))
4809 return false;
4810 *p = ++q;
4811 return true;
4812 }
4813
4814 /* for config file:
4815 * following = required but whitespace allowed, quotes optional
4816 * if numeric, then conversion to integer and no memory allocation
4817 */
4818 bool
4819 copy_config_value(const char *keyword, char **mem,
4820 const char **p, const char *file, int line)
4821 {
4822 if (strncasecmp(*p, keyword, strlen(keyword)))
4823 return false;
4824 *p += strlen(keyword);
4825
4826 while (isspace((unsigned char)**p))
4827 *p += 1;
4828 if (**p != '=') {
4829 errno = 0;
4830 logerror("expected \"=\" in file %s, line %d", file, line);
4831 return false;
4832 }
4833 *p += 1;
4834
4835 return copy_config_value_word(mem, p);
4836 }
4837
4838 /* copy next parameter from a config line */
4839 bool
4840 copy_config_value_word(char **mem, const char **p)
4841 {
4842 const char *q;
4843 while (isspace((unsigned char)**p))
4844 *p += 1;
4845 if (**p == '"')
4846 return copy_config_value_quoted("\"", mem, p);
4847
4848 /* without quotes: find next whitespace or end of line */
4849 (void)((q = strchr(*p, ' ')) || (q = strchr(*p, '\t'))
4850 || (q = strchr(*p, '\n')) || (q = strchr(*p, '\0')));
4851
4852 if (q-*p == 0 || !(copy_string(mem, *p, q)))
4853 return false;
4854
4855 *p = ++q;
4856 return true;
4857 }
4858
4859 static int
4860 writev1(int fd, struct iovec *iov, size_t count)
4861 {
4862 ssize_t nw = 0, tot = 0;
4863 size_t ntries = 5;
4864
4865 if (count == 0)
4866 return 0;
4867 while (ntries--) {
4868 switch ((nw = writev(fd, iov, count))) {
4869 case -1:
4870 if (errno == EAGAIN || errno == EWOULDBLOCK) {
4871 struct pollfd pfd;
4872 pfd.fd = fd;
4873 pfd.events = POLLOUT;
4874 pfd.revents = 0;
4875 (void)poll(&pfd, 1, 500);
4876 continue;
4877 }
4878 return -1;
4879 case 0:
4880 return 0;
4881 default:
4882 tot += nw;
4883 while (nw > 0) {
4884 if (iov->iov_len > (size_t)nw) {
4885 iov->iov_len -= nw;
4886 iov->iov_base =
4887 (char *)iov->iov_base + nw;
4888 break;
4889 } else {
4890 if (--count == 0)
4891 return tot;
4892 nw -= iov->iov_len;
4893 iov++;
4894 }
4895 }
4896 }
4897 }
4898 return tot == 0 ? nw : tot;
4899 }
4900
4901
4902 #ifdef NDEBUG
4903 /*
4904 * -d also controls daemoniziation, so it makes sense even with
4905 * NDEBUG, but if the user also tries to specify the logging details
4906 * with an argument, warn them it's not compiled into this binary.
4907 */
4908 void
4909 set_debug(const char *level)
4910 {
4911 Debug = D_DEFAULT;
4912 if (level == NULL)
4913 return;
4914
4915 /* don't bother parsing the argument */
4916 fprintf(stderr,
4917 "%s: debug logging is not compiled\n",
4918 getprogname());
4919 }
4920
4921 #else /* !NDEBUG */
4922 void
4923 set_debug(const char *level)
4924 {
4925 if (level == NULL) {
4926 Debug = D_DEFAULT; /* compat */
4927 return;
4928 }
4929
4930 /* skip initial whitespace for consistency with strto*l */
4931 while (isspace((unsigned char)*level))
4932 ++level;
4933
4934 /* accept ~num to mean "all except num" */
4935 bool invert = level[0] == '~';
4936 if (invert)
4937 ++level;
4938
4939 errno = 0;
4940 char *endp = NULL;
4941 unsigned long bits = strtoul(level, &endp, 0);
4942 if (errno || endp == level || *endp != '\0') {
4943 fprintf(stderr, "%s: bad argument to -d\n", getprogname());
4944 usage();
4945 }
4946 if (invert)
4947 bits = ~bits;
4948
4949 Debug = bits & D_ALL;
4950
4951 /*
4952 * make it possible to use -d to stay in the foreground but
4953 * suppress all dbprintf output (there better be free bits in
4954 * typeof(Debug) that are not in D_ALL).
4955 */
4956 if (Debug == 0)
4957 Debug = ~D_ALL;
4958 }
4959 #endif /* !NDEBUG */
4960
4961
4962 #ifndef NDEBUG
4963 void
4964 dbprintf(const char *fname, const char *funname,
4965 size_t lnum, const char *fmt, ...)
4966 {
4967 va_list ap;
4968 char *ts;
4969
4970 ts = make_timestamp(NULL, true, (size_t)-1);
4971 printf("%s:%s:%s:%.4zu\t", ts, fname, funname, lnum);
4972
4973 va_start(ap, fmt);
4974 vprintf(fmt, ap);
4975 va_end(ap);
4976 }
4977 #endif
4978