X-Git-Url: http://git.cielonegro.org/gitweb.cgi?a=blobdiff_plain;f=Main.hs;h=430fdfc62d1281f5e23d6a78344ffde065c37df8;hb=e3e30c2bfa341cef11754e3f4d90b03844ef74d1;hp=736033feda5be8aef8976d81cb397705bed33187;hpb=ae4deb027146109a28b3070904c282dcbb0be4be;p=Rakka.git diff --git a/Main.hs b/Main.hs index 736033f..430fdfc 100644 --- a/Main.hs +++ b/Main.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} +import Control.Exception import Control.Monad import Data.List import Data.Maybe @@ -23,10 +24,13 @@ import System.Console.GetOpt import System.Directory import System.Environment import System.Exit +import System.FilePath import System.IO import System.Log.Handler.Simple import System.Log.Logger import System.Posix.Files +import System.Posix.IO +import System.Posix.Process import System.Posix.Types import System.Posix.User @@ -91,7 +95,7 @@ options = [ Option ['p'] ["port"] , Option ['r'] ["rebuild-index"] (NoArg OptRebuildIndex) - "Rebuild the index database." + "Rebuild the index database. (Only for debug purposes)" , Option ['h'] ["help"] (NoArg OptHelp) @@ -128,18 +132,23 @@ main = withOpenSSL $ gid <- getGroupID opts lsdir <- getLocalStateDir opts + -- Create our localstatedir *before* dropping privileges. createLocalStateDir lsdir uid gid setGroupID gid setUserID uid - setupLogger opts - env <- setupEnv lsdir portNum + -- Now that we have our localstatedir. Let's acquire a lock + -- on the lockfile. Then create other files. + withSystemLock (lsdir "lock") $ + withPidFile (lsdir "pid") $ + do setupLogger opts + env <- setupEnv lsdir portNum - rebuildIndexIfRequested env opts + rebuildIndexIfRequested env opts - infoM logger ("Listening to " ++ show portNum ++ "/tcp...") - runHttpd (envLucuConf env) (resTree env) [fallbackPageEntity env] + infoM logger ("Listening to " ++ show portNum ++ "/tcp...") + runHttpd (envLucuConf env) (resTree env) [fallbackPageEntity env] resTree :: Environment -> ResTree @@ -241,3 +250,29 @@ rebuildIndexIfRequested env opts _ -> False) opts when rebuild $ rebuildIndex (envStorage env) + +withSystemLock :: FilePath -> IO a -> IO a +withSystemLock lockfile = bracket lock' unlock' . const + where + lock' :: IO Fd + lock' = do fd <- openFd + lockfile + ReadWrite + (Just 420) -- 0644, -rw-r--r-- + defaultFileFlags + setLock fd (WriteLock, AbsoluteSeek, 0, 0) + return fd + + unlock' :: Fd -> IO () + unlock' = closeFd + +withPidFile :: FilePath -> IO a -> IO a +withPidFile lockfile = bracket_ mkPid' delPid' + where + mkPid' :: IO () + mkPid' = withFile lockfile WriteMode $ \ h -> + do pid <- getProcessID + hPutStrLn h (show pid) + + delPid' :: IO () + delPid' = removeFile lockfile