2 * Copyright (c) 1983, 1988, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #if defined(LIBC_SCCS) && !defined(lint)
31 static char sccsid[] = "@(#)syslog.c 8.5 (Berkeley) 4/29/95";
32 #endif /* LIBC_SCCS and not lint */
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
36 #include "namespace.h"
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/syslog.h>
55 #include "un-namespace.h"
57 #include "libc_private.h"
59 static int LogFile = -1; /* fd for log */
60 static int status; /* connection status */
61 static int opened; /* have done openlog() */
62 static int LogStat = 0; /* status bits, set by openlog() */
63 static const char *LogTag = NULL; /* string to tag the entry with */
64 static int LogFacility = LOG_USER; /* default facility code */
65 static int LogMask = 0xff; /* mask of priorities to be logged */
66 static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER;
68 #define THREAD_LOCK() \
70 if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \
72 #define THREAD_UNLOCK() \
74 if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \
77 static void disconnectlog(void); /* disconnect from syslogd */
78 static void connectlog(void); /* (re)connect to syslogd */
79 static void openlog_unlocked(const char *, int, int);
88 * Format of the magic cookie passed through the stdio hook
91 char *base; /* start of buffer */
96 * stdio write hook for writing to a static string buffer
97 * XXX: Maybe one day, dynamically allocate it so that the line length
101 writehook(void *cookie, const char *buf, int len)
103 struct bufcookie *h; /* private `handle' */
105 h = (struct bufcookie *)cookie;
107 /* clip in case of wraparound */
111 (void)memcpy(h->base, buf, len); /* `write' it. */
120 * print message on log file; output is intended for syslogd(8).
123 syslog(int pri, const char *fmt, ...)
128 vsyslog(pri, fmt, ap);
133 vsyslog1(int pri, const char *fmt, va_list ap)
139 char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64];
141 struct bufcookie tbuf_cookie;
142 struct bufcookie fmt_cookie;
144 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
145 /* Check for invalid bits. */
146 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
148 "syslog: unknown facility/priority: %x", pri);
149 pri &= LOG_PRIMASK|LOG_FACMASK;
154 /* Check priority against setlogmask values. */
155 if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
158 /* Set default facility if none specified. */
159 if ((pri & LOG_FACMASK) == 0)
162 /* Create the primary stdio hook */
163 tbuf_cookie.base = tbuf;
164 tbuf_cookie.left = sizeof(tbuf);
165 fp = fwopen(&tbuf_cookie, writehook);
169 /* Build the message. */
171 (void)fprintf(fp, "<%d>", pri);
172 (void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
173 if (LogStat & LOG_PERROR) {
174 /* Transfer to string buffer */
176 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
179 LogTag = _getprogname();
181 (void)fprintf(fp, "%s", LogTag);
182 if (LogStat & LOG_PID)
183 (void)fprintf(fp, "[%d]", getpid());
184 if (LogTag != NULL) {
185 (void)fprintf(fp, ": ");
188 /* Check to see if we can skip expanding the %m */
189 if (strstr(fmt, "%m")) {
191 /* Create the second stdio hook */
192 fmt_cookie.base = fmt_cpy;
193 fmt_cookie.left = sizeof(fmt_cpy) - 1;
194 fmt_fp = fwopen(&fmt_cookie, writehook);
195 if (fmt_fp == NULL) {
201 * Substitute error message for %m. Be careful not to
202 * molest an escaped percent "%%m". We want to pass it
203 * on untouched as the format is later parsed by vfprintf.
205 for ( ; (ch = *fmt); ++fmt) {
206 if (ch == '%' && fmt[1] == 'm') {
208 strerror_r(saved_errno, errstr, sizeof(errstr));
209 fputs(errstr, fmt_fp);
210 } else if (ch == '%' && fmt[1] == '%') {
219 /* Null terminate if room */
223 /* Guarantee null termination */
224 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
229 (void)vfprintf(fp, fmt, ap);
232 cnt = sizeof(tbuf) - tbuf_cookie.left;
234 /* Remove a trailing newline */
235 if (tbuf[cnt - 1] == '\n')
238 /* Output to stderr if requested. */
239 if (LogStat & LOG_PERROR) {
241 struct iovec *v = iov;
244 v->iov_len = cnt - (stdp - tbuf);
248 (void)_writev(STDERR_FILENO, iov, 2);
251 /* Get connected, output the message to the local logger. */
253 openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
257 * If the send() fails, there are two likely scenarios:
258 * 1) syslogd was restarted
259 * 2) /var/run/log is out of socket buffer space, which
260 * in most cases means local DoS.
261 * If the error does not indicate a full buffer, we address
262 * case #1 by attempting to reconnect to /var/run/log[priv]
263 * and resending the message once.
265 * If we are working with a privileged socket, the retry
266 * attempts end there, because we don't want to freeze a
267 * critical application like su(1) or sshd(8).
269 * Otherwise, we address case #2 by repeatedly retrying the
270 * send() to give syslogd a chance to empty its socket buffer.
273 if (send(LogFile, tbuf, cnt, 0) < 0) {
274 if (errno != ENOBUFS) {
276 * Scenario 1: syslogd was restarted
277 * reconnect and resend once
281 if (send(LogFile, tbuf, cnt, 0) >= 0)
284 * if the resend failed, fall through to
285 * possible scenario 2
288 while (errno == ENOBUFS) {
290 * Scenario 2: out of socket buffer space
291 * possible DoS, fail fast on a privileged
294 if (status == CONNPRIV)
297 if (send(LogFile, tbuf, cnt, 0) >= 0)
304 * Output the message to the console; try not to block
305 * as a blocking console should not stop other processes.
306 * Make sure the error reported is the one from the syslogd failure.
308 if (LogStat & LOG_CONS &&
309 (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >=
312 struct iovec *v = iov;
314 p = strchr(tbuf, '>') + 1;
316 v->iov_len = cnt - (p - tbuf);
318 v->iov_base = "\r\n";
320 (void)_writev(fd, iov, 2);
326 syslog_cancel_cleanup(void *arg __unused)
333 vsyslog(int pri, const char *fmt, va_list ap)
337 pthread_cleanup_push(syslog_cancel_cleanup, NULL);
338 vsyslog1(pri, fmt, ap);
339 pthread_cleanup_pop(1);
342 /* Should be called with mutex acquired */
347 * If the user closed the FD and opened another in the same slot,
348 * that's their problem. They should close it before calling on
355 status = NOCONN; /* retry connect */
358 /* Should be called with mutex acquired */
362 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
365 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
367 (void)_fcntl(LogFile, F_SETFD, FD_CLOEXEC);
369 if (LogFile != -1 && status == NOCONN) {
370 SyslogAddr.sun_len = sizeof(SyslogAddr);
371 SyslogAddr.sun_family = AF_UNIX;
374 * First try privileged socket. If no success,
375 * then try default socket.
377 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
378 sizeof SyslogAddr.sun_path);
379 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
380 sizeof(SyslogAddr)) != -1)
383 if (status == NOCONN) {
384 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
385 sizeof SyslogAddr.sun_path);
386 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
387 sizeof(SyslogAddr)) != -1)
391 if (status == NOCONN) {
393 * Try the old "/dev/log" path, for backward
396 (void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
397 sizeof SyslogAddr.sun_path);
398 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
399 sizeof(SyslogAddr)) != -1)
403 if (status == NOCONN) {
404 (void)_close(LogFile);
411 openlog_unlocked(const char *ident, int logstat, int logfac)
416 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
417 LogFacility = logfac;
419 if (LogStat & LOG_NDELAY) /* open immediately */
422 opened = 1; /* ident and facility has been set */
426 openlog(const char *ident, int logstat, int logfac)
430 pthread_cleanup_push(syslog_cancel_cleanup, NULL);
431 openlog_unlocked(ident, logstat, logfac);
432 pthread_cleanup_pop(1);
441 (void)_close(LogFile);
449 /* setlogmask -- set the log mask level */
451 setlogmask(int pmask)