update mediaserv to drop privileges (start as root) and fork into the background
g0dil [Tue, 14 Nov 2006 13:22:04 +0000 (13:22 +0000)]
main.cc

diff --git a/main.cc b/main.cc
index 5c057c7..36b0946 100644 (file)
--- a/main.cc
+++ b/main.cc
 
 // Custom includes
 #include <unistd.h>
+#include <sys/types.h>
+#include <pwd.h>
+#include <grp.h>
+
 #include <iostream>
 
+#include "Utils/Exception.hh"
+#include "Utils/DaemonTools.hh"
 #include "Server/HTTPLogger.hh"
 #include "Server/SimpleHTTPServer.hh"
 #include "Socket/TCPSocketHandle.hh"
 #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;
 }