xref: /netbsd-src/lib/libc/gen/xsyslog.c (revision e89934bbf778a6d6d6894877c4da59d0c7835b0f)
1 /*	$NetBSD: xsyslog.c,v 1.2 2017/01/12 01:58:39 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #if defined(LIBC_SCCS) && !defined(lint)
34 #if 0
35 static char sccsid[] = "@(#)syslog.c	8.5 (Berkeley) 4/29/95";
36 #else
37 __RCSID("$NetBSD: xsyslog.c,v 1.2 2017/01/12 01:58:39 christos Exp $");
38 #endif
39 #endif /* LIBC_SCCS and not lint */
40 
41 #include "namespace.h"
42 #include <sys/types.h>
43 #include <sys/param.h>
44 #include <sys/socket.h>
45 #include <sys/syslog.h>
46 #include <sys/uio.h>
47 #include <sys/un.h>
48 
49 #include <errno.h>
50 #include <stdio.h>
51 #include <stdarg.h>
52 #include <string.h>
53 #include <fcntl.h>
54 #include <unistd.h>
55 #include <stdlib.h>
56 #include <paths.h>
57 #include "syslog_private.h"
58 #include "reentrant.h"
59 #include "extern.h"
60 
61 static void
62 disconnectlog_r(struct syslog_data *data)
63 {
64 	/*
65 	 * If the user closed the FD and opened another in the same slot,
66 	 * that's their problem.  They should close it before calling on
67 	 * system services.
68 	 */
69 	if (data->log_file != -1) {
70 		(void)close(data->log_file);
71 		data->log_file = -1;
72 	}
73 	data->log_connected = 0;		/* retry connect */
74 }
75 
76 static void
77 connectlog_r(struct syslog_data *data)
78 {
79 	/* AF_UNIX address of local logger */
80 	static const struct sockaddr_un sun = {
81 		.sun_family = AF_LOCAL,
82 		.sun_len = sizeof(sun),
83 		.sun_path = _PATH_LOG,
84 	};
85 
86 	if (data->log_file == -1 || fcntl(data->log_file, F_GETFL, 0) == -1) {
87 		if ((data->log_file = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
88 		    0)) == -1)
89 			return;
90 		data->log_connected = 0;
91 	}
92 	if (!data->log_connected) {
93 		if (connect(data->log_file,
94 		    (const struct sockaddr *)(const void *)&sun,
95 		    (socklen_t)sizeof(sun)) == -1) {
96 			(void)close(data->log_file);
97 			data->log_file = -1;
98 		} else
99 			data->log_connected = 1;
100 	}
101 }
102 
103 void
104 _openlog_unlocked_r(const char *ident, int logstat, int logfac,
105     struct syslog_data *data)
106 {
107 	if (ident != NULL)
108 		data->log_tag = ident;
109 	data->log_stat = logstat;
110 	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
111 		data->log_fac = logfac;
112 
113 	if (data->log_stat & LOG_NDELAY)	/* open immediately */
114 		connectlog_r(data);
115 
116 	data->log_opened = 1;
117 }
118 
119 void
120 _closelog_unlocked_r(struct syslog_data *data)
121 {
122 	(void)close(data->log_file);
123 	data->log_file = -1;
124 	data->log_connected = 0;
125 }
126 
127 static void
128 _xsyslogp_r(int pri, struct syslog_fun *fun,
129     struct syslog_data *data, const char *msgid,
130     const char *sdfmt, const char *msgfmt, ...)
131 {
132 	va_list ap;
133 	va_start(ap, msgfmt);
134 	_vxsyslogp_r(pri, fun, data, msgid, sdfmt, msgfmt, ap);
135 	va_end(ap);
136 }
137 
138 void
139 _vxsyslogp_r(int pri, struct syslog_fun *fun,
140     struct syslog_data *data, const char *msgid,
141     const char *sdfmt, const char *msgfmt, va_list ap)
142 {
143 	static const char BRCOSP[] = "]: ";
144 	static const char CRLF[] = "\r\n";
145 	size_t cnt, prlen, tries;
146 	char ch, *p, *t;
147 	int fd, saved_errno;
148 #define TBUF_LEN	2048
149 #define FMT_LEN		1024
150 #define MAXTRIES	10
151 	char tbuf[TBUF_LEN], fmt_cpy[FMT_LEN], fmt_cat[FMT_LEN] = "";
152 	size_t tbuf_left, fmt_left, msgsdlen;
153 	char *fmt = fmt_cat;
154 	struct iovec iov[7];	/* prog + [ + pid + ]: + fmt + crlf */
155 	int opened, iovcnt;
156 
157 #define INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
158 	/* Check for invalid bits. */
159 	if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
160 		_xsyslogp_r(INTERNALLOG, &_syslog_ss_fun, data, NULL, NULL,
161 		    "%s: unknown facility/priority: %x", pri);
162 		pri &= LOG_PRIMASK|LOG_FACMASK;
163 	}
164 
165 	/* Check priority against setlogmask values. */
166 	if (!(LOG_MASK(LOG_PRI(pri)) & data->log_mask))
167 		return;
168 
169 	saved_errno = errno;
170 
171 	/* Set default facility if none specified. */
172 	if ((pri & LOG_FACMASK) == 0)
173 		pri |= data->log_fac;
174 
175 	/* Build the message. */
176 	p = tbuf;
177 	tbuf_left = TBUF_LEN;
178 
179 	prlen = snprintf_ss(p, tbuf_left, "<%d>1 ", pri);
180 	DEC();
181 
182 	prlen = (*fun->timefun)(p, tbuf_left);
183 
184 	(*fun->lock)(data);
185 
186 	if (data->log_hostname[0] == '\0' && gethostname(data->log_hostname,
187 	    sizeof(data->log_hostname)) == -1) {
188 		/* can this really happen? */
189 		data->log_hostname[0] = '-';
190 		data->log_hostname[1] = '\0';
191 	}
192 
193 	DEC();
194 	prlen = snprintf_ss(p, tbuf_left, " %s ", data->log_hostname);
195 
196 	if (data->log_tag == NULL)
197 		data->log_tag = getprogname();
198 
199 	DEC();
200 	prlen = snprintf_ss(p, tbuf_left, "%s ",
201 	    data->log_tag ? data->log_tag : "-");
202 
203 	(*fun->unlock)(data);
204 
205 	if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
206 		iovcnt = 0;
207 		iov[iovcnt].iov_base = p;
208 		iov[iovcnt].iov_len = prlen - 1;
209 		iovcnt++;
210 	}
211 	DEC();
212 
213 	if (data->log_stat & LOG_PID) {
214 		prlen = snprintf_ss(p, tbuf_left, "%d ", getpid());
215 		if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
216 			iov[iovcnt].iov_base = __UNCONST("[");
217 			iov[iovcnt].iov_len = 1;
218 			iovcnt++;
219 			iov[iovcnt].iov_base = p;
220 			iov[iovcnt].iov_len = prlen - 1;
221 			iovcnt++;
222 			iov[iovcnt].iov_base = __UNCONST(BRCOSP);
223 			iov[iovcnt].iov_len = 3;
224 			iovcnt++;
225 		}
226 	} else {
227 		prlen = snprintf_ss(p, tbuf_left, "- ");
228 		if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
229 			iov[iovcnt].iov_base = __UNCONST(BRCOSP + 1);
230 			iov[iovcnt].iov_len = 2;
231 			iovcnt++;
232 		}
233 	}
234 	DEC();
235 
236 	/*
237 	 * concat the format strings, then use one vsnprintf()
238 	 */
239 	if (msgid != NULL && *msgid != '\0') {
240 		strlcat(fmt_cat, msgid, FMT_LEN);
241 		strlcat(fmt_cat, " ", FMT_LEN);
242 	} else
243 		strlcat(fmt_cat, "- ", FMT_LEN);
244 
245 	if (sdfmt != NULL && *sdfmt != '\0') {
246 		strlcat(fmt_cat, sdfmt, FMT_LEN);
247 	} else
248 		strlcat(fmt_cat, "-", FMT_LEN);
249 
250 	if (data->log_stat & (LOG_PERROR|LOG_CONS))
251 		msgsdlen = strlen(fmt_cat) + 1;
252 	else
253 		msgsdlen = 0;	/* XXX: GCC */
254 
255 	if (msgfmt != NULL && *msgfmt != '\0') {
256 		strlcat(fmt_cat, " ", FMT_LEN);
257 		strlcat(fmt_cat, msgfmt, FMT_LEN);
258 	}
259 
260 	/*
261 	 * We wouldn't need this mess if printf handled %m, or if
262 	 * strerror() had been invented before syslog().
263 	 */
264 	for (t = fmt_cpy, fmt_left = FMT_LEN; (ch = *fmt) != '\0'; ++fmt) {
265 		if (ch == '%' && fmt[1] == 'm') {
266 			char buf[256];
267 
268 			if ((*fun->errfun)(saved_errno, buf, sizeof(buf)) != 0)
269 				prlen = snprintf_ss(t, fmt_left, "Error %d",
270 				    saved_errno);
271 			else
272 				prlen = strlcpy(t, buf, fmt_left);
273 			if (prlen >= fmt_left)
274 				prlen = fmt_left - 1;
275 			t += prlen;
276 			fmt++;
277 			fmt_left -= prlen;
278 		} else if (ch == '%' && fmt[1] == '%' && fmt_left > 2) {
279 			*t++ = '%';
280 			*t++ = '%';
281 			fmt++;
282 			fmt_left -= 2;
283 		} else {
284 			if (fmt_left > 1) {
285 				*t++ = ch;
286 				fmt_left--;
287 			}
288 		}
289 	}
290 	*t = '\0';
291 
292 	prlen = (*fun->prfun)(p, tbuf_left, fmt_cpy, ap);
293 	if (data->log_stat & (LOG_PERROR|LOG_CONS)) {
294 		iov[iovcnt].iov_base = p + msgsdlen;
295 		iov[iovcnt].iov_len = prlen - msgsdlen;
296 		iovcnt++;
297 	}
298 
299 	DEC();
300 	cnt = p - tbuf;
301 
302 	/* Output to stderr if requested. */
303 	if (data->log_stat & LOG_PERROR) {
304 		iov[iovcnt].iov_base = __UNCONST(CRLF + 1);
305 		iov[iovcnt].iov_len = 1;
306 		(void)writev(STDERR_FILENO, iov, iovcnt + 1);
307 	}
308 
309 	/* Get connected, output the message to the local logger. */
310 	(*fun->lock)(data);
311 	opened = !data->log_opened;
312 	if (opened)
313 		_openlog_unlocked_r(data->log_tag, data->log_stat, 0, data);
314 	connectlog_r(data);
315 
316 	/*
317 	 * If the send() failed, there are two likely scenarios:
318 	 *  1) syslogd was restarted
319 	 *  2) /dev/log is out of socket buffer space
320 	 * We attempt to reconnect to /dev/log to take care of
321 	 * case #1 and keep send()ing data to cover case #2
322 	 * to give syslogd a chance to empty its socket buffer.
323 	 */
324 	for (tries = 0; tries < MAXTRIES; tries++) {
325 		if (send(data->log_file, tbuf, cnt, 0) != -1)
326 			break;
327 		if (errno != ENOBUFS) {
328 			disconnectlog_r(data);
329 			connectlog_r(data);
330 		} else
331 			(void)usleep(1);
332 	}
333 
334 	/*
335 	 * Output the message to the console; try not to block
336 	 * as a blocking console should not stop other processes.
337 	 * Make sure the error reported is the one from the syslogd failure.
338 	 */
339 	if (tries == MAXTRIES && (data->log_stat & LOG_CONS) &&
340 	    (fd = open(_PATH_CONSOLE,
341 		O_WRONLY | O_NONBLOCK | O_CLOEXEC, 0)) >= 0) {
342 		iov[iovcnt].iov_base = __UNCONST(CRLF);
343 		iov[iovcnt].iov_len = 2;
344 		(void)writev(fd, iov, iovcnt + 1);
345 		(void)close(fd);
346 	}
347 
348 	if (!(*fun->unlock)(data) && opened)
349 		_closelog_unlocked_r(data);
350 }
351 
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