xref: /dragonfly/lib/libc/gen/syslog.c (revision 8ca63dbf)
1 /*
2  * Copyright (c) 1983, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
16  *
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
27  * SUCH DAMAGE.
28  *
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  */
32 
33 #include "namespace.h"
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/syslog.h>
37 #include <sys/uio.h>
38 #include <sys/un.h>
39 #include <netdb.h>
40 
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <paths.h>
44 #include <pthread.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <time.h>
49 #include <unistd.h>
50 
51 #include <stdarg.h>
52 #include "un-namespace.h"
53 
54 #include "libc_private.h"
55 
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;
64 
65 #define	THREAD_LOCK()							\
66 	do { 								\
67 		if (__isthreaded) _pthread_mutex_lock(&syslog_mutex);	\
68 	} while(0)
69 #define	THREAD_UNLOCK()							\
70 	do {								\
71 		if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex);	\
72 	} while(0)
73 
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);
77 
78 enum {
79 	NOCONN = 0,
80 	CONNDEF,
81 	CONNPRIV,
82 };
83 
84 /*
85  * Format of the magic cookie passed through the stdio hook
86  */
87 struct bufcookie {
88 	char	*base;	/* start of buffer */
89 	int	left;
90 };
91 
92 /*
93  * stdio write hook for writing to a static string buffer
94  * XXX: Maybe one day, dynamically allocate it so that the line length
95  *      is `unlimited'.
96  */
97 static int
writehook(void * cookie,const char * buf,int len)98 writehook(void *cookie, const char *buf, int len)
99 {
100 	struct bufcookie *h;	/* private `handle' */
101 
102 	h = (struct bufcookie *)cookie;
103 	if (len > h->left) {
104 		/* clip in case of wraparound */
105 		len = h->left;
106 	}
107 	if (len > 0) {
108 		memcpy(h->base, buf, len); /* `write' it. */
109 		h->base += len;
110 		h->left -= len;
111 	}
112 	return len;
113 }
114 
115 /*
116  * syslog, vsyslog --
117  *	print message on log file; output is intended for syslogd(8).
118  */
119 void
syslog(int pri,const char * fmt,...)120 syslog(int pri, const char *fmt, ...)
121 {
122 	va_list ap;
123 
124 	va_start(ap, fmt);
125 	vsyslog(pri, fmt, ap);
126 	va_end(ap);
127 }
128 
129 static void
vsyslog_unlocked(int pri,const char * fmt,va_list ap)130 vsyslog_unlocked(int pri, const char *fmt, va_list ap)
131 {
132 	char ch, *p;
133 	time_t now;
134 	int cnt, fd, saved_errno, maxtries;
135 	char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64];
136 	FILE *fp, *fmt_fp;
137 	struct bufcookie tbuf_cookie;
138 	struct bufcookie fmt_cookie;
139 
140 	stdp = NULL;
141 
142 #define	INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
143 	/* Check for invalid bits. */
144 	if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
145 		syslog(INTERNALLOG,
146 		    "syslog: unknown facility/priority: %x", pri);
147 		pri &= LOG_PRIMASK|LOG_FACMASK;
148 	}
149 
150 	saved_errno = errno;
151 
152 	/* Check priority against setlogmask values. */
153 	if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
154 		return;
155 
156 	/* Set default facility if none specified. */
157 	if ((pri & LOG_FACMASK) == 0)
158 		pri |= LogFacility;
159 
160 	/* Create the primary stdio hook */
161 	tbuf_cookie.base = tbuf;
162 	tbuf_cookie.left = sizeof(tbuf);
163 	fp = fwopen(&tbuf_cookie, writehook);
164 	if (fp == NULL)
165 		return;
166 
167 	/* Build the message. */
168 	time(&now);
169 	fprintf(fp, "<%d>", pri);
170 	fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
171 	if (LogStat & LOG_PERROR) {
172 		/* Transfer to string buffer */
173 		fflush(fp);
174 		stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
175 	}
176 	if (LogTag == NULL)
177 		LogTag = _getprogname();
178 	if (LogTag != NULL)
179 		fprintf(fp, "%s", LogTag);
180 	if (LogStat & LOG_PID)
181 		fprintf(fp, "[%d]", getpid());
182 	if (LogTag != NULL)
183 		fprintf(fp, ": ");
184 
185 	/* Check to see if we can skip expanding the %m */
186 	if (strstr(fmt, "%m")) {
187 
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) {
193 			fclose(fp);
194 			return;
195 		}
196 
197 		/*
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.
201 		 */
202 		for ( ; (ch = *fmt); ++fmt) {
203 			if (ch == '%' && fmt[1] == 'm') {
204 				++fmt;
205 				strerror_r(saved_errno, errstr, sizeof(errstr));
206 				fputs(errstr, fmt_fp);
207 			} else if (ch == '%' && fmt[1] == '%') {
208 				++fmt;
209 				fputc(ch, fmt_fp);
210 				fputc(ch, fmt_fp);
211 			} else {
212 				fputc(ch, fmt_fp);
213 			}
214 		}
215 
216 		/* Null terminate if room */
217 		fputc(0, fmt_fp);
218 		fclose(fmt_fp);
219 
220 		/* Guarantee null termination */
221 		fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
222 
223 		fmt = fmt_cpy;
224 	}
225 
226 	vfprintf(fp, fmt, ap);
227 	fclose(fp);
228 
229 	cnt = sizeof(tbuf) - tbuf_cookie.left;
230 
231 	/* Remove a trailing newline */
232 	if (tbuf[cnt - 1] == '\n')
233 		cnt--;
234 
235 	/* Output to stderr if requested. */
236 	if (LogStat & LOG_PERROR) {
237 		struct iovec iov[2];
238 		struct iovec *v = iov;
239 
240 		v->iov_base = stdp;
241 		v->iov_len = cnt - (stdp - tbuf);
242 		++v;
243 		v->iov_base = "\n";
244 		v->iov_len = 1;
245 		_writev(STDERR_FILENO, iov, 2);
246 	}
247 
248 	/* Get connected, output the message to the local logger. */
249 	if (!opened)
250 		openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
251 	connectlog();
252 
253 	/*
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.
259 	 *
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.
267 	 *
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).
271 	 *
272 	 */
273 	if (send(LogFile, tbuf, cnt, 0) < 0) {
274 		if (errno != ENOBUFS) {
275 			disconnectlog();
276 			connectlog();
277 		}
278 		for (maxtries = 10; maxtries; --maxtries) {
279 			if (send(LogFile, tbuf, cnt, 0) >= 0)
280 				return;
281 			if (status == CONNPRIV)
282 				break;
283 			if (errno != ENOBUFS)
284 				break;
285 			_usleep(1000000 / 10);
286 		}
287 	} else {
288 		return;
289 	}
290 
291 	/*
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.
295 	 */
296 	if ((LogStat & LOG_CONS) &&
297 	    (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >= 0) {
298 		struct iovec iov[2];
299 		struct iovec *v = iov;
300 
301 		p = strchr(tbuf, '>') + 1;
302 		v->iov_base = p;
303 		v->iov_len = cnt - (p - tbuf);
304 		++v;
305 		v->iov_base = "\r\n";
306 		v->iov_len = 2;
307 		_writev(fd, iov, 2);
308 		_close(fd);
309 	}
310 }
311 
312 void
vsyslog(int pri,const char * fmt,va_list ap)313 vsyslog(int pri, const char *fmt, va_list ap)
314 {
315 	THREAD_LOCK();
316 	vsyslog_unlocked(pri, fmt, ap);
317 	THREAD_UNLOCK();
318 }
319 
320 /* Should be called with mutex acquired */
321 static void
disconnectlog(void)322 disconnectlog(void)
323 {
324 	/*
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
327 	 * system services.
328 	 */
329 	if (LogFile != -1) {
330 		_close(LogFile);
331 		LogFile = -1;
332 	}
333 	status = NOCONN;			/* retry connect */
334 }
335 
336 /* Should be called with mutex acquired */
337 static void
connectlog(void)338 connectlog(void)
339 {
340 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
341 
342 	if (LogFile == -1) {
343 		if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
344 		    0)) == -1)
345 			return;
346 	}
347 	if (LogFile != -1 && status == NOCONN) {
348 		SyslogAddr.sun_len = sizeof(SyslogAddr);
349 		SyslogAddr.sun_family = AF_UNIX;
350 
351 		/*
352 		 * First try privileged socket. If no success,
353 		 * then try default socket.
354 		 */
355 		strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
356 		    sizeof SyslogAddr.sun_path);
357 		if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
358 		    sizeof(SyslogAddr)) != -1)
359 			status = CONNPRIV;
360 
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)
366 				status = CONNDEF;
367 		}
368 
369 		if (status == NOCONN) {
370 			/*
371 			 * Try the old "/dev/log" path, for backward
372 			 * compatibility.
373 			 */
374 			strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
375 			    sizeof SyslogAddr.sun_path);
376 			if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
377 			    sizeof(SyslogAddr)) != -1)
378 				status = CONNDEF;
379 		}
380 
381 		if (status == NOCONN) {
382 			_close(LogFile);
383 			LogFile = -1;
384 		}
385 	}
386 }
387 
388 static void
openlog_unlocked(const char * ident,int logstat,int logfac)389 openlog_unlocked(const char *ident, int logstat, int logfac)
390 {
391 	if (ident != NULL)
392 		LogTag = ident;
393 	LogStat = logstat;
394 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
395 		LogFacility = logfac;
396 
397 	if (LogStat & LOG_NDELAY)	/* open immediately */
398 		connectlog();
399 
400 	opened = 1;	/* ident and facility has been set */
401 }
402 
403 void
openlog(const char * ident,int logstat,int logfac)404 openlog(const char *ident, int logstat, int logfac)
405 {
406 	THREAD_LOCK();
407 	openlog_unlocked(ident, logstat, logfac);
408 	THREAD_UNLOCK();
409 }
410 
411 
412 void
closelog(void)413 closelog(void)
414 {
415 	THREAD_LOCK();
416 	if (LogFile != -1) {
417 		_close(LogFile);
418 		LogFile = -1;
419 	}
420 	LogTag = NULL;
421 	status = NOCONN;
422 	THREAD_UNLOCK();
423 }
424 
425 /* setlogmask -- set the log mask level */
426 int
setlogmask(int pmask)427 setlogmask(int pmask)
428 {
429 	int omask;
430 
431 	THREAD_LOCK();
432 	omask = LogMask;
433 	if (pmask != 0)
434 		LogMask = pmask;
435 	THREAD_UNLOCK();
436 	return (omask);
437 }
438