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