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 $
31 * $DragonFly: src/lib/libc/gen/syslog.c,v 1.9 2005/11/19 22:32:53 swildner Exp $
34 #include "namespace.h"
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/syslog.h>
53 #include "un-namespace.h"
55 #include "libc_private.h"
57 static int LogFile = -1; /* fd for log */
58 static int status; /* connection status */
59 static int opened; /* have done openlog() */
60 static int LogStat = 0; /* status bits, set by openlog() */
61 static const char *LogTag = NULL; /* string to tag the entry with */
62 static int LogFacility = LOG_USER; /* default facility code */
63 static int LogMask = 0xff; /* mask of priorities to be logged */
64 static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER;
66 #define THREAD_LOCK() \
68 if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \
70 #define THREAD_UNLOCK() \
72 if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \
75 static void disconnectlog(void); /* disconnect from syslogd */
76 static void connectlog(void); /* (re)connect to syslogd */
77 static void openlog_unlocked(const char *, int, int);
86 * Format of the magic cookie passed through the stdio hook
89 char *base; /* start of buffer */
94 * stdio write hook for writing to a static string buffer
95 * XXX: Maybe one day, dynamically allocate it so that the line length
99 writehook(void *cookie, const char *buf, int len)
101 struct bufcookie *h; /* private `handle' */
103 h = (struct bufcookie *)cookie;
105 /* clip in case of wraparound */
109 memcpy(h->base, buf, len); /* `write' it. */
118 * print message on log file; output is intended for syslogd(8).
121 syslog(int pri, const char *fmt, ...)
126 vsyslog(pri, fmt, ap);
131 vsyslog(int pri, const char *fmt, va_list ap)
137 char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64];
139 struct bufcookie tbuf_cookie;
140 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 fprintf(fp, "<%d>", pri);
178 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 fprintf(fp, "%s", LogTag);
188 if (LogStat & LOG_PID)
189 fprintf(fp, "[%d]", getpid());
190 if (LogTag != NULL) {
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 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 _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() failed, 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 * 3) syslogd itself got stuck.
270 * We attempt to reconnect to /var/run/log to take care of
271 * case #1 and keep send()ing data to cover case #2
272 * to give syslogd a chance to empty its socket buffer.
273 * However, to deal with #3 we retry no more than 10 times
274 * for up to one second before giving up. Otherwise a
275 * broken syslogd will completely and utterly break the
276 * entire system == bad.
278 * If we are working with a priveleged socket, then take
279 * only one attempt, because we don't want to freeze a
280 * critical application like su(1) or sshd(8).
283 if (send(LogFile, tbuf, cnt, 0) < 0) {
286 if (errno != ENOBUFS) {
290 for (maxtries = 10; maxtries; --maxtries) {
291 if (send(LogFile, tbuf, cnt, 0) >= 0) {
295 if (status == CONNPRIV)
297 if (errno != ENOBUFS)
299 _usleep(1000000 / 10);
307 * Output the message to the console; try not to block
308 * as a blocking console should not stop other processes.
309 * Make sure the error reported is the one from the syslogd failure.
311 if ((LogStat & LOG_CONS) &&
312 (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) {
314 struct iovec *v = iov;
316 p = strchr(tbuf, '>') + 1;
318 v->iov_len = cnt - (p - tbuf);
320 v->iov_base = "\r\n";
329 /* Should be called with mutex acquired */
334 * If the user closed the FD and opened another in the same slot,
335 * that's their problem. They should close it before calling on
342 status = NOCONN; /* retry connect */
345 /* Should be called with mutex acquired */
349 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
352 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
354 _fcntl(LogFile, F_SETFD, 1);
356 if (LogFile != -1 && status == NOCONN) {
357 SyslogAddr.sun_len = sizeof(SyslogAddr);
358 SyslogAddr.sun_family = AF_UNIX;
361 * First try priveleged socket. If no success,
362 * then try default socket.
364 strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
365 sizeof SyslogAddr.sun_path);
366 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
367 sizeof(SyslogAddr)) != -1)
370 if (status == NOCONN) {
371 strncpy(SyslogAddr.sun_path, _PATH_LOG,
372 sizeof SyslogAddr.sun_path);
373 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
374 sizeof(SyslogAddr)) != -1)
378 if (status == NOCONN) {
380 * Try the old "/dev/log" path, for backward
383 strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
384 sizeof SyslogAddr.sun_path);
385 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
386 sizeof(SyslogAddr)) != -1)
390 if (status == NOCONN) {
398 openlog_unlocked(const char *ident, int logstat, int logfac)
403 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
404 LogFacility = logfac;
406 if (LogStat & LOG_NDELAY) /* open immediately */
409 opened = 1; /* ident and facility has been set */
413 openlog(const char *ident, int logstat, int logfac)
416 openlog_unlocked(ident, logstat, logfac);
432 /* setlogmask -- set the log mask level */
434 setlogmask(int pmask)