@@ -1,4 +1,5 @@
1{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
2+{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE ExistentialQuantification #-}
3{-# LANGUAGE ExistentialQuantification #-}
3{-# LANGUAGE PatternGuards #-}
4{-# LANGUAGE PatternGuards #-}
4{-# LANGUAGE TypeFamilies #-}
5{-# LANGUAGE TypeFamilies #-}
@@ -11,7 +12,7 @@ module Network.Wai.Parse
11 , RequestBodyType (..)
12 , RequestBodyType (..)
12 , getRequestBodyType
13 , getRequestBodyType
13 , sinkRequestBody
14 , sinkRequestBody
14− , sinkRequestBodyEx
15+ , conduitRequestBody
16 , lbsBackEnd
17 , lbsBackEnd
17 , tempFileBackEnd
18 , tempFileBackEnd
@@ -20,24 +21,6 @@ module Network.Wai.Parse
21 , FileInfo (..)
22 , FileInfo (..)
22 , parseContentType
23 , parseContentType
23− , ParseRequestBodyOptions
24− , defaultParseRequestBodyOptions
25− , noLimitParseRequestBodyOptions
27− , setMaxRequestKeyLength
28− , clearMaxRequestKeyLength
29− , setMaxRequestNumFiles
30− , clearMaxRequestNumFiles
31− , setMaxRequestFileSize
32− , clearMaxRequestFileSize
33− , setMaxRequestFilesSize
34− , clearMaxRequestFilesSize
35− , setMaxRequestParmsSize
36− , clearMaxRequestParmsSize
38− , clearMaxHeaderLines
39− , setMaxHeaderLineLength
40− , clearMaxHeaderLineLength
42 , Bound (..)
25 , Bound (..)
43 , findBound
26 , findBound
@@ -48,30 +31,33 @@ module Network.Wai.Parse
51−import qualified Control.Exception as E
34+import qualified Data.ByteString.Search as Search
52import qualified Data.ByteString as S
35import qualified Data.ByteString as S
53import qualified Data.ByteString.Lazy as L
36import qualified Data.ByteString.Lazy as L
54import qualified Data.ByteString.Char8 as S8
37import qualified Data.ByteString.Char8 as S8
55import Data.Word (Word8)
38import Data.Word (Word8)
56−import Data.Int (Int64)
57−import Data.Maybe (catMaybes, fromMaybe)
39+import Data.Maybe (fromMaybe)
58import Data.List (sortBy)
40import Data.List (sortBy)
59−import Data.Function (on, fix)
41+import Data.Function (on)
60import System.Directory (removeFile, getTemporaryDirectory)
42import System.Directory (removeFile, getTemporaryDirectory)
61import System.IO (hClose, openBinaryTempFile)
43import System.IO (hClose, openBinaryTempFile)
62−import System.IO.Error (isDoesNotExistError)
63import Network.Wai
44import Network.Wai
46+import Data.Conduit.Internal ()
47+import qualified Data.Conduit.List as CL
48+import qualified Data.Conduit.Binary as CB
49+import Control.Monad.IO.Class (liftIO)
64import qualified Network.HTTP.Types as H
50import qualified Network.HTTP.Types as H
65−import Control.Applicative ((<$>))
51+import Data.Either (partitionEithers)
66−import Control.Exception (catchJust)
67−import Control.Monad (when, unless, guard)
52+import Control.Monad (when, unless)
53+import Control.Monad.Trans.Class (lift)
68−import Control.Monad.Trans.Resource (allocate, release, register, InternalState, runInternalState)
54+import Control.Monad.Trans.Resource (allocate, release, register)
69−import Data.IORef
55+#if MIN_VERSION_conduit(1, 0, 0)
70−import Network.HTTP.Types (hContentType)
56+import Data.Conduit.Internal (Pipe (NeedInput, HaveOutput), (>+>), withUpstream, injectLeftovers, ConduitM (..))
71−import Network.HTTP2( HTTP2Error (..), ErrorCodeId (..) )
72−import Data.CaseInsensitive (mk)
57+import Data.Void (Void)
74−import Prelude hiding (lines)
59+import Data.Conduit.Internal (sinkToPipe)
76breakDiscard :: Word8 -> S.ByteString -> (S.ByteString, S.ByteString)
62breakDiscard :: Word8 -> S.ByteString -> (S.ByteString, S.ByteString)
77breakDiscard w s =
63breakDiscard w s =
@@ -103,186 +89,28 @@ parseHttpAccept = map fst
105-- | Store uploaded files in memory
91-- | Store uploaded files in memory
106−lbsBackEnd :: Monad m => ignored1 -> ignored2 -> m S.ByteString -> m L.ByteString
92+lbsBackEnd :: Monad m => ignored1 -> ignored2 -> Sink S.ByteString m L.ByteString
107−lbsBackEnd _ _ popper =
93+lbsBackEnd _ _ = fmap L.fromChunks CL.consume
113− then return $ L.fromChunks $ front []
114− else loop $ front . (bs:)
116-- | Save uploaded files on disk as temporary files
95-- | Save uploaded files on disk as temporary files
118−-- Note: starting with version 2.0, removal of temp files is registered with
119−-- the provided @InternalState@. It is the responsibility of the caller to
120−-- ensure that this @InternalState@ gets cleaned up.
121−tempFileBackEnd :: InternalState -> ignored1 -> ignored2 -> IO S.ByteString -> IO FilePath
96+tempFileBackEnd :: MonadResource m => ignored1 -> ignored2 -> Sink S.ByteString m FilePath
122tempFileBackEnd = tempFileBackEndOpts getTemporaryDirectory "webenc.buf"
97tempFileBackEnd = tempFileBackEndOpts getTemporaryDirectory "webenc.buf"
124−-- | Same as 'tempFileBackEnd', but use configurable temp folders and patterns.
99+-- | Same as 'tempFileSink', but use configurable temp folders and patterns.
100+tempFileBackEndOpts :: MonadResource m
125−tempFileBackEndOpts :: IO FilePath -- ^ get temporary directory
101+ => IO FilePath -- ^ get temporary directory
126 -> String -- ^ filename pattern
102 -> String -- ^ filename pattern
128 -> ignored1
103 -> ignored1
129 -> ignored2
104 -> ignored2
130− -> IO S.ByteString
105+ -> Sink S.ByteString m FilePath
132−tempFileBackEndOpts getTmpDir pattrn internalState _ _ popper = do
106+tempFileBackEndOpts getTmpDir pattern _ _ = do
133− (key, (fp, h)) <- flip runInternalState internalState $ allocate it (hClose . snd)
107+ (key, (fp, h)) <- lift $ allocate (do
134− _ <- runInternalState (register $ removeFileQuiet fp) internalState
108+ tempDir <- getTmpDir
135− fix $ \loop -> do
109+ openBinaryTempFile tempDir pattern) (\(_, h) -> hClose h)
136− bs <- popper
110+ _ <- lift $ register $ removeFile fp
137− unless (S.null bs) $ do
111+ CB.sinkHandle h
140− release key
112+ lift $ release key
141 return fp
113 return fp
144− tempDir <- getTmpDir
145− openBinaryTempFile tempDir pattrn
146− removeFileQuiet fp = catchJust (guard . isDoesNotExistError)
150−-- | A data structure that describes the behavior of
151−-- the parseRequestBodyEx function.
154−data ParseRequestBodyOptions = ParseRequestBodyOptions
155− { -- | The maximum length of a filename
156− prboKeyLength :: Maybe Int
157− , -- | The maximum number of files.
158− prboMaxNumFiles :: Maybe Int
159− , -- | The maximum filesize per file.
160− prboMaxFileSize :: Maybe Int64
161− , -- | The maximum total filesize.
162− prboMaxFilesSize :: Maybe Int64
163− , -- | The maximum size of the sum of all parameters
164− prboMaxParmsSize :: Maybe Int
165− , -- | The maximum header lines per mime/multipart entry
166− prboMaxHeaderLines :: Maybe Int
167− , -- | The maximum header line length per mime/multipart entry
168− prboMaxHeaderLineLength :: Maybe Int }
170−-- | Set the maximum length of a filename.
173−setMaxRequestKeyLength :: Int -> ParseRequestBodyOptions -> ParseRequestBodyOptions
174−setMaxRequestKeyLength l p = p { prboKeyLength=Just l }
176−-- | Do not limit the length of filenames.
179−clearMaxRequestKeyLength :: ParseRequestBodyOptions -> ParseRequestBodyOptions
180−clearMaxRequestKeyLength p = p { prboKeyLength=Nothing }
182−-- | Set the maximum number of files per request.
185−setMaxRequestNumFiles :: Int -> ParseRequestBodyOptions -> ParseRequestBodyOptions
186−setMaxRequestNumFiles l p = p { prboMaxNumFiles=Just l }
188−-- | Do not limit the maximum number of files per request.
191−clearMaxRequestNumFiles :: ParseRequestBodyOptions -> ParseRequestBodyOptions
192−clearMaxRequestNumFiles p = p { prboMaxNumFiles=Nothing }
194−-- | Set the maximum filesize per file (in bytes).
197−setMaxRequestFileSize :: Int64 -> ParseRequestBodyOptions -> ParseRequestBodyOptions
198−setMaxRequestFileSize l p = p { prboMaxFileSize=Just l }
200−-- | Do not limit the maximum filesize per file.
203−clearMaxRequestFileSize :: ParseRequestBodyOptions -> ParseRequestBodyOptions
204−clearMaxRequestFileSize p = p { prboMaxFileSize=Nothing }
206−-- | Set the maximum size of all files per request.
209−setMaxRequestFilesSize :: Int64 -> ParseRequestBodyOptions -> ParseRequestBodyOptions
210−setMaxRequestFilesSize l p = p { prboMaxFilesSize=Just l }
212−-- | Do not limit the maximum size of all files per request.
215−clearMaxRequestFilesSize :: ParseRequestBodyOptions -> ParseRequestBodyOptions
216−clearMaxRequestFilesSize p = p { prboMaxFilesSize=Nothing }
218−-- | Set the maximum size of the sum of all parameters.
221−setMaxRequestParmsSize :: Int -> ParseRequestBodyOptions -> ParseRequestBodyOptions
222−setMaxRequestParmsSize l p = p { prboMaxParmsSize=Just l }
224−-- | Do not limit the maximum size of the sum of all parameters.
227−clearMaxRequestParmsSize :: ParseRequestBodyOptions -> ParseRequestBodyOptions
228−clearMaxRequestParmsSize p = p { prboMaxParmsSize=Nothing }
230−-- | Set the maximum header lines per mime/multipart entry.
233−setMaxHeaderLines :: Int -> ParseRequestBodyOptions -> ParseRequestBodyOptions
234−setMaxHeaderLines l p = p { prboMaxHeaderLines=Just l }
236−-- | Do not limit the maximum header lines per mime/multipart entry.
239−clearMaxHeaderLines:: ParseRequestBodyOptions -> ParseRequestBodyOptions
240−clearMaxHeaderLines p = p { prboMaxHeaderLines=Nothing }
242−-- | Set the maximum header line length per mime/multipart entry.
245−setMaxHeaderLineLength :: Int -> ParseRequestBodyOptions -> ParseRequestBodyOptions
246−setMaxHeaderLineLength l p = p { prboMaxHeaderLineLength=Just l }
248−-- | Do not limit the maximum header lines per mime/multipart entry.
251−clearMaxHeaderLineLength :: ParseRequestBodyOptions -> ParseRequestBodyOptions
252−clearMaxHeaderLineLength p = p { prboMaxHeaderLineLength=Nothing }
254−-- | A reasonable default set of parsing options.
255−-- Maximum key/filename length: 32 bytes;
256−-- maximum files: 10; filesize unlimited; maximum
257−-- size for parameters: 64kbytes; maximum number of header
258−-- lines: 32 bytes (applies only to headers of a mime/multipart message);
259−-- maximum header line length: Apache's default for that is 8190 bytes
260−-- (http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestline)
261−-- so we're using that here as well.
264−defaultParseRequestBodyOptions :: ParseRequestBodyOptions
265−defaultParseRequestBodyOptions = ParseRequestBodyOptions
266− { prboKeyLength=Just 32
267− , prboMaxNumFiles=Just 10
268− , prboMaxFileSize=Nothing
269− , prboMaxFilesSize=Nothing
270− , prboMaxParmsSize=Just 65336
271− , prboMaxHeaderLines=Just 32
272− , prboMaxHeaderLineLength=Just 8190 }
274−-- | Do not impose any memory limits.
277−noLimitParseRequestBodyOptions :: ParseRequestBodyOptions
278−noLimitParseRequestBodyOptions = ParseRequestBodyOptions
279− { prboKeyLength=Nothing
280− , prboMaxNumFiles=Nothing
281− , prboMaxFileSize=Nothing
282− , prboMaxFilesSize=Nothing
283− , prboMaxParmsSize=Nothing
284− , prboMaxHeaderLines=Nothing
285− , prboMaxHeaderLineLength=Nothing }
287-- | Information on an uploaded file.
115-- | Information on an uploaded file.
288data FileInfo c = FileInfo
116data FileInfo c = FileInfo
@@ -298,26 +126,17 @@ type Param = (S.ByteString, S.ByteString)
298-- | Post parameter name and associated file information.
126-- | Post parameter name and associated file information.
299type File y = (S.ByteString, FileInfo y)
127type File y = (S.ByteString, FileInfo y)
301−-- | A file uploading backend. Takes the parameter name, file name, and a
129+-- | A file uploading backend. Takes the parameter name, file name, and content
302−-- stream of data.
130+-- type, and returns a `Sink` for storing the contents.
303type BackEnd a = S.ByteString -- ^ parameter name
131type BackEnd a = S.ByteString -- ^ parameter name
304 -> FileInfo ()
132 -> FileInfo ()
305− -> IO S.ByteString
133+ -> Sink S.ByteString (ResourceT IO) a
308−-- | The mimetype of the http body.
309−-- Depending on whether just parameters or parameters and files
310−-- are passed, one or the other mimetype should be used.
312− = -- | application/x-www-form-urlencoded (parameters only)
314− | -- | multipart/form-data (parameters and files)
315− Multipart S.ByteString
135+data RequestBodyType = UrlEncoded | Multipart S.ByteString
317−-- | Get the mimetype of the body of an http request.
318getRequestBodyType :: Request -> Maybe RequestBodyType
137getRequestBodyType :: Request -> Maybe RequestBodyType
319getRequestBodyType req = do
138getRequestBodyType req = do
320− ctype' <- lookup hContentType $ requestHeaders req
139+ ctype' <- lookup "Content-Type" $ requestHeaders req
321 let (ctype, attrs) = parseContentType ctype'
140 let (ctype, attrs) = parseContentType ctype'
322 case ctype of
141 case ctype of
323 "application/x-www-form-urlencoded" -> return UrlEncoded
142 "application/x-www-form-urlencoded" -> return UrlEncoded
@@ -327,7 +146,7 @@ getRequestBodyType req = do
327-- | Parse a content type value, turning a single @ByteString@ into the actual
146-- | Parse a content type value, turning a single @ByteString@ into the actual
328-- content type and a list of pairs of attributes.
147-- content type and a list of pairs of attributes.
330−-- @since 1.3.2
149+-- Since 1.3.2
331parseContentType :: S.ByteString -> (S.ByteString, [(S.ByteString, S.ByteString)])
150parseContentType :: S.ByteString -> (S.ByteString, [(S.ByteString, S.ByteString)])
332parseContentType a = do
151parseContentType a = do
333 let (ctype, b) = S.break (== semicolon) a
152 let (ctype, b) = S.break (== semicolon) a
@@ -337,9 +156,6 @@ parseContentType a = do
337 semicolon = 59
156 semicolon = 59
338 equals = 61
157 equals = 61
339 space = 32
158 space = 32
340− dq s = if S.length s > 2 && S.head s == 34 && S.last s == 34 -- quote
341− then S.tail $ S.init s
343 goAttrs front bs
159 goAttrs front bs
344 | S.null bs = front []
160 | S.null bs = front []
345 | otherwise =
161 | otherwise =
@@ -348,172 +164,81 @@ parseContentType a = do
348 goAttr bs =
164 goAttr bs =
349 let (k, v') = S.break (== equals) bs
165 let (k, v') = S.break (== equals) bs
350 v = S.drop 1 v'
166 v = S.drop 1 v'
351− in (strip k, dq $ strip v)
167+ in (strip k, strip v)
352 strip = S.dropWhile (== space) . fst . S.breakEnd (/= space)
168 strip = S.dropWhile (== space) . fst . S.breakEnd (/= space)
354−-- | Parse the body of an HTTP request.
355−-- See parseRequestBodyEx for details.
356−-- Note: This function does not limit the memory it allocates.
357−-- When dealing with untrusted data (as is usually the case when
358−-- receiving input from the internet), it is recommended to
359−-- use the 'parseRequestBodyEx' function instead.
360parseRequestBody :: BackEnd y
170parseRequestBody :: BackEnd y
361 -> Request
171 -> Request
362− -> IO ([Param], [File y])
172+ -> ResourceT IO ([Param], [File y])
363−parseRequestBody = parseRequestBodyEx noLimitParseRequestBodyOptions
173+parseRequestBody s r =
365−-- | Parse the body of an HTTP request, limit resource usage.
366−-- The HTTP body can contain both parameters and files.
367−-- This function will return a list of key,value pairs
368−-- for all parameters, and a list of key,a pairs
369−-- for filenames. The a depends on the used backend that
370−-- is responsible for storing the received files.
371−parseRequestBodyEx :: ParseRequestBodyOptions
374− -> IO ([Param], [File y])
375−parseRequestBodyEx o s r =
376 case getRequestBodyType r of
174 case getRequestBodyType r of
377 Nothing -> return ([], [])
175 Nothing -> return ([], [])
378− Just rbt -> sinkRequestBodyEx o s rbt (requestBody r)
176+ Just rbt -> fmap partitionEithers $ requestBody r $$ conduitRequestBody s rbt =$ CL.consume
380sinkRequestBody :: BackEnd y
178sinkRequestBody :: BackEnd y
381 -> RequestBodyType
179 -> RequestBodyType
383− -> IO ([Param], [File y])
180+ -> Sink S.ByteString (ResourceT IO) ([Param], [File y])
384−sinkRequestBody = sinkRequestBodyEx noLimitParseRequestBodyOptions
181+sinkRequestBody s r = fmap partitionEithers $ conduitRequestBody s r =$ CL.consume
389−sinkRequestBodyEx :: ParseRequestBodyOptions
390− -> BackEnd y
183+conduitRequestBody :: BackEnd y
391− -> RequestBodyType
184+ -> RequestBodyType
393− -> IO ([Param], [File y])
394−sinkRequestBodyEx o s r body = do
395− ref <- newIORef ([], [])
396− let add x = atomicModifyIORef ref $ \(y, z) ->
398− Left y' -> ((y':y, z), ())
399− Right z' -> ((y, z':z), ())
400− conduitRequestBodyEx o s r body add
401− (\(a, b) -> (reverse a, reverse b)) <$> readIORef ref
403−conduitRequestBodyEx :: ParseRequestBodyOptions
407− -> (Either Param (File y) -> IO ())
185+ -> Conduit S.ByteString (ResourceT IO) (Either Param (File y))
408− -> IO ()
186+conduitRequestBody _ UrlEncoded = do
409−conduitRequestBodyEx o _ UrlEncoded rbody add = do
410 -- NOTE: in general, url-encoded data will be in a single chunk.
187 -- NOTE: in general, url-encoded data will be in a single chunk.
411 -- Therefore, I'm optimizing for the usual case by sticking with
188 -- Therefore, I'm optimizing for the usual case by sticking with
412 -- strict byte strings here.
189 -- strict byte strings here.
413− let loop size front = do
190+ bs <- CL.consume
416− then return $ S.concat $ front []
418− let newsize = size + S.length bs
419− case prboMaxParmsSize o of
420− Just maxSize -> when (newsize > maxSize) $
421− error "Maximum size of parameters exceeded"
422− Nothing -> return ()
423− loop newsize $ front . (bs:)
425− mapM_ (add . Left) $ H.parseSimpleQuery bs
191+ mapM_ yield $ map Left $ H.parseSimpleQuery $ S.concat bs
426−conduitRequestBodyEx o backend (Multipart bound) rbody add =
192+conduitRequestBody backend (Multipart bound) =
427− parsePiecesEx o backend (S8.pack "--" `S.append` bound) rbody add
193+ parsePieces backend $ S8.pack "--" `S.append` bound
429−
195+#if MIN_VERSION_conduit(1, 0, 0)
430−-- | Take one header or subheader line.
196+takeLine :: Monad m => Consumer S.ByteString m (Maybe S.ByteString)
431−-- Since: 3.0.26
197+#else
432−-- Throw 431 if headers too large.
433−takeLine :: Maybe Int -> Source -> IO (Maybe S.ByteString)
198+takeLine :: Monad m => Pipe S.ByteString S.ByteString o u m (Maybe S.ByteString)
434−takeLine maxlen src =
200+takeLine =
437− go front = do
203+ go front = await >>= maybe (close front) (push front)
438− bs <- readSource src
204+
440− Just maxlen' -> when (S.length front > maxlen') $
441− E.throwIO $ ConnectionError (UnknownErrorCode 431)
442− "Request Header Fields Too Large"
443− Nothing -> return ()
448− close front = leftover src front >> return Nothing
205+ close front = leftover (front S.empty) >> return Nothing
449 push front bs = do
206 push front bs = do
450− let (x, y) = S.break (== 10) bs -- LF
207+ let (x, y) = S.break (== 10) $ front bs -- LF
451 in if S.null y
208 in if S.null y
452− then go $ front `S.append` x
209+ then go $ S.append x
454− when (S.length y > 1) $ leftover src $ S.drop 1 y
211+ when (S.length y > 1) $ leftover $ S.drop 1 y
455− let res = front `S.append` x
457− Just maxlen' -> when (S.length res > maxlen') $
458− E.throwIO $ ConnectionError (UnknownErrorCode 431)
459− "Request Header Fields Too Large"
460− Nothing -> return ()
461− return $ Just $ killCR $ res
212+ return $ Just $ killCR x
463−takeLines' :: Maybe Int -> Maybe Int -> Source -> IO [S.ByteString]
214+#if MIN_VERSION_conduit(1, 0, 0)
464−takeLines' lineLength maxLines source =
215+takeLines :: Consumer S.ByteString (ResourceT IO) [S.ByteString]
465− reverse <$> takeLines'' [] lineLength maxLines source
216+#else
466−
217+takeLines :: Pipe S.ByteString S.ByteString o u (ResourceT IO) [S.ByteString]
467−takeLines''
218+#endif
472− -> IO [S.ByteString]
473−takeLines'' lines lineLength maxLines src = do
219+takeLines = do
476− when (length lines > maxLines') $
477− error "Too many lines in mime/multipart header"
478− Nothing -> return ()
479− res <- takeLine lineLength src
220+ res <- takeLine
480 case res of
221 case res of
481− Nothing -> return lines
222+ Nothing -> return []
483− | S.null l -> return lines
224+ | S.null l -> return []
484− | otherwise -> takeLines'' (l:lines) lineLength maxLines src
225+ | otherwise -> do
486−data Source = Source (IO S.ByteString) (IORef S.ByteString)
227+ return $ l : ls
488−mkSource :: IO S.ByteString -> IO Source
229+parsePieces :: BackEnd y
490− ref <- newIORef S.empty
491− return $ Source f ref
493−readSource :: Source -> IO S.ByteString
230+ -> S.ByteString
494−readSource (Source f ref) = do
231+#if MIN_VERSION_conduit(1, 0, 0)
495− bs <- atomicModifyIORef ref $ \bs -> (S.empty, bs)
232+ -> ConduitM S.ByteString (Either Param (File y)) (ResourceT IO) ()
498− else return bs
233+#else
500−leftover :: Source -> S.ByteString -> IO ()
501−leftover (Source _ ref) bs = writeIORef ref bs
503−parsePiecesEx :: ParseRequestBodyOptions
507− -> (Either Param (File y) -> IO ())
234+ -> Pipe S.ByteString S.ByteString (Either Param (File y)) u (ResourceT IO) ()
509−parsePiecesEx o sink bound rbody add =
236+parsePieces sink bound =
510− mkSource rbody >>= loop 0 0 0 0
237+ loop
512− loop :: Int -> Int -> Int -> Int64 -> Source -> IO ()
239+ loop = do
513− loop numParms numFiles parmSize filesSize src = do
514− _boundLine <- takeLine (prboMaxHeaderLineLength o) src
240+ _boundLine <- takeLine
515− res' <- takeLines' (prboMaxHeaderLineLength o)
241+ res' <- takeLines
516− (prboMaxHeaderLines o) src
517 unless (null res') $ do
242 unless (null res') $ do
518 let ls' = map parsePair res'
243 let ls' = map parsePair res'
519 let x = do
244 let x = do
@@ -524,57 +249,31 @@ parsePiecesEx o sink bound rbody add =
524 return (ct, name, lookup "filename" attrs)
249 return (ct, name, lookup "filename" attrs)
525 case x of
250 case x of
526 Just (mct, name, Just filename) -> do
251 Just (mct, name, Just filename) -> do
527− case prboKeyLength o of
528− Just maxKeyLength ->
529− when (S.length name > maxKeyLength) $
530− error "Filename is too long"
531− Nothing -> return ()
532− case prboMaxNumFiles o of
533− Just maxFiles -> when (numFiles >= maxFiles) $
534− error "Maximum number of files exceeded"
535− Nothing -> return ()
536 let ct = fromMaybe "application/octet-stream" mct
252 let ct = fromMaybe "application/octet-stream" mct
537 fi0 = FileInfo filename ct ()
253 fi0 = FileInfo filename ct ()
538− fs = catMaybes [ prboMaxFileSize o
539− , subtract filesSize <$> prboMaxFilesSize o ]
540− mfs = if fs == [] then Nothing else Just $ minimum fs
541− ((wasFound, fileSize), y) <- sinkTillBound' bound name fi0 sink src mfs
254+ (wasFound, y) <- sinkTillBound' bound name fi0 sink
542− let newFilesSize = filesSize + fileSize
543− add $ Right (name, fi0 { fileContent = y })
255+ yield $ Right (name, fi0 { fileContent = y })
544− when wasFound $ loop numParms (numFiles + 1) parmSize newFilesSize src
256+ when wasFound loop
545 Just (_ct, name, Nothing) -> do
257 Just (_ct, name, Nothing) -> do
546− case prboKeyLength o of
547− Just maxKeyLength ->
548− when (S.length name > maxKeyLength) $
549− error "Parameter name is too long"
550− Nothing -> return ()
551 let seed = id
258 let seed = id
552 let iter front bs = return $ front . (:) bs
259 let iter front bs = return $ front . (:) bs
553− ((wasFound, _fileSize), front) <- sinkTillBound bound iter seed src
260+ (wasFound, front) <- sinkTillBound bound iter seed
554− (fromIntegral <$> prboMaxParmsSize o)
555 let bs = S.concat $ front []
261 let bs = S.concat $ front []
556 let x' = (name, bs)
262 let x' = (name, bs)
557− let newParmSize = parmSize + S.length name + S.length bs
558− case prboMaxParmsSize o of
559− Just maxParmSize -> when (newParmSize > maxParmSize) $
560− error "Maximum size of parameters exceeded"
561− Nothing -> return ()
562− add $ Left x'
263+ yield $ Left x'
563− when wasFound $ loop (numParms + 1) numFiles
264+ when wasFound loop
564− newParmSize filesSize src
566 -- ignore this part
266 -- ignore this part
567 let seed = ()
267 let seed = ()
568 iter () _ = return ()
268 iter () _ = return ()
569− ((wasFound, _fileSize), ()) <- sinkTillBound bound iter seed src Nothing
269+ (wasFound, ()) <- sinkTillBound bound iter seed
570− when wasFound $ loop numParms numFiles parmSize filesSize src
270+ when wasFound loop
572− contDisp = mk $ S8.pack "Content-Disposition"
272+ contDisp = S8.pack "Content-Disposition"
573− contType = mk $ S8.pack "Content-Type"
273+ contType = S8.pack "Content-Type"
574 parsePair s =
274 parsePair s =
575 let (x, y) = breakDiscard 58 s -- colon
275 let (x, y) = breakDiscard 58 s -- colon
576− in (mk $ x, S.dropWhile (== 32) y) -- space
276+ in (x, S.dropWhile (== 32) y) -- space
579data Bound = FoundBound S.ByteString S.ByteString
278data Bound = FoundBound S.ByteString S.ByteString
580 | NoBound
279 | NoBound
@@ -582,7 +281,7 @@ data Bound = FoundBound S.ByteString S.ByteString
582 deriving (Eq, Show)
281 deriving (Eq, Show)
584findBound :: S.ByteString -> S.ByteString -> Bound
283findBound :: S.ByteString -> S.ByteString -> Bound
585−findBound b bs = handleBreak $ S.breakSubstring b bs
284+findBound b bs = handleBreak $ Search.breakOn b bs
587 handleBreak (h, t)
286 handleBreak (h, t)
588 | S.null t = go [lowBound..S.length bs - 1]
287 | S.null t = go [lowBound..S.length bs - 1]
@@ -608,90 +307,90 @@ sinkTillBound' :: S.ByteString
608 -> S.ByteString
307 -> S.ByteString
609 -> FileInfo ()
308 -> FileInfo ()
610 -> BackEnd y
309 -> BackEnd y
611− -> Source
310+#if MIN_VERSION_conduit(1, 0, 0)
612− -> Maybe Int64
311+ -> ConduitM S.ByteString o (ResourceT IO) (Bool, y)
613− -> IO ((Bool, Int64), y)
312+#else
313+ -> Pipe S.ByteString S.ByteString o u (ResourceT IO) (Bool, y)
614−sinkTillBound' bound name fi sink src max' = do
315+sinkTillBound' bound name fi sink =
615− (next, final) <- wrapTillBound bound src max'
316+#if MIN_VERSION_conduit(1, 0, 0)
616− y <- sink name fi next
317+ ConduitM $ anyOutput $
617− b <- final
318+#endif
618− return (b, y)
319+ conduitTillBound bound >+> withUpstream (fix $ sink name fi)
620−data WTB = WTBWorking (S.ByteString -> S.ByteString)
622−wrapTillBound :: S.ByteString -- ^ bound
625− -> IO (IO S.ByteString, IO (Bool, Int64)) -- ^ Bool indicates if the bound was found
626−wrapTillBound bound src max' = do
627− ref <- newIORef $ WTBWorking id
628− sref <- newIORef (0 :: Int64)
629− return (go ref sref, final ref sref)
631− final ref sref = do
321+#if MIN_VERSION_conduit(1, 0, 0)
632− x <- readIORef ref
322+ fix :: Sink S8.ByteString (ResourceT IO) y -> Pipe Void S8.ByteString Void Bool (ResourceT IO) y
633− case x of
323+ fix (ConduitM p) = ignoreTerm >+> injectLeftovers p
634− WTBWorking _ -> error "wrapTillBound did not finish"
324+ ignoreTerm = await' >>= maybe (return ()) (\x -> yield' x >> ignoreTerm)
635− WTBDone y -> do
325+ await' = NeedInput (return . Just) (const $ return Nothing)
636− siz <- readIORef sref
326+ yield' = HaveOutput (return ()) (return ())
638−
328+ anyOutput p = p >+> dropInput
639− go ref sref = do
329+ dropInput = NeedInput (const dropInput) return
640− state <- readIORef ref
330+#else
641− case state of
331+ fix = sinkToPipe
642− WTBDone _ -> return S.empty
332+#endif
643− WTBWorking front -> do
333+
644− bs <- readSource src
334+conduitTillBound :: Monad m
645− cur <- atomicModifyIORef' sref $ \ cur ->
335+ => S.ByteString -- bound
646− let new = cur + fromIntegral (S.length bs) in (new, new)
336+#if MIN_VERSION_conduit(1, 0, 0)
647− case max' of
337+ -> Pipe S.ByteString S.ByteString S.ByteString () m Bool
648− Just max'' | cur > max'' ->
338+#else
649− E.throwIO $ ConnectionError (UnknownErrorCode 413) "Payload Too Large"
339+ -> Pipe S.ByteString S.ByteString S.ByteString u m Bool
341+conduitTillBound bound =
342+#if MIN_VERSION_conduit(1, 0, 0)
347+ go front = await >>= maybe (close front) (push front)
349+ let bs = front S.empty
350+ unless (S.null bs) $ yield bs
650− _ -> return ()
351+ return False
653− writeIORef ref $ WTBDone False
654− return $ front bs
352+ push front bs' = do
655− else push $ front bs
353+ let bs = front bs'
658− case findBound bound bs of
354+ case findBound bound bs of
659− FoundBound before after -> do
355+ FoundBound before after -> do
660− let before' = killCRLF before
356+ let before' = killCRLF before
661− leftover src after
358+ leftover after
662− writeIORef ref $ WTBDone True
359+ return True
664− NoBound -> do
360+ NoBound -> do
665− -- don't emit newlines, in case it's part of a bound
361+ -- don't emit newlines, in case it's part of a bound
666− let (toEmit, front') =
362+ let (toEmit, front') =
667− if not (S8.null bs) && S8.last bs `elem` ['\r','\n']
363+ if not (S8.null bs) && S8.last bs `elem` "\r\n"
668− then let (x, y) = S.splitAt (S.length bs - 2) bs
364+ then let (x, y) = S.splitAt (S.length bs - 2) bs
669− in (x, S.append y)
365+ in (x, S.append y)
670− else (bs, id)
366+ else (bs, id)
671− writeIORef ref $ WTBWorking front'
672− if S.null toEmit
367+ yield toEmit
673− then go ref sref
368+ go front'
675− PartialBound -> do
369+ PartialBound -> go $ S.append bs
676− writeIORef ref $ WTBWorking $ S.append bs
679sinkTillBound :: S.ByteString
371sinkTillBound :: S.ByteString
680 -> (x -> S.ByteString -> IO x)
372 -> (x -> S.ByteString -> IO x)
682− -> Source
374+#if MIN_VERSION_conduit(1, 0, 0)
683− -> Maybe Int64
375+ -> Consumer S.ByteString (ResourceT IO) (Bool, x)
684− -> IO ((Bool, Int64), x)
376+#else
377+ -> Pipe S.ByteString S.ByteString o u (ResourceT IO) (Bool, x)
685−sinkTillBound bound iter seed0 src max' = do
379+sinkTillBound bound iter seed0 =
686− (next, final) <- wrapTillBound bound src max'
380+#if MIN_VERSION_conduit(1, 0, 0)
687− let loop seed = do
381+ ConduitM $
688− bs <- next
382+#endif
689− if S.null bs
383+ (conduitTillBound bound >+> (withUpstream $ ij $ CL.foldM iter' seed0))
690− then return seed
384+ where
691− else iter seed bs >>= loop
385+ iter' a b = liftIO $ iter a b
692− seed <- loop seed0
386+#if MIN_VERSION_conduit(1, 0, 0)
693− b <- final
387+ ij (ConduitM p) = ignoreTerm >+> injectLeftovers p
694− return (b, seed)
388+ ignoreTerm = await' >>= maybe (return ()) (\x -> yield' x >> ignoreTerm)
389+ await' = NeedInput (return . Just) (const $ return Nothing)
390+ yield' = HaveOutput (return ()) (return ())
696parseAttrs :: S.ByteString -> [(S.ByteString, S.ByteString)]
395parseAttrs :: S.ByteString -> [(S.ByteString, S.ByteString)]
697parseAttrs = map go . S.split 59 -- semicolon
396parseAttrs = map go . S.split 59 -- semicolon