-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT
{-# LANGUAGE TupleSections #-}

-- | Bounded reading of the name, version, @:action@ and file name claims in the unchanged PyPI publication relay body.
module Ecluse.Core.Registry.PyPI.Publish.Multipart (uploadClaims, pypiFileUploadOnly, pypiSdistNameForm, pypiVersionForm) where

import Data.ByteString qualified as BS
import Data.ByteString.Char8 qualified as BSC
import Data.Char (toLower)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Network.Wai.Parse qualified as Wai
import UnliftIO.Exception (tryAny)

import Ecluse.Core.Package (PackageName)
import Ecluse.Core.Registry (ParseError (..), PublishBodyFault (PublishMalformed, PublishUnsupported), parseRefusal)
import Ecluse.Core.Registry.PyPI.Project (builtFileCoordinate, canonicalName, fcVersionKey, projectName)
import Ecluse.Core.Security.Limits (Limits (..))
import Ecluse.Core.Server.Path (Filename, mkFilename, unFilename)
import Ecluse.Core.Text (isAsciiAlphaNum)
import Ecluse.Core.Version (canonicalPep440, renderVersion)

-- | The agreed project name of one @file_upload@ whose file name names that project at the declared version.
uploadClaims :: Limits -> Maybe ByteString -> ByteString -> IO (Either PublishBodyFault [Text])
uploadClaims :: Limits
-> Maybe ByteString
-> ByteString
-> IO (Either PublishBodyFault [Text])
uploadClaims Limits
limits Maybe ByteString
contentType ByteString
body = case Limits
-> Maybe ByteString -> ByteString -> Either ParseError [Claim]
checkedFields Limits
limits Maybe ByteString
contentType ByteString
body of
    Left ParseError
fault -> Either PublishBodyFault [Text]
-> IO (Either PublishBodyFault [Text])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishBodyFault -> Either PublishBodyFault [Text]
forall a b. a -> Either a b
Left (ParseError -> PublishBodyFault
PublishMalformed ParseError
fault))
    Right [Claim]
claims -> case (ParseError -> PublishBodyFault)
-> Either ParseError [ByteString]
-> Either PublishBodyFault [ByteString]
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first ParseError -> PublishBodyFault
PublishMalformed (FormField -> [Claim] -> Either ParseError [ByteString]
formValues FormField
ActionField [Claim]
claims) Either PublishBodyFault [ByteString]
-> ([ByteString] -> Either PublishBodyFault ())
-> Either PublishBodyFault ()
forall a b.
Either PublishBodyFault a
-> (a -> Either PublishBodyFault b) -> Either PublishBodyFault b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= [ByteString] -> Either PublishBodyFault ()
uploadAction of
        Left PublishBodyFault
fault -> Either PublishBodyFault [Text]
-> IO (Either PublishBodyFault [Text])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PublishBodyFault -> Either PublishBodyFault [Text]
forall a b. a -> Either a b
Left PublishBodyFault
fault)
        Right () -> (ParseError -> PublishBodyFault)
-> Either ParseError [Text] -> Either PublishBodyFault [Text]
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first ParseError -> PublishBodyFault
PublishMalformed (Either ParseError [Text] -> Either PublishBodyFault [Text])
-> (Either ParseError PackageName -> Either ParseError [Text])
-> Either ParseError PackageName
-> Either PublishBodyFault [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Either ParseError PackageName
-> (PackageName -> Either ParseError [Text])
-> Either ParseError [Text]
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= [Claim] -> PackageName -> Either ParseError [Text]
releaseFile [Claim]
claims) (Either ParseError PackageName -> Either PublishBodyFault [Text])
-> IO (Either ParseError PackageName)
-> IO (Either PublishBodyFault [Text])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Limits -> [Claim] -> IO (Either ParseError PackageName)
agreedName Limits
limits [Claim]
claims

-- | The @501@ reason for any other @:action@, such as @remove_pkg@ or @doc_upload@.
pypiFileUploadOnly :: Text
pypiFileUploadOnly :: Text
pypiFileUploadOnly = Text
"this proxy relays new-release uploads (:action=file_upload) only: change or remove an existing release at the publication target"

