Update.
[glibc.git] / misc / syslog.c
blobb89055b7b24358e419c58ab3e82344b8590cb12b
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) _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);
106 void
107 vsyslog(pri, fmt, ap)
108 int pri;
109 register const char *fmt;
110 va_list ap;
112 struct tm now_tm;
113 time_t now;
114 int fd;
115 FILE *f;
116 char *buf = 0;
117 size_t bufsize = 0;
118 size_t prioff, msgoff;
119 struct sigaction action, oldaction;
120 struct sigaction *oldaction_ptr = NULL;
121 int sigpipe;
122 int saved_errno = errno;
123 char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];
125 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
126 /* Check for invalid bits. */
127 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
128 syslog(INTERNALLOG,
129 "syslog: unknown facility/priority: %x", pri);
130 pri &= LOG_PRIMASK|LOG_FACMASK;
133 /* Check priority against setlogmask values. */
134 if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
135 return;
137 /* Set default facility if none specified. */
138 if ((pri & LOG_FACMASK) == 0)
139 pri |= LogFacility;
141 /* Build the message in a memory-buffer stream. */
142 f = open_memstream (&buf, &bufsize);
143 if (f == NULL)
145 /* We cannot get a stream. There is not much we can do but
146 emitting an error messages. */
147 char numbuf[3 * sizeof (pid_t)];
148 char *nump;
149 char *endp = __stpcpy (failbuf, "out of memory [");
150 pid_t pid = __getpid ();
152 nump = numbuf + sizeof (numbuf);
153 /* The PID can never be zero. */
155 *--nump = '0' + pid % 10;
156 while ((pid /= 10) != 0);
158 endp = __mempcpy (endp, nump, (nump + sizeof (numbuf)) - nump);
159 *endp++ = ']';
160 *endp = '\0';
161 buf = failbuf;
162 bufsize = endp - failbuf;
163 msgoff = 0;
165 else
167 prioff = fprintf (f, "<%d>", pri);
168 (void) time (&now);
169 #ifdef USE_IN_LIBIO
170 f->_IO_write_ptr += strftime (f->_IO_write_ptr,
171 f->_IO_write_end - f->_IO_write_ptr,
172 "%h %e %T ",
173 __localtime_r (&now, &now_tm));
174 #else
175 f->__bufp += strftime (f->__bufp, f->__put_limit - f->__bufp,
176 "%h %e %T ", __localtime_r (&now, &now_tm));
177 #endif
178 msgoff = ftell (f);
179 if (LogTag == NULL)
180 LogTag = __progname;
181 if (LogTag != NULL)
182 fputs_unlocked (LogTag, f);
183 if (LogStat & LOG_PID)
184 fprintf (f, "[%d]", __getpid ());
185 if (LogTag != NULL)
186 putc_unlocked (':', f), putc_unlocked (' ', f);
188 /* Restore errno for %m format. */
189 __set_errno (saved_errno);
191 /* We have the header. Print the user's format into the
192 buffer. */
193 vfprintf (f, fmt, ap);
195 /* Close the memory stream; this will finalize the data
196 into a malloc'd buffer in BUF. */
197 fclose (f);
200 /* Output to stderr if requested. */
201 if (LogStat & LOG_PERROR) {
202 struct iovec iov[2];
203 register struct iovec *v = iov;
205 v->iov_base = buf + msgoff;
206 v->iov_len = bufsize - msgoff;
207 /* Append a newline if necessary. */
208 if (buf[bufsize - 1] != '\n')
210 ++v;
211 v->iov_base = (char *) "\n";
212 v->iov_len = 1;
214 (void)__writev(STDERR_FILENO, iov, v - iov + 1);
217 /* Prepare for multiple users. We have to take care: open and
218 write are cancellation points. */
219 __libc_cleanup_region_start ((void (*) (void *)) cancel_handler,
220 &oldaction_ptr);
221 __libc_lock_lock (syslog_lock);
223 /* Prepare for a broken connection. */
224 memset (&action, 0, sizeof (action));
225 action.sa_handler = sigpipe_handler;
226 sigemptyset (&action.sa_mask);
227 sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
228 if (sigpipe == 0)
229 oldaction_ptr = &oldaction;
231 /* Get connected, output the message to the local logger. */
232 if (!connected)
233 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
235 /* If we have a SOCK_STREAM connection, also send ASCII NUL as
236 a record terminator. */
237 if (LogType == SOCK_STREAM)
238 ++bufsize;
240 if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
242 closelog_internal (); /* attempt re-open next time */
244 * Output the message to the console; don't worry about blocking,
245 * if console blocks everything will. Make sure the error reported
246 * is the one from the syslogd failure.
248 if (LogStat & LOG_CONS &&
249 (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
251 dprintf (fd, "%s\r\n", buf + msgoff);
252 (void)__close(fd);
256 if (sigpipe == 0)
257 __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
259 /* End of critical section. */
260 __libc_cleanup_region_end (0);
261 __libc_lock_unlock (syslog_lock);
263 free (buf);
266 static struct sockaddr SyslogAddr; /* AF_UNIX address of local logger */
268 static void
269 internal_function
270 openlog_internal(const char *ident, int logstat, int logfac)
272 if (ident != NULL)
273 LogTag = ident;
274 LogStat = logstat;
275 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
276 LogFacility = logfac;
278 while (1) {
279 if (LogFile == -1) {
280 SyslogAddr.sa_family = AF_UNIX;
281 (void)strncpy(SyslogAddr.sa_data, _PATH_LOG,
282 sizeof(SyslogAddr.sa_data));
283 if (LogStat & LOG_NDELAY) {
284 if ((LogFile = __socket(AF_UNIX, LogType, 0))
285 == -1)
286 return;
287 (void)__fcntl(LogFile, F_SETFD, 1);
290 if (LogFile != -1 && !connected)
292 int old_errno = errno;
293 if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
294 == -1)
296 int saved_errno = errno;
297 (void)__close(LogFile);
298 LogFile = -1;
299 if (LogType == SOCK_DGRAM
300 && saved_errno == EPROTOTYPE)
302 /* retry with next SOCK_STREAM: */
303 LogType = SOCK_STREAM;
304 __set_errno (old_errno);
305 continue;
307 } else
308 connected = 1;
310 break;
314 void
315 openlog (const char *ident, int logstat, int logfac)
317 /* Protect against multiple users. */
318 __libc_cleanup_region_start ((void (*) __P ((void *))) __libc_mutex_unlock,
319 &syslog_lock);
320 __libc_lock_lock (syslog_lock);
322 openlog_internal (ident, logstat, logfac);
324 /* Free the lock. */
325 __libc_cleanup_region_end (1);
328 static void
329 sigpipe_handler (int signo)
331 closelog_internal ();
334 static void
335 closelog_internal()
337 if (!connected)
338 return;
340 __close (LogFile);
341 LogFile = -1;
342 connected = 0;
345 void
346 closelog ()
348 /* Protect against multiple users. */
349 __libc_cleanup_region_start ((void (*) __P ((void *))) __libc_mutex_unlock,
350 &syslog_lock);
351 __libc_lock_lock (syslog_lock);
353 closelog_internal ();
354 LogTag = NULL;
355 LogType = SOCK_DGRAM; /* this is the default */
357 /* Free the lock. */
358 __libc_cleanup_region_end (1);
361 #ifdef _LIBC_REENTRANT
362 static void
363 cancel_handler (void *ptr)
365 /* Restore the old signal handler. */
366 struct sigaction *oldaction = *((struct sigaction **) ptr);
368 if (oldaction != (struct sigaction *) NULL)
369 __sigaction (SIGPIPE, oldaction, (struct sigaction *) NULL);
371 /* Free the lock. */
372 __libc_lock_unlock (syslog_lock);
374 #endif
376 /* setlogmask -- set the log mask level */
378 setlogmask(pmask)
379 int pmask;
381 int omask;
383 omask = LogMask;
384 if (pmask != 0)
385 LogMask = pmask;
386 return (omask);