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