Network.Wai.Handler.Warp

warp-3.2.3: 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

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
- getPort :: Settings -> Port
- getHost :: Settings -> HostPreference
- getOnOpen :: Settings -> SockAddr -> IO Bool
- getOnClose :: Settings -> SockAddr -> IO ()
- getOnException :: Settings -> Maybe Request -> SomeException -> IO ()
- 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
- warpVersion :: String

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

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 close 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 :: (Request -> Status -> Maybe Integer -> IO ()) -> Settings -> Settings

Setting a log function.

Since 3.X.X

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

## 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`
- `*4` means `HostIPv4`
- `!4` means `HostIPv4Only`
- `*6` means `HostIPv6`
- `!6` means `HostIPv6Only`

Any other values is treated as a hostname. As an example, to bind to the IPv4 local host only, use "127.0.0.1".

Instances

Eq HostPreference |
Ord HostPreference |
Read HostPreference |
Show HostPreference |
IsString 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 |
Show InvalidRequest |
Exception InvalidRequest |

# 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 |
Show FileInfo |

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

# Version

warpVersion :: String

The version of Warp.