xref: /dflybsd-src/lib/libc/gen/syslog.c (revision 40392ead9c5dc9b5cb76b4be834e2d99a661ccc0)
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
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
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 void
130 vsyslog(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 	THREAD_LOCK();
153 
154 	/* Check priority against setlogmask values. */
155 	if (!(LOG_MASK(LOG_PRI(pri)) & LogMask)) {
156 		THREAD_UNLOCK();
157 		return;
158 	}
159 
160 	/* Set default facility if none specified. */
161 	if ((pri & LOG_FACMASK) == 0)
162 		pri |= LogFacility;
163 
164 	/* Create the primary stdio hook */
165 	tbuf_cookie.base = tbuf;
166 	tbuf_cookie.left = sizeof(tbuf);
167 	fp = fwopen(&tbuf_cookie, writehook);
168 	if (fp == NULL) {
169 		THREAD_UNLOCK();
170 		return;
171 	}
172 
173 	/* Build the message. */
174 	time(&now);
175 	fprintf(fp, "<%d>", pri);
176 	fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
177 	if (LogStat & LOG_PERROR) {
178 		/* Transfer to string buffer */
179 		fflush(fp);
180 		stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
181 	}
182 	if (LogTag == NULL)
183 		LogTag = _getprogname();
184 	if (LogTag != NULL)
185 		fprintf(fp, "%s", LogTag);
186 	if (LogStat & LOG_PID)
187 		fprintf(fp, "[%d]", getpid());
188 	if (LogTag != NULL)
189 		fprintf(fp, ": ");
190 
191 	/* Check to see if we can skip expanding the %m */
192 	if (strstr(fmt, "%m")) {
193 
194 		/* Create the second stdio hook */
195 		fmt_cookie.base = fmt_cpy;
196 		fmt_cookie.left = sizeof(fmt_cpy) - 1;
197 		fmt_fp = fwopen(&fmt_cookie, writehook);
198 		if (fmt_fp == NULL) {
199 			fclose(fp);
200 			THREAD_UNLOCK();
201 			return;
202 		}
203 
204 		/*
205 		 * Substitute error message for %m.  Be careful not to
206 		 * molest an escaped percent "%%m".  We want to pass it
207 		 * on untouched as the format is later parsed by vfprintf.
208 		 */
209 		for ( ; (ch = *fmt); ++fmt) {
210 			if (ch == '%' && fmt[1] == 'm') {
211 				++fmt;
212 				strerror_r(saved_errno, errstr, sizeof(errstr));
213 				fputs(errstr, fmt_fp);
214 			} else if (ch == '%' && fmt[1] == '%') {
215 				++fmt;
216 				fputc(ch, fmt_fp);
217 				fputc(ch, fmt_fp);
218 			} else {
219 				fputc(ch, fmt_fp);
220 			}
221 		}
222 
223 		/* Null terminate if room */
224 		fputc(0, fmt_fp);
225 		fclose(fmt_fp);
226 
227 		/* Guarantee null termination */
228 		fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
229 
230 		fmt = fmt_cpy;
231 	}
232 
233 	vfprintf(fp, fmt, ap);
234 	fclose(fp);
235 
236 	cnt = sizeof(tbuf) - tbuf_cookie.left;
237 
238 	/* Remove a trailing newline */
239 	if (tbuf[cnt - 1] == '\n')
240 		cnt--;
241 
242 	/* Output to stderr if requested. */
243 	if (LogStat & LOG_PERROR) {
244 		struct iovec iov[2];
245 		struct iovec *v = iov;
246 
247 		v->iov_base = stdp;
248 		v->iov_len = cnt - (stdp - tbuf);
249 		++v;
250 		v->iov_base = "\n";
251 		v->iov_len = 1;
252 		_writev(STDERR_FILENO, iov, 2);
253 	}
254 
255 	/* Get connected, output the message to the local logger. */
256 	if (!opened)
257 		openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
258 	connectlog();
259 
260 	/*
261 	 * If the send() fails, there are three likely scenarios:
262 	 *  1) syslogd was restarted
263 	 *  2) /var/run/log is out of socket buffer space, which
264 	 *     in most cases means local DoS.
265 	 *  3) syslogd itself got stuck.
266 	 *
267 	 * We attempt to reconnect to /var/run/log to take care of
268 	 * case #1 and keep send()ing data to cover case #2
269 	 * to give syslogd a chance to empty its socket buffer.
270 	 * However, to deal with #3 we retry no more than 10 times
271 	 * for up to one second before giving up.  Otherwise a
272 	 * broken syslogd will completely and utterly break the
273 	 * entire system == bad.
274 	 *
275 	 * If we are working with a privileged socket, then take
276 	 * only one attempt, because we don't want to freeze a
277 	 * critical application like su(1) or sshd(8).
278 	 *
279 	 */
280 	if (send(LogFile, tbuf, cnt, 0) < 0) {
281 		if (errno != ENOBUFS) {
282 			disconnectlog();
283 			connectlog();
284 		}
285 		for (maxtries = 10; maxtries; --maxtries) {
286 			if (send(LogFile, tbuf, cnt, 0) >= 0) {
287 				THREAD_UNLOCK();
288 				return;
289 			}
290 			if (status == CONNPRIV)
291 				break;
292 			if (errno != ENOBUFS)
293 				break;
294 			_usleep(1000000 / 10);
295 		}
296 	} else {
297 		THREAD_UNLOCK();
298 		return;
299 	}
300 
301 	/*
302 	 * Output the message to the console; try not to block
303 	 * as a blocking console should not stop other processes.
304 	 * Make sure the error reported is the one from the syslogd failure.
305 	 */
306 	if ((LogStat & LOG_CONS) &&
307 	    (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >= 0) {
308 		struct iovec iov[2];
309 		struct iovec *v = iov;
310 
311 		p = strchr(tbuf, '>') + 1;
312 		v->iov_base = p;
313 		v->iov_len = cnt - (p - tbuf);
314 		++v;
315 		v->iov_base = "\r\n";
316 		v->iov_len = 2;
317 		_writev(fd, iov, 2);
318 		_close(fd);
319 	}
320 
321 	THREAD_UNLOCK();
322 }
323 
324 /* Should be called with mutex acquired */
325 static void
326 disconnectlog(void)
327 {
328 	/*
329 	 * If the user closed the FD and opened another in the same slot,
330 	 * that's their problem.  They should close it before calling on
331 	 * system services.
332 	 */
333 	if (LogFile != -1) {
334 		_close(LogFile);
335 		LogFile = -1;
336 	}
337 	status = NOCONN;			/* retry connect */
338 }
339 
340 /* Should be called with mutex acquired */
341 static void
342 connectlog(void)
343 {
344 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
345 
346 	if (LogFile == -1) {
347 		if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
348 			return;
349 		_fcntl(LogFile, F_SETFD, 1);
350 	}
351 	if (LogFile != -1 && status == NOCONN) {
352 		SyslogAddr.sun_len = sizeof(SyslogAddr);
353 		SyslogAddr.sun_family = AF_UNIX;
354 
355 		/*
356 		 * First try privileged socket. If no success,
357 		 * then try default socket.
358 		 */
359 		strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
360 		    sizeof SyslogAddr.sun_path);
361 		if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
362 		    sizeof(SyslogAddr)) != -1)
363 			status = CONNPRIV;
364 
365 		if (status == NOCONN) {
366 			strncpy(SyslogAddr.sun_path, _PATH_LOG,
367 			    sizeof SyslogAddr.sun_path);
368 			if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
369 			    sizeof(SyslogAddr)) != -1)
370 				status = CONNDEF;
371 		}
372 
373 		if (status == NOCONN) {
374 			/*
375 			 * Try the old "/dev/log" path, for backward
376 			 * compatibility.
377 			 */
378 			strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
379 			    sizeof SyslogAddr.sun_path);
380 			if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
381 			    sizeof(SyslogAddr)) != -1)
382 				status = CONNDEF;
383 		}
384 
385 		if (status == NOCONN) {
386 			_close(LogFile);
387 			LogFile = -1;
388 		}
389 	}
390 }
391 
392 static void
393 openlog_unlocked(const char *ident, int logstat, int logfac)
394 {
395 	if (ident != NULL)
396 		LogTag = ident;
397 	LogStat = logstat;
398 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
399 		LogFacility = logfac;
400 
401 	if (LogStat & LOG_NDELAY)	/* open immediately */
402 		connectlog();
403 
404 	opened = 1;	/* ident and facility has been set */
405 }
406 
407 void
408 openlog(const char *ident, int logstat, int logfac)
409 {
410 	THREAD_LOCK();
411 	openlog_unlocked(ident, logstat, logfac);
412 	THREAD_UNLOCK();
413 }
414 
415 
416 void
417 closelog(void)
418 {
419 	THREAD_LOCK();
420 	_close(LogFile);
421 	LogFile = -1;
422 	LogTag = NULL;
423 	status = NOCONN;
424 	THREAD_UNLOCK();
425 }
426 
427 /* setlogmask -- set the log mask level */
428 int
429 setlogmask(int pmask)
430 {
431 	int omask;
432 
433 	THREAD_LOCK();
434 	omask = LogMask;
435 	if (pmask != 0)
436 		LogMask = pmask;
437 	THREAD_UNLOCK();
438 	return (omask);
439 }
440