xref: /freebsd/lib/libc/gen/syslog.c (revision 70fe064ad7cab6c0444b91622f60ec6a462f308a)
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 /*
36 static char sccsid[] = "@(#)syslog.c	8.5 (Berkeley) 4/29/95";
37 */
38 static const char rcsid[] =
39   "$FreeBSD$";
40 #endif /* LIBC_SCCS and not lint */
41 
42 #include "namespace.h"
43 #include <sys/types.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 <stdio.h>
54 #include <string.h>
55 #include <time.h>
56 #include <unistd.h>
57 
58 #if __STDC__
59 #include <stdarg.h>
60 #else
61 #include <varargs.h>
62 #endif
63 #include "un-namespace.h"
64 
65 static int	LogFile = -1;		/* fd for log */
66 static int	connected;		/* have done connect */
67 static int	opened;			/* have done openlog() */
68 static int	LogStat = 0;		/* status bits, set by openlog() */
69 static const char *LogTag = NULL;	/* string to tag the entry with */
70 static int	LogFacility = LOG_USER;	/* default facility code */
71 static int	LogMask = 0xff;		/* mask of priorities to be logged */
72 extern char	*__progname;		/* Program name, from crt0. */
73 
74 static void	disconnectlog __P((void)); /* disconnect from syslogd */
75 static void	connectlog __P((void));	/* (re)connect to syslogd */
76 
77 /*
78  * Format of the magic cookie passed through the stdio hook
79  */
80 struct bufcookie {
81 	char	*base;	/* start of buffer */
82 	int	left;
83 };
84 
85 /*
86  * stdio write hook for writing to a static string buffer
87  * XXX: Maybe one day, dynamically allocate it so that the line length
88  *      is `unlimited'.
89  */
90 static
91 int writehook(cookie, buf, len)
92 	void	*cookie;	/* really [struct bufcookie *] */
93 	char	*buf;		/* characters to copy */
94 	int	len;		/* length to copy */
95 {
96 	struct bufcookie *h;	/* private `handle' */
97 
98 	h = (struct bufcookie *)cookie;
99 	if (len > h->left) {
100 		/* clip in case of wraparound */
101 		len = h->left;
102 	}
103 	if (len > 0) {
104 		(void)memcpy(h->base, buf, len); /* `write' it. */
105 		h->base += len;
106 		h->left -= len;
107 	}
108 	return 0;
109 }
110 
111 /*
112  * syslog, vsyslog --
113  *	print message on log file; output is intended for syslogd(8).
114  */
115 void
116 #if __STDC__
117 syslog(int pri, const char *fmt, ...)
118 #else
119 syslog(pri, fmt, va_alist)
120 	int pri;
121 	char *fmt;
122 	va_dcl
123 #endif
124 {
125 	va_list ap;
126 
127 #if __STDC__
128 	va_start(ap, fmt);
129 #else
130 	va_start(ap);
131 #endif
132 	vsyslog(pri, fmt, ap);
133 	va_end(ap);
134 }
135 
136 void
137 vsyslog(pri, fmt, ap)
138 	int pri;
139 	register const char *fmt;
140 	va_list ap;
141 {
142 	register int cnt;
143 	register char ch, *p;
144 	time_t now;
145 	int fd, saved_errno;
146 	char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26];
147 	FILE *fp, *fmt_fp;
148 	struct bufcookie tbuf_cookie;
149 	struct bufcookie fmt_cookie;
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 		syslog(INTERNALLOG,
155 		    "syslog: unknown facility/priority: %x", pri);
156 		pri &= LOG_PRIMASK|LOG_FACMASK;
157 	}
158 
159 	/* Check priority against setlogmask values. */
160 	if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
161 		return;
162 
163 	saved_errno = errno;
164 
165 	/* Set default facility if none specified. */
166 	if ((pri & LOG_FACMASK) == 0)
167 		pri |= LogFacility;
168 
169 	/* Create the primary stdio hook */
170 	tbuf_cookie.base = tbuf;
171 	tbuf_cookie.left = sizeof(tbuf);
172 	fp = fwopen(&tbuf_cookie, writehook);
173 	if (fp == NULL)
174 		return;
175 
176 	/* Build the message. */
177 	(void)time(&now);
178 	(void)fprintf(fp, "<%d>", pri);
179 	(void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
180 	if (LogStat & LOG_PERROR) {
181 		/* Transfer to string buffer */
182 		(void)fflush(fp);
183 		stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
184 	}
185 	if (LogTag == NULL)
186 		LogTag = __progname;
187 	if (LogTag != NULL)
188 		(void)fprintf(fp, "%s", LogTag);
189 	if (LogStat & LOG_PID)
190 		(void)fprintf(fp, "[%d]", getpid());
191 	if (LogTag != NULL) {
192 		(void)fprintf(fp, ": ");
193 	}
194 
195 	/* Check to see if we can skip expanding the %m */
196 	if (strstr(fmt, "%m")) {
197 
198 		/* Create the second stdio hook */
199 		fmt_cookie.base = fmt_cpy;
200 		fmt_cookie.left = sizeof(fmt_cpy) - 1;
201 		fmt_fp = fwopen(&fmt_cookie, writehook);
202 		if (fmt_fp == NULL) {
203 			fclose(fp);
204 			return;
205 		}
206 
207 		/* Substitute error message for %m. */
208 		for ( ; (ch = *fmt); ++fmt)
209 			if (ch == '%' && fmt[1] == 'm') {
210 				++fmt;
211 				fputs(strerror(saved_errno), fmt_fp);
212 			} else
213 				fputc(ch, fmt_fp);
214 
215 		/* Null terminate if room */
216 		fputc(0, fmt_fp);
217 		fclose(fmt_fp);
218 
219 		/* Guarantee null termination */
220 		fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
221 
222 		fmt = fmt_cpy;
223 	}
224 
225 	(void)vfprintf(fp, fmt, ap);
226 	(void)fclose(fp);
227 
228 	cnt = sizeof(tbuf) - tbuf_cookie.left;
229 
230 	/* Output to stderr if requested. */
231 	if (LogStat & LOG_PERROR) {
232 		struct iovec iov[2];
233 		register struct iovec *v = iov;
234 
235 		v->iov_base = stdp;
236 		v->iov_len = cnt - (stdp - tbuf);
237 		++v;
238 		v->iov_base = "\n";
239 		v->iov_len = 1;
240 		(void)_writev(STDERR_FILENO, iov, 2);
241 	}
242 
243 	/* Get connected, output the message to the local logger. */
244 	if (!opened)
245 		openlog(LogTag, LogStat | LOG_NDELAY, 0);
246 	connectlog();
247 	if (send(LogFile, tbuf, cnt, 0) >= 0)
248 		return;
249 
250 	/*
251 	 * If the send() failed, the odds are syslogd was restarted.
252 	 * Make one (only) attempt to reconnect to /dev/log.
253 	 */
254 	disconnectlog();
255 	connectlog();
256 	if (send(LogFile, tbuf, cnt, 0) >= 0)
257 		return;
258 
259 	/*
260 	 * Output the message to the console; don't worry about blocking,
261 	 * if console blocks everything will.  Make sure the error reported
262 	 * is the one from the syslogd failure.
263 	 */
264 	if (LogStat & LOG_CONS &&
265 	    (fd = _open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) {
266 		struct iovec iov[2];
267 		register struct iovec *v = iov;
268 
269 		p = strchr(tbuf, '>') + 1;
270 		v->iov_base = p;
271 		v->iov_len = cnt - (p - tbuf);
272 		++v;
273 		v->iov_base = "\r\n";
274 		v->iov_len = 2;
275 		(void)_writev(fd, iov, 2);
276 		(void)_close(fd);
277 	}
278 }
279 static void
280 disconnectlog()
281 {
282 	/*
283 	 * If the user closed the FD and opened another in the same slot,
284 	 * that's their problem.  They should close it before calling on
285 	 * system services.
286 	 */
287 	if (LogFile != -1) {
288 		_close(LogFile);
289 		LogFile = -1;
290 	}
291 	connected = 0;			/* retry connect */
292 }
293 
294 static void
295 connectlog()
296 {
297 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
298 
299 	if (LogFile == -1) {
300 		if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
301 			return;
302 		(void)_fcntl(LogFile, F_SETFD, 1);
303 	}
304 	if (LogFile != -1 && !connected) {
305 		SyslogAddr.sun_len = sizeof(SyslogAddr);
306 		SyslogAddr.sun_family = AF_UNIX;
307 		(void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
308 		    sizeof SyslogAddr.sun_path);
309 		connected = _connect(LogFile, (struct sockaddr *)&SyslogAddr,
310 			sizeof(SyslogAddr)) != -1;
311 
312 		if (!connected) {
313 			/*
314 			 * Try the old "/dev/log" path, for backward
315 			 * compatibility.
316 			 */
317 			(void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
318 			    sizeof SyslogAddr.sun_path);
319 			connected = _connect(LogFile,
320 				(struct sockaddr *)&SyslogAddr,
321 				sizeof(SyslogAddr)) != -1;
322 		}
323 
324 		if (!connected) {
325 			(void)_close(LogFile);
326 			LogFile = -1;
327 		}
328 	}
329 }
330 
331 void
332 openlog(ident, logstat, logfac)
333 	const char *ident;
334 	int logstat, logfac;
335 {
336 	if (ident != NULL)
337 		LogTag = ident;
338 	LogStat = logstat;
339 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
340 		LogFacility = logfac;
341 
342 	if (LogStat & LOG_NDELAY)	/* open immediately */
343 		connectlog();
344 
345 	opened = 1;	/* ident and facility has been set */
346 }
347 
348 void
349 closelog()
350 {
351 	(void)_close(LogFile);
352 	LogFile = -1;
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