xref: /freebsd/lib/libc/gen/syslog.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
1 /*
2  * Copyright (c) 1983, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #if defined(LIBC_SCCS) && !defined(lint)
35 static char sccsid[] = "@(#)syslog.c	8.5 (Berkeley) 4/29/95";
36 #endif /* LIBC_SCCS and not lint */
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "namespace.h"
41 #include <sys/types.h>
42 #include <sys/socket.h>
43 #include <sys/syslog.h>
44 #include <sys/uio.h>
45 #include <sys/un.h>
46 #include <netdb.h>
47 
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <paths.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <time.h>
55 #include <unistd.h>
56 
57 #include <stdarg.h>
58 #include "un-namespace.h"
59 
60 #include "libc_private.h"
61 
62 static int	LogFile = -1;		/* fd for log */
63 static int	connected;		/* have done connect */
64 static int	opened;			/* have done openlog() */
65 static int	LogStat = 0;		/* status bits, set by openlog() */
66 static const char *LogTag = NULL;	/* string to tag the entry with */
67 static int	LogFacility = LOG_USER;	/* default facility code */
68 static int	LogMask = 0xff;		/* mask of priorities to be logged */
69 
70 static void	disconnectlog(void); /* disconnect from syslogd */
71 static void	connectlog(void);	/* (re)connect to syslogd */
72 
73 /*
74  * Format of the magic cookie passed through the stdio hook
75  */
76 struct bufcookie {
77 	char	*base;	/* start of buffer */
78 	int	left;
79 };
80 
81 /*
82  * stdio write hook for writing to a static string buffer
83  * XXX: Maybe one day, dynamically allocate it so that the line length
84  *      is `unlimited'.
85  */
86 static
87 int writehook(cookie, buf, len)
88 	void	*cookie;	/* really [struct bufcookie *] */
89 	char	*buf;		/* characters to copy */
90 	int	len;		/* length to copy */
91 {
92 	struct bufcookie *h;	/* private `handle' */
93 
94 	h = (struct bufcookie *)cookie;
95 	if (len > h->left) {
96 		/* clip in case of wraparound */
97 		len = h->left;
98 	}
99 	if (len > 0) {
100 		(void)memcpy(h->base, buf, len); /* `write' it. */
101 		h->base += len;
102 		h->left -= len;
103 	}
104 	return 0;
105 }
106 
107 /*
108  * syslog, vsyslog --
109  *	print message on log file; output is intended for syslogd(8).
110  */
111 void
112 syslog(int pri, const char *fmt, ...)
113 {
114 	va_list ap;
115 
116 	va_start(ap, fmt);
117 	vsyslog(pri, fmt, ap);
118 	va_end(ap);
119 }
120 
121 void
122 vsyslog(pri, fmt, ap)
123 	int pri;
124 	const char *fmt;
125 	va_list ap;
126 {
127 	int cnt;
128 	char ch, *p;
129 	time_t now;
130 	int fd, saved_errno;
131 	char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26];
132 	FILE *fp, *fmt_fp;
133 	struct bufcookie tbuf_cookie;
134 	struct bufcookie fmt_cookie;
135 
136 #define	INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
137 	/* Check for invalid bits. */
138 	if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
139 		syslog(INTERNALLOG,
140 		    "syslog: unknown facility/priority: %x", pri);
141 		pri &= LOG_PRIMASK|LOG_FACMASK;
142 	}
143 
144 	/* Check priority against setlogmask values. */
145 	if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
146 		return;
147 
148 	saved_errno = errno;
149 
150 	/* Set default facility if none specified. */
151 	if ((pri & LOG_FACMASK) == 0)
152 		pri |= LogFacility;
153 
154 	/* Create the primary stdio hook */
155 	tbuf_cookie.base = tbuf;
156 	tbuf_cookie.left = sizeof(tbuf);
157 	fp = fwopen(&tbuf_cookie, writehook);
158 	if (fp == NULL)
159 		return;
160 
161 	/* Build the message. */
162 	(void)time(&now);
163 	(void)fprintf(fp, "<%d>", pri);
164 	(void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
165 	if (LogStat & LOG_PERROR) {
166 		/* Transfer to string buffer */
167 		(void)fflush(fp);
168 		stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
169 	}
170 	if (LogTag == NULL)
171 		LogTag = _getprogname();
172 	if (LogTag != NULL)
173 		(void)fprintf(fp, "%s", LogTag);
174 	if (LogStat & LOG_PID)
175 		(void)fprintf(fp, "[%d]", getpid());
176 	if (LogTag != NULL) {
177 		(void)fprintf(fp, ": ");
178 	}
179 
180 	/* Check to see if we can skip expanding the %m */
181 	if (strstr(fmt, "%m")) {
182 
183 		/* Create the second stdio hook */
184 		fmt_cookie.base = fmt_cpy;
185 		fmt_cookie.left = sizeof(fmt_cpy) - 1;
186 		fmt_fp = fwopen(&fmt_cookie, writehook);
187 		if (fmt_fp == NULL) {
188 			fclose(fp);
189 			return;
190 		}
191 
192 		/*
193 		 * Substitute error message for %m.  Be careful not to
194 		 * molest an escaped percent "%%m".  We want to pass it
195 		 * on untouched as the format is later parsed by vfprintf.
196 		 */
197 		for ( ; (ch = *fmt); ++fmt) {
198 			if (ch == '%' && fmt[1] == 'm') {
199 				++fmt;
200 				fputs(strerror(saved_errno), fmt_fp);
201 			} else if (ch == '%' && fmt[1] == '%') {
202 				++fmt;
203 				fputc(ch, fmt_fp);
204 				fputc(ch, fmt_fp);
205 			} else {
206 				fputc(ch, fmt_fp);
207 			}
208 		}
209 
210 		/* Null terminate if room */
211 		fputc(0, fmt_fp);
212 		fclose(fmt_fp);
213 
214 		/* Guarantee null termination */
215 		fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
216 
217 		fmt = fmt_cpy;
218 	}
219 
220 	(void)vfprintf(fp, fmt, ap);
221 	(void)fclose(fp);
222 
223 	cnt = sizeof(tbuf) - tbuf_cookie.left;
224 
225 	/* Output to stderr if requested. */
226 	if (LogStat & LOG_PERROR) {
227 		struct iovec iov[2];
228 		struct iovec *v = iov;
229 
230 		v->iov_base = stdp;
231 		v->iov_len = cnt - (stdp - tbuf);
232 		++v;
233 		v->iov_base = "\n";
234 		v->iov_len = 1;
235 		(void)_writev(STDERR_FILENO, iov, 2);
236 	}
237 
238 	/* Get connected, output the message to the local logger. */
239 	if (!opened)
240 		openlog(LogTag, LogStat | LOG_NDELAY, 0);
241 	connectlog();
242 	if (send(LogFile, tbuf, cnt, 0) >= 0)
243 		return;
244 
245 	/*
246 	 * If the send() failed, the odds are syslogd was restarted.
247 	 * Make one (only) attempt to reconnect to /dev/log.
248 	 */
249 	disconnectlog();
250 	connectlog();
251 	if (send(LogFile, tbuf, cnt, 0) >= 0)
252 		return;
253 
254 	/*
255 	 * Output the message to the console; try not to block
256 	 * as a blocking console should not stop other processes.
257 	 * Make sure the error reported is the one from the syslogd failure.
258 	 */
259 	if (LogStat & LOG_CONS &&
260 	    (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) {
261 		struct iovec iov[2];
262 		struct iovec *v = iov;
263 
264 		p = strchr(tbuf, '>') + 1;
265 		v->iov_base = p;
266 		v->iov_len = cnt - (p - tbuf);
267 		++v;
268 		v->iov_base = "\r\n";
269 		v->iov_len = 2;
270 		(void)_writev(fd, iov, 2);
271 		(void)_close(fd);
272 	}
273 }
274 static void
275 disconnectlog()
276 {
277 	/*
278 	 * If the user closed the FD and opened another in the same slot,
279 	 * that's their problem.  They should close it before calling on
280 	 * system services.
281 	 */
282 	if (LogFile != -1) {
283 		_close(LogFile);
284 		LogFile = -1;
285 	}
286 	connected = 0;			/* retry connect */
287 }
288 
289 static void
290 connectlog()
291 {
292 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
293 
294 	if (LogFile == -1) {
295 		if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
296 			return;
297 		(void)_fcntl(LogFile, F_SETFD, 1);
298 	}
299 	if (LogFile != -1 && !connected) {
300 		SyslogAddr.sun_len = sizeof(SyslogAddr);
301 		SyslogAddr.sun_family = AF_UNIX;
302 		(void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
303 		    sizeof SyslogAddr.sun_path);
304 		connected = _connect(LogFile, (struct sockaddr *)&SyslogAddr,
305 			sizeof(SyslogAddr)) != -1;
306 
307 		if (!connected) {
308 			/*
309 			 * Try the old "/dev/log" path, for backward
310 			 * compatibility.
311 			 */
312 			(void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
313 			    sizeof SyslogAddr.sun_path);
314 			connected = _connect(LogFile,
315 				(struct sockaddr *)&SyslogAddr,
316 				sizeof(SyslogAddr)) != -1;
317 		}
318 
319 		if (!connected) {
320 			(void)_close(LogFile);
321 			LogFile = -1;
322 		}
323 	}
324 }
325 
326 void
327 openlog(ident, logstat, logfac)
328 	const char *ident;
329 	int logstat, logfac;
330 {
331 	if (ident != NULL)
332 		LogTag = ident;
333 	LogStat = logstat;
334 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
335 		LogFacility = logfac;
336 
337 	if (LogStat & LOG_NDELAY)	/* open immediately */
338 		connectlog();
339 
340 	opened = 1;	/* ident and facility has been set */
341 }
342 
343 void
344 closelog()
345 {
346 	(void)_close(LogFile);
347 	LogFile = -1;
348 	LogTag = NULL;
349 	connected = 0;
350 }
351 
352 /* setlogmask -- set the log mask level */
353 int
354 setlogmask(pmask)
355 	int pmask;
356 {
357 	int omask;
358 
359 	omask = LogMask;
360 	if (pmask != 0)
361 		LogMask = pmask;
362 	return (omask);
363 }
364