Debian Codegraph @

Network/Wai/Application/Classic/CGI.hs

raw
1 {-# LANGUAGE OverloadedStrings, CPP, ScopedTypeVariables #-}
2
3 module Network.Wai.Application.Classic.CGI (
4 cgiApp
5 ) where
6
7 import qualified Control.Exception as E (SomeException, IOException, try, catch, bracket)
8 import Control.Monad (when, (<=<))
9 import Data.ByteString (ByteString)
10 import qualified Data.ByteString.Char8 as BS (readInt, unpack, tail)
11 import Data.Conduit
12 import qualified Data.Conduit.Binary as CB
13 import qualified Data.Conduit.List as CL
14 import Network.HTTP.Types
15 import Network.SockAddr
16 import Network.Wai
17 import Network.Wai.Conduit
18 import Network.Wai.Application.Classic.Conduit
19 import Network.Wai.Application.Classic.Field
20 import Network.Wai.Application.Classic.Header
21 import Network.Wai.Application.Classic.Path
22 import Network.Wai.Application.Classic.Types
23 import System.Environment
24 import System.IO
25 import System.Process
26
27 -- $setup
28 -- >>> :set -XOverloadedStrings
29
30 ----------------------------------------------------------------
31
32 type ENVVARS = [(String,String)]
33
34 gatewayInterface :: String
35 gatewayInterface = "CGI/1.1"
36
37 ----------------------------------------------------------------
38
39 {-|
40 Handle GET and POST for CGI.
41
42 The program to link this library must ignore SIGCHLD as follows:
43
44 > installHandler sigCHLD Ignore Nothing
45 -}
46 cgiApp :: ClassicAppSpec -> CgiAppSpec -> CgiRoute -> Application
47 cgiApp cspec spec cgii req respond = case method of
48 Right GET -> cgiApp' False cspec spec cgii req respond
49 Right POST -> cgiApp' True cspec spec cgii req respond
50 _ -> respond $ responseLBS methodNotAllowed405 textPlainHeader "Method Not Allowed\r\n" -- xxx
51 where
52 method = parseMethod $ requestMethod req
53
54 cgiApp' :: Bool -> ClassicAppSpec -> CgiAppSpec -> CgiRoute -> Application
55 cgiApp' body cspec spec cgii req respond = E.bracket setup teardown (respond <=< cgi)
56 where
57 setup = execProcess cspec spec cgii req
58 teardown (rhdl,whdl,pid) = do
59 terminateProcess pid -- SIGTERM
60 hClose rhdl
61 hClose whdl
62 cgi (rhdl,whdl,_) = do
63 when body $ toCGI whdl req
64 hClose whdl -- telling EOF
65 fromCGI rhdl
66
67 ----------------------------------------------------------------
68
69 type TRYPATH = Either E.IOException String
70
71 toCGI :: Handle -> Request -> IO ()
72 #if MIN_VERSION_conduit(1,3,0)
73 toCGI whdl req = runConduit (sourceRequestBody req .| CB.sinkHandle whdl)
74 #else
75 toCGI whdl req = sourceRequestBody req $$ CB.sinkHandle whdl
76 #endif
77
78 fromCGI :: Handle -> IO Response
79 fromCGI rhdl = do
80 (src', hs) <- cgiHeader `E.catch` recover
81 let (st, hdr, hasBody) = case check hs of
82 Nothing -> (internalServerError500,[],False)
83 Just (s,h) -> (s,h,True)
84 let src | hasBody = src'
85 | otherwise = CL.sourceNull
86 return $ responseSource st hdr src
87 where
88 check hs = lookup hContentType hs >> case lookup hStatus hs of
89 Nothing -> Just (ok200, hs)
90 Just l -> toStatus l >>= \s -> Just (s,hs')
91 where
92 hs' = filter (\(k,_) -> k /= hStatus) hs
93 toStatus s = BS.readInt s >>= \x -> Just (Status (fst x) s)
94 emptyHeader = []
95 recover (_ :: E.SomeException) = return (CL.sourceNull, emptyHeader)
96 cgiHeader = do
97 (rsrc,hs) <- CB.sourceHandle rhdl $$+ parseHeader
98 src <- toResponseSource rsrc
99 return (src,hs)
100
101 ----------------------------------------------------------------
102
103 execProcess :: ClassicAppSpec -> CgiAppSpec -> CgiRoute -> Request -> IO (Handle, Handle, ProcessHandle)
104 execProcess cspec spec cgii req = do
105 let naddr = showSockAddr . remoteHost $ req
106 epath <- E.try (getEnv "PATH") :: IO TRYPATH
107 (Just whdl,Just rhdl,_,pid) <- createProcess $ proSpec naddr epath
108 hSetEncoding rhdl latin1
109 hSetEncoding whdl latin1
110 return (rhdl, whdl, pid)
111 where
112 proSpec naddr epath = CreateProcess {
113 cmdspec = RawCommand prog []
114 , cwd = Nothing
115 , env = Just $ makeEnv req naddr scriptName pathinfo (softwareName cspec) epath
116 , std_in = CreatePipe
117 , std_out = CreatePipe
118 , std_err = Inherit
119 , close_fds = True
120 #if __GLASGOW_HASKELL__ >= 702
121 , create_group = True
122 #endif
123 #if __GLASGOW_HASKELL__ >= 707
124 , delegate_ctlc = False
125 #endif
126 #if __GLASGOW_HASKELL__ >= 800
127 , detach_console = False
128 , create_new_console = False
129 , new_session = False
130 , child_group = Nothing
131 , child_user = Nothing
132 #endif
133 #if __GLASGOW_HASKELL__ >= 802
134 , use_process_jobs = False
135 #endif
136 }
137 (prog, scriptName, pathinfo) =
138 pathinfoToCGI (cgiSrc cgii)
139 (cgiDst cgii)
140 (rawPathInfo req)
141 (indexCgi spec)
142
143 makeEnv :: Request -> String -> String -> String -> ByteString ->
144 TRYPATH -> ENVVARS
145 makeEnv req naddr scriptName pathinfo sname epath = addPath epath . addLen . addType . addCookie $ baseEnv
146 where
147 baseEnv = [
148 ("GATEWAY_INTERFACE", gatewayInterface)
149 , ("SCRIPT_NAME", scriptName)
150 , ("REQUEST_METHOD", BS.unpack . requestMethod $ req)
151 , ("SERVER_NAME", BS.unpack host)
152 , ("SERVER_PORT", BS.unpack port)
153 , ("REMOTE_ADDR", naddr)
154 , ("SERVER_PROTOCOL", show . httpVersion $ req)
155 , ("SERVER_SOFTWARE", BS.unpack sname)
156 , ("PATH_INFO", pathinfo)
157 , ("QUERY_STRING", query req)
158 ]
159 headers = requestHeaders req
160 addLen = addLength "CONTENT_LENGTH" $ requestBodyLength req
161 addType = addEnv "CONTENT_TYPE" $ lookup hContentType headers
162 addCookie = addEnv "HTTP_COOKIE" $ lookup hCookie headers
163 addPath (Left _) ev = ev
164 addPath (Right path) ev = ("PATH", path) : ev
165 query = BS.unpack . safeTail . rawQueryString
166 where
167 safeTail "" = ""
168 safeTail bs = BS.tail bs
169 (host, port) = hostPort req
170
171 addEnv :: String -> Maybe ByteString -> ENVVARS -> ENVVARS
172 addEnv _ Nothing envs = envs
173 addEnv key (Just val) envs = (key,BS.unpack val) : envs
174
175 addLength :: String -> RequestBodyLength -> ENVVARS -> ENVVARS
176 addLength _ ChunkedBody envs = envs
177 addLength key (KnownLength len) envs = (key, show len) : envs
178
179 {-|
180
181 >>> pathinfoToCGI "/cgi-bin/" "/User/cgi-bin/" "/cgi-bin/foo" "index.cgi"
182 ("/User/cgi-bin/foo","/cgi-bin/foo","")
183 >>> pathinfoToCGI "/cgi-bin/" "/User/cgi-bin/" "/cgi-bin/foo/bar" "index.cgi"
184 ("/User/cgi-bin/foo","/cgi-bin/foo","/bar")
185 >>> pathinfoToCGI "/cgi-bin/" "/User/cgi-bin/" "/cgi-bin/" "index.cgi"
186 ("/User/cgi-bin/index.cgi","/cgi-bin/index.cgi","")
187
188 -}
189
190 pathinfoToCGI :: Path -> Path -> Path -> Path -> (FilePath, String, String)
191 pathinfoToCGI src dst path index = (prog, scriptName, pathinfo)
192 where
193 path' = path <\> src
194 (prog',pathinfo')
195 | src == path = (index, "")
196 | otherwise = breakAtSeparator path'
197 prog = pathString (dst </> prog')
198 scriptName = pathString (src </> prog')
199 pathinfo = pathString pathinfo'