-import Network.URI
-import Prelude hiding (catch)
-import System.IO
-import System.IO.Error hiding (catch)
-
-
-type Resource a = ReaderT Interaction IO a
-
-
-{- /aaa/bbb/ccc にアクセスされた時、もし /aaa/bbb に貪欲なリソースがあ
- れば、假に /aaa/bbb/ccc に何らかのリソースがあったとしても必ず
- /aaa/bbb が撰ばれる。/aaa/bbb のリソースが貪欲でなければ、それは無視
- される。 -}
-data ResourceDef = ResourceDef {
- resUsesNativeThread :: Bool
- , resIsGreedy :: Bool
- , resGet :: Maybe (Resource ())
- , resHead :: Maybe (Resource ())
- , resPost :: Maybe (Resource ())
- , resPut :: Maybe (Resource ())
- , resDelete :: Maybe (Resource ())
- }
-type ResTree = ResNode -- root だから Map ではない
-type ResSubtree = Map String ResNode
-data ResNode = ResNode (Maybe ResourceDef) ResSubtree
-
-
-mkResTree :: [ ([String], ResourceDef) ] -> ResTree
-mkResTree list = processRoot list
- where
- processRoot :: [ ([String], ResourceDef) ] -> ResTree
- processRoot list
- = let (roots, nonRoots) = partition (\ (path, _) -> path == []) list
- children = processNonRoot nonRoots
- in
- if null roots then
- -- / にリソースが定義されない。/foo とかにはあるかも。
- ResNode Nothing children
- else
- -- / がある。
- let (_, def) = last roots
- in
- ResNode (Just def) children
-
- processNonRoot :: [ ([String], ResourceDef) ] -> ResSubtree
- processNonRoot list
- = let subtree = M.fromList [(name, node name)
- | name <- childNames]
- childNames = [name | (name:_, _) <- list]
- node name = let defs = [def | (path, def) <- list, path == [name]]
- in
- if null defs then
- -- この位置にリソースが定義されない。
- -- もっと下にはあるかも。
- ResNode Nothing children
- else
- -- この位置にリソースがある。
- ResNode (Just $ last defs) children
- children = processNonRoot [(path, def)
- | (_:path, def) <- list, not (null path)]
- in
- subtree
-
-
-findResource :: ResTree -> URI -> Maybe ResourceDef
-findResource (ResNode rootDefM subtree) uri
- = let pathStr = uriPath uri
- path = [x | x <- splitBy (== '/') pathStr, x /= ""]
- in
- if null path then
- rootDefM
- else
- walkTree subtree path
+import Network.Socket hiding (accept)
+import Network.URI hiding (path)
+import OpenSSL.X509
+
+-- |The 'Resource' monad. This monad implements
+-- 'Control.Monad.Trans.MonadIO' so it can do any 'Prelude.IO'
+-- actions.
+newtype Resource a = Resource { unRes :: ReaderT Interaction IO a }
+
+instance Functor Resource where
+ fmap f c = Resource (fmap f (unRes c))
+
+instance Monad Resource where
+ c >>= f = Resource (unRes c >>= unRes . f)
+ return = Resource . return
+ fail = Resource . fail
+
+instance MonadIO Resource where
+ liftIO = Resource . liftIO
+
+
+runRes :: Resource a -> Interaction -> IO a
+runRes r itr
+ = runReaderT (unRes r) itr
+
+
+getInteraction :: Resource Interaction
+getInteraction = Resource ask
+
+
+-- |Get the 'Network.HTTP.Lucu.Config.Config' value which is used for
+-- the httpd.
+getConfig :: Resource Config
+getConfig = do itr <- getInteraction
+ return $! itrConfig itr
+
+
+-- |Get the 'Network.Socket.SockAddr' of the remote host. If you want
+-- a string representation instead of 'Network.Socket.SockAddr', use
+-- 'getRemoteAddr''.
+getRemoteAddr :: Resource SockAddr
+getRemoteAddr = do itr <- getInteraction
+ return $! itrRemoteAddr itr
+
+
+-- |Get the string representation of the address of remote host. If
+-- you want a 'Network.Socket.SockAddr' instead of 'Prelude.String',
+-- use 'getRemoteAddr'.
+getRemoteAddr' :: Resource String
+getRemoteAddr' = do addr <- getRemoteAddr
+ (Just str, _) <- liftIO $! getNameInfo [NI_NUMERICHOST] True False addr
+ return str
+
+-- |Resolve an address to the remote host.
+getRemoteHost :: Resource String
+getRemoteHost = do addr <- getRemoteAddr
+ (Just str, _) <- liftIO $! getNameInfo [] True False addr
+ return str
+
+-- | Return the X.509 certificate of the client, or 'Nothing' if:
+--
+-- * This request didn't came through an SSL stream.
+--
+-- * The client didn't send us its certificate.
+--
+-- * The 'OpenSSL.Session.VerificationMode' of
+-- 'OpenSSL.Session.SSLContext' in
+-- 'Network.HTTP.Lucu.Config.SSLConfig' has not been set to
+-- 'OpenSSL.Session.VerifyPeer'.
+getRemoteCertificate :: Resource (Maybe X509)
+getRemoteCertificate = do itr <- getInteraction
+ return $! itrRemoteCert itr
+
+-- |Get the 'Network.HTTP.Lucu.Request.Request' value which represents
+-- the request header. In general you don't have to use this action.
+getRequest :: Resource Request
+getRequest = do itr <- getInteraction
+ req <- liftIO $! atomically $! readItr itr itrRequest fromJust
+ return req
+
+-- |Get the 'Network.HTTP.Lucu.Request.Method' value of the request.
+getMethod :: Resource Method
+getMethod = do req <- getRequest
+ return $! reqMethod req
+
+-- |Get the URI of the request.
+getRequestURI :: Resource URI
+getRequestURI = do req <- getRequest
+ return $! reqURI req
+
+-- |Get the HTTP version of the request.
+getRequestVersion :: Resource HttpVersion
+getRequestVersion = do req <- getRequest
+ return $! reqVersion req
+
+-- |Get the path of this 'Resource' (to be exact,
+-- 'Network.HTTP.Lucu.Resource.Tree.ResourceDef') in the
+-- 'Network.HTTP.Lucu.Resource.Tree.ResTree'. The result of this
+-- action is the exact path in the tree even if the
+-- 'Network.HTTP.Lucu.Resource.Tree.ResourceDef' is greedy.
+--
+-- Example:
+--
+-- > main = let tree = mkResTree [ (["foo"], resFoo) ]
+-- > in runHttpd defaultConfig tree
+-- >
+-- > resFoo = ResourceDef {
+-- > resIsGreedy = True
+-- > , resGet = Just $ do requestURI <- getRequestURI
+-- > resourcePath <- getResourcePath
+-- > pathInfo <- getPathInfo
+-- > -- uriPath requestURI == "/foo/bar/baz"
+-- > -- resourcePath == ["foo"]
+-- > -- pathInfo == ["bar", "baz"]
+-- > ...
+-- > , ...
+-- > }
+getResourcePath :: Resource [String]
+getResourcePath = do itr <- getInteraction
+ return $! fromJust $! itrResourcePath itr
+
+
+-- |This is an analogy of CGI PATH_INFO. The result is
+-- URI-unescaped. It is always @[]@ if the
+-- 'Network.HTTP.Lucu.Resource.Tree.ResourceDef' is not greedy. See
+-- 'getResourcePath'.
+getPathInfo :: Resource [String]
+getPathInfo = do rsrcPath <- getResourcePath
+ uri <- getRequestURI
+ let reqPathStr = uriPath uri
+ reqPath = [unEscapeString x | x <- splitBy (== '/') reqPathStr, x /= ""]
+ -- rsrcPath と reqPath の共通する先頭部分を reqPath か
+ -- ら全部取り除くと、それは PATH_INFO のやうなものにな
+ -- る。rsrcPath は全部一致してゐるに決まってゐる(でな
+ -- ければこの Resource が撰ばれた筈が無い)ので、
+ -- rsrcPath の長さの分だけ削除すれば良い。
+ return $! drop (length rsrcPath) reqPath
+
+-- |Assume the query part of request URI as
+-- application\/x-www-form-urlencoded, and parse it to pairs of
+-- @(name, formData)@. This action doesn't parse the request body. See
+-- 'inputForm'.
+getQueryForm :: Resource [(String, FormData)]
+getQueryForm = liftM parse' getRequestURI