-- | The @400@ reason for any upload that is not a wheel and does not name the declared release as PEP 625 names an sdist.
pypiSdistNameForm :: Text
pypiSdistNameForm :: Text
pypiSdistNameForm = Text
"multipart file name does not name the declared project and version: an sdist must be named <normalised_name>-<version>.tar.gz (PEP 625)"

-- | The @400@ reason for a declared version that is not a PEP 440 version, whatever the file is named.
pypiVersionForm :: Text
pypiVersionForm :: Text
pypiVersionForm = Text
"multipart version is not a PEP 440 version"

-- Uploaders send one file_upload. pypiserver deletes a release on remove_pkg under the same permission.
uploadAction :: [ByteString] -> Either PublishBodyFault ()
uploadAction :: [ByteString] -> Either PublishBodyFault ()
uploadAction = \case
    [ByteString
"file_upload"] -> () -> Either PublishBodyFault ()
forall a b. b -> Either a b
Right ()
    [ByteString
_] -> PublishBodyFault -> Either PublishBodyFault ()
forall a b. a -> Either a b
Left (Text -> PublishBodyFault
PublishUnsupported Text
pypiFileUploadOnly)
    [] -> PublishBodyFault -> Either PublishBodyFault ()
forall a b. a -> Either a b
Left (ParseError -> PublishBodyFault
PublishMalformed (Text -> ParseError
ParseError Text
"multipart upload has no :action"))
    [ByteString]
_ -> PublishBodyFault -> Either PublishBodyFault ()
forall a b. a -> Either a b
Left (ParseError -> PublishBodyFault
PublishMalformed (Text -> ParseError
ParseError Text
"multipart upload declares more than one :action"))

-- Conflicting or missing names refuse the relay, as does a name Wai would read differently.
agreedName :: Limits -> [Claim] -> IO (Either ParseError PackageName)
agreedName :: Limits -> [Claim] -> IO (Either ParseError PackageName)
agreedName Limits
limits [Claim]
claims = case FormField -> [Claim] -> Either ParseError [ByteString]
formValues FormField
NameField [Claim]
claims Either ParseError [ByteString]
-> ([ByteString] -> Either ParseError [PackageName])
-> Either ParseError [PackageName]
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (ByteString -> Either ParseError PackageName)
-> [ByteString] -> Either ParseError [PackageName]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ByteString -> Either ParseError PackageName
decodeName of
    Left ParseError
fault -> Either ParseError PackageName -> IO (Either ParseError PackageName)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ParseError -> Either ParseError PackageName
forall a b. a -> Either a b
Left ParseError
fault)
    Right [PackageName]
names -> do
        projected <- Limits -> [ByteString] -> IO (Either ParseError ())
projectNames Limits
limits ((PackageName -> ByteString) -> [PackageName] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> ByteString
TE.encodeUtf8 (Text -> ByteString)
-> (PackageName -> Text) -> PackageName -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PackageName -> Text
canonicalName) [PackageName]
names)
        pure $
            projected >> case names of
                [] -> Text -> Either ParseError PackageName
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart upload has no name"
                PackageName
name : [PackageName]
remaining
                    | (PackageName -> Bool) -> [PackageName] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (PackageName -> PackageName -> Bool
forall a. Eq a => a -> a -> Bool
== PackageName
name) [PackageName]
remaining -> PackageName -> Either ParseError PackageName
forall a b. b -> Either a b
Right PackageName
name
                    | Bool
otherwise -> Text -> Either ParseError PackageName
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart upload declares conflicting names"
  where
    decodeName :: ByteString -> Either ParseError PackageName
decodeName ByteString
bytes = (UnicodeException -> ParseError)
-> Either UnicodeException Text -> Either ParseError Text
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (ParseError -> UnicodeException -> ParseError
forall a b. a -> b -> a
const (Text -> ParseError
ParseError Text
"multipart name is not UTF-8")) (ByteString -> Either UnicodeException Text
TE.decodeUtf8' ByteString
bytes) Either ParseError Text
-> (Text -> Either ParseError PackageName)
-> Either ParseError PackageName
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Either ParseError PackageName
projectName

