networkaddress::operator<() throws exception if types don't match
[anytun.git] / src / daemon.hpp
blob9f1715dd12b9773887f8b03b44b134beaeb98fdc
1 #ifndef _DAEMON_HPP
2 #define _DAEMON_HPP
3 #ifndef NODAEMON
5 #include <poll.h>
6 #include <fcntl.h>
7 #include <pwd.h>
8 #include <grp.h>
9 #include <sys/wait.h>
10 #include <sys/stat.h>
11 #include <unistd.h>
13 void chrootAndDrop(std::string const& chrootdir, std::string const& username)
15 if (getuid() != 0)
17 std::cerr << "this programm has to be run as root in order to run in a chroot" << std::endl;
18 exit(-1);
21 struct passwd *pw = getpwnam(username.c_str());
22 if(pw) {
23 if(chroot(chrootdir.c_str()))
25 std::cerr << "can't chroot to " << chrootdir << std::endl;
26 exit(-1);
28 cLog.msg(Log::PRIO_NOTICE) << "we are in chroot jail (" << chrootdir << ") now" << std::endl;
29 chdir("/");
30 if (initgroups(pw->pw_name, pw->pw_gid) || setgid(pw->pw_gid) || setuid(pw->pw_uid))
32 std::cerr << "can't drop to user " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl;
33 exit(-1);
35 cLog.msg(Log::PRIO_NOTICE) << "dropped user to " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl;
37 else
39 std::cerr << "unknown user " << username << std::endl;
40 exit(-1);
44 void daemonize()
46 pid_t pid;
48 pid = fork();
49 if(pid) exit(0);
50 setsid();
51 pid = fork();
52 if(pid) exit(0);
54 // std::cout << "running in background now..." << std::endl;
56 int fd;
57 // for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors
58 for (fd=0;fd<=2;fd++) // close all file descriptors
59 close(fd);
60 fd=open("/dev/null",O_RDWR); // stdin
61 dup(fd); // stdout
62 dup(fd); // stderr
63 umask(027);
65 #endif
66 #endif