libc: Move out locking from vsyslog() core.
[dragonfly.git] / lib / libc / gen / syslog.c
CommitLineData
984263bc
MD
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.
dc71b7ab 13 * 3. Neither the name of the University nor the names of its contributors
984263bc
MD
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
16 *
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.
1de703da
MD
28 *
29 * @(#)syslog.c 8.5 (Berkeley) 4/29/95
cc753ff3 30 * $FreeBSD: src/lib/libc/gen/syslog.c,v 1.39 2007/01/09 00:27:55 imp Exp $
984263bc
MD
31 */
32
17ea2221 33#include "namespace.h"
984263bc
MD
34#include <sys/types.h>
35#include <sys/socket.h>
36#include <sys/syslog.h>
37#include <sys/uio.h>
38#include <sys/un.h>
39#include <netdb.h>
40
41#include <errno.h>
42#include <fcntl.h>
43#include <paths.h>
cc753ff3 44#include <pthread.h>
984263bc 45#include <stdio.h>
e59e8ef1 46#include <stdlib.h>
984263bc
MD
47#include <string.h>
48#include <time.h>
49#include <unistd.h>
50
984263bc 51#include <stdarg.h>
cc753ff3
PA
52#include "un-namespace.h"
53
54#include "libc_private.h"
984263bc
MD
55
56static int LogFile = -1; /* fd for log */
cc753ff3 57static int status; /* connection status */
984263bc
MD
58static int opened; /* have done openlog() */
59static int LogStat = 0; /* status bits, set by openlog() */
60static const char *LogTag = NULL; /* string to tag the entry with */
61static int LogFacility = LOG_USER; /* default facility code */
62static int LogMask = 0xff; /* mask of priorities to be logged */
cc753ff3
PA
63static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER;
64
65#define THREAD_LOCK() \
66 do { \
67 if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \
68 } while(0)
69#define THREAD_UNLOCK() \
70 do { \
71 if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \
72 } while(0)
73
74static void disconnectlog(void); /* disconnect from syslogd */
75static void connectlog(void); /* (re)connect to syslogd */
76static void openlog_unlocked(const char *, int, int);
77
78enum {
79 NOCONN = 0,
80 CONNDEF,
81 CONNPRIV,
82};
984263bc
MD
83
84/*
85 * Format of the magic cookie passed through the stdio hook
86 */
87struct bufcookie {
88 char *base; /* start of buffer */
89 int left;
90};
91
92/*
93 * stdio write hook for writing to a static string buffer
94 * XXX: Maybe one day, dynamically allocate it so that the line length
95 * is `unlimited'.
96 */
0f52d283 97static int
b0e25abd 98writehook(void *cookie, const char *buf, int len)
984263bc
MD
99{
100 struct bufcookie *h; /* private `handle' */
101
102 h = (struct bufcookie *)cookie;
103 if (len > h->left) {
104 /* clip in case of wraparound */
105 len = h->left;
106 }
107 if (len > 0) {
0f52d283 108 memcpy(h->base, buf, len); /* `write' it. */
984263bc
MD
109 h->base += len;
110 h->left -= len;
111 }
cc753ff3 112 return len;
984263bc
MD
113}
114
115/*
116 * syslog, vsyslog --
117 * print message on log file; output is intended for syslogd(8).
118 */
119void
984263bc 120syslog(int pri, const char *fmt, ...)
984263bc
MD
121{
122 va_list ap;
123
984263bc 124 va_start(ap, fmt);
984263bc
MD
125 vsyslog(pri, fmt, ap);
126 va_end(ap);
127}
128
8ca63dbf 129static void
130vsyslog_unlocked(int pri, const char *fmt, va_list ap)
984263bc 131{
e27dad4e 132 char ch, *p;
984263bc 133 time_t now;
40392ead 134 int cnt, fd, saved_errno, maxtries;
cc753ff3 135 char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64];
984263bc
MD
136 FILE *fp, *fmt_fp;
137 struct bufcookie tbuf_cookie;
138 struct bufcookie fmt_cookie;
139
b0e25abd
SW
140 stdp = NULL;
141
984263bc
MD
142#define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
143 /* Check for invalid bits. */
144 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
145 syslog(INTERNALLOG,
146 "syslog: unknown facility/priority: %x", pri);
147 pri &= LOG_PRIMASK|LOG_FACMASK;
148 }
149
cc753ff3
PA
150 saved_errno = errno;
151
984263bc 152 /* Check priority against setlogmask values. */
8ca63dbf 153 if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
984263bc 154 return;
984263bc
MD
155
156 /* Set default facility if none specified. */
157 if ((pri & LOG_FACMASK) == 0)
158 pri |= LogFacility;
159
160 /* Create the primary stdio hook */
161 tbuf_cookie.base = tbuf;
162 tbuf_cookie.left = sizeof(tbuf);
163 fp = fwopen(&tbuf_cookie, writehook);
8ca63dbf 164 if (fp == NULL)
984263bc
MD
165 return;
166
167 /* Build the message. */
0f52d283
SW
168 time(&now);
169 fprintf(fp, "<%d>", pri);
170 fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4);
984263bc
MD
171 if (LogStat & LOG_PERROR) {
172 /* Transfer to string buffer */
0f52d283 173 fflush(fp);
984263bc
MD
174 stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left);
175 }
176 if (LogTag == NULL)
cc753ff3 177 LogTag = _getprogname();
984263bc 178 if (LogTag != NULL)
0f52d283 179 fprintf(fp, "%s", LogTag);
984263bc 180 if (LogStat & LOG_PID)
0f52d283 181 fprintf(fp, "[%d]", getpid());
40392ead 182 if (LogTag != NULL)
0f52d283 183 fprintf(fp, ": ");
984263bc
MD
184
185 /* Check to see if we can skip expanding the %m */
186 if (strstr(fmt, "%m")) {
187
188 /* Create the second stdio hook */
189 fmt_cookie.base = fmt_cpy;
190 fmt_cookie.left = sizeof(fmt_cpy) - 1;
191 fmt_fp = fwopen(&fmt_cookie, writehook);
192 if (fmt_fp == NULL) {
193 fclose(fp);
194 return;
195 }
196
cc753ff3
PA
197 /*
198 * Substitute error message for %m. Be careful not to
199 * molest an escaped percent "%%m". We want to pass it
200 * on untouched as the format is later parsed by vfprintf.
201 */
202 for ( ; (ch = *fmt); ++fmt) {
984263bc
MD
203 if (ch == '%' && fmt[1] == 'm') {
204 ++fmt;
cc753ff3
PA
205 strerror_r(saved_errno, errstr, sizeof(errstr));
206 fputs(errstr, fmt_fp);
207 } else if (ch == '%' && fmt[1] == '%') {
208 ++fmt;
209 fputc(ch, fmt_fp);
210 fputc(ch, fmt_fp);
211 } else {
984263bc 212 fputc(ch, fmt_fp);
cc753ff3
PA
213 }
214 }
984263bc
MD
215
216 /* Null terminate if room */
217 fputc(0, fmt_fp);
218 fclose(fmt_fp);
219
220 /* Guarantee null termination */
221 fmt_cpy[sizeof(fmt_cpy) - 1] = '\0';
222
223 fmt = fmt_cpy;
224 }
225
0f52d283
SW
226 vfprintf(fp, fmt, ap);
227 fclose(fp);
984263bc
MD
228
229 cnt = sizeof(tbuf) - tbuf_cookie.left;
230
cc753ff3
PA
231 /* Remove a trailing newline */
232 if (tbuf[cnt - 1] == '\n')
233 cnt--;
234
984263bc
MD
235 /* Output to stderr if requested. */
236 if (LogStat & LOG_PERROR) {
237 struct iovec iov[2];
e27dad4e 238 struct iovec *v = iov;
984263bc
MD
239
240 v->iov_base = stdp;
241 v->iov_len = cnt - (stdp - tbuf);
242 ++v;
243 v->iov_base = "\n";
244 v->iov_len = 1;
0f52d283 245 _writev(STDERR_FILENO, iov, 2);
984263bc
MD
246 }
247
248 /* Get connected, output the message to the local logger. */
249 if (!opened)
cc753ff3 250 openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0);
984263bc 251 connectlog();
984263bc
MD
252
253 /*
40392ead 254 * If the send() fails, there are three likely scenarios:
cc753ff3
PA
255 * 1) syslogd was restarted
256 * 2) /var/run/log is out of socket buffer space, which
257 * in most cases means local DoS.
61f40eab
MD
258 * 3) syslogd itself got stuck.
259 *
cc753ff3
PA
260 * We attempt to reconnect to /var/run/log to take care of
261 * case #1 and keep send()ing data to cover case #2
262 * to give syslogd a chance to empty its socket buffer.
61f40eab
MD
263 * However, to deal with #3 we retry no more than 10 times
264 * for up to one second before giving up. Otherwise a
265 * broken syslogd will completely and utterly break the
266 * entire system == bad.
cc753ff3 267 *
40392ead 268 * If we are working with a privileged socket, then take
cc753ff3
PA
269 * only one attempt, because we don't want to freeze a
270 * critical application like su(1) or sshd(8).
271 *
984263bc 272 */
cc753ff3
PA
273 if (send(LogFile, tbuf, cnt, 0) < 0) {
274 if (errno != ENOBUFS) {
275 disconnectlog();
276 connectlog();
277 }
61f40eab 278 for (maxtries = 10; maxtries; --maxtries) {
8ca63dbf 279 if (send(LogFile, tbuf, cnt, 0) >= 0)
cc753ff3 280 return;
cc753ff3
PA
281 if (status == CONNPRIV)
282 break;
61f40eab
MD
283 if (errno != ENOBUFS)
284 break;
285 _usleep(1000000 / 10);
286 }
cc753ff3 287 } else {
984263bc 288 return;
cc753ff3 289 }
984263bc
MD
290
291 /*
292 * Output the message to the console; try not to block
293 * as a blocking console should not stop other processes.
294 * Make sure the error reported is the one from the syslogd failure.
295 */
61f40eab 296 if ((LogStat & LOG_CONS) &&
5270936c 297 (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK|O_CLOEXEC, 0)) >= 0) {
984263bc 298 struct iovec iov[2];
e27dad4e 299 struct iovec *v = iov;
984263bc
MD
300
301 p = strchr(tbuf, '>') + 1;
302 v->iov_base = p;
303 v->iov_len = cnt - (p - tbuf);
304 ++v;
305 v->iov_base = "\r\n";
306 v->iov_len = 2;
0f52d283
SW
307 _writev(fd, iov, 2);
308 _close(fd);
984263bc 309 }
8ca63dbf 310}
cc753ff3 311
8ca63dbf 312void
313vsyslog(int pri, const char *fmt, va_list ap)
314{
315 THREAD_LOCK();
316 vsyslog_unlocked(pri, fmt, ap);
cc753ff3 317 THREAD_UNLOCK();
984263bc 318}
cc753ff3
PA
319
320/* Should be called with mutex acquired */
984263bc 321static void
0f52d283 322disconnectlog(void)
984263bc
MD
323{
324 /*
325 * If the user closed the FD and opened another in the same slot,
326 * that's their problem. They should close it before calling on
327 * system services.
328 */
329 if (LogFile != -1) {
330 _close(LogFile);
331 LogFile = -1;
332 }
cc753ff3 333 status = NOCONN; /* retry connect */
984263bc
MD
334}
335
cc753ff3 336/* Should be called with mutex acquired */
984263bc 337static void
0f52d283 338connectlog(void)
984263bc
MD
339{
340 struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
341
342 if (LogFile == -1) {
8ca63dbf 343 if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC,
344 0)) == -1)
984263bc 345 return;
984263bc 346 }
cc753ff3 347 if (LogFile != -1 && status == NOCONN) {
984263bc
MD
348 SyslogAddr.sun_len = sizeof(SyslogAddr);
349 SyslogAddr.sun_family = AF_UNIX;
cc753ff3
PA
350
351 /*
40392ead 352 * First try privileged socket. If no success,
cc753ff3
PA
353 * then try default socket.
354 */
355 strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV,
984263bc 356 sizeof SyslogAddr.sun_path);
cc753ff3
PA
357 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
358 sizeof(SyslogAddr)) != -1)
359 status = CONNPRIV;
360
361 if (status == NOCONN) {
362 strncpy(SyslogAddr.sun_path, _PATH_LOG,
363 sizeof SyslogAddr.sun_path);
364 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
365 sizeof(SyslogAddr)) != -1)
366 status = CONNDEF;
367 }
984263bc 368
cc753ff3 369 if (status == NOCONN) {
984263bc
MD
370 /*
371 * Try the old "/dev/log" path, for backward
372 * compatibility.
373 */
0f52d283 374 strncpy(SyslogAddr.sun_path, _PATH_OLDLOG,
984263bc 375 sizeof SyslogAddr.sun_path);
cc753ff3
PA
376 if (_connect(LogFile, (struct sockaddr *)&SyslogAddr,
377 sizeof(SyslogAddr)) != -1)
378 status = CONNDEF;
984263bc
MD
379 }
380
cc753ff3 381 if (status == NOCONN) {
0f52d283 382 _close(LogFile);
984263bc
MD
383 LogFile = -1;
384 }
385 }
386}
387
cc753ff3
PA
388static void
389openlog_unlocked(const char *ident, int logstat, int logfac)
984263bc
MD
390{
391 if (ident != NULL)
392 LogTag = ident;
393 LogStat = logstat;
394 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
395 LogFacility = logfac;
396
397 if (LogStat & LOG_NDELAY) /* open immediately */
398 connectlog();
399
400 opened = 1; /* ident and facility has been set */
401}
402
cc753ff3
PA
403void
404openlog(const char *ident, int logstat, int logfac)
405{
406 THREAD_LOCK();
407 openlog_unlocked(ident, logstat, logfac);
408 THREAD_UNLOCK();
409}
410
411
984263bc 412void
0f52d283 413closelog(void)
984263bc 414{
cc753ff3 415 THREAD_LOCK();
8ca63dbf 416 if (LogFile != -1) {
417 _close(LogFile);
418 LogFile = -1;
419 }
984263bc 420 LogTag = NULL;
cc753ff3
PA
421 status = NOCONN;
422 THREAD_UNLOCK();
984263bc
MD
423}
424
425/* setlogmask -- set the log mask level */
426int
0f52d283 427setlogmask(int pmask)
984263bc
MD
428{
429 int omask;
430
cc753ff3 431 THREAD_LOCK();
984263bc
MD
432 omask = LogMask;
433 if (pmask != 0)
434 LogMask = pmask;
cc753ff3 435 THREAD_UNLOCK();
984263bc
MD
436 return (omask);
437}