module Network.HTTP.Types
(
Ascii
, Method
, methodGet
, methodPost
, methodHead
, methodPut
, methodDelete
, methodTrace
, methodConnect
, methodOptions
, StdMethod(..)
, parseMethod
, renderMethod
, renderStdMethod
, HttpVersion(..)
, http09
, http10
, http11
, Status(..)
, status100
, continue100
, status101
, switchingProtocols101
, status200
, ok200
, status201
, created201
, status202
, accepted202
, status203
, nonAuthoritative203
, status204
, noContent204
, status205
, resetContent205
, status206
, partialContent206
, status300
, multipleChoices300
, status301
, movedPermanently301
, status302
, found302
, status303
, seeOther303
, status304
, notModified304
, status305
, useProxy305
, status307
, temporaryRedirect307
, status400
, badRequest400
, status401
, unauthorized401
, status402
, paymentRequired402
, status403
, forbidden403
, status404
, notFound404
, status405
, methodNotAllowed405
, status406
, notAcceptable406
, status407
, proxyAuthenticationRequired407
, status408
, requestTimeout408
, status409
, conflict409
, status410
, gone410
, status411
, lengthRequired411
, status412
, preconditionFailed412
, status413
, requestEntityTooLarge413
, status414
, requestURITooLong414
, status415
, unsupportedMediaType415
, status416
, requestedRangeNotSatisfiable416
, status417
, expectationFailed417
, status418
, imATeaPot418
, status500
, internalServerError500
, status501
, notImplemented501
, status502
, badGateway502
, status503
, serviceUnavailable503
, status504
, gatewayTimeout504
, status505
, httpVersionNotSupported505
, Header
, RequestHeaders
, ResponseHeaders
, headerAccept
, headerAuthorization
, headerCacheControl
, headerConnection
, headerContentLength
, headerContentType
, headerContentMD5
, headerDate
, QueryItem
, Query
, SimpleQueryItem
, SimpleQuery
, simpleQueryToQuery
, renderQuery
, renderQueryBuilder
, renderSimpleQuery
, parseQuery
, parseSimpleQuery
, QueryText
, queryTextToQuery
, queryToQueryText
, renderQueryText
, parseQueryText
, encodePathSegments
, decodePathSegments
, encodePathSegmentsRelative
, encodePath
, decodePath
, urlEncodeBuilder
, urlEncode
, urlDecode
, statusNotAllowed
, statusContinue
, statusSwitchingProtocols
, statusOK
, statusCreated
, statusAccepted
, statusNonAuthoritative
, statusNoContent
, statusResetContent
, statusPartialContent
, statusMultipleChoices
, statusMovedPermanently
, statusFound
, statusSeeOther
, statusNotModified
, statusUseProxy
, statusTemporaryRedirect
, statusBadRequest
, statusUnauthorized
, statusPaymentRequired
, statusForbidden
, statusNotFound
, statusNotAcceptable
, statusProxyAuthenticationRequired
, statusRequestTimeout
, statusConflict
, statusGone
, statusLengthRequired
, statusPreconditionFailed
, statusRequestEntityTooLarge
, statusRequestURITooLong
, statusUnsupportedMediaType
, statusRequestedRangeNotSatisfiable
, statusExpectationFailed
, statusImATeapot
, statusServerError
, statusNotImplemented
, statusBadGateway
, statusServiceUnavailable
, statusGatewayTimeout
, statusHTTPVersionNotSupported
)
where
import Control.Arrow (second, (|||), (***))
import Data.Array
import Data.Bits (shiftL, (.|.))
import Data.Char
import Data.Maybe
import Data.Monoid (mempty, mappend, mconcat)
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8, decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Word (Word8)
import Data.List (intersperse)
import qualified Blaze.ByteString.Builder as Blaze
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.CaseInsensitive as CI
type Ascii = B.ByteString
type Method = Ascii
methodGet, methodPost, methodHead, methodPut, methodDelete, methodTrace, methodConnect, methodOptions :: Method
methodGet = renderStdMethod GET
methodPost = renderStdMethod POST
methodHead = renderStdMethod HEAD
methodPut = renderStdMethod PUT
methodDelete = renderStdMethod DELETE
methodTrace = renderStdMethod TRACE
methodConnect = renderStdMethod CONNECT
methodOptions = renderStdMethod OPTIONS
data StdMethod
= GET
| POST
| HEAD
| PUT
| DELETE
| TRACE
| CONNECT
| OPTIONS
deriving (Read, Show, Eq, Ord, Enum, Bounded, Ix)
methodArray :: Array StdMethod Method
methodArray = listArray (minBound, maxBound) $ map (B8.pack . show) [minBound :: StdMethod .. maxBound]
methodList :: [(Method, StdMethod)]
methodList = map (\(a, b) -> (b, a)) (assocs methodArray)
parseMethod :: Method -> Either Ascii StdMethod
parseMethod bs = maybe (Left bs) Right $ lookup bs methodList
renderMethod :: Either Ascii StdMethod -> Method
renderMethod = id ||| renderStdMethod
renderStdMethod :: StdMethod -> Method
renderStdMethod m = methodArray ! m
data HttpVersion
= HttpVersion {
httpMajor :: !Int
, httpMinor :: !Int
}
deriving (Eq, Ord)
instance Show HttpVersion where
show (HttpVersion major minor) = "HTTP/" ++ show major ++ "." ++ show minor
http09 :: HttpVersion
http09 = HttpVersion 0 9
http10 :: HttpVersion
http10 = HttpVersion 1 0
http11 :: HttpVersion
http11 = HttpVersion 1 1
data Status
= Status {
statusCode :: Int
, statusMessage :: Ascii
}
deriving (Show)
instance Eq Status where
Status { statusCode = a } == Status { statusCode = b } = a == b
instance Ord Status where
compare Status { statusCode = a } Status { statusCode = b } = a `compare` b
status100 :: Status
status100 = Status 100 "Continue"
continue100 :: Status
continue100 = status100
statusContinue :: Status
statusContinue = status100
status101 :: Status
status101 = Status 101 "Switching Protocols"
switchingProtocols101 :: Status
switchingProtocols101 = status101
statusSwitchingProtocols :: Status
statusSwitchingProtocols = status101
status200 :: Status
status200 = Status 200 "OK"
ok200 :: Status
ok200 = status200
statusOK :: Status
statusOK = status200
status201 :: Status
status201 = Status 201 "Created"
created201 :: Status
created201 = status201
statusCreated :: Status
statusCreated = status201
status202 :: Status
status202 = Status 202 "Accepted"
accepted202 :: Status
accepted202 = status202
statusAccepted :: Status
statusAccepted = status202
status203 :: Status
status203 = Status 203 "Non-Authoritative Information"
nonAuthoritative203 :: Status
nonAuthoritative203 = status203
statusNonAuthoritative :: Status
statusNonAuthoritative = status203
status204 :: Status
status204 = Status 204 "No Content"
noContent204 :: Status
noContent204 = status204
statusNoContent :: Status
statusNoContent = status204
status205 :: Status
status205 = Status 205 "Reset Content"
resetContent205 :: Status
resetContent205 = status205
statusResetContent :: Status
statusResetContent = status205
status206 :: Status
status206 = Status 206 "Partial Content"
partialContent206 :: Status
partialContent206 = status206
statusPartialContent :: Status
statusPartialContent = status206
status300 :: Status
status300 = Status 300 "Multiple Choices"
multipleChoices300 :: Status
multipleChoices300 = status300
statusMultipleChoices :: Status
statusMultipleChoices = status300
status301 :: Status
status301 = Status 301 "Moved Permanently"
movedPermanently301 :: Status
movedPermanently301 = status301
statusMovedPermanently :: Status
statusMovedPermanently = status301
status302 :: Status
status302 = Status 302 "Found"
found302 :: Status
found302 = status302
statusFound :: Status
statusFound = status302
status303 :: Status
status303 = Status 303 "See Other"
seeOther303 :: Status
seeOther303 = status303
statusSeeOther :: Status
statusSeeOther = status303
status304 :: Status
status304 = Status 304 "Not Modified"
notModified304 :: Status
notModified304 = status304
statusNotModified :: Status
statusNotModified = status304
status305 :: Status
status305 = Status 305 "Use Proxy"
useProxy305 :: Status
useProxy305 = status305
statusUseProxy :: Status
statusUseProxy = status305
status307 :: Status
status307 = Status 307 "Temporary Redirect"
temporaryRedirect307 :: Status
temporaryRedirect307 = status307
statusTemporaryRedirect :: Status
statusTemporaryRedirect = status307
status400 :: Status
status400 = Status 400 "Bad Request"
badRequest400 :: Status
badRequest400 = status400
statusBadRequest :: Status
statusBadRequest = status400
status401 :: Status
status401 = Status 401 "Unauthorized"
unauthorized401 :: Status
unauthorized401 = status401
statusUnauthorized :: Status
statusUnauthorized = status401
status402 :: Status
status402 = Status 402 "Payment Required"
paymentRequired402 :: Status
paymentRequired402 = status402
statusPaymentRequired :: Status
statusPaymentRequired = status402
status403 :: Status
status403 = Status 403 "Forbidden"
forbidden403 :: Status
forbidden403 = status403
statusForbidden :: Status
statusForbidden = status403
status404 :: Status
status404 = Status 404 "Not Found"
notFound404 :: Status
notFound404 = status404
statusNotFound :: Status
statusNotFound = status404
status405 :: Status
status405 = Status 405 "Method Not Allowed"
methodNotAllowed405 :: Status
methodNotAllowed405 = status405
statusNotAllowed :: Status
statusNotAllowed = status405
status406 :: Status
status406 = Status 406 "Not Acceptable"
notAcceptable406 :: Status
notAcceptable406 = status406
statusNotAcceptable :: Status
statusNotAcceptable = status406
status407 :: Status
status407 = Status 407 "Proxy Authentication Required"
proxyAuthenticationRequired407 :: Status
proxyAuthenticationRequired407 = status407
statusProxyAuthenticationRequired :: Status
statusProxyAuthenticationRequired = status407
status408 :: Status
status408 = Status 408 "Request Timeout"
requestTimeout408 :: Status
requestTimeout408 = status408
statusRequestTimeout :: Status
statusRequestTimeout = status408
status409 :: Status
status409 = Status 409 "Conflict"
conflict409 :: Status
conflict409 = status409
statusConflict :: Status
statusConflict = status409
status410 :: Status
status410 = Status 410 "Gone"
gone410 :: Status
gone410 = status410
statusGone :: Status
statusGone = status410
status411 :: Status
status411 = Status 411 "Length Required"
lengthRequired411 :: Status
lengthRequired411 = status411
statusLengthRequired :: Status
statusLengthRequired = status411
status412 :: Status
status412 = Status 412 "Precondition Failed"
preconditionFailed412 :: Status
preconditionFailed412 = status412
statusPreconditionFailed :: Status
statusPreconditionFailed = status412
status413 :: Status
status413 = Status 413 "Request Entity Too Large"
requestEntityTooLarge413 :: Status
requestEntityTooLarge413 = status413
statusRequestEntityTooLarge :: Status
statusRequestEntityTooLarge = status413
status414 :: Status
status414 = Status 414 "Request-URI Too Long"
requestURITooLong414 :: Status
requestURITooLong414 = status414
statusRequestURITooLong :: Status
statusRequestURITooLong = status414
status415 :: Status
status415 = Status 415 "Unsupported Media Type"
unsupportedMediaType415 :: Status
unsupportedMediaType415 = status415
statusUnsupportedMediaType :: Status
statusUnsupportedMediaType = status415
status416 :: Status
status416 = Status 416 "Requested Range Not Satisfiable"
requestedRangeNotSatisfiable416 :: Status
requestedRangeNotSatisfiable416 = status416
statusRequestedRangeNotSatisfiable :: Status
statusRequestedRangeNotSatisfiable = status416
status417 :: Status
status417 = Status 417 "Expectation Failed"
expectationFailed417 :: Status
expectationFailed417 = status417
statusExpectationFailed :: Status
statusExpectationFailed = status417
status418 :: Status
status418 = Status 418 "I'm a teapot"
imATeaPot418 :: Status
imATeaPot418 = status418
statusImATeapot :: Status
statusImATeapot = status418
status500 :: Status
status500 = Status 500 "Internal Server Error"
internalServerError500 :: Status
internalServerError500 = status500
statusServerError :: Status
statusServerError = status500
status501 :: Status
status501 = Status 501 "Not Implemented"
notImplemented501 :: Status
notImplemented501 = status501
statusNotImplemented :: Status
statusNotImplemented = status501
status502 :: Status
status502 = Status 502 "Bad Gateway"
badGateway502 :: Status
badGateway502 = status502
statusBadGateway :: Status
statusBadGateway = status502
status503 :: Status
status503 = Status 503 "Service Unavailable"
serviceUnavailable503 :: Status
serviceUnavailable503 = status503
statusServiceUnavailable :: Status
statusServiceUnavailable = status503
status504 :: Status
status504 = Status 504 "Gateway Timeout"
gatewayTimeout504 :: Status
gatewayTimeout504 = status504
statusGatewayTimeout :: Status
statusGatewayTimeout = status504
status505 :: Status
status505 = Status 505 "HTTP Version Not Supported"
httpVersionNotSupported505 :: Status
httpVersionNotSupported505 = status505
statusHTTPVersionNotSupported :: Status
statusHTTPVersionNotSupported = status505
type Header = (CI.CI Ascii, Ascii)
type RequestHeaders = [Header]
type ResponseHeaders = [Header]
headerAccept, headerAuthorization, headerCacheControl, headerConnection, headerContentLength, headerContentType, headerContentMD5, headerDate :: Ascii -> Header
headerAccept = (,) "Accept"
headerAuthorization = (,) "Authorization"
headerCacheControl = (,) "Cache-Control"
headerConnection = (,) "Connection"
headerContentLength = (,) "Content-Length"
headerContentType = (,) "Content-Type"
headerContentMD5 = (,) "Content-MD5"
headerDate = (,) "Date"
type QueryItem = (B.ByteString, Maybe B.ByteString)
type Query = [QueryItem]
type QueryText = [(Text, Maybe Text)]
queryTextToQuery :: QueryText -> Query
queryTextToQuery = map $ encodeUtf8 *** fmap encodeUtf8
renderQueryText :: Bool
-> QueryText
-> Blaze.Builder
renderQueryText b = renderQueryBuilder b . queryTextToQuery
queryToQueryText :: Query -> QueryText
queryToQueryText =
map $ go *** fmap go
where
go = decodeUtf8With lenientDecode
parseQueryText :: B.ByteString -> QueryText
parseQueryText = queryToQueryText . parseQuery
type SimpleQueryItem = (B.ByteString, B.ByteString)
type SimpleQuery = [SimpleQueryItem]
simpleQueryToQuery :: SimpleQuery -> Query
simpleQueryToQuery = map (\(a, b) -> (a, Just b))
renderQueryBuilder :: Bool
-> Query
-> Blaze.Builder
renderQueryBuilder _ [] = mempty
renderQueryBuilder qmark' (p:ps) = mconcat
$ go (if qmark' then qmark else mempty) p
: map (go amp) ps
where
qmark = Blaze.copyByteString "?"
amp = Blaze.copyByteString "&"
equal = Blaze.copyByteString "="
go sep (k, mv) = mconcat [
sep
, urlEncodeBuilder True k
, case mv of
Nothing -> mempty
Just v -> equal `mappend` urlEncodeBuilder True v
]
renderQuery :: Bool
-> Query -> Ascii
renderQuery qm = Blaze.toByteString . renderQueryBuilder qm
renderSimpleQuery :: Bool
-> SimpleQuery -> Ascii
renderSimpleQuery useQuestionMark = renderQuery useQuestionMark . simpleQueryToQuery
parseQuery :: B.ByteString -> Query
parseQuery = parseQueryString' . dropQuestion
where
dropQuestion q =
case B.uncons q of
Just (63, q') -> q'
_ -> q
parseQueryString' q | B.null q = []
parseQueryString' q =
let (x, xs) = breakDiscard queryStringSeparators q
in parsePair x : parseQueryString' xs
where
parsePair x =
let (k, v) = B.breakByte 61 x
v'' =
case B.uncons v of
Just (_, v') -> Just $ urlDecode True v'
_ -> Nothing
in (urlDecode True k, v'')
queryStringSeparators :: B.ByteString
queryStringSeparators = B.pack [38,59]
breakDiscard :: B.ByteString -> B.ByteString -> (B.ByteString, B.ByteString)
breakDiscard seps s =
let (x, y) = B.break (`B.elem` seps) s
in (x, B.drop 1 y)
parseSimpleQuery :: B.ByteString -> SimpleQuery
parseSimpleQuery = map (second $ fromMaybe B.empty) . parseQuery
ord8 :: Char -> Word8
ord8 = fromIntegral . ord
unreservedQS, unreservedPI :: [Word8]
unreservedQS = map ord8 "-_.~"
unreservedPI = map ord8 "-_.~:@&=+$,"
urlEncodeBuilder' :: [Word8] -> B.ByteString -> Blaze.Builder
urlEncodeBuilder' extraUnreserved = mconcat . map encodeChar . B.unpack
where
encodeChar ch | unreserved ch = Blaze.fromWord8 ch
| otherwise = h2 ch
unreserved ch | ch >= 65 && ch <= 90 = True
| ch >= 97 && ch <= 122 = True
| ch >= 48 && ch <= 57 = True
unreserved c = c `elem` extraUnreserved
h2 v = let (a, b) = v `divMod` 16 in Blaze.fromWord8s [37, h a, h b]
h i | i < 10 = 48 + i
| otherwise = 65 + i 10
urlEncodeBuilder
:: Bool
-> B.ByteString
-> Blaze.Builder
urlEncodeBuilder True = urlEncodeBuilder' unreservedQS
urlEncodeBuilder False = urlEncodeBuilder' unreservedPI
urlEncode :: Bool -> B.ByteString -> Ascii
urlEncode q = Blaze.toByteString . urlEncodeBuilder q
urlDecode :: Bool
-> B.ByteString -> B.ByteString
urlDecode replacePlus z = fst $ B.unfoldrN (B.length z) go z
where
go bs =
case B.uncons bs of
Nothing -> Nothing
Just (43, ws) | replacePlus -> Just (32, ws)
Just (37, ws) -> Just $ fromMaybe (37, ws) $ do
(x, xs) <- B.uncons ws
x' <- hexVal x
(y, ys) <- B.uncons xs
y' <- hexVal y
Just $ (combine x' y', ys)
Just (w, ws) -> Just (w, ws)
hexVal w
| 48 <= w && w <= 57 = Just $ w 48
| 65 <= w && w <= 70 = Just $ w 55
| 97 <= w && w <= 102 = Just $ w 87
| otherwise = Nothing
combine :: Word8 -> Word8 -> Word8
combine a b = shiftL a 4 .|. b
encodePathSegments :: [Text] -> Blaze.Builder
encodePathSegments [] = mempty
encodePathSegments (x:xs) =
Blaze.copyByteString "/"
`mappend` encodePathSegment x
`mappend` encodePathSegments xs
encodePathSegmentsRelative :: [Text] -> Blaze.Builder
encodePathSegmentsRelative xs = mconcat $ intersperse (Blaze.copyByteString "/") (map encodePathSegment xs)
encodePathSegment :: Text -> Blaze.Builder
encodePathSegment = urlEncodeBuilder False . encodeUtf8
decodePathSegments :: B.ByteString -> [Text]
decodePathSegments "" = []
decodePathSegments "/" = []
decodePathSegments a =
go $ drop1Slash a
where
drop1Slash bs =
case B.uncons bs of
Just (47, bs') -> bs'
_ -> bs
go bs =
let (x, y) = B.breakByte 47 bs
in decodePathSegment x :
if B.null y
then []
else go $ B.drop 1 y
decodePathSegment :: B.ByteString -> Text
decodePathSegment = decodeUtf8With lenientDecode . urlDecode False
encodePath :: [Text] -> Query -> Blaze.Builder
encodePath x [] = encodePathSegments x
encodePath x y = encodePathSegments x `mappend` renderQueryBuilder True y
decodePath :: B.ByteString -> ([Text], Query)
decodePath b =
let (x, y) = B.breakByte 63 b
in (decodePathSegments x, parseQuery y)