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