Add proper unwind information.
[glibc.git] / misc / syslog.c
blobfac969ae987904151be57837d3ebbc5bd84979a7
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 <stdio_ext.h>
45 #include <string.h>
46 #include <time.h>
47 #include <unistd.h>
48 #include <stdlib.h>
49 #include <bits/libc-lock.h>
50 #include <signal.h>
51 #include <locale.h>
53 #if __STDC__
54 #include <stdarg.h>
55 #else
56 #include <varargs.h>
57 #endif
59 #ifdef USE_IN_LIBIO
60 # include <libio/iolibio.h>
61 # define ftell(s) INTUSE(_IO_ftell) (s)
62 #endif
64 static int LogType = SOCK_DGRAM; /* type of socket connection */
65 static int LogFile = -1; /* fd for log */
66 static int connected; /* have done connect */
67 static int LogStat; /* status bits, set by openlog() */
68 static const char *LogTag; /* string to tag the entry with */
69 static int LogFacility = LOG_USER; /* default facility code */
70 static int LogMask = 0xff; /* mask of priorities to be logged */
71 extern char *__progname; /* Program name, from crt0. */
73 /* Define the lock. */
74 __libc_lock_define_initialized (static, syslog_lock)
76 static void openlog_internal(const char *, int, int) internal_function;
77 static void closelog_internal(void);
78 static void sigpipe_handler (int);
81 struct cleanup_arg
83 void *buf;
84 struct sigaction *oldaction;
87 static void
88 cancel_handler (void *ptr)
90 /* Restore the old signal handler. */
91 struct cleanup_arg *clarg = (struct cleanup_arg *) ptr;
93 if (clarg != NULL && clarg->oldaction != NULL)
94 __sigaction (SIGPIPE, clarg->oldaction, NULL);
96 /* Free the lock. */
97 __libc_lock_unlock (syslog_lock);
102 * syslog, vsyslog --
103 * print message on log file; output is intended for syslogd(8).
105 void
106 #if __STDC__
107 syslog(int pri, const char *fmt, ...)
108 #else
109 syslog(pri, fmt, va_alist)
110 int pri;
111 char *fmt;
112 va_dcl
113 #endif
115 va_list ap;
117 #if __STDC__
118 va_start(ap, fmt);
119 #else
120 va_start(ap);
121 #endif
122 vsyslog(pri, fmt, ap);
123 va_end(ap);
125 libc_hidden_def (syslog)
127 void
128 vsyslog(pri, fmt, ap)
129 int pri;
130 register const char *fmt;
131 va_list ap;
133 struct tm now_tm;
134 time_t now;
135 int fd;
136 FILE *f;
137 char *buf = 0;
138 size_t bufsize = 0;
139 size_t prioff, msgoff;
140 struct sigaction action, oldaction;
141 int sigpipe;
142 int saved_errno = errno;
143 char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];
145 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
146 /* Check for invalid bits. */
147 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
148 syslog(INTERNALLOG,
149 "syslog: unknown facility/priority: %x", pri);
150 pri &= LOG_PRIMASK|LOG_FACMASK;
153 /* Check priority against setlogmask values. */
154 if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
155 return;
157 /* Set default facility if none specified. */
158 if ((pri & LOG_FACMASK) == 0)
159 pri |= LogFacility;
161 /* Build the message in a memory-buffer stream. */
162 f = open_memstream (&buf, &bufsize);
163 if (f == NULL)
165 /* We cannot get a stream. There is not much we can do but
166 emitting an error messages. */
167 char numbuf[3 * sizeof (pid_t)];
168 char *nump;
169 char *endp = __stpcpy (failbuf, "out of memory [");
170 pid_t pid = __getpid ();
172 nump = numbuf + sizeof (numbuf);
173 /* The PID can never be zero. */
175 *--nump = '0' + pid % 10;
176 while ((pid /= 10) != 0);
178 endp = __mempcpy (endp, nump, (nump + sizeof (numbuf)) - nump);
179 *endp++ = ']';
180 *endp = '\0';
181 buf = failbuf;
182 bufsize = endp - failbuf;
183 msgoff = 0;
185 else
187 __fsetlocking (f, FSETLOCKING_BYCALLER);
188 prioff = fprintf (f, "<%d>", pri);
189 (void) time (&now);
190 #ifdef USE_IN_LIBIO
191 f->_IO_write_ptr += __strftime_l (f->_IO_write_ptr,
192 f->_IO_write_end - f->_IO_write_ptr,
193 "%h %e %T ",
194 __localtime_r (&now, &now_tm),
195 &_nl_C_locobj);
196 #else
197 f->__bufp += strftime (f->__bufp, f->__put_limit - f->__bufp,
198 "%h %e %T ", __localtime_r (&now, &now_tm));
199 #endif
200 msgoff = ftell (f);
201 if (LogTag == NULL)
202 LogTag = __progname;
203 if (LogTag != NULL)
204 fputs_unlocked (LogTag, f);
205 if (LogStat & LOG_PID)
206 fprintf (f, "[%d]", (int) __getpid ());
207 if (LogTag != NULL)
209 putc_unlocked (':', f);
210 putc_unlocked (' ', f);
213 /* Restore errno for %m format. */
214 __set_errno (saved_errno);
216 /* We have the header. Print the user's format into the
217 buffer. */
218 vfprintf (f, fmt, ap);
220 /* Close the memory stream; this will finalize the data
221 into a malloc'd buffer in BUF. */
222 fclose (f);
225 /* Output to stderr if requested. */
226 if (LogStat & LOG_PERROR) {
227 struct iovec iov[2];
228 register struct iovec *v = iov;
230 v->iov_base = buf + msgoff;
231 v->iov_len = bufsize - msgoff;
232 /* Append a newline if necessary. */
233 if (buf[bufsize - 1] != '\n')
235 ++v;
236 v->iov_base = (char *) "\n";
237 v->iov_len = 1;
240 __libc_cleanup_push (free, buf);
242 /* writev is a cancellation point. */
243 (void)__writev(STDERR_FILENO, iov, v - iov + 1);
245 __libc_cleanup_pop (0);
248 /* Prepare for multiple users. We have to take care: open and
249 write are cancellation points. */
250 struct cleanup_arg clarg;
251 clarg.buf = buf;
252 clarg.oldaction = NULL;
253 __libc_cleanup_push (cancel_handler, &clarg);
254 __libc_lock_lock (syslog_lock);
256 /* Prepare for a broken connection. */
257 memset (&action, 0, sizeof (action));
258 action.sa_handler = sigpipe_handler;
259 sigemptyset (&action.sa_mask);
260 sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
261 if (sigpipe == 0)
262 clarg.oldaction = &oldaction;
264 /* Get connected, output the message to the local logger. */
265 if (!connected)
266 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
268 /* If we have a SOCK_STREAM connection, also send ASCII NUL as
269 a record terminator. */
270 if (LogType == SOCK_STREAM)
271 ++bufsize;
273 if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
275 if (connected)
277 /* Try to reopen the syslog connection. Maybe it went
278 down. */
279 closelog_internal ();
280 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
283 if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
285 closelog_internal (); /* attempt re-open next time */
287 * Output the message to the console; don't worry
288 * about blocking, if console blocks everything will.
289 * Make sure the error reported is the one from the
290 * syslogd failure.
292 if (LogStat & LOG_CONS &&
293 (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
295 dprintf (fd, "%s\r\n", buf + msgoff);
296 (void)__close(fd);
301 if (sigpipe == 0)
302 __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
304 /* End of critical section. */
305 __libc_cleanup_pop (0);
306 __libc_lock_unlock (syslog_lock);
308 free (buf);
310 libc_hidden_def (vsyslog)
312 static struct sockaddr SyslogAddr; /* AF_UNIX address of local logger */
315 static void
316 internal_function
317 openlog_internal(const char *ident, int logstat, int logfac)
319 if (ident != NULL)
320 LogTag = ident;
321 LogStat = logstat;
322 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
323 LogFacility = logfac;
325 while (1) {
326 if (LogFile == -1) {
327 SyslogAddr.sa_family = AF_UNIX;
328 (void)strncpy(SyslogAddr.sa_data, _PATH_LOG,
329 sizeof(SyslogAddr.sa_data));
330 if (LogStat & LOG_NDELAY) {
331 if ((LogFile = __socket(AF_UNIX, LogType, 0))
332 == -1)
333 return;
334 (void)__fcntl(LogFile, F_SETFD, 1);
337 if (LogFile != -1 && !connected)
339 int old_errno = errno;
340 if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
341 == -1)
343 int saved_errno = errno;
344 int fd = LogFile;
345 LogFile = -1;
346 (void)__close(fd);
347 if (LogType == SOCK_DGRAM
348 && saved_errno == EPROTOTYPE)
350 /* retry with next SOCK_STREAM: */
351 LogType = SOCK_STREAM;
352 __set_errno (old_errno);
353 continue;
355 } else
356 connected = 1;
358 break;
362 void
363 openlog (const char *ident, int logstat, int logfac)
365 /* Protect against multiple users and cancellation. */
366 __libc_cleanup_push (cancel_handler, NULL);
367 __libc_lock_lock (syslog_lock);
369 openlog_internal (ident, logstat, logfac);
371 __libc_cleanup_pop (1);
374 static void
375 sigpipe_handler (int signo)
377 closelog_internal ();
380 static void
381 closelog_internal()
383 if (!connected)
384 return;
386 __close (LogFile);
387 LogFile = -1;
388 connected = 0;
391 void
392 closelog ()
394 /* Protect against multiple users and cancellation. */
395 __libc_cleanup_push (cancel_handler, NULL);
396 __libc_lock_lock (syslog_lock);
398 closelog_internal ();
399 LogTag = NULL;
400 LogType = SOCK_DGRAM; /* this is the default */
402 /* Free the lock. */
403 __libc_cleanup_pop (1);
406 /* setlogmask -- set the log mask level */
408 setlogmask(pmask)
409 int pmask;
411 int omask;
413 omask = LogMask;
414 if (pmask != 0)
415 LogMask = pmask;
416 return (omask);