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