xref: /netbsd-src/lib/libc/gen/syslog.c (revision aad9773e38ed2370a628a6416e098f9008fc10a7)
1 /*	$NetBSD: syslog.c,v 1.54 2014/09/18 13:58:20 christos Exp $	*/
2 
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 #if defined(LIBC_SCCS) && !defined(lint)
34 #if 0
35 static char sccsid[] = "@(#)syslog.c	8.5 (Berkeley) 4/29/95";
36 #else
37 __RCSID("$NetBSD: syslog.c,v 1.54 2014/09/18 13:58:20 christos Exp $");
38 #endif
39 #endif /* LIBC_SCCS and not lint */
40 
41 #include "namespace.h"
42 #include <sys/types.h>
43 #include <sys/param.h>
44 #include <sys/socket.h>
45 #include <sys/syslog.h>
46 #include <sys/uio.h>
47 #include <sys/un.h>
48 #include <netdb.h>
49 
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <paths.h>
53 #include <stdarg.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58 #include <unistd.h>
59 #include "reentrant.h"
60 #include "extern.h"
61 
62 #ifdef __weak_alias
63 __weak_alias(closelog,_closelog)
64 __weak_alias(openlog,_openlog)
65 __weak_alias(setlogmask,_setlogmask)
66 __weak_alias(syslog,_syslog)
67 __weak_alias(vsyslog,_vsyslog)
68 __weak_alias(syslogp,_syslogp)
69 __weak_alias(vsyslogp,_vsyslogp)
70 #endif
71 
72 static struct syslog_data sdata = SYSLOG_DATA_INIT;
73 
74 static void	openlog_unlocked_r(const char *, int, int,
75     struct syslog_data *);
76 static void	disconnectlog_r(struct syslog_data *);
77 static void	connectlog_r(struct syslog_data *);
78 
79 #define LOG_SIGNAL_SAFE	(int)0x80000000
80 
81 
82 #ifdef _REENTRANT
83 static mutex_t	syslog_mutex = MUTEX_INITIALIZER;
84 #endif
85 
86 /*
87  * syslog, vsyslog --
88  *	print message on log file; output is intended for syslogd(8).
89  */
90 void
91 syslog(int pri, const char *fmt, ...)
92 {
93 	va_list ap;
94 
95 	va_start(ap, fmt);
96 	vsyslog(pri, fmt, ap);
97 	va_end(ap);
98 }
99 
100 void
101 vsyslog(int pri, const char *fmt, va_list ap)
102 {
103 	vsyslog_r(pri, &sdata, fmt, ap);
104 }
105 
106 /*
107  * syslogp, vsyslogp --
108  *	like syslog but take additional arguments for MSGID and SD
109  */
110 void
111 syslogp(int pri, const char *msgid, const char *sdfmt, const char *msgfmt, ...)
112 {
113 	va_list ap;
114 
115 	va_start(ap, msgfmt);
116 	vsyslogp(pri, msgid, sdfmt, msgfmt, ap);
117 	va_end(ap);
118 }
119 
120 void
121 vsyslogp(int pri, const char *msgid, const char *sdfmt, const char *msgfmt, va_list ap)
122 {
123 	vsyslogp_r(pri, &sdata, msgid, sdfmt, msgfmt, ap);
124 }
125 
126 void
127 openlog(const char *ident, int logstat, int logfac)
128 {
129 	openlog_r(ident, logstat, logfac, &sdata);
130 }
131 
132 void
133 closelog(void)
134 {
135 	closelog_r(&sdata);
136 }
137 
138 /* setlogmask -- set the log mask level */
139 int
140 setlogmask(int pmask)
141 {
142 	return setlogmask_r(pmask, &sdata);
143 }
144 
145 /* Reentrant version of syslog, i.e. syslog_r() */
146 
147 void
148 syslog_r(int pri, struct syslog_data *data, const char *fmt, ...)
149 {
150 	va_list ap;
151 
152 	va_start(ap, fmt);
153 	vsyslog_r(pri, data, fmt, ap);
154 	va_end(ap);
155 }
156 
157 void
158 syslogp_r(int pri, struct syslog_data *data, const char *msgid,
159 	const char *sdfmt, const char *msgfmt, ...)
160 {
161 	va_list ap;
162 
163 	va_start(ap, msgfmt);
164 	vsyslogp_r(pri, data, msgid, sdfmt, msgfmt, ap);
165 	va_end(ap);
166 }
167 
168 void
169 syslog_ss(int pri, struct syslog_data *data, const char *fmt, ...)
170 {
171 	va_list ap;
172 
173 	va_start(ap, fmt);
174 	vsyslog_r(pri | LOG_SIGNAL_SAFE, data, fmt, ap);
175 	va_end(ap);
176 }
177 
178 void
179 syslogp_ss(int pri, struct syslog_data *data, const char *msgid,
180 	const char *sdfmt, const char *msgfmt, ...)
181 {
182 	va_list ap;
183 
184 	va_start(ap, msgfmt);
185 	vsyslogp_r(pri | LOG_SIGNAL_SAFE, data, msgid, sdfmt, msgfmt, ap);
186 	va_end(ap);
187 }
188 
189 void
190 vsyslog_ss(int pri, struct syslog_data *data, const char *fmt, va_list ap)
191 {
192 	vsyslog_r(pri | LOG_SIGNAL_SAFE, data, fmt, ap);
193 }
194 
195 void
196 vsyslogp_ss(int pri, struct syslog_data *data, const char *msgid,
197 	const char *sdfmt, const char *msgfmt, va_list ap)
198 {
199 	vsyslogp_r(pri | LOG_SIGNAL_SAFE, data, msgid, sdfmt, msgfmt, ap);
200 }
201 
202 
203 void
204 vsyslog_r(int pri, struct syslog_data *data, const char *fmt, va_list ap)
205 {
206 	vsyslogp_r(pri, data, NULL, NULL, fmt, ap);
207 }
208 
209 void
210 vsyslogp_r(int pri, struct syslog_data *data, const char *msgid,
211 	const char *sdfmt, const char *msgfmt, va_list ap)
212 {
213 	static const char BRCOSP[] = "]: ";
214 	static const char CRLF[] = "\r\n";
215 	size_t cnt, prlen, tries;
216 	char ch, *p, *t;
217 	struct timeval tv;
218 	struct tm tmnow;
219 	time_t now;
220 	int fd, saved_errno;
221 #define TBUF_LEN	2048
222 #define FMT_LEN		1024
223 #define MAXTRIES	10
224 	char tbuf[TBUF_LEN], fmt_cpy[FMT_LEN], fmt_cat[FMT_LEN] = "";
225 	size_t tbuf_left, fmt_left, msgsdlen;
226 	char *fmt = fmt_cat;
227 	int signal_safe = pri & LOG_SIGNAL_SAFE;
228 	struct iovec iov[7];	/* prog + [ + pid + ]: + fmt + crlf */
229 	int opened, iovcnt;
230 
231 	pri &= ~LOG_SIGNAL_SAFE;
232 
233 #define INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
234 	/* Check for invalid bits. */
235 	if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
236 		syslog_r(INTERNALLOG | signal_safe, data,
237 		    "syslog_r: unknown facility/priority: %x", pri);
238 		pri &= LOG_PRIMASK|LOG_FACMASK;
239 	}
240 
241 	/* Check priority against setlogmask values. */
242 	if (!(LOG_MASK(LOG_PRI(pri)) & data->log_mask))
243 		return;
244 
245 	saved_errno = errno;
246 
247 	/* Set default facility if none specified. */
248 	if ((pri & LOG_FACMASK) == 0)
249 		pri |= data->log_fac;
250 
251 	/* Build the message. */
252 	p = tbuf;
253 	tbuf_left = TBUF_LEN;
254 
255 #define DEC()							\
256 	do {							\
257 		if (prlen >= tbuf_left)				\
258 			prlen = tbuf_left - 1;			\
259 		p += prlen;					\
260 		tbuf_left -= prlen;				\
261 	} while (/*CONSTCOND*/0)
262 
263 	prlen = snprintf_ss(p, tbuf_left, "<%d>1 ", pri);
264 	DEC();
265 
266 	if (!signal_safe && (gettimeofday(&tv, NULL) != -1)) {
267 		/* strftime() implies tzset(), localtime_r() doesn't. */
268 		tzset();
269 		now = (time_t) tv.tv_sec;
270 		localtime_r(&now, &tmnow);
271 
272 		prlen = strftime(p, tbuf_left, "%FT%T", &tmnow);
273 		DEC();
274 		prlen = snprintf(p, tbuf_left, ".%06ld", (long)tv.tv_usec);
275 		DEC();
276 		prlen = strftime(p, tbuf_left-1, "%z", &tmnow);
277 		/* strftime gives eg. "+0200", but we need "+02:00" */
278 		if (prlen == 5) {
279 			p[prlen+1] = p[prlen];
280 			p[prlen]   = p[prlen-1];
281 			p[prlen-1] = p[prlen-2];
282 			p[prlen-2] = ':';
283 			prlen += 1;
284 		}
285 	} else {
286 		prlen = snprintf_ss(p, tbuf_left, "-");
287 #if 0
288 		/*
289 		 * if gmtime_r() was signal-safe we could output
290 		 * the UTC-time:
291 		 */
292 		gmtime_r(&now, &tmnow);
293 		prlen = strftime(p, tbuf_left, "%FT%TZ", &tmnow);
294 #endif
295 	}
296 
297 	if (data == &sdata)
298 		mutex_lock(&syslog_mutex);
299 
300 	if (data->log_hostname[0] == '\0' && gethostname(data->log_hostname,
301 	    sizeof(data->log_hostname)) == -1) {
302 		/* can this really happen? */
303 		data->log_hostname[0] = '-';
304 		data->log_hostname[1] = '\0';
305 	}
306 
307 	DEC();
308 	prlen = snprintf_ss(p, tbuf_left, " %s ", data->log_hostname);
309 
310 	if (data->log_tag == NULL)
311 		data->log_tag = getprogname();
312 
313 	DEC();
314 	prlen = snprintf_ss(p, tbuf_left, "%s ",
315 	    data->log_tag ? data->log_tag : "-");
316 
317 	if (data == &sdata)
318 		mutex_unlock(&syslog_mutex);
319 
320 	if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
321 		iovcnt = 0;
322 		iov[iovcnt].iov_base = p;
323 		iov[iovcnt].iov_len = prlen - 1;
324 		iovcnt++;
325 	}
326 	DEC();
327 
328 	if (data->log_stat & LOG_PID) {
329 		prlen = snprintf_ss(p, tbuf_left, "%d ", getpid());
330 		if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
331 			iov[iovcnt].iov_base = __UNCONST("[");
332 			iov[iovcnt].iov_len = 1;
333 			iovcnt++;
334 			iov[iovcnt].iov_base = p;
335 			iov[iovcnt].iov_len = prlen - 1;
336 			iovcnt++;
337 			iov[iovcnt].iov_base = __UNCONST(BRCOSP);
338 			iov[iovcnt].iov_len = 3;
339 			iovcnt++;
340 		}
341 	} else {
342 		prlen = snprintf_ss(p, tbuf_left, "- ");
343 		if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
344 			iov[iovcnt].iov_base = __UNCONST(BRCOSP + 1);
345 			iov[iovcnt].iov_len = 2;
346 			iovcnt++;
347 		}
348 	}
349 	DEC();
350 
351 	/*
352 	 * concat the format strings, then use one vsnprintf()
353 	 */
354 	if (msgid != NULL && *msgid != '\0') {
355 		strlcat(fmt_cat, msgid, FMT_LEN);
356 		strlcat(fmt_cat, " ", FMT_LEN);
357 	} else
358 		strlcat(fmt_cat, "- ", FMT_LEN);
359 
360 	if (sdfmt != NULL && *sdfmt != '\0') {
361 		strlcat(fmt_cat, sdfmt, FMT_LEN);
362 	} else
363 		strlcat(fmt_cat, "-", FMT_LEN);
364 
365 	if (data->log_stat & (LOG_PERROR|LOG_CONS))
366 		msgsdlen = strlen(fmt_cat) + 1;
367 	else
368 		msgsdlen = 0;	/* XXX: GCC */
369 
370 	if (msgfmt != NULL && *msgfmt != '\0') {
371 		strlcat(fmt_cat, " ", FMT_LEN);
372 		strlcat(fmt_cat, msgfmt, FMT_LEN);
373 	}
374 
375 	/*
376 	 * We wouldn't need this mess if printf handled %m, or if
377 	 * strerror() had been invented before syslog().
378 	 */
379 	for (t = fmt_cpy, fmt_left = FMT_LEN; (ch = *fmt) != '\0'; ++fmt) {
380 		if (ch == '%' && fmt[1] == 'm') {
381 			char ebuf[128];
382 			++fmt;
383 			if (signal_safe ||
384 			    strerror_r(saved_errno, ebuf, sizeof(ebuf)))
385 				prlen = snprintf_ss(t, fmt_left, "Error %d",
386 				    saved_errno);
387 			else
388 				prlen = snprintf_ss(t, fmt_left, "%s", ebuf);
389 			if (prlen >= fmt_left)
390 				prlen = fmt_left - 1;
391 			t += prlen;
392 			fmt_left -= prlen;
393 		} else if (ch == '%' && fmt[1] == '%' && fmt_left > 2) {
394 			*t++ = '%';
395 			*t++ = '%';
396 			fmt++;
397 			fmt_left -= 2;
398 		} else {
399 			if (fmt_left > 1) {
400 				*t++ = ch;
401 				fmt_left--;
402 			}
403 		}
404 	}
405 	*t = '\0';
406 
407 	if (signal_safe)
408 		prlen = vsnprintf_ss(p, tbuf_left, fmt_cpy, ap);
409 	else
410 		prlen = vsnprintf(p, tbuf_left, fmt_cpy, ap);
411 
412 	if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
413 		iov[iovcnt].iov_base = p + msgsdlen;
414 		iov[iovcnt].iov_len = prlen - msgsdlen;
415 		iovcnt++;
416 	}
417 
418 	DEC();
419 	cnt = p - tbuf;
420 
421 	/* Output to stderr if requested. */
422 	if (data->log_stat & LOG_PERROR) {
423 		iov[iovcnt].iov_base = __UNCONST(CRLF + 1);
424 		iov[iovcnt].iov_len = 1;
425 		(void)writev(STDERR_FILENO, iov, iovcnt + 1);
426 	}
427 
428 	/* Get connected, output the message to the local logger. */
429 	if (data == &sdata)
430 		mutex_lock(&syslog_mutex);
431 	opened = !data->log_opened;
432 	if (opened)
433 		openlog_unlocked_r(data->log_tag, data->log_stat, 0, data);
434 	connectlog_r(data);
435 
436 	/*
437 	 * If the send() failed, there are two likely scenarios:
438 	 *  1) syslogd was restarted
439 	 *  2) /dev/log is out of socket buffer space
440 	 * We attempt to reconnect to /dev/log to take care of
441 	 * case #1 and keep send()ing data to cover case #2
442 	 * to give syslogd a chance to empty its socket buffer.
443 	 */
444 	for (tries = 0; tries < MAXTRIES; tries++) {
445 		if (send(data->log_file, tbuf, cnt, 0) != -1)
446 			break;
447 		if (errno != ENOBUFS) {
448 			disconnectlog_r(data);
449 			connectlog_r(data);
450 		} else
451 			(void)usleep(1);
452 	}
453 
454 	/*
455 	 * Output the message to the console; try not to block
456 	 * as a blocking console should not stop other processes.
457 	 * Make sure the error reported is the one from the syslogd failure.
458 	 */
459 	if (tries == MAXTRIES && (data->log_stat & LOG_CONS) &&
460 	    (fd = open(_PATH_CONSOLE,
461 		O_WRONLY | O_NONBLOCK | O_CLOEXEC, 0)) >= 0) {
462 		iov[iovcnt].iov_base = __UNCONST(CRLF);
463 		iov[iovcnt].iov_len = 2;
464 		(void)writev(fd, iov, iovcnt + 1);
465 		(void)close(fd);
466 	}
467 
468 	if (data == &sdata)
469 		mutex_unlock(&syslog_mutex);
470 
471 	if (data != &sdata && opened) {
472 		/* preserve log tag */
473 		const char *ident = data->log_tag;
474 		closelog_r(data);
475 		data->log_tag = ident;
476 	}
477 }
478 
479 static void
480 disconnectlog_r(struct syslog_data *data)
481 {
482 	/*
483 	 * If the user closed the FD and opened another in the same slot,
484 	 * that's their problem.  They should close it before calling on
485 	 * system services.
486 	 */
487 	if (data->log_file != -1) {
488 		(void)close(data->log_file);
489 		data->log_file = -1;
490 	}
491 	data->log_connected = 0;		/* retry connect */
492 }
493 
494 static void
495 connectlog_r(struct syslog_data *data)
496 {
497 	/* AF_UNIX address of local logger */
498 	static const struct sockaddr_un sun = {
499 		.sun_family = AF_LOCAL,
500 		.sun_len = sizeof(sun),
501 		.sun_path = _PATH_LOG,
502 	};
503 
504 	if (data->log_file == -1 || fcntl(data->log_file, F_GETFL, 0) == -1) {
505 		if ((data->log_file = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
506 		    0)) == -1)
507 			return;
508 		data->log_connected = 0;
509 	}
510 	if (!data->log_connected) {
511 		if (connect(data->log_file,
512 		    (const struct sockaddr *)(const void *)&sun,
513 		    (socklen_t)sizeof(sun)) == -1) {
514 			(void)close(data->log_file);
515 			data->log_file = -1;
516 		} else
517 			data->log_connected = 1;
518 	}
519 }
520 
521 static void
522 openlog_unlocked_r(const char *ident, int logstat, int logfac,
523     struct syslog_data *data)
524 {
525 	if (ident != NULL)
526 		data->log_tag = ident;
527 	data->log_stat = logstat;
528 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
529 		data->log_fac = logfac;
530 
531 	if (data->log_stat & LOG_NDELAY)	/* open immediately */
532 		connectlog_r(data);
533 
534 	data->log_opened = 1;
535 }
536 
537 void
538 openlog_r(const char *ident, int logstat, int logfac, struct syslog_data *data)
539 {
540 	if (data == &sdata)
541 		mutex_lock(&syslog_mutex);
542 	openlog_unlocked_r(ident, logstat, logfac, data);
543 	if (data == &sdata)
544 		mutex_unlock(&syslog_mutex);
545 }
546 
547 void
548 closelog_r(struct syslog_data *data)
549 {
550 	if (data == &sdata)
551 		mutex_lock(&syslog_mutex);
552 	(void)close(data->log_file);
553 	data->log_file = -1;
554 	data->log_connected = 0;
555 	data->log_tag = NULL;
556 	if (data == &sdata)
557 		mutex_unlock(&syslog_mutex);
558 }
559 
560 int
561 setlogmask_r(int pmask, struct syslog_data *data)
562 {
563 	int omask;
564 
565 	omask = data->log_mask;
566 	if (pmask != 0)
567 		data->log_mask = pmask;
568 	return omask;
569 }
570