switched to endpoint @ anytun-config as well
[anytun.git] / src / daemon.hpp
blob13c4132a3485a25005015418c4bb9e86011c4247
2 void chrootAndDrop(std::string const& chrootdir, std::string const& username)
4 if (getuid() != 0)
6 std::cerr << "this programm has to be run as root in order to run in a chroot" << std::endl;
7 exit(-1);
10 struct passwd *pw = getpwnam(username.c_str());
11 if(pw) {
12 if(chroot(chrootdir.c_str()))
14 std::cerr << "can't chroot to " << chrootdir << std::endl;
15 exit(-1);
17 cLog.msg(Log::PRIO_NOTICE) << "we are in chroot jail (" << chrootdir << ") now" << std::endl;
18 chdir("/");
19 if (initgroups(pw->pw_name, pw->pw_gid) || setgid(pw->pw_gid) || setuid(pw->pw_uid))
21 std::cerr << "can't drop to user " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl;
22 exit(-1);
24 cLog.msg(Log::PRIO_NOTICE) << "dropped user to " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl;
26 else
28 std::cerr << "unknown user " << username << std::endl;
29 exit(-1);
33 void daemonize()
35 pid_t pid;
37 pid = fork();
38 if(pid) exit(0);
39 setsid();
40 pid = fork();
41 if(pid) exit(0);
43 // std::cout << "running in background now..." << std::endl;
45 int fd;
46 // for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors
47 for (fd=0;fd<=2;fd++) // close all file descriptors
48 close(fd);
49 fd=open("/dev/null",O_RDWR); // stdin
50 dup(fd); // stdout
51 dup(fd); // stderr
52 umask(027);