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