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