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 "namespace.h"
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/syslog.h>
53 #include "un-namespace.h"
55 #include "libc_private.h"
57 /* Maximum number of characters of syslog message */
60 static int LogFile = -1; /* fd for log */
61 static bool connected; /* have done connect */
62 static int opened; /* have done openlog() */
63 static int LogStat = 0; /* status bits, set by openlog() */
64 static pid_t LogPid = -1; /* process id to tag the entry with */
65 static const char *LogTag = NULL; /* string to tag the entry with */
66 static int LogTagLength = -1; /* usable part of LogTag */
67 static int LogFacility = LOG_USER; /* default facility code */
68 static int LogMask = 0xff; /* mask of priorities to be logged */
69 static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER;
71 #define THREAD_LOCK() \
73 if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \
75 #define THREAD_UNLOCK() \
77 if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \
80 /* RFC5424 defined value. */
83 static void disconnectlog(void); /* disconnect from syslogd */
84 static void connectlog(void); /* (re)connect to syslogd */
85 static void openlog_unlocked(const char *, int, int);
86 static void parse_tag(void); /* parse ident[NNN] if needed */
89 * Format of the magic cookie passed through the stdio hook
92 char *base; /* start of buffer */
97 * stdio write hook for writing to a static string buffer
98 * XXX: Maybe one day, dynamically allocate it so that the line length
102 writehook(void *cookie, const char *buf, int len)
104 struct bufcookie *h; /* private `handle' */
106 h = (struct bufcookie *)cookie;
108 /* clip in case of wraparound */
112 (void)memcpy(h->base, buf, len); /* `write' it. */
121 * print message on log file; output is intended for syslogd(8).
124 syslog(int pri, const char *fmt, ...)
129 vsyslog(pri, fmt, ap);
134 vsyslog1(int pri, const char *fmt, va_list ap)
140 int cnt, fd, saved_errno;
141 char hostname[MAXHOSTNAMELEN], *stdp, tbuf[MAXLINE], fmt_cpy[MAXLINE],
144 struct bufcookie tbuf_cookie;
145 struct bufcookie fmt_cookie;
147 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
148 /* Check for invalid bits. */
149 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
151 "syslog: unknown facility/priority: %x", pri);
152 pri &= LOG_PRIMASK|LOG_FACMASK;
157 /* Check priority against setlogmask values. */
158 if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
161 /* Set default facility if none specified. */
162 if ((pri & LOG_FACMASK) == 0)
165 /* Create the primary stdio hook */
166 tbuf_cookie.base = tbuf;
167 tbuf_cookie.left = sizeof(tbuf);
168 fp = fwopen(&tbuf_cookie, writehook);
172 /* Build the message according to RFC 5424. Tag and version. */
173 (void)fprintf(fp, "<%d>1 ", pri);
174 /* Timestamp similar to RFC 3339. */
175 if (gettimeofday(&now, NULL) == 0 &&
176 localtime_r(&now.tv_sec, &tm) != NULL) {
177 if (tm.tm_gmtoff < 0) {
179 tz_offset = -tm.tm_gmtoff;
182 tz_offset = tm.tm_gmtoff;
186 "%04d-%02d-%02d" /* Date. */
187 "T%02d:%02d:%02d.%06ld" /* Time. */
188 "%c%02ld:%02ld ", /* Time zone offset. */
189 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
190 tm.tm_hour, tm.tm_min, tm.tm_sec, now.tv_usec,
191 tz_sign, tz_offset / 3600, (tz_offset % 3600) / 60);
193 (void)fputs(NILVALUE " ", fp);
195 (void)gethostname(hostname, sizeof(hostname));
196 (void)fprintf(fp, "%s ",
197 hostname[0] == '\0' ? NILVALUE : hostname);
198 if (LogStat & LOG_PERROR) {
199 /* Transfer to string buffer */
201 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
203 /* Application name. */
205 LogTag = _getprogname();
206 else if (LogTagLength == -1)
208 if (LogTagLength > 0)
209 (void)fprintf(fp, "%.*s ", LogTagLength, LogTag);
211 (void)fprintf(fp, "%s ", LogTag == NULL ? NILVALUE : LogTag);
213 * Provide the process ID regardless of whether LOG_PID has been
214 * specified, as it provides valuable information. Many
215 * applications tend not to use this, even though they should.
217 if (LogTagLength <= 0)
219 (void)fprintf(fp, "%d ", (int)LogPid);
221 (void)fputs(NILVALUE " ", fp);
222 /* Structured data. */
223 (void)fputs(NILVALUE " ", fp);
225 /* Check to see if we can skip expanding the %m */
226 if (strstr(fmt, "%m")) {
228 /* Create the second stdio hook */
229 fmt_cookie.base = fmt_cpy;
230 fmt_cookie.left = sizeof(fmt_cpy) - 1;
231 fmt_fp = fwopen(&fmt_cookie, writehook);
232 if (fmt_fp == NULL) {
238 * Substitute error message for %m. Be careful not to
239 * molest an escaped percent "%%m". We want to pass it
240 * on untouched as the format is later parsed by vfprintf.
242 for ( ; (ch = *fmt); ++fmt) {
243 if (ch == '%' && fmt[1] == 'm') {
245 strerror_r(saved_errno, errstr, sizeof(errstr));
246 fputs(errstr, fmt_fp);
247 } else if (ch == '%' && fmt[1] == '%') {
256 /* Null terminate if room */
260 /* Guarantee null termination */
261 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
267 (void)vfprintf(fp, fmt, ap);
270 cnt = sizeof(tbuf) - tbuf_cookie.left;
272 /* Remove a trailing newline */
273 if (tbuf[cnt - 1] == '\n')
276 /* Output to stderr if requested. */
277 if (LogStat & LOG_PERROR) {
279 struct iovec *v = iov;
282 v->iov_len = cnt - (stdp - tbuf);
286 (void)_writev(STDERR_FILENO, iov, 2);
289 /* Get connected, output the message to the local logger. */
291 openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
295 * If the send() failed, there are two likely scenarios:
296 * 1) syslogd was restarted. In this case make one (only) attempt
298 * 2) We filled our buffer due to syslogd not being able to read
299 * as fast as we write. In this case prefer to lose the current
300 * message rather than whole buffer of previously logged data.
302 if (send(LogFile, tbuf, cnt, 0) < 0) {
303 if (errno != ENOBUFS) {
306 if (send(LogFile, tbuf, cnt, 0) >= 0)
313 * Output the message to the console; try not to block
314 * as a blocking console should not stop other processes.
315 * Make sure the error reported is the one from the syslogd failure.
317 if (LogStat & LOG_CONS &&
318 (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >=
321 struct iovec *v = iov;
323 p = strchr(tbuf, '>') + 3;
325 v->iov_len = cnt - (p - tbuf);
327 v->iov_base = "\r\n";
329 (void)_writev(fd, iov, 2);
335 syslog_cancel_cleanup(void *arg __unused)
342 vsyslog(int pri, const char *fmt, va_list ap)
346 pthread_cleanup_push(syslog_cancel_cleanup, NULL);
347 vsyslog1(pri, fmt, ap);
348 pthread_cleanup_pop(1);
351 /* Should be called with mutex acquired */
356 * If the user closed the FD and opened another in the same slot,
357 * that's their problem. They should close it before calling on
364 connected = false; /* retry connect */
367 /* Should be called with mutex acquired */
371 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
376 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
379 if (_getsockopt(LogFile, SOL_SOCKET, SO_SNDBUF, &len,
380 &(socklen_t){sizeof(len)}) == 0) {
383 (void)_setsockopt(LogFile, SOL_SOCKET, SO_SNDBUF,
389 SyslogAddr.sun_len = sizeof(SyslogAddr);
390 SyslogAddr.sun_family = AF_UNIX;
392 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
393 sizeof SyslogAddr.sun_path);
394 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
395 sizeof(SyslogAddr)) != -1)
398 (void)_close(LogFile);
405 openlog_unlocked(const char *ident, int logstat, int logfac)
413 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
414 LogFacility = logfac;
416 if (LogStat & LOG_NDELAY) /* open immediately */
419 opened = 1; /* ident and facility has been set */
423 openlog(const char *ident, int logstat, int logfac)
427 pthread_cleanup_push(syslog_cancel_cleanup, NULL);
428 openlog_unlocked(ident, logstat, logfac);
429 pthread_cleanup_pop(1);
438 (void)_close(LogFile);
447 /* setlogmask -- set the log mask level */
449 setlogmask(int pmask)
462 * Obtain LogPid from LogTag formatted as per RFC 3164,
463 * Section 5.3 Originating Process Information:
470 char *begin, *end, *p;
473 if (LogTag == NULL || (LogStat & LOG_PID) != 0)
476 * LogTagLength is -1 if LogTag was not parsed yet.
477 * Avoid multiple passes over same LogTag.
481 /* Check for presence of opening [ and non-empty ident. */
482 if ((begin = strchr(LogTag, '[')) == NULL || begin == LogTag)
484 /* Check for presence of closing ] at the very end and non-empty pid. */
485 if ((end = strchr(begin + 1, ']')) == NULL || end[1] != 0 ||
489 /* Check for pid to contain digits only. */
490 pid = (pid_t)strtol(begin + 1, &p, 10);
495 LogTagLength = begin - LogTag;