/******************************************************************************/
-/* postlicyd: a postfix policy daemon with a lot of features */
+/* pfixtools: a collection of postfix related tools */
/* ~~~~~~~~~ */
/* ________________________________________________________________________ */
/* */
* Copyright © 2007 Pierre Habouzit
*/
+#include <fcntl.h>
+#include <grp.h>
+#include <pwd.h>
#include <sys/un.h>
-#include "postlicyd.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;
return -1;
}
+ if (setnonblock(sock)) {
+ close(sock);
+ return -1;
+ }
+
if (listen(sock, 0) < 0) {
UNIXERR("bind");
close(sock);
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;
+}
+
+int drop_privilegies(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;
+}