xref: /titanic_41/usr/src/lib/libc/port/gen/syslog.c (revision 1dd08564e4a3aafe66b00aee6f222b0885346fe8)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1988 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 /*
31  * University Copyright- Copyright (c) 1982, 1986, 1988
32  * The Regents of the University of California
33  * All Rights Reserved
34  *
35  * University Acknowledgment- Portions of this document are derived from
36  * software developed by the University of California, Berkeley, and its
37  * contributors.
38  */
39 
40 #pragma ident	"%Z%%M%	%I%	%E% SMI"
41 
42 /*
43  * SYSLOG -- print message on log file
44  *
45  * This routine looks a lot like printf, except that it
46  * outputs to the log file instead of the standard output.
47  * Also:
48  *	adds a timestamp,
49  *	prints the module name in front of the message,
50  *	has some other formatting types (or will sometime),
51  *	adds a newline on the end of the message.
52  *
53  * The output of this routine is intended to be read by /etc/syslogd.
54  */
55 
56 #pragma weak _syslog = syslog
57 
58 #include "lint.h"
59 #include <sys/types.h>
60 #include <sys/types32.h>
61 #include <sys/mman.h>
62 #include <sys/stropts.h>
63 #include <sys/strlog.h>
64 #include <sys/log.h>		/* for LOG_MAXPS */
65 #include <stdlib.h>
66 #include <procfs.h>
67 #include <syslog.h>
68 #include <signal.h>
69 #include <fcntl.h>
70 #include <string.h>
71 #include <stdarg.h>
72 #include <unistd.h>
73 #include <wait.h>
74 #include <stdio.h>
75 #include <string.h>
76 #include <errno.h>
77 #include <thread.h>
78 #include <synch.h>
79 #include <sys/door.h>
80 #include <sys/stat.h>
81 #include <stropts.h>
82 #include <sys/fork.h>
83 #include <sys/wait.h>
84 #include "libc.h"
85 
86 #define	MAXLINE		1024		/* max message size (but see below) */
87 
88 #define	PRIMASK(p)	(1 << ((p) & LOG_PRIMASK))
89 #define	PRIFAC(p)	(((p) & LOG_FACMASK) >> 3)
90 #define	IMPORTANT 	LOG_ERR
91 
92 #ifndef FALSE
93 #define	FALSE 	0
94 #endif
95 
96 #ifndef TRUE
97 #define	TRUE	1
98 #endif
99 
100 #define	logname		"/dev/conslog"
101 #define	ctty		"/dev/syscon"
102 #define	sysmsg		"/dev/sysmsg"
103 
104 #define	DOORFILE	"/var/run/syslog_door"
105 
106 static struct __syslog {
107 	int	_LogFile;
108 	int	_LogStat;
109 	const char *_LogTag;
110 	int	_LogMask;
111 	char	*_SyslogHost;
112 	int	_LogFacility;
113 	int	_LogFileInvalid;
114 	int	_OpenLogCalled;
115 	dev_t   _LogDev;
116 	char	_ProcName[PRFNSZ + 1];
117 } __syslog = {
118 	-1,		/* fd for log */
119 	0,		/* status bits, set by openlog() */
120 	"syslog",	/* string to tag the entry with */
121 	0xff,		/* mask of priorities to be logged */
122 	NULL,
123 	LOG_USER,	/* default facility code */
124 	FALSE,		/* check for validity of fd for log */
125 	0,		/* openlog has not yet been called */
126 };
127 
128 #define	LogFile (__syslog._LogFile)
129 #define	LogStat (__syslog._LogStat)
130 #define	LogTag (__syslog._LogTag)
131 #define	LogMask (__syslog._LogMask)
132 #define	SyslogHost (__syslog._SyslogHost)
133 #define	LogFacility (__syslog._LogFacility)
134 #define	LogFileInvalid (__syslog._LogFileInvalid)
135 #define	OpenLogCalled (__syslog._OpenLogCalled)
136 #define	LogDev (__syslog._LogDev)
137 #define	ProcName (__syslog._ProcName)
138 
139 static int syslogd_ok(void);
140 
141 /*
142  * Regrettably, there are several instances inside libc where
143  * syslog() is called from the bottom of a deep call stack
144  * and a critical lock was acquired near the top of the stack.
145  *
146  * Because syslog() uses stdio (and it is called from within stdio)
147  * it runs the danger of deadlocking, perhaps with an interposed
148  * malloc() when fork() is occurring concurrently, perhaps with
149  * some other lock within libc.
150  *
151  * The only fix for this problem is to restructure libc not to do
152  * this thing and always to call syslog() with no locks held.
153  * This restructuring will require a substantial effort.
154  *
155  * Meanwhile, we just hope that on the rare occasion that syslog()
156  * is called from within libc (such occurrences should "never happen")
157  * that we don't get caught in a race condition deadlock.
158  */
159 void
160 syslog(int pri, const char *fmt, ...)
161 {
162 	va_list ap;
163 
164 	va_start(ap, fmt);
165 	vsyslog(pri, fmt, ap);
166 	va_end(ap);
167 }
168 
169 
170 void
171 vsyslog(int pri, const char *fmt, va_list ap)
172 {
173 	char *b, *f, *o;
174 	char c;
175 	int clen;
176 	char buf[MAXLINE + 2];
177 	char outline[MAXLINE + 256];  /* pad to allow date, system name... */
178 	time_t now;
179 	pid_t pid;
180 	struct log_ctl hdr;
181 	struct strbuf dat;
182 	struct strbuf ctl;
183 	char timestr[26];	/* hardwired value 26 due to Posix */
184 	size_t taglen;
185 	int olderrno = errno;
186 	struct stat statbuff;
187 	int procfd;
188 	char procfile[32];
189 	psinfo_t p;
190 	int showpid;
191 	uint32_t msgid;
192 	char *msgid_start, *msgid_end;
193 	int nowait;
194 
195 /*
196  * Maximum tag length is 256 (the pad in outline) minus the size of the
197  * other things that can go in the pad.
198  */
199 #define	MAX_TAG		230
200 
201 	/* see if we should just throw out this message */
202 	if (pri < 0 || PRIFAC(pri) >= LOG_NFACILITIES ||
203 	    (PRIMASK(pri) & LogMask) == 0)
204 		return;
205 
206 	if (LogFileInvalid)
207 		return;
208 
209 	/*
210 	 * if openlog() has not been called by the application,
211 	 * try to get the name of the application and set it
212 	 * as the ident string for messages. If unable to get
213 	 * it for any reason, fall back to using the default
214 	 * of syslog. If we succeed in getting the name, also
215 	 * turn on LOG_PID, to provide greater detail.
216 	 */
217 	showpid = 0;
218 	if (OpenLogCalled == 0) {
219 		(void) sprintf(procfile, "/proc/%d/psinfo", getpid());
220 		if ((procfd = open(procfile, O_RDONLY)) >= 0) {
221 			if (read(procfd, &p, sizeof (psinfo_t)) >= 0) {
222 				(void) strncpy(ProcName, p.pr_fname, PRFNSZ);
223 				LogTag = (const char *) &ProcName;
224 				showpid = LOG_PID;
225 			}
226 			(void) close(procfd);
227 		}
228 	}
229 	if (LogFile < 0)
230 		openlog(LogTag, LogStat|LOG_NDELAY|showpid, 0);
231 
232 	if ((fstat(LogFile, &statbuff) != 0) ||
233 	    (!S_ISCHR(statbuff.st_mode)) || (statbuff.st_rdev != LogDev)) {
234 		LogFileInvalid = TRUE;
235 		return;
236 	}
237 
238 	/* set default facility if none specified */
239 	if ((pri & LOG_FACMASK) == 0)
240 		pri |= LogFacility;
241 
242 	/* build the header */
243 	hdr.pri = pri;
244 	hdr.flags = SL_CONSOLE;
245 	hdr.level = 0;
246 
247 	/* build the message */
248 	/*
249 	 * To avoid potential security problems, bounds checking is done
250 	 * on outline and buf.
251 	 * The following code presumes that the header information will
252 	 * fit in 250-odd bytes, as was accounted for in the buffer size
253 	 * allocation.  This is dependent on the assumption that the LogTag
254 	 * and the string returned by sprintf() for getpid() will return
255 	 * be less than 230-odd characters combined.
256 	 */
257 	o = outline;
258 	(void) time(&now);
259 	(void) sprintf(o, "%.15s ", ctime_r(&now, timestr, 26) + 4);
260 	o += strlen(o);
261 
262 	if (LogTag) {
263 		taglen = strlen(LogTag) < MAX_TAG ? strlen(LogTag) : MAX_TAG;
264 		(void) strncpy(o, LogTag, taglen);
265 		o[taglen] = '\0';
266 		o += strlen(o);
267 	}
268 	if (LogStat & LOG_PID) {
269 		(void) sprintf(o, "[%d]", getpid());
270 		o += strlen(o);
271 	}
272 	if (LogTag) {
273 		(void) strcpy(o, ": ");
274 		o += 2;
275 	}
276 
277 	STRLOG_MAKE_MSGID(fmt, msgid);
278 	(void) sprintf(o, "[ID %u FACILITY_AND_PRIORITY] ", msgid);
279 	o += strlen(o);
280 
281 	b = buf;
282 	f = (char *)fmt;
283 	while ((c = *f++) != '\0' && b < &buf[MAXLINE]) {
284 		char *errmsg;
285 		if (c != '%') {
286 			*b++ = c;
287 			continue;
288 		}
289 		if ((c = *f++) != 'm') {
290 			*b++ = '%';
291 			*b++ = c;
292 			continue;
293 		}
294 		if ((errmsg = strerror(olderrno)) == NULL)
295 			(void) snprintf(b, &buf[MAXLINE] - b, "error %d",
296 			    olderrno);
297 		else {
298 			while (*errmsg != '\0' && b < &buf[MAXLINE]) {
299 				if (*errmsg == '%') {
300 					(void) strcpy(b, "%%");
301 					b += 2;
302 				}
303 				else
304 					*b++ = *errmsg;
305 				errmsg++;
306 			}
307 			*b = '\0';
308 		}
309 		b += strlen(b);
310 	}
311 	if (b > buf && *(b-1) != '\n')	/* ensure at least one newline */
312 		*b++ = '\n';
313 	*b = '\0';
314 	/* LINTED variable format specifier */
315 	(void) vsnprintf(o, &outline[sizeof (outline)] - o, buf, ap);
316 	clen  = (int)strlen(outline) + 1;	/* add one for NULL byte */
317 	if (clen > MAXLINE) {
318 		clen = MAXLINE;
319 		outline[MAXLINE-1] = '\0';
320 	}
321 
322 	/*
323 	 * 1136432 points out that the underlying log driver actually
324 	 * refuses to accept (ERANGE) messages longer than LOG_MAXPS
325 	 * bytes.  So it really doesn't make much sense to putmsg a
326 	 * longer message..
327 	 */
328 	if (clen > LOG_MAXPS) {
329 		clen = LOG_MAXPS;
330 		outline[LOG_MAXPS-1] = '\0';
331 	}
332 
333 	/* set up the strbufs */
334 	ctl.maxlen = sizeof (struct log_ctl);
335 	ctl.len = sizeof (struct log_ctl);
336 	ctl.buf = (caddr_t)&hdr;
337 	dat.maxlen = sizeof (outline);
338 	dat.len = clen;
339 	dat.buf = outline;
340 
341 	/* output the message to the local logger */
342 	if ((putmsg(LogFile, &ctl, &dat, 0) >= 0) && syslogd_ok())
343 		return;
344 	if (!(LogStat & LOG_CONS))
345 		return;
346 
347 	/*
348 	 * Output the message to the console directly.  To reduce visual
349 	 * clutter, we strip out the message ID.
350 	 */
351 	if ((msgid_start = strstr(outline, "[ID ")) != NULL &&
352 	    (msgid_end = strstr(msgid_start, "] ")) != NULL)
353 		(void) strcpy(msgid_start, msgid_end + 2);
354 
355 	clen = strlen(outline) + 1;
356 
357 	nowait = (LogStat & LOG_NOWAIT);
358 	pid = forkx(nowait? 0 : (FORK_NOSIGCHLD | FORK_WAITPID));
359 	if (pid == -1)
360 		return;
361 
362 	if (pid == 0) {
363 		sigset_t sigs;
364 		int fd;
365 
366 		(void) sigset(SIGALRM, SIG_DFL);
367 		(void) sigemptyset(&sigs);
368 		(void) sigaddset(&sigs, SIGALRM);
369 		(void) sigprocmask(SIG_UNBLOCK, &sigs, NULL);
370 		(void) alarm(5);
371 		if (((fd = open(sysmsg, O_WRONLY)) >= 0) ||
372 		    (fd = open(ctty, O_WRONLY)) >= 0) {
373 			(void) alarm(0);
374 			outline[clen - 1] = '\r';
375 			(void) write(fd, outline, clen);
376 			(void) close(fd);
377 		}
378 		_exit(0);
379 	}
380 	if (!nowait)
381 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
382 			continue;
383 }
384 
385 /*
386  * Use a door call to syslogd to see if it's alive.
387  */
388 static int
389 syslogd_ok(void)
390 {
391 	int d;
392 	int s;
393 	door_arg_t darg;
394 	door_info_t info;
395 
396 	if ((d = open(DOORFILE, O_RDONLY)) < 0)
397 		return (0);
398 	/*
399 	 * see if our pid matches the pid of the door server.
400 	 * If so, syslogd has called syslog(), probably as
401 	 * a result of some name service library error, and
402 	 * we don't want to let syslog continue and possibly
403 	 * fork here.
404 	 */
405 	info.di_target = 0;
406 	if (__door_info(d, &info) < 0 || info.di_target == getpid()) {
407 		(void) close(d);
408 		return (0);
409 	}
410 	darg.data_ptr = NULL;
411 	darg.data_size = 0;
412 	darg.desc_ptr = NULL;
413 	darg.desc_num = 0;
414 	darg.rbuf = NULL;
415 	darg.rsize = 0;
416 	s = __door_call(d, &darg);
417 	(void) close(d);
418 	if (s < 0)
419 		return (0);		/* failure - syslogd dead */
420 	else
421 		return (1);
422 }
423 
424 /*
425  * OPENLOG -- open system log
426  */
427 
428 void
429 openlog(const char *ident, int logstat, int logfac)
430 {
431 	struct	stat	statbuff;
432 
433 	OpenLogCalled = 1;
434 	if (ident != NULL)
435 		LogTag = ident;
436 	LogStat = logstat;
437 	if (logfac != 0)
438 		LogFacility = logfac & LOG_FACMASK;
439 
440 	/*
441 	 * if the fstat(2) fails or the st_rdev has changed
442 	 * then we must open the file
443 	 */
444 	if ((fstat(LogFile, &statbuff) == 0) &&
445 	    (S_ISCHR(statbuff.st_mode)) && (statbuff.st_rdev == LogDev))
446 		return;
447 
448 	if (LogStat & LOG_NDELAY) {
449 		LogFile = open(logname, O_WRONLY);
450 		(void) fcntl(LogFile, F_SETFD, 1);
451 		(void) fstat(LogFile, &statbuff);
452 		LogDev = statbuff.st_rdev;
453 	}
454 }
455 
456 /*
457  * CLOSELOG -- close the system log
458  */
459 
460 void
461 closelog(void)
462 {
463 	struct	stat	statbuff;
464 
465 	OpenLogCalled = 0;
466 
467 	/* if the LogFile is invalid it can not be closed */
468 	if (LogFileInvalid)
469 		return;
470 
471 	/*
472 	 * if the fstat(2) fails or the st_rdev has changed
473 	 * then we can not close the file
474 	 */
475 	if ((fstat(LogFile, &statbuff) == 0) && (statbuff.st_rdev == LogDev)) {
476 		(void) close(LogFile);
477 		LogFile = -1;
478 		LogStat = 0;
479 	}
480 }
481 
482 /*
483  * SETLOGMASK -- set the log mask level
484  */
485 int
486 setlogmask(int pmask)
487 {
488 	int omask = 0;
489 
490 	omask = LogMask;
491 	if (pmask != 0)
492 		LogMask = pmask;
493 	return (omask);
494 }
495