X-Git-Url: http://git.madism.org/?a=blobdiff_plain;f=daemon.c;h=ebda9671ddebed14381f23a890f05f036ab686b9;hb=1ff926eac33152aee930a454ac1d3dec6e6e5faf;hp=1d40424251ca781907ddd711d4067eaebf089586;hpb=90f03cb500b9d269c49291a257eb9472fd6c8fad;p=apps%2Fpfixtools.git diff --git a/daemon.c b/daemon.c index 1d40424..ebda967 100644 --- a/daemon.c +++ b/daemon.c @@ -1,5 +1,5 @@ /******************************************************************************/ -/* postlicyd: a postfix policy daemon with a lot of features */ +/* pfixtools: a collection of postfix related tools */ /* ~~~~~~~~~ */ /* ________________________________________________________________________ */ /* */ @@ -33,8 +33,10 @@ * Copyright © 2007 Pierre Habouzit */ -#include #include +#include +#include +#include #include "common.h" #include "daemon.h" @@ -57,7 +59,7 @@ static int setnonblock(int sock) } -int tcp_listen(const struct sockaddr *addr, socklen_t len) +int tcp_listen_nonblock(const struct sockaddr *addr, socklen_t len) { int sock; @@ -127,3 +129,50 @@ int accept_nonblock(int fd) return sock; } + +int daemon_detach(void) +{ + pid_t pid; + + close(STDIN_FILENO); + close(STDOUT_FILENO); + close(STDERR_FILENO); + + open("/dev/null", O_RDWR); + open("/dev/null", O_RDWR); + open("/dev/null", O_RDWR); + + pid = fork(); + if (pid < 0) + return -1; + if (pid) + exit(0); + + setsid(); + return 0; +} + +int drop_privileges(const char *user, const char *group) +{ + if (!geteuid()) { + struct passwd *pw; + struct group *gr; + + if (group) { + gr = getgrnam(group); + if (!gr) + return -1; + setgid(gr->gr_gid); + } + + pw = getpwnam(user); + if (!pw) + return -1; + if (!group) { + setgid(pw->pw_gid); + } + setuid(pw->pw_uid); + } + + return 0; +}