]> andersk Git - scripts-static-cat.git/blame - StaticCat.hs
Simplify exception handling using MonadCatchIO.
[scripts-static-cat.git] / StaticCat.hs
CommitLineData
59962b4a
AK
1{-# LANGUAGE DeriveDataTypeable, ViewPatterns #-}
2{-# OPTIONS_GHC -O2 -Wall #-}
3
51cce206 4import Prelude hiding (catch)
59962b4a 5import Control.Applicative
59962b4a 6import Control.Monad
51cce206 7import Control.Monad.CatchIO
59962b4a 8import qualified Data.ByteString.Lazy as B
59cbcd42 9import Data.Char
59962b4a
AK
10import Data.Dynamic
11import qualified Data.Map as M
12import Data.Time.Clock.POSIX
13import Data.Time.Format
14import Network.CGI
15import Numeric
16import System.FilePath
17import System.IO
51cce206 18import System.IO.Error (isDoesNotExistError, isPermissionError)
59962b4a
AK
19import System.Locale
20import System.Posix
21import System.Posix.Handle
22
23encodings :: M.Map String String
24encodings = M.fromList [
59cbcd42 25 (".bz2", "bzip2"),
59962b4a 26 (".gz", "gzip"),
59cbcd42 27 (".z", "compress")
59962b4a
AK
28 ]
29
30types :: M.Map String String
31types = M.fromList [
59cbcd42
AK
32 (".avi", "video/x-msvideo"),
33 (".css", "text/css"),
34 (".doc", "application/msword"),
35 (".gif", "image/gif"),
36 (".htm", "text/html"),
37 (".html", "text/html"),
38 (".ico", "image/vnd.microsoft.icon"),
39 (".il", "application/octet-stream"),
40 (".jar", "application/java-archive"),
41 (".jpeg", "image/jpeg"),
42 (".jpg", "image/jpeg"),
43 (".js", "application/x-javascript"),
44 (".mid", "audio/midi"),
45 (".midi", "audio/midi"),
46 (".mov", "video/quicktime"),
47 (".mp3", "audio/mpeg"),
48 (".mpeg", "video/mpeg"),
49 (".mpg", "video/mpeg"),
50 (".pdf", "application/pdf"),
51 (".png", "image/png"),
52 (".ppt", "application/vnd.ms-powerpoint"),
53 (".ps", "application/postscript"),
54 (".svg", "image/svg+xml"),
55 (".swf", "application/x-shockwave-flash"),
56 (".tar", "application/x-tar"),
57 (".tgz", "application/x-gzip"),
58 (".tif", "image/tiff"),
59 (".tiff", "image/tiff"),
60 (".wav", "audio/x-wav"),
61 (".wmv", "video/x-ms-wmv"),
62 (".xaml", "application/xaml+xml"),
63 (".xap", "application/x-silverlight-app"),
64 (".xhtml", "application/xhtml+xml"),
65 (".xls", "application/vnd.ms-excel"),
66 (".xml", "text/xml"),
67 (".xsl", "text/xml"),
68 (".zip", "application/zip")
59962b4a
AK
69 ]
70
59962b4a
AK
71data MyError = NotModified | Forbidden | NotFound | BadMethod | BadRange
72 deriving (Show, Typeable)
73
74instance Exception MyError
75
76outputMyError :: MyError -> CGI CGIResult
77outputMyError NotModified = setStatus 304 "Not Modified" >> outputNothing
78outputMyError Forbidden = outputError 403 "Forbidden" []
79outputMyError NotFound = outputError 404 "Not Found" []
80outputMyError BadMethod = outputError 405 "Method Not Allowed" []
81outputMyError BadRange = outputError 416 "Requested Range Not Satisfiable" []
82
83checkExtension :: FilePath -> CGI ()
84checkExtension file = do
85 let (base, ext) = splitExtension file
59cbcd42 86 ext' <- case M.lookup (map toLower ext) encodings of
59962b4a
AK
87 Nothing -> return ext
88 Just e -> do
89 setHeader "Content-Encoding" e
90 return $ takeExtension base
91
59cbcd42 92 case M.lookup (map toLower ext') types of
51cce206 93 Nothing -> throw Forbidden
59962b4a
AK
94 Just t -> setHeader "Content-Type" t
95
96checkMethod :: CGI CGIResult -> CGI CGIResult
97checkMethod rOutput = do
98 m <- requestMethod
99 case m of
100 "HEAD" -> rOutput >> outputNothing
101 "GET" -> rOutput
102 "POST" -> rOutput
51cce206 103 _ -> throw BadMethod
59962b4a
AK
104
105httpDate :: String
106httpDate = "%a, %d %b %Y %H:%M:%S %Z"
107formatHTTPDate :: EpochTime -> String
108formatHTTPDate = formatTime defaultTimeLocale httpDate .
109 posixSecondsToUTCTime . realToFrac
110parseHTTPDate :: String -> Maybe EpochTime
111parseHTTPDate = (fromInteger . floor . utcTimeToPOSIXSeconds <$>) .
112 parseTime defaultTimeLocale httpDate
113
114checkModified :: EpochTime -> CGI ()
115checkModified mTime = do
116 setHeader "Last-Modified" $ formatHTTPDate mTime
117 (requestHeader "If-Modified-Since" >>=) $ maybe (return ()) $ \ims ->
51cce206 118 when (parseHTTPDate ims >= Just mTime) $ throw NotModified
59962b4a
AK
119
120checkIfRange :: EpochTime -> CGI (Maybe ())
121checkIfRange mTime = do
122 (requestHeader "If-Range" >>=) $ maybe (return $ Just ()) $ \ir ->
123 return $ if parseHTTPDate ir == Just mTime then Just () else Nothing
124
125parseRange :: String -> FileOffset -> Maybe (FileOffset, FileOffset)
126parseRange (splitAt 6 -> ("bytes=", readDec -> [(a, "-")])) size =
127 Just (a, size - 1)
128parseRange (splitAt 6 -> ("bytes=", readDec -> [(a, '-':(readDec -> [(b, "")]))])) _ =
129 Just (a, b)
130parseRange _ _ = Nothing
131
132checkRange :: EpochTime -> FileOffset -> CGI (Maybe (FileOffset, FileOffset))
133checkRange mTime size = do
134 setHeader "Accept-Ranges" "bytes"
135 (requestHeader "Range" >>=) $ maybe (return Nothing) $ \range -> do
136 (checkIfRange mTime >>=) $ maybe (return Nothing) $ \() -> do
137 case parseRange range size of
138 Just (a, b) | a <= b -> return $ Just (a, b)
51cce206 139 _ -> throw BadRange
59962b4a 140
1cb5cdb0
AK
141outputAll :: Handle -> FileOffset -> CGI CGIResult
142outputAll h size = do
143 setHeader "Content-Length" $ show size
144 outputFPS =<< liftIO (B.hGetContents h)
145
146outputRange :: Handle -> FileOffset -> Maybe (FileOffset, FileOffset) -> CGI CGIResult
147outputRange h size Nothing = outputAll h size
148outputRange h size (Just (a, b)) = do
149 let len = b - a + 1
150
151 setStatus 206 "Partial Content"
152 setHeader "Content-Range" $
153 "bytes " ++ show a ++ "-" ++ show b ++ "/" ++ show size
154 setHeader "Content-Length" $ show len
155 liftIO $ hSeek h AbsoluteSeek (fromIntegral a)
156 outputFPS =<< liftIO (B.hGet h (fromIntegral len))
157
59962b4a 158serveFile :: FilePath -> CGI CGIResult
51cce206 159serveFile file = (`catch` outputMyError) $ do
59962b4a
AK
160 checkExtension file
161
162 checkMethod $ do
163
cee07ba6 164 let handleOpenError e =
51cce206
AK
165 if isDoesNotExistError e then throw NotFound
166 else if isPermissionError e then throw Forbidden
167 else throw e
168 h <- liftIO (openBinaryFile file ReadMode) `catch` handleOpenError
169 (`onException` liftIO (hClose h)) $ do
59962b4a
AK
170
171 status <- liftIO $ hGetStatus h
172 let mTime = modificationTime status
173 size = fileSize status
174 checkModified mTime
175
1cb5cdb0
AK
176 range <- checkRange mTime size
177 outputRange h size range
59962b4a
AK
178
179main :: IO ()
180main = runCGI $ handleErrors $ serveFile =<< pathTranslated
This page took 0.314108 seconds and 5 git commands to generate.