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 vsyslog(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;
156 /* Check priority against setlogmask values. */
157 if (!(LOG_MASK(LOG_PRI(pri)) & LogMask)) {
162 /* Set default facility if none specified. */
163 if ((pri & LOG_FACMASK) == 0)
166 /* Create the primary stdio hook */
167 tbuf_cookie.base = tbuf;
168 tbuf_cookie.left = sizeof(tbuf);
169 fp = fwopen(&tbuf_cookie, writehook);
175 /* Build the message. */
177 (void)fprintf(fp, "<%d>", pri);
178 (void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
179 if (LogStat & LOG_PERROR) {
180 /* Transfer to string buffer */
182 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
185 LogTag = _getprogname();
187 (void)fprintf(fp, "%s", LogTag);
188 if (LogStat & LOG_PID)
189 (void)fprintf(fp, "[%d]", getpid());
190 if (LogTag != NULL) {
191 (void)fprintf(fp, ": ");
194 /* Check to see if we can skip expanding the %m */
195 if (strstr(fmt, "%m")) {
197 /* Create the second stdio hook */
198 fmt_cookie.base = fmt_cpy;
199 fmt_cookie.left = sizeof(fmt_cpy) - 1;
200 fmt_fp = fwopen(&fmt_cookie, writehook);
201 if (fmt_fp == NULL) {
208 * Substitute error message for %m. Be careful not to
209 * molest an escaped percent "%%m". We want to pass it
210 * on untouched as the format is later parsed by vfprintf.
212 for ( ; (ch = *fmt); ++fmt) {
213 if (ch == '%' && fmt[1] == 'm') {
215 strerror_r(saved_errno, errstr, sizeof(errstr));
216 fputs(errstr, fmt_fp);
217 } else if (ch == '%' && fmt[1] == '%') {
226 /* Null terminate if room */
230 /* Guarantee null termination */
231 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
236 (void)vfprintf(fp, fmt, ap);
239 cnt = sizeof(tbuf) - tbuf_cookie.left;
241 /* Remove a trailing newline */
242 if (tbuf[cnt - 1] == '\n')
245 /* Output to stderr if requested. */
246 if (LogStat & LOG_PERROR) {
248 struct iovec *v = iov;
251 v->iov_len = cnt - (stdp - tbuf);
255 (void)_writev(STDERR_FILENO, iov, 2);
258 /* Get connected, output the message to the local logger. */
260 openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
264 * If the send() fails, there are two likely scenarios:
265 * 1) syslogd was restarted
266 * 2) /var/run/log is out of socket buffer space, which
267 * in most cases means local DoS.
268 * If the error does not indicate a full buffer, we address
269 * case #1 by attempting to reconnect to /var/run/log[priv]
270 * and resending the message once.
272 * If we are working with a privileged socket, the retry
273 * attempts end there, because we don't want to freeze a
274 * critical application like su(1) or sshd(8).
276 * Otherwise, we address case #2 by repeatedly retrying the
277 * send() to give syslogd a chance to empty its socket buffer.
280 if (send(LogFile, tbuf, cnt, 0) < 0) {
281 if (errno != ENOBUFS) {
283 * Scenario 1: syslogd was restarted
284 * reconnect and resend once
288 if (send(LogFile, tbuf, cnt, 0) >= 0) {
293 * if the resend failed, fall through to
294 * possible scenario 2
297 while (errno == ENOBUFS) {
299 * Scenario 2: out of socket buffer space
300 * possible DoS, fail fast on a privileged
303 if (status == CONNPRIV)
306 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, '>') + 1;
329 v->iov_len = cnt - (p - tbuf);
331 v->iov_base = "\r\n";
333 (void)_writev(fd, iov, 2);
340 /* Should be called with mutex acquired */
345 * If the user closed the FD and opened another in the same slot,
346 * that's their problem. They should close it before calling on
353 status = NOCONN; /* retry connect */
356 /* Should be called with mutex acquired */
360 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
363 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
365 (void)_fcntl(LogFile, F_SETFD, FD_CLOEXEC);
367 if (LogFile != -1 && status == NOCONN) {
368 SyslogAddr.sun_len = sizeof(SyslogAddr);
369 SyslogAddr.sun_family = AF_UNIX;
372 * First try privileged socket. If no success,
373 * then try default socket.
375 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
376 sizeof SyslogAddr.sun_path);
377 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
378 sizeof(SyslogAddr)) != -1)
381 if (status == NOCONN) {
382 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
383 sizeof SyslogAddr.sun_path);
384 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
385 sizeof(SyslogAddr)) != -1)
389 if (status == NOCONN) {
391 * Try the old "/dev/log" path, for backward
394 (void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
395 sizeof SyslogAddr.sun_path);
396 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
397 sizeof(SyslogAddr)) != -1)
401 if (status == NOCONN) {
402 (void)_close(LogFile);
409 openlog_unlocked(const char *ident, int logstat, int logfac)
414 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
415 LogFacility = logfac;
417 if (LogStat & LOG_NDELAY) /* open immediately */
420 opened = 1; /* ident and facility has been set */
424 openlog(const char *ident, int logstat, int logfac)
427 openlog_unlocked(ident, logstat, logfac);
437 (void)_close(LogFile);
445 /* setlogmask -- set the log mask level */
447 setlogmask(int pmask)