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