File: CGI.hs

package info (click to toggle)
ghc-cvs 20040725-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 68,484 kB
  • ctags: 19,658
  • sloc: haskell: 251,945; ansic: 109,709; asm: 24,961; sh: 12,825; perl: 5,786; makefile: 5,334; xml: 3,884; python: 682; yacc: 650; lisp: 477; cpp: 337; ml: 76; fortran: 24; csh: 18
file content (305 lines) | stat: -rw-r--r-- 8,749 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
-----------------------------------------------------------------------------
-- |
-- Module      :  Network.CGI
-- Copyright   :  (c) The University of Glasgow 2001
-- License     :  BSD-style (see the file libraries/network/LICENSE)
-- 
-- Maintainer  :  libraries@haskell.org
-- Stability   :  experimental
-- Portability :  non-portable (uses Control.Exception)
--
-- Haskell binding for CGI
--
-- Original Version by Erik Meijer <mailto:erik@cs.ruu.nl>
-- Further hacked on by Sven Panne <mailto:sven.panne@aedion.de>
-- Further hacking by Andy Gill <mailto:andy@galconn.com>
--
-----------------------------------------------------------------------------

-- note: if using Windows, you might need to wrap 'withSocketsDo' round main.

module Network.CGI (
    Html, 
    wrapper,            -- ::           ([(String,String)] -> IO Html) -> IO ()
    pwrapper,           -- :: PortID -> ([(String,String)] -> IO Html) -> IO ()
    connectToCGIScript  -- :: String -> PortID -> IO ()
  ) where

import Data.Char ( ord, chr, toUpper, isDigit, isAlphaNum, isHexDigit )
import System.Environment ( getEnv )
import Control.Monad(MonadPlus(..), guard)
import System.IO

import Text.Html
import Control.Exception as Exception
import Control.Concurrent

import Network
import Network.Socket as Socket

-- ---------------------------------------------------------------------------
-- Yet another combinator parser library

-- NOTE: This is all a little bit of a sledgehammer here for the simple task
-- at hand...

-- The parser monad

newtype Parser a = Parser (String -> [(a,String)])

instance Functor Parser where
   -- map :: (a -> b) -> (Parser a -> Parser b)
   fmap f (Parser p) = Parser (\inp -> [(f v, out) | (v, out) <- p inp])

instance Monad Parser where
   -- return :: a -> Parser a
   return v = Parser (\inp -> [(v,inp)])

   -- >>= :: Parser a -> (a -> Parser b) -> Parser b
   (Parser p) >>= f = Parser (\inp -> concat [papply (f v) out
                                             | (v,out) <- p inp])

instance MonadPlus Parser where
   -- zero :: Parser a
   mzero = Parser (\_ -> [])
   -- (++) :: Parser a -> Parser a -> Parser a
   (Parser p) `mplus` (Parser q) = Parser (\inp -> (p inp ++ q inp))


-- Other primitive parser combinators

item :: Parser Char
item = Parser (\inp -> case inp of
                     []     -> []
                     (x:xs) -> [(x,xs)])

force :: Parser a -> Parser a
force (Parser p) = Parser (\inp -> let x = p inp in
                             (fst (head x), snd (head x)) : tail x)

first :: Parser a -> Parser a
first (Parser p) = Parser (\inp -> case p inp of
                            []    -> []
                            (x:_) -> [x])

papply :: Parser a -> String -> [(a,String)]
papply (Parser p) inp = p inp


-- Derived combinators

plusplusplus :: Parser a -> Parser a -> Parser a
p `plusplusplus` q = first (p `mplus` q)

sat :: (Char -> Bool) -> Parser Char
sat p = do {x <- item; guard (p x); return x}

many :: Parser a -> Parser [a]
many p = force (many1 p `plusplusplus` return [])

many1 :: Parser a -> Parser [a]
many1 p = do {x <- p; xs <- many p; return (x:xs)}

sepby :: Parser a -> Parser b -> Parser [a]
p `sepby` sep = (p `sepby1` sep) `plusplusplus` return []

sepby1 :: Parser a -> Parser b -> Parser [a]
p `sepby1` sep = do x  <- p
                    xs <- many (do {sep; p})
                    return(x:xs)

char :: Char -> Parser Char
char x = sat (x==)

alphanum :: Parser Char
alphanum = sat isAlphaNum

string :: String -> Parser String
string []     = return ""
string (x:xs) = do char x
                   string xs
                   return (x:xs)

hexdigit :: Parser Char
hexdigit = sat isHexDigit

-- ---------------------------------------------------------------------------
-- Decoding application/x-www-form-urlencoded data

-- An URL encoded value consist of a sequence of
-- zero or more name "=" value pairs separated by "&"

-- Env ::= [Name "=" Value {"&" Name "=" Value}]

-- Names and values are URL-encoded,
-- according to the following table
-- 
--    character | encoding
--    ----------|---------
--     ' '      | '+'
--     '<'      | "%XX"
-- 	c       | "%"hexval(ord c)

urlDecode :: String -> [(String,String)]
urlDecode s = case papply env s of
                 [] -> []
                 ((e,_):_) -> e

env :: Parser [(String,String)]
env = (do n <- urlEncoded
          string "="
          v <- urlEncoded
          return (n,v)) `sepby` (string "&")

