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