2003-06-27 Jeroen Dekkers <jeroen@dekkers.cx>
[glibc.git] / misc / syslog.c
blobc1fdf5b6b98273f5aa070a13f669825e03e0e362
1 /*
2 * Copyright (c) 1983, 1988, 1993
3 * The Regents of the University of California. All rights reserved.
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 * 4. 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.
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.
30 #if defined(LIBC_SCCS) && !defined(lint)
31 static char sccsid[] = "@(#)syslog.c 8.4 (Berkeley) 3/18/94";
32 #endif /* LIBC_SCCS and not lint */
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/syslog.h>
37 #include <sys/uio.h>
38 #include <netdb.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <paths.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <time.h>
46 #include <unistd.h>
47 #include <stdlib.h>
48 #include <bits/libc-lock.h>
49 #include <signal.h>
51 #if __STDC__
52 #include <stdarg.h>
53 #else
54 #include <varargs.h>
55 #endif
57 #ifdef USE_IN_LIBIO
58 # include <libio/iolibio.h>
59 # define ftell(s) INTUSE(_IO_ftell) (s)
60 #endif
62 static int LogType = SOCK_DGRAM; /* type of socket connection */
63 static int LogFile = -1; /* fd for log */
64 static int connected; /* have done connect */
65 static int LogStat; /* status bits, set by openlog() */
66 static const char *LogTag; /* string to tag the entry with */
67 static int LogFacility = LOG_USER; /* default facility code */
68 static int LogMask = 0xff; /* mask of priorities to be logged */
69 extern char *__progname; /* Program name, from crt0. */
71 /* Define the lock. */
72 __libc_lock_define_initialized (static, syslog_lock)
74 static void openlog_internal(const char *, int, int) internal_function;
75 static void closelog_internal(void);
76 static void sigpipe_handler (int);
77 #ifdef _LIBC_REENTRANT
78 static void cancel_handler (void *);
79 #endif
82 * syslog, vsyslog --
83 * print message on log file; output is intended for syslogd(8).
85 void
86 #if __STDC__
87 syslog(int pri, const char *fmt, ...)
88 #else
89 syslog(pri, fmt, va_alist)
90 int pri;
91 char *fmt;
92 va_dcl
93 #endif
95 va_list ap;
97 #if __STDC__
98 va_start(ap, fmt);
99 #else
100 va_start(ap);
101 #endif
102 vsyslog(pri, fmt, ap);
103 va_end(ap);
105 libc_hidden_def (syslog)
107 void
108 vsyslog(pri, fmt, ap)
109 int pri;
110 register const char *fmt;
111 va_list ap;
113 struct tm now_tm;
114 time_t now;
115 int fd;
116 FILE *f;
117 char *buf = 0;
118 size_t bufsize = 0;
119 size_t prioff, msgoff;
120 struct sigaction action, oldaction;
121 struct sigaction *oldaction_ptr = NULL;
122 int sigpipe;
123 int saved_errno = errno;
124 char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];
126 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
127 /* Check for invalid bits. */
128 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
129 syslog(INTERNALLOG,
130 "syslog: unknown facility/priority: %x", pri);
131 pri &= LOG_PRIMASK|LOG_FACMASK;
134 /* Check priority against setlogmask values. */
135 if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
136 return;
138 /* Set default facility if none specified. */
139 if ((pri & LOG_FACMASK) == 0)
140 pri |= LogFacility;
142 /* Build the message in a memory-buffer stream. */
143 f = open_memstream (&buf, &bufsize);
144 if (f == NULL)
146 /* We cannot get a stream. There is not much we can do but
147 emitting an error messages. */
148 char numbuf[3 * sizeof (pid_t)];
149 char *nump;
150 char *endp = __stpcpy (failbuf, "out of memory [");
151 pid_t pid = __getpid ();
153 nump = numbuf + sizeof (numbuf);
154 /* The PID can never be zero. */
156 *--nump = '0' + pid % 10;
157 while ((pid /= 10) != 0);
159 endp = __mempcpy (endp, nump, (nump + sizeof (numbuf)) - nump);
160 *endp++ = ']';
161 *endp = '\0';
162 buf = failbuf;
163 bufsize = endp - failbuf;
164 msgoff = 0;
166 else
168 prioff = fprintf (f, "<%d>", pri);
169 (void) time (&now);
170 #ifdef USE_IN_LIBIO
171 f->_IO_write_ptr += strftime (f->_IO_write_ptr,
172 f->_IO_write_end - f->_IO_write_ptr,
173 "%h %e %T ",
174 __localtime_r (&now, &now_tm));
175 #else
176 f->__bufp += strftime (f->__bufp, f->__put_limit - f->__bufp,
177 "%h %e %T ", __localtime_r (&now, &now_tm));
178 #endif
179 msgoff = ftell (f);
180 if (LogTag == NULL)
181 LogTag = __progname;
182 if (LogTag != NULL)
183 fputs_unlocked (LogTag, f);
184 if (LogStat & LOG_PID)
185 fprintf (f, "[%d]", __getpid ());
186 if (LogTag != NULL)
187 putc_unlocked (':', f), putc_unlocked (' ', f);
189 /* Restore errno for %m format. */
190 __set_errno (saved_errno);
192 /* We have the header. Print the user's format into the
193 buffer. */
194 vfprintf (f, fmt, ap);
196 /* Close the memory stream; this will finalize the data
197 into a malloc'd buffer in BUF. */
198 fclose (f);
201 /* Output to stderr if requested. */
202 if (LogStat & LOG_PERROR) {
203 struct iovec iov[2];
204 register struct iovec *v = iov;
206 v->iov_base = buf + msgoff;
207 v->iov_len = bufsize - msgoff;
208 /* Append a newline if necessary. */
209 if (buf[bufsize - 1] != '\n')
211 ++v;
212 v->iov_base = (char *) "\n";
213 v->iov_len = 1;
215 (void)__writev(STDERR_FILENO, iov, v - iov + 1);
218 #ifdef _LIBC_REENTRANT
219 /* Prepare for multiple users. We have to take care: open and
220 write are cancellation points. */
221 __libc_cleanup_region_start (1, (void (*) (void *)) cancel_handler,
222 &oldaction_ptr);
223 __libc_lock_lock (syslog_lock);
224 #endif
226 /* Prepare for a broken connection. */
227 memset (&action, 0, sizeof (action));
228 action.sa_handler = sigpipe_handler;
229 sigemptyset (&action.sa_mask);
230 sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
231 if (sigpipe == 0)
232 oldaction_ptr = &oldaction;
234 /* Get connected, output the message to the local logger. */
235 if (!connected)
236 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
238 /* If we have a SOCK_STREAM connection, also send ASCII NUL as
239 a record terminator. */
240 if (LogType == SOCK_STREAM)
241 ++bufsize;
243 if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
245 if (connected)
247 /* Try to reopen the syslog connection. Maybe it went
248 down. */
249 closelog_internal ();
250 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
253 if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
255 closelog_internal (); /* attempt re-open next time */
257 * Output the message to the console; don't worry
258 * about blocking, if console blocks everything will.
259 * Make sure the error reported is the one from the
260 * syslogd failure.
262 if (LogStat & LOG_CONS &&
263 (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
265 dprintf (fd, "%s\r\n", buf + msgoff);
266 (void)__close(fd);
271 if (sigpipe == 0)
272 __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
274 #ifdef _LIBC_REENTRANT
275 /* End of critical section. */
276 __libc_cleanup_region_end (0);
277 __libc_lock_unlock (syslog_lock);
278 #endif
280 free (buf);
282 libc_hidden_def (vsyslog)
284 static struct sockaddr SyslogAddr; /* AF_UNIX address of local logger */
286 static void
287 internal_function
288 openlog_internal(const char *ident, int logstat, int logfac)
290 if (ident != NULL)
291 LogTag = ident;
292 LogStat = logstat;
293 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
294 LogFacility = logfac;
296 while (1) {
297 if (LogFile == -1) {
298 SyslogAddr.sa_family = AF_UNIX;
299 (void)strncpy(SyslogAddr.sa_data, _PATH_LOG,
300 sizeof(SyslogAddr.sa_data));
301 if (LogStat & LOG_NDELAY) {
302 if ((LogFile = __socket(AF_UNIX, LogType, 0))
303 == -1)
304 return;
305 (void)__fcntl(LogFile, F_SETFD, 1);
308 if (LogFile != -1 && !connected)
310 int old_errno = errno;
311 if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
312 == -1)
314 int saved_errno = errno;
315 (void)__close(LogFile);
316 LogFile = -1;
317 if (LogType == SOCK_DGRAM
318 && saved_errno == EPROTOTYPE)
320 /* retry with next SOCK_STREAM: */
321 LogType = SOCK_STREAM;
322 __set_errno (old_errno);
323 continue;
325 } else
326 connected = 1;
328 break;
333 static void
334 log_cleanup (void *arg)
336 __libc_lock_unlock (syslog_lock);
339 void
340 openlog (const char *ident, int logstat, int logfac)
342 #ifdef _LIBC_REENTRANT
343 /* Protect against multiple users. */
344 __libc_cleanup_region_start (1, log_cleanup, NULL);
345 __libc_lock_lock (syslog_lock);
346 #endif
348 openlog_internal (ident, logstat, logfac);
350 #ifdef _LIBC_REENTRANT
351 /* Free the lock. */
352 __libc_cleanup_region_end (1);
353 #endif
356 static void
357 sigpipe_handler (int signo)
359 closelog_internal ();
362 static void
363 closelog_internal()
365 if (!connected)
366 return;
368 __close (LogFile);
369 LogFile = -1;
370 connected = 0;
373 void
374 closelog ()
376 #ifdef _LIBC_REENTRANT
377 /* Protect against multiple users. */
378 __libc_cleanup_region_start (1, log_cleanup, NULL);
379 __libc_lock_lock (syslog_lock);
380 #endif
382 closelog_internal ();
383 LogTag = NULL;
384 LogType = SOCK_DGRAM; /* this is the default */
386 #ifdef _LIBC_REENTRANT
387 /* Free the lock. */
388 __libc_cleanup_region_end (1);
389 #endif
392 #ifdef _LIBC_REENTRANT
393 static void
394 cancel_handler (void *ptr)
396 /* Restore the old signal handler. */
397 struct sigaction *oldaction = *((struct sigaction **) ptr);
399 if (oldaction != (struct sigaction *) NULL)
400 __sigaction (SIGPIPE, oldaction, (struct sigaction *) NULL);
402 /* Free the lock. */
403 __libc_lock_unlock (syslog_lock);
405 #endif
407 /* setlogmask -- set the log mask level */
409 setlogmask(pmask)
410 int pmask;
412 int omask;
414 omask = LogMask;
415 if (pmask != 0)
416 LogMask = pmask;
417 return (omask);