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 * 3. 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
29 * @(#)syslog.c 8.5 (Berkeley) 4/29/95
30 * $FreeBSD: src/lib/libc/gen/syslog.c,v 1.39 2007/01/09 00:27:55 imp Exp $
33 #include "namespace.h"
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/syslog.h>
52 #include "un-namespace.h"
54 #include "libc_private.h"
56 static int LogFile = -1; /* fd for log */
57 static int status; /* connection status */
58 static int opened; /* have done openlog() */
59 static int LogStat = 0; /* status bits, set by openlog() */
60 static const char *LogTag = NULL; /* string to tag the entry with */
61 static int LogFacility = LOG_USER; /* default facility code */
62 static int LogMask = 0xff; /* mask of priorities to be logged */
63 static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER;
65 #define THREAD_LOCK() \
67 if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \
69 #define THREAD_UNLOCK() \
71 if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \
74 static void disconnectlog(void); /* disconnect from syslogd */
75 static void connectlog(void); /* (re)connect to syslogd */
76 static void openlog_unlocked(const char *, int, int);
85 * Format of the magic cookie passed through the stdio hook
88 char *base; /* start of buffer */
93 * stdio write hook for writing to a static string buffer
94 * XXX: Maybe one day, dynamically allocate it so that the line length
98 writehook(void *cookie, const char *buf, int len)
100 struct bufcookie *h; /* private `handle' */
102 h = (struct bufcookie *)cookie;
104 /* clip in case of wraparound */
108 memcpy(h->base, buf, len); /* `write' it. */
117 * print message on log file; output is intended for syslogd(8).
120 syslog(int pri, const char *fmt, ...)
125 vsyslog(pri, fmt, ap);
130 vsyslog_unlocked(int pri, const char *fmt, va_list ap)
134 int cnt, fd, saved_errno, maxtries;
135 char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64];
137 struct bufcookie tbuf_cookie;
138 struct bufcookie fmt_cookie;
142 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
143 /* Check for invalid bits. */
144 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
146 "syslog: unknown facility/priority: %x", pri);
147 pri &= LOG_PRIMASK|LOG_FACMASK;
152 /* Check priority against setlogmask values. */
153 if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
156 /* Set default facility if none specified. */
157 if ((pri & LOG_FACMASK) == 0)
160 /* Create the primary stdio hook */
161 tbuf_cookie.base = tbuf;
162 tbuf_cookie.left = sizeof(tbuf);
163 fp = fwopen(&tbuf_cookie, writehook);
167 /* Build the message. */
169 fprintf(fp, "<%d>", pri);
170 fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
171 if (LogStat & LOG_PERROR) {
172 /* Transfer to string buffer */
174 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
177 LogTag = _getprogname();
179 fprintf(fp, "%s", LogTag);
180 if (LogStat & LOG_PID)
181 fprintf(fp, "[%d]", getpid());
185 /* Check to see if we can skip expanding the %m */
186 if (strstr(fmt, "%m")) {
188 /* Create the second stdio hook */
189 fmt_cookie.base = fmt_cpy;
190 fmt_cookie.left = sizeof(fmt_cpy) - 1;
191 fmt_fp = fwopen(&fmt_cookie, writehook);
192 if (fmt_fp == NULL) {
198 * Substitute error message for %m. Be careful not to
199 * molest an escaped percent "%%m". We want to pass it
200 * on untouched as the format is later parsed by vfprintf.
202 for ( ; (ch = *fmt); ++fmt) {
203 if (ch == '%' && fmt[1] == 'm') {
205 strerror_r(saved_errno, errstr, sizeof(errstr));
206 fputs(errstr, fmt_fp);
207 } else if (ch == '%' && fmt[1] == '%') {
216 /* Null terminate if room */
220 /* Guarantee null termination */
221 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
226 vfprintf(fp, fmt, ap);
229 cnt = sizeof(tbuf) - tbuf_cookie.left;
231 /* Remove a trailing newline */
232 if (tbuf[cnt - 1] == '\n')
235 /* Output to stderr if requested. */
236 if (LogStat & LOG_PERROR) {
238 struct iovec *v = iov;
241 v->iov_len = cnt - (stdp - tbuf);
245 _writev(STDERR_FILENO, iov, 2);
248 /* Get connected, output the message to the local logger. */
250 openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
254 * If the send() fails, there are three likely scenarios:
255 * 1) syslogd was restarted
256 * 2) /var/run/log is out of socket buffer space, which
257 * in most cases means local DoS.
258 * 3) syslogd itself got stuck.
260 * We attempt to reconnect to /var/run/log to take care of
261 * case #1 and keep send()ing data to cover case #2
262 * to give syslogd a chance to empty its socket buffer.
263 * However, to deal with #3 we retry no more than 10 times
264 * for up to one second before giving up. Otherwise a
265 * broken syslogd will completely and utterly break the
266 * entire system == bad.
268 * If we are working with a privileged socket, then take
269 * only one attempt, because we don't want to freeze a
270 * critical application like su(1) or sshd(8).
273 if (send(LogFile, tbuf, cnt, 0) < 0) {
274 if (errno != ENOBUFS) {
278 for (maxtries = 10; maxtries; --maxtries) {
279 if (send(LogFile, tbuf, cnt, 0) >= 0)
281 if (status == CONNPRIV)
283 if (errno != ENOBUFS)
285 _usleep(1000000 / 10);
292 * Output the message to the console; try not to block
293 * as a blocking console should not stop other processes.
294 * Make sure the error reported is the one from the syslogd failure.
296 if ((LogStat & LOG_CONS) &&
297 (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >= 0) {
299 struct iovec *v = iov;
301 p = strchr(tbuf, '>') + 1;
303 v->iov_len = cnt - (p - tbuf);
305 v->iov_base = "\r\n";
313 vsyslog(int pri, const char *fmt, va_list ap)
316 vsyslog_unlocked(pri, fmt, ap);
320 /* Should be called with mutex acquired */
325 * If the user closed the FD and opened another in the same slot,
326 * that's their problem. They should close it before calling on
333 status = NOCONN; /* retry connect */
336 /* Should be called with mutex acquired */
340 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
343 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
347 if (LogFile != -1 && status == NOCONN) {
348 SyslogAddr.sun_len = sizeof(SyslogAddr);
349 SyslogAddr.sun_family = AF_UNIX;
352 * First try privileged socket. If no success,
353 * then try default socket.
355 strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
356 sizeof SyslogAddr.sun_path);
357 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
358 sizeof(SyslogAddr)) != -1)
361 if (status == NOCONN) {
362 strncpy(SyslogAddr.sun_path, _PATH_LOG,
363 sizeof SyslogAddr.sun_path);
364 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
365 sizeof(SyslogAddr)) != -1)
369 if (status == NOCONN) {
371 * Try the old "/dev/log" path, for backward
374 strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
375 sizeof SyslogAddr.sun_path);
376 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
377 sizeof(SyslogAddr)) != -1)
381 if (status == NOCONN) {
389 openlog_unlocked(const char *ident, int logstat, int logfac)
394 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
395 LogFacility = logfac;
397 if (LogStat & LOG_NDELAY) /* open immediately */
400 opened = 1; /* ident and facility has been set */
404 openlog(const char *ident, int logstat, int logfac)
407 openlog_unlocked(ident, logstat, logfac);
425 /* setlogmask -- set the log mask level */
427 setlogmask(int pmask)