projectNames :: Limits -> [ByteString] -> IO (Either ParseError ())
projectNames :: Limits -> [ByteString] -> IO (Either ParseError ())
projectNames Limits
limits [ByteString]
values
    | Integer
projectedSize Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Limits -> Int
maxPublishRequestBytes Limits
limits) = Either ParseError () -> IO (Either ParseError ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart name projection exceeds its byte bound")
    | Bool
otherwise = do
        chunks <- ByteString -> IO (IORef ByteString)
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef ([ByteString] -> ByteString
nameProjection [ByteString]
values)
        let readChunk = IORef ByteString -> (ByteString -> Param) -> IO ByteString
forall (m :: * -> *) a b.
MonadIO m =>
IORef a -> (a -> (a, b)) -> m b
atomicModifyIORef' IORef ByteString
chunks (\ByteString
remaining -> let (ByteString
chunk, ByteString
rest) = Int -> ByteString -> Param
BS.splitAt Int
32768 ByteString
remaining in (ByteString
rest, ByteString
chunk))
        outcome <- tryAny (Wai.sinkRequestBodyEx options discardFile (Wai.Multipart projectionBoundary) readChunk)
        pure $ case outcome of
            Left SomeException
_ -> Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"malformed or oversized multipart upload"
            Right ([Param]
params, [File ()]
files) -> Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([File ()] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [File ()]
files Bool -> Bool -> Bool
&& [Param]
params [Param] -> [Param] -> Bool
forall a. Eq a => a -> a -> Bool
== (ByteString -> Param) -> [ByteString] -> [Param]
forall a b. (a -> b) -> [a] -> [b]
map (ByteString
"name",) [ByteString]
values) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart name parsers disagree")
  where
    projectedSize :: Integer
projectedSize = [Integer] -> Integer
forall a (f :: * -> *). (Foldable f, Num a) => f a -> a
sum ((ByteString -> Integer) -> [ByteString] -> [Integer]
forall a b. (a -> b) -> [a] -> [b]
map (\ByteString
value -> Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
BS.length ByteString
value) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
100) [ByteString]
values) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
100
    options :: ParseRequestBodyOptions
options = Int -> ParseRequestBodyOptions -> ParseRequestBodyOptions
Wai.setMaxRequestParmsSize (Limits -> Int
maxMetadataBytes Limits
limits) ParseRequestBodyOptions
Wai.defaultParseRequestBodyOptions

-- A checked package name cannot contain a colon, so this delimiter cannot occur in projected values.
projectionBoundary :: ByteString
projectionBoundary :: ByteString
projectionBoundary = ByteString
"ecluse:name:projection"

nameProjection :: [ByteString] -> ByteString
nameProjection :: [ByteString] -> ByteString
nameProjection [ByteString]
values = [ByteString] -> ByteString
BS.concat ((ByteString -> ByteString) -> [ByteString] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map ByteString -> ByteString
part [ByteString]
values) ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
"--" ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
projectionBoundary ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
"--\r\n"
  where
    part :: ByteString -> ByteString
part ByteString
value = ByteString
"--" ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
projectionBoundary ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
"\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\n" ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
value ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
"\r\n"

discardFile :: Wai.BackEnd ()
discardFile :: BackEnd ()
discardFile ByteString
_ FileInfo ()
_ IO ByteString
readChunk = IO ()
drain
  where
    drain :: IO ()
drain = IO ByteString
readChunk IO ByteString -> (ByteString -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \ByteString
chunk -> Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ByteString -> Bool
BS.null ByteString
chunk) IO ()
drain

-- A store can key the write off the file name, so it must name the agreed project at the declared version.
releaseFile :: [Claim] -> PackageName -> Either ParseError [Text]
releaseFile :: [Claim] -> PackageName -> Either ParseError [Text]
releaseFile [Claim]
claims PackageName
name = do
    versions <- FormField -> [Claim] -> Either ParseError [ByteString]
formValues FormField
VersionField [Claim]
claims
    case (versions, [file | ContentClaim file <- claims]) of
        ([ByteString
version], [Just ByteString
file])
            | Maybe Version
