@@ -35,6 +35,7 @@ import qualified Network.Wai.Handler.Warp.FdCache as F
3535import qualified Network.Wai.Handler.Warp.FileInfoCache as I
3636import Network.Wai.Handler.Warp.HTTP2 (http2, isHTTP2)
3737import Network.Wai.Handler.Warp.Header
38+import Network.Wai.Handler.Warp.IORef
3839import Network.Wai.Handler.Warp.ReadInt
3940import Network.Wai.Handler.Warp.Recv
4041import Network.Wai.Handler.Warp.Request
@@ -262,6 +263,10 @@ fork :: Settings
262263 -> InternalInfo0
263264 -> IO ()
264265fork set mkConn addr app counter ii0 = settingsFork set $ \ unmask ->
266+ -- Allocate a new IORef indicating whether the connection has been
267+ -- closed, to avoid double-freeing a connection
268+ withClosedRef $ \ref ->
269+
265270 -- Run the connection maker to get a new connection, and ensure
266271 -- that the connection is closed. If the mkConn call throws an
267272 -- exception, we will leak the connection. If the mkConn call is
@@ -272,11 +277,13 @@ fork set mkConn addr app counter ii0 = settingsFork set $ \ unmask ->
272277 -- We grab the connection before registering timeouts since the
273278 -- timeouts will be useless during connection creation, due to the
274279 -- fact that async exceptions are still masked.
275− bracket mkConn closeConn $ \(conn, transport) ->
280+ bracket mkConn (closeConn ref . fst) $ \(conn, transport) ->
276281
277282 -- We need to register a timeout handler for this thread, and
278− -- cancel that handler as soon as we exit.
279− bracket (T.registerKillThread (timeoutManager0 ii0)) T.cancel $ \th ->
283+ -- cancel that handler as soon as we exit. We additionally close
284+ -- the connection immediately in case the child thread catches the
285+ -- async exception or performs some long-running cleanup action.
286+ bracket (T.registerKillThread (timeoutManager0 ii0) (closeConn ref conn)) T.cancel $ \th ->
280287
281288 let ii1 = toInternalInfo1 ii0 th
282289 -- We now have fully registered a connection close handler
@@ -294,7 +301,11 @@ fork set mkConn addr app counter ii0 = settingsFork set $ \ unmask ->
294301 -- bracket with closeConn above ensures the connection is closed.
295302 when goingon $ serveConnection conn ii1 addr transport set app
296303 where
297− closeConn (conn, _transport) = connClose conn
304+ withClosedRef inner = newIORef False >>= inner
305+
306+ closeConn ref conn = do
307+ isClosed <- atomicModifyIORef' ref $ \x -> (True, x)
308+ unless isClosed $ connClose conn
298309
299310 onOpen adr = increase counter >> settingsOnOpen set adr
300311 onClose adr _ = decrease counter >> settingsOnClose set adr