xref: /netbsd-src/lib/libc/gen/syslog.c (revision 5b239d0be1d6682ecf6030411841b40cc91e8b34)
1 /*	$NetBSD: syslog.c,v 1.38 2006/11/05 04:35:35 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.38 2006/11/05 04:35:35 christos Exp $");
38 #endif
39 #endif /* LIBC_SCCS and not lint */
40 
41 #include "namespace.h"
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include <sys/syslog.h>
45 #include <sys/uio.h>
46 #include <sys/un.h>
47 #include <netdb.h>
48 
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <paths.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <time.h>
57 #include <unistd.h>
58 #include "reentrant.h"
59 
60 #ifdef __weak_alias
61 __weak_alias(closelog,_closelog)
62 __weak_alias(openlog,_openlog)
63 __weak_alias(setlogmask,_setlogmask)
64 __weak_alias(syslog,_syslog)
65 __weak_alias(vsyslog,_vsyslog)
66 
67 __weak_alias(closelog_r,_closelog_r)
68 __weak_alias(openlog_r,_openlog_r)
69 __weak_alias(setlogmask_r,_setlogmask_r)
70 __weak_alias(syslog_r,_syslog_r)
71 __weak_alias(vsyslog_r,_vsyslog_r)
72 __weak_alias(syslog_ss,_syslog_ss)
73 __weak_alias(vsyslog_ss,_vsyslog_ss)
74 #endif
75 
76 static struct syslog_data sdata = SYSLOG_DATA_INIT;
77 
78 static void	openlog_unlocked_r(const char *, int, int,
79     struct syslog_data *);
80 static void	disconnectlog_r(struct syslog_data *);
81 static void	connectlog_r(struct syslog_data *);
82 
83 #define LOG_SIGNAL_SAFE	(int)0x80000000
84 
85 
86 #ifdef _REENTRANT
87 static mutex_t	syslog_mutex = MUTEX_INITIALIZER;
88 #endif
89 
90 /*
91  * syslog, vsyslog --
92  *	print message on log file; output is intended for syslogd(8).
93  */
94 void
95 syslog(int pri, const char *fmt, ...)
96 {
97 	va_list ap;
98 
99 	va_start(ap, fmt);
100 	vsyslog(pri, fmt, ap);
101 	va_end(ap);
102 }
103 
104 void
105 vsyslog(int pri, const char *fmt, va_list ap)
106 {
107 	vsyslog_r(pri, &sdata, fmt, ap);
108 }
109 
110 void
111 openlog(const char *ident, int logstat, int logfac)
112 {
113 	openlog_r(ident, logstat, logfac, &sdata);
114 }
115 
116 void
117 closelog(void)
118 {
119 	closelog_r(&sdata);
120 }
121 
122 /* setlogmask -- set the log mask level */
123 int
124 setlogmask(int pmask)
125 {
126 	return setlogmask_r(pmask, &sdata);
127 }
128 
129 /* Reentrant version of syslog, i.e. syslog_r() */
130 
131 void
132 syslog_r(int pri, struct syslog_data *data, const char *fmt, ...)
133 {
134 	va_list ap;
135 
136 	va_start(ap, fmt);
137 	vsyslog_r(pri, data, fmt, ap);
138 	va_end(ap);
139 }
140 
141 void
142 syslog_ss(int pri, struct syslog_data *data, const char *fmt, ...)
143 {
144 	va_list ap;
145 
146 	va_start(ap, fmt);
147 	vsyslog_r(pri | LOG_SIGNAL_SAFE, data, fmt, ap);
148 	va_end(ap);
149 }
150 
151 void
152 vsyslog_ss(int pri, struct syslog_data *data, const char *fmt, va_list ap)
153 {
154 	vsyslog_r(pri | LOG_SIGNAL_SAFE, data, fmt, ap);
155 }
156 
157 void
158 vsyslog_r(int pri, struct syslog_data *data, const char *fmt, va_list ap)
159 {
160 	size_t cnt, prlen;
161 	char ch, *p, *t;
162 	time_t now;
163 	struct tm tmnow;
164 	int fd, saved_errno;
165 #define	TBUF_LEN	2048
166 #define	FMT_LEN		1024
167 	char *stdp = NULL;	/* pacify gcc */
168 	char tbuf[TBUF_LEN], fmt_cpy[FMT_LEN];
169 	size_t tbuf_left, fmt_left;
170 	int signal_safe = pri & LOG_SIGNAL_SAFE;
171 
172 	pri &= ~LOG_SIGNAL_SAFE;
173 
174 #define	INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
175 	/* Check for invalid bits. */
176 	if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
177 		syslog_r(INTERNALLOG | signal_safe, data,
178 		    "syslog_r: unknown facility/priority: %x", pri);
179 		pri &= LOG_PRIMASK|LOG_FACMASK;
180 	}
181 
182 	/* Check priority against setlogmask values. */
183 	if (!(LOG_MASK(LOG_PRI(pri)) & data->log_mask))
184 		return;
185 
186 	saved_errno = errno;
187 
188 	/* Set default facility if none specified. */
189 	if ((pri & LOG_FACMASK) == 0)
190 		pri |= data->log_fac;
191 
192 	/* Build the message. */
193 
194 	/*
195  	 * Although it's tempting, we can't ignore the possibility of
196 	 * overflowing the buffer when assembling the "fixed" portion
197 	 * of the message.  Strftime's "%h" directive expands to the
198 	 * locale's abbreviated month name, but if the user has the
199 	 * ability to construct to his own locale files, it may be
200 	 * arbitrarily long.
201 	 */
202 	 if (!signal_safe)
203 		(void)time(&now);
204 
205 	p = tbuf;
206 	tbuf_left = TBUF_LEN;
207 
208 #define	DEC()							\
209 	do {							\
210 		if (prlen >= tbuf_left)				\
211 			prlen = tbuf_left - 1;			\
212 		p += prlen;					\
213 		tbuf_left -= prlen;				\
214 	} while (/*CONSTCOND*/0)
215 
216 	prlen = snprintf_ss(p, tbuf_left, "<%d>", pri);
217 	DEC();
218 
219 	if (!signal_safe) {
220 		/* strftime() implies tzset(), localtime_r() doesn't. */
221 		tzset();
222 		prlen = strftime(p, tbuf_left, "%h %e %T ",
223 		    localtime_r(&now, &tmnow));
224 		DEC();
225 	}
226 
227 	if (data->log_stat & LOG_PERROR)
228 		stdp = p;
229 	if (data->log_tag == NULL)
230 		data->log_tag = getprogname();
231 	if (data->log_tag != NULL) {
232 		prlen = snprintf_ss(p, tbuf_left, "%s", data->log_tag);
233 		DEC();
234 	}
235 	if (data->log_stat & LOG_PID) {
236 		prlen = snprintf_ss(p, tbuf_left, "[%d]", getpid());
237 		DEC();
238 	}
239 	if (data->log_tag != NULL) {
240 		if (tbuf_left > 1) {
241 			*p++ = ':';
242 			tbuf_left--;
243 		}
244 		if (tbuf_left > 1) {
245 			*p++ = ' ';
246 			tbuf_left--;
247 		}
248 	}
249 
250 	/*
251 	 * We wouldn't need this mess if printf handled %m, or if
252 	 * strerror() had been invented before syslog().
253 	 */
254 	for (t = fmt_cpy, fmt_left = FMT_LEN; (ch = *fmt) != '\0'; ++fmt) {
255 		if (ch == '%' && fmt[1] == 'm') {
256 			char ebuf[128];
257 			++fmt;
258 			if (signal_safe ||
259 			    strerror_r(saved_errno, ebuf, sizeof(ebuf)))
260 				prlen = snprintf_ss(t, fmt_left, "Error %d",
261 				    saved_errno);
262 			else
263 				prlen = snprintf_ss(t, fmt_left, "%s", ebuf);
264 			if (prlen >= fmt_left)
265 				prlen = fmt_left - 1;
266 			t += prlen;
267 			fmt_left -= prlen;
268 		} else if (ch == '%' && fmt[1] == '%' && fmt_left > 2) {
269 			*t++ = '%';
270 			*t++ = '%';
271 			fmt++;
272 			fmt_left -= 2;
273 		} else {
274 			if (fmt_left > 1) {
275 				*t++ = ch;
276 				fmt_left--;
277 			}
278 		}
279 	}
280 	*t = '\0';
281 
282 	if (signal_safe)
283 		prlen = vsnprintf_ss(p, tbuf_left, fmt_cpy, ap);
284 	else
285 		prlen = vsnprintf(p, tbuf_left, fmt_cpy, ap);
286 	DEC();
287 	cnt = p - tbuf;
288 
289 	/* Output to stderr if requested. */
290 	if (data->log_stat & LOG_PERROR) {
291 		struct iovec iov[2];
292 
293 		iov[0].iov_base = stdp;
294 		iov[0].iov_len = cnt - (stdp - tbuf);
295 		iov[1].iov_base = __UNCONST("\n");
296 		iov[1].iov_len = 1;
297 		(void)writev(STDERR_FILENO, iov, 2);
298 	}
299 
300 	/* Get connected, output the message to the local logger. */
301 	if (data == &sdata)
302 		mutex_lock(&syslog_mutex);
303 	if (!data->opened)
304 		openlog_unlocked_r(data->log_tag, data->log_stat, 0, data);
305 	connectlog_r(data);
306 
307 	/*
308 	 * If the send() failed, there are two likely scenarios:
309 	 *  1) syslogd was restarted
310 	 *  2) /dev/log is out of socket buffer space
311 	 * We attempt to reconnect to /dev/log to take care of
312 	 * case #1 and keep send()ing data to cover case #2
313 	 * to give syslogd a chance to empty its socket buffer.
314 	 */
315 	if (send(data->log_file, tbuf, cnt, 0) == -1) {
316 		if (errno != ENOBUFS) {
317 			disconnectlog_r(data);
318 			connectlog_r(data);
319 		}
320 		do {
321 			usleep(1);
322 			if (send(data->log_file, tbuf, cnt, 0) != -1)
323 				break;
324 		} while (errno == ENOBUFS);
325 	}
326 	if (data == &sdata)
327 		mutex_unlock(&syslog_mutex);
328 
329 	/*
330 	 * Output the message to the console; try not to block
331 	 * as a blocking console should not stop other processes.
332 	 * Make sure the error reported is the one from the syslogd failure.
333 	 */
334 	if ((data->log_stat & LOG_CONS) &&
335 	    (fd = open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) {
336 		struct iovec iov[2];
337 
338 		p = strchr(tbuf, '>') + 1;
339 		iov[0].iov_base = p;
340 		iov[0].iov_len = cnt - (p - tbuf);
341 		iov[1].iov_base = __UNCONST("\r\n");
342 		iov[1].iov_len = 2;
343 		(void)writev(fd, iov, 2);
344 		(void)close(fd);
345 	}
346 	if (data != &sdata)
347 		closelog_r(data);
348 }
349 
350 static void
351 disconnectlog_r(struct syslog_data *data)
352 {
353 	/*
354 	 * If the user closed the FD and opened another in the same slot,
355 	 * that's their problem.  They should close it before calling on
356 	 * system services.
357 	 */
358 	if (data->log_file != -1) {
359 		(void)close(data->log_file);
360 		data->log_file = -1;
361 	}
362 	data->connected = 0;		/* retry connect */
363 }
364 
365 static void
366 connectlog_r(struct syslog_data *data)
367 {
368 	/* AF_UNIX address of local logger */
369 	static const struct sockaddr_un sun = {
370 		.sun_family = AF_LOCAL,
371 		.sun_len = sizeof(sun),
372 		.sun_path = _PATH_LOG,
373 	};
374 
375 	if (data->log_file == -1 || fcntl(data->log_file, F_GETFL, 0) == -1) {
376 		if ((data->log_file = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
377 			return;
378 		(void)fcntl(data->log_file, F_SETFD, FD_CLOEXEC);
379 		data->connected = 0;
380 	}
381 	if (!data->connected) {
382 		if (connect(data->log_file,
383 		    (const struct sockaddr *)(const void *)&sun,
384 		    sizeof(sun)) == -1) {
385 			(void)close(data->log_file);
386 			data->log_file = -1;
387  		} else
388 			data->connected = 1;
389 	}
390 }
391 
392 static void
393 openlog_unlocked_r(const char *ident, int logstat, int logfac,
394     struct syslog_data *data)
395 {
396 	if (ident != NULL)
397 		data->log_tag = ident;
398 	data->log_stat = logstat;
399 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
400 		data->log_fac = logfac;
401 
402 	if (data->log_stat & LOG_NDELAY)	/* open immediately */
403 		connectlog_r(data);
404 }
405 
406 void
407 openlog_r(const char *ident, int logstat, int logfac, struct syslog_data *data)
408 {
409 	if (data == &sdata)
410 		mutex_lock(&syslog_mutex);
411 	openlog_unlocked_r(ident, logstat, logfac, data);
412 	if (data == &sdata)
413 		mutex_unlock(&syslog_mutex);
414 }
415 
416 void
417 closelog_r(struct syslog_data *data)
418 {
419 	if (data == &sdata)
420 		mutex_lock(&syslog_mutex);
421 	(void)close(data->log_file);
422 	data->log_file = -1;
423 	data->connected = 0;
424 	data->log_tag = NULL;
425 	if (data == &sdata)
426 		mutex_unlock(&syslog_mutex);
427 }
428 
429 int
430 setlogmask_r(int pmask, struct syslog_data *data)
431 {
432 	int omask;
433 
434 	omask = data->log_mask;
435 	if (pmask != 0)
436 		data->log_mask = pmask;
437 	return omask;
438 }
439