diff options
author | Robert Ginda <rginda@google.com> | 2015-08-10 15:45:03 -0700 |
---|---|---|
committer | Robert Ginda <rginda@google.com> | 2015-08-10 15:45:03 -0700 |
commit | 4340b1831d360a440ab7bf5e1aa0170398437163 (patch) | |
tree | f5a90fac0006dada785191bc4e626982b62131e7 /libdaemon | |
parent | d012a8bd96e5ae970e89b181ae352c909adf506a (diff) | |
parent | 8d8ad60fce9134f31b233c78bd286d3f949aa3b8 (diff) | |
download | platform_external_libdaemon-4340b1831d360a440ab7bf5e1aa0170398437163.tar.gz platform_external_libdaemon-4340b1831d360a440ab7bf5e1aa0170398437163.tar.bz2 platform_external_libdaemon-4340b1831d360a440ab7bf5e1aa0170398437163.zip |
Import libdaemon into the Android tree.
Import libdaemon (a dep of external/avahi, which is a dep of
system/peerd).
At the time of the import the libdaemon HEAD was
0630da04e575213229f695bdc3dc90aa92ca4f55
Committed on 2012-09-03.
Bug: 22921222
Diffstat (limited to 'libdaemon')
-rw-r--r-- | libdaemon/Android.mk | 32 | ||||
-rw-r--r-- | libdaemon/Makefile.am | 47 | ||||
-rw-r--r-- | libdaemon/daemon.h | 41 | ||||
-rw-r--r-- | libdaemon/dexec.c | 232 | ||||
-rw-r--r-- | libdaemon/dexec.h | 84 | ||||
-rw-r--r-- | libdaemon/dfork.c | 730 | ||||
-rw-r--r-- | libdaemon/dfork.h | 165 | ||||
-rw-r--r-- | libdaemon/dlog.c | 93 | ||||
-rw-r--r-- | libdaemon/dlog.h | 119 | ||||
-rw-r--r-- | libdaemon/dnonblock.c | 49 | ||||
-rw-r--r-- | libdaemon/dnonblock.h | 52 | ||||
-rw-r--r-- | libdaemon/dpid.c | 281 | ||||
-rw-r--r-- | libdaemon/dpid.h | 106 | ||||
-rw-r--r-- | libdaemon/dsignal.c | 160 | ||||
-rw-r--r-- | libdaemon/dsignal.h | 80 |
15 files changed, 2271 insertions, 0 deletions
diff --git a/libdaemon/Android.mk b/libdaemon/Android.mk new file mode 100644 index 0000000..565c873 --- /dev/null +++ b/libdaemon/Android.mk @@ -0,0 +1,32 @@ +LOCAL_PATH:= $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_SRC_FILES:= \ + dexec.c \ + dfork.c \ + dlog.c \ + dnonblock.c \ + dpid.c \ + dsignal.c + +LOCAL_C_INCLUDES+= $(LOCAL_PATH)/.. + +LOCAL_MODULE:=libdaemon + +LOCAL_EXPORT_C_INCLUDE_DIRS:= $(LOCAL_PATH)/.. + +# -std=gnu99 -DHAVE_CONFIG_H -I. -I.. -I.. -g -O2 -pipe +# -Wall -W -Wextra -pedantic -Wformat -Wold-style-definition +# -Wdeclaration-after-statement -Wfloat-equal -Wmissing-declarations +# -Wmissing-prototypes -Wstrict-prototypes -Wredundant-decls +# -Wmissing-noreturn -Wshadow -Wendif-labels -Wpointer-arith +# -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Winline +# -Wstrict-aliasing +# -MT testd.o -MD -MP -MF .deps/testd.Tpo -c -o testd.o testd.c + +LOCAL_CFLAGS+= \ + -Wno-unused-parameter \ + -DHAVE_CONFIG_H \ + -DLOCALSTATEDIR=\"/var\" + +include $(BUILD_SHARED_LIBRARY) diff --git a/libdaemon/Makefile.am b/libdaemon/Makefile.am new file mode 100644 index 0000000..9c56611 --- /dev/null +++ b/libdaemon/Makefile.am @@ -0,0 +1,47 @@ +# This file is part of libdaemon. +# +# Copyright 2003-2008 Lennart Poettering +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +AM_CPPFLAGS='-DLOCALSTATEDIR="$(localstatedir)"' + +pkginclude_HEADERS = \ + dlog.h \ + dfork.h \ + dsignal.h \ + dnonblock.h \ + dpid.h \ + dexec.h \ + daemon.h + +lib_LTLIBRARIES = libdaemon.la + +libdaemon_la_SOURCES = \ + dlog.c \ + dfork.c \ + dsignal.c \ + dnonblock.c \ + dpid.c \ + dexec.c \ + daemon.h \ + $(pkg_include_HEADERS) + +libdaemon_la_LDFLAGS = -version-info $(LIBDAEMON_VERSION_INFO) $(LDFLAGS_NOUNDEFINED) diff --git a/libdaemon/daemon.h b/libdaemon/daemon.h new file mode 100644 index 0000000..3d3573a --- /dev/null +++ b/libdaemon/daemon.h @@ -0,0 +1,41 @@ +#ifndef foodaemonhfoo +#define foodaemonhfoo + +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +/** \file + * + * A header file including all other header files part of libdaemon + */ + +#include <libdaemon/dfork.h> +#include <libdaemon/dlog.h> +#include <libdaemon/dpid.h> +#include <libdaemon/dsignal.h> +#include <libdaemon/dexec.h> +#include <libdaemon/dnonblock.h> + +#endif diff --git a/libdaemon/dexec.c b/libdaemon/dexec.c new file mode 100644 index 0000000..7a89b62 --- /dev/null +++ b/libdaemon/dexec.c @@ -0,0 +1,232 @@ +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <sys/types.h> +#include <unistd.h> +#include <string.h> +#include <errno.h> +#include <sys/stat.h> +#include <stdlib.h> +#include <signal.h> +#include <sys/wait.h> +#include <limits.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdarg.h> +#include <assert.h> + +#include "dlog.h" +#include "dsignal.h" +#include "dfork.h" +#include "dexec.h" + +#define MAX_ARGS 64 + +int daemon_execv(const char *dir, int *ret, const char *prog, va_list ap) { + pid_t pid; + int p[2]; + unsigned n = 0; + static char buf[256]; + int sigfd, r; + fd_set fds; + int saved_errno; + + assert(daemon_signal_fd() >= 0); + + if (pipe(p) < 0) { + daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno)); + return -1; + } + + if ((pid = fork()) < 0) { + daemon_log(LOG_ERR, "fork() failed: %s", strerror(errno)); + + saved_errno = errno; + close(p[0]); + close(p[1]); + errno = saved_errno; + + return -1; + + } else if (pid == 0) { + char *args[MAX_ARGS]; + int i; + + if (p[1] != 1) + if (dup2(p[1], 1) < 0) { + daemon_log(LOG_ERR, "dup2: %s", strerror(errno)); + goto fail; + } + + if (p[1] != 2) + if (dup2(p[1], 2) < 0) { + daemon_log(LOG_ERR, "dup2: %s", strerror(errno)); + goto fail; + } + + + if (p[0] > 2) + close(p[0]); + + if (p[1] > 2) + close(p[1]); + + close(0); + + if (open("/dev/null", O_RDONLY) != 0) { + daemon_log(LOG_ERR, "Unable to open /dev/null as STDIN"); + goto fail; + } + + daemon_close_all(-1); + daemon_reset_sigs(-1); + daemon_unblock_sigs(-1); + + umask(0022); /* Set up a sane umask */ + + if (dir && chdir(dir) < 0) { + daemon_log(LOG_WARNING, "Failed to change to directory '%s'", dir); + chdir("/"); + } + + for (i = 0; i < MAX_ARGS-1; i++) + if (!(args[i] = va_arg(ap, char*))) + break; + args[i] = NULL; + + execv(prog, args); + + daemon_log(LOG_ERR, "execv(%s) failed: %s", prog, strerror(errno)); + + fail: + + _exit(EXIT_FAILURE); + } + + close(p[1]); + + FD_ZERO(&fds); + FD_SET(p[0], &fds); + sigfd = daemon_signal_fd(); + FD_SET(sigfd, &fds); + + n = 0; + + for (;;) { + fd_set qfds = fds; + + if (select(FD_SETSIZE, &qfds, NULL, NULL, NULL) < 0) { + + if (errno == EINTR) + continue; + + daemon_log(LOG_ERR, "select() failed: %s", strerror(errno)); + + saved_errno = errno; + close(p[0]); + errno = saved_errno; + return -1; + } + + if (FD_ISSET(p[0], &qfds)) { + char c; + + if (read(p[0], &c, 1) != 1) + break; + + buf[n] = c; + + if (c == '\n' || n >= sizeof(buf) - 2) { + if (c != '\n') n++; + buf[n] = 0; + + if (buf[0]) + daemon_log(LOG_INFO, "client: %s", buf); + + n = 0; + } else + n++; + } + + if (FD_ISSET(sigfd, &qfds)) { + int sig; + + if ((sig = daemon_signal_next()) < 0) { + saved_errno = errno; + close(p[0]); + errno = saved_errno; + return -1; + } + + if (sig != SIGCHLD) { + daemon_log(LOG_WARNING, "Killing child."); + kill(pid, SIGTERM); + } + } + } + + if (n > 0) { + buf[n] = 0; + daemon_log(LOG_WARNING, "client: %s", buf); + } + + close(p[0]); + + for (;;) { + if (waitpid(pid, &r, 0) < 0) { + + if (errno == EINTR) + continue; + + daemon_log(LOG_ERR, "waitpid(): %s", strerror(errno)); + return -1; + } else { + if (!WIFEXITED(r)) { + errno = ECANCELED; + return -1; + } + + if (ret) + *ret = WEXITSTATUS(r); + + return 0; + } + } +} + +int daemon_exec(const char *dir, int *ret, const char *prog, ...) { + va_list ap; + int r; + + va_start(ap, prog); + r = daemon_execv(dir, ret, prog, ap); + va_end(ap); + + return r; +} diff --git a/libdaemon/dexec.h b/libdaemon/dexec.h new file mode 100644 index 0000000..7c03017 --- /dev/null +++ b/libdaemon/dexec.h @@ -0,0 +1,84 @@ +#ifndef foodexechfoo +#define foodexechfoo + +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#include <stdarg.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + * + * Contains a robust API for running sub processes with STDOUT and + * STDERR redirected to syslog + */ + +/** This variable is defined to 1 iff daemon_exec() is supported. + * @since 0.4 + * @see daemon_exec() */ +#define DAEMON_EXEC_AVAILABLE 1 + +#if defined(__GNUC__) && ! defined(DAEMON_GCC_SENTINEL) +#define DAEMON_GCC_SENTINEL __attribute__ ((sentinel)) +#else +/** A macro for making use of GCCs printf compilation warnings */ +#define DAEMON_GCC_SENTINEL +#endif + +/** Run the specified executable with the specified arguments in the + * specified directory and return the return value of the program in + * the specified pointer. The calling process is blocked until the + * child finishes and all child output (either STDOUT or STDIN) has + * been written to syslog. Running this function requires that + * daemon_signal() has been called with SIGCHLD as argument. + * + * @param dir Working directory for the process. + * @param ret A pointer to an integer to write the return value of the program to. + * @param prog The path to the executable + * @param ... The arguments to be passed to the program, followed by a (char *) NULL + * @return Nonzero on failure, zero on success + * @since 0.4 + * @see DAEMON_EXEC_AVAILABLE + */ +int daemon_exec(const char *dir, int *ret, const char *prog, ...) DAEMON_GCC_SENTINEL; + +/** This variable is defined to 1 iff daemon_execv() is supported. + * @since 0.11 + * @see daemon_execv() */ +#define DAEMON_EXECV_AVAILABLE 1 + +/** The same as daemon_exec, but without variadic arguments + * @since 0.11 + * @see DAEMON_EXECV_AVAILABLE */ +int daemon_execv(const char *dir, int *ret, const char *prog, va_list ap); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libdaemon/dfork.c b/libdaemon/dfork.c new file mode 100644 index 0000000..783033f --- /dev/null +++ b/libdaemon/dfork.c @@ -0,0 +1,730 @@ +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <sys/types.h> +#include <unistd.h> +#include <errno.h> +#include <string.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/wait.h> +#include <assert.h> +#include <sys/ioctl.h> +#include <signal.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <dirent.h> + +#include "dfork.h" +#include "dnonblock.h" +#include "dlog.h" + +#if defined(_NSIG) /* On glibc NSIG does not count RT signals */ +# define SIGNAL_UPPER_BOUND _NSIG +#elif defined(NSIG) /* Solaris defines just this */ +# define SIGNAL_UPPER_BOUND NSIG +#else +# error "Unknown upper bound for signals" +#endif + +static int _daemon_retval_pipe[2] = { -1, -1 }; + +static int _null_open(int f, int fd) { + int fd2; + + if ((fd2 = open("/dev/null", f)) < 0) + return -1; + + if (fd2 == fd) + return fd; + + if (dup2(fd2, fd) < 0) + return -1; + + close(fd2); + return fd; +} + +static ssize_t atomic_read(int fd, void *d, size_t l) { + ssize_t t = 0; + + while (l > 0) { + ssize_t r; + + if ((r = read(fd, d, l)) <= 0) { + + if (r < 0) + return t > 0 ? t : -1; + else + return t; + } + + t += r; + d = (char*) d + r; + l -= r; + } + + return t; +} + +static ssize_t atomic_write(int fd, const void *d, size_t l) { + ssize_t t = 0; + + while (l > 0) { + ssize_t r; + + if ((r = write(fd, d, l)) <= 0) { + + if (r < 0) + return t > 0 ? t : -1; + else + return t; + } + + t += r; + d = (const char*) d + r; + l -= r; + } + + return t; +} + +static int move_fd_up(int *fd) { + assert(fd); + + while (*fd <= 2) { + if ((*fd = dup(*fd)) < 0) { + daemon_log(LOG_ERR, "dup(): %s", strerror(errno)); + return -1; + } + } + + return 0; +} + +static void sigchld(int s) { +} + +pid_t daemon_fork(void) { + pid_t pid; + int pipe_fds[2] = {-1, -1}; + struct sigaction sa_old, sa_new; + sigset_t ss_old, ss_new; + int saved_errno; + + memset(&sa_new, 0, sizeof(sa_new)); + sa_new.sa_handler = sigchld; + sa_new.sa_flags = SA_RESTART; + + if (sigemptyset(&ss_new) < 0) { + daemon_log(LOG_ERR, "sigemptyset() failed: %s", strerror(errno)); + return (pid_t) -1; + } + + if (sigaddset(&ss_new, SIGCHLD) < 0) { + daemon_log(LOG_ERR, "sigaddset() failed: %s", strerror(errno)); + return (pid_t) -1; + } + + if (sigaction(SIGCHLD, &sa_new, &sa_old) < 0) { + daemon_log(LOG_ERR, "sigaction() failed: %s", strerror(errno)); + return (pid_t) -1; + } + + if (sigprocmask(SIG_UNBLOCK, &ss_new, &ss_old) < 0) { + daemon_log(LOG_ERR, "sigprocmask() failed: %s", strerror(errno)); + + saved_errno = errno; + sigaction(SIGCHLD, &sa_old, NULL); + errno = saved_errno; + + return (pid_t) -1; + } + + if (pipe(pipe_fds) < 0) { + daemon_log(LOG_ERR, "pipe() failed: %s", strerror(errno)); + + saved_errno = errno; + sigaction(SIGCHLD, &sa_old, NULL); + sigprocmask(SIG_SETMASK, &ss_old, NULL); + errno = saved_errno; + + return (pid_t) -1; + } + + if ((pid = fork()) < 0) { /* First fork */ + daemon_log(LOG_ERR, "First fork() failed: %s", strerror(errno)); + + saved_errno = errno; + close(pipe_fds[0]); + close(pipe_fds[1]); + sigaction(SIGCHLD, &sa_old, NULL); + sigprocmask(SIG_SETMASK, &ss_old, NULL); + errno = saved_errno; + + return (pid_t) -1; + + } else if (pid == 0) { + pid_t dpid; + + /* First child. Now we are sure not to be a session leader or + * process group leader anymore, i.e. we know that setsid() + * will succeed. */ + + if (daemon_log_use & DAEMON_LOG_AUTO) + daemon_log_use = DAEMON_LOG_SYSLOG; + + if (close(pipe_fds[0]) < 0) { + daemon_log(LOG_ERR, "close() failed: %s", strerror(errno)); + goto fail; + } + + /* Move file descriptors up*/ + if (move_fd_up(&pipe_fds[1]) < 0) + goto fail; + + if (_daemon_retval_pipe[0] >= 0 && move_fd_up(&_daemon_retval_pipe[0]) < 0) + goto fail; + if (_daemon_retval_pipe[1] >= 0 && move_fd_up(&_daemon_retval_pipe[1]) < 0) + goto fail; + + if (_null_open(O_RDONLY, 0) < 0) { + daemon_log(LOG_ERR, "Failed to open /dev/null for STDIN: %s", strerror(errno)); + goto fail; + } + + if (_null_open(O_WRONLY, 1) < 0) { + daemon_log(LOG_ERR, "Failed to open /dev/null for STDOUT: %s", strerror(errno)); + goto fail; + } + + if (_null_open(O_WRONLY, 2) < 0) { + daemon_log(LOG_ERR, "Failed to open /dev/null for STDERR: %s", strerror(errno)); + goto fail; + } + + /* Create a new session. This will create a new session and a + * new process group for us and we will be the ledaer of + * both. This should always succeed because we cannot be the + * process group leader because we just forked. */ + if (setsid() < 0) { + daemon_log(LOG_ERR, "setsid() failed: %s", strerror(errno)); + goto fail; + } + + umask(0077); + + if (chdir("/") < 0) { + daemon_log(LOG_ERR, "chdir() failed: %s", strerror(errno)); + goto fail; + } + + if ((pid = fork()) < 0) { /* Second fork */ + daemon_log(LOG_ERR, "Second fork() failed: %s", strerror(errno)); + goto fail; + + } else if (pid == 0) { + /* Second child. Our father will exit right-away. That way + * we can be sure that we are a child of init now, even if + * the process which spawned us stays around for a longer + * time. Also, since we are no session leader anymore we + * can be sure that we will never acquire a controlling + * TTY. */ + + if (sigaction(SIGCHLD, &sa_old, NULL) < 0) { + daemon_log(LOG_ERR, "close() failed: %s", strerror(errno)); + goto fail; + } + + if (sigprocmask(SIG_SETMASK, &ss_old, NULL) < 0) { + daemon_log(LOG_ERR, "sigprocmask() failed: %s", strerror(errno)); + goto fail; + } + + if (signal(SIGTTOU, SIG_IGN) == SIG_ERR) { + daemon_log(LOG_ERR, "signal(SIGTTOU, SIG_IGN) failed: %s", strerror(errno)); + goto fail; + } + + if (signal(SIGTTIN, SIG_IGN) == SIG_ERR) { + daemon_log(LOG_ERR, "signal(SIGTTIN, SIG_IGN) failed: %s", strerror(errno)); + goto fail; + } + + if (signal(SIGTSTP, SIG_IGN) == SIG_ERR) { + daemon_log(LOG_ERR, "signal(SIGTSTP, SIG_IGN) failed: %s", strerror(errno)); + goto fail; + } + + dpid = getpid(); + if (atomic_write(pipe_fds[1], &dpid, sizeof(dpid)) != sizeof(dpid)) { + daemon_log(LOG_ERR, "write() failed: %s", strerror(errno)); + goto fail; + } + + if (close(pipe_fds[1]) < 0) { + daemon_log(LOG_ERR, "close() failed: %s", strerror(errno)); + goto fail; + } + + return 0; + + } else { + /* Second father */ + close(pipe_fds[1]); + _exit(0); + } + + fail: + dpid = (pid_t) -1; + + if (atomic_write(pipe_fds[1], &dpid, sizeof(dpid)) != sizeof(dpid)) + daemon_log(LOG_ERR, "Failed to write error PID: %s", strerror(errno)); + + close(pipe_fds[1]); + _exit(0); + + } else { + /* First father */ + pid_t dpid; + + close(pipe_fds[1]); + + if (waitpid(pid, NULL, WUNTRACED) < 0) { + saved_errno = errno; + close(pipe_fds[0]); + sigaction(SIGCHLD, &sa_old, NULL); + sigprocmask(SIG_SETMASK, &ss_old, NULL); + errno = saved_errno; + return -1; + } + + sigprocmask(SIG_SETMASK, &ss_old, NULL); + sigaction(SIGCHLD, &sa_old, NULL); + + if (atomic_read(pipe_fds[0], &dpid, sizeof(dpid)) != sizeof(dpid)) { + daemon_log(LOG_ERR, "Failed to read daemon PID."); + dpid = (pid_t) -1; + errno = EINVAL; + } else if (dpid == (pid_t) -1) + errno = EIO; + + saved_errno = errno; + close(pipe_fds[0]); + errno = saved_errno; + + return dpid; + } +} + +int daemon_retval_init(void) { + + if (_daemon_retval_pipe[0] < 0 || _daemon_retval_pipe[1] < 0) { + + if (pipe(_daemon_retval_pipe) < 0) { + daemon_log(LOG_ERR, "pipe(): %s", strerror(errno)); + return -1; + } + } + + return 0; +} + +void daemon_retval_done(void) { + int saved_errno = errno; + + if (_daemon_retval_pipe[0] >= 0) + close(_daemon_retval_pipe[0]); + + if (_daemon_retval_pipe[1] >= 0) + close(_daemon_retval_pipe[1]); + + _daemon_retval_pipe[0] = _daemon_retval_pipe[1] = -1; + + errno = saved_errno; +} + +int daemon_retval_send(int i) { + ssize_t r; + + if (_daemon_retval_pipe[1] < 0) { + errno = EINVAL; + return -1; + } + + r = atomic_write(_daemon_retval_pipe[1], &i, sizeof(i)); + + daemon_retval_done(); + + if (r != sizeof(i)) { + + if (r < 0) + daemon_log(LOG_ERR, "write() failed while writing return value to pipe: %s", strerror(errno)); + else { + daemon_log(LOG_ERR, "write() too short while writing return value from pipe"); + errno = EINVAL; + } + + return -1; + } + + return 0; +} + +int daemon_retval_wait(int timeout) { + ssize_t r; + int i; + + if (timeout > 0) { + struct timeval tv; + int s; + fd_set fds; + + tv.tv_sec = timeout; + tv.tv_usec = 0; + + FD_ZERO(&fds); + FD_SET(_daemon_retval_pipe[0], &fds); + + if ((s = select(FD_SETSIZE, &fds, 0, 0, &tv)) != 1) { + + if (s < 0) + daemon_log(LOG_ERR, "select() failed while waiting for return value: %s", strerror(errno)); + else { + errno = ETIMEDOUT; + daemon_log(LOG_ERR, "Timeout reached while wating for return value"); + } + + return -1; + } + } + + if ((r = atomic_read(_daemon_retval_pipe[0], &i, sizeof(i))) != sizeof(i)) { + + if (r < 0) + daemon_log(LOG_ERR, "read() failed while reading return value from pipe: %s", strerror(errno)); + else if (r == 0) { + daemon_log(LOG_ERR, "read() failed with EOF while reading return value from pipe."); + errno = EINVAL; + } else if (r > 0) { + daemon_log(LOG_ERR, "read() too short while reading return value from pipe."); + errno = EINVAL; + } + + return -1; + } + + daemon_retval_done(); + + return i; +} + +int daemon_close_all(int except_fd, ...) { + va_list ap; + int n = 0, i, r; + int *p; + int saved_errno; + + va_start(ap, except_fd); + + if (except_fd >= 0) + for (n = 1; va_arg(ap, int) >= 0; n++) + ; + + va_end(ap); + + if (!(p = malloc(sizeof(int) * (n+1)))) + return -1; + + va_start(ap, except_fd); + + i = 0; + if (except_fd >= 0) { + int fd; + p[i++] = except_fd; + + while ((fd = va_arg(ap, int)) >= 0) + p[i++] = fd; + } + p[i] = -1; + + va_end(ap); + + r = daemon_close_allv(p); + + saved_errno = errno; + free(p); + errno = saved_errno; + + return r; +} + +/** Same as daemon_close_all but takes an array of fds, terminated by -1 */ +int daemon_close_allv(const int except_fds[]) { + struct rlimit rl; + int fd, maxfd; + +#ifdef __linux__ + int saved_errno; + + DIR *d; + + if ((d = opendir("/proc/self/fd"))) { + + struct dirent *de; + + while ((de = readdir(d))) { + int found; + long l; + char *e = NULL; + int i; + + if (de->d_name[0] == '.') + continue; + + errno = 0; + l = strtol(de->d_name, &e, 10); + if (errno != 0 || !e || *e) { + closedir(d); + errno = EINVAL; + return -1; + } + + fd = (int) l; + + if ((long) fd != l) { + closedir(d); + errno = EINVAL; + return -1; + } + + if (fd < 3) + continue; + + if (fd == dirfd(d)) + continue; + + if (fd == _daemon_retval_pipe[1]) + continue; + + found = 0; + for (i = 0; except_fds[i] >= 0; i++) + if (except_fds[i] == fd) { + found = 1; + break; + } + + if (found) + continue; + + if (close(fd) < 0) { + saved_errno = errno; + closedir(d); + errno = saved_errno; + + return -1; + } + + if (fd == _daemon_retval_pipe[0]) + _daemon_retval_pipe[0] = -1; /* mark as closed */ + } + + closedir(d); + return 0; + } + +#endif + + if (getrlimit(RLIMIT_NOFILE, &rl) > 0) + maxfd = (int) rl.rlim_max; + else + maxfd = sysconf(_SC_OPEN_MAX); + + for (fd = 3; fd < maxfd; fd++) { + int i, found; + + if (fd == _daemon_retval_pipe[1]) + continue; + + found = 0; + for (i = 0; except_fds[i] >= 0; i++) + if (except_fds[i] == fd) { + found = 1; + break; + } + + if (found) + continue; + + if (close(fd) < 0 && errno != EBADF) + return -1; + + if (fd == _daemon_retval_pipe[0]) + _daemon_retval_pipe[0] = -1; /* mark as closed */ + } + + return 0; +} + +int daemon_unblock_sigs(int except, ...) { + va_list ap; + int n = 0, i, r; + int *p; + int saved_errno; + + va_start(ap, except); + + if (except >= 1) + for (n = 1; va_arg(ap, int) >= 0; n++) + ; + + va_end(ap); + + if (!(p = malloc(sizeof(int) * (n+1)))) + return -1; + + va_start(ap, except); + + i = 0; + if (except >= 1) { + int sig; + p[i++] = except; + + while ((sig = va_arg(ap, int)) >= 0) + p[i++] = sig; + } + p[i] = -1; + + va_end(ap); + + r = daemon_unblock_sigsv(p); + + saved_errno = errno; + free(p); + errno = saved_errno; + + return r; +} + +int daemon_unblock_sigsv(const int except[]) { + int i; + sigset_t ss; + + if (sigemptyset(&ss) < 0) + return -1; + + for (i = 0; except[i] > 0; i++) + if (sigaddset(&ss, except[i]) < 0) + return -1; + + return sigprocmask(SIG_SETMASK, &ss, NULL); +} + +int daemon_reset_sigs(int except, ...) { + va_list ap; + int n = 0, i, r; + int *p; + int saved_errno; + + va_start(ap, except); + + if (except >= 1) + for (n = 1; va_arg(ap, int) >= 0; n++) + ; + + va_end(ap); + + if (!(p = malloc(sizeof(int) * (n+1)))) + return -1; + + va_start(ap, except); + + i = 0; + if (except >= 1) { + int sig; + p[i++] = except; + + while ((sig = va_arg(ap, int)) >= 0) + p[i++] = sig; + } + p[i] = -1; + + va_end(ap); + + r = daemon_reset_sigsv(p); + + saved_errno = errno; + free(p); + errno = saved_errno; + + return r; +} + +int daemon_reset_sigsv(const int except[]) { + int sig; + + for (sig = 1; sig < SIGNAL_UPPER_BOUND; sig++) { + int reset = 1; + + switch (sig) { + case SIGKILL: + case SIGSTOP: + reset = 0; + break; + + default: { + int i; + + for (i = 0; except[i] > 0; i++) { + if (sig == except[i]) { + reset = 0; + break; + } + } + } + } + + if (reset) { + struct sigaction sa; + + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = SIG_DFL; + + /* On Linux the first two RT signals are reserved by + * glibc, and sigaction() will return EINVAL for them. */ + if ((sigaction(sig, &sa, NULL) < 0)) + if (errno != EINVAL) + return -1; + } + } + + return 0; +} diff --git a/libdaemon/dfork.h b/libdaemon/dfork.h new file mode 100644 index 0000000..47b1630 --- /dev/null +++ b/libdaemon/dfork.h @@ -0,0 +1,165 @@ +#ifndef foodaemonforkhfoo +#define foodaemonforkhfoo + +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#include <sys/types.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/** \mainpage libdaemon + * + * libdaemon + * + * For a brief explanation of libdaemons's purpose, have a look on the + * README file. Thank you! + * + */ + +/** \example testd.c + * This is an example for the usage of libdaemon + */ + +/** \file + * + * Contains an API for doing a daemonizing fork(). + * + * You may daemonize by calling daemon_fork(), a function similar to + * the plain fork(). If you want to return a return value of the + * initialization procedure of the child from the parent, you may use + * the daemon_retval_xxx() functions. + */ + +/** Does a daemonizing fork(). For the new daemon process STDIN, + * STDOUT, STDERR are connected to /dev/null, the process is a session + * leader, the current directory is changed to /, the umask is set to + * 777. + * @return On success, the PID of the child process is returned in the + * parent's thread of execution, and a 0 is returned in the child's + * thread of execution. On failure, -1 will be returned in the + * parent's context, no child process will be created, and errno will + * be set appropriately. + */ +pid_t daemon_fork(void); + +/** Allocate and initialize resources required by the + * daemon_retval_xxx() functions. These functions allow the child to + * send a value to the parent after completing its initialisation. + * Call this in the parent before forking. + * @return zero on success, nonzero on failure. + */ +int daemon_retval_init(void); + +/** Frees the resources allocated by daemon_retval_init(). This should + * be called if neither daemon_retval_wait() nor daemon_retval_send() + * is called in the current process. The resources allocated by + * daemon_retval_init() should be freed in both parent and daemon + * process. This may be achieved by using daemon_retval_wait() + * resp. daemon_retval_send(), or by using daemon_retval_done(). + */ +void daemon_retval_done(void); + +/** Return the value sent by the child via the daemon_retval_send() + * function, but wait only the specified number of seconds before + * timing out and returning a negative number. Should be called just + * once from the parent process only. A subsequent call to + * daemon_retval_done() in the parent is ignored. + * + * @param timeout Thetimeout in seconds + * @return The integer passed daemon_retval_send() in the daemon process, or -1 on failure. + */ +int daemon_retval_wait(int timeout); + +/** Send the specified integer to the parent process. Do not send -1 + * because this signifies a library error. Should be called just once + * from the daemon process only. A subsequent call to + * daemon_retval_done() in the daemon is ignored. @param s The + * integer to pass to daemon_retval_wait() in the parent process + * @return Zero on success, nonzero on failure. + */ +int daemon_retval_send(int s); + +/** This variable is defined to 1 iff daemon_close_all() and + * daemon_close_allv() are supported. + * @since 0.11 + * @see daemon_close_all(), daemon_close_allv() */ +#define DAEMON_CLOSE_ALL_AVAILABLE 1 + +/** Close all file descriptors except those passed. List needs to be + * terminated by -1. FDs 0, 1, 2 will be kept open anyway. + * @since 0.11 + * @see DAEMON_CLOSE_ALL_AVAILABLE */ +int daemon_close_all(int except_fd, ...); + +/** Same as daemon_close_all but takes an array of fds, terminated by + * -1 + * @since 0.11 + * @see DAEMON_CLOSE_ALL_AVAILABLE */ +int daemon_close_allv(const int except_fds[]); + +/** This variable is defined to 1 iff daemon_unblock_sigs() and + * daemon_unblock_sigsv() are supported. + * @since 0.13 + * @see daemon_unblock_sigs(), daemon_unblock_sigsv()*/ +#define DAEMON_UNBLOCK_SIGS_AVAILABLE 1 + +/** Unblock all signals except those passed. List needs to be + * terminated by -1. + * @since 0.13 + * @see DAEMON_UNBLOCK_SIGS_AVAILABLE */ +int daemon_unblock_sigs(int except, ...); + +/** Same as daemon_unblock_sigs() but takes an array of signals, + * terminated by -1 + * @since 0.13 + * @see DAEMON_UNBLOCK_SIGS_AVAILABLE */ +int daemon_unblock_sigsv(const int except[]); + +/** This variable is defined to 1 iff daemon_reset_sigs() and + * daemon_reset_sigsv() are supported. + * @since 0.13 + * @see daemon_reset_sigs(), daemon_reset_sigsv() */ +#define DAEMON_RESET_SIGS_AVAILABLE 1 + +/** Reset all signal handlers except those passed. List needs to be + * terminated by -1. + * @since 0.13 + * @see DAEMON_RESET_SIGS_AVAILABLE */ +int daemon_reset_sigs(int except, ...); + +/** Same as daemon_reset_sigs() but takes an array of signals, + * terminated by -1 + * @since 0.13 + * @see DAEMON_RESET_SIGS_AVAILABLE */ +int daemon_reset_sigsv(const int except[]); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libdaemon/dlog.c b/libdaemon/dlog.c new file mode 100644 index 0000000..1cc0566 --- /dev/null +++ b/libdaemon/dlog.c @@ -0,0 +1,93 @@ +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdarg.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> + +#include "dlog.h" + +enum daemon_log_flags daemon_log_use = DAEMON_LOG_AUTO|DAEMON_LOG_STDERR; +const char* daemon_log_ident = NULL; + +static int daemon_verbosity_level = LOG_INFO; + +void daemon_set_verbosity(int verbosity_prio) { + + /* Allow using negative verbosity levels to hide _all_ messages */ + if (verbosity_prio > 0 && (verbosity_prio & LOG_PRIMASK) != LOG_PRIMASK) + daemon_log(LOG_ERR, "The value %d is not a valid priority value", verbosity_prio); + + daemon_verbosity_level = verbosity_prio & LOG_PRIMASK; +} + +void daemon_logv(int prio, const char* template, va_list arglist) { + int saved_errno; + + saved_errno = errno; + + if (daemon_log_use & DAEMON_LOG_SYSLOG) { + openlog(daemon_log_ident ? daemon_log_ident : "UNKNOWN", LOG_PID, LOG_DAEMON); + vsyslog(prio | LOG_DAEMON, template, arglist); + } + + if (prio > daemon_verbosity_level) + goto end_daemon_logv; + + if (daemon_log_use & DAEMON_LOG_STDERR) { + vfprintf(stderr, template, arglist); + fprintf(stderr, "\n"); + } + + if (daemon_log_use & DAEMON_LOG_STDOUT) { + vfprintf(stdout, template, arglist); + fprintf(stdout, "\n"); + } + + end_daemon_logv: + errno = saved_errno; +} + +void daemon_log(int prio, const char* template, ...) { + va_list arglist; + + va_start(arglist, template); + daemon_logv(prio, template, arglist); + va_end(arglist); +} + +char *daemon_ident_from_argv0(char *argv0) { + char *p; + + if ((p = strrchr(argv0, '/'))) + return p+1; + + return argv0; +} diff --git a/libdaemon/dlog.h b/libdaemon/dlog.h new file mode 100644 index 0000000..deea520 --- /dev/null +++ b/libdaemon/dlog.h @@ -0,0 +1,119 @@ +#ifndef foodaemonloghfoo +#define foodaemonloghfoo + +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#include <syslog.h> +#include <stdarg.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + * + * Contains a robust API for logging messages + */ + +/** Specifies where to send the log messages to. The global variable daemon_log_use takes values of this type. + */ +enum daemon_log_flags { + DAEMON_LOG_SYSLOG = 1, /**< Log messages are written to syslog */ + DAEMON_LOG_STDERR = 2, /**< Log messages are written to STDERR */ + DAEMON_LOG_STDOUT = 4, /**< Log messages are written to STDOUT */ + DAEMON_LOG_AUTO = 8 /**< If this is set a daemon_fork() will + change this to DAEMON_LOG_SYSLOG in + the daemon process. */ +}; + +/** This variable is used to specify the log target(s) to + * use. Defaults to DAEMON_LOG_STDERR|DAEMON_LOG_AUTO */ +extern enum daemon_log_flags daemon_log_use; + +/** Specifies the syslog identification, use daemon_ident_from_argv0() + * to set this to a sensible value or generate your own. */ +extern const char* daemon_log_ident; + +#if defined(__GNUC__) && ! defined(DAEMON_GCC_PRINTF_ATTR) +#define DAEMON_GCC_PRINTF_ATTR(a,b) __attribute__ ((format (printf, a, b))) +#else +/** A macro for making use of GCCs printf compilation warnings */ +#define DAEMON_GCC_PRINTF_ATTR(a,b) +#endif + +/** Log a message using printf format strings using the specified syslog priority + * @param prio The syslog priority (PRIO_xxx constants) + * @param t,... The text message to log + */ +void daemon_log(int prio, const char* t, ...) DAEMON_GCC_PRINTF_ATTR(2,3); + +/** This variable is defined to 1 iff daemon_logv() is supported. + * @since 0.11 + * @see daemon_logv() + */ +#define DAEMON_LOGV_AVAILABLE 1 + +/** Same as daemon_log(), but without variadic arguments + * @since 0.11 + * @see DAEMON_LOGV_AVAILABLE + */ +void daemon_logv(int prio, const char* t, va_list ap); + +/** Return a sensible syslog identification for daemon_log_ident + * generated from argv[0]. This will return a pointer to the file name + * of argv[0], i.e. strrchr(argv[0], '\')+1 + * @param argv0 argv[0] as passed to main() + * @return The identification string + */ +char *daemon_ident_from_argv0(char *argv0); + +/** This variable is defined to 1 iff daemon_set_verbosity() is available. + * @since 0.14 + * @see daemon_set_verbosity() + */ +#define DAEMON_SET_VERBOSITY_AVAILABLE 1 + +/** Setter for the verbosity level of standard output. + * + * @param verbosity_prio Minimum priority level for messages to output + * on standard output/error + * + * Allows to decide which messages to output on standard output/error + * streams. All messages are logged to syslog and this setting does + * not influence that. + * + * The default value is LOG_WARNING. + * + * @since 0.14 + * @see DAEMON_SET_VERBOSITY_AVAILABLE + */ +void daemon_set_verbosity(int verbosity_prio); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libdaemon/dnonblock.c b/libdaemon/dnonblock.c new file mode 100644 index 0000000..003514e --- /dev/null +++ b/libdaemon/dnonblock.c @@ -0,0 +1,49 @@ +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <fcntl.h> + +#include "dnonblock.h" + +int daemon_nonblock(int fd, int b) { + int a, c; + + if ((a = fcntl(fd, F_GETFL)) < 0) + return -1; + + if (b) + c = a | O_NONBLOCK; + else + c = a & ~O_NONBLOCK; + + if (c == a) + return 0; + + return fcntl(fd, F_SETFL, c); +} diff --git a/libdaemon/dnonblock.h b/libdaemon/dnonblock.h new file mode 100644 index 0000000..e39da4e --- /dev/null +++ b/libdaemon/dnonblock.h @@ -0,0 +1,52 @@ +#ifndef foodaemonnonblockhfoo +#define foodaemonnonblockhfoo + +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + * + * Contains a single function used to change a file descriptor to + * non-blocking mode using fcntl(). + */ + +/** Change the passed file descriptor to non-blocking or blocking + * mode, depending on b. + * @param fd The file descriptor to manipulation + * @param b TRUE if non-blocking mode should be enabled, FALSE if it + * should be disabled + * @return Zero on success, nonzero on failure. + */ +int daemon_nonblock(int fd, int b); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libdaemon/dpid.c b/libdaemon/dpid.c new file mode 100644 index 0000000..7f66d0b --- /dev/null +++ b/libdaemon/dpid.c @@ -0,0 +1,281 @@ +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <signal.h> +#include <string.h> +#include <unistd.h> +#include <errno.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <time.h> +#include <sys/select.h> +#include <fcntl.h> +#include <stddef.h> +#include <sys/time.h> + +#include "dpid.h" +#include "dlog.h" + +#ifndef ETIME +#define ETIME ETIMEDOUT /* For FreeBSD */ +#endif + +#ifndef PATH_MAX +#define PATH_MAX 512 +#endif + +#define VARRUN LOCALSTATEDIR "/run" + +const char *daemon_pid_file_ident = NULL; +daemon_pid_file_proc_t daemon_pid_file_proc = daemon_pid_file_proc_default; + +const char *daemon_pid_file_proc_default(void) { +#ifdef HAVE_ASPRINTF + static char *fn = NULL; + free(fn); + asprintf(&fn, "%s/%s.pid", VARRUN, daemon_pid_file_ident ? daemon_pid_file_ident : "unknown"); +#else + static char fn[PATH_MAX]; + snprintf(fn, sizeof(fn), "%s/%s.pid", VARRUN, daemon_pid_file_ident ? daemon_pid_file_ident : "unknown"); +#endif + + return fn; +} + +static int lock_file(int fd, int enable) { + struct flock f; + + memset(&f, 0, sizeof(f)); + f.l_type = enable ? F_WRLCK : F_UNLCK; + f.l_whence = SEEK_SET; + f.l_start = 0; + f.l_len = 0; + + if (fcntl(fd, F_SETLKW, &f) < 0) { + + if (enable && errno == EBADF) { + f.l_type = F_RDLCK; + + if (fcntl(fd, F_SETLKW, &f) >= 0) + return 0; + } + + daemon_log(LOG_WARNING, "fcntl(F_SETLKW) failed: %s", strerror(errno)); + return -1; + } + + return 0; +} + +pid_t daemon_pid_file_is_running(void) { + const char *fn; + static char txt[256]; + int fd = -1, locked = -1; + pid_t ret = (pid_t) -1, pid; + ssize_t l; + long lpid; + char *e = NULL; + + if (!(fn = daemon_pid_file_proc())) { + errno = EINVAL; + goto finish; + } + + if ((fd = open(fn, O_RDWR, 0644)) < 0) { + if ((fd = open(fn, O_RDONLY, 0644)) < 0) { + if (errno != ENOENT) + daemon_log(LOG_WARNING, "Failed to open PID file: %s", strerror(errno)); + + goto finish; + } + } + + if ((locked = lock_file(fd, 1)) < 0) + goto finish; + + if ((l = read(fd, txt, sizeof(txt)-1)) < 0) { + int saved_errno = errno; + daemon_log(LOG_WARNING, "read(): %s", strerror(errno)); + unlink(fn); + errno = saved_errno; + goto finish; + } + + txt[l] = 0; + txt[strcspn(txt, "\r\n")] = 0; + + errno = 0; + lpid = strtol(txt, &e, 10); + pid = (pid_t) lpid; + + if (errno != 0 || !e || *e || (long) pid != lpid) { + daemon_log(LOG_WARNING, "PID file corrupt, removing. (%s)", fn); + unlink(fn); + errno = EINVAL; + goto finish; + } + + if (kill(pid, 0) != 0 && errno != EPERM) { + int saved_errno = errno; + daemon_log(LOG_WARNING, "Process %lu died: %s; trying to remove PID file. (%s)", (unsigned long) pid, strerror(errno), fn); + unlink(fn); + errno = saved_errno; + goto finish; + } + + ret = pid; + +finish: + + if (fd >= 0) { + int saved_errno = errno; + if (locked >= 0) + lock_file(fd, 0); + close(fd); + errno = saved_errno; + } + + return ret; +} + +int daemon_pid_file_kill(int s) { + pid_t pid; + + if ((pid = daemon_pid_file_is_running()) == (pid_t) -1) + return -1; + + if (kill(pid, s) < 0) + return -1; + + return 0; +} + +int daemon_pid_file_kill_wait(int s, int m) { + pid_t pid; + time_t t; + + if ((pid = daemon_pid_file_is_running()) < 0) + return -1; + + if (kill(pid, s) < 0) + return -1; + + t = time(NULL) + m; + + for (;;) { + int r; + struct timeval tv = { 0, 100000 }; + + if (time(NULL) > t) { + errno = ETIME; + return -1; + } + + if ((r = kill(pid, 0)) < 0 && errno != ESRCH) + return -1; + + if (r) + return 0; + + if (select(0, NULL, NULL, NULL, &tv) < 0) + return -1; + } +} + +int daemon_pid_file_create(void) { + const char *fn; + int fd = -1; + int ret = -1; + int locked = -1; + char t[64]; + ssize_t l; + mode_t u; + + u = umask(022); + + if (!(fn = daemon_pid_file_proc())) { + errno = EINVAL; + goto finish; + } + + if ((fd = open(fn, O_CREAT|O_RDWR|O_EXCL, 0644)) < 0) { + daemon_log(LOG_ERR, "open(%s): %s", fn, strerror(errno)); + goto finish; + } + + if ((locked = lock_file(fd, 1)) < 0) { + int saved_errno = errno; + unlink(fn); + errno = saved_errno; + goto finish; + } + + snprintf(t, sizeof(t), "%lu\n", (unsigned long) getpid()); + + l = strlen(t); + if (write(fd, t, l) != l) { + int saved_errno = errno; + daemon_log(LOG_WARNING, "write(): %s", strerror(errno)); + unlink(fn); + errno = saved_errno; + goto finish; + } + + ret = 0; + +finish: + + if (fd >= 0) { + int saved_errno = errno; + + if (locked >= 0) + lock_file(fd, 0); + + close(fd); + errno = saved_errno; + } + + umask(u); + + return ret; +} + +int daemon_pid_file_remove(void) { + const char *fn; + + if (!(fn = daemon_pid_file_proc())) { + errno = EINVAL; + return -1; + } + + return unlink(fn); +} diff --git a/libdaemon/dpid.h b/libdaemon/dpid.h new file mode 100644 index 0000000..66cdbb1 --- /dev/null +++ b/libdaemon/dpid.h @@ -0,0 +1,106 @@ +#ifndef foodaemonpidhfoo +#define foodaemonpidhfoo + +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#include <sys/types.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + * + * Contains an API for manipulating PID files. + */ + +/** Prototype of a function for generating the name of a PID file. + */ +typedef const char* (*daemon_pid_file_proc_t)(void); + +/** Identification string for the PID file name, only used when + * daemon_pid_file_proc is set to daemon_pid_file_proc_default(). Use + * daemon_ident_from_argv0() to generate an identification string from + * argv[0] + */ +extern const char *daemon_pid_file_ident; + +/** A function pointer which is used to generate the name of the PID + * file to manipulate. Points to daemon_pid_file_proc_default() by + * default. + */ +extern daemon_pid_file_proc_t daemon_pid_file_proc; + +/** A function for creating a pid file name from + * daemon_pid_file_ident + * @return The PID file path + */ +const char *daemon_pid_file_proc_default(void); + +/** Creates PID pid file for the current process + * @return zero on success, nonzero on failure + */ +int daemon_pid_file_create(void); + +/** Removes the PID file of the current process + * @return zero on success, nonzero on failure + */ +int daemon_pid_file_remove(void); + +/** Returns the PID file of a running daemon, if available + * @return The PID or negative on failure + */ +pid_t daemon_pid_file_is_running(void); + +/** Kills a running daemon, if available + * @param s The signal to send + * @return zero on success, nonzero on failure + */ +int daemon_pid_file_kill(int s); + +/** This variable is defined to 1 iff daemon_pid_file_kill_wait() is supported. + * @since 0.3 + * @see daemon_pid_file_kill_wait() */ +#define DAEMON_PID_FILE_KILL_WAIT_AVAILABLE 1 + +/** Similar to daemon_pid_file_kill() but waits until the process + * died. This functions is new in libdaemon 0.3. The macro + * DAEMON_PID_FILE_KILL_WAIT_AVAILABLE is defined iff libdaemon + * supports this function. + * + * @param s The signal to send + * @param m Seconds to wait at maximum + * @return zero on success, nonzero on failure (timeout condition is considered a failure) + * @since 0.3 + * @see DAEMON_PID_FILE_KILL_WAIT_AVAILABLE + */ +int daemon_pid_file_kill_wait(int s, int m); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libdaemon/dsignal.c b/libdaemon/dsignal.c new file mode 100644 index 0000000..e60fb38 --- /dev/null +++ b/libdaemon/dsignal.c @@ -0,0 +1,160 @@ +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <fcntl.h> +#include <unistd.h> +#include <errno.h> +#include <string.h> +#include <stdarg.h> +#include <signal.h> + +#include "dsignal.h" +#include "dlog.h" +#include "dnonblock.h" + +static int _signal_pipe[2] = { -1, -1 }; + +static void _sigfunc(int s) { + int saved_errno = errno; + write(_signal_pipe[1], &s, sizeof(s)); + errno = saved_errno; +} + +static int _init(void) { + + if (_signal_pipe[0] < 0 || _signal_pipe[1] < 0) { + if (pipe(_signal_pipe) < 0) { + daemon_log(LOG_ERR, "pipe(): %s", strerror(errno)); + return -1; + } + + if (daemon_nonblock(_signal_pipe[0], 1) < 0 || daemon_nonblock(_signal_pipe[1], 1) < 0) { + daemon_signal_done(); + return -1; + } + } + + return 0; +} + +int daemon_signal_install(int s){ + sigset_t ss; + struct sigaction sa; + + if (_init() < 0) + return -1; + + if (sigemptyset(&ss) < 0) { + daemon_log(LOG_ERR, "sigemptyset(): %s", strerror(errno)); + return -1; + } + + if (sigaddset(&ss, s) < 0) { + daemon_log(LOG_ERR, "sigaddset(): %s", strerror(errno)); + return -1; + } + + if (sigprocmask(SIG_UNBLOCK, &ss, NULL) < 0) { + daemon_log(LOG_ERR, "sigprocmask(): %s", strerror(errno)); + return -1; + } + + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = _sigfunc; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART; + + if (sigaction(s, &sa, NULL) < 0) { + daemon_log(LOG_ERR, "sigaction(%s, ...) failed: %s", strsignal(s), strerror(errno)); + return -1; + } + + return 0; +} + +int daemon_signal_init(int s, ...) { + int sig, r = 0; + va_list ap; + + if (_init() < 0) + return -1; + + va_start(ap, s); + + sig = s; + while (sig > 0) { + if ((r = daemon_signal_install(sig)) < 0) + break; + + sig = va_arg(ap, int); + } + + va_end(ap); + + return r; +} + +void daemon_signal_done(void) { + int saved_errno = errno; + + if (_signal_pipe[0] != -1) + close(_signal_pipe[0]); + + if (_signal_pipe[1] != -1) + close(_signal_pipe[1]); + + _signal_pipe[0] = _signal_pipe[1] = -1; + + errno = saved_errno; +} + +int daemon_signal_next(void) { + int s; + ssize_t r; + + if ((r = read(_signal_pipe[0], &s, sizeof(s))) == sizeof(s)) + return s; + + if (r < 0) { + + if (errno == EAGAIN) + return 0; + else { + daemon_log(LOG_ERR, "read(signal_pipe[0], ...): %s", strerror(errno)); + return -1; + } + } + + daemon_log(LOG_ERR, "Short read() on signal pipe."); + return -1; +} + +int daemon_signal_fd(void) { + return _signal_pipe[0]; +} diff --git a/libdaemon/dsignal.h b/libdaemon/dsignal.h new file mode 100644 index 0000000..1edfdcc --- /dev/null +++ b/libdaemon/dsignal.h @@ -0,0 +1,80 @@ +#ifndef foodaemonsignalhfoo +#define foodaemonsignalhfoo + +/*** + This file is part of libdaemon. + + Copyright 2003-2008 Lennart Poettering + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +***/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + * + * Contains the API for serializing signals to a pipe for + * usage with select() or poll(). + * + * You should register all signals you + * wish to handle with select() in your main loop with + * daemon_signal_init() or daemon_signal_install(). After that you + * should sleep on the file descriptor returned by daemon_signal_fd() + * and get the next signal recieved with daemon_signal_next(). You + * should call daemon_signal_done() before exiting. + */ + +/** Installs signal handlers for the specified signals + * @param s, ... The signals to install handlers for. The list should be terminated by 0 + * @return zero on success, nonzero on failure + */ +int daemon_signal_init(int s, ...); + +/** Install a signal handler for the specified signal + * @param s The signalto install handler for + * @return zero onsuccess,nonzero on failure + */ +int daemon_signal_install(int s); + +/** Free resources of signal handling, should be called before daemon exit + */ +void daemon_signal_done(void); + +/** Return the next signal recieved. This function will not + * block. Instead it returns 0 if no signal is queued. + * @return The next queued signal if one is queued, zero if none is + * queued, negative on failure. + */ +int daemon_signal_next(void); + +/** Return the file descriptor the daemon should select() on for + * reading. Whenever the descriptor is ready you should call + * daemon_signal_next() to get the next signal queued. + * @return The file descriptor or negative on failure + */ +int daemon_signal_fd(void); + +#ifdef __cplusplus +} +#endif + +#endif |