| [1590] | 1 | {-# LANGUAGE DeriveDataTypeable, ViewPatterns #-} | 
|---|
 | 2 | {-# OPTIONS_GHC -O2 -Wall #-} | 
|---|
 | 3 |  | 
|---|
 | 4 | import Prelude hiding (catch) | 
|---|
 | 5 | import Control.Applicative | 
|---|
 | 6 | import Control.Monad | 
|---|
 | 7 | import Control.Monad.CatchIO | 
|---|
 | 8 | import qualified Data.ByteString.Lazy as B | 
|---|
 | 9 | import Data.Char | 
|---|
 | 10 | import Data.Dynamic | 
|---|
 | 11 | import Data.Int | 
|---|
 | 12 | import qualified Data.Map as M | 
|---|
 | 13 | import Data.Time.Clock.POSIX | 
|---|
 | 14 | import Data.Time.Format | 
|---|
| [1931] | 15 | import Network.CGI | 
|---|
| [1590] | 16 | import Numeric | 
|---|
 | 17 | import System.FilePath | 
|---|
 | 18 | import System.IO | 
|---|
 | 19 | import System.IO.Error (isDoesNotExistError, isPermissionError) | 
|---|
 | 20 | import System.IO.Unsafe | 
|---|
 | 21 | import System.Locale | 
|---|
 | 22 | import System.Posix | 
|---|
 | 23 | import System.Posix.Handle | 
|---|
 | 24 |  | 
|---|
| [1931] | 25 | types :: M.Map String String | 
|---|
| [1590] | 26 | types = M.fromList [ | 
|---|
 | 27 |          (".avi", "video/x-msvideo"), | 
|---|
 | 28 |          (".css", "text/css"), | 
|---|
 | 29 |          (".doc", "application/msword"), | 
|---|
| [1877] | 30 |          (".docm", "application/vnd.ms-word.document.macroEnabled.12"), | 
|---|
 | 31 |          (".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"), | 
|---|
 | 32 |          (".dot", "application/msword"), | 
|---|
 | 33 |          (".dotm", "application/vnd.ms-word.template.macroEnabled.12"), | 
|---|
 | 34 |          (".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"), | 
|---|
| [2795] | 35 |          (".eot", "application/vnd.ms-fontobject"), | 
|---|
| [1590] | 36 |          (".gif", "image/gif"), | 
|---|
 | 37 |          (".htm", "text/html"), | 
|---|
 | 38 |          (".html", "text/html"), | 
|---|
 | 39 |          (".ico", "image/vnd.microsoft.icon"), | 
|---|
 | 40 |          (".il", "application/octet-stream"), | 
|---|
 | 41 |          (".jar", "application/java-archive"), | 
|---|
 | 42 |          (".jpeg", "image/jpeg"), | 
|---|
 | 43 |          (".jpg", "image/jpeg"), | 
|---|
| [2837] | 44 |          (".js", "application/javascript"), | 
|---|
| [1590] | 45 |          (".mid", "audio/midi"), | 
|---|
 | 46 |          (".midi", "audio/midi"), | 
|---|
 | 47 |          (".mov", "video/quicktime"), | 
|---|
 | 48 |          (".mp3", "audio/mpeg"), | 
|---|
 | 49 |          (".mpeg", "video/mpeg"), | 
|---|
 | 50 |          (".mpg", "video/mpeg"), | 
|---|
| [1877] | 51 |          (".odb", "application/vnd.oasis.opendocument.database"), | 
|---|
 | 52 |          (".odc", "application/vnd.oasis.opendocument.chart"), | 
|---|
 | 53 |          (".odf", "application/vnd.oasis.opendocument.formula"), | 
|---|
 | 54 |          (".odg", "application/vnd.oasis.opendocument.graphics"), | 
|---|
 | 55 |          (".odi", "application/vnd.oasis.opendocument.image"), | 
|---|
 | 56 |          (".odm", "application/vnd.oasis.opendocument.text-master"), | 
|---|
 | 57 |          (".odp", "application/vnd.oasis.opendocument.presentation"), | 
|---|
 | 58 |          (".ods", "application/vnd.oasis.opendocument.spreadsheet"), | 
|---|
 | 59 |          (".odt", "application/vnd.oasis.opendocument.text"), | 
|---|
| [2796] | 60 |          (".otf", "application/font-sfnt"), | 
|---|
| [1877] | 61 |          (".otg", "application/vnd.oasis.opendocument.graphics-template"), | 
|---|
 | 62 |          (".oth", "application/vnd.oasis.opendocument.text-web"), | 
|---|
 | 63 |          (".otp", "application/vnd.oasis.opendocument.presentation-template"), | 
|---|
 | 64 |          (".ots", "application/vnd.oasis.opendocument.spreadsheet-template"), | 
|---|
 | 65 |          (".ott", "application/vnd.oasis.opendocument.text-template"), | 
|---|
| [1590] | 66 |          (".pdf", "application/pdf"), | 
|---|
 | 67 |          (".png", "image/png"), | 
|---|
| [1877] | 68 |          (".pot", "application/vnd.ms-powerpoint"), | 
|---|
 | 69 |          (".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"), | 
|---|
 | 70 |          (".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"), | 
|---|
 | 71 |          (".ppa", "application/vnd.ms-powerpoint"), | 
|---|
 | 72 |          (".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"), | 
|---|
 | 73 |          (".pps", "application/vnd.ms-powerpoint"), | 
|---|
 | 74 |          (".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"), | 
|---|
 | 75 |          (".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"), | 
|---|
| [1590] | 76 |          (".ppt", "application/vnd.ms-powerpoint"), | 
|---|
| [1877] | 77 |          (".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"), | 
|---|
 | 78 |          (".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"), | 
|---|
| [1590] | 79 |          (".ps", "application/postscript"), | 
|---|
 | 80 |          (".svg", "image/svg+xml"), | 
|---|
 | 81 |          (".swf", "application/x-shockwave-flash"), | 
|---|
 | 82 |          (".tar", "application/x-tar"), | 
|---|
| [2837] | 83 |          (".tgz", "application/gzip"), | 
|---|
| [1590] | 84 |          (".tif", "image/tiff"), | 
|---|
 | 85 |          (".tiff", "image/tiff"), | 
|---|
| [2796] | 86 |          (".ttf", "application/font-sfnt"), | 
|---|
| [1590] | 87 |          (".wav", "audio/x-wav"), | 
|---|
 | 88 |          (".wmv", "video/x-ms-wmv"), | 
|---|
| [2795] | 89 |          (".woff", "application/font-woff"), | 
|---|
 | 90 |          (".woff2", "font/woff2"), | 
|---|
| [1590] | 91 |          (".xaml", "application/xaml+xml"), | 
|---|
 | 92 |          (".xap", "application/x-silverlight-app"), | 
|---|
 | 93 |          (".xhtml", "application/xhtml+xml"), | 
|---|
| [1877] | 94 |          (".xla", "application/vnd.ms-excel"), | 
|---|
 | 95 |          (".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"), | 
|---|
| [1590] | 96 |          (".xls", "application/vnd.ms-excel"), | 
|---|
| [1877] | 97 |          (".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"), | 
|---|
 | 98 |          (".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"), | 
|---|
 | 99 |          (".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), | 
|---|
 | 100 |          (".xlt", "application/vnd.ms-excel"), | 
|---|
 | 101 |          (".xltm", "application/vnd.ms-excel.template.macroEnabled.12"), | 
|---|
 | 102 |          (".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"), | 
|---|
| [1590] | 103 |          (".xml", "text/xml"), | 
|---|
| [2837] | 104 |          (".xsl", "application/xslt+xml"), | 
|---|
| [1590] | 105 |          (".zip", "application/zip") | 
|---|
 | 106 |         ] | 
|---|
 | 107 |  | 
|---|
 | 108 | data MyError = NotModified | Forbidden | NotFound | BadMethod | BadRange | 
|---|
 | 109 |     deriving (Show, Typeable) | 
|---|
 | 110 |  | 
|---|
 | 111 | instance Exception MyError | 
|---|
 | 112 |  | 
|---|
 | 113 | outputMyError :: MyError -> CGI CGIResult | 
|---|
 | 114 | outputMyError NotModified = setStatus 304 "Not Modified" >> outputNothing | 
|---|
 | 115 | outputMyError Forbidden = outputError 403 "Forbidden" [] | 
|---|
 | 116 | outputMyError NotFound = outputError 404 "Not Found" [] | 
|---|
 | 117 | outputMyError BadMethod = outputError 405 "Method Not Allowed" [] | 
|---|
 | 118 | outputMyError BadRange = outputError 416 "Requested Range Not Satisfiable" [] | 
|---|
 | 119 |  | 
|---|
| [1931] | 120 | checkExtension :: FilePath -> CGI () | 
|---|
| [2837] | 121 | checkExtension file = | 
|---|
 | 122 |   case M.lookup (map toLower (takeExtension file)) types of | 
|---|
| [1931] | 123 |     Nothing -> throw Forbidden | 
|---|
 | 124 |     Just t -> setHeader "Content-Type" t | 
|---|
 | 125 |  | 
|---|
| [1590] | 126 | checkMethod :: CGI CGIResult -> CGI CGIResult | 
|---|
 | 127 | checkMethod rOutput = do | 
|---|
 | 128 |   m <- requestMethod | 
|---|
 | 129 |   case m of | 
|---|
 | 130 |     "HEAD" -> rOutput >> outputNothing | 
|---|
 | 131 |     "GET" -> rOutput | 
|---|
 | 132 |     "POST" -> rOutput | 
|---|
 | 133 |     _ -> throw BadMethod | 
|---|
 | 134 |  | 
|---|
 | 135 | httpDate :: String | 
|---|
 | 136 | httpDate = "%a, %d %b %Y %H:%M:%S %Z" | 
|---|
 | 137 | formatHTTPDate :: EpochTime -> String | 
|---|
 | 138 | formatHTTPDate = formatTime defaultTimeLocale httpDate . | 
|---|
 | 139 |                  posixSecondsToUTCTime . realToFrac | 
|---|
 | 140 | parseHTTPDate :: String -> Maybe EpochTime | 
|---|
 | 141 | parseHTTPDate = (fromInteger . floor . utcTimeToPOSIXSeconds <$>) . | 
|---|
 | 142 |                 parseTime defaultTimeLocale httpDate | 
|---|
 | 143 |  | 
|---|
 | 144 | checkModified :: EpochTime -> CGI () | 
|---|
 | 145 | checkModified mTime = do | 
|---|
 | 146 |   setHeader "Last-Modified" $ formatHTTPDate mTime | 
|---|
 | 147 |   (requestHeader "If-Modified-Since" >>=) $ maybe (return ()) $ \ims -> | 
|---|
 | 148 |       when (parseHTTPDate ims >= Just mTime) $ throw NotModified | 
|---|
 | 149 |  | 
|---|
 | 150 | checkIfRange :: EpochTime -> CGI (Maybe ()) | 
|---|
 | 151 | checkIfRange mTime = do | 
|---|
 | 152 |   (requestHeader "If-Range" >>=) $ maybe (return $ Just ()) $ \ir -> | 
|---|
 | 153 |       return $ if parseHTTPDate ir == Just mTime then Just () else Nothing | 
|---|
 | 154 |  | 
|---|
| [1931] | 155 | parseRange :: String -> FileOffset -> Maybe (FileOffset, FileOffset) | 
|---|
 | 156 | parseRange (splitAt 6 -> ("bytes=", '-':(readDec -> [(len, "")]))) size = | 
|---|
 | 157 |     Just (max 0 (size - len), size - 1) | 
|---|
 | 158 | parseRange (splitAt 6 -> ("bytes=", readDec -> [(a, "-")])) size = | 
|---|
 | 159 |     Just (a, size - 1) | 
|---|
 | 160 | parseRange (splitAt 6 -> ("bytes=", readDec -> [(a, '-':(readDec -> [(b, "")]))])) size = | 
|---|
 | 161 |     Just (a, min (size - 1) b) | 
|---|
 | 162 | parseRange _ _ = Nothing | 
|---|
| [1590] | 163 |  | 
|---|
| [1931] | 164 | checkRange :: EpochTime -> FileOffset -> CGI (Maybe (FileOffset, FileOffset)) | 
|---|
 | 165 | checkRange mTime size = do | 
|---|
| [1590] | 166 |   setHeader "Accept-Ranges" "bytes" | 
|---|
 | 167 |   (requestHeader "Range" >>=) $ maybe (return Nothing) $ \range -> do | 
|---|
 | 168 |   (checkIfRange mTime >>=) $ maybe (return Nothing) $ \() -> do | 
|---|
| [1931] | 169 |     case parseRange range size of | 
|---|
 | 170 |       Just (a, b) | a <= b -> return $ Just (a, b) | 
|---|
| [1592] | 171 |       Just _ -> throw BadRange | 
|---|
 | 172 |       Nothing -> return Nothing | 
|---|
| [1590] | 173 |  | 
|---|
| [1931] | 174 | outputAll :: Handle -> FileOffset -> CGI CGIResult | 
|---|
 | 175 | outputAll h size = do | 
|---|
| [1590] | 176 |   setHeader "Content-Length" $ show size | 
|---|
 | 177 |   outputFPS =<< liftIO (B.hGetContents h) | 
|---|
 | 178 |  | 
|---|
 | 179 | -- | Lazily read a given number of bytes from the handle into a | 
|---|
 | 180 | -- 'ByteString', then close the handle. | 
|---|
 | 181 | hGetClose :: Handle -> Int64 -> IO B.ByteString | 
|---|
 | 182 | hGetClose h len = do | 
|---|
 | 183 |   contents <- B.hGetContents h | 
|---|
 | 184 |   end <- unsafeInterleaveIO (hClose h >> return B.empty) | 
|---|
 | 185 |   return (B.append (B.take len contents) end) | 
|---|
 | 186 |  | 
|---|
| [1931] | 187 | outputRange :: Handle -> FileOffset -> Maybe (FileOffset, FileOffset) -> CGI CGIResult | 
|---|
 | 188 | outputRange h size Nothing = outputAll h size | 
|---|
 | 189 | outputRange h size (Just (a, b)) = do | 
|---|
| [1590] | 190 |   let len = b - a + 1 | 
|---|
 | 191 |  | 
|---|
 | 192 |   setStatus 206 "Partial Content" | 
|---|
 | 193 |   setHeader "Content-Range" $ | 
|---|
 | 194 |    "bytes " ++ show a ++ "-" ++ show b ++ "/" ++ show size | 
|---|
 | 195 |   setHeader "Content-Length" $ show len | 
|---|
 | 196 |   liftIO $ hSeek h AbsoluteSeek (fromIntegral a) | 
|---|
 | 197 |   outputFPS =<< liftIO (hGetClose h (fromIntegral len)) | 
|---|
 | 198 |  | 
|---|
 | 199 | serveFile :: FilePath -> CGI CGIResult | 
|---|
 | 200 | serveFile file = (`catch` outputMyError) $ do | 
|---|
| [1931] | 201 |   checkExtension file | 
|---|
| [1590] | 202 |  | 
|---|
 | 203 |   checkMethod $ do | 
|---|
 | 204 |  | 
|---|
 | 205 |   let handleOpenError e = | 
|---|
 | 206 |           if isDoesNotExistError e then throw NotFound | 
|---|
 | 207 |           else if isPermissionError e then throw Forbidden | 
|---|
 | 208 |           else throw e | 
|---|
 | 209 |   h <- liftIO (openBinaryFile file ReadMode) `catch` handleOpenError | 
|---|
 | 210 |   (`onException` liftIO (hClose h)) $ do | 
|---|
 | 211 |  | 
|---|
 | 212 |   status <- liftIO $ hGetStatus h | 
|---|
 | 213 |   let mTime = modificationTime status | 
|---|
 | 214 |       size = fileSize status | 
|---|
 | 215 |   checkModified mTime | 
|---|
 | 216 |  | 
|---|
| [1931] | 217 |   range <- checkRange mTime size | 
|---|
 | 218 |   outputRange h size range | 
|---|
| [1590] | 219 |  | 
|---|
 | 220 | main :: IO () | 
|---|
 | 221 | main = runCGI $ handleErrors $ serveFile =<< pathTranslated | 
|---|