]> andersk Git - scripts-static-cat.git/blobdiff - StaticCat.hs
Add .ttf and .otf font file types
[scripts-static-cat.git] / StaticCat.hs
index baa509419ef70543f055a141dcc696f61444bb5a..0709fb910fd7336d9cfd24f3361faf645f061e66 100644 (file)
@@ -1,12 +1,14 @@
 {-# LANGUAGE DeriveDataTypeable, ViewPatterns #-}
 {-# OPTIONS_GHC -O2 -Wall #-}
 
+import Prelude hiding (catch)
 import Control.Applicative
-import Control.Exception
 import Control.Monad
+import Control.Monad.CatchIO
 import qualified Data.ByteString.Lazy as B
 import Data.Char
 import Data.Dynamic
+import Data.Int
 import qualified Data.Map as M
 import Data.Time.Clock.POSIX
 import Data.Time.Format
@@ -14,7 +16,8 @@ import Network.CGI
 import Numeric
 import System.FilePath
 import System.IO
-import System.IO.Error
+import System.IO.Error (isDoesNotExistError, isPermissionError)
+import System.IO.Unsafe
 import System.Locale
 import System.Posix
 import System.Posix.Handle
@@ -46,6 +49,7 @@ types = M.fromList [
          (".mp3", "audio/mpeg"),
          (".mpeg", "video/mpeg"),
          (".mpg", "video/mpeg"),
+         (".otf", "application/octet-stream"),
          (".pdf", "application/pdf"),
          (".png", "image/png"),
          (".ppt", "application/vnd.ms-powerpoint"),
@@ -56,6 +60,7 @@ types = M.fromList [
          (".tgz", "application/x-gzip"),
          (".tif", "image/tiff"),
          (".tiff", "image/tiff"),
+         (".ttf", "application/octet-stream"),
          (".wav", "audio/x-wav"),
          (".wmv", "video/x-ms-wmv"),
          (".xaml", "application/xaml+xml"),
@@ -67,15 +72,6 @@ types = M.fromList [
          (".zip", "application/zip")
         ]
 
-throwExceptionCGI :: Exception e => e -> CGI a
-throwExceptionCGI = throwCGI . toException
-
-catchExceptionCGI :: Exception e => CGI a -> (e -> CGI a) -> CGI a
-a `catchExceptionCGI` handler =
-    a `catchCGI` \e -> case fromException e of
-                           Nothing -> throwCGI e
-                           Just e_ -> handler e_
-
 data MyError = NotModified | Forbidden | NotFound | BadMethod | BadRange
     deriving (Show, Typeable)
 
@@ -98,7 +94,7 @@ checkExtension file = do
               return $ takeExtension base
 
   case M.lookup (map toLower ext') types of
-    Nothing -> throwExceptionCGI Forbidden
+    Nothing -> throw Forbidden
     Just t -> setHeader "Content-Type" t
 
 checkMethod :: CGI CGIResult -> CGI CGIResult
@@ -108,7 +104,7 @@ checkMethod rOutput = do
     "HEAD" -> rOutput >> outputNothing
     "GET" -> rOutput
     "POST" -> rOutput
-    _ -> throwExceptionCGI BadMethod
+    _ -> throw BadMethod
 
 httpDate :: String
 httpDate = "%a, %d %b %Y %H:%M:%S %Z"
@@ -123,7 +119,7 @@ checkModified :: EpochTime -> CGI ()
 checkModified mTime = do
   setHeader "Last-Modified" $ formatHTTPDate mTime
   (requestHeader "If-Modified-Since" >>=) $ maybe (return ()) $ \ims ->
-      when (parseHTTPDate ims >= Just mTime) $ throwExceptionCGI NotModified
+      when (parseHTTPDate ims >= Just mTime) $ throw NotModified
 
 checkIfRange :: EpochTime -> CGI (Maybe ())
 checkIfRange mTime = do
@@ -131,10 +127,12 @@ checkIfRange mTime = do
       return $ if parseHTTPDate ir == Just mTime then Just () else Nothing
 
 parseRange :: String -> FileOffset -> Maybe (FileOffset, FileOffset)
+parseRange (splitAt 6 -> ("bytes=", '-':(readDec -> [(len, "")]))) size =
+    Just (max 0 (size - len), size - 1)
 parseRange (splitAt 6 -> ("bytes=", readDec -> [(a, "-")])) size =
     Just (a, size - 1)
-parseRange (splitAt 6 -> ("bytes=", readDec -> [(a, '-':(readDec -> [(b, "")]))])) _ =
-    Just (a, b)
+parseRange (splitAt 6 -> ("bytes=", readDec -> [(a, '-':(readDec -> [(b, "")]))])) size =
+    Just (a, min (size - 1) b)
 parseRange _ _ = Nothing
 
 checkRange :: EpochTime -> FileOffset -> CGI (Maybe (FileOffset, FileOffset))
@@ -144,13 +142,22 @@ checkRange mTime size = do
   (checkIfRange mTime >>=) $ maybe (return Nothing) $ \() -> do
     case parseRange range size of
       Just (a, b) | a <= b -> return $ Just (a, b)
-      _ -> throwExceptionCGI BadRange
+      Just _ -> throw BadRange
+      Nothing -> return Nothing
 
 outputAll :: Handle -> FileOffset -> CGI CGIResult
 outputAll h size = do
   setHeader "Content-Length" $ show size
   outputFPS =<< liftIO (B.hGetContents h)
 
+-- | Lazily read a given number of bytes from the handle into a
+-- 'ByteString', then close the handle.
+hGetClose :: Handle -> Int64 -> IO B.ByteString
+hGetClose h len = do
+  contents <- B.hGetContents h
+  end <- unsafeInterleaveIO (hClose h >> return B.empty)
+  return (B.append (B.take len contents) end)
+
 outputRange :: Handle -> FileOffset -> Maybe (FileOffset, FileOffset) -> CGI CGIResult
 outputRange h size Nothing = outputAll h size
 outputRange h size (Just (a, b)) = do
@@ -161,23 +168,20 @@ outputRange h size (Just (a, b)) = do
    "bytes " ++ show a ++ "-" ++ show b ++ "/" ++ show size
   setHeader "Content-Length" $ show len
   liftIO $ hSeek h AbsoluteSeek (fromIntegral a)
-  outputFPS =<< liftIO (B.hGet h (fromIntegral len))
+  outputFPS =<< liftIO (hGetClose h (fromIntegral len))
 
 serveFile :: FilePath -> CGI CGIResult
-serveFile file = (`catchExceptionCGI` outputMyError) $ do
+serveFile file = (`catch` outputMyError) $ do
   checkExtension file
 
   checkMethod $ do
 
   let handleOpenError e =
-          if isDoesNotExistError e then throwExceptionCGI NotFound
-          else if isPermissionError e then throwExceptionCGI Forbidden
-          else throwExceptionCGI e
-  h <- liftIO (openBinaryFile file ReadMode) `catchExceptionCGI` handleOpenError
-  let handlePostOpenError e = do
-        liftIO $ hClose h
-        throwCGI e
-  (`catchCGI` handlePostOpenError) $ do
+          if isDoesNotExistError e then throw NotFound
+          else if isPermissionError e then throw Forbidden
+          else throw e
+  h <- liftIO (openBinaryFile file ReadMode) `catch` handleOpenError
+  (`onException` liftIO (hClose h)) $ do
 
   status <- liftIO $ hGetStatus h
   let mTime = modificationTime status
This page took 0.223738 seconds and 4 git commands to generate.