(CFLAGS-tst-align.c): Add -mpreferred-stack-boundary=4.
[glibc.git] / misc / syslog.c
blob6916356da717a0f58aa48db5dbac687452b6a8e2
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 <netdb.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <paths.h>
43 #include <stdio.h>
44 #include <stdio_ext.h>
45 #include <string.h>
46 #include <time.h>
47 #include <unistd.h>
48 #include <stdlib.h>
49 #include <bits/libc-lock.h>
50 #include <signal.h>
51 #include <locale.h>
53 #if __STDC__
54 #include <stdarg.h>
55 #else
56 #include <varargs.h>
57 #endif
59 #include <libio/iolibio.h>
60 #define ftell(s) INTUSE(_IO_ftell) (s)
62 static int LogType = SOCK_DGRAM; /* type of socket connection */
63 static int LogFile = -1; /* fd for log */
64 static int connected; /* have done connect */
65 static int LogStat; /* status bits, set by openlog() */
66 static const char *LogTag; /* string to tag the entry with */
67 static int LogFacility = LOG_USER; /* default facility code */
68 static int LogMask = 0xff; /* mask of priorities to be logged */
69 extern char *__progname; /* Program name, from crt0. */
71 /* Define the lock. */
72 __libc_lock_define_initialized (static, syslog_lock)
74 static void openlog_internal(const char *, int, int) internal_function;
75 static void closelog_internal(void);
76 static void sigpipe_handler (int);
79 struct cleanup_arg
81 void *buf;
82 struct sigaction *oldaction;
85 static void
86 cancel_handler (void *ptr)
88 /* Restore the old signal handler. */
89 struct cleanup_arg *clarg = (struct cleanup_arg *) ptr;
91 if (clarg != NULL && clarg->oldaction != NULL)
92 __sigaction (SIGPIPE, clarg->oldaction, NULL);
94 /* Free the lock. */
95 __libc_lock_unlock (syslog_lock);
100 * syslog, vsyslog --
101 * print message on log file; output is intended for syslogd(8).
103 void
104 #if __STDC__
105 syslog(int pri, const char *fmt, ...)
106 #else
107 syslog(pri, fmt, va_alist)
108 int pri;
109 char *fmt;
110 va_dcl
111 #endif
113 va_list ap;
115 #if __STDC__
116 va_start(ap, fmt);
117 #else
118 va_start(ap);
119 #endif
120 vsyslog(pri, fmt, ap);
121 va_end(ap);
123 libc_hidden_def (syslog)
125 void
126 vsyslog(pri, fmt, ap)
127 int pri;
128 register const char *fmt;
129 va_list ap;
131 struct tm now_tm;
132 time_t now;
133 int fd;
134 FILE *f;
135 char *buf = 0;
136 size_t bufsize = 0;
137 size_t prioff, msgoff;
138 struct sigaction action, oldaction;
139 int sigpipe;
140 int saved_errno = errno;
141 char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];
143 #define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
144 /* Check for invalid bits. */
145 if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
146 syslog(INTERNALLOG,
147 "syslog: unknown facility/priority: %x", pri);
148 pri &= LOG_PRIMASK|LOG_FACMASK;
151 /* Check priority against setlogmask values. */
152 if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
153 return;
155 /* Set default facility if none specified. */
156 if ((pri & LOG_FACMASK) == 0)
157 pri |= LogFacility;
159 /* Build the message in a memory-buffer stream. */
160 f = open_memstream (&buf, &bufsize);
161 if (f == NULL)
163 /* We cannot get a stream. There is not much we can do but
164 emitting an error messages. */
165 char numbuf[3 * sizeof (pid_t)];
166 char *nump;
167 char *endp = __stpcpy (failbuf, "out of memory [");
168 pid_t pid = __getpid ();
170 nump = numbuf + sizeof (numbuf);
171 /* The PID can never be zero. */
173 *--nump = '0' + pid % 10;
174 while ((pid /= 10) != 0);
176 endp = __mempcpy (endp, nump, (numbuf + sizeof (numbuf)) - nump);
177 *endp++ = ']';
178 *endp = '\0';
179 buf = failbuf;
180 bufsize = endp - failbuf;
181 msgoff = 0;
183 else
185 __fsetlocking (f, FSETLOCKING_BYCALLER);
186 prioff = fprintf (f, "<%d>", pri);
187 (void) time (&now);
188 f->_IO_write_ptr += __strftime_l (f->_IO_write_ptr,
189 f->_IO_write_end
190 - f->_IO_write_ptr,
191 "%h %e %T ",
192 __localtime_r (&now, &now_tm),
193 &_nl_C_locobj);
194 msgoff = ftell (f);
195 if (LogTag == NULL)
196 LogTag = __progname;
197 if (LogTag != NULL)
198 fputs_unlocked (LogTag, f);
199 if (LogStat & LOG_PID)
200 fprintf (f, "[%d]", (int) __getpid ());
201 if (LogTag != NULL)
203 putc_unlocked (':', f);
204 putc_unlocked (' ', f);
207 /* Restore errno for %m format. */
208 __set_errno (saved_errno);
210 /* We have the header. Print the user's format into the
211 buffer. */
212 vfprintf (f, fmt, ap);
214 /* Close the memory stream; this will finalize the data
215 into a malloc'd buffer in BUF. */
216 fclose (f);
219 /* Output to stderr if requested. */
220 if (LogStat & LOG_PERROR) {
221 struct iovec iov[2];
222 register struct iovec *v = iov;
224 v->iov_base = buf + msgoff;
225 v->iov_len = bufsize - msgoff;
226 /* Append a newline if necessary. */
227 if (buf[bufsize - 1] != '\n')
229 ++v;
230 v->iov_base = (char *) "\n";
231 v->iov_len = 1;
234 __libc_cleanup_push (free, buf == failbuf ? NULL : buf);
236 /* writev is a cancellation point. */
237 (void)__writev(STDERR_FILENO, iov, v - iov + 1);
239 __libc_cleanup_pop (0);
242 /* Prepare for multiple users. We have to take care: open and
243 write are cancellation points. */
244 struct cleanup_arg clarg;
245 clarg.buf = buf;
246 clarg.oldaction = NULL;
247 __libc_cleanup_push (cancel_handler, &clarg);
248 __libc_lock_lock (syslog_lock);
250 /* Prepare for a broken connection. */
251 memset (&action, 0, sizeof (action));
252 action.sa_handler = sigpipe_handler;
253 sigemptyset (&action.sa_mask);
254 sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
255 if (sigpipe == 0)
256 clarg.oldaction = &oldaction;
258 /* Get connected, output the message to the local logger. */
259 if (!connected)
260 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
262 /* If we have a SOCK_STREAM connection, also send ASCII NUL as
263 a record terminator. */
264 if (LogType == SOCK_STREAM)
265 ++bufsize;
267 if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
269 if (connected)
271 /* Try to reopen the syslog connection. Maybe it went
272 down. */
273 closelog_internal ();
274 openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
277 if (!connected || __send(LogFile, buf, bufsize, 0) < 0)
279 closelog_internal (); /* attempt re-open next time */
281 * Output the message to the console; don't worry
282 * about blocking, if console blocks everything will.
283 * Make sure the error reported is the one from the
284 * syslogd failure.
286 if (LogStat & LOG_CONS &&
287 (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
289 dprintf (fd, "%s\r\n", buf + msgoff);
290 (void)__close(fd);
295 if (sigpipe == 0)
296 __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
298 /* End of critical section. */
299 __libc_cleanup_pop (0);
300 __libc_lock_unlock (syslog_lock);
302 if (buf != failbuf)
303 free (buf);
305 libc_hidden_def (vsyslog)
307 static struct sockaddr SyslogAddr; /* AF_UNIX address of local logger */
310 static void
311 internal_function
312 openlog_internal(const char *ident, int logstat, int logfac)
314 if (ident != NULL)
315 LogTag = ident;
316 LogStat = logstat;
317 if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
318 LogFacility = logfac;
320 int retry = 0;
321 while (retry < 2) {
322 if (LogFile == -1) {
323 SyslogAddr.sa_family = AF_UNIX;
324 (void)strncpy(SyslogAddr.sa_data, _PATH_LOG,
325 sizeof(SyslogAddr.sa_data));
326 if (LogStat & LOG_NDELAY) {
327 if ((LogFile = __socket(AF_UNIX, LogType, 0))
328 == -1)
329 return;
330 (void)__fcntl(LogFile, F_SETFD, 1);
333 if (LogFile != -1 && !connected)
335 int old_errno = errno;
336 if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
337 == -1)
339 int saved_errno = errno;
340 int fd = LogFile;
341 LogFile = -1;
342 (void)__close(fd);
343 __set_errno (old_errno);
344 if (saved_errno == EPROTOTYPE)
346 /* retry with the other type: */
347 LogType = (LogType == SOCK_DGRAM
348 ? SOCK_STREAM : SOCK_DGRAM);
349 ++retry;
350 continue;
352 } else
353 connected = 1;
355 break;
359 void
360 openlog (const char *ident, int logstat, int logfac)
362 /* Protect against multiple users and cancellation. */
363 __libc_cleanup_push (cancel_handler, NULL);
364 __libc_lock_lock (syslog_lock);
366 openlog_internal (ident, logstat, logfac);
368 __libc_cleanup_pop (1);
371 static void
372 sigpipe_handler (int signo)
374 closelog_internal ();
377 static void
378 closelog_internal()
380 if (!connected)
381 return;
383 __close (LogFile);
384 LogFile = -1;
385 connected = 0;
388 void
389 closelog ()
391 /* Protect against multiple users and cancellation. */
392 __libc_cleanup_push (cancel_handler, NULL);
393 __libc_lock_lock (syslog_lock);
395 closelog_internal ();
396 LogTag = NULL;
397 LogType = SOCK_DGRAM; /* this is the default */
399 /* Free the lock. */
400 __libc_cleanup_pop (1);
403 /* setlogmask -- set the log mask level */
405 setlogmask(pmask)
406 int pmask;
408 int omask;
410 omask = LogMask;
411 if (pmask != 0)
412 LogMask = pmask;
413 return (omask);