packages feed

tls 2.6.3 → 2.6.4

raw patch · 14 files changed

+779/−153 lines, 14 filesPVP ok

version bump matches the API change (PVP)

API changes (from Hackage documentation)

+ Network.TLS: SendWith :: (forall g. () => ByteString -> STM g -> IO (Either g ())) -> SendWith
+ Network.TLS: byeWith :: MonadIO m => Context -> STM a -> m ()
+ Network.TLS: getBackendSendWith :: HasBackend a => a -> Maybe SendWith
+ Network.TLS: handshakeWith :: MonadIO m => Context -> STM a -> m (Either a ())
+ Network.TLS: newtype SendWith
+ Network.TLS: recvDataWith :: MonadIO m => Context -> STM a -> m (Either a ByteString)
+ Network.TLS: sendDataWith :: MonadIO m => Context -> ByteString -> STM a -> m (Either a ())

Files

CHANGELOG.md view
@@ -1,5 +1,14 @@ # Change log for "tls" +## Version 2.6.4++* An interrupted receive breaks the receive side and wakes PHA waiters.+  [#668](https://github.com/haskell-tls/hs-tls/pull/668)+* bye gives up on close_notify with the backend's SendWith.+  [#670](https://github.com/haskell-tls/hs-tls/pull/670)+* handshakeWith, recvDataWith, sendDataWith and byeWith give up on an STM action.+  [#672](https://github.com/haskell-tls/hs-tls/pull/672)+ ## Version 2.6.3  * Never wrap around the RTT of a ticket, and cap it at 10 seconds.
Network/TLS.hs view
@@ -29,12 +29,19 @@     closeNotifyReceived,     bye, +    -- * Giving up on an event+    handshakeWith,+    sendDataWith,+    recvDataWith,+    byeWith,+     -- * Exceptions     -- $exceptions      -- * Backend abstraction     HasBackend (..),     RecvWith (..),+    SendWith (..),     Backend (..),      -- * Parameters@@ -333,7 +340,12 @@ import Data.X509 (ExtKeyUsagePurpose (..), PrivKey (..), PubKey (..)) import Data.X509.Validation hiding (HostName, defaultHooks) -import Network.TLS.Backend (Backend (..), HasBackend (..), RecvWith (..))+import Network.TLS.Backend (+    Backend (..),+    HasBackend (..),+    RecvWith (..),+    SendWith (..),+ ) import Network.TLS.Cipher import Network.TLS.Compression (     Compression (..),
Network/TLS/Backend.hs view
@@ -15,6 +15,7 @@     HasBackend (..),     Backend (..),     RecvWith (..),+    SendWith (..), ) where  import Control.Concurrent.STM (STM)@@ -42,7 +43,8 @@     -- exceptions, including asynchronous ones, pass through as they are,     -- and 'Network.TLS.bye' can still send close_notify.  'Network.TLS.recvData'     -- may be called again only if the exception was thrown before any byte-    -- of a record was taken; otherwise the stream is left inside the record.+    -- of a record was taken.  Thrown inside the body of a record, it is+    -- thrown again by later receives (an asynchronous one as a TLS error).     }  -- | Types which a 'Network.TLS.Context' can be created on.@@ -60,6 +62,13 @@     getBackendRecvWith :: a -> Maybe RecvWith     getBackendRecvWith _ = Nothing +    -- | A send which can give up.  With it, 'Network.TLS.bye' gives up on+    --   close_notify when the peer does not read.+    --+    -- @since 2.6.4+    getBackendSendWith :: a -> Maybe SendWith+    getBackendSendWith _ = Nothing+ -- | A receive of the specified number of bytes which gives up once the --   'STM' action succeeds, answering what it gave as 'Left'.  Bytes --   already received by then are answered instead.@@ -67,6 +76,13 @@ -- @since 2.6.0 newtype RecvWith = RecvWith (forall g. Int -> STM g -> IO (Either g ByteString)) +-- | A send of all the bytes which gives up once the 'STM' action+--   succeeds, answering what it gave as 'Left'.  Part of the bytes may+--   have been sent by then.+--+-- @since 2.6.4+newtype SendWith = SendWith (forall g. ByteString -> STM g -> IO (Either g ()))+ instance HasBackend Backend where     initializeBackend _ = return ()     getBackend = id@@ -109,6 +125,7 @@                     Right bs                         | B.null bs -> done acc                         | otherwise -> loop (left - B.length bs) (bs : acc)+    getBackendSendWith sock = Just $ SendWith $ Network.sendAllWith sock #endif  instance HasBackend Handle where
Network/TLS/Context.hs view
@@ -74,6 +74,7 @@ ) where  import Control.Concurrent.MVar+import Control.Concurrent.STM import Control.Monad.State.Strict import Data.IORef import qualified Data.X509 as X509@@ -175,6 +176,9 @@     eof <- newIORef False     closeNotify <- newIORef False     txBroken <- newIORef Nothing+    rxBroken <- newIORef Nothing+    rxGiveUp <- newIORef Nothing+    txGiveUp <- newIORef Nothing     established <- newIORef NotEstablished     stats <- newIORef newMeasurement     needEmptyPacket <- newIORef False@@ -185,7 +189,7 @@     recvActionsRef <- newIORef []     appDataRef <- newIORef []     sendActionRef <- newIORef Nothing-    locks <- Locks <$> newMVar () <*> newMVar () <*> newMVar ()+    locks <- Locks <$> newTMVarIO () <*> newTMVarIO () <*> newTMVarIO ()     st13ref <- newIORef defaultTLS13State     mylimref <- newRecordLimitRef $ Just defaultRecordSizeLimit     peerlimref <- newRecordLimitRef $ Just defaultRecordSizeLimit@@ -203,6 +207,9 @@             Context                 { ctxBackend = getBackend backend                 , ctxBackendRecvWith = getBackendRecvWith backend+                , ctxBackendSendWith = getBackendSendWith backend+                , ctxRxGiveUp = rxGiveUp+                , ctxTxGiveUp = txGiveUp                 , ctxShared = shared                 , ctxSupported = supported                 , ctxDebug = debug@@ -217,6 +224,7 @@                 , ctxEOF_ = eof                 , ctxCloseNotify_ = closeNotify                 , ctxTxBroken_ = txBroken+                , ctxRxBroken_ = rxBroken                 , ctxEstablished_ = established                 , ctxNeedEmptyPacket = needEmptyPacket                 , ctxHooks = hooks
Network/TLS/Context/Internal.hs view
@@ -21,11 +21,17 @@     PendingRecvAction (..),     RecordLayer (..),     Locks (..),+    GiveUp (..),+    GaveUp (..),+    gaveUpSending,+    withRxGiveUp,+    withTxGiveUp,     RoleParams (..),     ctxEOF,     ctxCloseNotify,     ctxTxBroken,     ctxTxBrokenBy,+    ctxRxBrokenBy,     ctxEstablished,     withLog,     ctxWithHooks,@@ -33,6 +39,9 @@     setEOF,     setCloseNotify,     setTxBroken,+    setRxBroken,+    wakePHA,+    throwBroken,     setEstablished,     skipEarlyData,     contextFlush,@@ -43,10 +52,13 @@     updateMeasure,     withMeasure,     withReadLock,+    withReadLockGivingUp,     tryWithReadLock,     withWriteLock,+    withWriteLockGivingUp,     withStateLock,     withRWLock,+    withRWLockGivingUp,      -- * information     Information (..),@@ -97,6 +109,7 @@ ) where  import Control.Concurrent.MVar+import Control.Concurrent.STM import qualified Control.Exception as E import Control.Monad.State.Strict import Data.ByteArray (convert)@@ -133,6 +146,14 @@     -- ^ return the backend object associated with this context     , ctxBackendRecvWith :: Maybe RecvWith     -- ^ 'getBackendRecvWith' of the backend+    , ctxBackendSendWith :: Maybe SendWith+    -- ^ 'getBackendSendWith' of the backend+    , ctxRxGiveUp :: IORef (Maybe GiveUp)+    -- ^ what a receive through 'ctxBackendRecvWith' gives up on, set+    -- with the read lock taken+    , ctxTxGiveUp :: IORef (Maybe (STM ()))+    -- ^ what a send through 'ctxBackendSendWith' gives up on, set with+    -- the write lock taken     , ctxSupported :: Supported     , ctxShared :: Shared     , ctxDebug :: DebugParams@@ -145,6 +166,8 @@     , ctxTxBroken_ :: IORef (Maybe E.SomeException)     -- ^ the exception of the first failed send, which left the TX record     -- state ahead of the peer.+    , ctxRxBroken_ :: IORef (Maybe E.SomeException)+    -- ^ the exception which interrupted a receive inside a record.     , ctxEstablished_ :: IORef Established     -- ^ has the handshake been done and been successful.     , ctxTxRecordState :: MVar RecordState@@ -195,12 +218,46 @@     , doPostHandshakeAuthWith_ :: Context -> Handshake13R -> IO ()     } +-- | What a receive gives up on: before the first byte of a record, and+-- inside a record, which leaves the stream there.+data GiveUp = GiveUp+    { giveUpBetween :: STM ()+    , giveUpInside :: STM ()+    }++-- | Thrown by a receive which has given up before the first byte of a+-- record, and caught by the caller which set 'ctxRxGiveUp'.+data GaveUp = GaveUp deriving (Show)++instance E.Exception GaveUp++-- | Thrown by a send which has given up, which may have sent part of a+-- record.+gaveUpSending :: TLSException+gaveUpSending = PostHandshake $ Error_Misc "gave up sending"++-- | Running with a give-up for the receives; the read lock is taken.+withRxGiveUp :: Context -> GiveUp -> IO a -> IO a+withRxGiveUp ctx = withGiveUpIn (ctxRxGiveUp ctx)++-- | Running with a give-up for the sends; the write lock is taken.+withTxGiveUp :: Context -> STM () -> IO a -> IO a+withTxGiveUp ctx = withGiveUpIn (ctxTxGiveUp ctx)++withGiveUpIn :: IORef (Maybe b) -> b -> IO a -> IO a+withGiveUpIn ref g f =+    E.bracket+        (atomicModifyIORef' ref (\old -> (Just g, old)))+        (writeIORef ref)+        (const f)++-- | 'TMVar's, so that a wait for them can be given up on. data Locks = Locks-    { lockWrite :: MVar ()+    { lockWrite :: TMVar ()     -- ^ lock to use for writing data (including updating the state)-    , lockRead :: MVar ()+    , lockRead :: TMVar ()     -- ^ lock to use for reading data (including updating the state)-    , lockState :: MVar ()+    , lockState :: TMVar ()     -- ^ lock used during read/write when receiving and sending packet.     -- it is usually nested in a write or read lock.     }@@ -421,8 +478,13 @@         _ -> return Nothing  contextSend :: Context -> ByteString -> IO ()-contextSend c b =-    updateMeasure c (addBytesSent $ B.length b) >> (backendSend $ ctxBackend c) b+contextSend c b = do+    updateMeasure c (addBytesSent $ B.length b)+    mgiveUp <- readIORef $ ctxTxGiveUp c+    case (mgiveUp, ctxBackendSendWith c) of+        (Just giveUp, Just (SendWith sendWith)) ->+            sendWith b giveUp >>= either (\_ -> E.throwIO gaveUpSending) return+        _ -> backendSend (ctxBackend c) b  contextRecv :: Context -> Int -> IO ByteString contextRecv c sz = updateMeasure c (addBytesReceived sz) >> (backendRecv $ ctxBackend c) sz@@ -433,7 +495,11 @@ setEOF :: Context -> IO () setEOF ctx = do     writeIORef (ctxEOF_ ctx) True-    -- Wake up those waiting for a pending post-handshake authentication.+    wakePHA ctx++-- | Wake up those waiting for a pending post-handshake authentication.+wakePHA :: Context -> IO ()+wakePHA ctx = do     mpha <- tls13stPHA <$> readIORef (ctxTLS13State ctx)     forM_ mpha $ \(mv, err) -> void $ tryPutMVar mv $ PHAFailed err @@ -452,6 +518,22 @@ setTxBroken :: Context -> E.SomeException -> IO () setTxBroken ctx e = atomicModifyIORef' (ctxTxBroken_ ctx) $ \m -> (m <|> Just e, ()) +ctxRxBrokenBy :: Context -> IO (Maybe E.SomeException)+ctxRxBrokenBy ctx = readIORef $ ctxRxBroken_ ctx++-- | Throw again the exception which broke a direction.  An asynchronous+-- one was meant for the thread which got it, so it is replaced.+throwBroken :: String -> E.SomeException -> IO a+throwBroken msg e = E.throwIO $ case E.fromException e of+    Just (E.SomeAsyncException _) -> E.toException $ PostHandshake $ Error_Misc msg+    Nothing -> e++-- | The stream is left inside a record, so nothing more can be received.+setRxBroken :: Context -> E.SomeException -> IO ()+setRxBroken ctx e = do+    atomicModifyIORef' (ctxRxBroken_ ctx) $ \m -> (m <|> Just e, ())+    wakePHA ctx+ ctxEstablished :: Context -> IO Established ctxEstablished ctx = readIORef $ ctxEstablished_ ctx @@ -566,9 +648,23 @@ getStateRNG :: Context -> Int -> IO ByteString getStateRNG ctx n = usingState_ ctx $ genRandom n +withLock :: TMVar () -> IO a -> IO a+withLock lock = E.bracket_ (atomically $ takeTMVar lock) (atomically $ putTMVar lock ())++-- | Taking the lock unless the 'STM' action succeeds first.+withLockGivingUp :: TMVar () -> STM g -> IO a -> IO (Either g a)+withLockGivingUp lock giveUp f = E.mask $ \restore -> do+    r <- atomically $ (Right <$> takeTMVar lock) `orElse` (Left <$> giveUp)+    case r of+        Left g -> return $ Left g+        Right () -> (Right <$> restore f) `E.finally` atomically (putTMVar lock ())+ withReadLock :: Context -> IO a -> IO a-withReadLock ctx f = withMVar (lockRead $ ctxLocks ctx) (const f)+withReadLock ctx = withLock (lockRead $ ctxLocks ctx) +withReadLockGivingUp :: Context -> STM g -> IO a -> IO (Either g a)+withReadLockGivingUp ctx = withLockGivingUp (lockRead $ ctxLocks ctx)+ -- | Like 'withReadLock', but returns 'Nothing' immediately instead of waiting -- when another thread already holds the read lock. --@@ -581,22 +677,23 @@ -- is better than waiting for the current reader, which may hold the lock for -- arbitrarily long.  'bye' is the only such caller; see the note there. tryWithReadLock :: Context -> IO a -> IO (Maybe a)-tryWithReadLock ctx f = E.bracket acquire release $ \mlock -> case mlock of-    Nothing -> return Nothing-    Just _ -> Just <$> f-  where-    lock = lockRead $ ctxLocks ctx-    acquire = tryTakeMVar lock-    release = mapM_ (putMVar lock)+tryWithReadLock ctx f = either (const Nothing) Just <$> withReadLockGivingUp ctx (return ()) f  withWriteLock :: Context -> IO a -> IO a-withWriteLock ctx f = withMVar (lockWrite $ ctxLocks ctx) (const f)+withWriteLock ctx = withLock (lockWrite $ ctxLocks ctx) +withWriteLockGivingUp :: Context -> STM g -> IO a -> IO (Either g a)+withWriteLockGivingUp ctx = withLockGivingUp (lockWrite $ ctxLocks ctx)+ withRWLock :: Context -> IO a -> IO a withRWLock ctx f = withReadLock ctx $ withWriteLock ctx f +withRWLockGivingUp :: Context -> STM g -> IO a -> IO (Either g a)+withRWLockGivingUp ctx giveUp f =+    join <$> withReadLockGivingUp ctx giveUp (withWriteLockGivingUp ctx giveUp f)+ withStateLock :: Context -> IO a -> IO a-withStateLock ctx f = withMVar (lockState $ ctxLocks ctx) (const f)+withStateLock ctx = withLock (lockState $ ctxLocks ctx)  tls13orLater :: MonadIO m => Context -> m Bool tls13orLater ctx = do
Network/TLS/Core.hs view
@@ -11,7 +11,9 @@      -- * Initialisation and Termination of context     bye,+    byeWith,     handshake,+    handshakeWith,      -- * Application Layer Protocol Negotiation     getNegotiatedProtocol,@@ -21,7 +23,9 @@      -- * High level API     sendData,+    sendDataWith,     recvData,+    recvDataWith,     recvData',     closeNotifyReceived,     updateKey,@@ -41,13 +45,21 @@ import Data.IORef import GHC.IO.Exception (IOErrorType (..), IOException (..)) -import Network.TLS.Backend (Backend (..), RecvWith (..)) import Network.TLS.Context import Network.TLS.Context.Internal (+    GaveUp (..),+    GiveUp (..),     PHAResult (..),     ctxTxBroken,+    gaveUpSending,     incrementTLS13KeyUpdateCount,     resetTLS13KeyUpdateCount,+    wakePHA,+    withRWLockGivingUp,+    withReadLockGivingUp,+    withRxGiveUp,+    withTxGiveUp,+    withWriteLockGivingUp,  ) import Network.TLS.Extension import Network.TLS.Handshake@@ -79,52 +91,113 @@ -- This is to be called at the beginning of a connection, and during renegotiation. -- Don't use this function as the acquire resource of 'Control.Exception.bracket'. handshake :: MonadIO m => Context -> m ()-handshake ctx = do+handshake ctx = liftIO $ do     handshake_ ctx     -- Trying to receive an alert of client authentication failure-    liftIO $ do-        role <- usingState_ ctx getRole-        tls13 <- tls13orLater ctx-        sentClientCert <- tls13stSentClientCert <$> getTLS13State ctx-        when (role == ClientRole && tls13 && sentClientCert) $ do-            rtt <- getRTT ctx-            -- We are only willing to wait 'rtt' for the alert, but a receive-            -- must not be abandoned once it has started.  Records are read-            -- length-prefixed and the record layer keeps no receive buffer, so-            -- an aborted receive loses the bytes it has already taken off the-            -- transport and leaves the stream positioned inside a record.-            -- Every later read is then misframed, and the connection is dead-            -- with a spurious protocol error.-            ---            -- So the receive runs in its own thread and we stop waiting for it-            -- rather than interrupting it.  It holds the read lock, which keeps-            -- it the only reader and makes the next receive wait for it to-            -- finish; its outcome is left in 'tls13stPendingRecv' for that-            -- receive to pick up.-            done <- newEmptyTMVarIO-            void $ forkIO $ withReadLock ctx $ do-                r <- E.try $ recvData13 ctx-                modifyTLS13State ctx $ \st ->-                    st-                        { tls13stPendingRecv = case r of-                            Right dat -> PendingRecvData dat-                            Left err -> PendingRecvError err-                        }-                atomically $ putTMVar done ()-            late <- registerDelay rtt-            arrived <--                atomically $-                    (Just <$> takeTMVar done) `orElse` (Nothing <$ (readTVar late >>= check))-            -- Still report the authentication failure from 'handshake' itself-            -- whenever it did arrive in time.-            when (isJust arrived) $ do-                pending <- tls13stPendingRecv <$> getTLS13State ctx-                case pending of-                    PendingRecvError err -> do-                        modifyTLS13State ctx $ \st -> st{tls13stPendingRecv = NoPendingRecv}-                        E.throwIO err-                    _ -> return ()+    authFailureExpected ctx >>= \expected -> when expected $ waitAuthFailure ctx +-- | 'handshake' which gives up once the 'STM' action succeeds, also while+-- waiting for the locks or in a send.  After 'Left', the context cannot be+-- used.  With a backend which can neither give up on a receive nor on a+-- send, only the wait for the locks is given up on.+--+-- @since 2.6.4+handshakeWith :: MonadIO m => Context -> STM a -> m (Either a ())+handshakeWith ctx giveUp = liftIO $ do+    (giveUp', given) <- recording giveUp+    r <-+        E.try $+            withRWLockGivingUp ctx giveUp $+                withTxGiveUp ctx giveUp' $+                    withRxGiveUp ctx (GiveUp giveUp' giveUp') $+                        handshakeLocked ctx+    case r of+        Left e -> given >>= maybe (E.throwIO (e :: E.SomeException)) (return . Left)+        Right (Left a) -> return $ Left a+        Right (Right ()) -> do+            expected <- authFailureExpected ctx+            if not expected+                then return $ Right ()+                else case ctxBackendRecvWith ctx of+                    Nothing -> Right <$> waitAuthFailure ctx+                    Just _ -> waitAuthFailureGivingUp ctx giveUp' given++-- | Recording what the 'STM' action gave, for one which has given up.+recording :: STM a -> IO (STM (), IO (Maybe a))+recording giveUp = do+    var <- newTVarIO Nothing+    return (giveUp >>= writeTVar var . Just, readTVarIO var)++authFailureExpected :: Context -> IO Bool+authFailureExpected ctx = do+    role <- usingState_ ctx getRole+    tls13 <- tls13orLater ctx+    sentClientCert <- tls13stSentClientCert <$> getTLS13State ctx+    return $ role == ClientRole && tls13 && sentClientCert++-- | Waiting 'rtt' for an alert of client authentication failure.+waitAuthFailure :: Context -> IO ()+waitAuthFailure ctx = do+    rtt <- getRTT ctx+    -- We are only willing to wait 'rtt' for the alert, but a receive+    -- must not be abandoned once it has started.  Records are read+    -- length-prefixed and the record layer keeps no receive buffer, so+    -- an aborted receive loses the bytes it has already taken off the+    -- transport and leaves the stream positioned inside a record.+    -- Every later read is then misframed, and the connection is dead+    -- with a spurious protocol error.+    --+    -- So the receive runs in its own thread and we stop waiting for it+    -- rather than interrupting it.  It holds the read lock, which keeps+    -- it the only reader and makes the next receive wait for it to+    -- finish; its outcome is left in 'tls13stPendingRecv' for that+    -- receive to pick up.+    done <- newEmptyTMVarIO+    void $ forkIO $ withReadLock ctx $ do+        r <- E.try $ recvData13 ctx+        modifyTLS13State ctx $ \st ->+            st+                { tls13stPendingRecv = case r of+                    Right dat -> PendingRecvData dat+                    Left err -> PendingRecvError err+                }+        atomically $ putTMVar done ()+    late <- registerDelay rtt+    arrived <-+        atomically $+            (Just <$> takeTMVar done) `orElse` (Nothing <$ (readTVar late >>= check))+    -- Still report the authentication failure from 'handshake' itself+    -- whenever it did arrive in time.+    when (isJust arrived) $ do+        pending <- tls13stPendingRecv <$> getTLS13State ctx+        case pending of+            PendingRecvError err -> do+                modifyTLS13State ctx $ \st -> st{tls13stPendingRecv = NoPendingRecv}+                E.throwIO err+            _ -> return ()++-- | 'waitAuthFailure' with a backend which can give up: no thread, since+-- the receive gives up only before a record begins.  Once begun, only the+-- caller's give-up ends it, and the context cannot be used then.+waitAuthFailureGivingUp :: Context -> STM () -> IO (Maybe a) -> IO (Either a ())+waitAuthFailureGivingUp ctx giveUp given = do+    rtt <- getRTT ctx+    late <- registerDelay rtt+    let between = (readTVar late >>= check) `orElse` giveUp+    r <-+        withReadLockGivingUp ctx giveUp $+            withRxGiveUp ctx (GiveUp between giveUp) $+                E.try $+                    recvData13 ctx+    case r of+        Left () -> return $ Right ()+        Right (Right dat) -> do+            modifyTLS13State ctx $ \st -> st{tls13stPendingRecv = PendingRecvData dat}+            return $ Right ()+        Right (Left e)+            | isJust (E.fromException @GaveUp e) -> return $ Right ()+            | otherwise -> given >>= maybe (E.throwIO e) (return . Left)+ rttFactor :: Int rttFactor = 3 @@ -143,7 +216,8 @@ -- sending close_notify.  It should be called before closing the backend. -- This doesn't actually close the backend.  Nothing is sent after a failed -- handshake or a received alert, and a peer which has gone already is not--- an error.+-- an error.  With 'getBackendSendWith', close_notify is given up on when+-- the peer does not read it for a second or so. -- -- Proper usage is as follows: --@@ -158,7 +232,15 @@ -- >   handshake ctx -- >   ... bye :: MonadIO m => Context -> m ()-bye ctx = liftIO $ do+bye ctx = byeWith ctx (retry :: STM ())++-- | 'bye' which also gives up once the 'STM' action succeeds, on the+-- peer's last handshake messages and on close_notify alike.+--+-- @since 2.6.4+byeWith :: MonadIO m => Context -> STM a -> m ()+byeWith ctx giveUp0 = liftIO $ do+    let giveUp = void giveUp0     eof <- ctxEOF ctx     -- After a failed send, nothing is sent, so nothing is waited for either.     broken <- ctxTxBroken ctx@@ -167,13 +249,13 @@         role <- usingState_ ctx getRole         if role == ClientRole             then do-                withWriteLock ctx $ sendCFifNecessary ctx+                sending ctx giveUp $ sendCFifNecessary ctx                 -- receiving NewSessionTicket                 let chk = tls13stRecvNST <$> getTLS13State ctx                 recvNST <- chk                 unless recvNST $ do                     rtt <- getRTT ctx-                    tryRecvHS13 rtt chk+                    tryRecvHS13 giveUp rtt chk             else do                 -- receiving Client Finished                 let chk = tls13stRecvCF <$> getTLS13State ctx@@ -182,8 +264,8 @@                     -- no chance to measure RTT before receiving CF                     -- fixme: 1sec is good enough?                     let rtt = 1000000-                    tryRecvHS13 rtt chk-    bye_ ctx+                    tryRecvHS13 giveUp rtt chk+    bye_ ctx giveUp   where     -- Receiving these messages only improves the chances of a later session     -- resumption, so giving up on them costs nothing important.  We give up in@@ -204,52 +286,53 @@     --     -- A backend which can give up on a receive does so after 'rtt'; with     -- one which cannot, the messages are not waited for at all.-    tryRecvHS13 :: Int -> IO Bool -> IO ()-    tryRecvHS13 rtt chk = case ctxBackendRecvWith ctx of+    tryRecvHS13 :: STM () -> Int -> IO Bool -> IO ()+    tryRecvHS13 giveUp rtt chk = case ctxBackendRecvWith ctx of         Nothing -> return ()-        Just (RecvWith recvWith) -> do+        Just _ -> do             late <- registerDelay rtt-            let giveUp = readTVar late >>= check-                -- Bytes received before giving up are not the end of the stream.-                recv n = do-                    r <- recvWith n giveUp-                    expired <- readTVarIO late-                    case r of-                        Right bs | B.length bs == n || not expired -> return bs-                        _ -> E.throwIO GaveUpRecv-                ctx' = ctx{ctxBackend = (ctxBackend ctx){backendRecv = recv}}+            let g = (readTVar late >>= check) `orElse` giveUp             void $                 tryWithReadLock ctx $-                    recvHS13 ctx' chk `catchException` \e ->-                        -- Only an IOException means that the connection is gone-                        -- (see 'backendRecv'); otherwise close_notify is sent.-                        when (isJust (E.fromException @E.IOException e)) $-                            setEOF ctx---- | Thrown by a receive in 'bye' which has given up, and caught there.-data GaveUpRecv = GaveUpRecv deriving (Show)--instance E.Exception GaveUpRecv+                    withRxGiveUp ctx (GiveUp g g) $+                        recvHS13 ctx chk `catchException` \e ->+                            -- Only an IOException means that the connection is gone+                            -- (see 'backendRecv'); otherwise close_notify is sent.+                            when (isJust (E.fromException @E.IOException e)) $+                                setEOF ctx -bye_ :: MonadIO m => Context -> m ()-bye_ ctx = liftIO $ do+bye_ :: Context -> STM () -> IO ()+bye_ ctx giveUp = do     -- Although setEOF is always protected by the read lock, here we don't try     -- to wrap ctxEOF with it, so that function bye can still be called     -- concurrently to a blocked recvData.     eof <- ctxEOF ctx     broken <- ctxTxBroken ctx     tls13 <- tls13orLater ctx-    unless (eof || broken) $-        E.handleJust vanished return $-            withWriteLock ctx $+    -- No response to a post-handshake authentication is waited for.+    (`E.finally` wakePHA ctx) $+        unless (eof || broken) $+            sending ctx giveUp $                 if tls13                     then sendPacket13 ctx $ Alert13 [(AlertLevel_Warning, CloseNotify)]                     else sendPacket12 ctx $ Alert [(AlertLevel_Warning, CloseNotify)]++-- | A send of 'bye', with the write lock: given up on, as is the wait for+-- the lock, after a second or after 'rtt' if longer, or with the 'STM'+-- action.  With a backend which cannot give up on a send, it may block.+-- The peer may have closed the connection without close_notify: EPIPE or+-- ECONNRESET is then just the end of it.+sending :: Context -> STM () -> IO () -> IO ()+sending ctx giveUp send = E.handleJust ignorable return $ do+    rtt <- getRTT ctx+    late <- registerDelay $ max 1000000 rtt+    let g = (readTVar late >>= check) `orElse` giveUp+    void $ withWriteLockGivingUp ctx g $ withTxGiveUp ctx g send   where-    -- The peer may have closed the connection without close_notify:-    -- EPIPE or ECONNRESET is then just the end of it.-    vanished e-        | ioe_type e == ResourceVanished = Just ()+    ignorable :: E.SomeException -> Maybe ()+    ignorable e+        | Just ioe <- E.fromException e, ioe_type ioe == ResourceVanished = Just ()+        | Just e' <- E.fromException e, e' == gaveUpSending = Just ()         | otherwise = Nothing  -- | If the ALPN extension has been used, this will@@ -281,28 +364,59 @@ sendData _ "" = return () sendData ctx dataToSend = liftIO $ do     tls13 <- tls13orLater ctx-    let sendP bs-            | tls13 = do-                updateKeyBeforeLimit ctx-                sendPacket13 ctx $ AppData13 bs-                -- a KeyUpdate requested from now on is answered again-                modifyTLS13State ctx $ \st -> st{tls13stKeyUpdateResponded = False}-                role <- usingState_ ctx getRole-                sentCF <- tls13stSentCF <$> getTLS13State ctx-                rtt0 <- tls13st0RTT <$> getTLS13State ctx-                when (role == ClientRole && rtt0 && not sentCF) $-                    modifyTLS13State ctx $-                        \st -> st{tls13stPendingSentData = tls13stPendingSentData st . (bs :)}-            | otherwise = sendPacket12 ctx $ AppData bs     when tls13 $ withWriteLock ctx $ sendCFifNecessary ctx-    withWriteLock ctx $ do-        checkValid ctx-        -- All chunks are protected with the same write lock because we don't-        -- want to interleave writes from other threads in the middle of our-        -- possibly large write.-        mlen <- getPeerRecordLimit ctx -- plaintext, don't adjust for TLS 1.3-        mapM_ (mapChunks_ mlen sendP) (L.toChunks dataToSend)+    withWriteLock ctx $ sendDataLocked ctx tls13 dataToSend +-- | 'sendData' which gives up once the 'STM' action succeeds, also while+-- waiting for the write lock.  Given up on before anything is sent, the+-- context can still be used.  Given up on after that, part of the data+-- may have been sent, and how much is not known, so later sends throw.+-- With a backend which cannot give up on a send, only the wait for the+-- lock is given up on.+--+-- @since 2.6.4+sendDataWith :: MonadIO m => Context -> L.ByteString -> STM a -> m (Either a ())+sendDataWith _ "" _ = return $ Right ()+sendDataWith ctx dataToSend giveUp = liftIO $ do+    early <- atomically $ (Just <$> giveUp) `orElse` return Nothing+    case early of+        Just a -> return $ Left a+        Nothing -> do+            tls13 <- tls13orLater ctx+            (giveUp', given) <- recording giveUp+            withWriteLockGivingUp ctx giveUp (withTxGiveUp ctx giveUp' (send tls13))+                `E.catch` \e ->+                    if e == gaveUpSending+                        then given >>= maybe (E.throwIO e) (return . Left)+                        else E.throwIO e+  where+    send tls13 = do+        when tls13 $ sendCFifNecessary ctx+        sendDataLocked ctx tls13 dataToSend++sendDataLocked :: Context -> Bool -> L.ByteString -> IO ()+sendDataLocked ctx tls13 dataToSend = do+    checkValid ctx+    -- All chunks are protected with the same write lock because we don't+    -- want to interleave writes from other threads in the middle of our+    -- possibly large write.+    mlen <- getPeerRecordLimit ctx -- plaintext, don't adjust for TLS 1.3+    mapM_ (mapChunks_ mlen sendP) (L.toChunks dataToSend)+  where+    sendP bs+        | tls13 = do+            updateKeyBeforeLimit ctx+            sendPacket13 ctx $ AppData13 bs+            -- a KeyUpdate requested from now on is answered again+            modifyTLS13State ctx $ \st -> st{tls13stKeyUpdateResponded = False}+            role <- usingState_ ctx getRole+            sentCF <- tls13stSentCF <$> getTLS13State ctx+            rtt0 <- tls13st0RTT <$> getTLS13State ctx+            when (role == ClientRole && rtt0 && not sentCF) $+                modifyTLS13State ctx $+                    \st -> st{tls13stPendingSentData = tls13stPendingSentData st . (bs :)}+        | otherwise = sendPacket12 ctx $ AppData bs+ -- RFC 9846 Section 5.5: the keys are updated before the records sent -- under them reach the limit.  Early data cannot do so and stops there. updateKeyBeforeLimit :: Context -> IO ()@@ -349,6 +463,24 @@         -- will impact the validity of the context.         if tls13 then recvData13 ctx else recvData12 ctx +-- | 'recvData' which gives up once the 'STM' action succeeds, also while+-- waiting for the read lock.  It gives up only between records, and the+-- context can still be used then.  A record which has begun is read to+-- its end unless the 'STM' action succeeds meanwhile: then it throws, and+-- so do later receives.  With a backend which cannot give up on a+-- receive, only the wait for the lock is given up on.+--+-- @since 2.6.4+recvDataWith :: MonadIO m => Context -> STM a -> m (Either a ByteString)+recvDataWith ctx giveUp = liftIO $ do+    tls13 <- tls13orLater ctx+    (giveUp', given) <- recording giveUp+    fmap join $ withReadLockGivingUp ctx giveUp $ do+        checkValid ctx+        withRxGiveUp ctx (GiveUp giveUp' giveUp') $+            (Right <$> if tls13 then recvData13 ctx else recvData12 ctx)+                `E.catch` \GaveUp -> given >>= maybe (E.throwIO GaveUp) (return . Left)+ recvData12 :: Context -> IO ByteString recvData12 ctx = do     pending <- atomicModifyIORef' (ctxPendingAppData ctx) $ \xs -> ([], reverse xs)@@ -357,9 +489,9 @@         else return $ B.concat pending   where     process (Handshake [ch@ClientHello{}] [b]) =-        handshakeWith ctx (ch, b) >> recvData12 ctx+        renegotiate ctx (ch, b) >> recvData12 ctx     process (Handshake [hr@HelloRequest] [b]) =-        handshakeWith ctx (hr, b) >> recvData12 ctx+        renegotiate ctx (hr, b) >> recvData12 ctx     -- UserCanceled should be followed by a close_notify.     -- fixme: is it safe to call recvData12?     process (Alert [(AlertLevel_Warning, UserCanceled)]) = return B.empty@@ -650,7 +782,7 @@ -- the other side could have close the connection already, so wrap -- this in a try and ignore all exceptions tryBye :: Context -> IO ()-tryBye ctx = catchException (bye_ ctx) (\_ -> return ()) `E.finally` setEOF ctx+tryBye ctx = catchException (bye_ ctx retry) (\_ -> return ()) `E.finally` setEOF ctx  onError     :: Monad m
Network/TLS/Handshake.hs view
@@ -1,6 +1,7 @@ module Network.TLS.Handshake (     handshake_,-    handshakeWith,+    handshakeLocked,+    renegotiate,     handshakeClientWith,     handshakeServerWith,     handshakeClient,@@ -16,17 +17,18 @@ import Control.Monad.State.Strict  handshake_ :: MonadIO m => Context -> m ()-handshake_ ctx =-    liftIO $-        withRWLock ctx $-            handleException ctx (doHandshake_ (ctxRoleParams ctx) ctx)+handshake_ ctx = liftIO $ withRWLock ctx $ handshakeLocked ctx +-- | 'handshake_' with the read and write locks taken already.+handshakeLocked :: Context -> IO ()+handshakeLocked ctx = handleException ctx (doHandshake_ (ctxRoleParams ctx) ctx)+ -- Handshake when requested by the remote end -- This is called automatically by 'recvData', in a context where the read lock -- is already taken.  So contrary to 'handshake' above, here we only need to -- call withWriteLock.-handshakeWith :: MonadIO m => Context -> HandshakeR -> m ()-handshakeWith ctx hsr =+renegotiate :: MonadIO m => Context -> HandshakeR -> m ()+renegotiate ctx hsr =     liftIO $         withWriteLock ctx $             handleException ctx $
Network/TLS/PostHandshake.hs view
@@ -41,11 +41,11 @@ -- pending.  'Network.TLS.getClientCertificateChain' gives the authenticated chain. -- Server only. ----- The blocking wait ends with the response or with the end of the--- connection, e.g. a received alert or an 'Control.Exception.IOException'--- from the backend.  It waits as long as the client does not respond,--- and while 'Network.TLS.recvData' is stopped by another exception, so--- put a timeout on it if needed.+-- The blocking wait ends with the response, with the end of the+-- connection, e.g. a received alert, an 'Control.Exception.IOException'+-- from the backend or 'Network.TLS.bye', or with an exception inside a+-- record.  It waits as long as the client does not respond, and while+-- 'Network.TLS.recvData' is not called, so put a timeout on it if needed. requestCertificateAsync :: Context -> IO (Bool -> IO PHAResult) requestCertificateAsync ctx =     checkValid ctx >> doRequestCertificateAsync_ (ctxRoleParams ctx) ctx
Network/TLS/Record/Recv.hs view
@@ -1,15 +1,21 @@+{-# LANGUAGE TypeApplications #-}+ -- | TLS record layer in Rx direction module Network.TLS.Record.Recv (     recvRecord12,     recvRecord13, ) where +import Control.Concurrent.STM import qualified Control.Exception as E import qualified Data.ByteString as B+import Data.IORef +import Network.TLS.Backend import Network.TLS.Context.Internal import Network.TLS.Hooks import Network.TLS.Imports+import Network.TLS.Measurement import Network.TLS.Packet import Network.TLS.Record import Network.TLS.Struct@@ -51,7 +57,7 @@     -- ^ TLS context     -> IO (Either TLSError (Record Plaintext)) recvRecord12 ctx =-    readExactBytes ctx 5+    readExactBytes ctx False 5         >>= either (return . Left) (recvLengthE . (decodeHeader >=> checkType))   where     recvLengthE = either (return . Left) recvLength@@ -67,12 +73,12 @@         if exceedsTLSCiphertext 2048 readlen             then return $ Left maximumSizeExceeded             else-                readExactBytes ctx (fromIntegral readlen)+                readExactBytes ctx True (fromIntegral readlen)                     >>= either (return . Left) (getRecord ctx header)  recvRecord13 :: Context -> IO (Either TLSError (Record Plaintext)) recvRecord13 ctx =-    readExactBytes ctx 5+    readExactBytes ctx False 5         >>= either (return . Left) (recvLengthE . (decodeHeader >=> checkType))   where     recvLengthE = either (return . Left) recvLength@@ -89,7 +95,7 @@         if exceedsTLSCiphertext 256 readlen             then return $ Left maximumSizeExceeded             else-                readExactBytes ctx (fromIntegral readlen)+                readExactBytes ctx True (fromIntegral readlen)                     >>= either (return . Left) (getRecord13 header)     -- RFC 9846 Section 4.2.10: a server that rejected early data skips the     -- records it cannot deprotect, until the first one it can.@@ -130,11 +136,11 @@  ---------------------------------------------------------------- -readExactBytes :: Context -> Int -> IO (Either TLSError ByteString)-readExactBytes ctx sz = do-    -- A broken transport ends the connection, which also wakes up those-    -- waiting for a post-handshake authentication.-    hdrbs <- contextRecv ctx sz `E.catch` broken+readExactBytes :: Context -> Bool -> Int -> IO (Either TLSError ByteString)+readExactBytes ctx inRecord sz = do+    ctxRxBrokenBy ctx >>= mapM_ (throwBroken "a previous receive failed")+    mgiveUp <- readIORef $ ctxRxGiveUp ctx+    hdrbs <- recv mgiveUp `E.catch` broken     if B.length hdrbs == sz         then return $ Right hdrbs         else do@@ -150,5 +156,40 @@                                 ++ show (B.length hdrbs)                             )   where-    broken :: E.IOException -> IO a-    broken e = setEOF ctx >> E.throwIO e+    recv mgiveUp = case (mgiveUp, ctxBackendRecvWith ctx) of+        (Just giveUp, Just (RecvWith recvWith)) -> do+            updateMeasure ctx $ addBytesReceived sz+            let inside n = do+                    r <- recvWith n $ giveUpInside giveUp+                    gaveUp <- fired $ giveUpInside giveUp+                    case r of+                        Right bs | B.length bs == n || not gaveUp -> return bs+                        _ -> do+                            let e = PostHandshake $ Error_Misc "gave up inside a record"+                            setRxBroken ctx $ E.toException e+                            E.throwIO e+            if inRecord+                then inside sz+                else do+                    r <- recvWith sz $ giveUpBetween giveUp+                    case r of+                        Left () -> E.throwIO GaveUp+                        Right bs+                            | B.length bs == sz || B.null bs -> return bs+                            | otherwise -> do+                                -- Begun: the rest is given up on only inside.+                                gaveUp <- fired $ giveUpBetween giveUp+                                if gaveUp+                                    then (bs <>) <$> inside (sz - B.length bs)+                                    else return bs+        _ -> contextRecv ctx sz+    fired stm = atomically $ (True <$ stm) `orElse` return False+    -- A broken transport ends the connection.  Another exception inside a+    -- record leaves the stream there, so later receives fail at once.+    -- Both wake up those waiting for a post-handshake authentication.+    broken :: E.SomeException -> IO a+    broken e+        | isJust (E.fromException @E.IOException e) = setEOF ctx >> E.throwIO e+        | isJust (E.fromException @GaveUp e) = E.throwIO e+        | inRecord = setRxBroken ctx e >> E.throwIO e+        | otherwise = E.throwIO e
Network/TLS/Record/Send.hs view
@@ -61,11 +61,6 @@     -- The record state has advanced already, so a failed send leaves the     -- peer unable to decrypt any later record.  Later sends throw the same     -- exception, except an asynchronous one, which is not thrown again.-    ctxTxBrokenBy ctx >>= mapM_ (\e -> E.throwIO $ fromMaybe e $ asTLS e)+    ctxTxBrokenBy ctx >>= mapM_ (throwBroken "a previous send failed")     withLog ctx $ \logging -> loggingIOSent logging dataToSend     contextSend ctx dataToSend `E.catch` \e -> setTxBroken ctx e >> E.throwIO e-  where-    asTLS e = case E.fromException e of-        Just (E.SomeAsyncException _) ->-            Just $ E.toException $ PostHandshake $ Error_Misc "a previous send failed"-        Nothing -> Nothing
test/ByeSpec.hs view
@@ -79,6 +79,64 @@         pendingWith "needs network 3.2.12 or later" #endif +    it "gives up on a send over a socket" $ do+#if defined(mingw32_HOST_OS)+        -- The send does not wait for a reader there.+        pendingWith "Windows does not fill the send buffer"+#elif MIN_VERSION_network(3,2,12)+        (cs, ss) <- N.socketPair N.AF_UNIX N.Stream N.defaultProtocol+        case getBackendSendWith cs of+            Nothing -> expectationFailure "a socket should be able to give up"+            Just (SendWith sendWith) -> do+                -- Nobody reads, so the send buffer fills up.+                late <- registerDelay 100000+                sendWith (B.replicate 16000000 0) (readTVar late >>= check)+                    `shouldReturn` Left ()+        N.close cs+        N.close ss+#else+        pendingWith "needs network 3.2.12 or later"+#endif++    it "gives up on close_notify when the peer does not read" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        stuck <- newIORef False+        let noop = return ()+            -- a peer which no longer reads+            sendS bs = do+                s <- readIORef stuck+                if s then threadDelay maxBound else writePipeS pipe bs+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop sendS (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew (SendGivingUp sBackend $ sendWithVia stuck sendS) sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef stuck True+        timeout 5000000 (bye sCtx) `shouldReturn` Just ()+        -- The record may be partly sent, so nothing more is.+        r <- E.try @TLSException $ sendData sCtx "abc"+        r `shouldSatisfy` isLeft++    it "gives up on the answer to close_notify when the peer does not read" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        stuck <- newIORef False+        let noop = return ()+            sendS bs = do+                s <- readIORef stuck+                if s then threadDelay maxBound else writePipeS pipe bs+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop sendS (readPipeS pipe)+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew (SendGivingUp sBackend $ sendWithVia stuck sendS) sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef stuck True+        bye cCtx+        timeout 5000000 (recvData sCtx) `shouldReturn` Just mempty+     it "does not wait with a backend which cannot give up" $ do         (cParams, sParams) <- generate arbitraryPairParams13         pipe <- newPipe@@ -222,6 +280,75 @@         E.try (sendData sCtx "abc") `shouldReturn` Left (E.ErrorCall "broken")         E.try (sendData sCtx "abc") `shouldReturn` Left (E.ErrorCall "broken") +    it "throws the exception of a receive interrupted inside a record again" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        let noop = return ()+            -- only the body of a record, never its 5-byte header+            recvS n = do+                f <- readIORef failing+                when (f && n /= 5) $ E.throwIO $ E.ErrorCall "interrupted"+                readPipeS pipe n+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) recvS+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        sendData cCtx "abc"+        E.try (recvData sCtx) `shouldReturn` Left (E.ErrorCall "interrupted")+        writeIORef failing False+        sendData cCtx "def"+        timeout 1000000 (E.try (recvData sCtx))+            `shouldReturn` Just (Left (E.ErrorCall "interrupted"))+        -- close_notify can still be sent.+        bye sCtx+        timeout 1000000 (recvData cCtx) `shouldReturn` Just mempty++    it "does not throw an asynchronous exception of an interrupted receive again" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        let noop = return ()+            recvS n = do+                f <- readIORef failing+                when (f && n /= 5) $ E.throwIO E.ThreadKilled+                readPipeS pipe n+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) recvS+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        sendData cCtx "abc"+        E.try @E.AsyncException (recvData sCtx) `shouldReturn` Left E.ThreadKilled+        timeout 1000000 (E.try @TLSException (recvData sCtx))+            `shouldReturn` Just (Left (PostHandshake (Error_Misc "a previous receive failed")))++    it "keeps receiving after an exception before a record" $ do+        (cParams, sParams) <- generate arbitraryPairParams13+        pipe <- newPipe+        _ <- runPipe pipe+        failing <- newIORef False+        let noop = return ()+            -- e.g. a timeout while waiting for the next record+            recvS n = do+                f <- atomicModifyIORef' failing (\x -> (False, x))+                when f $ E.throwIO $ E.ErrorCall "timeout"+                readPipeS pipe n+            cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+            sBackend = Backend noop noop (writePipeS pipe) recvS+        cCtx <- contextNew cBackend cParams+        sCtx <- contextNew sBackend sParams+        concurrently_ (handshake cCtx) (handshake sCtx)+        writeIORef failing True+        E.try (recvData sCtx) `shouldReturn` Left (E.ErrorCall "timeout")+        sendData cCtx "abc"+        timeout 1000000 (recvData sCtx) `shouldReturn` Just "abc"+     it "does not wait after a failed send" $ do         (cParams, sParams) <- generate arbitraryPairParams13         pipe <- newPipe@@ -296,3 +423,17 @@     v <- newEmptyTMVarIO     _ <- forkIO $ rd n >>= atomically . putTMVar v     atomically $ (Right <$> takeTMVar v) `orElse` (Left <$> giveUp)++-- | A backend which can give up on a send.+data SendGivingUp = SendGivingUp Backend SendWith++instance HasBackend SendGivingUp where+    initializeBackend _ = return ()+    getBackend (SendGivingUp b _) = b+    getBackendSendWith (SendGivingUp _ f) = Just f++-- | Sending with the given send unless stuck, when only the give-up ends it.+sendWithVia :: IORef Bool -> (ByteString -> IO ()) -> SendWith+sendWithVia stuck snd' = SendWith $ \bs giveUp -> do+    s <- readIORef stuck+    if s then Left <$> atomically giveUp else Right <$> snd' bs
+ test/GiveUpSpec.hs view
@@ -0,0 +1,123 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module GiveUpSpec where++import Control.Concurrent.Async+import Control.Concurrent.STM+import qualified Control.Exception as E+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as L+import Data.Either (isLeft)+import GHC.Clock (getMonotonicTime)+import qualified Network.Socket as N+import qualified Network.Socket.ByteString as NB+import Network.TLS+import System.Timeout+import Test.Hspec+import Test.QuickCheck (generate)++import Arbitrary++spec :: Spec+spec = describe "giving up" $ do+#if MIN_VERSION_network(3,2,12)+    it "handshakeWith gives up on a silent server" $+        withSockets $ \(cs, _ss) -> do+            (cParams, _) <- generate arbitraryPairParams13+            cCtx <- contextNew cs cParams+            timeout 5000000 (handshakeWith cCtx =<< lateBy 50000)+                `shouldReturn` Just (Left ())++    it "handshakeWith and recvDataWith work as usual" $+        withPair $ \(cCtx, _) (sCtx, _) -> do+            sendData cCtx "abc"+            timeout 5000000 (recvDataWith sCtx (retry :: STM ())) `shouldReturn` Just (Right "abc")++    it "recvDataWith gives up between records, leaving the context usable" $+        withPair $ \(cCtx, _) (sCtx, _) -> do+            timeout 5000000 (recvDataWith sCtx =<< lateBy 50000) `shouldReturn` Just (Left ())+            sendData cCtx "abc"+            timeout 5000000 (recvData sCtx) `shouldReturn` Just "abc"++    it "recvDataWith throws when giving up inside a record" $+        withPair $ \(_, cs) (sCtx, _) -> do+            -- the first byte of a record, and no more+            NB.sendAll cs "\x17"+            r <- timeout 5000000 $ E.try @TLSException (recvDataWith sCtx =<< lateBy 50000)+            fmap isLeft r `shouldBe` Just True+            r' <- timeout 5000000 $ E.try @TLSException (recvData sCtx)+            fmap isLeft r' `shouldBe` Just True++    it "recvDataWith gives up waiting for another reader" $+        withPair $ \(cCtx, _) (sCtx, _) ->+            withAsync (recvData sCtx) $ \reader -> do+                waitReading+                timeout 5000000 (recvDataWith sCtx =<< lateBy 50000) `shouldReturn` Just (Left ())+                sendData cCtx "abc"+                timeout 5000000 (wait reader) `shouldReturn` Just "abc"++    it "sendDataWith gives up at once without sending" $+        withPair $ \(cCtx, _) (sCtx, _) -> do+            timeout 5000000 (sendDataWith sCtx "abc" (return ())) `shouldReturn` Just (Left ())+            timeout 5000000 (sendData sCtx "def") `shouldReturn` Just ()+            timeout 5000000 (recvData cCtx) `shouldReturn` Just "def"++#if !defined(mingw32_HOST_OS)+    it "sendDataWith gives up on a peer which does not read" $+        withPair $ \_ (sCtx, _) -> do+            timeout 5000000 (sendDataWith sCtx big =<< lateBy 100000)+                `shouldReturn` Just (Left ())+            r <- timeout 5000000 $ E.try @TLSException $ sendData sCtx "abc"+            fmap isLeft r `shouldBe` Just True++    it "sendDataWith gives up waiting for another writer" $+        withPair $ \_ (sCtx, _) ->+            withAsync (sendData sCtx big) $ \_ -> do+                waitReading+                timeout 5000000 (sendDataWith sCtx "abc" =<< lateBy 50000)+                    `shouldReturn` Just (Left ())++    it "byeWith gives up sooner than bye" $+        withPair $ \_ (sCtx, _) ->+            withAsync (sendData sCtx big) $ \_ -> do+                waitReading+                t0 <- getMonotonicTime+                timeout 5000000 (byeWith sCtx =<< lateBy 50000) `shouldReturn` Just ()+                t1 <- getMonotonicTime+                (t1 - t0) `shouldSatisfy` (< 0.5)+#endif+#else+    it "needs network 3.2.12 or later" $ pendingWith "network < 3.2.12"+#endif+  where+    big = L.fromStrict $ B.replicate 16000000 0+    -- letting the other thread start+    waitReading = timeout 100000 (atomically retry :: IO ()) >> return ()++-- | An 'STM' action which succeeds after the microseconds.+lateBy :: Int -> IO (STM ())+lateBy us = do+    late <- registerDelay us+    return $ readTVar late >>= check++withSockets :: ((N.Socket, N.Socket) -> IO a) -> IO a+withSockets =+    E.bracket+        (N.socketPair N.AF_UNIX N.Stream N.defaultProtocol)+        (\(cs, ss) -> N.close cs >> N.close ss)++-- | TLS 1.3 over a socket pair, the handshake done with 'handshakeWith'.+withPair :: ((Context, N.Socket) -> (Context, N.Socket) -> IO a) -> IO a+withPair body = withSockets $ \(cs, ss) -> do+    (cParams, sParams) <- generate arbitraryPairParams13+    cCtx <- contextNew cs cParams+    sCtx <- contextNew ss sParams+    r <-+        timeout 5000000 $+            concurrently+                (handshakeWith cCtx (retry :: STM ()))+                (handshakeWith sCtx (retry :: STM ()))+    r `shouldBe` Just (Right (), Right ())+    body (cCtx, cs) (sCtx, ss)
test/HandshakeSpec.hs view
@@ -310,6 +310,10 @@             post_handshake_auth_async_wait False         it "fails the waiter when the transport breaks" $             post_handshake_auth_async_reset+        it "fails the waiter when a receive is interrupted inside a record" $+            post_handshake_auth_async_interrupted+        it "fails the waiter when the server says bye" $+            post_handshake_auth_async_bye         it "closes the connection when a synchronous post-handshake auth fails" $             post_handshake_auth_sync_fail         it "commits the client certificate of a post-handshake auth at Finished" $@@ -3565,6 +3569,50 @@     writeIORef broken True     void (recvData sCtx) `shouldThrow` anyIOException     timeout 1000000 (check True) >>= (`shouldSatisfy` isFailed)+  where+    isFailed (Just (PHAFailed _)) = True+    isFailed _ = False++-- | A receive is interrupted by an exception inside a record while a+-- response is pending: the waiter fails instead of blocking forever.+post_handshake_auth_async_interrupted :: IO ()+post_handshake_auth_async_interrupted = do+    params <- generate arbitraryPairParams13+    cred <- generate arbitraryPHACredential+    let (cParams, sParams) = phaParams True cred params+    pipe <- newPipe+    _ <- runPipe pipe+    broken <- newIORef False+    let noop = return ()+        -- only the body of a record, never its 5-byte header+        sRecv n = do+            b <- readIORef broken+            if b && n /= 5 then E.throwIO (E.ErrorCall "interrupted") else readPipeS pipe n+        cBackend = Backend noop noop (writePipeC pipe) (readPipeC pipe)+        sBackend = Backend noop noop (writePipeS pipe) sRecv+    cCtx <- contextNew cBackend cParams+    sCtx <- contextNew sBackend sParams+    concurrently_ (handshake cCtx) (handshake sCtx)+    check <- requestCertificateAsync sCtx+    writeIORef broken True+    sendData cCtx "request"+    void (recvData sCtx) `shouldThrow` errorCall "interrupted"+    timeout 1000000 (check True) >>= (`shouldSatisfy` isFailed)+  where+    isFailed (Just (PHAFailed _)) = True+    isFailed _ = False++-- | The server says bye while a response is pending and nobody reads: the+-- waiter fails instead of blocking forever.+post_handshake_auth_async_bye :: IO ()+post_handshake_auth_async_bye = do+    params <- generate arbitraryPairParams13+    cred <- generate arbitraryPHACredential+    withPairContext (phaParams True cred params) $ \(cCtx, sCtx) -> do+        concurrently_ (handshake cCtx) (handshake sCtx)+        check <- requestCertificateAsync sCtx+        bye sCtx+        timeout 1000000 (check True) >>= (`shouldSatisfy` isFailed)   where     isFailed (Just (PHAFailed _)) = True     isFailed _ = False
tls.cabal view
@@ -1,6 +1,6 @@ cabal-version:      2.0 name:               tls-version:            2.6.3+version:            2.6.4 license:            BSD3 license-file:       LICENSE copyright:          Vincent Hanquez <vincent@snarc.org>@@ -213,6 +213,7 @@         ChannelBindingSpec         CiphersSpec         ECHSpec+        GiveUpSpec         EncodeSpec         HandshakeSpec         PipeChan