1 /* $OpenBSD: syslogd.c,v 1.256 2018/08/31 19:06:08 bluhm Exp $ */ 2 3 /* 4 * Copyright (c) 2014-2017 Alexander Bluhm <bluhm@genua.de> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 /* 20 * Copyright (c) 1983, 1988, 1993, 1994 21 * The Regents of the University of California. All rights reserved. 22 * 23 * Redistribution and use in source and binary forms, with or without 24 * modification, are permitted provided that the following conditions 25 * are met: 26 * 1. Redistributions of source code must retain the above copyright 27 * notice, this list of conditions and the following disclaimer. 28 * 2. Redistributions in binary form must reproduce the above copyright 29 * notice, this list of conditions and the following disclaimer in the 30 * documentation and/or other materials provided with the distribution. 31 * 3. Neither the name of the University nor the names of its contributors 32 * may be used to endorse or promote products derived from this software 33 * without specific prior written permission. 34 * 35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 45 * SUCH DAMAGE. 46 */ 47 48 /* 49 * syslogd -- log system messages 50 * 51 * This program implements a system log. It takes a series of lines. 52 * Each line may have a priority, signified as "<n>" as 53 * the first characters of the line. If this is 54 * not present, a default priority is used. 55 * 56 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will 57 * cause it to reread its configuration file. 58 * 59 * Defined Constants: 60 * 61 * MAXLINE -- the maximum line length that can be handled. 62 * DEFUPRI -- the default priority for user messages 63 * DEFSPRI -- the default priority for kernel messages 64 * 65 * Author: Eric Allman 66 * extensive changes by Ralph Campbell 67 * more extensive changes by Eric Allman (again) 68 * memory buffer logging by Damien Miller 69 * IPv6, libevent, syslog over TCP and TLS by Alexander Bluhm 70 */ 71 72 #define MAX_UDPMSG 1180 /* maximum UDP send size */ 73 #define MIN_MEMBUF (LOG_MAXLINE * 4) /* Minimum memory buffer size */ 74 #define MAX_MEMBUF (256 * 1024) /* Maximum memory buffer size */ 75 #define MAX_MEMBUF_NAME 64 /* Max length of membuf log name */ 76 #define MAX_TCPBUF (256 * 1024) /* Maximum tcp event buffer size */ 77 #define MAXSVLINE 120 /* maximum saved line length */ 78 #define FD_RESERVE 5 /* file descriptors not accepted */ 79 #define DEFUPRI (LOG_USER|LOG_NOTICE) 80 #define DEFSPRI (LOG_KERN|LOG_CRIT) 81 #define TIMERINTVL 30 /* interval for checking flush, mark */ 82 83 #include <sys/ioctl.h> 84 #include <sys/stat.h> 85 #include <sys/msgbuf.h> 86 #include <sys/queue.h> 87 #include <sys/sysctl.h> 88 #include <sys/un.h> 89 #include <sys/time.h> 90 #include <sys/resource.h> 91 92 #include <netinet/in.h> 93 #include <netdb.h> 94 #include <arpa/inet.h> 95 96 #include <ctype.h> 97 #include <err.h> 98 #include <errno.h> 99 #include <event.h> 100 #include <fcntl.h> 101 #include <fnmatch.h> 102 #include <limits.h> 103 #include <paths.h> 104 #include <signal.h> 105 #include <stdio.h> 106 #include <stdlib.h> 107 #include <string.h> 108 #include <tls.h> 109 #include <unistd.h> 110 #include <utmp.h> 111 #include <vis.h> 112 113 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b)) 114 #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b)) 115 116 #define SYSLOG_NAMES 117 #include <sys/syslog.h> 118 119 #include "log.h" 120 #include "syslogd.h" 121 #include "evbuffer_tls.h" 122 123 char *ConfFile = _PATH_LOGCONF; 124 const char ctty[] = _PATH_CONSOLE; 125 126 #define MAXUNAMES 20 /* maximum number of user names */ 127 128 129 /* 130 * Flags to logline(). 131 */ 132 133 #define IGN_CONS 0x001 /* don't print on console */ 134 #define SYNC_FILE 0x002 /* do fsync on file after printing */ 135 #define ADDDATE 0x004 /* add a date to the message */ 136 #define MARK 0x008 /* this message is a mark */ 137 138 /* 139 * This structure represents the files that will have log 140 * copies printed. 141 */ 142 143 struct filed { 144 SIMPLEQ_ENTRY(filed) f_next; /* next in linked list */ 145 int f_type; /* entry type, see below */ 146 int f_file; /* file descriptor */ 147 time_t f_time; /* time this was last written */ 148 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */ 149 char *f_program; /* program this applies to */ 150 char *f_hostname; /* host this applies to */ 151 union { 152 char f_uname[MAXUNAMES][UT_NAMESIZE+1]; 153 struct { 154 char f_loghost[1+4+3+1+NI_MAXHOST+1+NI_MAXSERV]; 155 /* @proto46://[hostname]:servname\0 */ 156 struct sockaddr_storage f_addr; 157 struct buffertls f_buftls; 158 struct bufferevent *f_bufev; 159 struct tls *f_ctx; 160 char *f_host; 161 int f_reconnectwait; 162 } f_forw; /* forwarding address */ 163 char f_fname[PATH_MAX]; 164 struct { 165 char f_mname[MAX_MEMBUF_NAME]; 166 struct ringbuf *f_rb; 167 int f_overflow; 168 int f_attached; 169 size_t f_len; 170 } f_mb; /* Memory buffer */ 171 } f_un; 172 char f_prevline[MAXSVLINE]; /* last message logged */ 173 char f_lasttime[33]; /* time of last occurrence */ 174 char f_prevhost[HOST_NAME_MAX+1]; /* host from which recd. */ 175 int f_prevpri; /* pri of f_prevline */ 176 int f_prevlen; /* length of f_prevline */ 177 int f_prevcount; /* repetition cnt of prevline */ 178 unsigned int f_repeatcount; /* number of "repeated" msgs */ 179 int f_quick; /* abort when matched */ 180 int f_dropped; /* warn, dropped message */ 181 time_t f_lasterrtime; /* last error was reported */ 182 }; 183 184 /* 185 * Intervals at which we flush out "message repeated" messages, 186 * in seconds after previous message is logged. After each flush, 187 * we move to the next interval until we reach the largest. 188 */ 189 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */ 190 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1) 191 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount]) 192 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \ 193 (f)->f_repeatcount = MAXREPEAT; \ 194 } 195 196 /* values for f_type */ 197 #define F_UNUSED 0 /* unused entry */ 198 #define F_FILE 1 /* regular file */ 199 #define F_TTY 2 /* terminal */ 200 #define F_CONSOLE 3 /* console terminal */ 201 #define F_FORWUDP 4 /* remote machine via UDP */ 202 #define F_USERS 5 /* list of users */ 203 #define F_WALL 6 /* everyone logged on */ 204 #define F_MEMBUF 7 /* memory buffer */ 205 #define F_PIPE 8 /* pipe to external program */ 206 #define F_FORWTCP 9 /* remote machine via TCP */ 207 #define F_FORWTLS 10 /* remote machine via TLS */ 208 209 char *TypeNames[] = { 210 "UNUSED", "FILE", "TTY", "CONSOLE", 211 "FORWUDP", "USERS", "WALL", "MEMBUF", 212 "PIPE", "FORWTCP", "FORWTLS", 213 }; 214 215 SIMPLEQ_HEAD(filed_list, filed) Files; 216 struct filed consfile; 217 218 int nunix; /* Number of Unix domain sockets requested */ 219 char **path_unix; /* Paths to Unix domain sockets */ 220 int Debug; /* debug flag */ 221 int Foreground; /* run in foreground, instead of daemonizing */ 222 char LocalHostName[HOST_NAME_MAX+1]; /* our hostname */ 223 char *LocalDomain; /* our local domain name */ 224 int Started = 0; /* set after privsep */ 225 int Initialized = 0; /* set when we have initialized ourselves */ 226 227 int MarkInterval = 20 * 60; /* interval between marks in seconds */ 228 int MarkSeq = 0; /* mark sequence number */ 229 int PrivChild = 0; /* Exec the privileged parent process */ 230 int Repeat = 0; /* 0 msg repeated, 1 in files only, 2 never */ 231 int SecureMode = 1; /* when true, speak only unix domain socks */ 232 int NoDNS = 0; /* when true, refrain from doing DNS lookups */ 233 int ZuluTime = 0; /* display date and time in UTC ISO format */ 234 int IncludeHostname = 0; /* include RFC 3164 hostnames when forwarding */ 235 int Family = PF_UNSPEC; /* protocol family, may disable IPv4 or IPv6 */ 236 char *path_ctlsock = NULL; /* Path to control socket */ 237 238 struct tls *server_ctx; 239 struct tls_config *client_config, *server_config; 240 const char *CAfile = "/etc/ssl/cert.pem"; /* file containing CA certificates */ 241 int NoVerify = 0; /* do not verify TLS server x509 certificate */ 242 const char *ClientCertfile = NULL; 243 const char *ClientKeyfile = NULL; 244 const char *ServerCAfile = NULL; 245 int tcpbuf_dropped = 0; /* count messages dropped from TCP or TLS */ 246 int file_dropped = 0; /* messages dropped due to file system full */ 247 int init_dropped = 0; /* messages dropped during initialization */ 248 249 #define CTL_READING_CMD 1 250 #define CTL_WRITING_REPLY 2 251 #define CTL_WRITING_CONT_REPLY 3 252 int ctl_state = 0; /* What the control socket is up to */ 253 int membuf_drop = 0; /* logs dropped in continuous membuf read */ 254 255 /* 256 * Client protocol NB. all numeric fields in network byte order 257 */ 258 #define CTL_VERSION 2 259 260 /* Request */ 261 struct { 262 u_int32_t version; 263 #define CMD_READ 1 /* Read out log */ 264 #define CMD_READ_CLEAR 2 /* Read and clear log */ 265 #define CMD_CLEAR 3 /* Clear log */ 266 #define CMD_LIST 4 /* List available logs */ 267 #define CMD_FLAGS 5 /* Query flags only */ 268 #define CMD_READ_CONT 6 /* Read out log continuously */ 269 u_int32_t cmd; 270 u_int32_t lines; 271 char logname[MAX_MEMBUF_NAME]; 272 } ctl_cmd; 273 274 size_t ctl_cmd_bytes = 0; /* number of bytes of ctl_cmd read */ 275 276 /* Reply */ 277 struct ctl_reply_hdr { 278 u_int32_t version; 279 #define CTL_HDR_FLAG_OVERFLOW 0x01 280 u_int32_t flags; 281 /* Reply text follows, up to MAX_MEMBUF long */ 282 }; 283 284 #define CTL_HDR_LEN (sizeof(struct ctl_reply_hdr)) 285 #define CTL_REPLY_MAXSIZE (CTL_HDR_LEN + MAX_MEMBUF) 286 #define CTL_REPLY_SIZE (strlen(reply_text) + CTL_HDR_LEN) 287 288 char *ctl_reply = NULL; /* Buffer for control connection reply */ 289 char *reply_text; /* Start of reply text in buffer */ 290 size_t ctl_reply_size = 0; /* Number of bytes used in reply */ 291 size_t ctl_reply_offset = 0; /* Number of bytes of reply written so far */ 292 293 char *linebuf; 294 int linesize; 295 296 int fd_ctlconn, fd_udp, fd_udp6, send_udp, send_udp6; 297 struct event *ev_ctlaccept, *ev_ctlread, *ev_ctlwrite; 298 299 struct peer { 300 struct buffertls p_buftls; 301 struct bufferevent *p_bufev; 302 struct tls *p_ctx; 303 char *p_peername; 304 char *p_hostname; 305 int p_fd; 306 }; 307 char hostname_unknown[] = "???"; 308 309 void klog_readcb(int, short, void *); 310 void udp_readcb(int, short, void *); 311 void unix_readcb(int, short, void *); 312 int reserve_accept4(int, int, struct event *, 313 void (*)(int, short, void *), struct sockaddr *, socklen_t *, int); 314 void tcp_acceptcb(int, short, void *); 315 void tls_acceptcb(int, short, void *); 316 void acceptcb(int, short, void *, int); 317 int octet_counting(struct evbuffer *, char **, int); 318 int non_transparent_framing(struct evbuffer *, char **); 319 void tcp_readcb(struct bufferevent *, void *); 320 void tcp_closecb(struct bufferevent *, short, void *); 321 int tcp_socket(struct filed *); 322 void tcp_dropcb(struct bufferevent *, void *); 323 void tcp_writecb(struct bufferevent *, void *); 324 void tcp_errorcb(struct bufferevent *, short, void *); 325 void tcp_connectcb(int, short, void *); 326 void tcp_connect_retry(struct bufferevent *, struct filed *); 327 int tcpbuf_countmsg(struct bufferevent *bufev); 328 void die_signalcb(int, short, void *); 329 void mark_timercb(int, short, void *); 330 void init_signalcb(int, short, void *); 331 void ctlsock_acceptcb(int, short, void *); 332 void ctlconn_readcb(int, short, void *); 333 void ctlconn_writecb(int, short, void *); 334 void ctlconn_logto(char *); 335 void ctlconn_cleanup(void); 336 337 struct filed *cfline(char *, char *, char *); 338 void cvthname(struct sockaddr *, char *, size_t); 339 int decode(const char *, const CODE *); 340 void markit(void); 341 void fprintlog(struct filed *, int, char *); 342 void dropped_warn(int *, const char *); 343 void init(void); 344 void logevent(int, const char *); 345 void logline(int, int, char *, char *); 346 struct filed *find_dup(struct filed *); 347 size_t parsepriority(const char *, int *); 348 void printline(char *, char *); 349 void printsys(char *); 350 void usage(void); 351 void wallmsg(struct filed *, struct iovec *); 352 int loghost_parse(char *, char **, char **, char **); 353 int getmsgbufsize(void); 354 void address_alloc(const char *, const char *, char ***, char ***, int *); 355 int socket_bind(const char *, const char *, const char *, int, 356 int *, int *); 357 int unix_socket(char *, int, mode_t); 358 void double_sockbuf(int, int); 359 void set_sockbuf(int); 360 void tailify_replytext(char *, int); 361 362 int 363 main(int argc, char *argv[]) 364 { 365 struct timeval to; 366 struct event *ev_klog, *ev_sendsys, *ev_udp, *ev_udp6, 367 *ev_bind, *ev_listen, *ev_tls, *ev_unix, 368 *ev_hup, *ev_int, *ev_quit, *ev_term, *ev_mark; 369 sigset_t sigmask; 370 const char *errstr; 371 char *p; 372 int ch, i; 373 int lockpipe[2] = { -1, -1}, pair[2], nullfd, fd; 374 int fd_ctlsock, fd_klog, fd_sendsys, *fd_bind, *fd_listen; 375 int *fd_tls, *fd_unix, nbind, nlisten, ntls; 376 char **bind_host, **bind_port, **listen_host, **listen_port; 377 char *tls_hostport, **tls_host, **tls_port; 378 379 /* block signal until handler is set up */ 380 sigemptyset(&sigmask); 381 sigaddset(&sigmask, SIGHUP); 382 if (sigprocmask(SIG_SETMASK, &sigmask, NULL) == -1) 383 err(1, "sigprocmask block"); 384 385 if ((path_unix = malloc(sizeof(*path_unix))) == NULL) 386 err(1, "malloc %s", _PATH_LOG); 387 path_unix[0] = _PATH_LOG; 388 nunix = 1; 389 390 bind_host = listen_host = tls_host = NULL; 391 bind_port = listen_port = tls_port = NULL; 392 tls_hostport = NULL; 393 nbind = nlisten = ntls = 0; 394 395 while ((ch = getopt(argc, argv, 396 "46a:C:c:dFf:hK:k:m:nP:p:rS:s:T:U:uVZ")) != -1) { 397 switch (ch) { 398 case '4': /* disable IPv6 */ 399 Family = PF_INET; 400 break; 401 case '6': /* disable IPv4 */ 402 Family = PF_INET6; 403 break; 404 case 'a': 405 if ((path_unix = reallocarray(path_unix, nunix + 1, 406 sizeof(*path_unix))) == NULL) 407 err(1, "unix path %s", optarg); 408 path_unix[nunix++] = optarg; 409 break; 410 case 'C': /* file containing CA certificates */ 411 CAfile = optarg; 412 break; 413 case 'c': /* file containing client certificate */ 414 ClientCertfile = optarg; 415 break; 416 case 'd': /* debug */ 417 Debug++; 418 break; 419 case 'F': /* foreground */ 420 Foreground = 1; 421 break; 422 case 'f': /* configuration file */ 423 ConfFile = optarg; 424 break; 425 case 'h': /* RFC 3164 hostnames */ 426 IncludeHostname = 1; 427 break; 428 case 'K': /* verify client with CA file */ 429 ServerCAfile = optarg; 430 break; 431 case 'k': /* file containing client key */ 432 ClientKeyfile = optarg; 433 break; 434 case 'm': /* mark interval */ 435 MarkInterval = strtonum(optarg, 0, 365*24*60, &errstr); 436 if (errstr) 437 errx(1, "mark_interval %s: %s", errstr, optarg); 438 MarkInterval *= 60; 439 break; 440 case 'n': /* don't do DNS lookups */ 441 NoDNS = 1; 442 break; 443 case 'P': /* used internally, exec the parent */ 444 PrivChild = strtonum(optarg, 2, INT_MAX, &errstr); 445 if (errstr) 446 errx(1, "priv child %s: %s", errstr, optarg); 447 break; 448 case 'p': /* path */ 449 path_unix[0] = optarg; 450 break; 451 case 'r': 452 Repeat++; 453 break; 454 case 'S': /* allow tls and listen on address */ 455 if (tls_hostport == NULL) 456 tls_hostport = optarg; 457 address_alloc("tls", optarg, &tls_host, &tls_port, 458 &ntls); 459 break; 460 case 's': 461 path_ctlsock = optarg; 462 break; 463 case 'T': /* allow tcp and listen on address */ 464 address_alloc("listen", optarg, &listen_host, 465 &listen_port, &nlisten); 466 break; 467 case 'U': /* allow udp only from address */ 468 address_alloc("bind", optarg, &bind_host, &bind_port, 469 &nbind); 470 break; 471 case 'u': /* allow udp input port */ 472 SecureMode = 0; 473 break; 474 case 'V': /* do not verify certificates */ 475 NoVerify = 1; 476 break; 477 case 'Z': /* time stamps in UTC ISO format */ 478 ZuluTime = 1; 479 break; 480 default: 481 usage(); 482 } 483 } 484 if (argc != optind) 485 usage(); 486 487 log_init(Debug, LOG_SYSLOG); 488 log_procinit("syslogd"); 489 if (Debug) 490 setvbuf(stdout, NULL, _IOLBF, 0); 491 492 if ((nullfd = open(_PATH_DEVNULL, O_RDWR)) == -1) 493 fatal("open %s", _PATH_DEVNULL); 494 for (fd = nullfd + 1; fd <= STDERR_FILENO; fd++) { 495 if (fcntl(fd, F_GETFL) == -1 && errno == EBADF) 496 if (dup2(nullfd, fd) == -1) 497 fatal("dup2 null"); 498 } 499 500 if (PrivChild > 1) 501 priv_exec(ConfFile, NoDNS, PrivChild, argc, argv); 502 503 consfile.f_type = F_CONSOLE; 504 (void)strlcpy(consfile.f_un.f_fname, ctty, 505 sizeof(consfile.f_un.f_fname)); 506 consfile.f_file = open(consfile.f_un.f_fname, O_WRONLY|O_NONBLOCK, 0); 507 if (consfile.f_file == -1) 508 log_warn("open %s", consfile.f_un.f_fname); 509 510 (void)gethostname(LocalHostName, sizeof(LocalHostName)); 511 if ((p = strchr(LocalHostName, '.')) != NULL) { 512 *p++ = '\0'; 513 LocalDomain = p; 514 } else 515 LocalDomain = ""; 516 517 /* Reserve space for kernel message buffer plus buffer full message. */ 518 linesize = getmsgbufsize() + 64; 519 if (linesize < LOG_MAXLINE) 520 linesize = LOG_MAXLINE; 521 linesize++; 522 if ((linebuf = malloc(linesize)) == NULL) 523 fatal("allocate line buffer"); 524 525 if (socket_bind("udp", NULL, "syslog", SecureMode, 526 &fd_udp, &fd_udp6) == -1) 527 log_warnx("socket bind * failed"); 528 if ((fd_bind = reallocarray(NULL, nbind, sizeof(*fd_bind))) == NULL) 529 fatal("allocate bind fd"); 530 for (i = 0; i < nbind; i++) { 531 if (socket_bind("udp", bind_host[i], bind_port[i], 0, 532 &fd_bind[i], &fd_bind[i]) == -1) 533 log_warnx("socket bind udp failed"); 534 } 535 if ((fd_listen = reallocarray(NULL, nlisten, sizeof(*fd_listen))) 536 == NULL) 537 fatal("allocate listen fd"); 538 for (i = 0; i < nlisten; i++) { 539 if (socket_bind("tcp", listen_host[i], listen_port[i], 0, 540 &fd_listen[i], &fd_listen[i]) == -1) 541 log_warnx("socket listen tcp failed"); 542 } 543 if ((fd_tls = reallocarray(NULL, ntls, sizeof(*fd_tls))) == NULL) 544 fatal("allocate tls fd"); 545 for (i = 0; i < ntls; i++) { 546 if (socket_bind("tls", tls_host[i], tls_port[i], 0, 547 &fd_tls[i], &fd_tls[i]) == -1) 548 log_warnx("socket listen tls failed"); 549 } 550 551 if ((fd_unix = reallocarray(NULL, nunix, sizeof(*fd_unix))) == NULL) 552 fatal("allocate unix fd"); 553 for (i = 0; i < nunix; i++) { 554 fd_unix[i] = unix_socket(path_unix[i], SOCK_DGRAM, 0666); 555 if (fd_unix[i] == -1) { 556 if (i == 0) 557 log_warnx("log socket %s failed", path_unix[i]); 558 continue; 559 } 560 double_sockbuf(fd_unix[i], SO_RCVBUF); 561 } 562 563 if (socketpair(AF_UNIX, SOCK_DGRAM, PF_UNSPEC, pair) == -1) { 564 log_warn("socketpair sendsyslog"); 565 fd_sendsys = -1; 566 } else { 567 double_sockbuf(pair[0], SO_RCVBUF); 568 double_sockbuf(pair[1], SO_SNDBUF); 569 fd_sendsys = pair[0]; 570 } 571 572 fd_ctlsock = fd_ctlconn = -1; 573 if (path_ctlsock != NULL) { 574 fd_ctlsock = unix_socket(path_ctlsock, SOCK_STREAM, 0600); 575 if (fd_ctlsock == -1) { 576 log_warnx("control socket %s failed", path_ctlsock); 577 } else { 578 if (listen(fd_ctlsock, 5) == -1) { 579 log_warn("listen control socket"); 580 close(fd_ctlsock); 581 fd_ctlsock = -1; 582 } 583 } 584 } 585 586 if ((fd_klog = open(_PATH_KLOG, O_RDONLY, 0)) == -1) { 587 log_warn("open %s", _PATH_KLOG); 588 } else if (fd_sendsys != -1) { 589 /* Use /dev/klog to register sendsyslog(2) receiver. */ 590 if (ioctl(fd_klog, LIOCSFD, &pair[1]) == -1) 591 log_warn("ioctl klog LIOCSFD sendsyslog"); 592 } 593 if (fd_sendsys != -1) 594 close(pair[1]); 595 596 if (tls_init() == -1) { 597 log_warn("tls_init"); 598 } else { 599 if ((client_config = tls_config_new()) == NULL) 600 log_warn("tls_config_new client"); 601 if (tls_hostport) { 602 if ((server_config = tls_config_new()) == NULL) 603 log_warn("tls_config_new server"); 604 if ((server_ctx = tls_server()) == NULL) { 605 log_warn("tls_server"); 606 for (i = 0; i < ntls; i++) 607 close(fd_tls[i]); 608 free(fd_tls); 609 fd_tls = NULL; 610 free(tls_host); 611 free(tls_port); 612 tls_host = tls_port = NULL; 613 ntls = 0; 614 } 615 } 616 } 617 if (client_config) { 618 if (NoVerify) { 619 tls_config_insecure_noverifycert(client_config); 620 tls_config_insecure_noverifyname(client_config); 621 } else { 622 if (tls_config_set_ca_file(client_config, 623 CAfile) == -1) { 624 log_warnx("load client TLS CA: %s", 625 tls_config_error(client_config)); 626 /* avoid reading default certs in chroot */ 627 tls_config_set_ca_mem(client_config, "", 0); 628 } else 629 log_debug("CAfile %s", CAfile); 630 } 631 if (ClientCertfile && ClientKeyfile) { 632 if (tls_config_set_cert_file(client_config, 633 ClientCertfile) == -1) 634 log_warnx("load client TLS cert: %s", 635 tls_config_error(client_config)); 636 else 637 log_debug("ClientCertfile %s", ClientCertfile); 638 639 if (tls_config_set_key_file(client_config, 640 ClientKeyfile) == -1) 641 log_warnx("load client TLS key: %s", 642 tls_config_error(client_config)); 643 else 644 log_debug("ClientKeyfile %s", ClientKeyfile); 645 } else if (ClientCertfile || ClientKeyfile) { 646 log_warnx("options -c and -k must be used together"); 647 } 648 if (tls_config_set_protocols(client_config, 649 TLS_PROTOCOLS_ALL) != 0) 650 log_warnx("set client TLS protocols: %s", 651 tls_config_error(client_config)); 652 if (tls_config_set_ciphers(client_config, "all") != 0) 653 log_warnx("set client TLS ciphers: %s", 654 tls_config_error(client_config)); 655 } 656 if (server_config && server_ctx) { 657 const char *names[2]; 658 659 names[0] = tls_hostport; 660 names[1] = tls_host[0]; 661 662 for (i = 0; i < 2; i++) { 663 if (asprintf(&p, "/etc/ssl/private/%s.key", names[i]) 664 == -1) 665 continue; 666 if (tls_config_set_key_file(server_config, p) == -1) { 667 log_warnx("load server TLS key: %s", 668 tls_config_error(server_config)); 669 free(p); 670 continue; 671 } 672 log_debug("Keyfile %s", p); 673 free(p); 674 if (asprintf(&p, "/etc/ssl/%s.crt", names[i]) == -1) 675 continue; 676 if (tls_config_set_cert_file(server_config, p) == -1) { 677 log_warnx("load server TLS cert: %s", 678 tls_config_error(server_config)); 679 free(p); 680 continue; 681 } 682 log_debug("Certfile %s", p); 683 free(p); 684 break; 685 } 686 687 if (ServerCAfile) { 688 if (tls_config_set_ca_file(server_config, 689 ServerCAfile) == -1) { 690 log_warnx("load server TLS CA: %s", 691 tls_config_error(server_config)); 692 /* avoid reading default certs in chroot */ 693 tls_config_set_ca_mem(server_config, "", 0); 694 } else 695 log_debug("Server CAfile %s", ServerCAfile); 696 tls_config_verify_client(server_config); 697 } 698 if (tls_config_set_protocols(server_config, 699 TLS_PROTOCOLS_ALL) != 0) 700 log_warnx("set server TLS protocols: %s", 701 tls_config_error(server_config)); 702 if (tls_config_set_ciphers(server_config, "compat") != 0) 703 log_warnx("Set server TLS ciphers: %s", 704 tls_config_error(server_config)); 705 if (tls_configure(server_ctx, server_config) != 0) { 706 log_warnx("tls_configure server: %s", 707 tls_error(server_ctx)); 708 tls_free(server_ctx); 709 server_ctx = NULL; 710 for (i = 0; i < ntls; i++) 711 close(fd_tls[i]); 712 free(fd_tls); 713 fd_tls = NULL; 714 free(tls_host); 715 free(tls_port); 716 tls_host = tls_port = NULL; 717 ntls = 0; 718 } 719 } 720 721 log_debug("off & running...."); 722 723 if (!Debug && !Foreground) { 724 char c; 725 726 pipe(lockpipe); 727 728 switch(fork()) { 729 case -1: 730 err(1, "fork"); 731 case 0: 732 setsid(); 733 close(lockpipe[0]); 734 break; 735 default: 736 close(lockpipe[1]); 737 read(lockpipe[0], &c, 1); 738 _exit(0); 739 } 740 } 741 742 /* tuck my process id away */ 743 if (!Debug) { 744 FILE *fp; 745 746 fp = fopen(_PATH_LOGPID, "w"); 747 if (fp != NULL) { 748 fprintf(fp, "%ld\n", (long)getpid()); 749 (void) fclose(fp); 750 } 751 } 752 753 /* Privilege separation begins here */ 754 priv_init(lockpipe[1], nullfd, argc, argv); 755 756 if (pledge("stdio unix inet recvfd", NULL) == -1) 757 err(1, "pledge"); 758 759 Started = 1; 760 761 /* Process is now unprivileged and inside a chroot */ 762 if (Debug) 763 event_set_log_callback(logevent); 764 event_init(); 765 766 if ((ev_ctlaccept = malloc(sizeof(struct event))) == NULL || 767 (ev_ctlread = malloc(sizeof(struct event))) == NULL || 768 (ev_ctlwrite = malloc(sizeof(struct event))) == NULL || 769 (ev_klog = malloc(sizeof(struct event))) == NULL || 770 (ev_sendsys = malloc(sizeof(struct event))) == NULL || 771 (ev_udp = malloc(sizeof(struct event))) == NULL || 772 (ev_udp6 = malloc(sizeof(struct event))) == NULL || 773 (ev_bind = reallocarray(NULL, nbind, sizeof(struct event))) 774 == NULL || 775 (ev_listen = reallocarray(NULL, nlisten, sizeof(struct event))) 776 == NULL || 777 (ev_tls = reallocarray(NULL, ntls, sizeof(struct event))) 778 == NULL || 779 (ev_unix = reallocarray(NULL, nunix, sizeof(struct event))) 780 == NULL || 781 (ev_hup = malloc(sizeof(struct event))) == NULL || 782 (ev_int = malloc(sizeof(struct event))) == NULL || 783 (ev_quit = malloc(sizeof(struct event))) == NULL || 784 (ev_term = malloc(sizeof(struct event))) == NULL || 785 (ev_mark = malloc(sizeof(struct event))) == NULL) 786 err(1, "malloc"); 787 788 event_set(ev_ctlaccept, fd_ctlsock, EV_READ|EV_PERSIST, 789 ctlsock_acceptcb, ev_ctlaccept); 790 event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST, 791 ctlconn_readcb, ev_ctlread); 792 event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST, 793 ctlconn_writecb, ev_ctlwrite); 794 event_set(ev_klog, fd_klog, EV_READ|EV_PERSIST, klog_readcb, ev_klog); 795 event_set(ev_sendsys, fd_sendsys, EV_READ|EV_PERSIST, unix_readcb, 796 ev_sendsys); 797 event_set(ev_udp, fd_udp, EV_READ|EV_PERSIST, udp_readcb, ev_udp); 798 event_set(ev_udp6, fd_udp6, EV_READ|EV_PERSIST, udp_readcb, ev_udp6); 799 for (i = 0; i < nbind; i++) 800 event_set(&ev_bind[i], fd_bind[i], EV_READ|EV_PERSIST, 801 udp_readcb, &ev_bind[i]); 802 for (i = 0; i < nlisten; i++) 803 event_set(&ev_listen[i], fd_listen[i], EV_READ|EV_PERSIST, 804 tcp_acceptcb, &ev_listen[i]); 805 for (i = 0; i < ntls; i++) 806 event_set(&ev_tls[i], fd_tls[i], EV_READ|EV_PERSIST, 807 tls_acceptcb, &ev_tls[i]); 808 for (i = 0; i < nunix; i++) 809 event_set(&ev_unix[i], fd_unix[i], EV_READ|EV_PERSIST, 810 unix_readcb, &ev_unix[i]); 811 812 signal_set(ev_hup, SIGHUP, init_signalcb, ev_hup); 813 signal_set(ev_int, SIGINT, die_signalcb, ev_int); 814 signal_set(ev_quit, SIGQUIT, die_signalcb, ev_quit); 815 signal_set(ev_term, SIGTERM, die_signalcb, ev_term); 816 817 evtimer_set(ev_mark, mark_timercb, ev_mark); 818 819 init(); 820 821 /* Allocate ctl socket reply buffer if we have a ctl socket */ 822 if (fd_ctlsock != -1 && 823 (ctl_reply = malloc(CTL_REPLY_MAXSIZE)) == NULL) 824 fatal("allocate control socket reply buffer"); 825 reply_text = ctl_reply + CTL_HDR_LEN; 826 827 if (!Debug) { 828 close(lockpipe[1]); 829 dup2(nullfd, STDIN_FILENO); 830 dup2(nullfd, STDOUT_FILENO); 831 dup2(nullfd, STDERR_FILENO); 832 } 833 if (nullfd > 2) 834 close(nullfd); 835 836 /* 837 * Signal to the priv process that the initial config parsing is done 838 * so that it will reject any future attempts to open more files 839 */ 840 priv_config_parse_done(); 841 842 if (fd_ctlsock != -1) 843 event_add(ev_ctlaccept, NULL); 844 if (fd_klog != -1) 845 event_add(ev_klog, NULL); 846 if (fd_sendsys != -1) 847 event_add(ev_sendsys, NULL); 848 if (!SecureMode) { 849 if (fd_udp != -1) 850 event_add(ev_udp, NULL); 851 if (fd_udp6 != -1) 852 event_add(ev_udp6, NULL); 853 } else { 854 /* 855 * If generic UDP file descriptors are used neither 856 * for receiving nor for sending, close them. Then 857 * there is no useless *.514 in netstat. 858 */ 859 if (fd_udp != -1 && !send_udp) { 860 close(fd_udp); 861 fd_udp = -1; 862 } 863 if (fd_udp6 != -1 && !send_udp6) { 864 close(fd_udp6); 865 fd_udp6 = -1; 866 } 867 } 868 for (i = 0; i < nbind; i++) 869 if (fd_bind[i] != -1) 870 event_add(&ev_bind[i], NULL); 871 for (i = 0; i < nlisten; i++) 872 if (fd_listen[i] != -1) 873 event_add(&ev_listen[i], NULL); 874 for (i = 0; i < ntls; i++) 875 if (fd_tls[i] != -1) 876 event_add(&ev_tls[i], NULL); 877 for (i = 0; i < nunix; i++) 878 if (fd_unix[i] != -1) 879 event_add(&ev_unix[i], NULL); 880 881 signal_add(ev_hup, NULL); 882 signal_add(ev_term, NULL); 883 if (Debug) { 884 signal_add(ev_int, NULL); 885 signal_add(ev_quit, NULL); 886 } else { 887 (void)signal(SIGINT, SIG_IGN); 888 (void)signal(SIGQUIT, SIG_IGN); 889 } 890 (void)signal(SIGCHLD, SIG_IGN); 891 (void)signal(SIGPIPE, SIG_IGN); 892 893 to.tv_sec = TIMERINTVL; 894 to.tv_usec = 0; 895 evtimer_add(ev_mark, &to); 896 897 log_info(LOG_INFO, "start"); 898 log_debug("syslogd: started"); 899 900 sigemptyset(&sigmask); 901 if (sigprocmask(SIG_SETMASK, &sigmask, NULL) == -1) 902 err(1, "sigprocmask unblock"); 903 904 event_dispatch(); 905 /* NOTREACHED */ 906 return (0); 907 } 908 909 void 910 address_alloc(const char *name, const char *address, char ***host, 911 char ***port, int *num) 912 { 913 char *p; 914 915 /* do not care about memory leak, argv has to be preserved */ 916 if ((p = strdup(address)) == NULL) 917 err(1, "%s address %s", name, address); 918 if ((*host = reallocarray(*host, *num + 1, sizeof(**host))) == NULL) 919 err(1, "%s host %s", name, address); 920 if ((*port = reallocarray(*port, *num + 1, sizeof(**port))) == NULL) 921 err(1, "%s port %s", name, address); 922 if (loghost_parse(p, NULL, *host + *num, *port + *num) == -1) 923 errx(1, "bad %s address: %s", name, address); 924 (*num)++; 925 } 926 927 int 928 socket_bind(const char *proto, const char *host, const char *port, 929 int shutread, int *fd, int *fd6) 930 { 931 struct addrinfo hints, *res, *res0; 932 char hostname[NI_MAXHOST], servname[NI_MAXSERV]; 933 int *fdp, error, reuseaddr; 934 935 *fd = *fd6 = -1; 936 if (proto == NULL) 937 proto = "udp"; 938 if (port == NULL) 939 port = strcmp(proto, "tls") == 0 ? "syslog-tls" : "syslog"; 940 941 memset(&hints, 0, sizeof(hints)); 942 hints.ai_family = Family; 943 if (strcmp(proto, "udp") == 0) { 944 hints.ai_socktype = SOCK_DGRAM; 945 hints.ai_protocol = IPPROTO_UDP; 946 } else { 947 hints.ai_socktype = SOCK_STREAM; 948 hints.ai_protocol = IPPROTO_TCP; 949 } 950 hints.ai_flags = AI_PASSIVE; 951 952 if ((error = getaddrinfo(host, port, &hints, &res0))) { 953 log_warnx("getaddrinfo proto %s, host %s, port %s: %s", 954 proto, host ? host : "*", port, gai_strerror(error)); 955 return (-1); 956 } 957 958 for (res = res0; res; res = res->ai_next) { 959 switch (res->ai_family) { 960 case AF_INET: 961 fdp = fd; 962 break; 963 case AF_INET6: 964 fdp = fd6; 965 break; 966 default: 967 continue; 968 } 969 if (*fdp >= 0) 970 continue; 971 972 if ((*fdp = socket(res->ai_family, 973 res->ai_socktype | SOCK_NONBLOCK, res->ai_protocol)) == -1) 974 continue; 975 976 if (getnameinfo(res->ai_addr, res->ai_addrlen, hostname, 977 sizeof(hostname), servname, sizeof(servname), 978 NI_NUMERICHOST | NI_NUMERICSERV | 979 (res->ai_socktype == SOCK_DGRAM ? NI_DGRAM : 0)) != 0) { 980 log_debug("Malformed bind address"); 981 hostname[0] = servname[0] = '\0'; 982 } 983 if (shutread && shutdown(*fdp, SHUT_RD) == -1) { 984 log_warn("shutdown SHUT_RD " 985 "protocol %d, address %s, portnum %s", 986 res->ai_protocol, hostname, servname); 987 close(*fdp); 988 *fdp = -1; 989 continue; 990 } 991 if (!shutread && res->ai_protocol == IPPROTO_UDP) 992 double_sockbuf(*fdp, SO_RCVBUF); 993 else if (res->ai_protocol == IPPROTO_TCP) 994 set_sockbuf(*fdp); 995 reuseaddr = 1; 996 if (setsockopt(*fdp, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, 997 sizeof(reuseaddr)) == -1) { 998 log_warn("setsockopt SO_REUSEADDR " 999 "protocol %d, address %s, portnum %s", 1000 res->ai_protocol, hostname, servname); 1001 close(*fdp); 1002 *fdp = -1; 1003 continue; 1004 } 1005 if (bind(*fdp, res->ai_addr, res->ai_addrlen) == -1) { 1006 log_warn("bind protocol %d, address %s, portnum %s", 1007 res->ai_protocol, hostname, servname); 1008 close(*fdp); 1009 *fdp = -1; 1010 continue; 1011 } 1012 if (!shutread && res->ai_protocol == IPPROTO_TCP && 1013 listen(*fdp, 10) == -1) { 1014 log_warn("listen protocol %d, address %s, portnum %s", 1015 res->ai_protocol, hostname, servname); 1016 close(*fdp); 1017 *fdp = -1; 1018 continue; 1019 } 1020 } 1021 1022 freeaddrinfo(res0); 1023 1024 if (*fd == -1 && *fd6 == -1) 1025 return (-1); 1026 return (0); 1027 } 1028 1029 void 1030 klog_readcb(int fd, short event, void *arg) 1031 { 1032 struct event *ev = arg; 1033 ssize_t n; 1034 1035 n = read(fd, linebuf, linesize - 1); 1036 if (n > 0) { 1037 linebuf[n] = '\0'; 1038 printsys(linebuf); 1039 } else if (n < 0 && errno != EINTR) { 1040 log_warn("read klog"); 1041 event_del(ev); 1042 } 1043 } 1044 1045 void 1046 udp_readcb(int fd, short event, void *arg) 1047 { 1048 struct sockaddr_storage sa; 1049 socklen_t salen; 1050 ssize_t n; 1051 1052 salen = sizeof(sa); 1053 n = recvfrom(fd, linebuf, LOG_MAXLINE, 0, (struct sockaddr *)&sa, 1054 &salen); 1055 if (n > 0) { 1056 char resolve[NI_MAXHOST]; 1057 1058 linebuf[n] = '\0'; 1059 cvthname((struct sockaddr *)&sa, resolve, sizeof(resolve)); 1060 log_debug("cvthname res: %s", resolve); 1061 printline(resolve, linebuf); 1062 } else if (n < 0 && errno != EINTR && errno != EWOULDBLOCK) 1063 log_warn("recvfrom udp"); 1064 } 1065 1066 void 1067 unix_readcb(int fd, short event, void *arg) 1068 { 1069 struct sockaddr_un sa; 1070 socklen_t salen; 1071 ssize_t n; 1072 1073 salen = sizeof(sa); 1074 n = recvfrom(fd, linebuf, LOG_MAXLINE, 0, (struct sockaddr *)&sa, 1075 &salen); 1076 if (n > 0) { 1077 linebuf[n] = '\0'; 1078 printline(LocalHostName, linebuf); 1079 } else if (n < 0 && errno != EINTR && errno != EWOULDBLOCK) 1080 log_warn("recvfrom unix"); 1081 } 1082 1083 int 1084 reserve_accept4(int lfd, int event, struct event *ev, 1085 void (*cb)(int, short, void *), 1086 struct sockaddr *sa, socklen_t *salen, int flags) 1087 { 1088 struct timeval to = { 1, 0 }; 1089 int afd; 1090 1091 if (event & EV_TIMEOUT) { 1092 log_debug("Listen again"); 1093 /* Enable the listen event, there is no timeout anymore. */ 1094 event_set(ev, lfd, EV_READ|EV_PERSIST, cb, ev); 1095 event_add(ev, NULL); 1096 errno = EWOULDBLOCK; 1097 return (-1); 1098 } 1099 1100 if (getdtablecount() + FD_RESERVE >= getdtablesize()) { 1101 afd = -1; 1102 errno = EMFILE; 1103 } else 1104 afd = accept4(lfd, sa, salen, flags); 1105 1106 if (afd == -1 && (errno == ENFILE || errno == EMFILE)) { 1107 log_info(LOG_WARNING, "accept deferred: %s", strerror(errno)); 1108 /* 1109 * Disable the listen event and convert it to a timeout. 1110 * Pass the listen file descriptor to the callback. 1111 */ 1112 event_del(ev); 1113 event_set(ev, lfd, 0, cb, ev); 1114 event_add(ev, &to); 1115 return (-1); 1116 } 1117 1118 return (afd); 1119 } 1120 1121 void 1122 tcp_acceptcb(int lfd, short event, void *arg) 1123 { 1124 acceptcb(lfd, event, arg, 0); 1125 } 1126 1127 void 1128 tls_acceptcb(int lfd, short event, void *arg) 1129 { 1130 acceptcb(lfd, event, arg, 1); 1131 } 1132 1133 void 1134 acceptcb(int lfd, short event, void *arg, int usetls) 1135 { 1136 struct event *ev = arg; 1137 struct peer *p; 1138 struct sockaddr_storage ss; 1139 socklen_t sslen; 1140 char hostname[NI_MAXHOST], servname[NI_MAXSERV]; 1141 char *peername; 1142 int fd; 1143 1144 sslen = sizeof(ss); 1145 if ((fd = reserve_accept4(lfd, event, ev, tcp_acceptcb, 1146 (struct sockaddr *)&ss, &sslen, SOCK_NONBLOCK)) == -1) { 1147 if (errno != ENFILE && errno != EMFILE && 1148 errno != EINTR && errno != EWOULDBLOCK && 1149 errno != ECONNABORTED) 1150 log_warn("accept tcp socket"); 1151 return; 1152 } 1153 log_debug("Accepting tcp connection"); 1154 1155 if (getnameinfo((struct sockaddr *)&ss, sslen, hostname, 1156 sizeof(hostname), servname, sizeof(servname), 1157 NI_NUMERICHOST | NI_NUMERICSERV) != 0 || 1158 asprintf(&peername, ss.ss_family == AF_INET6 ? 1159 "[%s]:%s" : "%s:%s", hostname, servname) == -1) { 1160 log_debug("Malformed accept address"); 1161 peername = hostname_unknown; 1162 } 1163 log_debug("Peer addresss and port %s", peername); 1164 if ((p = malloc(sizeof(*p))) == NULL) { 1165 log_warn("allocate \"%s\"", peername); 1166 close(fd); 1167 return; 1168 } 1169 p->p_fd = fd; 1170 if ((p->p_bufev = bufferevent_new(fd, tcp_readcb, NULL, tcp_closecb, 1171 p)) == NULL) { 1172 log_warn("bufferevent \"%s\"", peername); 1173 free(p); 1174 close(fd); 1175 return; 1176 } 1177 p->p_ctx = NULL; 1178 if (usetls) { 1179 if (tls_accept_socket(server_ctx, &p->p_ctx, fd) < 0) { 1180 log_warnx("tls_accept_socket \"%s\": %s", 1181 peername, tls_error(server_ctx)); 1182 bufferevent_free(p->p_bufev); 1183 free(p); 1184 close(fd); 1185 return; 1186 } 1187 buffertls_set(&p->p_buftls, p->p_bufev, p->p_ctx, fd); 1188 buffertls_accept(&p->p_buftls, fd); 1189 log_debug("tcp accept callback: tls context success"); 1190 } 1191 if (!NoDNS && peername != hostname_unknown && 1192 priv_getnameinfo((struct sockaddr *)&ss, ss.ss_len, hostname, 1193 sizeof(hostname)) != 0) { 1194 log_debug("Host name for accept address (%s) unknown", 1195 hostname); 1196 } 1197 if (peername == hostname_unknown || 1198 (p->p_hostname = strdup(hostname)) == NULL) 1199 p->p_hostname = hostname_unknown; 1200 log_debug("Peer hostname %s", hostname); 1201 p->p_peername = peername; 1202 bufferevent_enable(p->p_bufev, EV_READ); 1203 1204 log_info(LOG_DEBUG, "%s logger \"%s\" accepted", 1205 p->p_ctx ? "tls" : "tcp", peername); 1206 } 1207 1208 /* 1209 * Syslog over TCP RFC 6587 3.4.1. Octet Counting 1210 */ 1211 int 1212 octet_counting(struct evbuffer *evbuf, char **msg, int drain) 1213 { 1214 char *p, *buf, *end; 1215 int len; 1216 1217 buf = EVBUFFER_DATA(evbuf); 1218 end = buf + EVBUFFER_LENGTH(evbuf); 1219 /* 1220 * It can be assumed that octet-counting framing is used if a syslog 1221 * frame starts with a digit. 1222 */ 1223 if (buf >= end || !isdigit((unsigned char)*buf)) 1224 return (-1); 1225 /* 1226 * SYSLOG-FRAME = MSG-LEN SP SYSLOG-MSG 1227 * MSG-LEN is the octet count of the SYSLOG-MSG in the SYSLOG-FRAME. 1228 * We support up to 5 digits in MSG-LEN, so the maximum is 99999. 1229 */ 1230 for (p = buf; p < end && p < buf + 5; p++) { 1231 if (!isdigit((unsigned char)*p)) 1232 break; 1233 } 1234 if (buf >= p || p >= end || *p != ' ') 1235 return (-1); 1236 p++; 1237 /* Using atoi() is safe as buf starts with 1 to 5 digits and a space. */ 1238 len = atoi(buf); 1239 if (drain) 1240 log_debugadd(" octet counting %d", len); 1241 if (p + len > end) 1242 return (0); 1243 if (drain) 1244 evbuffer_drain(evbuf, p - buf); 1245 if (msg) 1246 *msg = p; 1247 return (len); 1248 } 1249 1250 /* 1251 * Syslog over TCP RFC 6587 3.4.2. Non-Transparent-Framing 1252 */ 1253 int 1254 non_transparent_framing(struct evbuffer *evbuf, char **msg) 1255 { 1256 char *p, *buf, *end; 1257 1258 buf = EVBUFFER_DATA(evbuf); 1259 end = buf + EVBUFFER_LENGTH(evbuf); 1260 /* 1261 * The TRAILER has usually been a single character and most often 1262 * is ASCII LF (%d10). However, other characters have also been 1263 * seen, with ASCII NUL (%d00) being a prominent example. 1264 */ 1265 for (p = buf; p < end; p++) { 1266 if (*p == '\0' || *p == '\n') 1267 break; 1268 } 1269 if (p + 1 - buf >= INT_MAX) 1270 return (-1); 1271 log_debugadd(" non transparent framing"); 1272 if (p >= end) 1273 return (0); 1274 /* 1275 * Some devices have also been seen to emit a two-character 1276 * TRAILER, which is usually CR and LF. 1277 */ 1278 if (buf < p && p[0] == '\n' && p[-1] == '\r') 1279 p[-1] = '\0'; 1280 if (msg) 1281 *msg = buf; 1282 return (p + 1 - buf); 1283 } 1284 1285 void 1286 tcp_readcb(struct bufferevent *bufev, void *arg) 1287 { 1288 struct peer *p = arg; 1289 char *msg; 1290 int len; 1291 1292 while (EVBUFFER_LENGTH(bufev->input) > 0) { 1293 log_debugadd("%s logger \"%s\"", p->p_ctx ? "tls" : "tcp", 1294 p->p_peername); 1295 msg = NULL; 1296 len = octet_counting(bufev->input, &msg, 1); 1297 if (len < 0) 1298 len = non_transparent_framing(bufev->input, &msg); 1299 if (len < 0) 1300 log_debugadd("unknown method"); 1301 if (msg == NULL) { 1302 log_debugadd(", incomplete frame"); 1303 break; 1304 } 1305 log_debug(", use %d bytes", len); 1306 if (len > 0 && msg[len-1] == '\n') 1307 msg[len-1] = '\0'; 1308 if (len == 0 || msg[len-1] != '\0') { 1309 memcpy(linebuf, msg, MINIMUM(len, LOG_MAXLINE)); 1310 linebuf[MINIMUM(len, LOG_MAXLINE)] = '\0'; 1311 msg = linebuf; 1312 } 1313 printline(p->p_hostname, msg); 1314 evbuffer_drain(bufev->input, len); 1315 } 1316 /* Maximum frame has 5 digits, 1 space, MAXLINE chars, 1 new line. */ 1317 if (EVBUFFER_LENGTH(bufev->input) >= 5 + 1 + LOG_MAXLINE + 1) { 1318 log_debug(", use %zu bytes", EVBUFFER_LENGTH(bufev->input)); 1319 printline(p->p_hostname, EVBUFFER_DATA(bufev->input)); 1320 evbuffer_drain(bufev->input, -1); 1321 } else if (EVBUFFER_LENGTH(bufev->input) > 0) 1322 log_debug(", buffer %zu bytes", EVBUFFER_LENGTH(bufev->input)); 1323 } 1324 1325 void 1326 tcp_closecb(struct bufferevent *bufev, short event, void *arg) 1327 { 1328 struct peer *p = arg; 1329 1330 if (event & EVBUFFER_EOF) { 1331 log_info(LOG_DEBUG, "%s logger \"%s\" connection close", 1332 p->p_ctx ? "tls" : "tcp", p->p_peername); 1333 } else { 1334 log_info(LOG_NOTICE, "%s logger \"%s\" connection error: %s", 1335 p->p_ctx ? "tls" : "tcp", p->p_peername, 1336 p->p_ctx ? tls_error(p->p_ctx) : strerror(errno)); 1337 } 1338 1339 if (p->p_peername != hostname_unknown) 1340 free(p->p_peername); 1341 if (p->p_hostname != hostname_unknown) 1342 free(p->p_hostname); 1343 bufferevent_free(p->p_bufev); 1344 close(p->p_fd); 1345 free(p); 1346 } 1347 1348 int 1349 tcp_socket(struct filed *f) 1350 { 1351 int s; 1352 1353 if ((s = socket(f->f_un.f_forw.f_addr.ss_family, 1354 SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) { 1355 log_warn("socket \"%s\"", f->f_un.f_forw.f_loghost); 1356 return (-1); 1357 } 1358 set_sockbuf(s); 1359 if (connect(s, (struct sockaddr *)&f->f_un.f_forw.f_addr, 1360 f->f_un.f_forw.f_addr.ss_len) == -1 && errno != EINPROGRESS) { 1361 log_warn("connect \"%s\"", f->f_un.f_forw.f_loghost); 1362 close(s); 1363 return (-1); 1364 } 1365 return (s); 1366 } 1367 1368 void 1369 tcp_dropcb(struct bufferevent *bufev, void *arg) 1370 { 1371 struct filed *f = arg; 1372 1373 /* 1374 * Drop data received from the forward log server. 1375 */ 1376 log_debug("loghost \"%s\" did send %zu bytes back", 1377 f->f_un.f_forw.f_loghost, EVBUFFER_LENGTH(bufev->input)); 1378 evbuffer_drain(bufev->input, -1); 1379 } 1380 1381 void 1382 tcp_writecb(struct bufferevent *bufev, void *arg) 1383 { 1384 struct filed *f = arg; 1385 char ebuf[ERRBUFSIZE]; 1386 1387 /* 1388 * Successful write, connection to server is good, reset wait time. 1389 */ 1390 log_debug("loghost \"%s\" successful write", f->f_un.f_forw.f_loghost); 1391 f->f_un.f_forw.f_reconnectwait = 0; 1392 1393 if (f->f_dropped > 0 && 1394 EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) < MAX_TCPBUF) { 1395 snprintf(ebuf, sizeof(ebuf), "to loghost \"%s\"", 1396 f->f_un.f_forw.f_loghost); 1397 dropped_warn(&f->f_dropped, ebuf); 1398 } 1399 } 1400 1401 void 1402 tcp_errorcb(struct bufferevent *bufev, short event, void *arg) 1403 { 1404 struct filed *f = arg; 1405 char *p, *buf, *end; 1406 int l; 1407 char ebuf[ERRBUFSIZE]; 1408 1409 if (event & EVBUFFER_EOF) 1410 snprintf(ebuf, sizeof(ebuf), "loghost \"%s\" connection close", 1411 f->f_un.f_forw.f_loghost); 1412 else 1413 snprintf(ebuf, sizeof(ebuf), 1414 "loghost \"%s\" connection error: %s", 1415 f->f_un.f_forw.f_loghost, f->f_un.f_forw.f_ctx ? 1416 tls_error(f->f_un.f_forw.f_ctx) : strerror(errno)); 1417 log_debug("%s", ebuf); 1418 1419 /* The SIGHUP handler may also close the socket, so invalidate it. */ 1420 if (f->f_un.f_forw.f_ctx) { 1421 tls_close(f->f_un.f_forw.f_ctx); 1422 tls_free(f->f_un.f_forw.f_ctx); 1423 f->f_un.f_forw.f_ctx = NULL; 1424 } 1425 close(f->f_file); 1426 f->f_file = -1; 1427 1428 /* 1429 * The messages in the output buffer may be out of sync. 1430 * Check that the buffer starts with "1234 <1234 octets>\n". 1431 * Otherwise remove the partial message from the beginning. 1432 */ 1433 buf = EVBUFFER_DATA(bufev->output); 1434 end = buf + EVBUFFER_LENGTH(bufev->output); 1435 if (buf < end && !((l = octet_counting(bufev->output, &p, 0)) > 0 && 1436 p[l-1] == '\n')) { 1437 for (p = buf; p < end; p++) { 1438 if (*p == '\n') { 1439 evbuffer_drain(bufev->output, p - buf + 1); 1440 break; 1441 } 1442 } 1443 /* Without '\n' discard everything. */ 1444 if (p == end) 1445 evbuffer_drain(bufev->output, -1); 1446 log_debug("loghost \"%s\" dropped partial message", 1447 f->f_un.f_forw.f_loghost); 1448 f->f_dropped++; 1449 } 1450 1451 tcp_connect_retry(bufev, f); 1452 1453 /* Log the connection error to the fresh buffer after reconnecting. */ 1454 log_info(LOG_WARNING, "%s", ebuf); 1455 } 1456 1457 void 1458 tcp_connectcb(int fd, short event, void *arg) 1459 { 1460 struct filed *f = arg; 1461 struct bufferevent *bufev = f->f_un.f_forw.f_bufev; 1462 int s; 1463 1464 if ((s = tcp_socket(f)) == -1) { 1465 tcp_connect_retry(bufev, f); 1466 return; 1467 } 1468 log_debug("tcp connect callback: socket success, event %#x", event); 1469 f->f_file = s; 1470 1471 bufferevent_setfd(bufev, s); 1472 bufferevent_setcb(bufev, tcp_dropcb, tcp_writecb, tcp_errorcb, f); 1473 /* 1474 * Although syslog is a write only protocol, enable reading from 1475 * the socket to detect connection close and errors. 1476 */ 1477 bufferevent_enable(bufev, EV_READ|EV_WRITE); 1478 1479 if (f->f_type == F_FORWTLS) { 1480 if ((f->f_un.f_forw.f_ctx = tls_client()) == NULL) { 1481 log_warn("tls_client \"%s\"", f->f_un.f_forw.f_loghost); 1482 goto error; 1483 } 1484 if (client_config && 1485 tls_configure(f->f_un.f_forw.f_ctx, client_config) == -1) { 1486 log_warnx("tls_configure \"%s\": %s", 1487 f->f_un.f_forw.f_loghost, 1488 tls_error(f->f_un.f_forw.f_ctx)); 1489 goto error; 1490 } 1491 if (tls_connect_socket(f->f_un.f_forw.f_ctx, s, 1492 f->f_un.f_forw.f_host) == -1) { 1493 log_warnx("tls_connect_socket \"%s\": %s", 1494 f->f_un.f_forw.f_loghost, 1495 tls_error(f->f_un.f_forw.f_ctx)); 1496 goto error; 1497 } 1498 log_debug("tcp connect callback: tls context success"); 1499 1500 buffertls_set(&f->f_un.f_forw.f_buftls, bufev, 1501 f->f_un.f_forw.f_ctx, s); 1502 buffertls_connect(&f->f_un.f_forw.f_buftls, s); 1503 } 1504 1505 return; 1506 1507 error: 1508 if (f->f_un.f_forw.f_ctx) { 1509 tls_free(f->f_un.f_forw.f_ctx); 1510 f->f_un.f_forw.f_ctx = NULL; 1511 } 1512 close(f->f_file); 1513 f->f_file = -1; 1514 tcp_connect_retry(bufev, f); 1515 } 1516 1517 void 1518 tcp_connect_retry(struct bufferevent *bufev, struct filed *f) 1519 { 1520 struct timeval to; 1521 1522 if (f->f_un.f_forw.f_reconnectwait == 0) 1523 f->f_un.f_forw.f_reconnectwait = 1; 1524 else 1525 f->f_un.f_forw.f_reconnectwait <<= 1; 1526 if (f->f_un.f_forw.f_reconnectwait > 600) 1527 f->f_un.f_forw.f_reconnectwait = 600; 1528 to.tv_sec = f->f_un.f_forw.f_reconnectwait; 1529 to.tv_usec = 0; 1530 1531 log_debug("tcp connect retry: wait %d", 1532 f->f_un.f_forw.f_reconnectwait); 1533 bufferevent_setfd(bufev, -1); 1534 /* We can reuse the write event as bufferevent is disabled. */ 1535 evtimer_set(&bufev->ev_write, tcp_connectcb, f); 1536 evtimer_add(&bufev->ev_write, &to); 1537 } 1538 1539 int 1540 tcpbuf_countmsg(struct bufferevent *bufev) 1541 { 1542 char *p, *buf, *end; 1543 int i = 0; 1544 1545 buf = EVBUFFER_DATA(bufev->output); 1546 end = buf + EVBUFFER_LENGTH(bufev->output); 1547 for (p = buf; p < end; p++) { 1548 if (*p == '\n') 1549 i++; 1550 } 1551 return (i); 1552 } 1553 1554 void 1555 usage(void) 1556 { 1557 1558 (void)fprintf(stderr, 1559 "usage: syslogd [-46dFhnruVZ] [-a path] [-C CAfile]\n" 1560 "\t[-c cert_file] [-f config_file] [-K CAfile] [-k key_file]\n" 1561 "\t[-m mark_interval] [-p log_socket] [-S listen_address]\n" 1562 "\t[-s reporting_socket] [-T listen_address] [-U bind_address]\n"); 1563 exit(1); 1564 } 1565 1566 /* 1567 * Parse a priority code of the form "<123>" into pri, and return the 1568 * length of the priority code including the surrounding angle brackets. 1569 */ 1570 size_t 1571 parsepriority(const char *msg, int *pri) 1572 { 1573 size_t nlen; 1574 char buf[11]; 1575 const char *errstr; 1576 int maybepri; 1577 1578 if (*msg++ == '<') { 1579 nlen = strspn(msg, "1234567890"); 1580 if (nlen > 0 && nlen < sizeof(buf) && msg[nlen] == '>') { 1581 strlcpy(buf, msg, nlen + 1); 1582 maybepri = strtonum(buf, 0, INT_MAX, &errstr); 1583 if (errstr == NULL) { 1584 *pri = maybepri; 1585 return nlen + 2; 1586 } 1587 } 1588 } 1589 1590 return 0; 1591 } 1592 1593 /* 1594 * Take a raw input line, decode the message, and print the message 1595 * on the appropriate log files. 1596 */ 1597 void 1598 printline(char *hname, char *msg) 1599 { 1600 int pri; 1601 char *p, *q, line[LOG_MAXLINE + 4 + 1]; /* message, encoding, NUL */ 1602 1603 /* test for special codes */ 1604 pri = DEFUPRI; 1605 p = msg; 1606 p += parsepriority(p, &pri); 1607 if (pri &~ (LOG_FACMASK|LOG_PRIMASK)) 1608 pri = DEFUPRI; 1609 1610 /* 1611 * Don't allow users to log kernel messages. 1612 * NOTE: since LOG_KERN == 0 this will also match 1613 * messages with no facility specified. 1614 */ 1615 if (LOG_FAC(pri) == LOG_KERN) 1616 pri = LOG_USER | LOG_PRI(pri); 1617 1618 for (q = line; *p && q < &line[LOG_MAXLINE]; p++) { 1619 if (*p == '\n') 1620 *q++ = ' '; 1621 else 1622 q = vis(q, *p, 0, 0); 1623 } 1624 line[LOG_MAXLINE] = *q = '\0'; 1625 1626 logline(pri, 0, hname, line); 1627 } 1628 1629 /* 1630 * Take a raw input line from /dev/klog, split and format similar to syslog(). 1631 */ 1632 void 1633 printsys(char *msg) 1634 { 1635 int c, pri, flags; 1636 char *lp, *p, *q, line[LOG_MAXLINE + 1]; 1637 size_t prilen; 1638 1639 (void)snprintf(line, sizeof line, "%s: ", _PATH_UNIX); 1640 lp = line + strlen(line); 1641 for (p = msg; *p != '\0'; ) { 1642 flags = SYNC_FILE | ADDDATE; /* fsync file after write */ 1643 pri = DEFSPRI; 1644 prilen = parsepriority(p, &pri); 1645 p += prilen; 1646 if (prilen == 0) { 1647 /* kernel printf's come out on console */ 1648 flags |= IGN_CONS; 1649 } 1650 if (pri &~ (LOG_FACMASK|LOG_PRIMASK)) 1651 pri = DEFSPRI; 1652 1653 q = lp; 1654 while (*p && (c = *p++) != '\n' && q < &line[sizeof(line) - 4]) 1655 q = vis(q, c, 0, 0); 1656 1657 logline(pri, flags, LocalHostName, line); 1658 } 1659 } 1660 1661 void 1662 vlogmsg(int pri, const char *proc, const char *fmt, va_list ap) 1663 { 1664 char msg[ERRBUFSIZE]; 1665 size_t l; 1666 1667 l = snprintf(msg, sizeof(msg), "%s[%d]: ", proc, getpid()); 1668 if (l < sizeof(msg)) 1669 vsnprintf(msg + l, sizeof(msg) - l, fmt, ap); 1670 if (!Started) { 1671 fprintf(stderr, "%s\n", msg); 1672 init_dropped++; 1673 return; 1674 } 1675 logline(pri, ADDDATE, LocalHostName, msg); 1676 } 1677 1678 struct timeval now; 1679 1680 /* 1681 * Log a message to the appropriate log files, users, etc. based on 1682 * the priority. 1683 */ 1684 void 1685 logline(int pri, int flags, char *from, char *msg) 1686 { 1687 struct filed *f; 1688 int fac, msglen, prilev, i; 1689 char timestamp[33]; 1690 char prog[NAME_MAX+1]; 1691 1692 log_debug("logline: pri 0%o, flags 0x%x, from %s, msg %s", 1693 pri, flags, from, msg); 1694 1695 /* 1696 * Check to see if msg looks non-standard. 1697 */ 1698 timestamp[0] = '\0'; 1699 msglen = strlen(msg); 1700 if ((flags & ADDDATE) == 0) { 1701 if (msglen >= 16 && msg[3] == ' ' && msg[6] == ' ' && 1702 msg[9] == ':' && msg[12] == ':' && msg[15] == ' ') { 1703 /* BSD syslog TIMESTAMP, RFC 3164 */ 1704 strlcpy(timestamp, msg, 16); 1705 msg += 16; 1706 msglen -= 16; 1707 if (ZuluTime) 1708 flags |= ADDDATE; 1709 } else if (msglen >= 20 && 1710 isdigit(msg[0]) && isdigit(msg[1]) && isdigit(msg[2]) && 1711 isdigit(msg[3]) && msg[4] == '-' && 1712 isdigit(msg[5]) && isdigit(msg[6]) && msg[7] == '-' && 1713 isdigit(msg[8]) && isdigit(msg[9]) && msg[10] == 'T' && 1714 isdigit(msg[11]) && isdigit(msg[12]) && msg[13] == ':' && 1715 isdigit(msg[14]) && isdigit(msg[15]) && msg[16] == ':' && 1716 isdigit(msg[17]) && isdigit(msg[18]) && (msg[19] == '.' || 1717 msg[19] == 'Z' || msg[19] == '+' || msg[19] == '-')) { 1718 /* FULL-DATE "T" FULL-TIME, RFC 5424 */ 1719 strlcpy(timestamp, msg, sizeof(timestamp)); 1720 msg += 19; 1721 msglen -= 19; 1722 i = 0; 1723 if (msglen >= 3 && msg[0] == '.' && isdigit(msg[1])) { 1724 /* TIME-SECFRAC */ 1725 msg += 2; 1726 msglen -= 2; 1727 i += 2; 1728 while(i < 7 && msglen >= 1 && isdigit(msg[0])) { 1729 msg++; 1730 msglen--; 1731 i++; 1732 } 1733 } 1734 if (msglen >= 2 && msg[0] == 'Z' && msg[1] == ' ') { 1735 /* "Z" */ 1736 timestamp[20+i] = '\0'; 1737 msg += 2; 1738 msglen -= 2; 1739 } else if (msglen >= 7 && 1740 (msg[0] == '+' || msg[0] == '-') && 1741 isdigit(msg[1]) && isdigit(msg[2]) && 1742 msg[3] == ':' && 1743 isdigit(msg[4]) && isdigit(msg[5]) && 1744 msg[6] == ' ') { 1745 /* TIME-NUMOFFSET */ 1746 timestamp[25+i] = '\0'; 1747 msg += 7; 1748 msglen -= 7; 1749 } else { 1750 /* invalid time format, roll back */ 1751 timestamp[0] = '\0'; 1752 msg -= 19 + i; 1753 msglen += 19 + i; 1754 flags |= ADDDATE; 1755 } 1756 } else if (msglen >= 2 && msg[0] == '-' && msg[1] == ' ') { 1757 /* NILVALUE, RFC 5424 */ 1758 msg += 2; 1759 msglen -= 2; 1760 flags |= ADDDATE; 1761 } else 1762 flags |= ADDDATE; 1763 } 1764 1765 (void)gettimeofday(&now, NULL); 1766 if (flags & ADDDATE) { 1767 if (ZuluTime) { 1768 struct tm *tm; 1769 size_t l; 1770 1771 tm = gmtime(&now.tv_sec); 1772 l = strftime(timestamp, sizeof(timestamp), "%FT%T", tm); 1773 /* 1774 * Use only millisecond precision as some time has 1775 * passed since syslog(3) was called. 1776 */ 1777 snprintf(timestamp + l, sizeof(timestamp) - l, 1778 ".%03ldZ", now.tv_usec / 1000); 1779 } else 1780 strlcpy(timestamp, ctime(&now.tv_sec) + 4, 16); 1781 } 1782 1783 /* extract facility and priority level */ 1784 if (flags & MARK) 1785 fac = LOG_NFACILITIES; 1786 else { 1787 fac = LOG_FAC(pri); 1788 if (fac >= LOG_NFACILITIES || fac < 0) 1789 fac = LOG_USER; 1790 } 1791 prilev = LOG_PRI(pri); 1792 1793 /* extract program name */ 1794 while (isspace((unsigned char)*msg)) { 1795 msg++; 1796 msglen--; 1797 } 1798 for (i = 0; i < NAME_MAX; i++) { 1799 if (!isalnum((unsigned char)msg[i]) && msg[i] != '-') 1800 break; 1801 prog[i] = msg[i]; 1802 } 1803 prog[i] = 0; 1804 1805 /* log the message to the particular outputs */ 1806 if (!Initialized) { 1807 f = &consfile; 1808 if (f->f_type == F_CONSOLE) { 1809 strlcpy(f->f_lasttime, timestamp, 1810 sizeof(f->f_lasttime)); 1811 strlcpy(f->f_prevhost, from, 1812 sizeof(f->f_prevhost)); 1813 fprintlog(f, flags, msg); 1814 /* May be set to F_UNUSED, try again next time. */ 1815 f->f_type = F_CONSOLE; 1816 } 1817 init_dropped++; 1818 return; 1819 } 1820 SIMPLEQ_FOREACH(f, &Files, f_next) { 1821 /* skip messages that are incorrect priority */ 1822 if (f->f_pmask[fac] < prilev || 1823 f->f_pmask[fac] == INTERNAL_NOPRI) 1824 continue; 1825 1826 /* skip messages with the incorrect program or hostname */ 1827 if (f->f_program && fnmatch(f->f_program, prog, 0) != 0) 1828 continue; 1829 if (f->f_hostname && fnmatch(f->f_hostname, from, 0) != 0) 1830 continue; 1831 1832 if (f->f_type == F_CONSOLE && (flags & IGN_CONS)) 1833 continue; 1834 1835 /* don't output marks to recently written files */ 1836 if ((flags & MARK) && 1837 (now.tv_sec - f->f_time) < MarkInterval / 2) 1838 continue; 1839 1840 /* 1841 * suppress duplicate lines to this file 1842 */ 1843 if ((Repeat == 0 || (Repeat == 1 && 1844 (f->f_type != F_PIPE && f->f_type != F_FORWUDP && 1845 f->f_type != F_FORWTCP && f->f_type != F_FORWTLS))) && 1846 (flags & MARK) == 0 && msglen == f->f_prevlen && 1847 !strcmp(msg, f->f_prevline) && 1848 !strcmp(from, f->f_prevhost)) { 1849 strlcpy(f->f_lasttime, timestamp, 1850 sizeof(f->f_lasttime)); 1851 f->f_prevcount++; 1852 log_debug("msg repeated %d times, %ld sec of %d", 1853 f->f_prevcount, (long)(now.tv_sec - f->f_time), 1854 repeatinterval[f->f_repeatcount]); 1855 /* 1856 * If domark would have logged this by now, 1857 * flush it now (so we don't hold isolated messages), 1858 * but back off so we'll flush less often 1859 * in the future. 1860 */ 1861 if (now.tv_sec > REPEATTIME(f)) { 1862 fprintlog(f, flags, (char *)NULL); 1863 BACKOFF(f); 1864 } 1865 } else { 1866 /* new line, save it */ 1867 if (f->f_prevcount) 1868 fprintlog(f, 0, (char *)NULL); 1869 f->f_repeatcount = 0; 1870 f->f_prevpri = pri; 1871 strlcpy(f->f_lasttime, timestamp, 1872 sizeof(f->f_lasttime)); 1873 strlcpy(f->f_prevhost, from, 1874 sizeof(f->f_prevhost)); 1875 if (msglen < MAXSVLINE) { 1876 f->f_prevlen = msglen; 1877 strlcpy(f->f_prevline, msg, 1878 sizeof(f->f_prevline)); 1879 fprintlog(f, flags, (char *)NULL); 1880 } else { 1881 f->f_prevline[0] = 0; 1882 f->f_prevlen = 0; 1883 fprintlog(f, flags, msg); 1884 } 1885 } 1886 1887 if (f->f_quick) 1888 break; 1889 } 1890 } 1891 1892 void 1893 fprintlog(struct filed *f, int flags, char *msg) 1894 { 1895 struct iovec iov[6]; 1896 struct iovec *v; 1897 int l, retryonce; 1898 char line[LOG_MAXLINE + 1], repbuf[80], greetings[500]; 1899 char ebuf[ERRBUFSIZE]; 1900 1901 v = iov; 1902 if (f->f_type == F_WALL) { 1903 l = snprintf(greetings, sizeof(greetings), 1904 "\r\n\7Message from syslogd@%s at %.24s ...\r\n", 1905 f->f_prevhost, ctime(&now.tv_sec)); 1906 if (l < 0 || (size_t)l >= sizeof(greetings)) 1907 l = strlen(greetings); 1908 v->iov_base = greetings; 1909 v->iov_len = l; 1910 v++; 1911 v->iov_base = ""; 1912 v->iov_len = 0; 1913 v++; 1914 } else if (f->f_lasttime[0] != '\0') { 1915 v->iov_base = f->f_lasttime; 1916 v->iov_len = strlen(f->f_lasttime); 1917 v++; 1918 v->iov_base = " "; 1919 v->iov_len = 1; 1920 v++; 1921 } else { 1922 v->iov_base = ""; 1923 v->iov_len = 0; 1924 v++; 1925 v->iov_base = ""; 1926 v->iov_len = 0; 1927 v++; 1928 } 1929 if (f->f_prevhost[0] != '\0') { 1930 v->iov_base = f->f_prevhost; 1931 v->iov_len = strlen(v->iov_base); 1932 v++; 1933 v->iov_base = " "; 1934 v->iov_len = 1; 1935 v++; 1936 } else { 1937 v->iov_base = ""; 1938 v->iov_len = 0; 1939 v++; 1940 v->iov_base = ""; 1941 v->iov_len = 0; 1942 v++; 1943 } 1944 1945 if (msg) { 1946 v->iov_base = msg; 1947 v->iov_len = strlen(msg); 1948 } else if (f->f_prevcount > 1) { 1949 l = snprintf(repbuf, sizeof(repbuf), 1950 "last message repeated %d times", f->f_prevcount); 1951 if (l < 0 || (size_t)l >= sizeof(repbuf)) 1952 l = strlen(repbuf); 1953 v->iov_base = repbuf; 1954 v->iov_len = l; 1955 } else { 1956 v->iov_base = f->f_prevline; 1957 v->iov_len = f->f_prevlen; 1958 } 1959 v++; 1960 1961 log_debugadd("Logging to %s", TypeNames[f->f_type]); 1962 f->f_time = now.tv_sec; 1963 1964 switch (f->f_type) { 1965 case F_UNUSED: 1966 log_debug("%s", ""); 1967 break; 1968 1969 case F_FORWUDP: 1970 log_debug(" %s", f->f_un.f_forw.f_loghost); 1971 l = snprintf(line, MINIMUM(MAX_UDPMSG + 1, sizeof(line)), 1972 "<%d>%.32s %s%s%s", f->f_prevpri, (char *)iov[0].iov_base, 1973 IncludeHostname ? LocalHostName : "", 1974 IncludeHostname ? " " : "", 1975 (char *)iov[4].iov_base); 1976 if (l < 0 || (size_t)l > MINIMUM(MAX_UDPMSG, sizeof(line))) 1977 l = MINIMUM(MAX_UDPMSG, sizeof(line)); 1978 if (sendto(f->f_file, line, l, 0, 1979 (struct sockaddr *)&f->f_un.f_forw.f_addr, 1980 f->f_un.f_forw.f_addr.ss_len) != l) { 1981 switch (errno) { 1982 case EADDRNOTAVAIL: 1983 case EHOSTDOWN: 1984 case EHOSTUNREACH: 1985 case ENETDOWN: 1986 case ENETUNREACH: 1987 case ENOBUFS: 1988 case EWOULDBLOCK: 1989 /* silently dropped */ 1990 break; 1991 default: 1992 f->f_type = F_UNUSED; 1993 log_warn("sendto \"%s\"", 1994 f->f_un.f_forw.f_loghost); 1995 break; 1996 } 1997 } 1998 break; 1999 2000 case F_FORWTCP: 2001 case F_FORWTLS: 2002 log_debugadd(" %s", f->f_un.f_forw.f_loghost); 2003 if (EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) >= 2004 MAX_TCPBUF) { 2005 log_debug(" (dropped)"); 2006 f->f_dropped++; 2007 break; 2008 } 2009 /* 2010 * Syslog over TLS RFC 5425 4.3. Sending Data 2011 * Syslog over TCP RFC 6587 3.4.1. Octet Counting 2012 * Use an additional '\n' to split messages. This allows 2013 * buffer synchronisation, helps legacy implementations, 2014 * and makes line based testing easier. 2015 */ 2016 l = snprintf(line, sizeof(line), "<%d>%.32s %s%s\n", 2017 f->f_prevpri, (char *)iov[0].iov_base, 2018 IncludeHostname ? LocalHostName : "", 2019 IncludeHostname ? " " : ""); 2020 if (l < 0) { 2021 log_debug(" (dropped snprintf)"); 2022 f->f_dropped++; 2023 break; 2024 } 2025 l = evbuffer_add_printf(f->f_un.f_forw.f_bufev->output, 2026 "%zu <%d>%.32s %s%s%s\n", 2027 (size_t)l + strlen(iov[4].iov_base), 2028 f->f_prevpri, (char *)iov[0].iov_base, 2029 IncludeHostname ? LocalHostName : "", 2030 IncludeHostname ? " " : "", 2031 (char *)iov[4].iov_base); 2032 if (l < 0) { 2033 log_debug(" (dropped evbuffer_add_printf)"); 2034 f->f_dropped++; 2035 break; 2036 } 2037 bufferevent_enable(f->f_un.f_forw.f_bufev, EV_WRITE); 2038 log_debug("%s", ""); 2039 break; 2040 2041 case F_CONSOLE: 2042 if (flags & IGN_CONS) { 2043 log_debug(" (ignored)"); 2044 break; 2045 } 2046 /* FALLTHROUGH */ 2047 2048 case F_TTY: 2049 case F_FILE: 2050 case F_PIPE: 2051 log_debug(" %s", f->f_un.f_fname); 2052 if (f->f_type != F_FILE && f->f_type != F_PIPE) { 2053 v->iov_base = "\r\n"; 2054 v->iov_len = 2; 2055 } else { 2056 v->iov_base = "\n"; 2057 v->iov_len = 1; 2058 } 2059 retryonce = 0; 2060 again: 2061 if (writev(f->f_file, iov, 6) < 0) { 2062 int e = errno; 2063 2064 /* allow to recover from file system full */ 2065 if (e == ENOSPC && f->f_type == F_FILE) { 2066 if (f->f_dropped++ == 0) { 2067 f->f_type = F_UNUSED; 2068 errno = e; 2069 log_warn("write to file \"%s\"", 2070 f->f_un.f_fname); 2071 f->f_type = F_FILE; 2072 } 2073 break; 2074 } 2075 2076 /* pipe is non-blocking. log and drop message if full */ 2077 if (e == EAGAIN && f->f_type == F_PIPE) { 2078 if (now.tv_sec - f->f_lasterrtime > 120) { 2079 f->f_lasterrtime = now.tv_sec; 2080 log_warn("write to pipe \"%s\"", 2081 f->f_un.f_fname); 2082 } 2083 break; 2084 } 2085 2086 /* 2087 * Check for errors on TTY's or program pipes. 2088 * Errors happen due to loss of tty or died programs. 2089 */ 2090 if (e == EAGAIN) { 2091 /* 2092 * Silently drop messages on blocked write. 2093 * This can happen when logging to a locked tty. 2094 */ 2095 break; 2096 } 2097 2098 (void)close(f->f_file); 2099 if ((e == EIO || e == EBADF) && 2100 f->f_type != F_FILE && f->f_type != F_PIPE && 2101 !retryonce) { 2102 f->f_file = priv_open_tty(f->f_un.f_fname); 2103 retryonce = 1; 2104 if (f->f_file < 0) { 2105 f->f_type = F_UNUSED; 2106 log_warn("priv_open_tty \"%s\"", 2107 f->f_un.f_fname); 2108 } else 2109 goto again; 2110 } else if ((e == EPIPE || e == EBADF) && 2111 f->f_type == F_PIPE && !retryonce) { 2112 f->f_file = priv_open_log(f->f_un.f_fname); 2113 retryonce = 1; 2114 if (f->f_file < 0) { 2115 f->f_type = F_UNUSED; 2116 log_warn("priv_open_log \"%s\"", 2117 f->f_un.f_fname); 2118 } else 2119 goto again; 2120 } else { 2121 f->f_type = F_UNUSED; 2122 f->f_file = -1; 2123 errno = e; 2124 log_warn("writev \"%s\"", f->f_un.f_fname); 2125 } 2126 } else { 2127 if (flags & SYNC_FILE) 2128 (void)fsync(f->f_file); 2129 if (f->f_dropped && f->f_type == F_FILE) { 2130 snprintf(ebuf, sizeof(ebuf), "to file \"%s\"", 2131 f->f_un.f_fname); 2132 dropped_warn(&f->f_dropped, ebuf); 2133 } 2134 } 2135 break; 2136 2137 case F_USERS: 2138 case F_WALL: 2139 log_debug("%s", ""); 2140 v->iov_base = "\r\n"; 2141 v->iov_len = 2; 2142 wallmsg(f, iov); 2143 break; 2144 2145 case F_MEMBUF: 2146 log_debug("%s", ""); 2147 snprintf(line, sizeof(line), "%.32s %s %s", 2148 (char *)iov[0].iov_base, (char *)iov[2].iov_base, 2149 (char *)iov[4].iov_base); 2150 if (ringbuf_append_line(f->f_un.f_mb.f_rb, line) == 1) 2151 f->f_un.f_mb.f_overflow = 1; 2152 if (f->f_un.f_mb.f_attached) 2153 ctlconn_logto(line); 2154 break; 2155 } 2156 f->f_prevcount = 0; 2157 } 2158 2159 /* 2160 * WALLMSG -- Write a message to the world at large 2161 * 2162 * Write the specified message to either the entire 2163 * world, or a list of approved users. 2164 */ 2165 void 2166 wallmsg(struct filed *f, struct iovec *iov) 2167 { 2168 struct utmp ut; 2169 char utline[sizeof(ut.ut_line) + 1]; 2170 static int reenter; /* avoid calling ourselves */ 2171 FILE *uf; 2172 int i; 2173 2174 if (reenter++) 2175 return; 2176 if ((uf = priv_open_utmp()) == NULL) { 2177 log_warn("priv_open_utmp"); 2178 reenter = 0; 2179 return; 2180 } 2181 while (fread(&ut, sizeof(ut), 1, uf) == 1) { 2182 if (ut.ut_name[0] == '\0') 2183 continue; 2184 /* must use strncpy since ut_* may not be NUL terminated */ 2185 strncpy(utline, ut.ut_line, sizeof(utline) - 1); 2186 utline[sizeof(utline) - 1] = '\0'; 2187 if (f->f_type == F_WALL) { 2188 ttymsg(iov, 6, utline); 2189 continue; 2190 } 2191 /* should we send the message to this user? */ 2192 for (i = 0; i < MAXUNAMES; i++) { 2193 if (!f->f_un.f_uname[i][0]) 2194 break; 2195 if (!strncmp(f->f_un.f_uname[i], ut.ut_name, 2196 UT_NAMESIZE)) { 2197 ttymsg(iov, 6, utline); 2198 break; 2199 } 2200 } 2201 } 2202 (void)fclose(uf); 2203 reenter = 0; 2204 } 2205 2206 /* 2207 * Return a printable representation of a host address. 2208 */ 2209 void 2210 cvthname(struct sockaddr *f, char *result, size_t res_len) 2211 { 2212 if (getnameinfo(f, f->sa_len, result, res_len, NULL, 0, 2213 NI_NUMERICHOST|NI_NUMERICSERV|NI_DGRAM) != 0) { 2214 log_debug("Malformed from address"); 2215 strlcpy(result, hostname_unknown, res_len); 2216 return; 2217 } 2218 log_debug("cvthname(%s)", result); 2219 if (NoDNS) 2220 return; 2221 2222 if (priv_getnameinfo(f, f->sa_len, result, res_len) != 0) 2223 log_debug("Host name for from address (%s) unknown", result); 2224 } 2225 2226 void 2227 die_signalcb(int signum, short event, void *arg) 2228 { 2229 die(signum); 2230 } 2231 2232 void 2233 mark_timercb(int unused, short event, void *arg) 2234 { 2235 struct event *ev = arg; 2236 struct timeval to; 2237 2238 markit(); 2239 2240 to.tv_sec = TIMERINTVL; 2241 to.tv_usec = 0; 2242 evtimer_add(ev, &to); 2243 } 2244 2245 void 2246 init_signalcb(int signum, short event, void *arg) 2247 { 2248 init(); 2249 log_info(LOG_INFO, "restart"); 2250 2251 dropped_warn(&file_dropped, "to file"); 2252 dropped_warn(&tcpbuf_dropped, "to remote loghost"); 2253 log_debug("syslogd: restarted"); 2254 } 2255 2256 void 2257 logevent(int severity, const char *msg) 2258 { 2259 log_debug("libevent: [%d] %s", severity, msg); 2260 } 2261 2262 void 2263 dropped_warn(int *count, const char *what) 2264 { 2265 int dropped; 2266 2267 if (*count == 0) 2268 return; 2269 2270 dropped = *count; 2271 *count = 0; 2272 log_info(LOG_WARNING, "dropped %d message%s %s", 2273 dropped, dropped == 1 ? "" : "s", what); 2274 } 2275 2276 __dead void 2277 die(int signo) 2278 { 2279 struct filed *f; 2280 2281 SIMPLEQ_FOREACH(f, &Files, f_next) { 2282 /* flush any pending output */ 2283 if (f->f_prevcount) 2284 fprintlog(f, 0, (char *)NULL); 2285 if (f->f_type == F_FORWTLS || f->f_type == F_FORWTCP) { 2286 tcpbuf_dropped += f->f_dropped + 2287 tcpbuf_countmsg(f->f_un.f_forw.f_bufev); 2288 f->f_dropped = 0; 2289 } 2290 if (f->f_type == F_FILE) { 2291 file_dropped += f->f_dropped; 2292 f->f_dropped = 0; 2293 } 2294 } 2295 dropped_warn(&init_dropped, "during initialization"); 2296 dropped_warn(&file_dropped, "to file"); 2297 dropped_warn(&tcpbuf_dropped, "to remote loghost"); 2298 2299 if (signo) 2300 log_info(LOG_ERR, "exiting on signal %d", signo); 2301 log_debug("syslogd: exited"); 2302 exit(0); 2303 } 2304 2305 /* 2306 * INIT -- Initialize syslogd from configuration table 2307 */ 2308 void 2309 init(void) 2310 { 2311 char progblock[NAME_MAX+1], hostblock[NAME_MAX+1], *cline, *p, *q; 2312 struct filed_list mb; 2313 struct filed *f, *m; 2314 FILE *cf; 2315 int i; 2316 size_t s; 2317 2318 log_debug("init"); 2319 2320 /* If config file has been modified, then just die to restart */ 2321 if (priv_config_modified()) { 2322 log_debug("config file changed: dying"); 2323 die(0); 2324 } 2325 2326 /* 2327 * Close all open log files. 2328 */ 2329 Initialized = 0; 2330 SIMPLEQ_INIT(&mb); 2331 while (!SIMPLEQ_EMPTY(&Files)) { 2332 f = SIMPLEQ_FIRST(&Files); 2333 SIMPLEQ_REMOVE_HEAD(&Files, f_next); 2334 /* flush any pending output */ 2335 if (f->f_prevcount) 2336 fprintlog(f, 0, (char *)NULL); 2337 2338 switch (f->f_type) { 2339 case F_FORWTLS: 2340 if (f->f_un.f_forw.f_ctx) { 2341 tls_close(f->f_un.f_forw.f_ctx); 2342 tls_free(f->f_un.f_forw.f_ctx); 2343 } 2344 free(f->f_un.f_forw.f_host); 2345 /* FALLTHROUGH */ 2346 case F_FORWTCP: 2347 tcpbuf_dropped += f->f_dropped + 2348 tcpbuf_countmsg(f->f_un.f_forw.f_bufev); 2349 bufferevent_free(f->f_un.f_forw.f_bufev); 2350 /* FALLTHROUGH */ 2351 case F_FILE: 2352 if (f->f_type == F_FILE) { 2353 file_dropped += f->f_dropped; 2354 f->f_dropped = 0; 2355 } 2356 case F_TTY: 2357 case F_CONSOLE: 2358 case F_PIPE: 2359 (void)close(f->f_file); 2360 break; 2361 } 2362 free(f->f_program); 2363 free(f->f_hostname); 2364 if (f->f_type == F_MEMBUF) { 2365 f->f_program = NULL; 2366 f->f_hostname = NULL; 2367 log_debug("add %p to mb", f); 2368 SIMPLEQ_INSERT_HEAD(&mb, f, f_next); 2369 } else 2370 free(f); 2371 } 2372 SIMPLEQ_INIT(&Files); 2373 2374 /* open the configuration file */ 2375 if ((cf = priv_open_config()) == NULL) { 2376 log_debug("cannot open %s", ConfFile); 2377 SIMPLEQ_INSERT_TAIL(&Files, 2378 cfline("*.ERR\t/dev/console", "*", "*"), f_next); 2379 SIMPLEQ_INSERT_TAIL(&Files, 2380 cfline("*.PANIC\t*", "*", "*"), f_next); 2381 Initialized = 1; 2382 dropped_warn(&init_dropped, "during initialization"); 2383 return; 2384 } 2385 2386 /* 2387 * Foreach line in the conf table, open that file. 2388 */ 2389 cline = NULL; 2390 s = 0; 2391 strlcpy(progblock, "*", sizeof(progblock)); 2392 strlcpy(hostblock, "*", sizeof(hostblock)); 2393 while (getline(&cline, &s, cf) != -1) { 2394 /* 2395 * check for end-of-section, comments, strip off trailing 2396 * spaces and newline character. !progblock and +hostblock 2397 * are treated specially: the following lines apply only to 2398 * that program. 2399 */ 2400 for (p = cline; isspace((unsigned char)*p); ++p) 2401 continue; 2402 if (*p == '\0' || *p == '#') 2403 continue; 2404 if (*p == '!' || *p == '+') { 2405 q = (*p == '!') ? progblock : hostblock; 2406 p++; 2407 while (isspace((unsigned char)*p)) 2408 p++; 2409 if (*p == '\0' || (*p == '*' && (p[1] == '\0' || 2410 isspace((unsigned char)p[1])))) { 2411 strlcpy(q, "*", NAME_MAX+1); 2412 continue; 2413 } 2414 for (i = 0; i < NAME_MAX; i++) { 2415 if (*p == '\0' || isspace((unsigned char)*p)) 2416 break; 2417 *q++ = *p++; 2418 } 2419 *q = '\0'; 2420 continue; 2421 } 2422 2423 p = cline + strlen(cline); 2424 while (p > cline) 2425 if (!isspace((unsigned char)*--p)) { 2426 p++; 2427 break; 2428 } 2429 *p = '\0'; 2430 f = cfline(cline, progblock, hostblock); 2431 if (f != NULL) 2432 SIMPLEQ_INSERT_TAIL(&Files, f, f_next); 2433 } 2434 free(cline); 2435 if (!feof(cf)) 2436 fatal("read config file"); 2437 2438 /* Match and initialize the memory buffers */ 2439 SIMPLEQ_FOREACH(f, &Files, f_next) { 2440 if (f->f_type != F_MEMBUF) 2441 continue; 2442 log_debug("Initialize membuf %s at %p", 2443 f->f_un.f_mb.f_mname, f); 2444 2445 SIMPLEQ_FOREACH(m, &mb, f_next) { 2446 if (m->f_un.f_mb.f_rb == NULL) 2447 continue; 2448 if (strcmp(m->f_un.f_mb.f_mname, 2449 f->f_un.f_mb.f_mname) == 0) 2450 break; 2451 } 2452 if (m == NULL) { 2453 log_debug("Membuf no match"); 2454 f->f_un.f_mb.f_rb = ringbuf_init(f->f_un.f_mb.f_len); 2455 if (f->f_un.f_mb.f_rb == NULL) { 2456 f->f_type = F_UNUSED; 2457 log_warn("allocate membuf"); 2458 } 2459 } else { 2460 log_debug("Membuf match f:%p, m:%p", f, m); 2461 f->f_un = m->f_un; 2462 m->f_un.f_mb.f_rb = NULL; 2463 } 2464 } 2465 2466 /* make sure remaining buffers are freed */ 2467 while (!SIMPLEQ_EMPTY(&mb)) { 2468 m = SIMPLEQ_FIRST(&mb); 2469 SIMPLEQ_REMOVE_HEAD(&mb, f_next); 2470 if (m->f_un.f_mb.f_rb != NULL) { 2471 log_warnx("mismatched membuf"); 2472 ringbuf_free(m->f_un.f_mb.f_rb); 2473 } 2474 log_debug("Freeing membuf %p", m); 2475 2476 free(m); 2477 } 2478 2479 /* close the configuration file */ 2480 (void)fclose(cf); 2481 2482 Initialized = 1; 2483 dropped_warn(&init_dropped, "during initialization"); 2484 2485 if (Debug) { 2486 SIMPLEQ_FOREACH(f, &Files, f_next) { 2487 for (i = 0; i <= LOG_NFACILITIES; i++) 2488 if (f->f_pmask[i] == INTERNAL_NOPRI) 2489 printf("X "); 2490 else 2491 printf("%d ", f->f_pmask[i]); 2492 printf("%s: ", TypeNames[f->f_type]); 2493 switch (f->f_type) { 2494 case F_FILE: 2495 case F_TTY: 2496 case F_CONSOLE: 2497 case F_PIPE: 2498 printf("%s", f->f_un.f_fname); 2499 break; 2500 2501 case F_FORWUDP: 2502 case F_FORWTCP: 2503 case F_FORWTLS: 2504 printf("%s", f->f_un.f_forw.f_loghost); 2505 break; 2506 2507 case F_USERS: 2508 for (i = 0; i < MAXUNAMES && 2509 *f->f_un.f_uname[i]; i++) 2510 printf("%s, ", f->f_un.f_uname[i]); 2511 break; 2512 2513 case F_MEMBUF: 2514 printf("%s", f->f_un.f_mb.f_mname); 2515 break; 2516 2517 } 2518 if (f->f_program || f->f_hostname) 2519 printf(" (%s, %s)", 2520 f->f_program ? f->f_program : "*", 2521 f->f_hostname ? f->f_hostname : "*"); 2522 printf("\n"); 2523 } 2524 } 2525 } 2526 2527 #define progmatches(p1, p2) \ 2528 (p1 == p2 || (p1 != NULL && p2 != NULL && strcmp(p1, p2) == 0)) 2529 2530 /* 2531 * Spot a line with a duplicate file, pipe, console, tty, or membuf target. 2532 */ 2533 struct filed * 2534 find_dup(struct filed *f) 2535 { 2536 struct filed *list; 2537 2538 SIMPLEQ_FOREACH(list, &Files, f_next) { 2539 if (list->f_quick || f->f_quick) 2540 continue; 2541 switch (list->f_type) { 2542 case F_FILE: 2543 case F_TTY: 2544 case F_CONSOLE: 2545 case F_PIPE: 2546 if (strcmp(list->f_un.f_fname, f->f_un.f_fname) == 0 && 2547 progmatches(list->f_program, f->f_program) && 2548 progmatches(list->f_hostname, f->f_hostname)) { 2549 log_debug("duplicate %s", f->f_un.f_fname); 2550 return (list); 2551 } 2552 break; 2553 case F_MEMBUF: 2554 if (strcmp(list->f_un.f_mb.f_mname, 2555 f->f_un.f_mb.f_mname) == 0 && 2556 progmatches(list->f_program, f->f_program) && 2557 progmatches(list->f_hostname, f->f_hostname)) { 2558 log_debug("duplicate membuf %s", 2559 f->f_un.f_mb.f_mname); 2560 return (list); 2561 } 2562 break; 2563 } 2564 } 2565 return (NULL); 2566 } 2567 2568 /* 2569 * Crack a configuration file line 2570 */ 2571 struct filed * 2572 cfline(char *line, char *progblock, char *hostblock) 2573 { 2574 int i, pri; 2575 size_t rb_len; 2576 char *bp, *p, *q, *proto, *host, *port, *ipproto; 2577 char buf[LOG_MAXLINE]; 2578 struct filed *xf, *f, *d; 2579 struct timeval to; 2580 2581 log_debug("cfline(\"%s\", f, \"%s\", \"%s\")", 2582 line, progblock, hostblock); 2583 2584 if ((f = calloc(1, sizeof(*f))) == NULL) 2585 fatal("allocate struct filed"); 2586 for (i = 0; i <= LOG_NFACILITIES; i++) 2587 f->f_pmask[i] = INTERNAL_NOPRI; 2588 2589 /* save program name if any */ 2590 f->f_quick = 0; 2591 if (*progblock == '!') { 2592 progblock++; 2593 f->f_quick = 1; 2594 } 2595 if (*hostblock == '+') { 2596 hostblock++; 2597 f->f_quick = 1; 2598 } 2599 if (strcmp(progblock, "*") != 0) 2600 f->f_program = strdup(progblock); 2601 if (strcmp(hostblock, "*") != 0) 2602 f->f_hostname = strdup(hostblock); 2603 2604 /* scan through the list of selectors */ 2605 for (p = line; *p && *p != '\t' && *p != ' ';) { 2606 2607 /* find the end of this facility name list */ 2608 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; ) 2609 continue; 2610 2611 /* collect priority name */ 2612 for (bp = buf; *q && !strchr("\t,; ", *q); ) 2613 *bp++ = *q++; 2614 *bp = '\0'; 2615 2616 /* skip cruft */ 2617 while (*q && strchr(",;", *q)) 2618 q++; 2619 2620 /* decode priority name */ 2621 if (*buf == '*') 2622 pri = LOG_PRIMASK + 1; 2623 else { 2624 /* ignore trailing spaces */ 2625 for (i=strlen(buf)-1; i >= 0 && buf[i] == ' '; i--) { 2626 buf[i]='\0'; 2627 } 2628 2629 pri = decode(buf, prioritynames); 2630 if (pri < 0) { 2631 log_warnx("unknown priority name \"%s\"", buf); 2632 free(f); 2633 return (NULL); 2634 } 2635 } 2636 2637 /* scan facilities */ 2638 while (*p && !strchr("\t.; ", *p)) { 2639 for (bp = buf; *p && !strchr("\t,;. ", *p); ) 2640 *bp++ = *p++; 2641 *bp = '\0'; 2642 if (*buf == '*') 2643 for (i = 0; i < LOG_NFACILITIES; i++) 2644 f->f_pmask[i] = pri; 2645 else { 2646 i = decode(buf, facilitynames); 2647 if (i < 0) { 2648 log_warnx("unknown facility name " 2649 "\"%s\"", buf); 2650 free(f); 2651 return (NULL); 2652 } 2653 f->f_pmask[i >> 3] = pri; 2654 } 2655 while (*p == ',' || *p == ' ') 2656 p++; 2657 } 2658 2659 p = q; 2660 } 2661 2662 /* skip to action part */ 2663 while (*p == '\t' || *p == ' ') 2664 p++; 2665 2666 switch (*p) { 2667 case '@': 2668 if ((strlcpy(f->f_un.f_forw.f_loghost, p, 2669 sizeof(f->f_un.f_forw.f_loghost)) >= 2670 sizeof(f->f_un.f_forw.f_loghost))) { 2671 log_warnx("loghost too long \"%s\"", p); 2672 break; 2673 } 2674 if (loghost_parse(++p, &proto, &host, &port) == -1) { 2675 log_warnx("bad loghost \"%s\"", 2676 f->f_un.f_forw.f_loghost); 2677 break; 2678 } 2679 if (proto == NULL) 2680 proto = "udp"; 2681 ipproto = proto; 2682 if (strcmp(proto, "udp") == 0) { 2683 if (fd_udp == -1) 2684 proto = "udp6"; 2685 if (fd_udp6 == -1) 2686 proto = "udp4"; 2687 ipproto = proto; 2688 } else if (strcmp(proto, "udp4") == 0) { 2689 if (fd_udp == -1) { 2690 log_warnx("no udp4 \"%s\"", 2691 f->f_un.f_forw.f_loghost); 2692 break; 2693 } 2694 } else if (strcmp(proto, "udp6") == 0) { 2695 if (fd_udp6 == -1) { 2696 log_warnx("no udp6 \"%s\"", 2697 f->f_un.f_forw.f_loghost); 2698 break; 2699 } 2700 } else if (strcmp(proto, "tcp") == 0 || 2701 strcmp(proto, "tcp4") == 0 || strcmp(proto, "tcp6") == 0) { 2702 ; 2703 } else if (strcmp(proto, "tls") == 0) { 2704 ipproto = "tcp"; 2705 } else if (strcmp(proto, "tls4") == 0) { 2706 ipproto = "tcp4"; 2707 } else if (strcmp(proto, "tls6") == 0) { 2708 ipproto = "tcp6"; 2709 } else { 2710 log_warnx("bad protocol \"%s\"", 2711 f->f_un.f_forw.f_loghost); 2712 break; 2713 } 2714 if (strlen(host) >= NI_MAXHOST) { 2715 log_warnx("host too long \"%s\"", 2716 f->f_un.f_forw.f_loghost); 2717 break; 2718 } 2719 if (port == NULL) 2720 port = strncmp(proto, "tls", 3) == 0 ? 2721 "syslog-tls" : "syslog"; 2722 if (strlen(port) >= NI_MAXSERV) { 2723 log_warnx("port too long \"%s\"", 2724 f->f_un.f_forw.f_loghost); 2725 break; 2726 } 2727 if (priv_getaddrinfo(ipproto, host, port, 2728 (struct sockaddr*)&f->f_un.f_forw.f_addr, 2729 sizeof(f->f_un.f_forw.f_addr)) != 0) { 2730 log_warnx("bad hostname \"%s\"", 2731 f->f_un.f_forw.f_loghost); 2732 break; 2733 } 2734 f->f_file = -1; 2735 if (strncmp(proto, "udp", 3) == 0) { 2736 switch (f->f_un.f_forw.f_addr.ss_family) { 2737 case AF_INET: 2738 send_udp = 1; 2739 f->f_file = fd_udp; 2740 break; 2741 case AF_INET6: 2742 send_udp6 = 1; 2743 f->f_file = fd_udp6; 2744 break; 2745 } 2746 f->f_type = F_FORWUDP; 2747 } else if (strncmp(ipproto, "tcp", 3) == 0) { 2748 if ((f->f_un.f_forw.f_bufev = bufferevent_new(-1, 2749 tcp_dropcb, tcp_writecb, tcp_errorcb, f)) == NULL) { 2750 log_warn("bufferevent \"%s\"", 2751 f->f_un.f_forw.f_loghost); 2752 break; 2753 } 2754 if (strncmp(proto, "tls", 3) == 0) { 2755 f->f_un.f_forw.f_host = strdup(host); 2756 f->f_type = F_FORWTLS; 2757 } else { 2758 f->f_type = F_FORWTCP; 2759 } 2760 /* 2761 * If we try to connect to a TLS server immediately 2762 * syslogd gets an SIGPIPE as the signal handlers have 2763 * not been set up. Delay the connection until the 2764 * event loop is started. We can reuse the write event 2765 * for that as bufferevent is still disabled. 2766 */ 2767 to.tv_sec = 0; 2768 to.tv_usec = 1; 2769 evtimer_set(&f->f_un.f_forw.f_bufev->ev_write, 2770 tcp_connectcb, f); 2771 evtimer_add(&f->f_un.f_forw.f_bufev->ev_write, &to); 2772 } 2773 break; 2774 2775 case '/': 2776 case '|': 2777 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname)); 2778 d = find_dup(f); 2779 if (d != NULL) { 2780 for (i = 0; i <= LOG_NFACILITIES; i++) 2781 if (f->f_pmask[i] != INTERNAL_NOPRI) 2782 d->f_pmask[i] = f->f_pmask[i]; 2783 free(f); 2784 return (NULL); 2785 } 2786 if (strcmp(p, ctty) == 0) { 2787 f->f_file = priv_open_tty(p); 2788 if (f->f_file < 0) 2789 log_warn("priv_open_tty \"%s\"", p); 2790 } else { 2791 f->f_file = priv_open_log(p); 2792 if (f->f_file < 0) 2793 log_warn("priv_open_log \"%s\"", p); 2794 } 2795 if (f->f_file < 0) { 2796 f->f_type = F_UNUSED; 2797 break; 2798 } 2799 if (isatty(f->f_file)) { 2800 if (strcmp(p, ctty) == 0) 2801 f->f_type = F_CONSOLE; 2802 else 2803 f->f_type = F_TTY; 2804 } else { 2805 if (*p == '|') 2806 f->f_type = F_PIPE; 2807 else { 2808 f->f_type = F_FILE; 2809 2810 /* Clear O_NONBLOCK flag on f->f_file */ 2811 if ((i = fcntl(f->f_file, F_GETFL)) != -1) { 2812 i &= ~O_NONBLOCK; 2813 fcntl(f->f_file, F_SETFL, i); 2814 } 2815 } 2816 } 2817 break; 2818 2819 case '*': 2820 f->f_type = F_WALL; 2821 break; 2822 2823 case ':': 2824 f->f_type = F_MEMBUF; 2825 2826 /* Parse buffer size (in kb) */ 2827 errno = 0; 2828 rb_len = strtoul(++p, &q, 0); 2829 if (*p == '\0' || (errno == ERANGE && rb_len == ULONG_MAX) || 2830 *q != ':' || rb_len == 0) { 2831 f->f_type = F_UNUSED; 2832 log_warnx("strtoul \"%s\"", p); 2833 break; 2834 } 2835 q++; 2836 rb_len *= 1024; 2837 2838 /* Copy buffer name */ 2839 for(i = 0; (size_t)i < sizeof(f->f_un.f_mb.f_mname) - 1; i++) { 2840 if (!isalnum((unsigned char)q[i])) 2841 break; 2842 f->f_un.f_mb.f_mname[i] = q[i]; 2843 } 2844 2845 /* Make sure buffer name is unique */ 2846 xf = find_dup(f); 2847 2848 /* Error on missing or non-unique name, or bad buffer length */ 2849 if (i == 0 || rb_len > MAX_MEMBUF || xf != NULL) { 2850 f->f_type = F_UNUSED; 2851 log_warnx("find_dup \"%s\"", p); 2852 break; 2853 } 2854 2855 /* Set buffer length */ 2856 rb_len = MAXIMUM(rb_len, MIN_MEMBUF); 2857 f->f_un.f_mb.f_len = rb_len; 2858 f->f_un.f_mb.f_overflow = 0; 2859 f->f_un.f_mb.f_attached = 0; 2860 break; 2861 2862 default: 2863 for (i = 0; i < MAXUNAMES && *p; i++) { 2864 for (q = p; *q && *q != ','; ) 2865 q++; 2866 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE); 2867 if ((q - p) > UT_NAMESIZE) 2868 f->f_un.f_uname[i][UT_NAMESIZE] = '\0'; 2869 else 2870 f->f_un.f_uname[i][q - p] = '\0'; 2871 while (*q == ',' || *q == ' ') 2872 q++; 2873 p = q; 2874 } 2875 f->f_type = F_USERS; 2876 break; 2877 } 2878 return (f); 2879 } 2880 2881 /* 2882 * Parse the host and port parts from a loghost string. 2883 */ 2884 int 2885 loghost_parse(char *str, char **proto, char **host, char **port) 2886 { 2887 char *prefix = NULL; 2888 2889 if ((*host = strchr(str, ':')) && 2890 (*host)[1] == '/' && (*host)[2] == '/') { 2891 prefix = str; 2892 **host = '\0'; 2893 str = *host + 3; 2894 } 2895 if (proto) 2896 *proto = prefix; 2897 else if (prefix) 2898 return (-1); 2899 2900 *host = str; 2901 if (**host == '[') { 2902 (*host)++; 2903 str = strchr(*host, ']'); 2904 if (str == NULL) 2905 return (-1); 2906 *str++ = '\0'; 2907 } 2908 *port = strrchr(str, ':'); 2909 if (*port != NULL) 2910 *(*port)++ = '\0'; 2911 2912 return (0); 2913 } 2914 2915 /* 2916 * Retrieve the size of the kernel message buffer, via sysctl. 2917 */ 2918 int 2919 getmsgbufsize(void) 2920 { 2921 int msgbufsize, mib[2]; 2922 size_t size; 2923 2924 mib[0] = CTL_KERN; 2925 mib[1] = KERN_MSGBUFSIZE; 2926 size = sizeof msgbufsize; 2927 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) { 2928 log_debug("couldn't get kern.msgbufsize"); 2929 return (0); 2930 } 2931 return (msgbufsize); 2932 } 2933 2934 /* 2935 * Decode a symbolic name to a numeric value 2936 */ 2937 int 2938 decode(const char *name, const CODE *codetab) 2939 { 2940 const CODE *c; 2941 char *p, buf[40]; 2942 2943 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) { 2944 if (isupper((unsigned char)*name)) 2945 *p = tolower((unsigned char)*name); 2946 else 2947 *p = *name; 2948 } 2949 *p = '\0'; 2950 for (c = codetab; c->c_name; c++) 2951 if (!strcmp(buf, c->c_name)) 2952 return (c->c_val); 2953 2954 return (-1); 2955 } 2956 2957 void 2958 markit(void) 2959 { 2960 struct filed *f; 2961 2962 (void)gettimeofday(&now, NULL); 2963 MarkSeq += TIMERINTVL; 2964 if (MarkSeq >= MarkInterval) { 2965 logline(LOG_INFO, ADDDATE|MARK, LocalHostName, "-- MARK --"); 2966 MarkSeq = 0; 2967 } 2968 2969 SIMPLEQ_FOREACH(f, &Files, f_next) { 2970 if (f->f_prevcount && now.tv_sec >= REPEATTIME(f)) { 2971 log_debug("flush %s: repeated %d times, %d sec", 2972 TypeNames[f->f_type], f->f_prevcount, 2973 repeatinterval[f->f_repeatcount]); 2974 fprintlog(f, 0, (char *)NULL); 2975 BACKOFF(f); 2976 } 2977 } 2978 } 2979 2980 int 2981 unix_socket(char *path, int type, mode_t mode) 2982 { 2983 struct sockaddr_un s_un; 2984 int fd, optval; 2985 mode_t old_umask; 2986 2987 memset(&s_un, 0, sizeof(s_un)); 2988 s_un.sun_family = AF_UNIX; 2989 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >= 2990 sizeof(s_un.sun_path)) { 2991 log_warnx("socket path too long \"%s\"", path); 2992 return (-1); 2993 } 2994 2995 if ((fd = socket(AF_UNIX, type, 0)) == -1) { 2996 log_warn("socket unix \"%s\"", path); 2997 return (-1); 2998 } 2999 3000 if (Debug) { 3001 if (connect(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == 0 || 3002 errno == EPROTOTYPE) { 3003 close(fd); 3004 errno = EISCONN; 3005 log_warn("connect unix \"%s\"", path); 3006 return (-1); 3007 } 3008 } 3009 3010 old_umask = umask(0177); 3011 3012 unlink(path); 3013 if (bind(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == -1) { 3014 log_warn("bind unix \"%s\"", path); 3015 umask(old_umask); 3016 close(fd); 3017 return (-1); 3018 } 3019 3020 umask(old_umask); 3021 3022 if (chmod(path, mode) == -1) { 3023 log_warn("chmod unix \"%s\"", path); 3024 close(fd); 3025 unlink(path); 3026 return (-1); 3027 } 3028 3029 optval = LOG_MAXLINE + PATH_MAX; 3030 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval)) 3031 == -1) 3032 log_warn("setsockopt unix \"%s\"", path); 3033 3034 return (fd); 3035 } 3036 3037 void 3038 double_sockbuf(int fd, int optname) 3039 { 3040 socklen_t len; 3041 int i, newsize, oldsize = 0; 3042 3043 len = sizeof(oldsize); 3044 if (getsockopt(fd, SOL_SOCKET, optname, &oldsize, &len) == -1) 3045 log_warn("getsockopt bufsize"); 3046 len = sizeof(newsize); 3047 newsize = LOG_MAXLINE + 128; /* data + control */ 3048 /* allow 8 full length messages */ 3049 for (i = 0; i < 4; i++, newsize *= 2) { 3050 if (newsize <= oldsize) 3051 continue; 3052 if (setsockopt(fd, SOL_SOCKET, optname, &newsize, len) == -1) 3053 log_warn("setsockopt bufsize %d", newsize); 3054 } 3055 } 3056 3057 void 3058 set_sockbuf(int fd) 3059 { 3060 int size = 65536; 3061 3062 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) == -1) 3063 log_warn("setsockopt sndbufsize %d", size); 3064 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) == -1) 3065 log_warn("setsockopt rcvbufsize %d", size); 3066 } 3067 3068 void 3069 ctlconn_cleanup(void) 3070 { 3071 struct filed *f; 3072 3073 close(fd_ctlconn); 3074 fd_ctlconn = -1; 3075 event_del(ev_ctlread); 3076 event_del(ev_ctlwrite); 3077 event_add(ev_ctlaccept, NULL); 3078 3079 if (ctl_state == CTL_WRITING_CONT_REPLY) 3080 SIMPLEQ_FOREACH(f, &Files, f_next) 3081 if (f->f_type == F_MEMBUF) 3082 f->f_un.f_mb.f_attached = 0; 3083 3084 ctl_state = ctl_cmd_bytes = ctl_reply_offset = ctl_reply_size = 0; 3085 } 3086 3087 void 3088 ctlsock_acceptcb(int fd, short event, void *arg) 3089 { 3090 struct event *ev = arg; 3091 3092 if ((fd = reserve_accept4(fd, event, ev, ctlsock_acceptcb, 3093 NULL, NULL, SOCK_NONBLOCK)) == -1) { 3094 if (errno != ENFILE && errno != EMFILE && 3095 errno != EINTR && errno != EWOULDBLOCK && 3096 errno != ECONNABORTED) 3097 log_warn("accept control socket"); 3098 return; 3099 } 3100 log_debug("Accepting control connection"); 3101 3102 if (fd_ctlconn != -1) 3103 ctlconn_cleanup(); 3104 3105 /* Only one connection at a time */ 3106 event_del(ev); 3107 3108 fd_ctlconn = fd; 3109 /* file descriptor has changed, reset event */ 3110 event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST, 3111 ctlconn_readcb, ev_ctlread); 3112 event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST, 3113 ctlconn_writecb, ev_ctlwrite); 3114 event_add(ev_ctlread, NULL); 3115 ctl_state = CTL_READING_CMD; 3116 ctl_cmd_bytes = 0; 3117 } 3118 3119 static struct filed 3120 *find_membuf_log(const char *name) 3121 { 3122 struct filed *f; 3123 3124 SIMPLEQ_FOREACH(f, &Files, f_next) { 3125 if (f->f_type == F_MEMBUF && 3126 strcmp(f->f_un.f_mb.f_mname, name) == 0) 3127 break; 3128 } 3129 return (f); 3130 } 3131 3132 void 3133 ctlconn_readcb(int fd, short event, void *arg) 3134 { 3135 struct filed *f; 3136 struct ctl_reply_hdr *reply_hdr = (struct ctl_reply_hdr *)ctl_reply; 3137 ssize_t n; 3138 u_int32_t flags = 0; 3139 3140 if (ctl_state == CTL_WRITING_REPLY || 3141 ctl_state == CTL_WRITING_CONT_REPLY) { 3142 /* client has closed the connection */ 3143 ctlconn_cleanup(); 3144 return; 3145 } 3146 3147 retry: 3148 n = read(fd, (char*)&ctl_cmd + ctl_cmd_bytes, 3149 sizeof(ctl_cmd) - ctl_cmd_bytes); 3150 switch (n) { 3151 case -1: 3152 if (errno == EINTR) 3153 goto retry; 3154 if (errno == EWOULDBLOCK) 3155 return; 3156 log_warn("read control socket"); 3157 /* FALLTHROUGH */ 3158 case 0: 3159 ctlconn_cleanup(); 3160 return; 3161 default: 3162 ctl_cmd_bytes += n; 3163 } 3164 if (ctl_cmd_bytes < sizeof(ctl_cmd)) 3165 return; 3166 3167 if (ntohl(ctl_cmd.version) != CTL_VERSION) { 3168 log_warnx("unknown client protocol version"); 3169 ctlconn_cleanup(); 3170 return; 3171 } 3172 3173 /* Ensure that logname is \0 terminated */ 3174 if (memchr(ctl_cmd.logname, '\0', sizeof(ctl_cmd.logname)) == NULL) { 3175 log_warnx("corrupt control socket command"); 3176 ctlconn_cleanup(); 3177 return; 3178 } 3179 3180 *reply_text = '\0'; 3181 3182 ctl_reply_size = ctl_reply_offset = 0; 3183 memset(reply_hdr, '\0', sizeof(*reply_hdr)); 3184 3185 ctl_cmd.cmd = ntohl(ctl_cmd.cmd); 3186 log_debug("ctlcmd %x logname \"%s\"", ctl_cmd.cmd, ctl_cmd.logname); 3187 3188 switch (ctl_cmd.cmd) { 3189 case CMD_READ: 3190 case CMD_READ_CLEAR: 3191 case CMD_READ_CONT: 3192 case CMD_FLAGS: 3193 f = find_membuf_log(ctl_cmd.logname); 3194 if (f == NULL) { 3195 strlcpy(reply_text, "No such log\n", MAX_MEMBUF); 3196 } else { 3197 if (ctl_cmd.cmd != CMD_FLAGS) { 3198 ringbuf_to_string(reply_text, MAX_MEMBUF, 3199 f->f_un.f_mb.f_rb); 3200 } 3201 if (f->f_un.f_mb.f_overflow) 3202 flags |= CTL_HDR_FLAG_OVERFLOW; 3203 if (ctl_cmd.cmd == CMD_READ_CLEAR) { 3204 ringbuf_clear(f->f_un.f_mb.f_rb); 3205 f->f_un.f_mb.f_overflow = 0; 3206 } 3207 if (ctl_cmd.cmd == CMD_READ_CONT) { 3208 f->f_un.f_mb.f_attached = 1; 3209 tailify_replytext(reply_text, 3210 ctl_cmd.lines > 0 ? ctl_cmd.lines : 10); 3211 } else if (ctl_cmd.lines > 0) { 3212 tailify_replytext(reply_text, ctl_cmd.lines); 3213 } 3214 } 3215 break; 3216 case CMD_CLEAR: 3217 f = find_membuf_log(ctl_cmd.logname); 3218 if (f == NULL) { 3219 strlcpy(reply_text, "No such log\n", MAX_MEMBUF); 3220 } else { 3221 ringbuf_clear(f->f_un.f_mb.f_rb); 3222 if (f->f_un.f_mb.f_overflow) 3223 flags |= CTL_HDR_FLAG_OVERFLOW; 3224 f->f_un.f_mb.f_overflow = 0; 3225 strlcpy(reply_text, "Log cleared\n", MAX_MEMBUF); 3226 } 3227 break; 3228 case CMD_LIST: 3229 SIMPLEQ_FOREACH(f, &Files, f_next) { 3230 if (f->f_type == F_MEMBUF) { 3231 strlcat(reply_text, f->f_un.f_mb.f_mname, 3232 MAX_MEMBUF); 3233 if (f->f_un.f_mb.f_overflow) { 3234 strlcat(reply_text, "*", MAX_MEMBUF); 3235 flags |= CTL_HDR_FLAG_OVERFLOW; 3236 } 3237 strlcat(reply_text, " ", MAX_MEMBUF); 3238 } 3239 } 3240 strlcat(reply_text, "\n", MAX_MEMBUF); 3241 break; 3242 default: 3243 log_warnx("unsupported control socket command"); 3244 ctlconn_cleanup(); 3245 return; 3246 } 3247 reply_hdr->version = htonl(CTL_VERSION); 3248 reply_hdr->flags = htonl(flags); 3249 3250 ctl_reply_size = CTL_REPLY_SIZE; 3251 log_debug("ctlcmd reply length %lu", (u_long)ctl_reply_size); 3252 3253 /* Otherwise, set up to write out reply */ 3254 ctl_state = (ctl_cmd.cmd == CMD_READ_CONT) ? 3255 CTL_WRITING_CONT_REPLY : CTL_WRITING_REPLY; 3256 3257 event_add(ev_ctlwrite, NULL); 3258 3259 /* another syslogc can kick us out */ 3260 if (ctl_state == CTL_WRITING_CONT_REPLY) 3261 event_add(ev_ctlaccept, NULL); 3262 } 3263 3264 void 3265 ctlconn_writecb(int fd, short event, void *arg) 3266 { 3267 struct event *ev = arg; 3268 ssize_t n; 3269 3270 if (!(ctl_state == CTL_WRITING_REPLY || 3271 ctl_state == CTL_WRITING_CONT_REPLY)) { 3272 /* Shouldn't be here! */ 3273 log_warnx("control socket write with bad state"); 3274 ctlconn_cleanup(); 3275 return; 3276 } 3277 3278 retry: 3279 n = write(fd, ctl_reply + ctl_reply_offset, 3280 ctl_reply_size - ctl_reply_offset); 3281 switch (n) { 3282 case -1: 3283 if (errno == EINTR) 3284 goto retry; 3285 if (errno == EWOULDBLOCK) 3286 return; 3287 if (errno != EPIPE) 3288 log_warn("write control socket"); 3289 /* FALLTHROUGH */ 3290 case 0: 3291 ctlconn_cleanup(); 3292 return; 3293 default: 3294 ctl_reply_offset += n; 3295 } 3296 if (ctl_reply_offset < ctl_reply_size) 3297 return; 3298 3299 if (ctl_state != CTL_WRITING_CONT_REPLY) { 3300 ctlconn_cleanup(); 3301 return; 3302 } 3303 3304 /* 3305 * Make space in the buffer for continous writes. 3306 * Set offset behind reply header to skip it 3307 */ 3308 *reply_text = '\0'; 3309 ctl_reply_offset = ctl_reply_size = CTL_REPLY_SIZE; 3310 3311 /* Now is a good time to report dropped lines */ 3312 if (membuf_drop) { 3313 strlcat(reply_text, "<ENOBUFS>\n", MAX_MEMBUF); 3314 ctl_reply_size = CTL_REPLY_SIZE; 3315 membuf_drop = 0; 3316 } else { 3317 /* Nothing left to write */ 3318 event_del(ev); 3319 } 3320 } 3321 3322 /* Shorten replytext to number of lines */ 3323 void 3324 tailify_replytext(char *replytext, int lines) 3325 { 3326 char *start, *nl; 3327 int count = 0; 3328 start = nl = replytext; 3329 3330 while ((nl = strchr(nl, '\n')) != NULL) { 3331 nl++; 3332 if (++count > lines) { 3333 start = strchr(start, '\n'); 3334 start++; 3335 } 3336 } 3337 if (start != replytext) { 3338 int len = strlen(start); 3339 memmove(replytext, start, len); 3340 *(replytext + len) = '\0'; 3341 } 3342 } 3343 3344 void 3345 ctlconn_logto(char *line) 3346 { 3347 size_t l; 3348 3349 if (membuf_drop) 3350 return; 3351 3352 l = strlen(line); 3353 if (l + 2 > (CTL_REPLY_MAXSIZE - ctl_reply_size)) { 3354 /* remember line drops for later report */ 3355 membuf_drop = 1; 3356 return; 3357 } 3358 memcpy(ctl_reply + ctl_reply_size, line, l); 3359 memcpy(ctl_reply + ctl_reply_size + l, "\n", 2); 3360 ctl_reply_size += l + 1; 3361 event_add(ev_ctlwrite, NULL); 3362 } 3363