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