Nothing <- ByteString -> Maybe Version
declaredVersion ByteString
version -> Text -> Either ParseError [Text]
forall a. Text -> Either ParseError a
parseRefusal Text
pypiVersionForm
            | Just Version
declared <- ByteString -> Maybe Version
declaredVersion ByteString
version
            , Just FileCoordinate
coordinate <- PackageName -> Text -> Maybe FileCoordinate
builtFileCoordinate PackageName
name (Text -> Maybe FileCoordinate)
-> (Filename -> Text) -> Filename -> Maybe FileCoordinate
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Filename -> Text
unFilename (Filename -> Maybe FileCoordinate)
-> Maybe Filename -> Maybe FileCoordinate
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Text -> Maybe Filename
distributionFilename (Text -> Maybe Filename) -> Maybe Text -> Maybe Filename
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< ByteString -> Maybe Text
utf8 ByteString
file
            , FileCoordinate -> Text
fcVersionKey FileCoordinate
coordinate Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Version -> Text
renderVersion Version
declared ->
                [Text] -> Either ParseError [Text]
forall a b. b -> Either a b
Right [PackageName -> Text
canonicalName PackageName
name]
            | ByteString
".whl" ByteString -> ByteString -> Bool
`BS.isSuffixOf` ByteString
file -> Text -> Either ParseError [Text]
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart file name does not name the declared project and version"
            | Bool
otherwise -> Text -> Either ParseError [Text]
forall a. Text -> Either ParseError a
parseRefusal Text
pypiSdistNameForm
        ([], [Maybe ByteString]
_) -> Text -> Either ParseError [Text]
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart upload has no version"
        ([ByteString]
_, []) -> Text -> Either ParseError [Text]
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart upload has no content file"
        ([ByteString]
_, [Maybe ByteString
Nothing]) -> Text -> Either ParseError [Text]
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart content part has no file name"
        ([ByteString], [Maybe ByteString])
_ -> Text -> Either ParseError [Text]
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart upload declares more than one version or content file"
  where
    utf8 :: ByteString -> Maybe Text
utf8 = Either UnicodeException Text -> Maybe Text
forall l r. Either l r -> Maybe r
rightToMaybe (Either UnicodeException Text -> Maybe Text)
-> (ByteString -> Either UnicodeException Text)
-> ByteString
-> Maybe Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either UnicodeException Text
TE.decodeUtf8'
    declaredVersion :: ByteString -> Maybe Version
declaredVersion = Text -> Maybe Version
canonicalPep440 (Text -> Maybe Version)
-> (ByteString -> Maybe Text) -> ByteString -> Maybe Version
forall (m :: * -> *) b c a.
Monad m =>
(b -> m c) -> (a -> m b) -> a -> m c
<=< ByteString -> Maybe Text
utf8

