+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;
+}
+
+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;
+}