Network.Wai.Handler.Warp

warp-3.2.8: A fast, light-weight web server for WAI applications.

Safe Haskell | None
Language | Haskell98

Network.Wai.Handler.Warp

Contents

- Run a Warp server
- Settings
  - Setters
  - Getters
  - Exception handler
  - Exception response handler
- Data types
- Utilities
- Version
- HTTP/2
  - HTTP2 data
  - Push promise

Description

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
  - = NotEnoughLines [String]
  - | BadFirstLine String
  - | NonHttp
  - | IncompleteHeaders
  - | ConnectionClosedByPeer
  - | OverLargeHeader
  - | BadProxyHeader String
- pauseTimeout :: Request -> IO ()
- data FileInfo = FileInfo {
  - fileInfoName :: !FilePath
  - fileInfoSize :: !Integer
  - fileInfoTime :: HTTPDate
  - fileInfoDate :: ByteString
  }
- 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 () #

Run an `Application` on the given port. This calls `runSettings` with `defaultSettings`.

runEnv :: Port -> Application -> IO () #

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 () #

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 () #

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

data 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 #

The default settings for the Warp server. See the individual settings for the default value.

## Setters

setPort :: Port -> Settings -> Settings #

Port to listen on. Default value: 3000

Since 2.1.0

setHost :: HostPreference -> Settings -> Settings #

Interface to bind to. Default value: HostIPv4

Since 2.1.0

setOnException :: (Maybe Request -> SomeException -> IO ()) -> Settings -> Settings #

What to do with exceptions thrown by either the application or server. Default: `defaultOnException`

Since 2.1.0

setOnExceptionResponse :: (SomeException -> Response) -> Settings -> Settings #

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

setOnOpen :: (SockAddr -> IO Bool) -> Settings -> Settings #

What to do when a connection is opened. When `False` is returned, the connection is closed immediately. Otherwise, the connection is going on. Default: always returns `True`.

Since 2.1.0

setOnClose :: (SockAddr -> IO ()) -> Settings -> Settings #

What to do when a connection is closed. Default: do nothing.

Since 2.1.0

setTimeout :: Int -> Settings -> Settings #

Timeout value in seconds. Default value: 30

Since 2.1.0

setManager :: Manager -> Settings -> Settings #

Use an existing timeout manager instead of spawning a new one. If used, `settingsTimeout` is ignored.

Since 2.1.0

setFdCacheDuration :: Int -> Settings -> Settings #

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 #

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 #

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 #

Perform no parsing on the rawPathInfo.

This is useful for writing HTTP proxies.

Default: False

Since 2.1.0

setInstallShutdownHandler :: (IO () -> IO ()) -> Settings -> Settings #

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.

Default: does not install any code.

Since 3.0.1

setServerName :: ByteString -> Settings -> Settings #

Default server name if application does not set one.

Since 3.0.2

setMaximumBodyFlush :: Maybe Int -> Settings -> Settings #

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 #

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 #

Do not use the PROXY protocol.

Since 3.0.5

setProxyProtocolRequired :: Settings -> Settings #

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 #

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 #

Size in bytes read to prevent Slowloris protection. Default value: 2048

Since 3.1.2

setHTTP2Disabled :: Settings -> Settings #

Disable HTTP2.

Since 3.1.7

setLogger #

Arguments

:: (Request -> Status -> Maybe Integer -> IO ()) | request, status, maybe file-size
-> Settings |
-> Settings |

Setting a log function.

Since 3.X.X

setServerPushLogger #

Arguments

:: (Request -> ByteString -> Integer -> IO ()) | request, path, file-size
-> Settings |
-> Settings |

Setting a log function for HTTP/2 server push.

Since: 3.2.7

setGracefulShutdownTimeout :: Maybe Int -> Settings -> Settings #

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.

Since 3.2.8

## Getters

getPort :: Settings -> Port #

Get the listening port.

Since 2.1.1

getHost :: Settings -> HostPreference #

Get the interface to bind to.

Since 2.1.1

getOnOpen :: Settings -> SockAddr -> IO Bool #

Get the action on opening connection.

getOnClose :: Settings -> SockAddr -> IO () #

Get the action on closeing connection.

getOnException :: Settings -> Maybe Request -> SomeException -> IO () #

Get the exception handler.

getGracefulShutdownTimeout :: Settings -> Maybe Int #

Get the graceful shutdown timeout

Since 3.2.8

## Exception handler

defaultOnException :: Maybe Request -> SomeException -> IO () #

Printing an exception to standard error if `defaultShouldDisplayException` returns `True`.

Since: 3.1.0

defaultShouldDisplayException :: SomeException -> Bool #

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 #

Sending 400 for bad requests. Sending 500 for internal server errors.

Since: 3.1.0

exceptionResponseForDebug :: SomeException -> Response #

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:

- `*` means `HostAny` - "any IPv4 or IPv6 hostname"
- `*4` means `HostIPv4` - "any IPv4 or IPv6 hostname, IPv4 preferred"
- `!4` means `HostIPv4Only` - "any IPv4 hostname"
- `*6` means `HostIPv6`@ - "any IPv4 or IPv6 hostname, IPv6 preferred"
- `!6` means `HostIPv6Only` - "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

