Update.
[jlayton/glibc.git] / misc / syslog.c
1 /*
2  * Copyright (c) 1983, 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #if defined(LIBC_SCCS) && !defined(lint)
35 static char sccsid[] = "@(#)syslog.c    8.4 (Berkeley) 3/18/94";
36 #endif /* LIBC_SCCS and not lint */
37
38 #include <sys/types.h>
39 #include <sys/socket.h>
40 #include <sys/syslog.h>
41 #include <sys/uio.h>
42 #include <netdb.h>
43
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <paths.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <time.h>
50 #include <unistd.h>
51 #include <stdlib.h>
52 #include <bits/libc-lock.h>
53 #include <signal.h>
54
55 #if __STDC__
56 #include <stdarg.h>
57 #else
58 #include <varargs.h>
59 #endif
60
61 #ifdef USE_IN_LIBIO
62 # include <libio/iolibio.h>
63 # define ftell(s) _IO_ftell (s)
64 #endif
65
66 static int      LogType = SOCK_DGRAM;   /* type of socket connection */
67 static int      LogFile = -1;           /* fd for log */
68 static int      connected;              /* have done connect */
69 static int      LogStat = 0;            /* status bits, set by openlog() */
70 static const char *LogTag = NULL;       /* string to tag the entry with */
71 static int      LogFacility = LOG_USER; /* default facility code */
72 static int      LogMask = 0xff;         /* mask of priorities to be logged */
73 extern char     *__progname;            /* Program name, from crt0. */
74
75 /* Define the lock.  */
76 __libc_lock_define_initialized (static, syslog_lock)
77
78 static void openlog_internal(const char *, int, int) internal_function;
79 static void closelog_internal(void);
80 static void sigpipe_handler (int);
81 #ifdef _LIBC_REENTRANT
82 static void cancel_handler (void *);
83 #endif
84
85 /*
86  * syslog, vsyslog --
87  *      print message on log file; output is intended for syslogd(8).
88  */
89 void
90 #if __STDC__
91 syslog(int pri, const char *fmt, ...)
92 #else
93 syslog(pri, fmt, va_alist)
94         int pri;
95         char *fmt;
96         va_dcl
97 #endif
98 {
99         va_list ap;
100
101 #if __STDC__
102         va_start(ap, fmt);
103 #else
104         va_start(ap);
105 #endif
106         vsyslog(pri, fmt, ap);
107         va_end(ap);
108 }
109
110 void
111 vsyslog(pri, fmt, ap)
112         int pri;
113         register const char *fmt;
114         va_list ap;
115 {
116         struct tm now_tm;
117         time_t now;
118         int fd;
119         FILE *f;
120         char *buf = 0;
121         size_t bufsize = 0;
122         size_t prioff, msgoff;
123         struct sigaction action, oldaction;
124         struct sigaction *oldaction_ptr = NULL;
125         int sigpipe;
126         int saved_errno = errno;
127
128 #define INTERNALLOG     LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
129         /* Check for invalid bits. */
130         if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
131                 syslog(INTERNALLOG,
132                     "syslog: unknown facility/priority: %x", pri);
133                 pri &= LOG_PRIMASK|LOG_FACMASK;
134         }
135
136         /* Check priority against setlogmask values. */
137         if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
138                 return;
139
140         /* Set default facility if none specified. */
141         if ((pri & LOG_FACMASK) == 0)
142                 pri |= LogFacility;
143
144         /* Build the message in a memory-buffer stream.  */
145         f = open_memstream (&buf, &bufsize);
146         prioff = fprintf (f, "<%d>", pri);
147         (void) time (&now);
148 #ifdef USE_IN_LIBIO
149         f->_IO_write_ptr += strftime (f->_IO_write_ptr,
150                                       f->_IO_write_end - f->_IO_write_ptr,
151                                       "%h %e %T ",
152                                       __localtime_r (&now, &now_tm));
153 #else
154         f->__bufp += strftime (f->__bufp, f->__put_limit - f->__bufp,
155                                "%h %e %T ", __localtime_r (&now, &now_tm));
156 #endif
157         msgoff = ftell (f);
158         if (LogTag == NULL)
159           LogTag = __progname;
160         if (LogTag != NULL)
161           fputs_unlocked (LogTag, f);
162         if (LogStat & LOG_PID)
163           fprintf (f, "[%d]", __getpid ());
164         if (LogTag != NULL)
165           putc_unlocked (':', f), putc_unlocked (' ', f);
166
167         /* Restore errno for %m format.  */
168         __set_errno (saved_errno);
169
170         /* We have the header.  Print the user's format into the buffer.  */
171         vfprintf (f, fmt, ap);
172
173         /* Close the memory stream; this will finalize the data
174            into a malloc'd buffer in BUF.  */
175         fclose (f);
176
177         /* Output to stderr if requested. */
178         if (LogStat & LOG_PERROR) {
179                 struct iovec iov[2];
180                 register struct iovec *v = iov;
181
182                 v->iov_base = buf + msgoff;
183                 v->iov_len = bufsize - msgoff;
184                 ++v;
185                 v->iov_base = (char *) "\n";
186                 v->iov_len = 1;
187                 (void)__writev(STDERR_FILENO, iov, 2);
188         }
189
190         /* Prepare for multiple users.  We have to take care: open and
191            write are cancellation points.  */
192         __libc_cleanup_region_start ((void (*) (void *)) cancel_handler,
193                                      &oldaction_ptr);
194         __libc_lock_lock (syslog_lock);
195
196         /* Prepare for a broken connection.  */
197         memset (&action, 0, sizeof (action));
198         action.sa_handler = sigpipe_handler;
199         sigemptyset (&action.sa_mask);
200         sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
201         if (sigpipe == 0)
202           oldaction_ptr = &oldaction;
203
204         /* Get connected, output the message to the local logger. */
205         if (!connected)
206                 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
207
208         /* If we have a SOCK_STREAM connection, also send ASCII NUL as
209            a record terminator.  */
210         if (LogType == SOCK_STREAM)
211           ++bufsize;
212
213         if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
214           {
215             closelog_internal ();       /* attempt re-open next time */
216             /*
217              * Output the message to the console; don't worry about blocking,
218              * if console blocks everything will.  Make sure the error reported
219              * is the one from the syslogd failure.
220              */
221             if (LogStat & LOG_CONS &&
222                 (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
223               {
224                 dprintf (fd, "%s\r\n", buf + msgoff);
225                 (void)__close(fd);
226               }
227           }
228
229         if (sigpipe == 0)
230                 __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
231
232         /* End of critical section.  */
233         __libc_cleanup_region_end (0);
234         __libc_lock_unlock (syslog_lock);
235
236         free (buf);
237 }
238
239 static struct sockaddr SyslogAddr;      /* AF_UNIX address of local logger */
240
241 static void
242 internal_function
243 openlog_internal(const char *ident, int logstat, int logfac)
244 {
245         if (ident != NULL)
246                 LogTag = ident;
247         LogStat = logstat;
248         if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
249                 LogFacility = logfac;
250
251         while (1) {
252                 if (LogFile == -1) {
253                         SyslogAddr.sa_family = AF_UNIX;
254                         (void)strncpy(SyslogAddr.sa_data, _PATH_LOG,
255                                       sizeof(SyslogAddr.sa_data));
256                         if (LogStat & LOG_NDELAY) {
257                                 if ((LogFile = __socket(AF_UNIX, LogType, 0))
258                                     == -1)
259                                         return;
260                                 (void)__fcntl(LogFile, F_SETFD, 1);
261                         }
262                 }
263                 if (LogFile != -1 && !connected)
264                 {
265                         int old_errno = errno;
266                         if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
267                             == -1)
268                         {
269                                 int saved_errno = errno;
270                                 (void)__close(LogFile);
271                                 LogFile = -1;
272                                 if (LogType == SOCK_DGRAM
273                                     && saved_errno == EPROTOTYPE)
274                                 {
275                                         /* retry with next SOCK_STREAM: */
276                                         LogType = SOCK_STREAM;
277                                         __set_errno (old_errno);
278                                         continue;
279                                 }
280                         } else
281                                 connected = 1;
282                 }
283                 break;
284         }
285 }
286
287 void
288 openlog (const char *ident, int logstat, int logfac)
289 {
290   /* Protect against multiple users.  */
291   __libc_cleanup_region_start ((void (*) __P ((void *))) __libc_mutex_unlock,
292                                &syslog_lock);
293   __libc_lock_lock (syslog_lock);
294
295   openlog_internal (ident, logstat, logfac);
296
297   /* Free the lock.  */
298   __libc_cleanup_region_end (1);
299 }
300
301 static void
302 sigpipe_handler (int signo)
303 {
304   closelog_internal ();
305 }
306
307 static void
308 closelog_internal()
309 {
310   if (!connected)
311     return;
312
313   __close (LogFile);
314   LogFile = -1;
315   connected = 0;
316 }
317
318 void
319 closelog ()
320 {
321   /* Protect against multiple users.  */
322   __libc_cleanup_region_start ((void (*) __P ((void *))) __libc_mutex_unlock,
323                                &syslog_lock);
324   __libc_lock_lock (syslog_lock);
325
326   closelog_internal ();
327   LogTag = NULL;
328
329   /* Free the lock.  */
330   __libc_cleanup_region_end (1);
331 }
332
333 #ifdef _LIBC_REENTRANT
334 static void
335 cancel_handler (void *ptr)
336 {
337   /* Restore the old signal handler.  */
338   struct sigaction *oldaction = *((struct sigaction **) ptr);
339
340   if (oldaction != (struct sigaction *) NULL)
341     __sigaction (SIGPIPE, oldaction, (struct sigaction *) NULL);
342
343   /* Free the lock.  */
344   __libc_lock_unlock (syslog_lock);
345 }
346 #endif
347
348 /* setlogmask -- set the log mask level */
349 int
350 setlogmask(pmask)
351         int pmask;
352 {
353         int omask;
354
355         omask = LogMask;
356         if (pmask != 0)
357                 LogMask = pmask;
358         return (omask);
359 }