xref: /freebsd/lib/libc/gen/syslog.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #if defined(LIBC_SCCS) && !defined(lint)
35 static char sccsid[] = "@(#)syslog.c	8.5 (Berkeley) 4/29/95";
36 #endif /* LIBC_SCCS and not lint */
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "namespace.h"
41 #include <sys/types.h>
42 #include <sys/socket.h>
43 #include <sys/syslog.h>
44 #include <sys/uio.h>
45 #include <sys/un.h>
46 #include <netdb.h>
47 
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <paths.h>
51 #include <pthread.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <time.h>
56 #include <unistd.h>
57 
58 #include <stdarg.h>
59 #include "un-namespace.h"
60 
61 #include "libc_private.h"
62 
63 static int	LogFile = -1;		/* fd for log */
64 static int	status;			/* connection status */
65 static int	opened;			/* have done openlog() */
66 static int	LogStat = 0;		/* status bits, set by openlog() */
67 static const char *LogTag = NULL;	/* string to tag the entry with */
68 static int	LogFacility = LOG_USER;	/* default facility code */
69 static int	LogMask = 0xff;		/* mask of priorities to be logged */
70 static pthread_mutex_t	syslog_mutex = PTHREAD_MUTEX_INITIALIZER;
71 
72 #define	THREAD_LOCK()							\
73 	do { 								\
74 		if (__isthreaded) _pthread_mutex_lock(&syslog_mutex);	\
75 	} while(0)
76 #define	THREAD_UNLOCK()							\
77 	do {								\
78 		if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex);	\
79 	} while(0)
80 
81 static void	disconnectlog(void); /* disconnect from syslogd */
82 static void	connectlog(void);	/* (re)connect to syslogd */
83 static void	openlog_unlocked(const char *, int, int);
84 
85 enum {
86 	NOCONN = 0,
87 	CONNDEF,
88 	CONNPRIV,
89 };
90 
91 /*
92  * Format of the magic cookie passed through the stdio hook
93  */
94 struct bufcookie {
95 	char	*base;	/* start of buffer */
96 	int	left;
97 };
98 
99 /*
100  * stdio write hook for writing to a static string buffer
101  * XXX: Maybe one day, dynamically allocate it so that the line length
102  *      is `unlimited'.
103  */
104 static
105 int writehook(cookie, buf, len)
106 	void	*cookie;	/* really [struct bufcookie *] */
107 	char	*buf;		/* characters to copy */
108 	int	len;		/* length to copy */
109 {
110 	struct bufcookie *h;	/* private `handle' */
111 
112 	h = (struct bufcookie *)cookie;
113 	if (len > h->left) {
114 		/* clip in case of wraparound */
115 		len = h->left;
116 	}
117 	if (len > 0) {
118 		(void)memcpy(h->base, buf, len); /* `write' it. */
119 		h->base += len;
120 		h->left -= len;
121 	}
122 	return 0;
123 }
124 
125 /*
126  * syslog, vsyslog --
127  *	print message on log file; output is intended for syslogd(8).
128  */
129 void
130 syslog(int pri, const char *fmt, ...)
131 {
132 	va_list ap;
133 
134 	va_start(ap, fmt);
135 	vsyslog(pri, fmt, ap);
136 	va_end(ap);
137 }
138 
139 void
140 vsyslog(pri, fmt, ap)
141 	int pri;
142 	const char *fmt;
143 	va_list ap;
144 {
145 	int cnt;
146 	char ch, *p;
147 	time_t now;
148 	int fd, saved_errno;
149 	char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64];
150 	FILE *fp, *fmt_fp;
151 	struct bufcookie tbuf_cookie;
152 	struct bufcookie fmt_cookie;
153 
154 #define	INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
155 	/* Check for invalid bits. */
156 	if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
157 		syslog(INTERNALLOG,
158 		    "syslog: unknown facility/priority: %x", pri);
159 		pri &= LOG_PRIMASK|LOG_FACMASK;
160 	}
161 
162 	THREAD_LOCK();
163 
164 	/* Check priority against setlogmask values. */
165 	if (!(LOG_MASK(LOG_PRI(pri)) & LogMask)) {
166 		THREAD_UNLOCK();
167 		return;
168 	}
169 
170 	saved_errno = errno;
171 
172 	/* Set default facility if none specified. */
173 	if ((pri & LOG_FACMASK) == 0)
174 		pri |= LogFacility;
175 
176 	/* Create the primary stdio hook */
177 	tbuf_cookie.base = tbuf;
178 	tbuf_cookie.left = sizeof(tbuf);
179 	fp = fwopen(&tbuf_cookie, writehook);
180 	if (fp == NULL) {
181 		THREAD_UNLOCK();
182 		return;
183 	}
184 
185 	/* Build the message. */
186 	(void)time(&now);
187 	(void)fprintf(fp, "<%d>", pri);
188 	(void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
189 	if (LogStat & LOG_PERROR) {
190 		/* Transfer to string buffer */
191 		(void)fflush(fp);
192 		stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
193 	}
194 	if (LogTag == NULL)
195 		LogTag = _getprogname();
196 	if (LogTag != NULL)
197 		(void)fprintf(fp, "%s", LogTag);
198 	if (LogStat & LOG_PID)
199 		(void)fprintf(fp, "[%d]", getpid());
200 	if (LogTag != NULL) {
201 		(void)fprintf(fp, ": ");
202 	}
203 
204 	/* Check to see if we can skip expanding the %m */
205 	if (strstr(fmt, "%m")) {
206 
207 		/* Create the second stdio hook */
208 		fmt_cookie.base = fmt_cpy;
209 		fmt_cookie.left = sizeof(fmt_cpy) - 1;
210 		fmt_fp = fwopen(&fmt_cookie, writehook);
211 		if (fmt_fp == NULL) {
212 			fclose(fp);
213 			THREAD_UNLOCK();
214 			return;
215 		}
216 
217 		/*
218 		 * Substitute error message for %m.  Be careful not to
219 		 * molest an escaped percent "%%m".  We want to pass it
220 		 * on untouched as the format is later parsed by vfprintf.
221 		 */
222 		for ( ; (ch = *fmt); ++fmt) {
223 			if (ch == '%' && fmt[1] == 'm') {
224 				++fmt;
225 				strerror_r(saved_errno, errstr, sizeof(errstr));
226 				fputs(errstr, fmt_fp);
227 			} else if (ch == '%' && fmt[1] == '%') {
228 				++fmt;
229 				fputc(ch, fmt_fp);
230 				fputc(ch, fmt_fp);
231 			} else {
232 				fputc(ch, fmt_fp);
233 			}
234 		}
235 
236 		/* Null terminate if room */
237 		fputc(0, fmt_fp);
238 		fclose(fmt_fp);
239 
240 		/* Guarantee null termination */
241 		fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
242 
243 		fmt = fmt_cpy;
244 	}
245 
246 	(void)vfprintf(fp, fmt, ap);
247 	(void)fclose(fp);
248 
249 	cnt = sizeof(tbuf) - tbuf_cookie.left;
250 
251 	/* Remove a trailing newline */
252 	if (tbuf[cnt - 1] == '\n')
253 		cnt--;
254 
255 	/* Output to stderr if requested. */
256 	if (LogStat & LOG_PERROR) {
257 		struct iovec iov[2];
258 		struct iovec *v = iov;
259 
260 		v->iov_base = stdp;
261 		v->iov_len = cnt - (stdp - tbuf);
262 		++v;
263 		v->iov_base = "\n";
264 		v->iov_len = 1;
265 		(void)_writev(STDERR_FILENO, iov, 2);
266 	}
267 
268 	/* Get connected, output the message to the local logger. */
269 	if (!opened)
270 		openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
271 	connectlog();
272 
273 	/*
274 	 * If the send() failed, there are two likely scenarios:
275 	 *  1) syslogd was restarted
276 	 *  2) /var/run/log is out of socket buffer space, which
277 	 *     in most cases means local DoS.
278 	 * We attempt to reconnect to /var/run/log to take care of
279 	 * case #1 and keep send()ing data to cover case #2
280 	 * to give syslogd a chance to empty its socket buffer.
281 	 *
282 	 * If we are working with a priveleged socket, then take
283 	 * only one attempt, because we don't want to freeze a
284 	 * critical application like su(1) or sshd(8).
285 	 *
286 	 */
287 
288 	if (send(LogFile, tbuf, cnt, 0) < 0) {
289 		if (errno != ENOBUFS) {
290 			disconnectlog();
291 			connectlog();
292 		}
293 		do {
294 			usleep(1);
295 			if (send(LogFile, tbuf, cnt, 0) >= 0) {
296 				THREAD_UNLOCK();
297 				return;
298 			}
299 			if (status == CONNPRIV)
300 				break;
301 		} while (errno == ENOBUFS);
302 	} else {
303 		THREAD_UNLOCK();
304 		return;
305 	}
306 
307 	/*
308 	 * Output the message to the console; try not to block
309 	 * as a blocking console should not stop other processes.
310 	 * Make sure the error reported is the one from the syslogd failure.
311 	 */
312 	if (LogStat & LOG_CONS &&
313 	    (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) {
314 		struct iovec iov[2];
315 		struct iovec *v = iov;
316 
317 		p = strchr(tbuf, '>') + 1;
318 		v->iov_base = p;
319 		v->iov_len = cnt - (p - tbuf);
320 		++v;
321 		v->iov_base = "\r\n";
322 		v->iov_len = 2;
323 		(void)_writev(fd, iov, 2);
324 		(void)_close(fd);
325 	}
326 
327 	THREAD_UNLOCK();
328 }
329 
330 /* Should be called with mutex acquired */
331 static void
332 disconnectlog()
333 {
334 	/*
335 	 * If the user closed the FD and opened another in the same slot,
336 	 * that's their problem.  They should close it before calling on
337 	 * system services.
338 	 */
339 	if (LogFile != -1) {
340 		_close(LogFile);
341 		LogFile = -1;
342 	}
343 	status = NOCONN;			/* retry connect */
344 }
345 
346 /* Should be called with mutex acquired */
347 static void
348 connectlog()
349 {
350 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
351 
352 	if (LogFile == -1) {
353 		if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
354 			return;
355 		(void)_fcntl(LogFile, F_SETFD, 1);
356 	}
357 	if (LogFile != -1 && status == NOCONN) {
358 		SyslogAddr.sun_len = sizeof(SyslogAddr);
359 		SyslogAddr.sun_family = AF_UNIX;
360 
361 		/*
362 		 * First try priveleged socket. If no success,
363 		 * then try default socket.
364 		 */
365 		(void)strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
366 		    sizeof SyslogAddr.sun_path);
367 		if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
368 		    sizeof(SyslogAddr)) != -1)
369 			status = CONNPRIV;
370 
371 		if (status == NOCONN) {
372 			(void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
373 			    sizeof SyslogAddr.sun_path);
374 			if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
375 			    sizeof(SyslogAddr)) != -1)
376 				status = CONNDEF;
377 		}
378 
379 		if (status == NOCONN) {
380 			/*
381 			 * Try the old "/dev/log" path, for backward
382 			 * compatibility.
383 			 */
384 			(void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
385 			    sizeof SyslogAddr.sun_path);
386 			if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
387 			    sizeof(SyslogAddr)) != -1)
388 				status = CONNDEF;
389 		}
390 
391 		if (status == NOCONN) {
392 			(void)_close(LogFile);
393 			LogFile = -1;
394 		}
395 	}
396 }
397 
398 static void
399 openlog_unlocked(ident, logstat, logfac)
400 	const char *ident;
401 	int logstat, logfac;
402 {
403 	if (ident != NULL)
404 		LogTag = ident;
405 	LogStat = logstat;
406 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
407 		LogFacility = logfac;
408 
409 	if (LogStat & LOG_NDELAY)	/* open immediately */
410 		connectlog();
411 
412 	opened = 1;	/* ident and facility has been set */
413 }
414 
415 void
416 openlog(ident, logstat, logfac)
417 	const char *ident;
418 	int logstat, logfac;
419 {
420 	THREAD_LOCK();
421 	openlog_unlocked(ident, logstat, logfac);
422 	THREAD_UNLOCK();
423 }
424 
425 
426 void
427 closelog()
428 {
429 	THREAD_LOCK();
430 	(void)_close(LogFile);
431 	LogFile = -1;
432 	LogTag = NULL;
433 	status = NOCONN;
434 	THREAD_UNLOCK();
435 }
436 
437 /* setlogmask -- set the log mask level */
438 int
439 setlogmask(pmask)
440 	int pmask;
441 {
442 	int omask;
443 
444 	THREAD_LOCK();
445 	omask = LogMask;
446 	if (pmask != 0)
447 		LogMask = pmask;
448 	THREAD_UNLOCK();
449 	return (omask);
450 }
451