| Safe Haskell | None |
|---|---|
| Language | Haskell2010 |
Network.Wai.Handler.Warp.Internal
Description
IMPORTANT NOTICE
This module exports internals mainly to provide the warp-tls package
with tools to implement what it needs to. This module/API should NOT be
expected to remain stable at all, even between minor releases.
If you see a use case for these functions or types for other purposes,
please create an issue in the repository so that we might add it to the
main Warp API.
Synopsis
- data Settings = Settings {
- settingsPort :: Port
- settingsHost :: HostPreference
- settingsOnException :: Maybe Request -> SomeException -> IO ()
- settingsOnConnectionException :: Maybe (SockAddr -> SomeException -> IO ())
- settingsOnExceptionResponse :: SomeException -> Response
- settingsOnOpen :: SockAddr -> IO Bool
- settingsOnClose :: SockAddr -> IO ()
- settingsTimeout :: Int
- settingsManager :: Maybe Manager
- settingsFdCacheDuration :: Int
- settingsFileInfoCacheDuration :: Int
- settingsBeforeMainLoop :: IO ()
- settingsFork :: ((forall a. IO a -> IO a) -> IO ()) -> IO ()
- settingsAccept :: Socket -> IO (Socket, SockAddr)
- settingsNoParsePath :: Bool
- settingsInstallShutdownHandler :: IO () -> IO ()
- settingsServerName :: ByteString
- settingsMaximumBodyFlush :: Maybe Int
- settingsProxyProtocol :: ProxyProtocol
- settingsSlowlorisSize :: Int
- settingsHTTP2Enabled :: Bool
- settingsLogger :: Request -> Status -> Maybe Integer -> IO ()
- settingsServerPushLogger :: Request -> ByteString -> Integer -> IO ()
- settingsGracefulShutdownTimeout :: Maybe Int
- settingsGracefulCloseTimeout1 :: Int
- settingsGracefulCloseTimeout2 :: Int
- settingsMaxTotalHeaderLength :: Int
- settingsAltSvc :: Maybe ByteString
- settingsMaxBuilderResponseBufferSize :: Int
- settingsConnectionCounter :: Maybe Counter
- settingsServerState :: Maybe ServerState
- settingsUnsafeClose :: Bool
- data ProxyProtocol
- makeSettingsAndCounter :: IO (Counter, Settings)
- makeSettingsAndServerState :: IO (ServerState, Settings)
- data Counter
- getCount :: Counter -> IO Int
- data ServerState
- makeServerState :: Settings -> IO (ServerState, Settings)
- runSettingsConnection :: Settings -> IO (Connection, SockAddr) -> Application -> IO ()
- runSettingsConnectionMaker :: Settings -> IO (IO Connection, SockAddr) -> Application -> IO ()
- runSettingsConnectionMakerSecure :: Settings -> IO (IO (Connection, Transport), SockAddr) -> Application -> IO ()
- runSettingsConnectionMakerSecureWith :: Settings -> Listener -> IO (IO (Connection, Transport), SockAddr) -> Application -> IO ()
- data Transport
- = TCP
- | TLS {
- tlsMajorVersion :: Int
- tlsMinorVersion :: Int
- tlsNegotiatedProtocol :: Maybe ByteString
- tlsChiperID :: Word16
- tlsClientCertificate :: Maybe CertificateChain
- | QUIC {
- quicNegotiatedProtocol :: Maybe ByteString
- quicChiperID :: Word16
- quicClientCertificate :: Maybe CertificateChain
- data Listener = Listener {
- acceptOrStop :: IO (Maybe (Socket, SockAddr))
- closeListener :: IO ()
- noListener :: Listener
- makeListener :: Settings -> Socket -> IO Listener
- data AcceptStopped = AcceptStopped
- data Connection = Connection {
- connSendMany :: [ByteString] -> IO ()
- connSendAll :: ByteString -> IO ()
- connSendFile :: SendFile
- connClose :: IO ()
- connRecv :: Recv
- connRecvBuf :: RecvBuf
- connWriteBuffer :: IORef WriteBuffer
- connHTTP2 :: IORef Bool
- connMySockAddr :: SockAddr
- connAppsInProgress :: TVar Int
- socketConnection :: Settings -> Socket -> IO Connection
- type Recv = IO ByteString
- makeGracefulRecv :: Socket -> BufferPool -> ServerState -> TVar Int -> Recv
- type RecvBuf = Buffer -> BufSize -> IO Bool
- type Buffer = Ptr Word8
- type BufSize = Int
- data WriteBuffer = WriteBuffer {}
- createWriteBuffer :: BufSize -> IO WriteBuffer
- allocateBuffer :: Int -> IO Buffer
- freeBuffer :: Buffer -> IO ()
- copy :: Buffer -> ByteString -> IO Buffer
- data FileId = FileId {
- fileIdPath :: FilePath
- fileIdFd :: Maybe Fd
- type SendFile = FileId -> Integer -> Integer -> IO () -> [ByteString] -> IO ()
- sendFile :: Socket -> Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile
- readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile
- warpVersion :: String
- data InternalInfo = InternalInfo {
- timeoutManager :: Manager
- getDate :: IO GMTDate
- getFd :: FilePath -> IO (Maybe Fd, Refresh)
- getFileInfo :: FilePath -> IO FileInfo
- type HeaderValue = ByteString
- type IndexedHeader = IndexedRequestHeader
- defaultIndexRequestHeader :: IndexedRequestHeader
- cancel :: Handle -> IO ()
- defaultManager :: Manager
- emptyHandle :: Handle
- initialize :: Int -> IO Manager
- killManager :: Manager -> IO ()
- pause :: Handle -> IO ()
- register :: Manager -> TimeoutAction -> IO Handle
- registerKillThread :: Manager -> TimeoutAction -> IO Handle
- resume :: Handle -> IO ()
- stopManager :: Manager -> IO ()
- tickle :: Handle -> IO ()
- withHandle :: Manager -> TimeoutAction -> (Handle -> IO a) -> IO a
- withHandleKillThread :: Manager -> TimeoutAction -> (Handle -> IO ()) -> IO ()
- withManager :: Int -> (Manager -> IO a) -> IO a
- withManager' :: Int -> (Manager -> IO a) -> IO a
- data TimeoutThread = TimeoutThread
- data Handle
- data Manager
- type TimeoutAction = IO ()
- closeFile :: Fd -> IO ()
- openFile :: FilePath -> IO Fd
- setFileCloseOnExec :: Fd -> IO ()
- withFdCache :: Int -> ((FilePath -> IO (Maybe Fd, Refresh)) -> IO a) -> IO a
- data Fd
- type Refresh = IO ()
- getInfo :: FilePath -> IO FileInfo
- withFileInfoCache :: Int -> ((FilePath -> IO FileInfo) -> IO a) -> IO a
- data FileInfo = FileInfo {
- fileInfoName :: !FilePath
- fileInfoSize :: !Integer
- fileInfoTime :: HTTPDate
- fileInfoDate :: ByteString
- withDateCache :: (IO GMTDate -> IO a) -> IO a
- type GMTDate = ByteString
- data Source
- data FirstRequest
- recvRequest :: FirstRequest -> Settings -> Connection -> InternalInfo -> Handle -> SockAddr -> Source -> Transport -> IO (Request, Maybe (IORef Int), IndexedRequestHeader, IO ByteString)
- sendResponse :: Settings -> Connection -> InternalInfo -> Handle -> Request -> IndexedRequestHeader -> IO ByteString -> Response -> IO Bool
- setSocketCloseOnExec :: Socket -> IO ()
- windowsThreadBlockHack :: IO a -> IO a
- http2server :: String -> Settings -> InternalInfo -> Transport -> SockAddr -> Application -> Server
- withII :: Settings -> (InternalInfo -> IO a) -> IO a
- serveConnection :: Connection -> InternalInfo -> Handle -> SockAddr -> Transport -> Settings -> Application -> IO ()
- pReadMaker :: InternalInfo -> PositionReadMaker
Settings
Various Warp server settings. This is purposely kept as an abstract data
type so that new settings can be added without breaking backwards
compatibility. In order to create a Settings value, use defaultSettings
and the various 'set' functions to modify individual fields. For example:
setTimeout 20 defaultSettings
Constructors
| Settings | |
Fields
| |
data ProxyProtocol Source #
Specify usage of the PROXY protocol.
Constructors
| ProxyProtocolNone | See |
| ProxyProtocolRequired | See |
| ProxyProtocolOptional | See |
makeSettingsAndCounter :: IO (Counter, Settings) Source #
Create defaultSettings with a connection counter.
Use getCount on the returned Counter to check open connections.
DEPRECATED in favor of makeSettingsAndServerState
Since: 3.4.11
makeSettingsAndServerState :: IO (ServerState, Settings) Source #
Create defaultSettings with a ServerState.
Use functions like currentOpenConnections and currentShuttingDownState
to gain insight into the state of the server.
Since: 3.4.13
Connection counter
The connections of a server: how many there are, and which threads are serving them.
Both come from the ThreadManager, which counts a connection from
when the accept loop keeps a place for it -- before the thread that
will serve it has been scheduled, which is too late for a graceful
shutdown to notice it.
Server state
data ServerState Source #
Internal read-only state of the server
Since: 3.4.13
makeServerState :: Settings -> IO (ServerState, Settings) Source #
Takes Settings and either returns the ServerState
that was already in there, or creates a new ServerState.
The returned Settings will always contain a ServerState.
This makes it idempotent if care is taken that the oldSettings
are not used after using this function.
Since: 3.4.13
Low level run functions
runSettingsConnection :: Settings -> IO (Connection, SockAddr) -> Application -> IO () Source #
The connection setup action would be expensive. A good example
is initialization of TLS.
So, this converts the connection setup action to the connection maker
which will be executed after forking a new worker thread.
Then this calls runSettingsConnectionMaker with the connection maker.
This allows the expensive computations to be performed
in a separate worker thread instead of the main server loop.
Since: 1.3.5
runSettingsConnectionMaker :: Settings -> IO (IO Connection, SockAddr) -> Application -> IO () Source #
This modifies the connection maker so that it returns TCP for Transport
(i.e. plain HTTP) then calls runSettingsConnectionMakerSecure.
runSettingsConnectionMakerSecure :: Settings -> IO (IO (Connection, Transport), SockAddr) -> Application -> IO () Source #
The core run function which takes Settings,
a connection maker and Application.
The connection maker can return a connection of either plain HTTP
or HTTP over TLS.
Since: 2.1.4
runSettingsConnectionMakerSecureWith :: Settings -> Listener -> IO (IO (Connection, Transport), SockAddr) -> Application -> IO () Source #
runSettingsConnectionMakerSecure for a caller that has the listening
socket, and so can say how the accept loop waits on it and what becomes
of it when the loop stops.
What kind of transport is used for this connection?
Constructors
| TCP | Plain channel: TCP |
| TLS | |
Fields
| |
| QUIC | |
Fields
| |
Stopping the accept loop
What the accept loop waits on at the top of each turn, and what it leaves behind when it stops.
A server used to be stopped by closing the listening socket under the
thread waiting in accept on it. That takes an IO manager that can wake
a thread out of a wait by closing the file descriptor under it, which is
what closeFdWith is for, and the IO manager that provides it
is not the only one there will be. So the loop waits for the socket and
for the shutdown at once and ends on whichever comes first; the socket is
closed after it, by which time nothing is waiting on it.
Constructors
| Listener | |
Fields
| |
noListener :: Listener Source #
For a caller that handed warp a connection maker and no socket. There is nothing here to accept and nothing to close, and such a server ends the way it always did: by whatever its maker accepts on being closed.
makeListener :: Settings -> Socket -> IO Listener Source #
data AcceptStopped Source #
Thrown by a connection maker which was told to stop rather than handed a connection, and caught by the accept loop. A maker has to return a connection or throw, so this is how it says that there will not be one.
Constructors
| AcceptStopped |
Instances
| Exception AcceptStopped Source # | |
Defined in Network.Wai.Handler.Warp.Run Methods toException :: AcceptStopped -> SomeException fromException :: SomeException -> Maybe AcceptStopped displayException :: AcceptStopped -> String backtraceDesired :: AcceptStopped -> Bool | |
| Show AcceptStopped Source # | |
Defined in Network.Wai.Handler.Warp.Run Methods showsPrec :: Int -> AcceptStopped -> ShowS show :: AcceptStopped -> String showList :: [AcceptStopped] -> ShowS | |
Connection
data Connection Source #
Data type to manipulate IO actions for connections. This is used to abstract IO actions for plain HTTP and HTTP over TLS.
Constructors
| Connection | |
Fields
| |
socketConnection :: Settings -> Socket -> IO Connection Source #
Creating Connection for plain HTTP based on a given socket.
(N.B. make sure the Settings have an initialized ServerState to guarantee
a graceful shutdown)
Receive
makeGracefulRecv :: Socket -> BufferPool -> ServerState -> TVar Int -> Recv Source #
Create a Recv which stops receiving when the server is shutting down
and no Application is still using this Socket.
Nothing is closed and no thread is interrupted to make it return: the
read and the shutdown are waited for at once, inside receiveWith.
Buffer
data WriteBuffer Source #
A write buffer of a specified size containing bytes and a way to free the buffer.
createWriteBuffer :: BufSize -> IO WriteBuffer Source #
Allocate a buffer of the given size and wrap it in a WriteBuffer
containing that size and a finalizer.
allocateBuffer :: Int -> IO Buffer Source #
Allocating a buffer with malloc().
freeBuffer :: Buffer -> IO () Source #
Releasing a buffer with free().
Sendfile
Data type to abstract file identifiers. On Unix, a file descriptor would be specified to make use of the file descriptor cache.
Since: 3.1.0
Constructors
| FileId | |
Fields
| |
type SendFile = FileId -> Integer -> Integer -> IO () -> [ByteString] -> IO () Source #
fileid, offset, length, hook action, HTTP headers
Since: 3.1.0
sendFile :: Socket -> Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile Source #
Function to send a file based on sendfile() for Linux/Mac/FreeBSD.
This makes use of the file descriptor cache.
For other OSes, this is identical to readSendFile.
Since: 3.1.0
readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile Source #
Function to send a file based on pread()/send() for Unix.
This makes use of the file descriptor cache.
For Windows, this is emulated by Handle.
Since: 3.1.0
Version
warpVersion :: String Source #
The version of Warp.
Data types
The internals of IndexedHeader have changed since 3.4.15, so we
keep exporting it as a type synonym, but it is now a record instead of
an array.
As such there's no more requestMaxIndex, but we provide a blank
defaultIndexRequestHeader.
data InternalInfo Source #
Constructors
| InternalInfo | |
Fields
| |
type HeaderValue = ByteString Source #
The type for header value used with HeaderName.
type IndexedHeader = IndexedRequestHeader Source #
defaultIndexRequestHeader :: IndexedRequestHeader Source #
IndexedRequestHeader with no headers set.
Time out manager
In order to provide slowloris protection, Warp provides timeout handlers. We follow these rules:
- A timeout is created when a connection is opened.
- When all request headers are read, the timeout is tickled.
- Every time at least the slowloris size settings number of bytes of the request body are read, the timeout is tickled.
- The timeout is paused while executing user code. This will apply to both the application itself, and a ResponseSource response. The timeout is resumed as soon as we return from user code.
- Every time data is successfully sent to the client, the timeout is tickled.
emptyHandle :: Handle #
initialize :: Int -> IO Manager #
killManager :: Manager -> IO () #
register :: Manager -> TimeoutAction -> IO Handle #
registerKillThread :: Manager -> TimeoutAction -> IO Handle #
stopManager :: Manager -> IO () #
withHandle :: Manager -> TimeoutAction -> (Handle -> IO a) -> IO a #
withHandleKillThread :: Manager -> TimeoutAction -> (Handle -> IO ()) -> IO () #
withManager :: Int -> (Manager -> IO a) -> IO a #
withManager' :: Int -> (Manager -> IO a) -> IO a #
data TimeoutThread #
Constructors
| TimeoutThread |
Instances
| Exception TimeoutThread # | |
Defined in System.TimeManager Methods toException :: TimeoutThread -> SomeException fromException :: SomeException -> Maybe TimeoutThread displayException :: TimeoutThread -> String backtraceDesired :: TimeoutThread -> Bool | |
| Show TimeoutThread # | |
Defined in System.TimeManager Methods showsPrec :: Int -> TimeoutThread -> ShowS show :: TimeoutThread -> String showList :: [TimeoutThread] -> ShowS | |
type TimeoutAction = IO () #
File descriptor cache
setFileCloseOnExec :: Fd -> IO () Source #
withFdCache :: Int -> ((FilePath -> IO (Maybe Fd, Refresh)) -> IO a) -> IO a Source #
Creating MutableFdCache and executing the action in the second
argument. The first argument is a cache duration in microseconds.
Instances
| Bits Fd # | |
Defined in GHC.Internal.System.Posix.Types Methods complement :: Fd -> Fd complementBit :: Fd -> Int -> Fd bitSizeMaybe :: Fd -> Maybe Int unsafeShiftL :: Fd -> Int -> Fd unsafeShiftR :: Fd -> Int -> Fd | |
| FiniteBits Fd # | |
Defined in GHC.Internal.System.Posix.Types | |
| Eq Fd # | |
| Ord Fd # | |
| Bounded Fd # | |
Defined in GHC.Internal.System.Posix.Types | |
| Enum Fd # | |
| Storable Fd # | |
Defined in GHC.Internal.System.Posix.Types Methods peekElemOff :: Ptr Fd -> Int -> IO Fd pokeElemOff :: Ptr Fd -> Int -> Fd -> IO () peekByteOff :: Ptr b -> Int -> IO Fd pokeByteOff :: Ptr b -> Int -> Fd -> IO () | |
| Ix Fd # | |
| Num Fd # | |
| Read Fd # | |
Defined in GHC.Internal.System.Posix.Types | |
| Integral Fd # | |
| Real Fd # | |
Defined in GHC.Internal.System.Posix.Types Methods toRational :: Fd -> Rational | |
| Show Fd # | |
File information cache
withFileInfoCache :: Int -> ((FilePath -> IO FileInfo) -> IO a) -> IO a Source #
Creating a file information cache and executing the action in the second argument. The first argument is a cache duration in microseconds.
File information.
Constructors
| FileInfo | |
Fields
| |
Date
withDateCache :: (IO GMTDate -> IO a) -> IO a Source #
Creating DateCache and executing the action.
Request and response
Type for input streaming.
Caveat: a Source is meant to be used in one thread only.
data FirstRequest Source #
first request on this connection?
Constructors
| FirstRequest | |
| SubsequentRequest |
Arguments
| :: FirstRequest | |
| -> Settings | |
| -> Connection | |
| -> InternalInfo | |
| -> Handle | |
| -> SockAddr | Peer's address. |
| -> Source | Where HTTP request comes from. |
| -> Transport | |
| -> IO (Request, Maybe (IORef Int), IndexedRequestHeader, IO ByteString) |
|
Receiving a HTTP request from Connection and parsing its header
to create Request.
Arguments
| :: Settings | |
| -> Connection | |
| -> InternalInfo | |
| -> Handle | |
| -> Request | HTTP request. |
| -> IndexedRequestHeader | Indexed header of HTTP request. |
| -> IO ByteString | source from client, for raw response |
| -> Response | HTTP response including status code and response header. |
| -> IO Bool | Returing True if the connection is persistent. |
Sending a HTTP response to Connection according to Response.
Applications/middlewares MUST provide a proper ResponseHeaders.
so that inconsistency does not happen.
No header is deleted by this function.
Especially, Applications/middlewares MUST provide a proper Content-Type. They MUST NOT provide Content-Length, Content-Range, and Transfer-Encoding because they are inserted, when necessary, regardless they already exist. This function does not insert Content-Encoding. It's middleware's responsibility.
The Date and Server header is added if not exist in HTTP response header.
There are three basic APIs to create Response:
responseBuilder::Status->ResponseHeaders->Builder->Response- HTTP response body is created from
Builder. Transfer-Encoding: chunked is used in HTTP/1.1. responseStream::Status->ResponseHeaders->StreamingBody->Response- HTTP response body is created from
Builder. Transfer-Encoding: chunked is used in HTTP/1.1. responseRaw:: (IOByteString-> (ByteString->IO()) ->IO()) ->Response->Response- No header is added and no Transfer-Encoding: is applied.
responseFile::Status->ResponseHeaders->FilePath->MaybeFilePart->Response- HTTP response body is sent (by sendfile(), if possible) for GET method. HTTP response body is not sent by HEAD method. Content-Length and Content-Range are automatically added into the HTTP response header if necessary. If Content-Length and Content-Range exist in the HTTP response header, they would cause inconsistency. "Accept-Ranges: bytes" is also inserted.
Applications are categorized into simple and sophisticated.
Sophisticated applications should specify Just to
Maybe FilePart. They should treat the conditional request
by themselves. A proper Status (200 or 206) must be provided.
Simple applications should specify Nothing to
Maybe FilePart. The size of the specified file is obtained
by disk access or from the file info cache.
If-Modified-Since, If-Unmodified-Since, If-Range and Range
are processed. Since a proper status is chosen, Status is
ignored. Last-Modified is inserted.
Platform dependent helper functions
setSocketCloseOnExec :: Socket -> IO () Source #
Set flag FileCloseOnExec flag on a socket (on Unix)
Copied from: https://github.com/mzero/plush/blob/master/src/Plush/Server/Warp.hs
Since: 3.2.17
windowsThreadBlockHack :: IO a -> IO a Source #
Misc
http2server :: String -> Settings -> InternalInfo -> Transport -> SockAddr -> Application -> Server Source #
Converting WAI application to the server type of http2 library.
Since: 3.3.11
withII :: Settings -> (InternalInfo -> IO a) -> IO a Source #
Running an action with internal info.
Since: 3.3.11
serveConnection :: Connection -> InternalInfo -> Handle -> SockAddr -> Transport -> Settings -> Application -> IO () Source #
pReadMaker :: InternalInfo -> PositionReadMaker Source #
PositionReadMaker based on file descriptor cache.
Since: 3.3.13