@@ -1,89 +1,145 @@
1+{-# LANGUAGE BangPatterns #-}
12{-# LANGUAGE CPP #-}
23{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE PackageImports #-}
5+{-# LANGUAGE PatternGuards #-}
6+{-# LANGUAGE RecordWildCards #-}
37{-# LANGUAGE ScopedTypeVariables #-}
48{-# LANGUAGE TupleSections #-}
9+{-# LANGUAGE ViewPatterns #-}
510{-# OPTIONS_GHC -fno-warn-deprecations #-}
611
712module Network.Wai.Handler.Warp.Run where
813
14+import "iproute" Data.IP (toHostAddress, toHostAddress6)
915import Control.Arrow (first)
10−import Control.Concurrent (threadDelay, forkIOWithUnmask)
1116import qualified Control.Concurrent as Conc (yield)
1217import Control.Exception as E
13−import Control.Monad (forever, when, unless, void)
14−import Data.ByteString (ByteString)
1518import qualified Data.ByteString as S
19+import Data.Char (chr)
1620import Data.IORef (IORef, newIORef, readIORef, writeIORef)
1721import Data.Streaming.Network (bindPortTCP)
18−import Network (sClose, Socket)
19−import Network.Socket (accept, withSocketsDo, SockAddr)
22+import Foreign.C.Error (Errno(..), eCONNABORTED)
23+import GHC.IO.Exception (IOException(..))
24+import qualified Network.HTTP2 as H2
25+import Network.Socket (Socket, close, accept, withSocketsDo, SockAddr(SockAddrInet, SockAddrInet6), setSocketOption, SocketOption(..))
26+#if MIN_VERSION_network(3,1,1)
27+import Network.Socket (gracefulClose)
28+#endif
2029import qualified Network.Socket.ByteString as Sock
2130import Network.Wai
31+import Network.Wai.Internal (ResponseReceived (ResponseReceived))
32+import System.Environment (lookupEnv)
33+import qualified System.TimeManager as T
34+import System.Timeout (timeout)
35+
2236import Network.Wai.Handler.Warp.Buffer
37+import Network.Wai.Handler.Warp.Counter
2338import qualified Network.Wai.Handler.Warp.Date as D
2439import qualified Network.Wai.Handler.Warp.FdCache as F
40+import qualified Network.Wai.Handler.Warp.FileInfoCache as I
41+import Network.Wai.Handler.Warp.HTTP2 (http2)
42+import Network.Wai.Handler.Warp.HTTP2.Types (isHTTP2)
2543import Network.Wai.Handler.Warp.Header
44+import Network.Wai.Handler.Warp.Imports hiding (readInt)
45+import Network.Wai.Handler.Warp.ReadInt
2646import Network.Wai.Handler.Warp.Recv
2747import Network.Wai.Handler.Warp.Request
2848import Network.Wai.Handler.Warp.Response
2949import Network.Wai.Handler.Warp.SendFile
3050import Network.Wai.Handler.Warp.Settings
31−import qualified Network.Wai.Handler.Warp.Timeout as T
3251import Network.Wai.Handler.Warp.Types
33−import Network.Wai.Internal (ResponseReceived (ResponseReceived))
52+
3453
3554#if WINDOWS
3655import Network.Wai.Handler.Warp.Windows
3756#else
38−import System.Posix.IO (FdOption(CloseOnExec), setFdOption)
3957import Network.Socket (fdSocket)
4058#endif
4159
42−-- | Default action value for 'Connection'.
43−socketConnection :: Socket -> IO Connection
44−socketConnection s = do
45− readBuf <- allocateBuffer bufferSize
60+-- | Creating 'Connection' for plain HTTP based on a given socket.
61+socketConnection :: Settings -> Socket -> IO Connection
62+#if MIN_VERSION_network(3,1,1)
63+socketConnection set s = do
64+#else
65+socketConnection _ s = do
66+#endif
67+ bufferPool <- newBufferPool
4668 writeBuf <- allocateBuffer bufferSize
69+ let sendall = Sock.sendAll s
70+ isH2 <- newIORef False -- HTTP/1.x
4771 return Connection {
4872 connSendMany = Sock.sendMany s
49− , connSendAll = Sock.sendAll s
50− , connSendFile = defaultSendFile s
51− , connClose = sClose s >> freeBuffer readBuf >> freeBuffer writeBuf
52− , connRecv = receive s readBuf bufferSize
53− , connReadBuffer = readBuf
73+ , connSendAll = sendall
74+ , connSendFile = sendFile s writeBuf bufferSize sendall
75+#if MIN_VERSION_network(3,1,1)
76+ , connClose = do
77+ h2 <- readIORef isH2
78+ let tm = if h2 then settingsGracefulCloseTimeout2 set
79+ else settingsGracefulCloseTimeout1 set
80+ if tm == 0 then
81+ close s
82+ else
83+ gracefulClose s tm `E.catch` \(E.SomeException _) -> return ()
84+#else
85+ , connClose = close s
86+#endif
87+ , connFree = freeBuffer writeBuf
88+ , connRecv = receive s bufferPool
89+ , connRecvBuf = receiveBuf s
5490 , connWriteBuffer = writeBuf
5591 , connBufferSize = bufferSize
56− , connSendFileOverride = Override s
92+ , connHTTP2 = isH2
5793 }
5894
59−#if __GLASGOW_HASKELL__ < 702
60−allowInterrupt :: IO ()
61−allowInterrupt = unblock $ return ()
62−#endif
63−
64−-- | Run an 'Application' on the given port. This calls 'runSettings' with
65−-- 'defaultSettings'.
95+-- | Run an 'Application' on the given port.
96+-- This calls 'runSettings' with 'defaultSettings'.
6697run :: Port -> Application -> IO ()
6798run p = runSettings defaultSettings { settingsPort = p }
6899
100+-- | Run an 'Application' on the port present in the @PORT@
101+-- environment variable. Uses the 'Port' given when the variable is unset.
102+-- This calls 'runSettings' with 'defaultSettings'.
103+--
104+-- Since 3.0.9
105+runEnv :: Port -> Application -> IO ()
106+runEnv p app = do
107+ mp <- lookupEnv "PORT"
108+
109+ maybe (run p app) runReadPort mp
110+
111+ where
112+ runReadPort :: String -> IO ()
113+ runReadPort sp = case reads sp of
114+ ((p', _):_) -> run p' app
115+ _ -> fail $ "Invalid value in $PORT: " ++ sp
116+
69117-- | Run an 'Application' with the given 'Settings'.
118+-- This opens a listen socket on the port defined in 'Settings' and
119+-- calls 'runSettingsSocket'.
70120runSettings :: Settings -> Application -> IO ()
71121runSettings set app = withSocketsDo $
72122 bracket
73123 (bindPortTCP (settingsPort set) (settingsHost set))
74− sClose
124+ close
75125 (\socket -> do
76126 setSocketCloseOnExec socket
77127 runSettingsSocket set socket app)
78128
79−-- | Same as 'runSettings', but uses a user-supplied socket instead of opening
80−-- one. This allows the user to provide, for example, Unix named socket, which
129+-- | This installs a shutdown handler for the given socket and
130+-- calls 'runSettingsConnection' with the default connection setup action
131+-- which handles plain (non-cipher) HTTP.
132+-- When the listen socket in the second argument is closed, all live
133+-- connections are gracefully shut down.
134+--
135+-- The supplied socket can be a Unix named socket, which
81136-- can be used when reverse HTTP proxying into your application.
82137--
83138-- Note that the 'settingsPort' will still be passed to 'Application's via the
84139-- 'serverPort' record.
85140runSettingsSocket :: Settings -> Socket -> Application -> IO ()
86−runSettingsSocket set socket app =
141+runSettingsSocket set socket app = do
142+ settingsInstallShutdownHandler set closeListenSocket
87143 runSettingsConnection set getConn app
88144 where
89145 getConn = do
@@ -93,13 +149,20 @@ runSettingsSocket set socket app =
93149 (s, sa) <- accept socket
94150#endif
95151 setSocketCloseOnExec s
96− conn <- socketConnection s
152+ -- NoDelay causes an error for AF_UNIX.
153+ setSocketOption s NoDelay 1 `E.catch` \(E.SomeException _) -> return ()
154+ conn <- socketConnection set s
97155 return (conn, sa)
98156
99−-- | Allows you to provide a function which will return a 'Connection'. In
100−-- cases where creating the @Connection@ can be expensive, this allows the
101−-- expensive computations to be performed in a separate thread instead of the
102−-- main server loop.
157+ closeListenSocket = close socket
158+
159+-- | The connection setup action would be expensive. A good example
160+-- is initialization of TLS.
161+-- So, this converts the connection setup action to the connection maker
162+-- which will be executed after forking a new worker thread.
163+-- Then this calls 'runSettingsConnectionMaker' with the connection maker.
164+-- This allows the expensive computations to be performed
165+-- in a separate worker thread instead of the main server loop.
103166--
104167-- Since 1.3.5
105168runSettingsConnection :: Settings -> IO (Connection, SockAddr) -> Application -> IO ()
@@ -109,138 +172,281 @@ runSettingsConnection set getConn app = runSettingsConnectionMaker set getConnMa
109172 (conn, sa) <- getConn
110173 return (return conn, sa)
111174
175+-- | This modifies the connection maker so that it returns 'TCP' for 'Transport'
176+-- (i.e. plain HTTP) then calls 'runSettingsConnectionMakerSecure'.
112177runSettingsConnectionMaker :: Settings -> IO (IO Connection, SockAddr) -> Application -> IO ()
113178runSettingsConnectionMaker x y =
114− runSettingsConnectionMakerSecure x (go y)
179+ runSettingsConnectionMakerSecure x (toTCP <$> y)
115180 where
116− go = fmap (first (fmap (, False)))
181+ toTCP = first ((, TCP) <$>)
182+
183+----------------------------------------------------------------
117184
118−-- | Allows you to provide a function which will return a function
119−-- which will return 'Connection'.
185+-- | The core run function which takes 'Settings',
186+-- a connection maker and 'Application'.
187+-- The connection maker can return a connection of either plain HTTP
188+-- or HTTP over TLS.
120189--
121190-- Since 2.1.4
122−runSettingsConnectionMakerSecure :: Settings -> IO (IO (Connection, Bool), SockAddr) -> Application -> IO ()
191+runSettingsConnectionMakerSecure :: Settings -> IO (IO (Connection, Transport), SockAddr) -> Application -> IO ()
123192runSettingsConnectionMakerSecure set getConnMaker app = do
124193 settingsBeforeMainLoop set
194+ counter <- newCounter
195+ withII $ acceptConnection set getConnMaker app counter
196+ where
197+ withII action =
198+ withTimeoutManager $ \tm ->
199+ D.withDateCache $ \dc ->
200+ F.withFdCache fdCacheDurationInSeconds $ \fdc ->
201+ I.withFileInfoCache fdFileInfoDurationInSeconds $ \fic -> do
202+ let ii = InternalInfo tm dc fdc fic
203+ action ii
125204
126− -- Note that there is a thorough discussion of the exception safety of the
127− -- following code at: https://github.com/yesodweb/wai/issues/146
128− --
129− -- We need to make sure of two things:
130− --
131− -- 1. Asynchronous exceptions are not blocked entirely in the main loop.
132− -- Doing so would make it impossible to kill the Warp thread.
133− --
134− -- 2. Once a connection maker is received via getConnLoop, the connection
135− -- is guaranteed to be closed, even in the presence of async exceptions.
205+ !fdCacheDurationInSeconds = settingsFdCacheDuration set * 1000000
206+ !fdFileInfoDurationInSeconds = settingsFileInfoCacheDuration set * 1000000
207+ !timeoutInSeconds = settingsTimeout set * 1000000
208+ withTimeoutManager f = case settingsManager set of
209+ Just tm -> f tm
210+ Nothing -> bracket
211+ (T.initialize timeoutInSeconds)
212+ T.stopManager
213+ f
214+
215+-- Note that there is a thorough discussion of the exception safety of the
216+-- following code at: https://github.com/yesodweb/wai/issues/146
217+--
218+-- We need to make sure of two things:
219+--
220+-- 1. Asynchronous exceptions are not blocked entirely in the main loop.
221+-- Doing so would make it impossible to kill the Warp thread.
222+--
223+-- 2. Once a connection maker is received via acceptNewConnection, the
224+-- connection is guaranteed to be closed, even in the presence of
225+-- async exceptions.
226+--
227+-- Our approach is explained in the comments below.
228+acceptConnection :: Settings
229+ -> IO (IO (Connection, Transport), SockAddr)
230+ -> Application
231+ -> Counter
232+ -> InternalInfo
233+ -> IO ()
234+acceptConnection set getConnMaker app counter ii = do
235+ -- First mask all exceptions in acceptLoop. This is necessary to
236+ -- ensure that no async exception is throw between the call to
237+ -- acceptNewConnection and the registering of connClose.
136238 --
137− -- Our approach is explained in the comments below.
138−
139− -- First mask all exceptions in the main loop. This is necessary to ensure
140− -- that no async exception is throw between the call to getConnLoop and the
141− -- registering of connClose.
142− D.withDateCache $ \dc -> do
143− F.withFdCache (settingsFdCacheDuration set * 1000000) $ \fc -> do
144− withTimeoutManager $ \tm -> mask_ . forever $ do
239+ -- acceptLoop can be broken by closing the listing socket.
240+ void $ mask_ acceptLoop
241+ -- In some cases, we want to stop Warp here without graceful shutdown.
242+ -- So, async exceptions are allowed here.
243+ -- That's why `finally` is not used.
244+ gracefulShutdown set counter
245+ where
246+ acceptLoop = do
145247 -- Allow async exceptions before receiving the next connection maker.
146248 allowInterrupt
147249
148− -- getConnLoop will try to receive the next incoming request. It
149− -- returns a /connection maker/, not a connection, since in some
150− -- circumstances creating a working connection from a raw socket may be
151− -- an expensive operation, and this expensive work should not be
152− -- performed in the main event loop. An example of something expensive
153− -- would be TLS negotiation.
154− (mkConn, addr) <- getConnLoop
250+ -- acceptNewConnection will try to receive the next incoming
251+ -- request. It returns a /connection maker/, not a connection,
252+ -- since in some circumstances creating a working connection
253+ -- from a raw socket may be an expensive operation, and this
254+ -- expensive work should not be performed in the main event
255+ -- loop. An example of something expensive would be TLS
256+ -- negotiation.
257+ mx <- acceptNewConnection
258+ case mx of
259+ Nothing -> return ()
260+ Just (mkConn, addr) -> do
261+ fork set mkConn addr app counter ii
262+ acceptLoop
155263
156− -- Fork a new worker thread for this connection maker, and ask for a
157− -- function to unmask (i.e., allow async exceptions to be thrown).
264+ acceptNewConnection = do
265+ ex <- try getConnMaker
266+ case ex of
267+ Right x -> return $ Just x
268+ Left e -> do
269+ let eConnAborted = getErrno eCONNABORTED
270+ getErrno (Errno cInt) = cInt
271+ if ioe_errno e == Just eConnAborted
272+ then acceptNewConnection
273+ else do
274+ settingsOnException set Nothing $ toException e
275+ return Nothing
276+
277+-- Fork a new worker thread for this connection maker, and ask for a
278+-- function to unmask (i.e., allow async exceptions to be thrown).
279+fork :: Settings
280+ -> IO (Connection, Transport)
281+ -> SockAddr
282+ -> Application
283+ -> Counter
284+ -> InternalInfo
285+ -> IO ()
286+fork set mkConn addr app counter ii = settingsFork set $ \unmask ->
287+ -- Call the user-supplied on exception code if any
288+ -- exceptions are thrown.
289+ handle (settingsOnException set Nothing) $
290+ -- Run the connection maker to get a new connection, and ensure
291+ -- that the connection is closed. If the mkConn call throws an
292+ -- exception, we will leak the connection. If the mkConn call is
293+ -- vulnerable to attacks (e.g., Slowloris), we do nothing to
294+ -- protect the server. It is therefore vital that mkConn is well
295+ -- vetted.
158296 --
159− -- GHC 7.8 cannot infer the type of "void . forkIOWithUnmask"
160− void $ forkIOWithUnmask $ \unmask ->
161− -- Run the connection maker to get a new connection, and ensure
162− -- that the connection is closed. If the mkConn call throws an
163− -- exception, we will leak the connection. If the mkConn call is
164− -- vulnerable to attacks (e.g., Slowloris), we do nothing to
165− -- protect the server. It is therefore vital that mkConn is well
166− -- vetted.
167− --
168− -- We grab the connection before registering timeouts since the
169− -- timeouts will be useless during connection creation, due to the
170− -- fact that async exceptions are still masked.
171− bracket mkConn (connClose . fst) $ \(conn', isSecure') ->
172−
173− -- We need to register a timeout handler for this thread, and
174− -- cancel that handler as soon as we exit.
175− bracket (T.registerKillThread tm) T.cancel $ \th ->
176− let ii = InternalInfo th fc dc
177− conn = setSendFile conn' fc
178− -- We now have fully registered a connection close handler
179− -- in the case of all exceptions, so it is safe to one
180− -- again allow async exceptions.
181− in unmask .
182− -- Call the user-supplied on exception code if any
183− -- exceptions are thrown.
184− handle (onE Nothing) .
185−
186− -- Call the user-supplied code for connection open and close events
187− bracket (onOpen addr) (const $ onClose addr) $ \goingon ->
188−
189− -- Actually serve this connection.
190− -- onnClose above ensures the termination of the connection.
191− when goingon $ serveConnection conn ii addr isSecure' set app
297+ -- We grab the connection before registering timeouts since the
298+ -- timeouts will be useless during connection creation, due to the
299+ -- fact that async exceptions are still masked.
300+ bracket mkConn cleanUp (serve unmask)
192301 where
193− -- FIXME: only IOEception is caught. What about other exceptions?
194− getConnLoop = getConnMaker `E.catch` \(e :: IOException) -> do
195− onE Nothing (toException e)
196− -- "resource exhausted (Too many open files)" may happen by accept().
197− -- Wait a second hoping that resource will be available.
198− threadDelay 1000000
199− getConnLoop
200− onE mreq e =
201− case fromException e of
202− Just (NotEnoughLines []) -> return ()
203− _ -> settingsOnException set mreq e
204− onOpen = settingsOnOpen set
205− onClose = settingsOnClose set
206−
207− withTimeoutManager f =
208− case settingsManager set of
209− Nothing -> bracket
210− (T.initialize $ settingsTimeout set * 1000000)
211− T.stopManager
212− f
213− Just tm -> f tm
302+ cleanUp (conn, _) = connClose conn `finally` connFree conn
303+
304+ -- We need to register a timeout handler for this thread, and
305+ -- cancel that handler as soon as we exit.
306+ serve unmask (conn, transport) = bracket register cancel $ \th -> do
307+ -- We now have fully registered a connection close handler in
308+ -- the case of all exceptions, so it is safe to once again
309+ -- allow async exceptions.
310+ unmask .
311+ -- Call the user-supplied code for connection open and
312+ -- close events
313+ bracket (onOpen addr) (onClose addr) $ \goingon ->
314+ -- Actually serve this connection. bracket with closeConn
315+ -- above ensures the connection is closed.
316+ when goingon $ serveConnection conn ii th addr transport set app
317+ where
318+ register = T.registerKillThread (timeoutManager ii) (connClose conn)
319+ cancel = T.cancel
320+
321+ onOpen adr = increase counter >> settingsOnOpen set adr
322+ onClose adr _ = decrease counter >> settingsOnClose set adr
214323
215324serveConnection :: Connection
216325 -> InternalInfo
326+ -> T.Handle
217327 -> SockAddr
218− -> Bool -- ^ is secure?
328+ -> Transport
219329 -> Settings
220330 -> Application
221331 -> IO ()
222−serveConnection conn ii addr isSecure' settings app = do
332+serveConnection conn ii th origAddr transport settings app = do
333+ -- fixme: Upgrading to HTTP/2 should be supported.
334+ (h2,bs) <- if isHTTP2 transport then
335+ return (True, "")
336+ else do
337+ bs0 <- connRecv conn
338+ if S.length bs0 >= 4 && "PRI " `S.isPrefixOf` bs0 then
339+ return (True, bs0)
340+ else
341+ return (False, bs0)
223342 istatus <- newIORef False
224− src <- mkSource (connSource conn th istatus)
225− recvSendLoop istatus src `E.catch` \e -> do
226− sendErrorResponse istatus e
227− throwIO (e :: SomeException)
343+ if settingsHTTP2Enabled settings && h2 then do
344+ rawRecvN <- makeReceiveN bs (connRecv conn) (connRecvBuf conn)
345+ -- This thread becomes the sender in http2 library.
346+ -- In the case of event source, one request comes and one
347+ -- worker gets busy. But it is likely that the receiver does
348+ -- not receive any data at all while the sender is sending
349+ -- output data from the worker. It's not good enough to tickle
350+ -- the time handler in the receiver only. So, we should tickle
351+ -- the time handler in both the receiver and the sender.
352+ let recvN = wrappedRecvN th istatus (settingsSlowlorisSize settings) rawRecvN
353+ sendBS x = connSendAll conn x >> T.tickle th
354+ -- fixme: origAddr
355+ checkTLS
356+ setConnHTTP2 conn True
357+ http2 conn transport ii origAddr settings recvN sendBS app
358+ else do
359+ src <- mkSource (wrappedRecv conn th istatus (settingsSlowlorisSize settings))
360+ writeIORef istatus True
361+ leftoverSource src bs
362+ addr <- getProxyProtocolAddr src
363+ http1 True addr istatus src `E.catch` \e ->
364+ case () of
365+ ()
366+ -- See comment below referencing
367+ -- https://github.com/yesodweb/wai/issues/618
368+ | Just NoKeepAliveRequest <- fromException e -> return ()
369+ -- No valid request
370+ | Just (BadFirstLine _) <- fromException e -> return ()
371+ | otherwise -> do
372+ _ <- sendErrorResponse (dummyreq addr) istatus e
373+ throwIO e
228374
229375 where
230− th = threadHandle ii
376+ getProxyProtocolAddr src =
377+ case settingsProxyProtocol settings of
378+ ProxyProtocolNone ->
379+ return origAddr
380+ ProxyProtocolRequired -> do
381+ seg <- readSource src
382+ parseProxyProtocolHeader src seg
383+ ProxyProtocolOptional -> do
384+ seg <- readSource src
385+ if S.isPrefixOf "PROXY " seg
386+ then parseProxyProtocolHeader src seg
387+ else do leftoverSource src seg
388+ return origAddr
231389
232− sendErrorResponse istatus e = do
390+ parseProxyProtocolHeader src seg = do
391+ let (header,seg') = S.break (== 0x0d) seg -- 0x0d == CR
392+ maybeAddr = case S.split 0x20 header of -- 0x20 == space
393+ ["PROXY","TCP4",clientAddr,_,clientPort,_] ->
394+ case [x | (x, t) <- reads (decodeAscii clientAddr), null t] of
395+ [a] -> Just (SockAddrInet (readInt clientPort)
396+ (toHostAddress a))
397+ _ -> Nothing
398+ ["PROXY","TCP6",clientAddr,_,clientPort,_] ->
399+ case [x | (x, t) <- reads (decodeAscii clientAddr), null t] of
400+ [a] -> Just (SockAddrInet6 (readInt clientPort)
401+ 0
402+ (toHostAddress6 a)
403+ 0)
404+ _ -> Nothing
405+ ("PROXY":"UNKNOWN":_) ->
406+ Just origAddr
407+ _ ->
408+ Nothing
409+ case maybeAddr of
410+ Nothing -> throwIO (BadProxyHeader (decodeAscii header))
411+ Just a -> do leftoverSource src (S.drop 2 seg') -- drop CRLF
412+ return a
413+
414+ decodeAscii = map (chr . fromEnum) . S.unpack
415+
416+ shouldSendErrorResponse se
417+ | Just ConnectionClosedByPeer <- fromException se = False
418+ | otherwise = True
419+
420+ sendErrorResponse req istatus e = do
233421 status <- readIORef istatus
234− when status $ void $
235− sendResponse conn ii dummyreq defaultIndexRequestHeader (return S.empty) (errorResponse e)
422+ if shouldSendErrorResponse e && status
423+ then do
424+ sendResponse settings conn ii th req defaultIndexRequestHeader (return S.empty) (errorResponse e)
425+ else return False
236426
237− dummyreq = defaultRequest { remoteHost = addr }
427+ dummyreq addr = defaultRequest { remoteHost = addr }
238428
239429 errorResponse e = settingsOnExceptionResponse settings e
240430
241− recvSendLoop istatus fromClient = do
242− (req', idxhdr) <- recvRequest settings conn ii addr fromClient
243− let req = req' { isSecure = isSecure' }
431+ http1 firstRequest addr istatus src = do
432+ (req, mremainingRef, idxhdr, nextBodyFlush) <- recvRequest firstRequest settings conn ii th addr src transport
433+ keepAlive <- processRequest istatus src req mremainingRef idxhdr nextBodyFlush
434+ `E.catch` \e -> do
435+ settingsOnException settings (Just req) e
436+ -- Don't throw the error again to prevent calling settingsOnException twice.
437+ return False
438+
439+ -- When doing a keep-alive connection, the other side may just
440+ -- close the connection. We don't want to treat that as an
441+ -- exceptional situation, so we pass in False to http1 (which
442+ -- in turn passes in False to recvRequest), indicating that
443+ -- this is not the first request. If, when trying to read the
444+ -- request headers, no data is available, recvRequest will
445+ -- throw a NoKeepAliveRequest exception, which we catch here
446+ -- and ignore. See: https://github.com/yesodweb/wai/issues/618
447+ when keepAlive $ http1 False addr istatus src
448+
449+ processRequest istatus src req mremainingRef idxhdr nextBodyFlush = do
244450 -- Let the application run for as long as it wants
245451 T.pause th
246452
@@ -248,54 +454,146 @@ serveConnection conn ii addr isSecure' settings app = do
248454 -- creating the request, we need to make sure that we don't get
249455 -- an async exception before calling the ResponseSource.
250456 keepAliveRef <- newIORef $ error "keepAliveRef not filled"
251− _ <- app req $ \res -> do
457+ r <- E.try $ app req $ \res -> do
252458 T.resume th
253459 -- FIXME consider forcing evaluation of the res here to
254460 -- send more meaningful error messages to the user.
255461 -- However, it may affect performance.
256462 writeIORef istatus False
257− keepAlive <- sendResponse conn ii req idxhdr (readSource fromClient) res
463+ keepAlive <- sendResponse settings conn ii th req idxhdr (readSource src) res
258464 writeIORef keepAliveRef keepAlive
259465 return ResponseReceived
466+ case r of
467+ Right ResponseReceived -> return ()
468+ Left e@(SomeException _)
469+ | Just (ExceptionInsideResponseBody e') <- fromException e -> throwIO e'
470+ | otherwise -> do
471+ keepAlive <- sendErrorResponse req istatus e
472+ settingsOnException settings (Just req) e
473+ writeIORef keepAliveRef keepAlive
474+
260475 keepAlive <- readIORef keepAliveRef
261476
262477 -- We just send a Response and it takes a time to
263478 -- receive a Request again. If we immediately call recv,
264− -- it is likely to fail and the IO manager works.
265− -- It is very costy. So, we yield to another Haskell
266− -- thread hoping that the next Request will arraive
479+ -- it is likely to fail and cause the IO manager to do some work.
480+ -- It is very costly, so we yield to another Haskell
481+ -- thread hoping that the next Request will arrive
267482 -- when this Haskell thread will be re-scheduled.
268483 -- This improves performance at least when
269484 -- the number of cores is small.
270485 Conc.yield
271486
272− when keepAlive $ do
273− -- flush the rest of the request body
274− flushBody $ requestBody req
275− T.resume th
276− recvSendLoop istatus fromClient
487+ if keepAlive
488+ then
489+ -- If there is an unknown or large amount of data to still be read
490+ -- from the request body, simple drop this connection instead of
491+ -- reading it all in to satisfy a keep-alive request.
492+ case settingsMaximumBodyFlush settings of
493+ Nothing -> do
494+ flushEntireBody nextBodyFlush
495+ T.resume th
496+ return True
497+ Just maxToRead -> do
498+ let tryKeepAlive = do
499+ -- flush the rest of the request body
500+ isComplete <- flushBody nextBodyFlush maxToRead
501+ if isComplete then do
502+ T.resume th
503+ return True
504+ else
505+ return False
506+ case mremainingRef of
507+ Just ref -> do
508+ remaining <- readIORef ref
509+ if remaining <= maxToRead then
510+ tryKeepAlive
511+ else
512+ return False
513+ Nothing -> tryKeepAlive
514+ else
515+ return False
277516
278−flushBody :: IO ByteString -> IO ()
279−flushBody src =
517+ checkTLS = case transport of
518+ TCP -> return () -- direct
519+ tls -> unless (tls12orLater tls) $ goaway conn H2.InadequateSecurity "Weak TLS"
520+ tls12orLater tls = tlsMajorVersion tls == 3 && tlsMinorVersion tls >= 3
521+
522+-- connClose must not be called here since Run:fork calls it
523+goaway :: Connection -> H2.ErrorCodeId -> ByteString -> IO ()
524+goaway Connection{..} etype debugmsg = connSendAll bytestream
525+ where
526+ einfo = H2.encodeInfo id 0
527+ frame = H2.GoAwayFrame 0 etype debugmsg
528+ bytestream = H2.encodeFrame einfo frame
529+
530+flushEntireBody :: IO ByteString -> IO ()
531+flushEntireBody src =
280532 loop
281533 where
282534 loop = do
283535 bs <- src
284536 unless (S.null bs) loop
285537
286−connSource :: Connection -> T.Handle -> IORef Bool -> IO ByteString
287−connSource Connection { connRecv = recv } th istatus = do
538+flushBody :: IO ByteString -- ^ get next chunk
539+ -> Int -- ^ maximum to flush
540+ -> IO Bool -- ^ True == flushed the entire body, False == we didn't
541+flushBody src =
542+ loop
543+ where
544+ loop toRead = do
545+ bs <- src
546+ let toRead' = toRead - S.length bs
547+ case () of
548+ ()
549+ | S.null bs -> return True
550+ | toRead' >= 0 -> loop toRead'
551+ | otherwise -> return False
552+
553+wrappedRecv :: Connection -> T.Handle -> IORef Bool -> Int -> IO ByteString
554+wrappedRecv Connection { connRecv = recv } th istatus slowlorisSize = do
288555 bs <- recv
289556 unless (S.null bs) $ do
290557 writeIORef istatus True
291− when (S.length bs >= 2048) $ T.tickle th
558+ when (S.length bs >= slowlorisSize) $ T.tickle th
559+ return bs
560+
561+wrappedRecvN :: T.Handle -> IORef Bool -> Int -> (BufSize -> IO ByteString) -> (BufSize -> IO ByteString)
562+wrappedRecvN th istatus slowlorisSize readN bufsize = do
563+ bs <- readN bufsize
564+ unless (S.null bs) $ do
565+ writeIORef istatus True
566+ -- TODO: think about the slowloris protection in HTTP2: current code
567+ -- might open a slow-loris attack vector. Rather than timing we should
568+ -- consider limiting the per-client connections assuming that in HTTP2
569+ -- we should allow only few connections per host (real-world
570+ -- deployments with large NATs may be trickier).
571+ when (S.length bs >= slowlorisSize || bufsize <= slowlorisSize) $ T.tickle th
292572 return bs
293573
574+-- | Set flag FileCloseOnExec flag on a socket (on Unix)
575+--
294576-- Copied from: https://github.com/mzero/plush/blob/master/src/Plush/Server/Warp.hs
577+--
578+-- @since 3.2.17
295579setSocketCloseOnExec :: Socket -> IO ()
296580#if WINDOWS
297581setSocketCloseOnExec _ = return ()
298582#else
299−setSocketCloseOnExec socket =
300− setFdOption (fromIntegral $ fdSocket socket) CloseOnExec True
583+setSocketCloseOnExec socket = do
584+#if MIN_VERSION_network(3,0,0)
585+ fd <- fdSocket socket
586+#else
587+ let fd = fdSocket socket
588+#endif
589+ F.setFileCloseOnExec $ fromIntegral fd
301590#endif
591+
592+gracefulShutdown :: Settings -> Counter -> IO ()
593+gracefulShutdown set counter =
594+ case settingsGracefulShutdownTimeout set of
595+ Nothing ->
596+ waitForZero counter
597+ (Just seconds) ->
598+ void (timeout (seconds * microsPerSecond) (waitForZero counter))
599+ where microsPerSecond = 1000000