diff options
author | Othmar Gsenger <otti@anytun.org> | 2008-11-17 23:42:12 +0000 |
---|---|---|
committer | Othmar Gsenger <otti@anytun.org> | 2008-11-17 23:42:12 +0000 |
commit | 4bb7e445a67c8a5057a1cadd2d6700c2f7728d26 (patch) | |
tree | 2618271cd8357f1997bd5bc0e2d6b6ca49676fee /src/daemon.hpp | |
parent | added OnConnect Callback (diff) |
fixed anytun-controld
Diffstat (limited to 'src/daemon.hpp')
-rw-r--r-- | src/daemon.hpp | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/src/daemon.hpp b/src/daemon.hpp new file mode 100644 index 0000000..13c4132 --- /dev/null +++ b/src/daemon.hpp @@ -0,0 +1,55 @@ + +void chrootAndDrop(std::string const& chrootdir, std::string const& username) +{ + if (getuid() != 0) + { + std::cerr << "this programm has to be run as root in order to run in a chroot" << std::endl; + exit(-1); + } + + struct passwd *pw = getpwnam(username.c_str()); + if(pw) { + if(chroot(chrootdir.c_str())) + { + std::cerr << "can't chroot to " << chrootdir << std::endl; + exit(-1); + } + cLog.msg(Log::PRIO_NOTICE) << "we are in chroot jail (" << chrootdir << ") now" << std::endl; + chdir("/"); + if (initgroups(pw->pw_name, pw->pw_gid) || setgid(pw->pw_gid) || setuid(pw->pw_uid)) + { + std::cerr << "can't drop to user " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl; + exit(-1); + } + cLog.msg(Log::PRIO_NOTICE) << "dropped user to " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl; + } + else + { + std::cerr << "unknown user " << username << std::endl; + exit(-1); + } +} + +void daemonize() +{ + pid_t pid; + + pid = fork(); + if(pid) exit(0); + setsid(); + pid = fork(); + if(pid) exit(0); + +// std::cout << "running in background now..." << std::endl; + + int fd; +// for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors + for (fd=0;fd<=2;fd++) // close all file descriptors + close(fd); + fd=open("/dev/null",O_RDWR); // stdin + dup(fd); // stdout + dup(fd); // stderr + umask(027); +} + + |