Safe Haskell | None |
---|---|
Language | Haskell98 |
A fast, light-weight HTTP server handler for WAI.
HTTP/1.0, HTTP/1.1 and HTTP/2 are supported. For HTTP/2, Warp supports direct and ALPN (in TLS) but not upgrade.
Note on slowloris timeouts: to prevent slowloris attacks, timeouts are used at various points in request receiving and response sending. One interesting corner case is partial request body consumption; in that case, Warp's timeout handling is still in effect, and the timeout will not be triggered again. Therefore, it is recommended that once you start consuming the request body, you either:
- consume the entire body promptly
- call the
pauseTimeout
function
For more information, see https://github.com/yesodweb/wai/issues/351.
Synopsis
- run :: Port -> Application -> IO ()
- runEnv :: Port -> Application -> IO ()
- runSettings :: Settings -> Application -> IO ()
- runSettingsSocket :: Settings -> Socket -> Application -> IO ()
- data Settings
- defaultSettings :: Settings
- setPort :: Port -> Settings -> Settings
- setHost :: HostPreference -> Settings -> Settings
- setOnException :: (Maybe Request -> SomeException -> IO ()) -> Settings -> Settings
- setOnExceptionResponse :: (SomeException -> Response) -> Settings -> Settings
- setOnOpen :: (SockAddr -> IO Bool) -> Settings -> Settings
- setOnClose :: (SockAddr -> IO ()) -> Settings -> Settings
- setTimeout :: Int -> Settings -> Settings
- setManager :: Manager -> Settings -> Settings
- setFdCacheDuration :: Int -> Settings -> Settings
- setFileInfoCacheDuration :: Int -> Settings -> Settings
- setBeforeMainLoop :: IO () -> Settings -> Settings
- setNoParsePath :: Bool -> Settings -> Settings
- setInstallShutdownHandler :: (IO () -> IO ()) -> Settings -> Settings
- setServerName :: ByteString -> Settings -> Settings
- setMaximumBodyFlush :: Maybe Int -> Settings -> Settings
- setFork :: (((forall a. IO a -> IO a) -> IO ()) -> IO ()) -> Settings -> Settings
- setProxyProtocolNone :: Settings -> Settings
- setProxyProtocolRequired :: Settings -> Settings
- setProxyProtocolOptional :: Settings -> Settings
- setSlowlorisSize :: Int -> Settings -> Settings
- setHTTP2Disabled :: Settings -> Settings
- setLogger :: (Request -> Status -> Maybe Integer -> IO ()) -> Settings -> Settings
- setServerPushLogger :: (Request -> ByteString -> Integer -> IO ()) -> Settings -> Settings
- setGracefulShutdownTimeout :: Maybe Int -> Settings -> Settings
- getPort :: Settings -> Port
- getHost :: Settings -> HostPreference
- getOnOpen :: Settings -> SockAddr -> IO Bool
- getOnClose :: Settings -> SockAddr -> IO ()
- getOnException :: Settings -> Maybe Request -> SomeException -> IO ()
- getGracefulShutdownTimeout :: Settings -> Maybe Int
- defaultOnException :: Maybe Request -> SomeException -> IO ()
- defaultShouldDisplayException :: SomeException -> Bool
- defaultOnExceptionResponse :: SomeException -> Response
- exceptionResponseForDebug :: SomeException -> Response
- data HostPreference
- type Port = Int
- data InvalidRequest
- pauseTimeout :: Request -> IO ()
- data FileInfo = FileInfo {}
- getFileInfo :: Request -> FilePath -> IO FileInfo
- withApplication :: IO Application -> (Port -> IO a) -> IO a
- withApplicationSettings :: Settings -> IO Application -> (Port -> IO a) -> IO a
- testWithApplication :: IO Application -> (Port -> IO a) -> IO a
- testWithApplicationSettings :: Settings -> IO Application -> (Port -> IO a) -> IO a
- openFreePort :: IO (Port, Socket)
- warpVersion :: String
- data HTTP2Data
- http2dataPushPromise :: HTTP2Data -> [PushPromise]
- http2dataTrailers :: HTTP2Data -> ResponseHeaders
- defaultHTTP2Data :: HTTP2Data
- getHTTP2Data :: Request -> IO (Maybe HTTP2Data)
- setHTTP2Data :: Request -> Maybe HTTP2Data -> IO ()
- modifyHTTP2Data :: Request -> (Maybe HTTP2Data -> Maybe HTTP2Data) -> IO ()
- data PushPromise
- promisedPath :: PushPromise -> ByteString
- promisedFile :: PushPromise -> FilePath
- promisedResponseHeaders :: PushPromise -> ResponseHeaders
- promisedWeight :: PushPromise -> Weight
- defaultPushPromise :: PushPromise
Run a Warp server
All of these automatically serve the same Application
over HTTP/1,
HTTP/1.1, and HTTP/2.
run :: Port -> Application -> IO () Source #
Run an Application
on the given port.
This calls runSettings
with defaultSettings
.
runEnv :: Port -> Application -> IO () Source #
Run an Application
on the port present in the PORT
environment variable. Uses the Port
given when the variable is unset.
This calls runSettings
with defaultSettings
.
Since 3.0.9
runSettings :: Settings -> Application -> IO () Source #
Run an Application
with the given Settings
.
This opens a listen socket on the port defined in Settings
and
calls runSettingsSocket
.
runSettingsSocket :: Settings -> Socket -> Application -> IO () Source #
This installs a shutdown handler for the given socket and
calls runSettingsConnection
with the default connection setup action
which handles plain (non-cipher) HTTP.
When the listen socket in the second argument is closed, all live
connections are gracefully shut down.
The supplied socket can be a Unix named socket, which can be used when reverse HTTP proxying into your application.
Note that the settingsPort
will still be passed to Application
s via the
serverPort
record.
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
defaultSettings :: Settings Source #
The default settings for the Warp server. See the individual settings for the default value.
Setters
setHost :: HostPreference -> Settings -> Settings Source #
Interface to bind to. Default value: HostIPv4
Since 2.1.0
setOnException :: (Maybe Request -> SomeException -> IO ()) -> Settings -> Settings Source #
What to do with exceptions thrown by either the application or server.
Default: defaultOnException
Since 2.1.0
setOnExceptionResponse :: (SomeException -> Response) -> Settings -> Settings Source #
A function to create a Response
when an exception occurs.
Default: defaultOnExceptionResponse
Note that an application can handle its own exceptions without interfering with Warp:
myApp :: Application myApp request respond = innerApp `catch` onError where onError = respond . response500 request response500 :: Request -> SomeException -> Response response500 req someEx = responseLBS status500 -- ...
Since 2.1.0
setOnClose :: (SockAddr -> IO ()) -> Settings -> Settings Source #
What to do when a connection is closed. Default: do nothing.
Since 2.1.0
setTimeout :: Int -> Settings -> Settings Source #
Timeout value in seconds. Default value: 30
Since 2.1.0
setManager :: Manager -> Settings -> Settings Source #
Use an existing timeout manager instead of spawning a new one. If used,
settingsTimeout
is ignored.
Since 2.1.0
setFdCacheDuration :: Int -> Settings -> Settings Source #
Cache duration time of file descriptors in seconds. 0 means that the cache mechanism is not used.
The FD cache is an optimization that is useful for servers dealing with static files. However, if files are being modified, it can cause incorrect results in some cases. Therefore, we disable it by default. If you know that your files will be static or you prefer performance to file consistency, it's recommended to turn this on; a reasonable value for those cases is 10. Enabling this cache results in drastic performance improvement for file transfers.
Default value: 0, was previously 10
Since 3.0.13
setFileInfoCacheDuration :: Int -> Settings -> Settings Source #
Cache duration time of file information in seconds. 0 means that the cache mechanism is not used.
The file information cache is an optimization that is useful for servers dealing with static files. However, if files are being modified, it can cause incorrect results in some cases. Therefore, we disable it by default. If you know that your files will be static or you prefer performance to file consistency, it's recommended to turn this on; a reasonable value for those cases is 10. Enabling this cache results in drastic performance improvement for file transfers.
Default value: 0
setBeforeMainLoop :: IO () -> Settings -> Settings Source #
Code to run after the listening socket is ready but before entering the main event loop. Useful for signaling to tests that they can start running, or to drop permissions after binding to a restricted port.
Default: do nothing.
Since 2.1.0
setNoParsePath :: Bool -> Settings -> Settings Source #
Perform no parsing on the rawPathInfo.
This is useful for writing HTTP proxies.
Default: False
Since 2.1.0
setInstallShutdownHandler :: (IO () -> IO ()) -> Settings -> Settings Source #
A code to install shutdown handler.
For instance, this code should set up a UNIX signal handler. The handler should call the first argument, which closes the listen socket, at shutdown.
Example usage:
settings :: IO () ->Settings
settings shutdownAction =setInstallShutdownHandler
shutdownHandlerdefaultSettings
where shutdownHandler closeSocket = void $installHandler
sigTERM
(Catch
$ shutdownAction >> closeSocket)Nothing
Note that by default, the graceful shutdown mode lasts indefinitely
(see setGracefulShutdownTimeout
). If you install a signal handler as above,
upon receiving that signal, the custon shutdown action will run and all
outstanding requests will be handled.
You may instead prefer to do one or both of the following:
- Only wait a finite amount of time for outstanding requests to complete,
using
setGracefulShutdownTimeout
. - Only catch one signal, so the second hard-kills the Warp server, using
CatchOnce
.
Default: does not install any code.
Since 3.0.1
setServerName :: ByteString -> Settings -> Settings Source #
Default server name to be sent as the "Server:" header if an application does not set one. If an empty string is set, the "Server:" header is not sent. This is true even if an application set one.
Since 3.0.2
setMaximumBodyFlush :: Maybe Int -> Settings -> Settings Source #
The maximum number of bytes to flush from an unconsumed request body.
By default, Warp does not flush the request body so that, if a large body is
present, the connection is simply terminated instead of wasting time and
bandwidth on transmitting it. However, some clients do not deal with that
situation well. You can either change this setting to Nothing
to flush the
entire body in all cases, or in your application ensure that you always
consume the entire request body.
Default: 8192 bytes.
Since 3.0.3
setFork :: (((forall a. IO a -> IO a) -> IO ()) -> IO ()) -> Settings -> Settings Source #
Code to fork a new thread to accept a connection.
This may be useful if you need OS bound threads, or if you wish to develop an alternative threading model.
Default: void . forkIOWithUnmask
Since 3.0.4
setProxyProtocolNone :: Settings -> Settings Source #
Do not use the PROXY protocol.
Since 3.0.5
setProxyProtocolRequired :: Settings -> Settings Source #
Require PROXY header.
This is for cases where a "dumb" TCP/SSL proxy is being used, which cannot
add an X-Forwarded-For
HTTP header field but has enabled support for the
PROXY protocol.
See http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt and http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#proxy-protocol.
Only the human-readable header format (version 1) is supported. The binary header format (version 2) is not supported.
Since 3.0.5
setProxyProtocolOptional :: Settings -> Settings Source #
Use the PROXY header if it exists, but also accept
connections without the header. See setProxyProtocolRequired
.
WARNING: This is contrary to the PROXY protocol specification and using it can indicate a security problem with your architecture if the web server is directly accessable to the public, since it would allow easy IP address spoofing. However, it can be useful in some cases, such as if a load balancer health check uses regular HTTP without the PROXY header, but proxied connections do include the PROXY header.
Since 3.0.5
setSlowlorisSize :: Int -> Settings -> Settings Source #
Size in bytes read to prevent Slowloris attacks. Default value: 2048
Since 3.1.2
setHTTP2Disabled :: Settings -> Settings Source #
Disable HTTP2.
Since 3.1.7
:: (Request -> Status -> Maybe Integer -> IO ()) | request, status, maybe file-size |
-> Settings | |
-> Settings |
Setting a log function.
Since 3.X.X
Setting a log function for HTTP/2 server push.
Since: 3.2.7
setGracefulShutdownTimeout :: Maybe Int -> Settings -> Settings Source #
Set the graceful shutdown timeout. A timeout of Nothing
will
wait indefinitely, and a number, if provided, will be treated as seconds
to wait for requests to finish, before shutting down the server entirely.
Graceful shutdown mode is entered when the server socket is closed; see
setInstallShutdownHandler
for an example of how this could be done in
response to a UNIX signal.
Since 3.2.8
Getters
getHost :: Settings -> HostPreference Source #
Get the interface to bind to.
Since 2.1.1
getOnException :: Settings -> Maybe Request -> SomeException -> IO () Source #
Get the exception handler.
getGracefulShutdownTimeout :: Settings -> Maybe Int Source #
Get the graceful shutdown timeout
Since 3.2.8
Exception handler
defaultOnException :: Maybe Request -> SomeException -> IO () Source #
Printing an exception to standard error
if defaultShouldDisplayException
returns True
.
Since: 3.1.0
defaultShouldDisplayException :: SomeException -> Bool Source #
Apply the logic provided by defaultOnException
to determine if an
exception should be shown or not. The goal is to hide exceptions which occur
under the normal course of the web server running.
Since 2.1.3
Exception response handler
defaultOnExceptionResponse :: SomeException -> Response Source #
Sending 400 for bad requests. Sending 500 for internal server errors.
Since: 3.1.0
exceptionResponseForDebug :: SomeException -> Response Source #
Exception handler for the debugging purpose. 500, text/plain, a showed exception.
Since: 2.0.3.2
Data types
data HostPreference #
Which host to bind.
Note: The IsString
instance recognizes the following special values:
*
meansHostAny
- "any IPv4 or IPv6 hostname"*4
meansHostIPv4
- "any IPv4 or IPv6 hostname, IPv4 preferred"!4
meansHostIPv4Only
- "any IPv4 hostname"*6
meansHostIPv6
@ - "any IPv4 or IPv6 hostname, IPv6 preferred"!6
meansHostIPv6Only
- "any IPv6 hostname"
Note that the permissive *
values allow binding to an IPv4 or an
IPv6 hostname, which means you might be able to successfully bind
to a port more times than you expect (eg once on the IPv4 localhost
127.0.0.1 and again on the IPv6 localhost 0:0:0:0:0:0:0:1).
Any other value is treated as a hostname. As an example, to bind to the IPv4 local host only, use "127.0.0.1".
Instances
data InvalidRequest Source #
Error types for bad Request
.
NotEnoughLines [String] | |
BadFirstLine String | |
NonHttp | |
IncompleteHeaders | |
ConnectionClosedByPeer | |
OverLargeHeader | |
BadProxyHeader String |
Instances
Eq InvalidRequest Source # | |
Defined in Network.Wai.Handler.Warp.Types (==) :: InvalidRequest -> InvalidRequest -> Bool # (/=) :: InvalidRequest -> InvalidRequest -> Bool # | |
Show InvalidRequest Source # | |
Defined in Network.Wai.Handler.Warp.Types showsPrec :: Int -> InvalidRequest -> ShowS # show :: InvalidRequest -> String # showList :: [InvalidRequest] -> ShowS # | |
Exception InvalidRequest Source # | |
Defined in Network.Wai.Handler.Warp.Types |
Utilities
pauseTimeout :: Request -> IO () Source #
Explicitly pause the slowloris timeout.
This is useful for cases where you partially consume a request body. For more information, see https://github.com/yesodweb/wai/issues/351
Since 3.0.10
File information.
FileInfo | |
|
getFileInfo :: Request -> FilePath -> IO FileInfo Source #
Getting file information of the target file.
This function first uses a stat(2) or similar system call
to obtain information of the target file, then registers
it into the internal cache.
From the next time, the information is obtained
from the cache. This reduces the overhead to call the system call.
The internal cache is refreshed every duration specified by
setFileInfoCacheDuration
.
This function throws an IO
exception if the information is not
available. For instance, the target file does not exist.
If this function is used an a Request generated by a WAI
backend besides Warp, it also throws an IO
exception.
Since 3.1.10
withApplication :: IO Application -> (Port -> IO a) -> IO a Source #
Runs the given Application
on a free port. Passes the port to the given
operation and executes it, while the Application
is running. Shuts down the
server before returning.
Since: 3.2.4
withApplicationSettings :: Settings -> IO Application -> (Port -> IO a) -> IO a Source #
withApplication
with given Settings
. This will ignore the port value
set by setPort
in Settings
.
Since: 3.2.7
testWithApplication :: IO Application -> (Port -> IO a) -> IO a Source #
Same as withApplication
but with different exception handling: If the
given Application
throws an exception, testWithApplication
will re-throw
the exception to the calling thread, possibly interrupting the execution of
the given operation.
This is handy for running tests against an Application
over a real network
port. When running tests, it's useful to let exceptions thrown by your
Application
propagate to the main thread of the test-suite.
The exception handling makes this function unsuitable for use in production.
Use withApplication
instead.
Since: 3.2.4
testWithApplicationSettings :: Settings -> IO Application -> (Port -> IO a) -> IO a Source #
testWithApplication
with given Settings
.
Since: 3.2.7
openFreePort :: IO (Port, Socket) Source #
Opens a socket on a free port and returns both port and socket.
Since: 3.2.4
Version
warpVersion :: String Source #
The version of Warp.
HTTP/2
HTTP2 data
http2dataPushPromise :: HTTP2Data -> [PushPromise] Source #
Accessor for PushPromise
in HTTP2Data
.
Since: 3.2.7
defaultHTTP2Data :: HTTP2Data Source #
Default HTTP/2 specific data.
Since: 3.2.7
getHTTP2Data :: Request -> IO (Maybe HTTP2Data) Source #
Getting HTTP2Data
through vault of the request.
Warp uses this to receive HTTP2Data
from Middleware
.
Since: 3.2.7
setHTTP2Data :: Request -> Maybe HTTP2Data -> IO () Source #
Setting HTTP2Data
through vault of the request.
Application
or Middleware
should use this.
Since: 3.2.7
modifyHTTP2Data :: Request -> (Maybe HTTP2Data -> Maybe HTTP2Data) -> IO () Source #
Modifying HTTP2Data
through vault of the request.
Application
or Middleware
should use this.
Since: 3.2.8
Push promise
data PushPromise Source #
HTTP/2 push promise or sever push.
Since: 3.2.7
Instances
Eq PushPromise Source # | |
Defined in Network.Wai.Handler.Warp.HTTP2.Types (==) :: PushPromise -> PushPromise -> Bool # (/=) :: PushPromise -> PushPromise -> Bool # | |
Ord PushPromise Source # | |
Defined in Network.Wai.Handler.Warp.HTTP2.Types compare :: PushPromise -> PushPromise -> Ordering # (<) :: PushPromise -> PushPromise -> Bool # (<=) :: PushPromise -> PushPromise -> Bool # (>) :: PushPromise -> PushPromise -> Bool # (>=) :: PushPromise -> PushPromise -> Bool # max :: PushPromise -> PushPromise -> PushPromise # min :: PushPromise -> PushPromise -> PushPromise # | |
Show PushPromise Source # | |
Defined in Network.Wai.Handler.Warp.HTTP2.Types showsPrec :: Int -> PushPromise -> ShowS # show :: PushPromise -> String # showList :: [PushPromise] -> ShowS # |
promisedPath :: PushPromise -> ByteString Source #
Accessor for a URL path in PushPromise
.
E.g. "/style/default.css".
Since: 3.2.7
promisedFile :: PushPromise -> FilePath Source #
Accessor for FilePath
in PushPromise
.
E.g. "FILE_PATH/default.css".
Since: 3.2.7
promisedResponseHeaders :: PushPromise -> ResponseHeaders Source #
Accessor for ResponseHeaders
in PushPromise
"content-type" must be specified.
Default value: [].
Since: 3.2.7
promisedWeight :: PushPromise -> Weight Source #
Accessor for Weight
in PushPromise
.
Default value: 16.
Since: 3.2.7
defaultPushPromise :: PushPromise Source #
Default push promise.
Since: 3.2.7