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 /*
35  * SYSLOG -- print message on log file
36  *
37  * This routine looks a lot like printf, except that it outputs to the
38  * log file instead of the standard output.  Also:
39  *	adds a timestamp,
40  *	prints the module name in front of the message,
41  *	has some other formatting types (or will sometime),
42  *	adds a newline on the end of the message.
43  *
44  * The output of this routine is intended to be read by syslogd(8).
45  *
46  * Author: Eric Allman
47  * Modified to use UNIX domain IPC by Ralph Campbell
48  * Patched March 12, 1996 by A. Ian Vogelesang <vogelesang@hdshq.com>
49  *  - to correct the handling of message & format string truncation,
50  *  - to visibly tag truncated records to facilitate
51  *    investigation of such Bad Things with grep, and,
52  *  - to correct the handling of case where "write"
53  *    returns after writing only part of the message.
54  * Rewritten by Martin Mares <mj@atrey.karlin.mff.cuni.cz> on May 14, 1997
55  *  - better buffer overrun checks.
56  *  - special handling of "%m" removed as we use GNU sprintf which handles
57  *    it automatically.
58  *  - Major code cleanup.
59  */
60 
61 #include <sys/types.h>
62 #include <sys/socket.h>
63 #include <sys/file.h>
64 #include <sys/signal.h>
65 #include <sys/syslog.h>
66 
67 #include <sys/uio.h>
68 #include <sys/wait.h>
69 #include <netdb.h>
70 #include <string.h>
71 #include <time.h>
72 #include <unistd.h>
73 #include <errno.h>
74 #include <stdarg.h>
75 #include <paths.h>
76 #include <stdio.h>
77 #include <ctype.h>
78 #include <signal.h>
79 
80 
81 #include <bits/uClibc_mutex.h>
82 
83 __UCLIBC_MUTEX_STATIC(mylock, PTHREAD_MUTEX_INITIALIZER);
84 
85 
86 /* !glibc_compat: glibc uses argv[0] by default
87  * (default: if there was no openlog or if openlog passed NULL),
88  * not string "syslog"
89  */
90 static const char *LogTag = "syslog";   /* string to tag the entry with */
91 static int       LogFile = -1;          /* fd for log */
92 static smalluint connected;             /* have done connect */
93 /* all bits in option argument for openlog fit in 8 bits */
94 static smalluint LogStat = 0;           /* status bits, set by openlog */
95 /* default facility code if openlog is not called */
96 /* (this fits in 8 bits even without >> 3 shift, but playing extra safe) */
97 static smalluint LogFacility = LOG_USER >> 3;
98 /* bits mask of priorities to be logged (eight prios - 8 bits is enough) */
99 static smalluint LogMask = 0xff;
100 /* AF_UNIX address of local logger (we use struct sockaddr
101  * instead of struct sockaddr_un since "/dev/log" is small enough) */
102 static const struct sockaddr SyslogAddr = {
103 	.sa_family = AF_UNIX, /* sa_family_t (usually a short) */
104 	.sa_data = _PATH_LOG  /* char [14] */
105 };
106 
107 static void
closelog_intern(int sig)108 closelog_intern(int sig)
109 {
110 	/* mylock must be held by the caller */
111 	if (LogFile != -1) {
112 		(void) close(LogFile);
113 	}
114 	LogFile = -1;
115 	connected = 0;
116 	if (sig == 0) { /* called from closelog()? - reset to defaults */
117 		LogStat = 0;
118 		LogTag = "syslog";
119 		LogFacility = LOG_USER >> 3;
120 		LogMask = 0xff;
121 	}
122 }
123 
124 static void
openlog_intern(void)125 openlog_intern(void)
126 {
127 	int fd;
128 	int logType = SOCK_DGRAM;
129 	static const struct timeval tv = { 1, 0 };
130 
131 	fd = LogFile;
132 	if (fd == -1) {
133  retry:
134 		if (1) { /* if statement left in to make .diff cleaner */
135 			LogFile = fd = socket(AF_UNIX, logType, 0);
136 			if (fd == -1) {
137 				return;
138 			}
139 			fcntl(fd, F_SETFD, FD_CLOEXEC);
140 			/* We don't want to block if e.g. syslogd is SIGSTOPed */
141 			fcntl(fd, F_SETFL, O_NONBLOCK | fcntl(fd, F_GETFL));
142 		}
143 	}
144 
145 	if (fd != -1 && !connected) {
146 		if (connect(fd, &SyslogAddr, sizeof(SyslogAddr)) != -1) {
147 			/* We want to block send if e.g. syslogd is SIGSTOPed */
148 			fcntl(fd, F_SETFL, ~O_NONBLOCK & fcntl(fd, F_GETFL));
149 			setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
150 			connected = 1;
151 		} else {
152 			if (fd != -1) {
153 				close(fd);
154 				LogFile = fd = -1;
155 			}
156 			if (logType == SOCK_DGRAM) {
157 				logType = SOCK_STREAM;
158 				goto retry;
159 			}
160 		}
161 	}
162 }
163 
164 /*
165  * OPENLOG -- open system log
166  */
167 void
openlog(const char * ident,int logstat,int logfac)168 openlog(const char *ident, int logstat, int logfac)
169 {
170 	__UCLIBC_MUTEX_LOCK(mylock);
171 
172 	if (ident != NULL)
173 		LogTag = ident;
174 	LogStat = logstat;
175 	/* (we were checking also for logfac != 0, but it breaks
176 	 * openlog(xx, LOG_KERN) since LOG_KERN == 0) */
177 	if ((logfac & ~LOG_FACMASK) == 0) /* if we don't have invalid bits */
178 		LogFacility = (unsigned)logfac >> 3;
179 
180 	if (logstat & LOG_NDELAY)
181 		openlog_intern();
182 
183 	__UCLIBC_MUTEX_UNLOCK(mylock);
184 }
185 
186 /*
187  * syslog, vsyslog --
188  *     print message on log file; output is intended for syslogd(8).
189  */
190 static
191 #ifndef __USE_BSD
192 __always_inline
193 #endif
194 void
__vsyslog(int pri,const char * fmt,va_list ap)195 __vsyslog(int pri, const char *fmt, va_list ap)
196 {
197 	register char *p;
198 	char *last_chr, *head_end, *end, *stdp;
199 	time_t now;
200 	int fd, saved_errno;
201 	int rc;
202 	char tbuf[1024]; /* syslogd is unable to handle longer messages */
203 
204 	/* Just throw out this message if pri has bad bits. */
205 	if ((pri & ~(LOG_PRIMASK|LOG_FACMASK)) != 0)
206 		return;
207 
208 	saved_errno = errno;
209 
210 	__UCLIBC_MUTEX_LOCK(mylock);
211 
212 	/* See if we should just throw out this message according to LogMask. */
213 	if ((LogMask & LOG_MASK(LOG_PRI(pri))) == 0)
214 		goto getout;
215 	if (LogFile < 0 || !connected)
216 		openlog_intern();
217 
218 	/* Set default facility if none specified. */
219 	if ((pri & LOG_FACMASK) == 0)
220 		pri |= ((int)LogFacility << 3);
221 
222 	/* Build the message. We know the starting part of the message can take
223 	 * no longer than 64 characters plus length of the LogTag. So it's
224 	 * safe to test only LogTag and use normal sprintf everywhere else.
225 	 */
226 	(void)time(&now);
227 	stdp = p = tbuf + sprintf(tbuf, "<%d>%.15s ", pri, ctime(&now) + 4);
228 	/*if (LogTag) - always true */ {
229 		if (strlen(LogTag) < sizeof(tbuf) - 64)
230 			p += sprintf(p, "%s", LogTag);
231 		else
232 			p += sprintf(p, "<BUFFER OVERRUN ATTEMPT>");
233 	}
234 	if (LogStat & LOG_PID)
235 		p += sprintf(p, "[%d]", getpid());
236 	/*if (LogTag) - always true */ {
237 		*p++ = ':';
238 		*p++ = ' ';
239 	}
240 	head_end = p;
241 
242 	/* We format the rest of the message. If the buffer becomes full, we mark
243 	 * the message as truncated. Note that we require at least 2 free bytes
244 	 * in the buffer as we might want to add "\r\n" there.
245 	 */
246 
247 	end = tbuf + sizeof(tbuf) - 1;
248 	__set_errno(saved_errno);
249 	p += vsnprintf(p, end - p, fmt, ap);
250 	if (p >= end || p < head_end) {	/* Returned -1 in case of error... */
251 		static const char truncate_msg[12] = "[truncated] "; /* no NUL! */
252 		memmove(head_end + sizeof(truncate_msg), head_end,
253 				end - head_end - sizeof(truncate_msg));
254 		memcpy(head_end, truncate_msg, sizeof(truncate_msg));
255 		if (p < head_end) {
256 			while (p < end && *p) {
257 				p++;
258 			}
259 		}
260 		else {
261 			p = end - 1;
262 		}
263 
264 	}
265 	last_chr = p;
266 
267 	/* Output to stderr if requested. */
268 	if (LogStat & LOG_PERROR) {
269 		*last_chr = '\n';
270 		(void)write(STDERR_FILENO, stdp, last_chr - stdp + 1);
271 	}
272 
273 	/* Output the message to the local logger using NUL as a message delimiter. */
274 	p = tbuf;
275 	*last_chr = '\0';
276  retry:
277 	if (LogFile >= 0) {
278 		do {
279 			/* can't just use write, it can result in SIGPIPE */
280 			rc = send(LogFile, p, last_chr + 1 - p, MSG_NOSIGNAL);
281 			if (rc < 0) {
282 				switch (errno) {
283 				case EINTR:
284 					break;
285 				case ECONNRESET:
286 					/* syslogd restarted, reopen log */
287 					closelog_intern(1);
288 					openlog_intern();
289 					goto retry;
290 				case EAGAIN:
291 					/* syslogd stalled, noting we can do */
292 				default:
293 					closelog_intern(1); /* 1: do not reset LogXXX globals to default */
294 					goto write_err;
295 				}
296 				rc = 0;
297 			}
298 			p += rc;
299 		} while (p <= last_chr);
300 		goto getout;
301 	}
302 
303  write_err:
304 	/*
305 	 * Output the message to the console; don't worry about blocking,
306 	 * if console blocks everything will.  Make sure the error reported
307 	 * is the one from the syslogd failure.
308 	 */
309 	/* should mode be O_WRONLY | O_NOCTTY? -- Uli */
310 	/* yes, but in Linux "/dev/console" never becomes ctty anyway -- vda */
311 	if ((LogStat & LOG_CONS) &&
312 	    (fd = open(_PATH_CONSOLE, O_WRONLY | O_NOCTTY)) >= 0) {
313 		p = strchr(tbuf, '>') + 1;
314 		last_chr[0] = '\r';
315 		last_chr[1] = '\n';
316 		(void)write(fd, p, last_chr - p + 2);
317 		(void)close(fd);
318 	}
319 
320  getout:
321 	__UCLIBC_MUTEX_UNLOCK(mylock);
322 }
323 #ifdef __USE_BSD
strong_alias(__vsyslog,vsyslog)324 strong_alias(__vsyslog,vsyslog)
325 #endif
326 
327 void
328 syslog(int pri, const char *fmt, ...)
329 {
330 	va_list ap;
331 
332 	va_start(ap, fmt);
333 	__vsyslog(pri, fmt, ap);
334 	va_end(ap);
335 }
libc_hidden_def(syslog)336 libc_hidden_def(syslog)
337 
338 /*
339  * CLOSELOG -- close the system log
340  */
341 void
342 closelog(void)
343 {
344 	__UCLIBC_MUTEX_LOCK(mylock);
345 	closelog_intern(0); /* 0: reset LogXXX globals to default */
346 	__UCLIBC_MUTEX_UNLOCK(mylock);
347 }
348 
349 /* setlogmask -- set the log mask level */
setlogmask(int pmask)350 int setlogmask(int pmask)
351 {
352 	int omask;
353 
354 	omask = LogMask;
355 	if (pmask != 0) {
356 /*		__UCLIBC_MUTEX_LOCK(mylock);*/
357 		LogMask = pmask;
358 /*		__UCLIBC_MUTEX_UNLOCK(mylock);*/
359 	}
360 	return omask;
361 }
362