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