@@ -101,6 +101,7 @@ import qualified Data.IntSet as IntSet ( empty
101 , singleton
101 , singleton
105import Data.Map (Map)
106import Data.Map (Map)
106import qualified Data.Map as Map (empty)
107import qualified Data.Map as Map (empty)
@@ -1333,15 +1334,18 @@ handleIncomingMessages (ourEndPoint, theirEndPoint) = do
1333 putMVar mvar response
1334 putMVar mvar response
1335 -- Close a connection
1336 -- Close a connection
1337+ -- It is important that we verify that the connection is in fact open,
1338+ -- because otherwise we should not decrement the reference count
1336 closeConnection :: ConnectionId -> IO ()
1339 closeConnection :: ConnectionId -> IO ()
1337 closeConnection cid = do
1340 closeConnection cid = do
1338− -- TODO: we should check that this connection is in fact open
1339− writeChan ourChannel (ConnectionClosed cid)
1340− modifyMVar_ theirState $ \(RemoteEndPointValid vst) ->
1341+ modifyMVar_ theirState $ \(RemoteEndPointValid vst) -> do
1342+ unless (IntSet.member cid (vst ^. remoteIncoming)) $
1343+ throwIO $ userError "Invalid CloseConnection"
1341 return ( RemoteEndPointValid
1344 return ( RemoteEndPointValid
1342 . (remoteIncoming ^: IntSet.delete cid)
1345 . (remoteIncoming ^: IntSet.delete cid)
1348+ writeChan ourChannel (ConnectionClosed cid)
1345 closeIfUnused (ourEndPoint, theirEndPoint)
1349 closeIfUnused (ourEndPoint, theirEndPoint)
1347 -- Close the socket (if we don't have any outgoing connections)
1351 -- Close the socket (if we don't have any outgoing connections)
@@ -1382,7 +1386,9 @@ handleIncomingMessages (ourEndPoint, theirEndPoint) = do
1382 putMVar resolved ()
1386 putMVar resolved ()
1383 return True
1387 return True
1385− -- Read a message and output it on the endPoint's channel
1389+ -- Read a message and output it on the endPoint's channel By rights we
1390+ -- should verify that the connection ID is valid, but this is unnecessary
1386 readMessage :: N.Socket -> ConnectionId -> IO ()
1392 readMessage :: N.Socket -> ConnectionId -> IO ()
1387 readMessage sock connId =
1393 readMessage sock connId =
1388 recvWithLength sock >>= writeChan ourChannel . Received connId
1394 recvWithLength sock >>= writeChan ourChannel . Received connId