-- Wheel and sdist names hold only these characters, so the gate also refuses whitespace and percent signs.
distributionFilename :: Text -> Maybe Filename
distributionFilename :: Text -> Maybe Filename
distributionFilename Text
raw = do
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard ((Char -> Bool) -> Text -> Bool
T.all (\Char
c -> Char -> Bool
isAsciiAlphaNum Char
c Bool -> Bool -> Bool
|| Char
c Char -> String -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` (String
"-_.!+" :: String)) Text
raw)
    Text -> Maybe Filename
mkFilename Text
raw

-- A guarded field sent as a file part is refused, because a store reads file parts apart from form fields.
formValues :: FormField -> [Claim] -> Either ParseError [ByteString]
formValues :: FormField -> [Claim] -> Either ParseError [ByteString]
formValues FormField
field [Claim]
claims = ((Maybe ByteString, ByteString) -> Either ParseError ByteString)
-> [(Maybe ByteString, ByteString)]
-> Either ParseError [ByteString]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (Maybe ByteString, ByteString) -> Either ParseError ByteString
forall {a} {b}. (Maybe a, b) -> Either ParseError b
plainValue [(Maybe ByteString
file, ByteString
value) | FormClaim FormField
found Maybe ByteString
file ByteString
value <- [Claim]
claims, FormField
found FormField -> FormField -> Bool
forall a. Eq a => a -> a -> Bool
== FormField
field]
  where
    plainValue :: (Maybe a, b) -> Either ParseError b
plainValue = \case
        (Maybe a
Nothing, b
value) -> b -> Either ParseError b
forall a b. b -> Either a b
Right b
value
        (Just a
_, b
_) -> Text -> Either ParseError b
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart name, version, or :action is a file part"

-- The parts the guard reads: a form field with any file name it carries, and the content part's file name, never its data.
data Claim = FormClaim FormField (Maybe ByteString) ByteString | ContentClaim (Maybe ByteString)

data FormField = NameField | ActionField | VersionField
    deriving stock (FormField -> FormField -> Bool
(FormField -> FormField -> Bool)
-> (FormField -> FormField -> Bool) -> Eq FormField
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FormField -> FormField -> Bool
== :: FormField -> FormField -> Bool
$c/= :: FormField -> FormField -> Bool
/= :: FormField -> FormField -> Bool
Eq)

checkedFields :: Limits -> Maybe ByteString -> ByteString -> Either ParseError [Claim]
checkedFields :: Limits
-> Maybe ByteString -> ByteString -> Either ParseError [Claim]
checkedFields Limits
limits Maybe ByteString
contentType ByteString
body = do
    Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ByteString -> Int
BS.length ByteString
body Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Limits -> Int
maxPublishRequestBytes Limits
limits) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart upload exceeds its byte bound")
    header <- Either ParseError ByteString
-> (ByteString -> Either ParseError ByteString)
-> Maybe ByteString
-> Either ParseError ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Text -> Either ParseError ByteString
forall a. Text -> Either ParseError a
parseRefusal Text
"missing multipart Content-Type") ByteString -> Either ParseError ByteString
forall a b. b -> Either a b
Right Maybe ByteString
contentType
    when (BS.length header > 8192) (parseRefusal "multipart Content-Type exceeds its bound")
    let (mediaType, attributes) = Wai.parseContentType header
    unless (mediaType == "multipart/form-data") (parseRefusal "upload is not multipart/form-data")
    boundary <- case [value | ("boundary", value) <- attributes] of
        [ByteString
value] | Bool -> Bool
not (ByteString -> Bool
BS.null ByteString
value), ByteString -> Int
BS.length ByteString
value Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
70, (Word8 -> Bool) -> ByteString -> Bool
BS.all Word8 -> Bool
boundaryByte ByteString
value -> ByteString -> Either ParseError ByteString
forall a b. b -> Either a b
Right ByteString
value
        [ByteString]
_ -> Text -> Either ParseError ByteString
forall a. Text -> Either ParseError a
parseRefusal Text
"missing, malformed, or ambiguous multipart boundary"
    unless (BS.isPrefixOf ("--" <> boundary <> "\r\n") body) (parseRefusal "multipart opening boundary is missing")
    checkParts limits boundary 0 (BS.drop (BS.length boundary + 4) body)

boundaryByte :: Word8 -> Bool
boundaryByte :: Word8 -> Bool
boundaryByte Word8
byte = Word8
byte Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
33 Bool -> Bool -> Bool
&& Word8
byte Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word8
126 Bool -> Bool -> Bool
&& Word8
byte Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
34 Bool -> Bool -> Bool
&& Word8
byte Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word8
92

-- Wai ignores malformed part headers, so reject ambiguity before it selects a disposition claim.
checkParts :: Limits -> ByteString -> Int -> ByteString -> Either ParseError [Claim]
checkParts :: Limits
-> ByteString -> Int -> ByteString -> Either ParseError [Claim]
checkParts Limits
limits ByteString
boundary Int
count ByteString
bytes = do
    Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
count Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Limits -> Int
multipartPartCeiling Limits
limits) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart part count exceeds its bound")
    let (ByteString
headers, ByteString
headerSuffix) = ByteString -> ByteString -> Param
BS.breakSubstring ByteString
"\r\n\r\n" ByteString
bytes
    Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ByteString -> Bool
BS.null ByteString
headerSuffix Bool -> Bool -> Bool
|| ByteString -> Int
BS.length ByteString
headers Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
16384) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"malformed multipart headers")
    claim <- ByteString -> Either ParseError (Maybe (ByteString -> Claim))
checkHeaders ByteString
headers
    (value, suffix) <- splitPart boundary (BS.drop 4 headerSuffix)
    when (hidesDelimiter boundary (BS.take (BS.length headers + 4 + BS.length value) bytes)) (parseRefusal "multipart part hides a boundary delimiter")
    later <- case suffix of
        ByteString
"--\r\n" -> [Claim] -> Either ParseError [Claim]
forall a b. b -> Either a b
Right []
        ByteString
"--" -> [Claim] -> Either ParseError [Claim]
forall a b. b -> Either a b
Right []
        ByteString
remaining | Just ByteString
following <- ByteString -> ByteString -> Maybe ByteString
BS.stripPrefix ByteString
"\r\n" ByteString
remaining -> Limits
-> ByteString -> Int -> ByteString -> Either ParseError [Claim]
checkParts Limits
limits ByteString
boundary (Int
count Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) ByteString
following
        ByteString
_ -> Text -> Either ParseError [Claim]
forall a. Text -> Either ParseError a
parseRefusal Text
"malformed or padded multipart boundary delimiter"
    pure (map ($ value) (maybeToList claim) <> later)

splitPart :: ByteString -> ByteString -> Either ParseError (ByteString, ByteString)
splitPart :: ByteString -> ByteString -> Either ParseError Param
splitPart ByteString
boundary ByteString
bytes = case ByteString -> ByteString -> Param
BS.breakSubstring (ByteString
"\r\n--" ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
boundary) ByteString
bytes of
    (ByteString
_, ByteString
suffix) | ByteString -> Bool
BS.null ByteString
suffix -> Text -> Either ParseError Param
forall a. Text -> Either ParseError a
parseRefusal Text
"multipart closing boundary is missing"
    (ByteString
value, ByteString
suffix) -> Param -> Either ParseError Param
forall a b. b -> Either a b
Right (ByteString
value, Int -> ByteString -> ByteString
BS.drop (ByteString -> Int
BS.length ByteString
boundary Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4) ByteString
suffix)

-- Python's cgi and werkzeug also end a part at a delimiter after a bare CR or LF, so none may sit inside a part.
hidesDelimiter :: ByteString -> ByteString -> Bool
hidesDelimiter :: ByteString -> ByteString -> Bool
hidesDelimiter ByteString
boundary ByteString
part = ByteString -> ByteString -> Bool
BS.isPrefixOf ByteString
delimiter ByteString
part Bool -> Bool -> Bool
|| (ByteString -> Bool) -> [ByteString] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (ByteString -> ByteString -> Bool
`BS.isInfixOf` ByteString
part) [Word8 -> ByteString -> ByteString
BS.cons Word8
10 ByteString
delimiter, Word8 -> ByteString -> ByteString
BS.cons Word8
13 ByteString
delimiter]
  where
    delimiter :: ByteString
delimiter = ByteString
"--" ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
boundary

checkHeaders :: ByteString -> Either ParseError (Maybe (ByteString -> Claim))
checkHeaders :: ByteString -> Either ParseError (Maybe (ByteString -> Claim))
checkHeaders ByteString
bytes = do
    headers <- (ByteString -> Either ParseError Param)
-> [ByteString] -> Either ParseError [Param]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ByteString -> Either ParseError Param
parseHeader (ByteString -> [ByteString]
BSC.lines ByteString
bytes)
    disposition <- case [value | ("content-disposition", value) <- headers] of
        [ByteString
value] -> ByteString -> Either ParseError ByteString
forall a b. b -> Either a b
Right ByteString
value
        [ByteString]
_ -> Text -> Either ParseError ByteString
forall a. Text -> Either ParseError a
parseRefusal Text
"missing or ambiguous multipart disposition"
    when (BS.elem 92 disposition) (parseRefusal "escaped multipart disposition attributes are unsupported")
    let (kind, attributes) = Wai.parseContentType disposition
    when (any (BS.elem 34 . snd) attributes) (parseRefusal "malformed quoted multipart disposition attribute")
    name <- case [value | ("name", value) <- attributes] of
        [ByteString
value] | ByteString
kind ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
"form-data", Bool -> Bool
not (ByteString -> Bool
BS.null ByteString
value) -> ByteString -> Either ParseError ByteString
forall a b. b -> Either a b
Right ByteString
value
        [ByteString]
_ -> Text -> Either ParseError ByteString
forall a. Text -> Either ParseError a
parseRefusal Text
"malformed multipart disposition name"
    filename <- case [value | ("filename", value) <- attributes] of
        [] -> Maybe ByteString -> Either ParseError (Maybe ByteString)
forall a b. b -> Either a b
Right Maybe ByteString
forall a. Maybe a
Nothing
        [ByteString
value] -> Maybe ByteString -> Either ParseError (Maybe ByteString)
forall a b. b -> Either a b
Right (ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
value)
        [ByteString]
_ -> Text -> Either ParseError (Maybe ByteString)
forall a. Text -> Either ParseError a
parseRefusal Text
"ambiguous multipart filename"
    when (any (\(ByteString
key, ByteString
_) -> ByteString
key ByteString -> [ByteString] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`notElem` [ByteString
"name", ByteString
"filename"]) attributes) (parseRefusal "unsupported multipart disposition attribute")
    pure (partClaim name filename)
  where
    parseHeader :: ByteString -> Either ParseError Param
parseHeader ByteString
line = do
        let clean :: ByteString
clean = ByteString -> Maybe ByteString -> ByteString
forall a. a -> Maybe a -> a
fromMaybe ByteString
line (ByteString -> ByteString -> Maybe ByteString
BS.stripSuffix ByteString
"\r" ByteString
line)
            (ByteString
key, ByteString
rest) = (Word8 -> Bool) -> ByteString -> Param
BS.break (Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
58) ByteString
clean
        Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ByteString -> Bool
BS.null ByteString
key Bool -> Bool -> Bool
|| ByteString -> Bool
BS.null ByteString
rest Bool -> Bool -> Bool
|| (Word8 -> Bool) -> ByteString -> Bool
BS.any (\Word8
c -> Word8
c Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word8
32 Bool -> Bool -> Bool
|| Word8
c Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
127) ByteString
key) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"malformed multipart header")
        Param -> Either ParseError Param
forall a. a -> Either ParseError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((Char -> Char) -> ByteString -> ByteString
BSC.map Char -> Char
toLower ByteString
key, (Char -> Bool) -> ByteString -> ByteString
BSC.dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' ') (Int -> ByteString -> ByteString
BS.drop Int
1 ByteString
rest))

-- Every other part passes through unread. The content part's value is its file data, which the guard never reads.
partClaim :: ByteString -> Maybe ByteString -> Maybe (ByteString -> Claim)
partClaim :: ByteString -> Maybe ByteString -> Maybe (ByteString -> Claim)
partClaim ByteString
name Maybe ByteString
filename = case ByteString
name of
    ByteString
"content" -> (ByteString -> Claim) -> Maybe (ByteString -> Claim)
forall a. a -> Maybe a
Just (Claim -> ByteString -> Claim
forall a b. a -> b -> a
const (Maybe ByteString -> Claim
ContentClaim Maybe ByteString
filename))
    ByteString
"name" -> (ByteString -> Claim) -> Maybe (ByteString -> Claim)
forall a. a -> Maybe a
Just (FormField -> Maybe ByteString -> ByteString -> Claim
FormClaim FormField
NameField Maybe ByteString
filename)
    ByteString
":action" -> (ByteString -> Claim) -> Maybe (ByteString -> Claim)
forall a. a -> Maybe a
Just (FormField -> Maybe ByteString -> ByteString -> Claim
FormClaim FormField
ActionField Maybe ByteString
filename)
    ByteString
"version" -> (ByteString -> Claim) -> Maybe (ByteString -> Claim)
forall a. a -> Maybe a
Just (FormField -> Maybe ByteString -> ByteString -> Claim
FormClaim FormField
VersionField Maybe ByteString
filename)
    ByteString
_ -> Maybe (ByteString -> Claim)
forall a. Maybe a
Nothing