Running HTTP/2 server.
Modulehttp2-5.3.10Haskell2010
Network.HTTP2.Server
HTTP/2 server library.
Example:
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Control.Exception as E
import Data.ByteString.Builder (byteString)
import Network.HTTP.Types (ok200)
import Network.Run.TCP (runTCPServer) -- network-run
import Network.HTTP2.Server
main :: IO ()
main = runTCPServer Nothing "80" runHTTP2Server
where
runHTTP2Server s = E.bracket (allocSimpleConfig s 4096)
freeSimpleConfig
(\config -> run defaultServerConfig config server)
server _req _aux sendResponse = sendResponse response []
where
response = responseBuilder ok200 header body
header = [("Content-Type", "text/plain")]
body = byteString "Hello, world!\n"- 21 types
- 42 values
- Packagehttp2-5.3.10
- Exports63
- LanguageHaskell2010
- LicenceBSD-3-Clause
- SourceServer.hs
Runner
1 declarationServer configuration
5 declarationsServer configuration
Instances2Eq, Show
Eq ServerConfigDefined in http2-5.3.10 · Network.HTTP2.Server.RunShow ServerConfigDefined in http2-5.3.10 · Network.HTTP2.Server.Run
The default server config.
defaultServerConfigServerConfig {numberOfWorkers = 8, connectionWindowSize = 16777216, settings = Settings {headerTableSize = 4096, enablePush = True, maxConcurrentStreams = Just 64, initialWindowSize = 262144, maxFrameSize = 16384, maxHeaderListSize = Nothing, pingRateLimit = 10, emptyFrameRateLimit = 4, settingsRateLimit = 4, rstRateLimit = 4}}
Deprecated. No effect anymore
Deprecated field.
The window size of incoming streams
Settings
HTTP/2 setting
8 declarationsHTTP/2 settings. See https://datatracker.ietf.org/doc/html/rfc9113#name-defined-settings.
The default settings.
defaultSettingsSettings {headerTableSize = 4096, enablePush = True, maxConcurrentStreams = Just 64, initialWindowSize = 262144, maxFrameSize = 16384, maxHeaderListSize = Nothing, pingRateLimit = 10, emptyFrameRateLimit = 4, settingsRateLimit = 4, rstRateLimit = 4}
SETTINGS_HEADER_TABLE_SIZE
SETTINGS_ENABLE_PUSH
SETTINGS_MAX_CONCURRENT_STREAMS
SETTINGS_INITIAL_WINDOW_SIZE
SETTINGS_MAX_FRAME_SIZE
SETTINGS_MAX_HEADER_LIST_SIZE
Rate limits
Maximum number of pings allowed per second (CVE-2019-9512)
Maximum number of settings frames allowed per second (CVE-2019-9515)
Maximum number of empty data frames allowed per second (CVE-2019-9518)
Maximum number of reset frames allowed per second (CVE-2023-44487)
Common configuration
45 declarationsHTTP/2 configuration.
Constructors
ConfigconfWriteBuffer :: BufferThis is used only by frameSender. This MUST be freed after frameSender is terminated.
confBufferSize :: BufferSizeThe size of the write buffer. We assume that the read buffer is the same size. So, this value is announced via SETTINGS_MAX_FRAME_SIZE to the peer.
confSendAll :: ByteString -> IO ()confReadN :: Int -> IO ByteStringconfPositionReadMaker :: PositionReadMakerconfTimeoutManager :: ManagerconfMySockAddr :: SockAddrThis is copied into Aux, if exist, on server.
confPeerSockAddr :: SockAddrThis is copied into Aux, if exist, on server.
Making simple configuration whose IO is not efficient. A write buffer is allocated internally. WAI timeout manger is initialized with 30_000_000 microseconds.
Making simple configuration whose IO is not efficient. A write buffer is allocated internally. The third argument is microseconds to initialize WAI timeout manager.
Deallocating the resource of the simple configuration.
Request from client.
Response from server.
Additional information.
Local socket address copied from Config.
Remove socket address copied from Config.
Time handle for the worker processing this request and response.
Server type. 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.
The sending function must only be called once.
Either the next trailers maker or final trailers.
Constructors
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 bsUsage example:
let h2rsp = responseFile ...
maker = trailersMaker (CH.hashInit :: Context SHA1)
h2rsp' = setResponseTrailersMaker h2rsp makerTrailersMake to create no trailers.
Authority.
How many bytes to read
Offset for file.
File specification.
Constructors
Constructors
OutBodyIfaceoutBodyUnmask :: forall x. IO x -> IO xUnmask exceptions in the thread spawned for the request body
This is used in the client: we spawn the new thread for the request body with exceptions masked, and provide the body of OutBodyStreamingIface with a callback to unmask them again (typically after installing an exception handler).
Unmasking in the server is a no-op, as here the scope of the thread that is spawned for the server is the entire handler, not just the response streaming body.
outBodyPush :: Builder -> IO ()Push a new chunk
In
http2, there is no direct correspondence between chunks and the resultingDATAframes sent: the chunks are collected (written to an internal write buffer) until we can fill a frame.See also outBodyFlush.
outBodyPushFinal :: Builder -> IO ()Push the final chunk
Using this function instead of outBodyPush can be used to guarantee that the final HTTP2 DATA frame is marked end-of-stream; with outBodyPush it may happen that an additional empty DATA frame is used for this purpose. Additionally, after calling this function, outBodyCancel will be a no-op.
outBodyCancel :: Maybe SomeException -> IO ()Cancel the stream
Sends a
RST_STREAMto the peer. If cancelling as the result of an exception, a Just should be provided which specifies the exception which will be stored locally as the reason for cancelling the stream; in this case, the error code sent with theRST_STREAMwill beINTERNAL_ERROR(see https://datatracker.ietf.org/doc/html/rfc7540#section-7). If Nothing is given, the error code will beCANCEL.If there is a partially constructed
DATAframe at the time of cancellation, this frame is discarded. If this is undesirable, you should call outBodyFlush prior to cancelling.outBodyFlush :: IO ()Flush
This can be used to emit a DATA frame with the data collected so far (using outBodyPush), even if that DATA frame has not yet reached the maximum frame size. Calling outBodyFlush unnecessarily can therefore result in excessive overhead from frame headers.
If no data is available to send, this is a no-op.
Path.
"http" or "https".
Making a position read and its closer.
Position read for files.
Position read based on Handle.
Reading n bytes.
Naive implementation for readN.
NOTE: This function is intended to be used by a single thread only. (It is probably quite rare anyway to want concurrent reads from the same network socket.)
Getter for response body size. This value is available for file body.
Creating push promise. The third argument is traditional, not used.
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.
Constructors
PushPromisepromiseRequestPath :: ByteStringAccessor for a URL path in a push promise (a virtual request from a server). E.g. "/style/default.css".
promiseResponse :: ResponseAccessor for response actually pushed from a server.
Reading a chunk of the request body. An empty ByteString returned when finished.
Generalization of getRequestBodyChunk which also returns if the ByteString is the final one
Reading request trailers. This function must be called after getRequestBodyChunk returns an empty.
Getting the authority from a request.
Getting the body size from a request.
Getting the headers from a request.
Getting the method from a request.
Getting the path from a request.
Getting the scheme from a request.
Creating response with builder.
Creating response with file.
Creating response without body.
Creating response with streaming.
Generalization of responseStreaming.
Setting TrailersMaker to Response.