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