typo.
[glibc.git] / misc / syslog.c
blob6b0e7748fe9b855af443276e7e7661537b5e3f6c
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 <sys/un.h>
39 #include <netdb.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <paths.h>
44 #include <stdio.h>
45 #include <stdio_ext.h>
46 #include <string.h>
47 #include <time.h>
48 #include <unistd.h>
49 #include <stdlib.h>
50 #include <bits/libc-lock.h>
51 #include <signal.h>
52 #include <locale.h>
54 #if __STDC__
55 #include <stdarg.h>
56 #else
57 #include <varargs.h>
58 #endif
60 #include <libio/iolibio.h>
61 #define ftell(s) INTUSE(_IO_ftell) (s)
63 static int LogType = SOCK_DGRAM; /* type of socket connection */
64 static int LogFile = -1; /* fd for log */
65 static int connected; /* have done connect */
66 static int LogStat; /* status bits, set by openlog() */
67 static const char *LogTag; /* string to tag the entry with */
68 static int LogFacility = LOG_USER; /* default facility code */
69 static int LogMask = 0xff; /* mask of priorities to be logged */
70 extern char *__progname; /* Program name, from crt0. */
72 /* Define the lock. */
73 __libc_lock_define_initialized (static, syslog_lock)
75 static void openlog_internal(const char *, int, int) internal_function;
76 static void closelog_internal(void);
77 #ifndef NO_SIGPIPE
78 static void sigpipe_handler (int);
79 #endif
81 #ifndef send_flags
82 # define send_flags 0
83 #endif
85 struct cleanup_arg
87 void *buf;
88 struct sigaction *oldaction;
91 static void
92 cancel_handler (void *ptr)
94 #ifndef NO_SIGPIPE
95 /* Restore the old signal handler. */
96 struct cleanup_arg *clarg = (struct cleanup_arg *) ptr;
98 if (clarg != NULL && clarg->oldaction != NULL)
99 __sigaction (SIGPIPE, clarg->oldaction, NULL);
100 #endif
102 /* Free the lock. */
103 __libc_lock_unlock (syslog_lock);
108 * syslog, vsyslog --
109 * print message on log file; output is intended for syslogd(8).
111 void
112 syslog(int pri, const char *fmt, ...)
114 va_list ap;
116 va_start(ap, fmt);
117 __vsyslog_chk(pri, -1, fmt, ap);
118 va_end(ap);
120 libc_hidden_def (syslog)
122 void
123 __syslog_chk(int pri, int flag, const char *fmt, ...)
125 va_list ap;
127 va_start(ap, fmt);
128 __vsyslog_chk(pri, flag, fmt, ap);
129 va_end(ap);
132 void
133 __vsyslog_chk(int pri, int flag, const char *fmt, va_list ap)
135 struct tm now_tm;
136 time_t now;
137 int fd;
138 FILE *f;
139 char *buf = 0;
140 size_t bufsize = 0;
141 size_t prioff, msgoff;
142 #ifndef NO_SIGPIPE
143 struct sigaction action, oldaction;
144 int sigpipe;
145 #endif
146 int saved_errno = errno;
147 char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];
149 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
150 /* Check for invalid bits. */
151 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
152 syslog(INTERNALLOG,
153 "syslog: unknown facility/priority: %x", pri);
154 pri &= LOG_PRIMASK|LOG_FACMASK;
157 /* Check priority against setlogmask values. */
158 if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
159 return;
161 /* Set default facility if none specified. */
162 if ((pri & LOG_FACMASK) == 0)
163 pri |= LogFacility;
165 /* Build the message in a memory-buffer stream. */
166 f = open_memstream (&buf, &bufsize);
167 if (f == NULL)
169 /* We cannot get a stream. There is not much we can do but
170 emitting an error messages. */
171 char numbuf[3 * sizeof (pid_t)];
172 char *nump;
173 char *endp = __stpcpy (failbuf, "out of memory [");
174 pid_t pid = __getpid ();
176 nump = numbuf + sizeof (numbuf);
177 /* The PID can never be zero. */
179 *--nump = '0' + pid % 10;
180 while ((pid /= 10) != 0);
182 endp = __mempcpy (endp, nump, (numbuf + sizeof (numbuf)) - nump);
183 *endp++ = ']';
184 *endp = '\0';
185 buf = failbuf;
186 bufsize = endp - failbuf;
187 msgoff = 0;
189 else
191 __fsetlocking (f, FSETLOCKING_BYCALLER);
192 prioff = fprintf (f, "<%d>", pri);
193 (void) time (&now);
194 f->_IO_write_ptr += __strftime_l (f->_IO_write_ptr,
195 f->_IO_write_end
196 - f->_IO_write_ptr,
197 "%h %e %T ",
198 __localtime_r (&now, &now_tm),
199 _nl_C_locobj_ptr);
200 msgoff = ftell (f);
201 if (LogTag == NULL)
202 LogTag = __progname;
203 if (LogTag != NULL)
204 fputs_unlocked (LogTag, f);
205 if (LogStat & LOG_PID)
206 fprintf (f, "[%d]", (int) __getpid ());
207 if (LogTag != NULL)
209 putc_unlocked (':', f);
210 putc_unlocked (' ', f);
213 /* Restore errno for %m format. */
214 __set_errno (saved_errno);
216 /* We have the header. Print the user's format into the
217 buffer. */
218 if (flag == -1)
219 vfprintf (f, fmt, ap);
220 else
221 __vfprintf_chk (f, flag, fmt, ap);
223 /* Close the memory stream; this will finalize the data
224 into a malloc'd buffer in BUF. */
225 fclose (f);
228 /* Output to stderr if requested. */
229 if (LogStat & LOG_PERROR) {
230 struct iovec iov[2];
231 register struct iovec *v = iov;
233 v->iov_base = buf + msgoff;
234 v->iov_len = bufsize - msgoff;
235 /* Append a newline if necessary. */
236 if (buf[bufsize - 1] != '\n')
238 ++v;
239 v->iov_base = (char *) "\n";
240 v->iov_len = 1;
243 __libc_cleanup_push (free, buf == failbuf ? NULL : buf);
245 /* writev is a cancellation point. */
246 (void)__writev(STDERR_FILENO, iov, v - iov + 1);
248 __libc_cleanup_pop (0);
251 /* Prepare for multiple users. We have to take care: open and
252 write are cancellation points. */
253 struct cleanup_arg clarg;
254 clarg.buf = buf;
255 clarg.oldaction = NULL;
256 __libc_cleanup_push (cancel_handler, &clarg);
257 __libc_lock_lock (syslog_lock);
259 #ifndef NO_SIGPIPE
260 /* Prepare for a broken connection. */
261 memset (&action, 0, sizeof (action));
262 action.sa_handler = sigpipe_handler;
263 sigemptyset (&action.sa_mask);
264 sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
265 if (sigpipe == 0)
266 clarg.oldaction = &oldaction;
267 #endif
269 /* Get connected, output the message to the local logger. */
270 if (!connected)
271 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
273 /* If we have a SOCK_STREAM connection, also send ASCII NUL as
274 a record terminator. */
275 if (LogType == SOCK_STREAM)
276 ++bufsize;
278 if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
280 if (connected)
282 /* Try to reopen the syslog connection. Maybe it went
283 down. */
284 closelog_internal ();
285 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
288 if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
290 closelog_internal (); /* attempt re-open next time */
292 * Output the message to the console; don't worry
293 * about blocking, if console blocks everything will.
294 * Make sure the error reported is the one from the
295 * syslogd failure.
297 if (LogStat & LOG_CONS &&
298 (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
300 dprintf (fd, "%s\r\n", buf + msgoff);
301 (void)__close(fd);
306 #ifndef NO_SIGPIPE
307 if (sigpipe == 0)
308 __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
309 #endif
311 /* End of critical section. */
312 __libc_cleanup_pop (0);
313 __libc_lock_unlock (syslog_lock);
315 if (buf != failbuf)
316 free (buf);
318 libc_hidden_def (__vsyslog_chk)
320 void
321 vsyslog(pri, fmt, ap)
322 int pri;
323 register const char *fmt;
324 va_list ap;
326 __vsyslog_chk (pri, -1, fmt, ap);
328 libc_hidden_def (vsyslog)
330 static struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
333 static void
334 internal_function
335 openlog_internal(const char *ident, int logstat, int logfac)
337 if (ident != NULL)
338 LogTag = ident;
339 LogStat = logstat;
340 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
341 LogFacility = logfac;
343 int retry = 0;
344 while (retry < 2) {
345 if (LogFile == -1) {
346 SyslogAddr.sun_family = AF_UNIX;
347 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
348 sizeof(SyslogAddr.sun_path));
349 if (LogStat & LOG_NDELAY) {
350 if ((LogFile = __socket(AF_UNIX, LogType, 0))
351 == -1)
352 return;
353 (void)__fcntl(LogFile, F_SETFD, 1);
356 if (LogFile != -1 && !connected)
358 int old_errno = errno;
359 if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
360 == -1)
362 int saved_errno = errno;
363 int fd = LogFile;
364 LogFile = -1;
365 (void)__close(fd);
366 __set_errno (old_errno);
367 if (saved_errno == EPROTOTYPE)
369 /* retry with the other type: */
370 LogType = (LogType == SOCK_DGRAM
371 ? SOCK_STREAM : SOCK_DGRAM);
372 ++retry;
373 continue;
375 } else
376 connected = 1;
378 break;
382 void
383 openlog (const char *ident, int logstat, int logfac)
385 /* Protect against multiple users and cancellation. */
386 __libc_cleanup_push (cancel_handler, NULL);
387 __libc_lock_lock (syslog_lock);
389 openlog_internal (ident, logstat, logfac);
391 __libc_cleanup_pop (1);
394 #ifndef NO_SIGPIPE
395 static void
396 sigpipe_handler (int signo)
398 closelog_internal ();
400 #endif
402 static void
403 closelog_internal()
405 if (!connected)
406 return;
408 __close (LogFile);
409 LogFile = -1;
410 connected = 0;
413 void
414 closelog ()
416 /* Protect against multiple users and cancellation. */
417 __libc_cleanup_push (cancel_handler, NULL);
418 __libc_lock_lock (syslog_lock);
420 closelog_internal ();
421 LogTag = NULL;
422 LogType = SOCK_DGRAM; /* this is the default */
424 /* Free the lock. */
425 __libc_cleanup_pop (1);
428 /* setlogmask -- set the log mask level */
430 setlogmask(pmask)
431 int pmask;
433 int omask;
435 omask = LogMask;
436 if (pmask != 0)
437 LogMask = pmask;
438 return (omask);