urlEncoded :: Parser String
urlEncoded
 = many ( alphanum `mplus` extra `mplus` safe
         `mplus` do{ char '+' ; return ' '}
         `mplus` do{ char '%'
		   ; d <- hexadecimal
		   ; return $ chr (hex2int d)
		   }
         )

extra :: Parser Char
extra = sat (`elem` "!*'(),")

safe :: Parser Char
safe = sat (`elem` "$-_.")

hexadecimal :: Parser HexString
hexadecimal = do d1 <- hexdigit
                 d2 <- hexdigit
                 return [d1,d2]

type HexString = String

hex2int :: HexString -> Int
hex2int ds = foldl (\n d -> n*16+d) 0 (map (toInt . toUpper) ds)
   where toInt d | isDigit d    =  ord d - ord '0'
         toInt d | isHexDigit d = (ord d - ord 'A') + 10
         toInt d                = error ("hex2int: illegal hex digit " ++ [d])

-- A function to do URL encoding and proving its correctness might be a
-- nice exercise for the book.
-- 
-- We don't usually need it for CGI scripts though. The browser does the
-- encoding and the CGI script does the decoding.

-- ---------------------------------------------------------------------------
-- Hide the CGI protocol from the programmer

wrapper :: ([(String,String)] -> IO Html) -> IO ()
wrapper f = do qs      <- getQueryString
               cgiVars <- getCgiVars
               a       <- f (cgiVars ++ urlDecode qs)
	       putStr "Content-type: text/html\n\n"
               putStr (renderHtml a)

getCgiVars :: IO [(String,String)]
getCgiVars = do vals <- mapM myGetEnv cgiVarNames
                return (zip cgiVarNames vals)

cgiVarNames :: [String]
cgiVarNames =
   [ "DOCUMENT_ROOT"
   , "AUTH_TYPE"
   , "GATEWAY_INTERFACE"
   , "SERVER_SOFTWARE"
   , "SERVER_NAME"
   , "REQUEST_METHOD"
   , "SERVER_ADMIN"
   , "SERVER_PORT"
   , "QUERY_STRING"
   , "CONTENT_LENGTH"
   , "CONTENT_TYPE"
   , "REMOTE_USER"
   , "REMOTE_IDENT"
   , "REMOTE_ADDR"
   , "REMOTE_HOST"
   , "TZ"
   , "PATH"
   , "PATH_INFO"
   , "PATH_TRANSLATED"
   , "SCRIPT_NAME"
   , "SCRIPT_FILENAME"
   , "HTTP_CONNECTION"
   , "HTTP_ACCEPT_LANGUAGE"
   , "HTTP_ACCEPT"
   , "HTTP_HOST"
   , "HTTP_UA_COLOR"
   , "HTTP_UA_CPU"
   , "HTTP_UA_OS"
   , "HTTP_UA_PIXELS"
   , "HTTP_USER_AGENT"
   ]                      


pwrapper :: PortID -> ([(String,String)] -> IO Html) -> IO ()
pwrapper pid f = 
       do { sock <- listenOn pid
          ; acceptConnections fn sock
          }
  where
       fn h = do { qs <- hGetLine h
                 ; a <- f (urlDecode qs)
	         ; hPutStr h "Content-type: text/html\n\n"
                 ; hPutStr h (renderHtml a)
                 }

acceptConnections fn sock = do
  (h, SockAddrInet port haddr) <- accept' sock
  forkIO (fn h `finally` (hClose h))
  acceptConnections fn sock

accept' :: Socket 		-- Listening Socket
       -> IO (Handle,SockAddr)	-- StdIO Handle for read/write
accept' sock = do
 (sock', addr) <- Socket.accept sock
 handle	<- socketToHandle sock' ReadWriteMode
 return (handle,addr)

-- ---------------------------------------------------------------------------
-- Small boot function for creating dummy cgi scripts

-- Sample program:
-- 
-- 	   main = connectToCGIScript "localhost" (PortNumber 3432)
-- 

connectToCGIScript :: String -> PortID -> IO ()
connectToCGIScript host portId
     = do { str <- getQueryString
          ; h <- connectTo host portId
                 `Exception.catch`
                   (\ e -> abort "Can not connect to CGI damon." e)
	  ; hPutStrLn h str
	  ; (sendBack h `finally` (hClose h))
               `Prelude.catch` (\e -> if isEOFError e
			              then return ()
                                      else ioError e)
          }

abort :: String -> Exception -> IO a
abort msg e = 
    do { putStrLn ("Content-type: text/html\n\n" ++
		   "<html><body>" ++ msg ++ "</body></html>")
       ; throw e
       }

sendBack h = do { s <- hGetLine h
                ; putStrLn s
		; sendBack h
                }

getQueryString :: IO String
getQueryString = do
   method <- myGetEnv "REQUEST_METHOD"
   case method of
      "POST" -> do len <- myGetEnv "CONTENT_LENGTH"
                   inp <- getContents
                   return (take (read len) inp)
      _      -> myGetEnv "QUERY_STRING"

myGetEnv :: String -> IO String
myGetEnv v = Prelude.catch (getEnv v) (const (return ""))