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