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