.
[glibc/history.git] / misc / syslog.c
blob5781b4a9646d59ae6e4a85125528a4371da28ff4
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 #include <math_ldbl_opt.h>
63 #define ftell(s) INTUSE(_IO_ftell) (s)
65 static int LogType = SOCK_DGRAM; /* type of socket connection */
66 static int LogFile = -1; /* fd for log */
67 static int connected; /* have done connect */
68 static int LogStat; /* status bits, set by openlog() */
69 static const char *LogTag; /* string to tag the entry with */
70 static int LogFacility = LOG_USER; /* default facility code */
71 static int LogMask = 0xff; /* mask of priorities to be logged */
72 extern char *__progname; /* Program name, from crt0. */
74 /* Define the lock. */
75 __libc_lock_define_initialized (static, syslog_lock)
77 static void openlog_internal(const char *, int, int) internal_function;
78 static void closelog_internal(void);
79 #ifndef NO_SIGPIPE
80 static void sigpipe_handler (int);
81 #endif
83 #ifndef send_flags
84 # define send_flags 0
85 #endif
87 struct cleanup_arg
89 void *buf;
90 struct sigaction *oldaction;
93 static void
94 cancel_handler (void *ptr)
96 #ifndef NO_SIGPIPE
97 /* Restore the old signal handler. */
98 struct cleanup_arg *clarg = (struct cleanup_arg *) ptr;
100 if (clarg != NULL && clarg->oldaction != NULL)
101 __sigaction (SIGPIPE, clarg->oldaction, NULL);
102 #endif
104 /* Free the lock. */
105 __libc_lock_unlock (syslog_lock);
110 * syslog, vsyslog --
111 * print message on log file; output is intended for syslogd(8).
113 void
114 __syslog(int pri, const char *fmt, ...)
116 va_list ap;
118 va_start(ap, fmt);
119 __vsyslog_chk(pri, -1, fmt, ap);
120 va_end(ap);
122 ldbl_hidden_def (__syslog, syslog)
123 ldbl_strong_alias (__syslog, syslog)
125 void
126 __syslog_chk(int pri, int flag, const char *fmt, ...)
128 va_list ap;
130 va_start(ap, fmt);
131 __vsyslog_chk(pri, flag, fmt, ap);
132 va_end(ap);
135 void
136 __vsyslog_chk(int pri, int flag, const char *fmt, va_list ap)
138 struct tm now_tm;
139 time_t now;
140 int fd;
141 FILE *f;
142 char *buf = 0;
143 size_t bufsize = 0;
144 size_t prioff, msgoff;
145 #ifndef NO_SIGPIPE
146 struct sigaction action, oldaction;
147 int sigpipe;
148 #endif
149 int saved_errno = errno;
150 char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];
152 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
153 /* Check for invalid bits. */
154 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
155 syslog(INTERNALLOG,
156 "syslog: unknown facility/priority: %x", pri);
157 pri &= LOG_PRIMASK|LOG_FACMASK;
160 /* Check priority against setlogmask values. */
161 if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
162 return;
164 /* Set default facility if none specified. */
165 if ((pri & LOG_FACMASK) == 0)
166 pri |= LogFacility;
168 /* Build the message in a memory-buffer stream. */
169 f = open_memstream (&buf, &bufsize);
170 if (f == NULL)
172 /* We cannot get a stream. There is not much we can do but
173 emitting an error messages. */
174 char numbuf[3 * sizeof (pid_t)];
175 char *nump;
176 char *endp = __stpcpy (failbuf, "out of memory [");
177 pid_t pid = __getpid ();
179 nump = numbuf + sizeof (numbuf);
180 /* The PID can never be zero. */
182 *--nump = '0' + pid % 10;
183 while ((pid /= 10) != 0);
185 endp = __mempcpy (endp, nump, (numbuf + sizeof (numbuf)) - nump);
186 *endp++ = ']';
187 *endp = '\0';
188 buf = failbuf;
189 bufsize = endp - failbuf;
190 msgoff = 0;
192 else
194 __fsetlocking (f, FSETLOCKING_BYCALLER);
195 prioff = fprintf (f, "<%d>", pri);
196 (void) time (&now);
197 f->_IO_write_ptr += __strftime_l (f->_IO_write_ptr,
198 f->_IO_write_end
199 - f->_IO_write_ptr,
200 "%h %e %T ",
201 __localtime_r (&now, &now_tm),
202 _nl_C_locobj_ptr);
203 msgoff = ftell (f);
204 if (LogTag == NULL)
205 LogTag = __progname;
206 if (LogTag != NULL)
207 fputs_unlocked (LogTag, f);
208 if (LogStat & LOG_PID)
209 fprintf (f, "[%d]", (int) __getpid ());
210 if (LogTag != NULL)
212 putc_unlocked (':', f);
213 putc_unlocked (' ', f);
216 /* Restore errno for %m format. */
217 __set_errno (saved_errno);
219 /* We have the header. Print the user's format into the
220 buffer. */
221 if (flag == -1)
222 vfprintf (f, fmt, ap);
223 else
224 __vfprintf_chk (f, flag, fmt, ap);
226 /* Close the memory stream; this will finalize the data
227 into a malloc'd buffer in BUF. */
228 fclose (f);
231 /* Output to stderr if requested. */
232 if (LogStat & LOG_PERROR) {
233 struct iovec iov[2];
234 register struct iovec *v = iov;
236 v->iov_base = buf + msgoff;
237 v->iov_len = bufsize - msgoff;
238 /* Append a newline if necessary. */
239 if (buf[bufsize - 1] != '\n')
241 ++v;
242 v->iov_base = (char *) "\n";
243 v->iov_len = 1;
246 __libc_cleanup_push (free, buf == failbuf ? NULL : buf);
248 /* writev is a cancellation point. */
249 (void)__writev(STDERR_FILENO, iov, v - iov + 1);
251 __libc_cleanup_pop (0);
254 /* Prepare for multiple users. We have to take care: open and
255 write are cancellation points. */
256 struct cleanup_arg clarg;
257 clarg.buf = buf;
258 clarg.oldaction = NULL;
259 __libc_cleanup_push (cancel_handler, &clarg);
260 __libc_lock_lock (syslog_lock);
262 #ifndef NO_SIGPIPE
263 /* Prepare for a broken connection. */
264 memset (&action, 0, sizeof (action));
265 action.sa_handler = sigpipe_handler;
266 sigemptyset (&action.sa_mask);
267 sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
268 if (sigpipe == 0)
269 clarg.oldaction = &oldaction;
270 #endif
272 /* Get connected, output the message to the local logger. */
273 if (!connected)
274 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
276 /* If we have a SOCK_STREAM connection, also send ASCII NUL as
277 a record terminator. */
278 if (LogType == SOCK_STREAM)
279 ++bufsize;
281 if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
283 if (connected)
285 /* Try to reopen the syslog connection. Maybe it went
286 down. */
287 closelog_internal ();
288 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
291 if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
293 closelog_internal (); /* attempt re-open next time */
295 * Output the message to the console; don't worry
296 * about blocking, if console blocks everything will.
297 * Make sure the error reported is the one from the
298 * syslogd failure.
300 if (LogStat & LOG_CONS &&
301 (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
303 dprintf (fd, "%s\r\n", buf + msgoff);
304 (void)__close(fd);
309 #ifndef NO_SIGPIPE
310 if (sigpipe == 0)
311 __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
312 #endif
314 /* End of critical section. */
315 __libc_cleanup_pop (0);
316 __libc_lock_unlock (syslog_lock);
318 if (buf != failbuf)
319 free (buf);
321 libc_hidden_def (__vsyslog_chk)
323 void
324 __vsyslog(int pri, const char *fmt, va_list ap)
326 __vsyslog_chk (pri, -1, fmt, ap);
328 ldbl_hidden_def (__vsyslog, vsyslog)
329 ldbl_strong_alias (__vsyslog, vsyslog)
331 static struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */
334 static void
335 internal_function
336 openlog_internal(const char *ident, int logstat, int logfac)
338 if (ident != NULL)
339 LogTag = ident;
340 LogStat = logstat;
341 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
342 LogFacility = logfac;
344 int retry = 0;
345 while (retry < 2) {
346 if (LogFile == -1) {
347 SyslogAddr.sun_family = AF_UNIX;
348 (void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
349 sizeof(SyslogAddr.sun_path));
350 if (LogStat & LOG_NDELAY) {
351 if ((LogFile = __socket(AF_UNIX, LogType, 0))
352 == -1)
353 return;
354 (void)__fcntl(LogFile, F_SETFD, 1);
357 if (LogFile != -1 && !connected)
359 int old_errno = errno;
360 if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
361 == -1)
363 int saved_errno = errno;
364 int fd = LogFile;
365 LogFile = -1;
366 (void)__close(fd);
367 __set_errno (old_errno);
368 if (saved_errno == EPROTOTYPE)
370 /* retry with the other type: */
371 LogType = (LogType == SOCK_DGRAM
372 ? SOCK_STREAM : SOCK_DGRAM);
373 ++retry;
374 continue;
376 } else
377 connected = 1;
379 break;
383 void
384 openlog (const char *ident, int logstat, int logfac)
386 /* Protect against multiple users and cancellation. */
387 __libc_cleanup_push (cancel_handler, NULL);
388 __libc_lock_lock (syslog_lock);
390 openlog_internal (ident, logstat, logfac);
392 __libc_cleanup_pop (1);
395 #ifndef NO_SIGPIPE
396 static void
397 sigpipe_handler (int signo)
399 closelog_internal ();
401 #endif
403 static void
404 closelog_internal()
406 if (!connected)
407 return;
409 __close (LogFile);
410 LogFile = -1;
411 connected = 0;
414 void
415 closelog ()
417 /* Protect against multiple users and cancellation. */
418 __libc_cleanup_push (cancel_handler, NULL);
419 __libc_lock_lock (syslog_lock);
421 closelog_internal ();
422 LogTag = NULL;
423 LogType = SOCK_DGRAM; /* this is the default */
425 /* Free the lock. */
426 __libc_cleanup_pop (1);
429 /* setlogmask -- set the log mask level */
431 setlogmask(pmask)
432 int pmask;
434 int omask;
436 omask = LogMask;
437 if (pmask != 0)
438 LogMask = pmask;
439 return (omask);