From: g0dil Date: Tue, 14 Nov 2006 13:22:04 +0000 (+0000) Subject: update mediaserv to drop privileges (start as root) and fork into the background X-Git-Url: http://g0dil.de/git?a=commitdiff_plain;h=9c080cb572fa0bdff5e2900ed7c6ef8347f1e522;p=mediaserv.git update mediaserv to drop privileges (start as root) and fork into the background --- diff --git a/main.cc b/main.cc index 5c057c7..36b0946 100644 --- a/main.cc +++ b/main.cc @@ -14,8 +14,14 @@ // Custom includes #include +#include +#include +#include + #include +#include "Utils/Exception.hh" +#include "Utils/DaemonTools.hh" #include "Server/HTTPLogger.hh" #include "Server/SimpleHTTPServer.hh" #include "Socket/TCPSocketHandle.hh" @@ -24,37 +30,43 @@ #define prefix_ ///////////////////////////////cc.p//////////////////////////////////////// -namespace { - void errfail(char const * fn) - { - std::cerr << fn << ": (" << errno << ") " << strerror(errno) << "\n"; - exit(1); - } - -} +#define THROW_SYSERR(cmd,e) if (e) throw satcom::lib::SystemException(#cmd,errno) int main(int argc, char** argv) { - //try { + try { + struct ::passwd * pw = getpwnam("media"); THROW_SYSERR( getpwnam, !pw ); + struct ::group * gr = getgrnam("media"); THROW_SYSERR( getgrnam, !gr ); + THROW_SYSERR( setegid,::setegid(gr->gr_gid) < 0 ); + THROW_SYSERR( seteuid, ::seteuid(pw->pw_uid) < 0 ); g0dil::mediaserv::HTTPLogger logger ("log/access.log"); - //try { - if (chdir("wwwroot") < 0) errfail("chdir"); - if (chroot(".") < 0) errfail("chroot"); - if (setreuid(getuid(),getuid()) < 0) errfail("setreuid"); + THROW_SYSERR( seteuid, ::seteuid(0) < 0 ); + THROW_SYSERR( setegid, ::setegid(0) ); + try { + // We have to make sure not to access any sytem files after the chroot + // (initgroups accesses /etc/group, redirect_stdio accesses /dev/null) + satcom::lib::redirect_stdio(); + THROW_SYSERR( initgroups, ::initgroups("media",gr->gr_gid) < 0 ); + THROW_SYSERR( chdir, chdir("wwwroot") < 0 ); + THROW_SYSERR( chroot, chroot(".") < 0 ); satcom::lib::TCPv4ServerSocketHandle socket (argv[1]); + THROW_SYSERR( setregid, ::setregid(gr->gr_gid,gr->gr_gid) < 0 ); + THROW_SYSERR( setreuid, ::setreuid(pw->pw_uid,pw->pw_uid) < 0 ); + satcom::lib::daemonize(); socket.blocking(false); socket.protocol().reuseaddr(true); g0dil::mediaserv::SimpleHTTPServer server (socket,logger); + satcom::lib::Scheduler::instance().process(); -// } -// catch (std::exception const & ex) { -// logger.failedRequest(ex.what()); -// } -// } -// catch (std::exception const & ex) { -// std::cerr << ex.what() << "\n"; -// exit(1); -// } + } + catch (std::exception const & ex) { + logger.failedRequest(ex.what()); + } + } + catch (std::exception const & ex) { + std::cerr << ex.what() << "\n"; + exit(1); + } return 0; }