xref: /openbsd-src/lib/libc/gen/syslog.c (revision 0eea0d082377cb9c3ec583313dc4d52b7b6a4d6d)
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. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if defined(LIBC_SCCS) && !defined(lint)
31 static char rcsid[] = "$OpenBSD: syslog.c,v 1.26 2004/05/18 02:05:52 jfb Exp $";
32 #endif /* LIBC_SCCS and not lint */
33 
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/syslog.h>
37 #include <sys/uio.h>
38 #include <sys/un.h>
39 #include <netdb.h>
40 
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <paths.h>
44 #include <stdio.h>
45 #include <string.h>
46 #include <time.h>
47 #include <unistd.h>
48 #include <stdarg.h>
49 
50 static struct syslog_data sdata = SYSLOG_DATA_INIT;
51 
52 extern char	*__progname;		/* Program name, from crt0. */
53 
54 static void	disconnectlog_r(struct syslog_data *);	/* disconnect from syslogd */
55 static void	connectlog_r(struct syslog_data *);	/* (re)connect to syslogd */
56 
57 /*
58  * syslog, vsyslog --
59  *	print message on log file; output is intended for syslogd(8).
60  */
61 void
62 syslog(int pri, const char *fmt, ...)
63 {
64 	va_list ap;
65 
66 	va_start(ap, fmt);
67 	vsyslog(pri, fmt, ap);
68 	va_end(ap);
69 }
70 
71 void
72 vsyslog(int pri, const char *fmt, va_list ap)
73 {
74 	vsyslog_r(pri, &sdata, fmt, ap);
75 }
76 
77 void
78 openlog(const char *ident, int logstat, int logfac)
79 {
80 	openlog_r(ident, logstat, logfac, &sdata);
81 }
82 
83 void
84 closelog(void)
85 {
86 	closelog_r(&sdata);
87 }
88 
89 /* setlogmask -- set the log mask level */
90 int
91 setlogmask(int pmask)
92 {
93 	return setlogmask_r(pmask, &sdata);
94 }
95 
96 /* Reentrant version of syslog, i.e. syslog_r() */
97 
98 void
99 syslog_r(int pri, struct syslog_data *data, const char *fmt, ...)
100 {
101 	va_list ap;
102 
103 	va_start(ap, fmt);
104 	vsyslog_r(pri, data, fmt, ap);
105 	va_end(ap);
106 }
107 
108 void
109 vsyslog_r(int pri, struct syslog_data *data, const char *fmt, va_list ap)
110 {
111 	int cnt;
112 	char ch, *p, *t;
113 	time_t now;
114 	int fd, saved_errno, error;
115 #define	TBUF_LEN	2048
116 #define	FMT_LEN		1024
117 	char *stdp, tbuf[TBUF_LEN], fmt_cpy[FMT_LEN];
118 	int tbuf_left, fmt_left, prlen;
119 
120 #define	INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
121 	/* Check for invalid bits. */
122 	if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
123 		if (data == &sdata) {
124 			syslog(INTERNALLOG,
125 			    "syslog: unknown facility/priority: %x", pri);
126 		} else {
127 			syslog_r(INTERNALLOG, data,
128 			    "syslog_r: unknown facility/priority: %x", pri);
129 		}
130 		pri &= LOG_PRIMASK|LOG_FACMASK;
131 	}
132 
133 	/* Check priority against setlogmask values. */
134 	if (!(LOG_MASK(LOG_PRI(pri)) & data->log_mask))
135 		return;
136 
137 	saved_errno = errno;
138 
139 	/* Set default facility if none specified. */
140 	if ((pri & LOG_FACMASK) == 0)
141 		pri |= data->log_fac;
142 
143 	/* If we have been called through syslog(), no need for reentrancy. */
144 	if (data == &sdata)
145 		(void)time(&now);
146 
147 	p = tbuf;
148 	tbuf_left = TBUF_LEN;
149 
150 #define	DEC()	\
151 	do {					\
152 		if (prlen < 0)			\
153 			prlen = 0;		\
154 		if (prlen >= tbuf_left)		\
155 			prlen = tbuf_left - 1;	\
156 		p += prlen;			\
157 		tbuf_left -= prlen;		\
158 	} while (0)
159 
160 	prlen = snprintf(p, tbuf_left, "<%d>", pri);
161 	DEC();
162 
163 	/*
164 	 * syslogd will expand time automagically for reentrant case, and
165 	 * for normal case, just do like before
166 	 */
167 	if (data == &sdata) {
168 		prlen = strftime(p, tbuf_left, "%h %e %T ", localtime(&now));
169 		DEC();
170 	}
171 
172 	if (data->log_stat & LOG_PERROR)
173 		stdp = p;
174 	if (data->log_tag == NULL)
175 		data->log_tag = __progname;
176 	if (data->log_tag != NULL) {
177 		prlen = snprintf(p, tbuf_left, "%s", data->log_tag);
178 		DEC();
179 	}
180 	if (data->log_stat & LOG_PID) {
181 		prlen = snprintf(p, tbuf_left, "[%ld]", (long)getpid());
182 		DEC();
183 	}
184 	if (data->log_tag != NULL) {
185 		if (tbuf_left > 1) {
186 			*p++ = ':';
187 			tbuf_left--;
188 		}
189 		if (tbuf_left > 1) {
190 			*p++ = ' ';
191 			tbuf_left--;
192 		}
193 	}
194 
195 	/* strerror() is not reentrant */
196 
197 	for (t = fmt_cpy, fmt_left = FMT_LEN; (ch = *fmt); ++fmt) {
198 		if (ch == '%' && fmt[1] == 'm') {
199 			++fmt;
200 			if (data == &sdata) {
201 				prlen = snprintf(t, fmt_left, "%s",
202 				    strerror(saved_errno));
203 			} else {
204 				prlen = snprintf(t, fmt_left, "Error %d",
205 				    saved_errno);
206 			}
207 			if (prlen >= fmt_left)
208 				prlen = fmt_left - 1;
209 			t += prlen;
210 			fmt_left -= prlen;
211 		} else if (ch == '%' && fmt[1] == '%' && fmt_left > 2) {
212 			*t++ = '%';
213 			*t++ = '%';
214 			fmt++;
215 			fmt_left -= 2;
216 		} else {
217 			if (fmt_left > 1) {
218 				*t++ = ch;
219 				fmt_left--;
220 			}
221 		}
222 	}
223 	*t = '\0';
224 
225 	prlen = vsnprintf(p, tbuf_left, fmt_cpy, ap);
226 	DEC();
227 	cnt = p - tbuf;
228 
229 	/* Output to stderr if requested. */
230 	if (data->log_stat & LOG_PERROR) {
231 		struct iovec iov[2];
232 
233 		iov[0].iov_base = stdp;
234 		iov[0].iov_len = cnt - (stdp - tbuf);
235 		iov[1].iov_base = "\n";
236 		iov[1].iov_len = 1;
237 		(void)writev(STDERR_FILENO, iov, 2);
238 	}
239 
240 	/* Get connected, output the message to the local logger. */
241 	if (!data->opened)
242 		openlog_r(data->log_tag, data->log_stat, 0, data);
243 	connectlog_r(data);
244 
245 	/*
246 	 * If the send() failed, there are two likely scenarios:
247 	 *  1) syslogd was restarted
248 	 *  2) /dev/log is out of socket buffer space
249 	 * We attempt to reconnect to /dev/log to take care of
250 	 * case #1 and keep send()ing data to cover case #2
251 	 * to give syslogd a chance to empty its socket buffer.
252 	 */
253 	if ((error = send(data->log_file, tbuf, cnt, 0)) < 0) {
254 		if (errno != ENOBUFS) {
255 			disconnectlog_r(data);
256 			connectlog_r(data);
257 		}
258 		do {
259 			usleep(1);
260 			if ((error = send(data->log_file, tbuf, cnt, 0)) >= 0)
261 				break;
262 		} while (errno == ENOBUFS);
263 	}
264 
265 	/*
266 	 * Output the message to the console; try not to block
267 	 * as a blocking console should not stop other processes.
268 	 * Make sure the error reported is the one from the syslogd failure.
269 	 */
270 	if (error == -1 && (data->log_stat & LOG_CONS) &&
271 	    (fd = open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) {
272 		struct iovec iov[2];
273 
274 		p = strchr(tbuf, '>') + 1;
275 		iov[0].iov_base = p;
276 		iov[0].iov_len = cnt - (p - tbuf);
277 		iov[1].iov_base = "\r\n";
278 		iov[1].iov_len = 2;
279 		(void)writev(fd, iov, 2);
280 		(void)close(fd);
281 	}
282 
283 	if (data != &sdata)
284 		closelog_r(data);
285 }
286 
287 static void
288 disconnectlog_r(struct syslog_data *data)
289 {
290 	/*
291 	 * If the user closed the FD and opened another in the same slot,
292 	 * that's their problem.  They should close it before calling on
293 	 * system services.
294 	 */
295 	if (data->log_file != -1) {
296 		close(data->log_file);
297 		data->log_file = -1;
298 	}
299 	data->connected = 0;		/* retry connect */
300 }
301 
302 static void
303 connectlog_r(struct syslog_data *data)
304 {
305 	struct sockaddr_un SyslogAddr;	/* AF_UNIX address of local logger */
306 
307 	if (data->log_file == -1) {
308 		if ((data->log_file = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
309 			return;
310 		(void)fcntl(data->log_file, F_SETFD, 1);
311 	}
312 	if (data->log_file != -1 && !data->connected) {
313 		memset(&SyslogAddr, '\0', sizeof(SyslogAddr));
314 		SyslogAddr.sun_len = sizeof(SyslogAddr);
315 		SyslogAddr.sun_family = AF_UNIX;
316 		strlcpy(SyslogAddr.sun_path, _PATH_LOG,
317 		    sizeof(SyslogAddr.sun_path));
318 		if (connect(data->log_file, (struct sockaddr *)&SyslogAddr,
319 		    sizeof(SyslogAddr)) == -1) {
320 			(void)close(data->log_file);
321 			data->log_file = -1;
322 		} else
323 			data->connected = 1;
324 	}
325 }
326 
327 void
328 openlog_r(const char *ident, int logstat, int logfac, struct syslog_data *data)
329 {
330 	if (ident != NULL)
331 		data->log_tag = ident;
332 	data->log_stat = logstat;
333 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
334 		data->log_fac = logfac;
335 
336 	if (data->log_stat & LOG_NDELAY)	/* open immediately */
337 		connectlog_r(data);
338 
339 	data->opened = 1;	/* ident and facility has been set */
340 }
341 
342 void
343 closelog_r(struct syslog_data *data)
344 {
345 	(void)close(data->log_file);
346 	data->log_file = -1;
347 	data->connected = 0;
348 	data->log_tag = NULL;
349 }
350 
351 /* setlogmask -- set the log mask level */
352 int
353 setlogmask_r(int pmask, struct syslog_data *data)
354 {
355 	int omask;
356 
357 	omask = data->log_mask;
358 	if (pmask != 0)
359 		data->log_mask = pmask;
360 	return (omask);
361 }
362