* Removed the __P macros from lib/
[dragonfly.git] / lib / libc / gen / 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  * @(#)syslog.c 8.5 (Berkeley) 4/29/95
34  * $FreeBSD: src/lib/libc/gen/syslog.c,v 1.21.2.3 2002/11/18 11:49:55 ru Exp $
35  * $DragonFly: src/lib/libc/gen/syslog.c,v 1.3 2003/11/12 20:21:23 eirikn Exp $
36  */
37
38 #include <sys/types.h>
39 #include <sys/socket.h>
40 #include <sys/syslog.h>
41 #include <sys/uio.h>
42 #include <sys/un.h>
43 #include <netdb.h>
44
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <paths.h>
48 #include <stdio.h>
49 #include <string.h>
50 #include <time.h>
51 #include <unistd.h>
52
53 #if __STDC__
54 #include <stdarg.h>
55 #else
56 #include <varargs.h>
57 #endif
58
59 static int      LogFile = -1;           /* fd for log */
60 static int      connected;              /* have done connect */
61 static int      opened;                 /* have done openlog() */
62 static int      LogStat = 0;            /* status bits, set by openlog() */
63 static const char *LogTag = NULL;       /* string to tag the entry with */
64 static int      LogFacility = LOG_USER; /* default facility code */
65 static int      LogMask = 0xff;         /* mask of priorities to be logged */
66 extern char     *__progname;            /* Program name, from crt0. */
67
68 static void     disconnectlog (void); /* disconnect from syslogd */
69 static void     connectlog (void);      /* (re)connect to syslogd */
70
71 /*
72  * Format of the magic cookie passed through the stdio hook
73  */
74 struct bufcookie {
75         char    *base;  /* start of buffer */
76         int     left;
77 };
78
79 /*
80  * stdio write hook for writing to a static string buffer
81  * XXX: Maybe one day, dynamically allocate it so that the line length
82  *      is `unlimited'.
83  */
84 static
85 int writehook(cookie, buf, len)
86         void    *cookie;        /* really [struct bufcookie *] */
87         char    *buf;           /* characters to copy */
88         int     len;            /* length to copy */
89 {
90         struct bufcookie *h;    /* private `handle' */
91
92         h = (struct bufcookie *)cookie;
93         if (len > h->left) {
94                 /* clip in case of wraparound */
95                 len = h->left;
96         }
97         if (len > 0) {
98                 (void)memcpy(h->base, buf, len); /* `write' it. */
99                 h->base += len;
100                 h->left -= len;
101         }
102         return 0;
103 }
104
105 /*
106  * syslog, vsyslog --
107  *      print message on log file; output is intended for syslogd(8).
108  */
109 void
110 #if __STDC__
111 syslog(int pri, const char *fmt, ...)
112 #else
113 syslog(pri, fmt, va_alist)
114         int pri;
115         char *fmt;
116         va_dcl
117 #endif
118 {
119         va_list ap;
120
121 #if __STDC__
122         va_start(ap, fmt);
123 #else
124         va_start(ap);
125 #endif
126         vsyslog(pri, fmt, ap);
127         va_end(ap);
128 }
129
130 void
131 vsyslog(pri, fmt, ap)
132         int pri;
133         register const char *fmt;
134         va_list ap;
135 {
136         register int cnt;
137         register char ch, *p;
138         time_t now;
139         int fd, saved_errno;
140         char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26];
141         FILE *fp, *fmt_fp;
142         struct bufcookie tbuf_cookie;
143         struct bufcookie fmt_cookie;
144
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;
151         }
152
153         /* Check priority against setlogmask values. */
154         if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
155                 return;
156
157         saved_errno = errno;
158
159         /* Set default facility if none specified. */
160         if ((pri & LOG_FACMASK) == 0)
161                 pri |= LogFacility;
162
163         /* Create the primary stdio hook */
164         tbuf_cookie.base = tbuf;
165         tbuf_cookie.left = sizeof(tbuf);
166         fp = fwopen(&tbuf_cookie, writehook);
167         if (fp == NULL)
168                 return;
169
170         /* Build the message. */
171         (void)time(&now);
172         (void)fprintf(fp, "<%d>", pri);
173         (void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
174         if (LogStat & LOG_PERROR) {
175                 /* Transfer to string buffer */
176                 (void)fflush(fp);
177                 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
178         }
179         if (LogTag == NULL)
180                 LogTag = __progname;
181         if (LogTag != NULL)
182                 (void)fprintf(fp, "%s", LogTag);
183         if (LogStat & LOG_PID)
184                 (void)fprintf(fp, "[%d]", getpid());
185         if (LogTag != NULL) {
186                 (void)fprintf(fp, ": ");
187         }
188
189         /* Check to see if we can skip expanding the %m */
190         if (strstr(fmt, "%m")) {
191
192                 /* Create the second stdio hook */
193                 fmt_cookie.base = fmt_cpy;
194                 fmt_cookie.left = sizeof(fmt_cpy) - 1;
195                 fmt_fp = fwopen(&fmt_cookie, writehook);
196                 if (fmt_fp == NULL) {
197                         fclose(fp);
198                         return;
199                 }
200
201                 /* Substitute error message for %m. */
202                 for ( ; (ch = *fmt); ++fmt)
203                         if (ch == '%' && fmt[1] == 'm') {
204                                 ++fmt;
205                                 fputs(strerror(saved_errno), fmt_fp);
206                         } else
207                                 fputc(ch, fmt_fp);
208
209                 /* Null terminate if room */
210                 fputc(0, fmt_fp);
211                 fclose(fmt_fp);
212
213                 /* Guarantee null termination */
214                 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
215
216                 fmt = fmt_cpy;
217         }
218
219         (void)vfprintf(fp, fmt, ap);
220         (void)fclose(fp);
221
222         cnt = sizeof(tbuf) - tbuf_cookie.left;
223
224         /* Output to stderr if requested. */
225         if (LogStat & LOG_PERROR) {
226                 struct iovec iov[2];
227                 register struct iovec *v = iov;
228
229                 v->iov_base = stdp;
230                 v->iov_len = cnt - (stdp - tbuf);
231                 ++v;
232                 v->iov_base = "\n";
233                 v->iov_len = 1;
234                 (void)writev(STDERR_FILENO, iov, 2);
235         }
236
237         /* Get connected, output the message to the local logger. */
238         if (!opened)
239                 openlog(LogTag, LogStat | LOG_NDELAY, 0);
240         connectlog();
241         if (send(LogFile, tbuf, cnt, 0) >= 0)
242                 return;
243
244         /*
245          * If the send() failed, the odds are syslogd was restarted.
246          * Make one (only) attempt to reconnect to /dev/log.
247          */
248         disconnectlog();
249         connectlog();
250         if (send(LogFile, tbuf, cnt, 0) >= 0)
251                 return;
252
253         /*
254          * Output the message to the console; try not to block
255          * as a blocking console should not stop other processes.
256          * Make sure the error reported is the one from the syslogd failure.
257          */
258         if (LogStat & LOG_CONS &&
259             (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) {
260                 struct iovec iov[2];
261                 register struct iovec *v = iov;
262
263                 p = strchr(tbuf, '>') + 1;
264                 v->iov_base = p;
265                 v->iov_len = cnt - (p - tbuf);
266                 ++v;
267                 v->iov_base = "\r\n";
268                 v->iov_len = 2;
269                 (void)writev(fd, iov, 2);
270                 (void)_close(fd);
271         }
272 }
273 static void
274 disconnectlog()
275 {
276         /*
277          * If the user closed the FD and opened another in the same slot,
278          * that's their problem.  They should close it before calling on
279          * system services.
280          */
281         if (LogFile != -1) {
282                 _close(LogFile);
283                 LogFile = -1;
284         }
285         connected = 0;                  /* retry connect */
286 }
287
288 static void
289 connectlog()
290 {
291         struct sockaddr_un SyslogAddr;  /* AF_UNIX address of local logger */
292
293         if (LogFile == -1) {
294                 if ((LogFile = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
295                         return;
296                 (void)_fcntl(LogFile, F_SETFD, 1);
297         }
298         if (LogFile != -1 && !connected) {
299                 SyslogAddr.sun_len = sizeof(SyslogAddr);
300                 SyslogAddr.sun_family = AF_UNIX;
301                 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
302                     sizeof SyslogAddr.sun_path);
303                 connected = connect(LogFile, (struct sockaddr *)&SyslogAddr,
304                         sizeof(SyslogAddr)) != -1;
305
306                 if (!connected) {
307                         /*
308                          * Try the old "/dev/log" path, for backward
309                          * compatibility.
310                          */
311                         (void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
312                             sizeof SyslogAddr.sun_path);
313                         connected = connect(LogFile,
314                                 (struct sockaddr *)&SyslogAddr,
315                                 sizeof(SyslogAddr)) != -1;
316                 }
317
318                 if (!connected) {
319                         (void)_close(LogFile);
320                         LogFile = -1;
321                 }
322         }
323 }
324
325 void
326 openlog(ident, logstat, logfac)
327         const char *ident;
328         int logstat, logfac;
329 {
330         if (ident != NULL)
331                 LogTag = ident;
332         LogStat = logstat;
333         if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
334                 LogFacility = logfac;
335
336         if (LogStat & LOG_NDELAY)       /* open immediately */
337                 connectlog();
338
339         opened = 1;     /* ident and facility has been set */
340 }
341
342 void
343 closelog()
344 {
345         (void)_close(LogFile);
346         LogFile = -1;
347         LogTag = NULL;
348         connected = 0;
349 }
350
351 /* setlogmask -- set the log mask level */
352 int
353 setlogmask(pmask)
354         int pmask;
355 {
356         int omask;
357
358         omask = LogMask;
359         if (pmask != 0)
360                 LogMask = pmask;
361         return (omask);
362 }