2 #include <sys/socket.h>
13 #include "fork_impl.h"
15 static volatile int lock[1];
16 static char log_ident[32];
18 static int log_facility = LOG_USER;
19 static int log_mask = 0xff;
20 static int log_fd = -1;
21 volatile int *const __syslog_lockptr = lock;
23 int setlogmask(int maskpri)
27 if (maskpri) log_mask = maskpri;
43 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
48 pthread_setcancelstate(cs, 0);
51 static void __openlog()
53 log_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
54 if (log_fd >= 0) connect(log_fd, (void *)&log_addr, sizeof log_addr);
57 void openlog(const char *ident, int opt, int facility)
60 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
64 size_t n = strnlen(ident, sizeof log_ident - 1);
65 memcpy(log_ident, ident, n);
71 log_facility = facility;
73 if ((opt & LOG_NDELAY) && log_fd<0) __openlog();
76 pthread_setcancelstate(cs, 0);
79 static int is_lost_conn(int e)
81 return e==ECONNREFUSED || e==ECONNRESET || e==ENOTCONN || e==EPIPE;
84 static void _vsyslog(int priority, const char *message, va_list ap)
90 int errno_save = errno;
96 if (log_fd < 0) __openlog();
98 if (!(priority & LOG_FACMASK)) priority |= log_facility;
102 strftime(timebuf, sizeof timebuf, "%b %e %T", &tm);
104 pid = (log_opt & LOG_PID) ? getpid() : 0;
105 l = snprintf(buf, sizeof buf, "<%d>%s %n%s%s%.0d%s: ",
106 priority, timebuf, &hlen, log_ident, "["+!pid, pid, "]"+!pid);
108 l2 = vsnprintf(buf+l, sizeof buf - l, message, ap);
110 if (l2 >= sizeof buf - l) l = sizeof buf - 1;
112 if (buf[l-1] != '\n') buf[l++] = '\n';
113 if (send(log_fd, buf, l, 0) < 0 && (!is_lost_conn(errno)
114 || connect(log_fd, (void *)&log_addr, sizeof log_addr) < 0
115 || send(log_fd, buf, l, 0) < 0)
116 && (log_opt & LOG_CONS)) {
117 fd = open("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
119 dprintf(fd, "%.*s", l-hlen, buf+hlen);
123 if (log_opt & LOG_PERROR) dprintf(2, "%.*s", l-hlen, buf+hlen);
127 static void __vsyslog(int priority, const char *message, va_list ap)
130 if (!(log_mask & LOG_MASK(priority&7)) || (priority&~0x3ff)) return;
131 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
133 _vsyslog(priority, message, ap);
135 pthread_setcancelstate(cs, 0);
138 void syslog(int priority, const char *message, ...)
141 va_start(ap, message);
142 __vsyslog(priority, message, ap);
146 weak_alias(__vsyslog, vsyslog);