From 0572e31529cb2521c04944b81761b12e77fe1064 Mon Sep 17 00:00:00 2001 From: Daniel Borkmann Date: Sun, 3 Mar 2013 14:33:26 +0100 Subject: [PATCH] xio: redirect stdout, stderr to syslog in daemon mode Signed-off-by: Daniel Borkmann --- curvetun.c | 5 ++++- xio.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ xio.h | 1 + 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/curvetun.c b/curvetun.c index cd8752f2..e81debec 100644 --- a/curvetun.c +++ b/curvetun.c @@ -496,9 +496,12 @@ static void daemonize(const char *lockfile) if (getppid() == 1) return; - if (daemon(0, 0)) + if (daemon(0, 1)) panic("Cannot daemonize: %s", strerror(errno)); + to_std_log(&stdout); + to_std_log(&stderr); + umask(lperm); if (lockfile) { lfp = open(lockfile, O_RDWR | O_CREAT | O_EXCL, diff --git a/xio.c b/xio.c index 81ea5f55..82bf0632 100644 --- a/xio.c +++ b/xio.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -200,3 +201,48 @@ int secrand(void) return ret; } + +static char const *priov[] = { + [LOG_EMERG] = "EMERG:", + [LOG_ALERT] = "ALERT:", + [LOG_CRIT] = "CRIT:", + [LOG_ERR] = "ERR:", + [LOG_WARNING] = "WARNING:", + [LOG_NOTICE] = "NOTICE:", + [LOG_INFO] = "INFO:", + [LOG_DEBUG] = "DEBUG:", +}; + +static ssize_t cookie_writer(void *cookie, char const *data, size_t leng) +{ + int prio = LOG_DEBUG, len; + + do { + len = strlen(priov[prio]); + } while (memcmp(data, priov[prio], len) && --prio >= 0); + + if (prio < 0) { + prio = LOG_INFO; + } else { + data += len; + leng -= len; + } + + while (*data == ' ') { + ++data; + --leng; + } + + syslog(prio, "%.*s", (int) leng, data); + + return leng; +} + +static cookie_io_functions_t cookie_log = { + .write = cookie_writer, +}; + +void to_std_log(FILE **pfp) +{ + setvbuf(*pfp = fopencookie(NULL, "w", cookie_log), NULL, _IOLBF, 0); +} diff --git a/xio.h b/xio.h index 3df7d9dc..f38549e7 100644 --- a/xio.h +++ b/xio.h @@ -17,5 +17,6 @@ extern ssize_t write_or_die(int fd, const void *buf, size_t count); extern ssize_t read_exact(int fd, void *buf, size_t len, int mayexit); extern ssize_t write_exact(int fd, void *buf, size_t len, int mayexit); extern int secrand(void); +extern void to_std_log(FILE **pfp); #endif /* XIO_H */ -- 2.11.4.GIT