Strip whitespace for secrets
[apps/pfixtools.git] / daemon.c
index d3dc00d..392dccb 100644 (file)
--- 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                  */
 /*          ~~~~~~~~~                                                         */
 /*  ________________________________________________________________________  */
 /*                                                                            */
  */
 
 #include <sys/un.h>
+#include <fcntl.h>
 
 #include "common.h"
 #include "daemon.h"
 
-int tcp_listen(const struct sockaddr *addr, socklen_t len)
+static int setnonblock(int sock)
+{
+    int res = fcntl(sock, F_GETFL);
+
+    if (res < 0) {
+        UNIXERR("fcntl");
+        return -1;
+    }
+
+    if (fcntl(sock, F_SETFL, res | O_NONBLOCK) < 0) {
+        UNIXERR("fcntl");
+        return -1;
+    }
+
+    return 0;
+}
+
+
+int tcp_listen_nonblock(const struct sockaddr *addr, socklen_t len)
 {
     int sock;
 
@@ -78,6 +97,11 @@ int tcp_listen(const struct sockaddr *addr, socklen_t len)
         return -1;
     }
 
+    if (setnonblock(sock)) {
+        close(sock);
+        return -1;
+    }
+
     if (listen(sock, 0) < 0) {
         UNIXERR("bind");
         close(sock);
@@ -87,3 +111,41 @@ int tcp_listen(const struct sockaddr *addr, socklen_t len)
     return sock;
 }
 
+int accept_nonblock(int fd)
+{
+    int sock = accept(fd, NULL, 0);
+
+    if (sock < 0) {
+        UNIXERR("accept");
+        return -1;
+    }
+
+    if (setnonblock(sock)) {
+        close(sock);
+        return -1;
+    }
+
+    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;
+}