1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1983, 1988, 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32 #include <sys/cdefs.h> 33 __SCCSID("@(#)syslog.c 8.5 (Berkeley) 4/29/95"); 34 __FBSDID("$FreeBSD$"); 35 36 #include "namespace.h" 37 #include <sys/param.h> 38 #include <sys/socket.h> 39 #include <sys/syslog.h> 40 #include <sys/time.h> 41 #include <sys/uio.h> 42 #include <sys/un.h> 43 #include <netdb.h> 44 45 #include <errno.h> 46 #include <fcntl.h> 47 #include <paths.h> 48 #include <pthread.h> 49 #include <stdbool.h> 50 #include <stdio.h> 51 #include <stdlib.h> 52 #include <string.h> 53 #include <time.h> 54 #include <unistd.h> 55 56 #include <stdarg.h> 57 #include "un-namespace.h" 58 59 #include "libc_private.h" 60 61 /* Maximum number of characters of syslog message */ 62 #define MAXLINE 8192 63 64 static int LogFile = -1; /* fd for log */ 65 static bool connected; /* have done connect */ 66 static int opened; /* have done openlog() */ 67 static int LogStat = 0; /* status bits, set by openlog() */ 68 static pid_t LogPid = -1; /* process id to tag the entry with */ 69 static const char *LogTag = NULL; /* string to tag the entry with */ 70 static int LogTagLength = -1; /* usable part of LogTag */ 71 static int LogFacility = LOG_USER; /* default facility code */ 72 static int LogMask = 0xff; /* mask of priorities to be logged */ 73 static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER; 74 75 #define THREAD_LOCK() \ 76 do { \ 77 if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \ 78 } while(0) 79 #define THREAD_UNLOCK() \ 80 do { \ 81 if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \ 82 } while(0) 83 84 /* RFC5424 defined value. */ 85 #define NILVALUE "-" 86 87 static void disconnectlog(void); /* disconnect from syslogd */ 88 static void connectlog(void); /* (re)connect to syslogd */ 89 static void openlog_unlocked(const char *, int, int); 90 static void parse_tag(void); /* parse ident[NNN] if needed */ 91 92 /* 93 * Format of the magic cookie passed through the stdio hook 94 */ 95 struct bufcookie { 96 char *base; /* start of buffer */ 97 int left; 98 }; 99 100 /* 101 * stdio write hook for writing to a static string buffer 102 * XXX: Maybe one day, dynamically allocate it so that the line length 103 * is `unlimited'. 104 */ 105 static int 106 writehook(void *cookie, const char *buf, int len) 107 { 108 struct bufcookie *h; /* private `handle' */ 109 110 h = (struct bufcookie *)cookie; 111 if (len > h->left) { 112 /* clip in case of wraparound */ 113 len = h->left; 114 } 115 if (len > 0) { 116 (void)memcpy(h->base, buf, len); /* `write' it. */ 117 h->base += len; 118 h->left -= len; 119 } 120 return len; 121 } 122 123 /* 124 * syslog, vsyslog -- 125 * print message on log file; output is intended for syslogd(8). 126 */ 127 void 128 syslog(int pri, const char *fmt, ...) 129 { 130 va_list ap; 131 132 va_start(ap, fmt); 133 vsyslog(pri, fmt, ap); 134 va_end(ap); 135 } 136 137 static void 138 vsyslog1(int pri, const char *fmt, va_list ap) 139 { 140 struct timeval now; 141 struct tm tm; 142 char ch, *p; 143 long tz_offset; 144 int cnt, fd, saved_errno; 145 char hostname[MAXHOSTNAMELEN], *stdp, tbuf[MAXLINE], fmt_cpy[MAXLINE], 146 errstr[64], tz_sign; 147 FILE *fp, *fmt_fp; 148 struct bufcookie tbuf_cookie; 149 struct bufcookie fmt_cookie; 150 151 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID 152 /* Check for invalid bits. */ 153 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) { 154 syslog(INTERNALLOG, 155 "syslog: unknown facility/priority: %x", pri); 156 pri &= LOG_PRIMASK|LOG_FACMASK; 157 } 158 159 saved_errno = errno; 160 161 /* Check priority against setlogmask values. */ 162 if (!(LOG_MASK(LOG_PRI(pri)) & LogMask)) 163 return; 164 165 /* Set default facility if none specified. */ 166 if ((pri & LOG_FACMASK) == 0) 167 pri |= LogFacility; 168 169 /* Create the primary stdio hook */ 170 tbuf_cookie.base = tbuf; 171 tbuf_cookie.left = sizeof(tbuf); 172 fp = fwopen(&tbuf_cookie, writehook); 173 if (fp == NULL) 174 return; 175 176 /* Build the message according to RFC 5424. Tag and version. */ 177 (void)fprintf(fp, "<%d>1 ", pri); 178 /* Timestamp similar to RFC 3339. */ 179 if (gettimeofday(&now, NULL) == 0 && 180 localtime_r(&now.tv_sec, &tm) != NULL) { 181 if (tm.tm_gmtoff < 0) { 182 tz_sign = '-'; 183 tz_offset = -tm.tm_gmtoff; 184 } else { 185 tz_sign = '+'; 186 tz_offset = tm.tm_gmtoff; 187 } 188 189 (void)fprintf(fp, 190 "%04d-%02d-%02d" /* Date. */ 191 "T%02d:%02d:%02d.%06ld" /* Time. */ 192 "%c%02ld:%02ld ", /* Time zone offset. */ 193 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 194 tm.tm_hour, tm.tm_min, tm.tm_sec, now.tv_usec, 195 tz_sign, tz_offset / 3600, (tz_offset % 3600) / 60); 196 } else 197 (void)fputs(NILVALUE " ", fp); 198 /* Hostname. */ 199 (void)gethostname(hostname, sizeof(hostname)); 200 (void)fprintf(fp, "%s ", 201 hostname[0] == '\0' ? NILVALUE : hostname); 202 if (LogStat & LOG_PERROR) { 203 /* Transfer to string buffer */ 204 (void)fflush(fp); 205 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left); 206 } 207 /* Application name. */ 208 if (LogTag == NULL) 209 LogTag = _getprogname(); 210 else if (LogTagLength == -1) 211 parse_tag(); 212 if (LogTagLength > 0) 213 (void)fprintf(fp, "%.*s ", LogTagLength, LogTag); 214 else 215 (void)fprintf(fp, "%s ", LogTag == NULL ? NILVALUE : LogTag); 216 /* 217 * Provide the process ID regardless of whether LOG_PID has been 218 * specified, as it provides valuable information. Many 219 * applications tend not to use this, even though they should. 220 */ 221 if (LogPid == -1) 222 LogPid = getpid(); 223 (void)fprintf(fp, "%d ", (int)LogPid); 224 /* Message ID. */ 225 (void)fputs(NILVALUE " ", fp); 226 /* Structured data. */ 227 (void)fputs(NILVALUE " ", fp); 228 229 /* Check to see if we can skip expanding the %m */ 230 if (strstr(fmt, "%m")) { 231 232 /* Create the second stdio hook */ 233 fmt_cookie.base = fmt_cpy; 234 fmt_cookie.left = sizeof(fmt_cpy) - 1; 235 fmt_fp = fwopen(&fmt_cookie, writehook); 236 if (fmt_fp == NULL) { 237 fclose(fp); 238 return; 239 } 240 241 /* 242 * Substitute error message for %m. Be careful not to 243 * molest an escaped percent "%%m". We want to pass it 244 * on untouched as the format is later parsed by vfprintf. 245 */ 246 for ( ; (ch = *fmt); ++fmt) { 247 if (ch == '%' && fmt[1] == 'm') { 248 ++fmt; 249 strerror_r(saved_errno, errstr, sizeof(errstr)); 250 fputs(errstr, fmt_fp); 251 } else if (ch == '%' && fmt[1] == '%') { 252 ++fmt; 253 fputc(ch, fmt_fp); 254 fputc(ch, fmt_fp); 255 } else { 256 fputc(ch, fmt_fp); 257 } 258 } 259 260 /* Null terminate if room */ 261 fputc(0, fmt_fp); 262 fclose(fmt_fp); 263 264 /* Guarantee null termination */ 265 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0'; 266 267 fmt = fmt_cpy; 268 } 269 270 /* Message. */ 271 (void)vfprintf(fp, fmt, ap); 272 (void)fclose(fp); 273 274 cnt = sizeof(tbuf) - tbuf_cookie.left; 275 276 /* Remove a trailing newline */ 277 if (tbuf[cnt - 1] == '\n') 278 cnt--; 279 280 /* Output to stderr if requested. */ 281 if (LogStat & LOG_PERROR) { 282 struct iovec iov[2]; 283 struct iovec *v = iov; 284 285 v->iov_base = stdp; 286 v->iov_len = cnt - (stdp - tbuf); 287 ++v; 288 v->iov_base = "\n"; 289 v->iov_len = 1; 290 (void)_writev(STDERR_FILENO, iov, 2); 291 } 292 293 /* Get connected, output the message to the local logger. */ 294 if (!opened) 295 openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0); 296 connectlog(); 297 298 /* 299 * If the send() failed, there are two likely scenarios: 300 * 1) syslogd was restarted. In this case make one (only) attempt 301 * to reconnect. 302 * 2) We filled our buffer due to syslogd not being able to read 303 * as fast as we write. In this case prefer to lose the current 304 * message rather than whole buffer of previously logged data. 305 */ 306 if (send(LogFile, tbuf, cnt, 0) < 0) { 307 if (errno != ENOBUFS) { 308 disconnectlog(); 309 connectlog(); 310 if (send(LogFile, tbuf, cnt, 0) >= 0) 311 return; 312 } 313 } else 314 return; 315 316 /* 317 * Output the message to the console; try not to block 318 * as a blocking console should not stop other processes. 319 * Make sure the error reported is the one from the syslogd failure. 320 */ 321 if (LogStat & LOG_CONS && 322 (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >= 323 0) { 324 struct iovec iov[2]; 325 struct iovec *v = iov; 326 327 p = strchr(tbuf, '>') + 3; 328 v->iov_base = p; 329 v->iov_len = cnt - (p - tbuf); 330 ++v; 331 v->iov_base = "\r\n"; 332 v->iov_len = 2; 333 (void)_writev(fd, iov, 2); 334 (void)_close(fd); 335 } 336 } 337 338 static void 339 syslog_cancel_cleanup(void *arg __unused) 340 { 341 342 THREAD_UNLOCK(); 343 } 344 345 void 346 vsyslog(int pri, const char *fmt, va_list ap) 347 { 348 349 THREAD_LOCK(); 350 pthread_cleanup_push(syslog_cancel_cleanup, NULL); 351 vsyslog1(pri, fmt, ap); 352 pthread_cleanup_pop(1); 353 } 354 355 /* Should be called with mutex acquired */ 356 static void 357 disconnectlog(void) 358 { 359 /* 360 * If the user closed the FD and opened another in the same slot, 361 * that's their problem. They should close it before calling on 362 * system services. 363 */ 364 if (LogFile != -1) { 365 _close(LogFile); 366 LogFile = -1; 367 } 368 connected = false; /* retry connect */ 369 } 370 371 /* Should be called with mutex acquired */ 372 static void 373 connectlog(void) 374 { 375 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */ 376 377 if (LogFile == -1) { 378 socklen_t len; 379 380 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 381 0)) == -1) 382 return; 383 if (_getsockopt(LogFile, SOL_SOCKET, SO_SNDBUF, &len, 384 &(socklen_t){sizeof(len)}) == 0) { 385 if (len < MAXLINE) { 386 len = MAXLINE; 387 (void)_setsockopt(LogFile, SOL_SOCKET, SO_SNDBUF, 388 &len, sizeof(len)); 389 } 390 } 391 } 392 if (!connected) { 393 SyslogAddr.sun_len = sizeof(SyslogAddr); 394 SyslogAddr.sun_family = AF_UNIX; 395 396 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG, 397 sizeof SyslogAddr.sun_path); 398 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr, 399 sizeof(SyslogAddr)) != -1) 400 connected = true; 401 else { 402 (void)_close(LogFile); 403 LogFile = -1; 404 } 405 } 406 } 407 408 static void 409 openlog_unlocked(const char *ident, int logstat, int logfac) 410 { 411 if (ident != NULL) { 412 LogTag = ident; 413 LogTagLength = -1; 414 } 415 LogStat = logstat; 416 parse_tag(); 417 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0) 418 LogFacility = logfac; 419 420 if (LogStat & LOG_NDELAY) /* open immediately */ 421 connectlog(); 422 423 opened = 1; /* ident and facility has been set */ 424 } 425 426 void 427 openlog(const char *ident, int logstat, int logfac) 428 { 429 430 THREAD_LOCK(); 431 pthread_cleanup_push(syslog_cancel_cleanup, NULL); 432 openlog_unlocked(ident, logstat, logfac); 433 pthread_cleanup_pop(1); 434 } 435 436 437 void 438 closelog(void) 439 { 440 THREAD_LOCK(); 441 if (LogFile != -1) { 442 (void)_close(LogFile); 443 LogFile = -1; 444 } 445 LogTag = NULL; 446 LogTagLength = -1; 447 connected = false; 448 THREAD_UNLOCK(); 449 } 450 451 /* setlogmask -- set the log mask level */ 452 int 453 setlogmask(int pmask) 454 { 455 int omask; 456 457 THREAD_LOCK(); 458 omask = LogMask; 459 if (pmask != 0) 460 LogMask = pmask; 461 THREAD_UNLOCK(); 462 return (omask); 463 } 464 465 /* 466 * Obtain LogPid from LogTag formatted as following: ident[NNN] 467 */ 468 static void 469 parse_tag(void) 470 { 471 char *begin, *end, *p; 472 pid_t pid; 473 474 if (LogTag == NULL || (LogStat & LOG_PID) != 0) 475 return; 476 /* 477 * LogTagLength is -1 if LogTag was not parsed yet. 478 * Avoid multiple passes over same LogTag. 479 */ 480 LogTagLength = 0; 481 482 /* Check for presence of opening [ and non-empty ident. */ 483 if ((begin = strchr(LogTag, '[')) == NULL || begin == LogTag) 484 return; 485 /* Check for presence of closing ] at the very end and non-empty pid. */ 486 if ((end = strchr(begin + 1, ']')) == NULL || end[1] != 0 || 487 (end - begin) < 2) 488 return; 489 490 /* Check for pid to contain digits only. */ 491 pid = (pid_t)strtol(begin + 1, &p, 10); 492 if (p != end) 493 return; 494 495 LogPid = pid; 496 LogTagLength = begin - LogTag; 497 } 498