-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | HTTP/2 library -- -- HTTP/2 library including frames, priority queues, HPACK and server. @package http2 @version 2.0.0 module Network.HPACK.Token -- | Internal representation for header keys. data Token Token :: !Int -> !Bool -> !Bool -> !CI ByteString -> Token -- | Index for value table [ix] :: Token -> !Int -- | should be indexed in HPACK [shouldBeIndexed] :: Token -> !Bool -- | is this a pseudo header key? [isPseudo] :: Token -> !Bool -- | Case insensitive header key [tokenKey] :: Token -> !CI ByteString -- | Extracting an index from a token. tokenIx :: Token -> Int -- | Extracting a case insensitive header key from a token. tokenCIKey :: Token -> ByteString -- | Extracting a folded header key from a token. tokenFoldedKey :: Token -> ByteString -- | Making a token from a header key. -- --
-- >>> toToken ":authority" == tokenAuthority
-- True
--
-- >>> toToken "foo"
-- Token {ix = 54, shouldBeIndexed = True, isPseudo = False, tokenKey = "foo"}
--
-- >>> toToken ":bar"
-- Token {ix = 54, shouldBeIndexed = True, isPseudo = True, tokenKey = ":bar"}
--
toToken :: ByteString -> Token
-- | Minimum token index.
minTokenIx :: Int
-- | Maximun token index defined in the static table.
maxStaticTokenIx :: Int
-- | Maximum token index.
maxTokenIx :: Int
-- | Token index for tokenCookie.
cookieTokenIx :: Int
-- | Is this token ix to be held in the place holder?
isMaxTokenIx :: Int -> Bool
-- | Is this token ix for Cookie?
isCookieTokenIx :: Int -> Bool
-- | Is this token ix for a header not defined in the static table?
isStaticTokenIx :: Int -> Bool
-- | Is this token for a header not defined in the static table?
isStaticToken :: Token -> Bool
tokenAuthority :: Token
tokenMethod :: Token
tokenPath :: Token
tokenScheme :: Token
tokenStatus :: Token
tokenAcceptCharset :: Token
tokenAcceptEncoding :: Token
tokenAcceptLanguage :: Token
tokenAcceptRanges :: Token
tokenAccept :: Token
tokenAccessControlAllowOrigin :: Token
tokenAge :: Token
tokenAllow :: Token
tokenAuthorization :: Token
tokenCacheControl :: Token
tokenContentDisposition :: Token
tokenContentEncoding :: Token
tokenContentLanguage :: Token
tokenContentLength :: Token
tokenContentLocation :: Token
tokenContentRange :: Token
tokenContentType :: Token
tokenCookie :: Token
tokenDate :: Token
tokenEtag :: Token
tokenExpect :: Token
tokenExpires :: Token
tokenFrom :: Token
tokenHost :: Token
tokenIfMatch :: Token
tokenIfModifiedSince :: Token
tokenIfNoneMatch :: Token
tokenIfRange :: Token
tokenIfUnmodifiedSince :: Token
tokenLastModified :: Token
tokenLink :: Token
tokenLocation :: Token
tokenMaxForwards :: Token
tokenProxyAuthenticate :: Token
tokenProxyAuthorization :: Token
tokenRange :: Token
tokenReferer :: Token
tokenRefresh :: Token
tokenRetryAfter :: Token
tokenServer :: Token
tokenSetCookie :: Token
tokenStrictTransportSecurity :: Token
tokenTransferEncoding :: Token
tokenUserAgent :: Token
tokenVary :: Token
tokenVia :: Token
tokenWwwAuthenticate :: Token
-- | Not defined in the static table.
tokenConnection :: Token
-- | Not defined in the static table.
tokenTE :: Token
-- | A place holder to hold header keys not defined in the static table.
tokenMax :: Token
instance GHC.Show.Show Network.HPACK.Token.Token
instance GHC.Classes.Eq Network.HPACK.Token.Token
-- | HPACK(https://tools.ietf.org/html/rfc7541) encoding and
-- decoding a header list.
module Network.HPACK
-- | Converting HeaderList to the HPACK format. This function has
-- overhead of allocating/freeing a temporary buffer.
-- BufferOverrun will be thrown if the temporary buffer is too
-- small.
encodeHeader :: EncodeStrategy -> Size -> DynamicTable -> HeaderList -> IO ByteString
-- | Converting the HPACK format to HeaderList.
--
-- -- >>> defaultDynamicTableSize -- 4096 --defaultDynamicTableSize :: Int -- | Creating DynamicTable for encoding. newDynamicTableForEncoding :: Size -> IO DynamicTable -- | Creating DynamicTable for decoding. newDynamicTableForDecoding :: Size -> Size -> IO DynamicTable -- | Clearing DynamicTable. Currently, this frees the temporary -- buffer for Huffman decoding. clearDynamicTable :: DynamicTable -> IO () -- | Creating DynamicTable for encoding, performing the action and -- clearing the DynamicTable. withDynamicTableForEncoding :: Size -> (DynamicTable -> IO a) -> IO a -- | Creating DynamicTable for decoding, performing the action and -- clearing the DynamicTable. withDynamicTableForDecoding :: Size -> Size -> (DynamicTable -> IO a) -> IO a -- | When SETTINGS_HEADER_TABLE_SIZE is received from a peer, its value -- should be set by this function. setLimitForEncoding :: Size -> DynamicTable -> IO () -- | Compression algorithms for HPACK encoding. data CompressionAlgo -- | No compression Naive :: CompressionAlgo -- | Using indices in the static table only Static :: CompressionAlgo -- | Using indices Linear :: CompressionAlgo -- | Strategy for HPACK encoding. data EncodeStrategy EncodeStrategy :: !CompressionAlgo -> !Bool -> EncodeStrategy -- | Which compression algorithm is used. [compressionAlgo] :: EncodeStrategy -> !CompressionAlgo -- | Whether or not to use Huffman encoding for strings. [useHuffman] :: EncodeStrategy -> !Bool -- | Default EncodeStrategy. -- --
-- >>> defaultEncodeStrategy
-- EncodeStrategy {compressionAlgo = Linear, useHuffman = False}
--
defaultEncodeStrategy :: EncodeStrategy
-- | Errors for decoder.
data DecodeError
-- | Index is out of range
IndexOverrun :: Index -> DecodeError
-- | Eos appears in the middle of huffman string
EosInTheMiddle :: DecodeError
-- | Non-eos appears in the end of huffman string
IllegalEos :: DecodeError
-- | Eos of huffman string is more than 7 bits
TooLongEos :: DecodeError
-- | Encoded string has no length
EmptyEncodedString :: DecodeError
-- | A peer set the dynamic table size less than 32
TooSmallTableSize :: DecodeError
-- | A peer tried to change the dynamic table size over the limit
TooLargeTableSize :: DecodeError
-- | Table size update at the non-beginning
IllegalTableSizeUpdate :: DecodeError
HeaderBlockTruncated :: DecodeError
IllegalHeaderName :: DecodeError
data BufferOverrun
-- | The buffer size is not enough
BufferOverrun :: BufferOverrun
-- | Header list.
type HeaderList = [Header]
-- | Header.
type Header = (HeaderName, HeaderValue)
-- | Header name.
type HeaderName = ByteString
-- | Header value.
type HeaderValue = ByteString
-- | TokenBased header list.
type TokenHeaderList = [TokenHeader]
-- | TokenBased header.
type TokenHeader = (Token, HeaderValue)
-- | An array to get HeaderValue quickly. getHeaderValue
-- should be used. Internally, the key is Token ix.
type ValueTable = Array Int (Maybe HeaderValue)
-- | A pair of token list and value table.
type HeaderTable = (TokenHeaderList, ValueTable)
-- | Accessing HeaderValue with Token.
getHeaderValue :: Token -> ValueTable -> Maybe HeaderValue
-- | Converting a header list of the http-types style to
-- TokenHeaderList and ValueTable.
toHeaderTable :: [(CI HeaderName, HeaderValue)] -> IO HeaderTable
-- | Size in bytes.
type Size = Int
-- | Index for table.
type Index = Int
-- | A pointer to Word8.
type Buffer = Ptr Word8
-- | Size of a buffer.
type BufferSize = Int
-- | This is partial implementation of the priority of HTTP/2.
--
-- This implementation does support structured priority queue but not
-- support re-structuring. This means that it is assumed that an entry
-- created by a Priority frame is never closed. The entry behaves an
-- intermediate node, not a leaf.
--
-- This queue is fair for weight. Consider two weights: 201 and 101.
-- Repeating enqueue/dequeue probably produces 201, 201, 101, 201, 201,
-- 101, ...
--
-- Only one entry per stream should be enqueued.
module Network.HTTP2.Priority
-- | Internal representation of priority in priority queues. The precedence
-- of a dequeued entry should be specified to enqueue when the entry is
-- enqueued again.
data Precedence
-- | Default precedence.
defaultPrecedence :: Precedence
-- | Converting Priority to Precedence. When an entry is
-- enqueued at the first time, this function should be used.
toPrecedence :: Priority -> Precedence
-- | Abstract data type for priority trees.
data PriorityTree a
-- | Creating a new priority tree.
newPriorityTree :: IO (PriorityTree a)
-- | Bringing up the structure of the priority tree. This must be used for
-- Priority frame.
prepare :: PriorityTree a -> StreamId -> Priority -> IO ()
-- | Enqueuing an entry to the priority tree. This must be used for Header
-- frame.
enqueue :: PriorityTree a -> StreamId -> Precedence -> a -> IO ()
-- | Dequeuing an entry from the priority tree.
dequeue :: PriorityTree a -> IO (StreamId, Precedence, a)
-- | Dequeuing an entry from the priority tree.
dequeueSTM :: PriorityTree a -> STM (StreamId, Precedence, a)
-- | Checking if the priority tree is empty.
isEmpty :: PriorityTree a -> IO Bool
-- | Checking if the priority tree is empty.
isEmptySTM :: PriorityTree a -> STM Bool
-- | Deleting the entry corresponding to StreamId. delete and
-- enqueue are used to change the priority of a live stream.
delete :: PriorityTree a -> StreamId -> Precedence -> IO (Maybe a)
-- | Framing in HTTP/2(https://tools.ietf.org/html/rfc7540).
module Network.HTTP2
-- | The data type for HTTP/2 frames.
data Frame
Frame :: !FrameHeader -> !FramePayload -> Frame
[frameHeader] :: Frame -> !FrameHeader
[framePayload] :: Frame -> !FramePayload
-- | The data type for HTTP/2 frame headers.
data FrameHeader
FrameHeader :: !Int -> !FrameFlags -> !StreamId -> FrameHeader
[payloadLength] :: FrameHeader -> !Int
[flags] :: FrameHeader -> !FrameFlags
[streamId] :: FrameHeader -> !StreamId
-- | The data type for HTTP/2 frame payloads.
data FramePayload
DataFrame :: !ByteString -> FramePayload
HeadersFrame :: !Maybe Priority -> !HeaderBlockFragment -> FramePayload
PriorityFrame :: !Priority -> FramePayload
RSTStreamFrame :: !ErrorCodeId -> FramePayload
SettingsFrame :: !SettingsList -> FramePayload
PushPromiseFrame :: !StreamId -> !HeaderBlockFragment -> FramePayload
PingFrame :: !ByteString -> FramePayload
GoAwayFrame :: !StreamId -> !ErrorCodeId -> !ByteString -> FramePayload
WindowUpdateFrame :: !WindowSize -> FramePayload
ContinuationFrame :: !HeaderBlockFragment -> FramePayload
UnknownFrame :: !FrameType -> !ByteString -> FramePayload
-- | The type for fragments of a header encoded with HPACK.
type HeaderBlockFragment = ByteString
-- | The type for padding in payloads.
type Padding = ByteString
-- | Checking if padding is defined in this frame type.
--
-- -- >>> isPaddingDefined $ DataFrame "" -- True -- -- >>> isPaddingDefined $ PingFrame "" -- False --isPaddingDefined :: FramePayload -> Bool -- | Encoding an HTTP/2 frame to ByteString. This function is not -- efficient enough for high performace program because of the -- concatenation of ByteString. -- --
-- >>> encodeFrame (encodeInfo id 1) (DataFrame "body") -- "\NUL\NUL\EOT\NUL\NUL\NUL\NUL\NUL\SOHbody" --encodeFrame :: EncodeInfo -> FramePayload -> ByteString -- | Encoding an HTTP/2 frame to [ByteString]. This is suitable for -- sendMany. encodeFrameChunks :: EncodeInfo -> FramePayload -> [ByteString] -- | Encoding an HTTP/2 frame header. The frame header must be completed. encodeFrameHeader :: FrameTypeId -> FrameHeader -> ByteString -- | Writing an encoded HTTP/2 frame header to the buffer. The length of -- the buffer must be larger than or equal to 9 bytes. encodeFrameHeaderBuf :: FrameTypeId -> FrameHeader -> Ptr Word8 -> IO () -- | Encoding an HTTP/2 frame payload. This returns a complete frame header -- and chunks of payload. encodeFramePayload :: EncodeInfo -> FramePayload -> (FrameHeader, [ByteString]) -- | Auxiliary information for frame encoding. data EncodeInfo EncodeInfo :: !FrameFlags -> !StreamId -> !Maybe Padding -> EncodeInfo -- | Flags to be set in a frame header [encodeFlags] :: EncodeInfo -> !FrameFlags -- | Stream id to be set in a frame header [encodeStreamId] :: EncodeInfo -> !StreamId -- | Padding if any. In the case where this value is set but the priority -- flag is not set, this value gets preference over the priority flag. -- So, if this value is set, the priority flag is also set. [encodePadding] :: EncodeInfo -> !Maybe Padding -- | A smart builder of EncodeInfo. -- --
-- >>> encodeInfo setAck 0
-- EncodeInfo {encodeFlags = 1, encodeStreamId = 0, encodePadding = Nothing}
--
encodeInfo :: (FrameFlags -> FrameFlags) -> Int -> EncodeInfo
-- | Decoding an HTTP/2 frame to ByteString. The second argument
-- must be include the entire of frame. So, this function is not useful
-- for real applications but useful for testing.
decodeFrame :: Settings -> ByteString -> Either HTTP2Error Frame
-- | Decoding an HTTP/2 frame header. Must supply 9 bytes.
decodeFrameHeader :: ByteString -> (FrameTypeId, FrameHeader)
-- | Checking a frame header and reporting an error if any.
--
-- -- >>> checkFrameHeader defaultSettings (FrameData,(FrameHeader 100 0 0)) -- Left (ConnectionError ProtocolError "cannot used in control stream") --checkFrameHeader :: Settings -> (FrameTypeId, FrameHeader) -> Either HTTP2Error (FrameTypeId, FrameHeader) -- | Decoding an HTTP/2 frame payload. This function is considered to -- return a frame payload decoder according to a frame type. decodeFramePayload :: FrameTypeId -> FramePayloadDecoder -- | The type for frame payload decoder. type FramePayloadDecoder = FrameHeader -> ByteString -> Either HTTP2Error FramePayload -- | Frame payload decoder for DATA frame. decodeDataFrame :: FramePayloadDecoder -- | Frame payload decoder for HEADERS frame. decodeHeadersFrame :: FramePayloadDecoder -- | Frame payload decoder for PRIORITY frame. decodePriorityFrame :: FramePayloadDecoder -- | Frame payload decoder for RST_STREAM frame. decoderstStreamFrame :: FramePayloadDecoder -- | Frame payload decoder for SETTINGS frame. decodeSettingsFrame :: FramePayloadDecoder -- | Frame payload decoder for PUSH_PROMISE frame. decodePushPromiseFrame :: FramePayloadDecoder -- | Frame payload decoder for PING frame. decodePingFrame :: FramePayloadDecoder -- | Frame payload decoder for GOAWAY frame. decodeGoAwayFrame :: FramePayloadDecoder -- | Frame payload decoder for WINDOW_UPDATE frame. decodeWindowUpdateFrame :: FramePayloadDecoder -- | Frame payload decoder for CONTINUATION frame. decodeContinuationFrame :: FramePayloadDecoder -- | The type for frame type. data FrameTypeId FrameData :: FrameTypeId FrameHeaders :: FrameTypeId FramePriority :: FrameTypeId FrameRSTStream :: FrameTypeId FrameSettings :: FrameTypeId FramePushPromise :: FrameTypeId FramePing :: FrameTypeId FrameGoAway :: FrameTypeId FrameWindowUpdate :: FrameTypeId FrameContinuation :: FrameTypeId FrameUnknown :: FrameType -> FrameTypeId -- | Getting FrameType from FramePayload. -- --
-- >>> framePayloadToFrameTypeId (DataFrame "body") -- FrameData --framePayloadToFrameTypeId :: FramePayload -> FrameTypeId -- | The type for raw frame type. type FrameType = Word8 -- | Converting FrameTypeId to FrameType. -- --
-- >>> fromFrameTypeId FrameData -- 0 -- -- >>> fromFrameTypeId FrameContinuation -- 9 -- -- >>> fromFrameTypeId (FrameUnknown 10) -- 10 --fromFrameTypeId :: FrameTypeId -> FrameType -- | Converting FrameType to FrameTypeId. -- --
-- >>> toFrameTypeId 0 -- FrameData -- -- >>> toFrameTypeId 9 -- FrameContinuation -- -- >>> toFrameTypeId 10 -- FrameUnknown 10 --toFrameTypeId :: FrameType -> FrameTypeId -- | Type for stream priority data Priority Priority :: !Bool -> !StreamId -> !Weight -> Priority [exclusive] :: Priority -> !Bool [streamDependency] :: Priority -> !StreamId [weight] :: Priority -> !Weight -- | The type for weight in priority. Its values are from 1 to 256. type Weight = Int -- | Default priority which depends on stream 0. -- --
-- >>> defaultPriority
-- Priority {exclusive = False, streamDependency = 0, weight = 16}
--
defaultPriority :: Priority
-- | Highest priority which depends on stream 0.
--
--
-- >>> highestPriority
-- Priority {exclusive = False, streamDependency = 0, weight = 256}
--
highestPriority :: Priority
-- | The type for stream identifier
type StreamId = Int
-- | Checking if the stream identifier for control.
--
-- -- >>> isControl 0 -- True -- -- >>> isControl 1 -- False --isControl :: StreamId -> Bool -- | Checking if the stream identifier for request. -- --
-- >>> isRequest 0 -- False -- -- >>> isRequest 1 -- True --isRequest :: StreamId -> Bool -- | Checking if the stream identifier for response. -- --
-- >>> isResponse 0 -- False -- -- >>> isResponse 2 -- True --isResponse :: StreamId -> Bool -- | Checking if the exclusive flag is set. testExclusive :: StreamId -> Bool -- | Setting the exclusive flag. setExclusive :: StreamId -> StreamId -- | Clearing the exclusive flag. clearExclusive :: StreamId -> StreamId -- | The type for flags. type FrameFlags = Word8 -- | The initial value of flags. No flags are set. -- --
-- >>> defaultFlags -- 0 --defaultFlags :: FrameFlags -- | Checking if the END_STREAM flag is set. >>> testEndStream 0x1 -- True testEndStream :: FrameFlags -> Bool -- | Checking if the ACK flag is set. >>> testAck 0x1 True testAck :: FrameFlags -> Bool -- | Checking if the END_HEADERS flag is set. -- --
-- >>> testEndHeader 0x4 -- True --testEndHeader :: FrameFlags -> Bool -- | Checking if the PADDED flag is set. -- --
-- >>> testPadded 0x8 -- True --testPadded :: FrameFlags -> Bool -- | Checking if the PRIORITY flag is set. -- --
-- >>> testPriority 0x20 -- True --testPriority :: FrameFlags -> Bool -- | Setting the END_STREAM flag. -- --
-- >>> setEndStream 0 -- 1 --setEndStream :: FrameFlags -> FrameFlags -- | Setting the ACK flag. -- --
-- >>> setAck 0 -- 1 --setAck :: FrameFlags -> FrameFlags -- | Setting the END_HEADERS flag. -- --
-- >>> setEndHeader 0 -- 4 --setEndHeader :: FrameFlags -> FrameFlags -- | Setting the PADDED flag. -- --
-- >>> setPadded 0 -- 8 --setPadded :: FrameFlags -> FrameFlags -- | Setting the PRIORITY flag. -- --
-- >>> setPriority 0 -- 32 --setPriority :: FrameFlags -> FrameFlags -- | Association list of SETTINGS. type SettingsList = [(SettingsKeyId, SettingsValue)] -- | The type for SETTINGS key. data SettingsKeyId SettingsHeaderTableSize :: SettingsKeyId SettingsEnablePush :: SettingsKeyId SettingsMaxConcurrentStreams :: SettingsKeyId SettingsInitialWindowSize :: SettingsKeyId SettingsMaxFrameSize :: SettingsKeyId SettingsMaxHeaderBlockSize :: SettingsKeyId -- | The type for raw SETTINGS value. type SettingsValue = Int -- | Converting SettingsKeyId to raw value. -- --
-- >>> fromSettingsKeyId SettingsHeaderTableSize -- 1 -- -- >>> fromSettingsKeyId SettingsMaxHeaderBlockSize -- 6 --fromSettingsKeyId :: SettingsKeyId -> Word16 -- | Converting raw value to SettingsKeyId. -- --
-- >>> toSettingsKeyId 0 -- Nothing -- -- >>> toSettingsKeyId 1 -- Just SettingsHeaderTableSize -- -- >>> toSettingsKeyId 6 -- Just SettingsMaxHeaderBlockSize -- -- >>> toSettingsKeyId 7 -- Nothing --toSettingsKeyId :: Word16 -> Maybe SettingsKeyId -- | Checking SettingsList and reporting an error if any. -- --
-- >>> checkSettingsList [(SettingsEnablePush,2)] -- Just (ConnectionError ProtocolError "enable push must be 0 or 1") --checkSettingsList :: SettingsList -> Maybe HTTP2Error -- | Cooked version of settings. This is suitable to be stored in a HTTP/2 -- context. data Settings Settings :: !Int -> !Bool -> !Maybe Int -> !WindowSize -> !Int -> !Maybe Int -> Settings [headerTableSize] :: Settings -> !Int [enablePush] :: Settings -> !Bool [maxConcurrentStreams] :: Settings -> !Maybe Int [initialWindowSize] :: Settings -> !WindowSize [maxFrameSize] :: Settings -> !Int [maxHeaderBlockSize] :: Settings -> !Maybe Int -- | The default settings. -- --
-- >>> defaultSettings
-- Settings {headerTableSize = 4096, enablePush = True, maxConcurrentStreams = Nothing, initialWindowSize = 65535, maxFrameSize = 16384, maxHeaderBlockSize = Nothing}
--
defaultSettings :: Settings
-- | Updating settings.
--
--
-- >>> updateSettings defaultSettings [(SettingsEnablePush,0),(SettingsMaxHeaderBlockSize,200)]
-- Settings {headerTableSize = 4096, enablePush = False, maxConcurrentStreams = Nothing, initialWindowSize = 65535, maxFrameSize = 16384, maxHeaderBlockSize = Just 200}
--
updateSettings :: Settings -> SettingsList -> Settings
-- | The type for window size.
type WindowSize = Int
-- | The default initial window size.
--
-- -- >>> defaultInitialWindowSize -- 65535 --defaultInitialWindowSize :: WindowSize -- | The maximum window size. -- --
-- >>> maxWindowSize -- 2147483647 --maxWindowSize :: WindowSize -- | Checking if a window size exceeds the maximum window size. -- --
-- >>> isWindowOverflow 10 -- False -- -- >>> isWindowOverflow maxWindowSize -- False -- -- >>> isWindowOverflow (maxWindowSize + 1) -- True --isWindowOverflow :: WindowSize -> Bool -- | The type for raw error code. type ErrorCode = Word32 -- | The type for error code. See -- https://tools.ietf.org/html/rfc7540#section-7. data ErrorCodeId NoError :: ErrorCodeId ProtocolError :: ErrorCodeId InternalError :: ErrorCodeId FlowControlError :: ErrorCodeId SettingsTimeout :: ErrorCodeId StreamClosed :: ErrorCodeId FrameSizeError :: ErrorCodeId RefusedStream :: ErrorCodeId Cancel :: ErrorCodeId CompressionError :: ErrorCodeId ConnectError :: ErrorCodeId EnhanceYourCalm :: ErrorCodeId InadequateSecurity :: ErrorCodeId HTTP11Required :: ErrorCodeId UnknownErrorCode :: ErrorCode -> ErrorCodeId -- | Converting ErrorCodeId to ErrorCode. -- --
-- >>> fromErrorCodeId NoError -- 0 -- -- >>> fromErrorCodeId InadequateSecurity -- 12 --fromErrorCodeId :: ErrorCodeId -> ErrorCode -- | Converting ErrorCode to ErrorCodeId. -- --
-- >>> toErrorCodeId 0 -- NoError -- -- >>> toErrorCodeId 0xc -- InadequateSecurity -- -- >>> toErrorCodeId 0xe -- UnknownErrorCode 14 --toErrorCodeId :: ErrorCode -> ErrorCodeId -- | The connection error or the stream error. data HTTP2Error ConnectionError :: !ErrorCodeId -> !ByteString -> HTTP2Error StreamError :: !ErrorCodeId -> !StreamId -> HTTP2Error -- | Obtaining ErrorCodeId from HTTP2Error. errorCodeId :: HTTP2Error -> ErrorCodeId -- | The preface of HTTP/2. -- --
-- >>> connectionPreface -- "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" --connectionPreface :: ByteString -- | Length of the preface. -- --
-- >>> connectionPrefaceLength -- 24 --connectionPrefaceLength :: Int -- | The length of HTTP/2 frame header. -- --
-- >>> frameHeaderLength -- 9 --frameHeaderLength :: Int -- | The maximum length of HTTP/2 payload. -- --
-- >>> maxPayloadLength -- 16384 --maxPayloadLength :: Int -- | Default concurrency. -- --
-- >>> recommendedConcurrency -- 100 --recommendedConcurrency :: Int -- | HTTP/2 server library. -- -- Example: -- --
-- {-# LANGUAGE OverloadedStrings #-}
-- module Main (main) where
--
-- import Control.Concurrent (forkFinally)
-- import qualified Control.Exception as E
-- import Control.Monad (forever, void)
-- import Data.ByteString.Builder (byteString)
-- import Network.HTTP.Types (ok200)
-- import Network.HTTP2.Server
-- import Network.Socket
--
-- main :: IO ()
-- main = withSocketsDo $ do
-- addr <- resolve "80"
-- E.bracket (open addr) close loop
-- where
-- server _req _ctl sendResponse = sendResponse response []
-- where
-- response = responseBuilder ok200 [("Content-Type", "text/plain")] (byteString "Hello, world!\n")
-- loop sock = forever $ do
-- (s, _peer) <- accept sock
-- (config, cleanup) <- makeSimpleConfig s 4096
-- void $ forkFinally (run config server) (\_ -> close s >> cleanup)
-- resolve port = do
-- let hints = defaultHints {
-- addrFlags = [AI_PASSIVE]
-- , addrSocketType = Stream
-- }
-- addr:_ <- getAddrInfo (Just hints) Nothing (Just port)
-- return addr
-- open addr = do
-- sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
-- setSocketOption sock ReuseAddr 1
-- withFdSocket sock $ setCloseOnExecIfNeeded
-- bind sock (addrAddress addr)
-- listen sock 10
-- return sock
--
module Network.HTTP2.Server
-- | Running HTTP/2 server.
run :: Config -> Server -> IO ()
-- | HTTP/2 server configuration.
data Config
Config :: Buffer -> BufferSize -> (ByteString -> IO ()) -> (Int -> IO ByteString) -> PositionReadMaker -> Config
[confWriteBuffer] :: Config -> Buffer
[confBufferSize] :: Config -> BufferSize
[confSendAll] :: Config -> ByteString -> IO ()
[confReadN] :: Config -> Int -> IO ByteString
[confPositionReadMaker] :: Config -> PositionReadMaker
-- | Making configuration whose IO is not efficient. A write buffer is
-- allocated internally. That should be deallocated by the returned
-- action.
makeSimpleConfig :: Socket -> BufferSize -> IO (Config, IO ())
-- | HTTP/2 server takes a HTTP request, should generate a HTTP response
-- and push promises, then should give them to the sending function. The
-- sending function would throw exceptions so that they can be logged.
type Server = Request -> Aux -> (Response -> [PushPromise] -> IO ()) -> IO ()
-- | HTTP request.
data Request
-- | Accessor for request headers.
requestHeaders :: Request -> HeaderTable
-- | Accessor for body length specified in content-length:.
requestBodySize :: Request -> Maybe Int
-- | Reading a chunk of the request body. An empty ByteString
-- returned when finished.
getRequestBodyChunk :: Request -> IO ByteString
-- | Reading request trailers. This function must be called after
-- getRequestBodyChunk returns an empty.
getRequestTrailers :: Request -> IO (Maybe HeaderTable)
-- | Additional information.
data Aux
-- | Time handle for the worker processing this request and response.
auxTimeHandle :: Aux -> Handle
-- | HTTP response.
data Response
-- | Creating response without body.
responseNoBody :: Status -> ResponseHeaders -> Response
-- | Creating response with file.
responseFile :: Status -> ResponseHeaders -> FileSpec -> Response
-- | Creating response with streaming.
responseStreaming :: Status -> ResponseHeaders -> ((Builder -> IO ()) -> IO () -> IO ()) -> Response
-- | Creating response with builder.
responseBuilder :: Status -> ResponseHeaders -> Builder -> Response
-- | Accessor for response status.
responseStatus :: Response -> Status
-- | Getter for response body size. This value is available for file body.
responseBodySize :: Response -> Maybe Int
-- | Trailers maker. A chunks of the response body is passed with
-- Just. The maker should update internal state with the
-- ByteString and return the next trailers maker. When response
-- body reaches its end, Nothing is passed and the maker should
-- generate trailers. An example:
--
--
-- {-# LANGUAGE BangPatterns #-}
-- import Data.ByteString (ByteString)
-- import qualified Data.ByteString.Char8 as C8
-- import Crypto.Hash (Context, SHA1) -- cryptonite
-- import qualified Crypto.Hash as CH
--
-- -- Strictness is important for Context.
-- trailersMaker :: Context SHA1 -> Maybe ByteString -> IO NextTrailersMaker
-- trailersMaker ctx Nothing = return $ Trailers [("X-SHA1", sha1)]
-- where
-- !sha1 = C8.pack $ show $ CH.hashFinalize ctx
-- trailersMaker ctx (Just bs) = return $ NextTrailersMaker $ trailersMaker ctx'
-- where
-- !ctx' = CH.hashUpdate ctx bs
--
--
-- Usage example:
--
-- -- let h2rsp = responseFile ... -- maker = trailersMaker (CH.hashInit :: Context SHA1) -- h2rsp' = setResponseTrailersMaker h2rsp maker --type TrailersMaker = Maybe ByteString -> IO NextTrailersMaker -- | Either the next trailers maker or final trailers. data NextTrailersMaker NextTrailersMaker :: !TrailersMaker -> NextTrailersMaker Trailers :: ResponseHeaders -> NextTrailersMaker -- | TrailersMake to create no trailers. defaultTrailersMaker :: TrailersMaker -- | Setting TrailersMaker to Response. setResponseTrailersMaker :: Response -> TrailersMaker -> Response -- | HTTP/2 push promise or sever push. Pseudo REQUEST headers in push -- promise is automatically generated. Then, a server push is sent -- according to promiseResponse. data PushPromise -- | Creating push promise. pushPromise :: ByteString -> Response -> Weight -> PushPromise -- | Accessor for a URL path in a push promise (a virtual request from a -- server). E.g. "/style/default.css". promiseRequestPath :: PushPromise -> ByteString -- | Accessor for response actually pushed from a server. promiseResponse :: PushPromise -> Response -- | Accessor for response weight. promiseWeight :: PushPromise -> Weight -- | File specification. data FileSpec FileSpec :: FilePath -> FileOffset -> ByteCount -> FileSpec -- | Offset for file. type FileOffset = Int64 -- | How many bytes to read type ByteCount = Int64 -- | Naive implementation for readN. defaultReadN :: Socket -> IORef (Maybe ByteString) -> Int -> IO ByteString -- | Making a position read and its closer. type PositionReadMaker = FilePath -> IO (PositionRead, Sentinel) -- | Position read for files. type PositionRead = FileOffset -> ByteCount -> Buffer -> IO ByteCount -- | Manipulating a file resource. data Sentinel -- | Closing a file resource. Its refresher is automatiaclly generated by -- the internal timer. Closer :: IO () -> Sentinel -- | Refreshing a file resource while reading. Closing the file must be -- done by its own timer or something. Refresher :: IO () -> Sentinel -- | Position read based on Handle. defaultPositionReadMaker :: PositionReadMaker