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 #include "namespace.h"
35 #include <sys/param.h>
36 #include <sys/socket.h>
37 #include <sys/syslog.h>
55 #include "un-namespace.h"
57 #include "libc_private.h"
59 /* Maximum number of characters of syslog message */
62 static int LogFile = -1; /* fd for log */
63 static bool connected; /* have done connect */
64 static int opened; /* have done openlog() */
65 static int LogStat = 0; /* status bits, set by openlog() */
66 static pid_t LogPid = -1; /* process id to tag the entry with */
67 static const char *LogTag = NULL; /* string to tag the entry with */
68 static int LogTagLength = -1; /* usable part of LogTag */
69 static int LogFacility = LOG_USER; /* default facility code */
70 static int LogMask = 0xff; /* mask of priorities to be logged */
71 static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER;
73 #define THREAD_LOCK() \
75 if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \
77 #define THREAD_UNLOCK() \
79 if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \
82 /* RFC5424 defined value. */
85 static void disconnectlog(void); /* disconnect from syslogd */
86 static void connectlog(void); /* (re)connect to syslogd */
87 static void openlog_unlocked(const char *, int, int);
88 static void parse_tag(void); /* parse ident[NNN] if needed */
91 * Format of the magic cookie passed through the stdio hook
94 char *base; /* start of buffer */
99 * stdio write hook for writing to a static string buffer
100 * XXX: Maybe one day, dynamically allocate it so that the line length
104 writehook(void *cookie, const char *buf, int len)
106 struct bufcookie *h; /* private `handle' */
108 h = (struct bufcookie *)cookie;
110 /* clip in case of wraparound */
114 (void)memcpy(h->base, buf, len); /* `write' it. */
123 * print message on log file; output is intended for syslogd(8).
126 syslog(int pri, const char *fmt, ...)
131 vsyslog(pri, fmt, ap);
136 vsyslog1(int pri, const char *fmt, va_list ap)
142 int cnt, fd, saved_errno;
143 char hostname[MAXHOSTNAMELEN], *stdp, tbuf[MAXLINE], fmt_cpy[MAXLINE],
146 struct bufcookie tbuf_cookie;
147 struct bufcookie fmt_cookie;
149 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
150 /* Check for invalid bits. */
151 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
153 "syslog: unknown facility/priority: %x", pri);
154 pri &= LOG_PRIMASK|LOG_FACMASK;
159 /* Check priority against setlogmask values. */
160 if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
163 /* Set default facility if none specified. */
164 if ((pri & LOG_FACMASK) == 0)
167 /* Create the primary stdio hook */
168 tbuf_cookie.base = tbuf;
169 tbuf_cookie.left = sizeof(tbuf);
170 fp = fwopen(&tbuf_cookie, writehook);
174 /* Build the message according to RFC 5424. Tag and version. */
175 (void)fprintf(fp, "<%d>1 ", pri);
176 /* Timestamp similar to RFC 3339. */
177 if (gettimeofday(&now, NULL) == 0 &&
178 localtime_r(&now.tv_sec, &tm) != NULL) {
179 if (tm.tm_gmtoff < 0) {
181 tz_offset = -tm.tm_gmtoff;
184 tz_offset = tm.tm_gmtoff;
188 "%04d-%02d-%02d" /* Date. */
189 "T%02d:%02d:%02d.%06ld" /* Time. */
190 "%c%02ld:%02ld ", /* Time zone offset. */
191 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
192 tm.tm_hour, tm.tm_min, tm.tm_sec, now.tv_usec,
193 tz_sign, tz_offset / 3600, (tz_offset % 3600) / 60);
195 (void)fputs(NILVALUE " ", fp);
197 (void)gethostname(hostname, sizeof(hostname));
198 (void)fprintf(fp, "%s ",
199 hostname[0] == '\0' ? NILVALUE : hostname);
200 if (LogStat & LOG_PERROR) {
201 /* Transfer to string buffer */
203 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
205 /* Application name. */
207 LogTag = _getprogname();
208 else if (LogTagLength == -1)
210 if (LogTagLength > 0)
211 (void)fprintf(fp, "%.*s ", LogTagLength, LogTag);
213 (void)fprintf(fp, "%s ", LogTag == NULL ? NILVALUE : LogTag);
215 * Provide the process ID regardless of whether LOG_PID has been
216 * specified, as it provides valuable information. Many
217 * applications tend not to use this, even though they should.
219 if (LogTagLength <= 0)
221 (void)fprintf(fp, "%d ", (int)LogPid);
223 (void)fputs(NILVALUE " ", fp);
224 /* Structured data. */
225 (void)fputs(NILVALUE " ", fp);
227 /* Check to see if we can skip expanding the %m */
228 if (strstr(fmt, "%m")) {
230 /* Create the second stdio hook */
231 fmt_cookie.base = fmt_cpy;
232 fmt_cookie.left = sizeof(fmt_cpy) - 1;
233 fmt_fp = fwopen(&fmt_cookie, writehook);
234 if (fmt_fp == NULL) {
240 * Substitute error message for %m. Be careful not to
241 * molest an escaped percent "%%m". We want to pass it
242 * on untouched as the format is later parsed by vfprintf.
244 for ( ; (ch = *fmt); ++fmt) {
245 if (ch == '%' && fmt[1] == 'm') {
247 strerror_r(saved_errno, errstr, sizeof(errstr));
248 fputs(errstr, fmt_fp);
249 } else if (ch == '%' && fmt[1] == '%') {
258 /* Null terminate if room */
262 /* Guarantee null termination */
263 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
269 (void)vfprintf(fp, fmt, ap);
272 cnt = sizeof(tbuf) - tbuf_cookie.left;
274 /* Remove a trailing newline */
275 if (tbuf[cnt - 1] == '\n')
278 /* Output to stderr if requested. */
279 if (LogStat & LOG_PERROR) {
281 struct iovec *v = iov;
284 v->iov_len = cnt - (stdp - tbuf);
288 (void)_writev(STDERR_FILENO, iov, 2);
291 /* Get connected, output the message to the local logger. */
293 openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
297 * If the send() failed, there are two likely scenarios:
298 * 1) syslogd was restarted. In this case make one (only) attempt
300 * 2) We filled our buffer due to syslogd not being able to read
301 * as fast as we write. In this case prefer to lose the current
302 * message rather than whole buffer of previously logged data.
304 if (send(LogFile, tbuf, cnt, 0) < 0) {
305 if (errno != ENOBUFS) {
308 if (send(LogFile, tbuf, cnt, 0) >= 0)
315 * Output the message to the console; try not to block
316 * as a blocking console should not stop other processes.
317 * Make sure the error reported is the one from the syslogd failure.
319 if (LogStat & LOG_CONS &&
320 (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >=
323 struct iovec *v = iov;
325 p = strchr(tbuf, '>') + 3;
327 v->iov_len = cnt - (p - tbuf);
329 v->iov_base = "\r\n";
331 (void)_writev(fd, iov, 2);
337 syslog_cancel_cleanup(void *arg __unused)
344 vsyslog(int pri, const char *fmt, va_list ap)
348 pthread_cleanup_push(syslog_cancel_cleanup, NULL);
349 vsyslog1(pri, fmt, ap);
350 pthread_cleanup_pop(1);
353 /* Should be called with mutex acquired */
358 * If the user closed the FD and opened another in the same slot,
359 * that's their problem. They should close it before calling on
366 connected = false; /* retry connect */
369 /* Should be called with mutex acquired */
373 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
378 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
381 if (_getsockopt(LogFile, SOL_SOCKET, SO_SNDBUF, &len,
382 &(socklen_t){sizeof(len)}) == 0) {
385 (void)_setsockopt(LogFile, SOL_SOCKET, SO_SNDBUF,
391 SyslogAddr.sun_len = sizeof(SyslogAddr);
392 SyslogAddr.sun_family = AF_UNIX;
394 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
395 sizeof SyslogAddr.sun_path);
396 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
397 sizeof(SyslogAddr)) != -1)
400 (void)_close(LogFile);
407 openlog_unlocked(const char *ident, int logstat, int logfac)
415 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
416 LogFacility = logfac;
418 if (LogStat & LOG_NDELAY) /* open immediately */
421 opened = 1; /* ident and facility has been set */
425 openlog(const char *ident, int logstat, int logfac)
429 pthread_cleanup_push(syslog_cancel_cleanup, NULL);
430 openlog_unlocked(ident, logstat, logfac);
431 pthread_cleanup_pop(1);
440 (void)_close(LogFile);
449 /* setlogmask -- set the log mask level */
451 setlogmask(int pmask)
464 * Obtain LogPid from LogTag formatted as per RFC 3164,
465 * Section 5.3 Originating Process Information:
472 char *begin, *end, *p;
475 if (LogTag == NULL || (LogStat & LOG_PID) != 0)
478 * LogTagLength is -1 if LogTag was not parsed yet.
479 * Avoid multiple passes over same LogTag.
483 /* Check for presence of opening [ and non-empty ident. */
484 if ((begin = strchr(LogTag, '[')) == NULL || begin == LogTag)
486 /* Check for presence of closing ] at the very end and non-empty pid. */
487 if ((end = strchr(begin + 1, ']')) == NULL || end[1] != 0 ||
491 /* Check for pid to contain digits only. */
492 pid = (pid_t)strtol(begin + 1, &p, 10);
497 LogTagLength = begin - LogTag;