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