added compile time options NOCRYPT,NODAEMON,NOEXEC for easyier windows porting
[anytun.git] / src / daemon.hpp
blobbe5c7104c141feccf2e0b29cd621855318b7eee7
1 #ifndef _DAEMON_HPP
2 #define _DAEMON_HPP
3 #ifndef NODAEMON
5 void chrootAndDrop(std::string const& chrootdir, std::string const& username)
7 if (getuid() != 0)
9 std::cerr << "this programm has to be run as root in order to run in a chroot" << std::endl;
10 exit(-1);
13 struct passwd *pw = getpwnam(username.c_str());
14 if(pw) {
15 if(chroot(chrootdir.c_str()))
17 std::cerr << "can't chroot to " << chrootdir << std::endl;
18 exit(-1);
20 cLog.msg(Log::PRIO_NOTICE) << "we are in chroot jail (" << chrootdir << ") now" << std::endl;
21 chdir("/");
22 if (initgroups(pw->pw_name, pw->pw_gid) || setgid(pw->pw_gid) || setuid(pw->pw_uid))
24 std::cerr << "can't drop to user " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl;
25 exit(-1);
27 cLog.msg(Log::PRIO_NOTICE) << "dropped user to " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl;
29 else
31 std::cerr << "unknown user " << username << std::endl;
32 exit(-1);
36 void daemonize()
38 pid_t pid;
40 pid = fork();
41 if(pid) exit(0);
42 setsid();
43 pid = fork();
44 if(pid) exit(0);
46 // std::cout << "running in background now..." << std::endl;
48 int fd;
49 // for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors
50 for (fd=0;fd<=2;fd++) // close all file descriptors
51 close(fd);
52 fd=open("/dev/null",O_RDWR); // stdin
53 dup(fd); // stdout
54 dup(fd); // stderr
55 umask(027);
57 #endif
58 #endif