/
GZip.hs
316 lines (247 loc) · 9.98 KB
/
GZip.hs
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
306
307
308
309
310
311
312
313
314
315
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Snap.Util.GZip
( withCompression
, withCompression' ) where
import qualified Codec.Compression.GZip as GZip
import qualified Codec.Compression.Zlib as Zlib
import Control.Concurrent
import Control.Applicative hiding (many)
import Control.Exception
import Control.Monad
import Control.Monad.Trans
import Data.Attoparsec.Char8 hiding (Done)
import qualified Data.ByteString.Lazy.Char8 as L
import Data.ByteString.Char8 (ByteString)
import Data.Iteratee.WrappedByteString
import Data.Maybe
import qualified Data.Set as Set
import Data.Set (Set)
import Data.Typeable
import Prelude hiding (catch, takeWhile)
------------------------------------------------------------------------------
import Snap.Internal.Debug
import Snap.Internal.Parsing
import Snap.Iteratee hiding (Enumerator)
import Snap.Types
------------------------------------------------------------------------------
-- | Runs a 'Snap' web handler with compression if available.
--
-- If the client has indicated support for @gzip@ or @compress@ in its
-- @Accept-Encoding@ header, and the @Content-Type@ in the response is one of
-- the following types:
--
-- * @application/x-javascript@
--
-- * @text/css@
--
-- * @text/html@
--
-- * @text/javascript@
--
-- * @text/plain@
--
-- * @text/xml@
--
-- * @application/x-font-truetype@
--
-- Then the given handler's output stream will be compressed,
-- @Content-Encoding@ will be set in the output headers, and the
-- @Content-Length@ will be cleared if it was set. (We can't process the stream
-- in O(1) space if the length is known beforehand.)
--
-- The wrapped handler will be run to completion, and then the 'Response'
-- that's contained within the 'Snap' monad state will be passed to
-- 'finishWith' to prevent further processing.
--
withCompression :: Snap a -- ^ the web handler to run
-> Snap ()
withCompression = withCompression' compressibleMimeTypes
------------------------------------------------------------------------------
-- | The same as 'withCompression', with control over which MIME types to
-- compress.
withCompression' :: Set ByteString
-- ^ set of compressible MIME types
-> Snap a
-- ^ the web handler to run
-> Snap ()
withCompression' mimeTable action = do
_ <- action
resp <- getResponse
-- If a content-encoding is already set, do nothing. This prevents
-- "withCompression $ withCompression m" from ruining your day.
when (not $ isJust $ getHeader "Content-Encoding" resp) $ do
let mbCt = getHeader "Content-Type" resp
debug $ "withCompression', content-type is " ++ show mbCt
case mbCt of
(Just ct) -> when (Set.member ct mimeTable) chkAcceptEncoding
_ -> return $! ()
getResponse >>= finishWith
where
chkAcceptEncoding :: Snap ()
chkAcceptEncoding = do
req <- getRequest
debug $ "checking accept-encoding"
let mbAcc = getHeader "Accept-Encoding" req
debug $ "accept-encoding is " ++ show mbAcc
let s = fromMaybe "" mbAcc
types <- liftIO $ parseAcceptEncoding s
chooseType types
chooseType [] = return $! ()
chooseType ("gzip":_) = gzipCompression "gzip"
chooseType ("compress":_) = compressCompression "compress"
chooseType ("x-gzip":_) = gzipCompression "x-gzip"
chooseType ("x-compress":_) = compressCompression "x-compress"
chooseType (_:xs) = chooseType xs
------------------------------------------------------------------------------
-- private following
------------------------------------------------------------------------------
------------------------------------------------------------------------------
compressibleMimeTypes :: Set ByteString
compressibleMimeTypes = Set.fromList [ "application/x-font-truetype"
, "application/x-javascript"
, "text/css"
, "text/html"
, "text/javascript"
, "text/plain"
, "text/xml" ]
------------------------------------------------------------------------------
gzipCompression :: ByteString -> Snap ()
gzipCompression ce = modifyResponse f
where
f = setHeader "Content-Encoding" ce .
setHeader "Vary" "Accept-Encoding" .
clearContentLength .
modifyResponseBody gcompress
------------------------------------------------------------------------------
compressCompression :: ByteString -> Snap ()
compressCompression ce = modifyResponse f
where
f = setHeader "Content-Encoding" ce .
setHeader "Vary" "Accept-Encoding" .
clearContentLength .
modifyResponseBody ccompress
------------------------------------------------------------------------------
gcompress :: forall a . Enumerator a -> Enumerator a
gcompress = compressEnumerator GZip.compress
------------------------------------------------------------------------------
ccompress :: forall a . Enumerator a -> Enumerator a
ccompress = compressEnumerator Zlib.compress
------------------------------------------------------------------------------
compressEnumerator :: forall a .
(L.ByteString -> L.ByteString)
-> Enumerator a
-> Enumerator a
compressEnumerator compFunc enum iteratee = do
writeEnd <- newChan
readEnd <- newChan
tid <- forkIO $ threadProc readEnd writeEnd
enum (IterateeG $ f readEnd writeEnd tid iteratee)
where
--------------------------------------------------------------------------
streamFinished :: Stream -> Bool
streamFinished (EOF _) = True
streamFinished (Chunk _) = False
--------------------------------------------------------------------------
consumeSomeOutput :: Chan Stream
-> Iteratee IO a
-> IO (Iteratee IO a)
consumeSomeOutput writeEnd iter = do
e <- isEmptyChan writeEnd
if e
then return iter
else do
ch <- readChan writeEnd
iter' <- liftM liftI $ runIter iter ch
consumeSomeOutput writeEnd iter'
--------------------------------------------------------------------------
consumeRest :: Chan Stream
-> Iteratee IO a
-> IO (IterV IO a)
consumeRest writeEnd iter = do
ch <- readChan writeEnd
iv <- runIter iter ch
if (streamFinished ch)
then return iv
else consumeRest writeEnd $ liftI iv
--------------------------------------------------------------------------
f readEnd writeEnd tid i (EOF Nothing) = do
writeChan readEnd Nothing
x <- consumeRest writeEnd i
killThread tid
return x
f _ _ tid _ (EOF (Just e)) = do
killThread tid
return $ Cont undefined (Just e)
f readEnd writeEnd tid i (Chunk s') = do
let s = unWrap s'
writeChan readEnd $ Just s
i' <- consumeSomeOutput writeEnd i
return $ Cont (IterateeG $ f readEnd writeEnd tid i') Nothing
--------------------------------------------------------------------------
threadProc :: Chan (Maybe ByteString)
-> Chan Stream
-> IO ()
threadProc readEnd writeEnd = do
stream <- getChanContents readEnd
let bs = L.fromChunks $ streamToChunks stream
let output = L.toChunks $ compFunc bs
runIt output `catch` \(e::SomeException) ->
writeChan writeEnd $ EOF (Just $ Err $ show e)
where
runIt (x:xs) = do
writeChan writeEnd (toChunk x) >> runIt xs
runIt [] = do
writeChan writeEnd $ EOF Nothing
--------------------------------------------------------------------------
streamToChunks [] = []
streamToChunks (Nothing:_) = []
streamToChunks ((Just x):xs) = x:(streamToChunks xs)
--------------------------------------------------------------------------
toChunk = Chunk . WrapBS
------------------------------------------------------------------------------
-- We're not gonna bother with quality values; we'll do gzip or compress in
-- that order.
acceptParser :: Parser [ByteString]
acceptParser = do
xs <- option [] $ (:[]) <$> encoding
ys <- many (char ',' *> encoding)
endOfInput
return $ xs ++ ys
where
encoding = skipSpace *> c <* skipSpace
c = do
x <- coding
option () qvalue
return x
qvalue = do
skipSpace
char ';'
skipSpace
char 'q'
skipSpace
char '='
float
return ()
coding = string "*" <|> takeWhile isCodingChar
isCodingChar ch = isDigit ch || isAlpha_ascii ch || ch == '-' || ch == '_'
float = takeWhile isDigit >>
option () (char '.' >> takeWhile isDigit >> pure ())
------------------------------------------------------------------------------
data BadAcceptEncodingException = BadAcceptEncodingException
deriving (Typeable)
------------------------------------------------------------------------------
instance Show BadAcceptEncodingException where
show BadAcceptEncodingException = "bad 'accept-encoding' header"
------------------------------------------------------------------------------
instance Exception BadAcceptEncodingException
------------------------------------------------------------------------------
parseAcceptEncoding :: ByteString -> IO [ByteString]
parseAcceptEncoding s =
case r of
Left _ -> throwIO BadAcceptEncodingException
Right x -> return x
where
r = fullyParse s acceptParser