xref: /freebsd/lib/libc/gen/syslog.c (revision 38d120bc13ac1de5b739b67b87016b9122149374)
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  * 4. 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 
30 #if defined(LIBC_SCCS) && !defined(lint)
31 static char sccsid[] = "@(#)syslog.c	8.5 (Berkeley) 4/29/95";
32 #endif /* LIBC_SCCS and not lint */
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "namespace.h"
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/syslog.h>
40 #include <sys/uio.h>
41 #include <sys/un.h>
42 #include <netdb.h>
43 
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <paths.h>
47 #include <pthread.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <time.h>
52 #include <unistd.h>
53 
54 #include <stdarg.h>
55 #include "un-namespace.h"
56 
57 #include "libc_private.h"
58 
59 static int	LogFile = -1;		/* fd for log */
60 static int	status;			/* connection status */
61 static int	opened;			/* have done openlog() */
62 static int	LogStat = 0;		/* status bits, set by openlog() */
63 static const char *LogTag = NULL;	/* string to tag the entry with */
64 static int	LogFacility = LOG_USER;	/* default facility code */
65 static int	LogMask = 0xff;		/* mask of priorities to be logged */
66 static pthread_mutex_t	syslog_mutex = PTHREAD_MUTEX_INITIALIZER;
67 
68 #define	THREAD_LOCK()							\
69 	do { 								\
70 		if (__isthreaded) _pthread_mutex_lock(&syslog_mutex);	\
71 	} while(0)
72 #define	THREAD_UNLOCK()							\
73 	do {								\
74 		if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex);	\
75 	} while(0)
76 
77 static void	disconnectlog(void); /* disconnect from syslogd */
78 static void	connectlog(void);	/* (re)connect to syslogd */
79 static void	openlog_unlocked(const char *, int, int);
80 
81 enum {
82 	NOCONN = 0,
83 	CONNDEF,
84 	CONNPRIV,
85 };
86 
87 /*
88  * Format of the magic cookie passed through the stdio hook
89  */
90 struct bufcookie {
91 	char	*base;	/* start of buffer */
92 	int	left;
93 };
94 
95 /*
96  * stdio write hook for writing to a static string buffer
97  * XXX: Maybe one day, dynamically allocate it so that the line length
98  *      is `unlimited'.
99  */
100 static int
101 writehook(void *cookie, const char *buf, int len)
102 {
103 	struct bufcookie *h;	/* private `handle' */
104 
105 	h = (struct bufcookie *)cookie;
106 	if (len > h->left) {
107 		/* clip in case of wraparound */
108 		len = h->left;
109 	}
110 	if (len > 0) {
111 		(void)memcpy(h->base, buf, len); /* `write' it. */
112 		h->base += len;
113 		h->left -= len;
114 	}
115 	return len;
116 }
117 
118 /*
119  * syslog, vsyslog --
120  *	print message on log file; output is intended for syslogd(8).
121  */
122 void
123 syslog(int pri, const char *fmt, ...)
124 {
125 	va_list ap;
126 
127 	va_start(ap, fmt);
128 	vsyslog(pri, fmt, ap);
129 	va_end(ap);
130 }
131 
132 void
133 vsyslog(int pri, const char *fmt, va_list ap)
134 {
135 	int cnt;
136 	char ch, *p;
137 	time_t now;
138 	int fd, saved_errno;
139 	char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64];
140 	FILE *fp, *fmt_fp;
141 	struct bufcookie tbuf_cookie;
142 	struct bufcookie fmt_cookie;
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 	(void)time(&now);
177 	(void)fprintf(fp, "<%d>", pri);
178 	(void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
179 	if (LogStat & LOG_PERROR) {
180 		/* Transfer to string buffer */
181 		(void)fflush(fp);
182 		stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
183 	}
184 	if (LogTag == NULL)
185 		LogTag = _getprogname();
186 	if (LogTag != NULL)
187 		(void)fprintf(fp, "%s", LogTag);
188 	if (LogStat & LOG_PID)
189 		(void)fprintf(fp, "[%d]", getpid());
190 	if (LogTag != NULL) {
191 		(void)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 	(void)vfprintf(fp, fmt, ap);
237 	(void)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 		(void)_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() fails, 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 	 * If the error does not indicate a full buffer, we address
269 	 * case #1 by attempting to reconnect to /var/run/log[priv]
270 	 * and resending the message once.
271 	 *
272 	 * If we are working with a privileged socket, the retry
273 	 * attempts end there, because we don't want to freeze a
274 	 * critical application like su(1) or sshd(8).
275 	 *
276 	 * Otherwise, we address case #2 by repeatedly retrying the
277 	 * send() to give syslogd a chance to empty its socket buffer.
278 	 */
279 
280 	if (send(LogFile, tbuf, cnt, 0) < 0) {
281 		if (errno != ENOBUFS) {
282 			/*
283 			 * Scenario 1: syslogd was restarted
284 			 * reconnect and resend once
285 			 */
286 			disconnectlog();
287 			connectlog();
288 			if (send(LogFile, tbuf, cnt, 0) >= 0) {
289 				THREAD_UNLOCK();
290 				return;
291 			}
292 			/*
293 			 * if the resend failed, fall through to
294 			 * possible scenario 2
295 			 */
296 		}
297 		while (errno == ENOBUFS) {
298 			/*
299 			 * Scenario 2: out of socket buffer space
300 			 * possible DoS, fail fast on a privileged
301 			 * socket
302 			 */
303 			if (status == CONNPRIV)
304 				break;
305 			_usleep(1);
306 			if (send(LogFile, tbuf, cnt, 0) >= 0) {
307 				THREAD_UNLOCK();
308 				return;
309 			}
310 		}
311 	} else {
312 		THREAD_UNLOCK();
313 		return;
314 	}
315 
316 	/*
317 	 * Output the message to the console; try not to block
318 	 * as a blocking console should not stop other processes.
319 	 * Make sure the error reported is the one from the syslogd failure.
320 	 */
321 	if (LogStat & LOG_CONS &&
322 	    (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >=
323 	    0) {
324 		struct iovec iov[2];
325 		struct iovec *v = iov;
326 
327 		p = strchr(tbuf, '>') + 1;
328 		v->iov_base = p;
329 		v->iov_len = cnt - (p - tbuf);
330 		++v;
331 		v->iov_base = "\r\n";
332 		v->iov_len = 2;
333 		(void)_writev(fd, iov, 2);
334 		(void)_close(fd);
335 	}
336 
337 	THREAD_UNLOCK();
338 }
339 
340 /* Should be called with mutex acquired */
341 static void
342 disconnectlog(void)
343 {
344 	/*
345 	 * If the user closed the FD and opened another in the same slot,
346 	 * that's their problem.  They should close it before calling on
347 	 * system services.
348 	 */
349 	if (LogFile != -1) {
350 		_close(LogFile);
351 		LogFile = -1;
352 	}
353 	status = NOCONN;			/* retry connect */
354 }
355 
356 /* Should be called with mutex acquired */
357 static void
358 connectlog(void)
359 {
360 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
361 
362 	if (LogFile == -1) {
363 		if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
364 		    0)) == -1)
365 			return;
366 	}
367 	if (LogFile != -1 && status == NOCONN) {
368 		SyslogAddr.sun_len = sizeof(SyslogAddr);
369 		SyslogAddr.sun_family = AF_UNIX;
370 
371 		/*
372 		 * First try privileged socket. If no success,
373 		 * then try default socket.
374 		 */
375 		(void)strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
376 		    sizeof SyslogAddr.sun_path);
377 		if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
378 		    sizeof(SyslogAddr)) != -1)
379 			status = CONNPRIV;
380 
381 		if (status == NOCONN) {
382 			(void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
383 			    sizeof SyslogAddr.sun_path);
384 			if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
385 			    sizeof(SyslogAddr)) != -1)
386 				status = CONNDEF;
387 		}
388 
389 		if (status == NOCONN) {
390 			/*
391 			 * Try the old "/dev/log" path, for backward
392 			 * compatibility.
393 			 */
394 			(void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
395 			    sizeof SyslogAddr.sun_path);
396 			if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
397 			    sizeof(SyslogAddr)) != -1)
398 				status = CONNDEF;
399 		}
400 
401 		if (status == NOCONN) {
402 			(void)_close(LogFile);
403 			LogFile = -1;
404 		}
405 	}
406 }
407 
408 static void
409 openlog_unlocked(const char *ident, int logstat, int logfac)
410 {
411 	if (ident != NULL)
412 		LogTag = ident;
413 	LogStat = logstat;
414 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
415 		LogFacility = logfac;
416 
417 	if (LogStat & LOG_NDELAY)	/* open immediately */
418 		connectlog();
419 
420 	opened = 1;	/* ident and facility has been set */
421 }
422 
423 void
424 openlog(const char *ident, int logstat, int logfac)
425 {
426 	THREAD_LOCK();
427 	openlog_unlocked(ident, logstat, logfac);
428 	THREAD_UNLOCK();
429 }
430 
431 
432 void
433 closelog(void)
434 {
435 	THREAD_LOCK();
436 	if (LogFile != -1) {
437 		(void)_close(LogFile);
438 		LogFile = -1;
439 	}
440 	LogTag = NULL;
441 	status = NOCONN;
442 	THREAD_UNLOCK();
443 }
444 
445 /* setlogmask -- set the log mask level */
446 int
447 setlogmask(int pmask)
448 {
449 	int omask;
450 
451 	THREAD_LOCK();
452 	omask = LogMask;
453 	if (pmask != 0)
454 		LogMask = pmask;
455 	THREAD_UNLOCK();
456 	return (omask);
457 }
458