Eq HostPreference |
Methods (==) :: HostPreference -> HostPreference -> Bool # (/=) :: HostPreference -> HostPreference -> Bool #
Ord HostPreference |
Methods compare :: HostPreference -> HostPreference -> Ordering # (<) :: HostPreference -> HostPreference -> Bool # (<=) :: HostPreference -> HostPreference -> Bool # (>) :: HostPreference -> HostPreference -> Bool # (>=) :: HostPreference -> HostPreference -> Bool # max :: HostPreference -> HostPreference -> HostPreference # min :: HostPreference -> HostPreference -> HostPreference #
Read HostPreference |
Methods readsPrec :: Int -> ReadS HostPreference # readList :: ReadS [HostPreference] # readPrec :: ReadPrec HostPreference # readListPrec :: ReadPrec [HostPreference] #
Show HostPreference |
Methods showsPrec :: Int -> HostPreference -> ShowS # show :: HostPreference -> String # showList :: [HostPreference] -> ShowS #
IsString HostPreference |
Methods fromString :: String -> HostPreference #

type Port = Int #

TCP port number.

data InvalidRequest #

Error types for bad `Request`.

Constructors

NotEnoughLines [String] |
BadFirstLine String |
NonHttp |
IncompleteHeaders |
ConnectionClosedByPeer |
OverLargeHeader |
BadProxyHeader String |

Instances

Eq InvalidRequest # |
Methods (==) :: InvalidRequest -> InvalidRequest -> Bool # (/=) :: InvalidRequest -> InvalidRequest -> Bool #
Show InvalidRequest # |
Methods showsPrec :: Int -> InvalidRequest -> ShowS # show :: InvalidRequest -> String # showList :: [InvalidRequest] -> ShowS #
Exception InvalidRequest # |
Methods toException :: InvalidRequest -> SomeException # fromException :: SomeException -> Maybe InvalidRequest # displayException :: InvalidRequest -> String #

# Utilities

pauseTimeout :: Request -> IO () #

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

data FileInfo #

File information.

Constructors

FileInfo |
Fields fileInfoName :: !FilePath fileInfoSize :: !Integer fileInfoTime :: HTTPDate Modification time fileInfoDate :: ByteString Modification time in the GMT format

Instances

Eq FileInfo # |
Methods (==) :: FileInfo -> FileInfo -> Bool # (/=) :: FileInfo -> FileInfo -> Bool #
Show FileInfo # |
Methods showsPrec :: Int -> FileInfo -> ShowS # show :: FileInfo -> String # showList :: [FileInfo] -> ShowS #

getFileInfo :: Request -> FilePath -> IO FileInfo #

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 #

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 #

`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 #

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 #

`testWithApplication` with given `Settings`.

Since: 3.2.7

openFreePort :: IO (Port, Socket) #

Opens a socket on a free port and returns both port and socket.

Since: 3.2.4

# Version

warpVersion :: String #

The version of Warp.

# HTTP/2

## HTTP2 data

data HTTP2Data #

HTTP/2 specific data.

Since: 3.2.7

Instances

Eq HTTP2Data # |
Methods (==) :: HTTP2Data -> HTTP2Data -> Bool # (/=) :: HTTP2Data -> HTTP2Data -> Bool #
Show HTTP2Data # |
Methods showsPrec :: Int -> HTTP2Data -> ShowS # show :: HTTP2Data -> String # showList :: [HTTP2Data] -> ShowS #

http2dataPushPromise :: HTTP2Data -> [PushPromise] #

Accessor for `PushPromise` in `HTTP2Data`.

Since: 3.2.7

http2dataTrailers :: HTTP2Data -> ResponseHeaders #

defaultHTTP2Data :: HTTP2Data #

Default HTTP/2 specific data.

Since: 3.2.7

getHTTP2Data :: Request -> IO (Maybe HTTP2Data) #

Getting `HTTP2Data` through vault of the request. Warp uses this to receive `HTTP2Data` from `Middleware`.

Since: 3.2.7

setHTTP2Data :: Request -> Maybe HTTP2Data -> IO () #

Setting `HTTP2Data` through vault of the request. `Application` or `Middleware` should use this.

Since: 3.2.7

modifyHTTP2Data :: Request -> (Maybe HTTP2Data -> Maybe HTTP2Data) -> IO () #

Modifying `HTTP2Data` through vault of the request. `Application` or `Middleware` should use this.

Since: 3.2.8

## Push promise

data PushPromise #

HTTP/2 push promise or sever push.

Since: 3.2.7

Instances

Eq PushPromise # |
Methods (==) :: PushPromise -> PushPromise -> Bool # (/=) :: PushPromise -> PushPromise -> Bool #
Ord PushPromise # |
Methods 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 # |
Methods showsPrec :: Int -> PushPromise -> ShowS # show :: PushPromise -> String # showList :: [PushPromise] -> ShowS #

promisedPath :: PushPromise -> ByteString #

Accessor for a URL path in `PushPromise`. E.g. "/style/default.css".

Since: 3.2.7

promisedFile :: PushPromise -> FilePath #

Accessor for `FilePath` in `PushPromise`. E.g. "FILE_PATH/default.css".

Since: 3.2.7

promisedResponseHeaders :: PushPromise -> ResponseHeaders #

Accessor for `ResponseHeaders` in `PushPromise` "content-type" must be specified. Default value: [].

Since: 3.2.7

promisedWeight :: PushPromise -> Weight #

Accessor for `Weight` in `PushPromise`. Default value: 16.

Since: 3.2.7

defaultPushPromise :: PushPromise #

Default push promise.

Since: 3.2.7