xref: /freebsd/lib/libc/gen/syslog.c (revision 2546665afcaf0d53dc2c7058fee96354b3680f5a)
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 	/* Remove a trailing newline */
226 	if (tbuf[cnt - 1] == '\n')
227 		cnt--;
228 
229 	/* Output to stderr if requested. */
230 	if (LogStat & LOG_PERROR) {
231 		struct iovec iov[2];
232 		struct iovec *v = iov;
233 
234 		v->iov_base = stdp;
235 		v->iov_len = cnt - (stdp - tbuf);
236 		++v;
237 		v->iov_base = "\n";
238 		v->iov_len = 1;
239 		(void)_writev(STDERR_FILENO, iov, 2);
240 	}
241 
242 	/* Get connected, output the message to the local logger. */
243 	if (!opened)
244 		openlog(LogTag, LogStat | LOG_NDELAY, 0);
245 	connectlog();
246 	if (send(LogFile, tbuf, cnt, 0) >= 0)
247 		return;
248 
249 	/*
250 	 * If the send() failed, the odds are syslogd was restarted.
251 	 * Make one (only) attempt to reconnect to /dev/log.
252 	 */
253 	disconnectlog();
254 	connectlog();
255 	if (send(LogFile, tbuf, cnt, 0) >= 0)
256 		return;
257 
258 	/*
259 	 * Output the message to the console; try not to block
260 	 * as a blocking console should not stop other processes.
261 	 * Make sure the error reported is the one from the syslogd failure.
262 	 */
263 	if (LogStat & LOG_CONS &&
264 	    (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) {
265 		struct iovec iov[2];
266 		struct iovec *v = iov;
267 
268 		p = strchr(tbuf, '>') + 1;
269 		v->iov_base = p;
270 		v->iov_len = cnt - (p - tbuf);
271 		++v;
272 		v->iov_base = "\r\n";
273 		v->iov_len = 2;
274 		(void)_writev(fd, iov, 2);
275 		(void)_close(fd);
276 	}
277 }
278 static void
279 disconnectlog()
280 {
281 	/*
282 	 * If the user closed the FD and opened another in the same slot,
283 	 * that's their problem.  They should close it before calling on
284 	 * system services.
285 	 */
286 	if (LogFile != -1) {
287 		_close(LogFile);
288 		LogFile = -1;
289 	}
290 	connected = 0;			/* retry connect */
291 }
292 
293 static void
294 connectlog()
295 {
296 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
297 
298 	if (LogFile == -1) {
299 		if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
300 			return;
301 		(void)_fcntl(LogFile, F_SETFD, 1);
302 	}
303 	if (LogFile != -1 && !connected) {
304 		SyslogAddr.sun_len = sizeof(SyslogAddr);
305 		SyslogAddr.sun_family = AF_UNIX;
306 		(void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
307 		    sizeof SyslogAddr.sun_path);
308 		connected = _connect(LogFile, (struct sockaddr *)&SyslogAddr,
309 			sizeof(SyslogAddr)) != -1;
310 
311 		if (!connected) {
312 			/*
313 			 * Try the old "/dev/log" path, for backward
314 			 * compatibility.
315 			 */
316 			(void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
317 			    sizeof SyslogAddr.sun_path);
318 			connected = _connect(LogFile,
319 				(struct sockaddr *)&SyslogAddr,
320 				sizeof(SyslogAddr)) != -1;
321 		}
322 
323 		if (!connected) {
324 			(void)_close(LogFile);
325 			LogFile = -1;
326 		}
327 	}
328 }
329 
330 void
331 openlog(ident, logstat, logfac)
332 	const char *ident;
333 	int logstat, logfac;
334 {
335 	if (ident != NULL)
336 		LogTag = ident;
337 	LogStat = logstat;
338 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
339 		LogFacility = logfac;
340 
341 	if (LogStat & LOG_NDELAY)	/* open immediately */
342 		connectlog();
343 
344 	opened = 1;	/* ident and facility has been set */
345 }
346 
347 void
348 closelog()
349 {
350 	(void)_close(LogFile);
351 	LogFile = -1;
352 	LogTag = NULL;
353 	connected = 0;
354 }
355 
356 /* setlogmask -- set the log mask level */
357 int
358 setlogmask(pmask)
359 	int pmask;
360 {
361 	int omask;
362 
363 	omask = LogMask;
364 	if (pmask != 0)
365 		LogMask = pmask;
366 	return (omask);
367 }
368