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