xref: /freebsd/lib/libc/gen/syslog.c (revision 397e83df75e0fcd0d3fcb95ae4d794cb7600fc89)
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 "namespace.h"
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/syslog.h>
36 #include <sys/time.h>
37 #include <sys/uio.h>
38 #include <sys/un.h>
39 #include <netdb.h>
40 
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <paths.h>
44 #include <pthread.h>
45 #include <stdbool.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <time.h>
50 #include <unistd.h>
51 
52 #include <stdarg.h>
53 #include "un-namespace.h"
54 
55 #include "libc_private.h"
56 
57 /* Maximum number of characters of syslog message */
58 #define	MAXLINE		8192
59 
60 static int	LogFile = -1;		/* fd for log */
61 static bool	connected;		/* have done connect */
62 static int	opened;			/* have done openlog() */
63 static int	LogStat = 0;		/* status bits, set by openlog() */
64 static pid_t	LogPid = -1;		/* process id to tag the entry with */
65 static const char *LogTag = NULL;	/* string to tag the entry with */
66 static int	LogTagLength = -1;	/* usable part of LogTag */
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 /* RFC5424 defined value. */
81 #define NILVALUE "-"
82 
83 static void	disconnectlog(void); /* disconnect from syslogd */
84 static void	connectlog(void);	/* (re)connect to syslogd */
85 static void	openlog_unlocked(const char *, int, int);
86 static void	parse_tag(void);	/* parse ident[NNN] if needed */
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[MAXLINE], fmt_cpy[MAXLINE],
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)fputs(NILVALUE " ", fp);
194 	/* Hostname. */
195 	(void)gethostname(hostname, sizeof(hostname));
196 	(void)fprintf(fp, "%s ",
197 	    hostname[0] == '\0' ? NILVALUE : hostname);
198 	if (LogStat & LOG_PERROR) {
199 		/* Transfer to string buffer */
200 		(void)fflush(fp);
201 		stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
202 	}
203 	/* Application name. */
204 	if (LogTag == NULL)
205 		LogTag = _getprogname();
206 	else if (LogTagLength == -1)
207 		parse_tag();
208 	if (LogTagLength > 0)
209 		(void)fprintf(fp, "%.*s ", LogTagLength, LogTag);
210 	else
211 		(void)fprintf(fp, "%s ", LogTag == NULL ? NILVALUE : LogTag);
212 	/*
213 	 * Provide the process ID regardless of whether LOG_PID has been
214 	 * specified, as it provides valuable information. Many
215 	 * applications tend not to use this, even though they should.
216 	 */
217 	if (LogTagLength <= 0)
218 		LogPid = getpid();
219 	(void)fprintf(fp, "%d ", (int)LogPid);
220 	/* Message ID. */
221 	(void)fputs(NILVALUE " ", fp);
222 	/* Structured data. */
223 	(void)fputs(NILVALUE " ", fp);
224 
225 	/* Check to see if we can skip expanding the %m */
226 	if (strstr(fmt, "%m")) {
227 
228 		/* Create the second stdio hook */
229 		fmt_cookie.base = fmt_cpy;
230 		fmt_cookie.left = sizeof(fmt_cpy) - 1;
231 		fmt_fp = fwopen(&fmt_cookie, writehook);
232 		if (fmt_fp == NULL) {
233 			fclose(fp);
234 			return;
235 		}
236 
237 		/*
238 		 * Substitute error message for %m.  Be careful not to
239 		 * molest an escaped percent "%%m".  We want to pass it
240 		 * on untouched as the format is later parsed by vfprintf.
241 		 */
242 		for ( ; (ch = *fmt); ++fmt) {
243 			if (ch == '%' && fmt[1] == 'm') {
244 				++fmt;
245 				strerror_r(saved_errno, errstr, sizeof(errstr));
246 				fputs(errstr, fmt_fp);
247 			} else if (ch == '%' && fmt[1] == '%') {
248 				++fmt;
249 				fputc(ch, fmt_fp);
250 				fputc(ch, fmt_fp);
251 			} else {
252 				fputc(ch, fmt_fp);
253 			}
254 		}
255 
256 		/* Null terminate if room */
257 		fputc(0, fmt_fp);
258 		fclose(fmt_fp);
259 
260 		/* Guarantee null termination */
261 		fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
262 
263 		fmt = fmt_cpy;
264 	}
265 
266 	/* Message. */
267 	(void)vfprintf(fp, fmt, ap);
268 	(void)fclose(fp);
269 
270 	cnt = sizeof(tbuf) - tbuf_cookie.left;
271 
272 	/* Remove a trailing newline */
273 	if (tbuf[cnt - 1] == '\n')
274 		cnt--;
275 
276 	/* Output to stderr if requested. */
277 	if (LogStat & LOG_PERROR) {
278 		struct iovec iov[2];
279 		struct iovec *v = iov;
280 
281 		v->iov_base = stdp;
282 		v->iov_len = cnt - (stdp - tbuf);
283 		++v;
284 		v->iov_base = "\n";
285 		v->iov_len = 1;
286 		(void)_writev(STDERR_FILENO, iov, 2);
287 	}
288 
289 	/* Get connected, output the message to the local logger. */
290 	if (!opened)
291 		openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
292 	connectlog();
293 
294 	/*
295 	 * If the send() failed, there are two likely scenarios:
296 	 * 1) syslogd was restarted.  In this case make one (only) attempt
297 	 *    to reconnect.
298 	 * 2) We filled our buffer due to syslogd not being able to read
299 	 *    as fast as we write.  In this case prefer to lose the current
300 	 *    message rather than whole buffer of previously logged data.
301 	 */
302 	if (send(LogFile, tbuf, cnt, 0) < 0) {
303 		if (errno != ENOBUFS) {
304 			disconnectlog();
305 			connectlog();
306 			if (send(LogFile, tbuf, cnt, 0) >= 0)
307 				return;
308 		}
309 	} else
310 		return;
311 
312 	/*
313 	 * Output the message to the console; try not to block
314 	 * as a blocking console should not stop other processes.
315 	 * Make sure the error reported is the one from the syslogd failure.
316 	 */
317 	if (LogStat & LOG_CONS &&
318 	    (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >=
319 	    0) {
320 		struct iovec iov[2];
321 		struct iovec *v = iov;
322 
323 		p = strchr(tbuf, '>') + 3;
324 		v->iov_base = p;
325 		v->iov_len = cnt - (p - tbuf);
326 		++v;
327 		v->iov_base = "\r\n";
328 		v->iov_len = 2;
329 		(void)_writev(fd, iov, 2);
330 		(void)_close(fd);
331 	}
332 }
333 
334 static void
335 syslog_cancel_cleanup(void *arg __unused)
336 {
337 
338 	THREAD_UNLOCK();
339 }
340 
341 void
342 vsyslog(int pri, const char *fmt, va_list ap)
343 {
344 
345 	THREAD_LOCK();
346 	pthread_cleanup_push(syslog_cancel_cleanup, NULL);
347 	vsyslog1(pri, fmt, ap);
348 	pthread_cleanup_pop(1);
349 }
350 
351 /* Should be called with mutex acquired */
352 static void
353 disconnectlog(void)
354 {
355 	/*
356 	 * If the user closed the FD and opened another in the same slot,
357 	 * that's their problem.  They should close it before calling on
358 	 * system services.
359 	 */
360 	if (LogFile != -1) {
361 		_close(LogFile);
362 		LogFile = -1;
363 	}
364 	connected = false;			/* retry connect */
365 }
366 
367 /* Should be called with mutex acquired */
368 static void
369 connectlog(void)
370 {
371 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
372 
373 	if (LogFile == -1) {
374 		socklen_t len;
375 
376 		if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
377 		    0)) == -1)
378 			return;
379 		if (_getsockopt(LogFile, SOL_SOCKET, SO_SNDBUF, &len,
380 		    &(socklen_t){sizeof(len)}) == 0) {
381 			if (len < MAXLINE) {
382 				len = MAXLINE;
383 				(void)_setsockopt(LogFile, SOL_SOCKET, SO_SNDBUF,
384 				    &len, sizeof(len));
385 			}
386 		}
387 	}
388 	if (!connected) {
389 		SyslogAddr.sun_len = sizeof(SyslogAddr);
390 		SyslogAddr.sun_family = AF_UNIX;
391 
392 		(void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
393 		    sizeof SyslogAddr.sun_path);
394 		if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
395 		    sizeof(SyslogAddr)) != -1)
396 			connected = true;
397 		else {
398 			(void)_close(LogFile);
399 			LogFile = -1;
400 		}
401 	}
402 }
403 
404 static void
405 openlog_unlocked(const char *ident, int logstat, int logfac)
406 {
407 	if (ident != NULL) {
408 		LogTag = ident;
409 		LogTagLength = -1;
410 	}
411 	LogStat = logstat;
412 	parse_tag();
413 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
414 		LogFacility = logfac;
415 
416 	if (LogStat & LOG_NDELAY)	/* open immediately */
417 		connectlog();
418 
419 	opened = 1;	/* ident and facility has been set */
420 }
421 
422 void
423 openlog(const char *ident, int logstat, int logfac)
424 {
425 
426 	THREAD_LOCK();
427 	pthread_cleanup_push(syslog_cancel_cleanup, NULL);
428 	openlog_unlocked(ident, logstat, logfac);
429 	pthread_cleanup_pop(1);
430 }
431 
432 
433 void
434 closelog(void)
435 {
436 	THREAD_LOCK();
437 	if (LogFile != -1) {
438 		(void)_close(LogFile);
439 		LogFile = -1;
440 	}
441 	LogTag = NULL;
442 	LogTagLength = -1;
443 	connected = false;
444 	THREAD_UNLOCK();
445 }
446 
447 /* setlogmask -- set the log mask level */
448 int
449 setlogmask(int pmask)
450 {
451 	int omask;
452 
453 	THREAD_LOCK();
454 	omask = LogMask;
455 	if (pmask != 0)
456 		LogMask = pmask;
457 	THREAD_UNLOCK();
458 	return (omask);
459 }
460 
461 /*
462  * Obtain LogPid from LogTag formatted as per RFC 3164,
463  * Section 5.3 Originating Process Information:
464  *
465  * ident[NNN]
466  */
467 static void
468 parse_tag(void)
469 {
470 	char *begin, *end, *p;
471 	pid_t pid;
472 
473 	if (LogTag == NULL || (LogStat & LOG_PID) != 0)
474 		return;
475 	/*
476 	 * LogTagLength is -1 if LogTag was not parsed yet.
477 	 * Avoid multiple passes over same LogTag.
478 	 */
479 	LogTagLength = 0;
480 
481 	/* Check for presence of opening [ and non-empty ident. */
482 	if ((begin = strchr(LogTag, '[')) == NULL || begin == LogTag)
483 		return;
484 	/* Check for presence of closing ] at the very end and non-empty pid. */
485 	if ((end = strchr(begin + 1, ']')) == NULL || end[1] != 0 ||
486 	    (end - begin) < 2)
487 		return;
488 
489 	/* Check for pid to contain digits only. */
490 	pid = (pid_t)strtol(begin + 1, &p, 10);
491 	if (p != end)
492 		return;
493 
494 	LogPid = pid;
495 	LogTagLength = begin - LogTag;
496 }
497