2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1983, 1988, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
32 #include <sys/cdefs.h>
33 __SCCSID("@(#)syslog.c 8.5 (Berkeley) 4/29/95");
34 __FBSDID("$FreeBSD$");
36 #include "namespace.h"
37 #include <sys/param.h>
38 #include <sys/socket.h>
39 #include <sys/syslog.h>
57 #include "un-namespace.h"
59 #include "libc_private.h"
61 /* Maximum number of characters of syslog message */
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;
75 #define THREAD_LOCK() \
77 if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \
79 #define THREAD_UNLOCK() \
81 if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \
84 /* RFC5424 defined value. */
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 */
93 * Format of the magic cookie passed through the stdio hook
96 char *base; /* start of buffer */
101 * stdio write hook for writing to a static string buffer
102 * XXX: Maybe one day, dynamically allocate it so that the line length
106 writehook(void *cookie, const char *buf, int len)
108 struct bufcookie *h; /* private `handle' */
110 h = (struct bufcookie *)cookie;
112 /* clip in case of wraparound */
116 (void)memcpy(h->base, buf, len); /* `write' it. */
125 * print message on log file; output is intended for syslogd(8).
128 syslog(int pri, const char *fmt, ...)
133 vsyslog(pri, fmt, ap);
138 vsyslog1(int pri, const char *fmt, va_list ap)
144 int cnt, fd, saved_errno;
145 char hostname[MAXHOSTNAMELEN], *stdp, tbuf[MAXLINE], fmt_cpy[MAXLINE],
148 struct bufcookie tbuf_cookie;
149 struct bufcookie fmt_cookie;
151 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
152 /* Check for invalid bits. */
153 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
155 "syslog: unknown facility/priority: %x", pri);
156 pri &= LOG_PRIMASK|LOG_FACMASK;
161 /* Check priority against setlogmask values. */
162 if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
165 /* Set default facility if none specified. */
166 if ((pri & LOG_FACMASK) == 0)
169 /* Create the primary stdio hook */
170 tbuf_cookie.base = tbuf;
171 tbuf_cookie.left = sizeof(tbuf);
172 fp = fwopen(&tbuf_cookie, writehook);
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) {
183 tz_offset = -tm.tm_gmtoff;
186 tz_offset = tm.tm_gmtoff;
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);
197 (void)fputs(NILVALUE " ", fp);
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 */
205 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
207 /* Application name. */
209 LogTag = _getprogname();
210 else if (LogTagLength == -1)
212 if (LogTagLength > 0)
213 (void)fprintf(fp, "%.*s ", LogTagLength, LogTag);
215 (void)fprintf(fp, "%s ", LogTag == NULL ? NILVALUE : LogTag);
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.
221 if (LogTagLength <= 0)
223 (void)fprintf(fp, "%d ", (int)LogPid);
225 (void)fputs(NILVALUE " ", fp);
226 /* Structured data. */
227 (void)fputs(NILVALUE " ", fp);
229 /* Check to see if we can skip expanding the %m */
230 if (strstr(fmt, "%m")) {
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) {
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.
246 for ( ; (ch = *fmt); ++fmt) {
247 if (ch == '%' && fmt[1] == 'm') {
249 strerror_r(saved_errno, errstr, sizeof(errstr));
250 fputs(errstr, fmt_fp);
251 } else if (ch == '%' && fmt[1] == '%') {
260 /* Null terminate if room */
264 /* Guarantee null termination */
265 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
271 (void)vfprintf(fp, fmt, ap);
274 cnt = sizeof(tbuf) - tbuf_cookie.left;
276 /* Remove a trailing newline */
277 if (tbuf[cnt - 1] == '\n')
280 /* Output to stderr if requested. */
281 if (LogStat & LOG_PERROR) {
283 struct iovec *v = iov;
286 v->iov_len = cnt - (stdp - tbuf);
290 (void)_writev(STDERR_FILENO, iov, 2);
293 /* Get connected, output the message to the local logger. */
295 openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
299 * If the send() failed, there are two likely scenarios:
300 * 1) syslogd was restarted. In this case make one (only) attempt
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.
306 if (send(LogFile, tbuf, cnt, 0) < 0) {
307 if (errno != ENOBUFS) {
310 if (send(LogFile, tbuf, cnt, 0) >= 0)
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.
321 if (LogStat & LOG_CONS &&
322 (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >=
325 struct iovec *v = iov;
327 p = strchr(tbuf, '>') + 3;
329 v->iov_len = cnt - (p - tbuf);
331 v->iov_base = "\r\n";
333 (void)_writev(fd, iov, 2);
339 syslog_cancel_cleanup(void *arg __unused)
346 vsyslog(int pri, const char *fmt, va_list ap)
350 pthread_cleanup_push(syslog_cancel_cleanup, NULL);
351 vsyslog1(pri, fmt, ap);
352 pthread_cleanup_pop(1);
355 /* Should be called with mutex acquired */
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
368 connected = false; /* retry connect */
371 /* Should be called with mutex acquired */
375 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
380 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
383 if (_getsockopt(LogFile, SOL_SOCKET, SO_SNDBUF, &len,
384 &(socklen_t){sizeof(len)}) == 0) {
387 (void)_setsockopt(LogFile, SOL_SOCKET, SO_SNDBUF,
393 SyslogAddr.sun_len = sizeof(SyslogAddr);
394 SyslogAddr.sun_family = AF_UNIX;
396 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
397 sizeof SyslogAddr.sun_path);
398 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
399 sizeof(SyslogAddr)) != -1)
402 (void)_close(LogFile);
409 openlog_unlocked(const char *ident, int logstat, int logfac)
417 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
418 LogFacility = logfac;
420 if (LogStat & LOG_NDELAY) /* open immediately */
423 opened = 1; /* ident and facility has been set */
427 openlog(const char *ident, int logstat, int logfac)
431 pthread_cleanup_push(syslog_cancel_cleanup, NULL);
432 openlog_unlocked(ident, logstat, logfac);
433 pthread_cleanup_pop(1);
442 (void)_close(LogFile);
451 /* setlogmask -- set the log mask level */
453 setlogmask(int pmask)
466 * Obtain LogPid from LogTag formatted as per RFC 3164,
467 * Section 5.3 Originating Process Information:
474 char *begin, *end, *p;
477 if (LogTag == NULL || (LogStat & LOG_PID) != 0)
480 * LogTagLength is -1 if LogTag was not parsed yet.
481 * Avoid multiple passes over same LogTag.
485 /* Check for presence of opening [ and non-empty ident. */
486 if ((begin = strchr(LogTag, '[')) == NULL || begin == LogTag)
488 /* Check for presence of closing ] at the very end and non-empty pid. */
489 if ((end = strchr(begin + 1, ']')) == NULL || end[1] != 0 ||
493 /* Check for pid to contain digits only. */
494 pid = (pid_t)strtol(begin + 1, &p, 10);
499 LogTagLength = begin - LogTag;