packages feed

quic 0.3.24 → 0.3.25

raw patch · 34 files changed

+1043/−285 lines, 34 filesdep ~cryptonPVP: major bump suggested

API removals or changes: PVP suggests a major version bump

Dependency ranges changed: crypton

API changes (from Hackage documentation)

- Network.QUIC.Internal: checkPeerClosedSTM :: Connection -> STM ()
- Network.QUIC.Internal: peerClosedSTM :: Connection -> STM a
+ Network.QUIC: waitAcceptableSTM :: Connection -> STM ()
+ Network.QUIC: waitFinishedSTM :: Connection -> STM a
+ Network.QUIC: waitReadableSTM :: Stream -> STM ()
+ Network.QUIC.Internal: [connAckElicitingSent] :: Connection -> TVar Bool
+ Network.QUIC.Internal: [connEnd] :: Connection -> TVar (Maybe SomeException)
+ Network.QUIC.Internal: ackElicitingSent :: Connection -> IO ()
+ Network.QUIC.Internal: appGracePeriod :: Int
+ Network.QUIC.Internal: checkConnectionEndSTM :: Connection -> STM ()
+ Network.QUIC.Internal: concurrentlyApp :: Connection -> IO a -> IO b -> IO (a, b)
+ Network.QUIC.Internal: connectionEndedSTM :: Connection -> STM ()
+ Network.QUIC.Internal: endReason :: SomeException -> SomeException
+ Network.QUIC.Internal: endedNormally :: SomeException
+ Network.QUIC.Internal: exitedNormally :: InternalControl -> IO ()
+ Network.QUIC.Internal: isConnectionEnded :: Connection -> IO Bool
+ Network.QUIC.Internal: readRecvQSTM :: RecvQ -> STM ReceivedPacket
+ Network.QUIC.Internal: recordingEnd :: Connection -> IO a -> IO a
+ Network.QUIC.Internal: runProtocolThreads :: [IO ()] -> IO ()
+ Network.QUIC.Internal: setConnectionEnd :: Connection -> SomeException -> IO ()
+ Network.QUIC.Internal: takeCryptoSTM :: Connection -> STM Crypto
+ Network.QUIC.Internal: waitAcceptableSTM :: Connection -> STM ()
+ Network.QUIC.Internal: waitEncryptionLevelSTM :: Connection -> EncryptionLevel -> STM ()
+ Network.QUIC.Internal: waitFinishedSTM :: Connection -> STM a
+ Network.QUIC.Internal: waitPeerCIDWithin :: Connection -> Microseconds -> IO (Maybe CIDInfo)
+ Network.QUIC.Internal: waitReadableSTM :: Stream -> STM ()
+ Network.QUIC.Internal: waitWithin :: Microseconds -> STM a -> IO (Maybe a)
- Network.QUIC.Internal: Connection :: ConnState -> DebugLogger -> QLogger -> Hooks -> ~Send -> ~Recv -> RecvQ -> DatagramQ -> IORef (Socket, TVar Bool) -> IORef [Socket] -> (CID -> StatelessResetToken) -> ThreadManager -> ThreadId -> Rate -> IORef RoleInfo -> IORef VersionInfo -> VersionInfo -> Parameters -> IORef CIDDB -> IORef Parameters -> TVar CIDDB -> IORef PeerInfo -> InputQ -> CryptoQ -> OutputQ -> Rate -> TVar Int -> Shared -> IORef Int -> IORef (IO ()) -> Array EncryptionLevel (IORef PacketNumber) -> Array EncryptionLevel (IORef IntSet) -> TVar StreamTable -> TVar (IntMap Departed) -> TVar Concurrency -> TVar Concurrency -> IORef Concurrency -> IORef Concurrency -> IORef OpenedStreams -> IORef OpenedStreams -> TVar TxFlow -> IORef RxFlow -> TVar MigrationState -> IORef Bool -> IORef Microseconds -> IORef Int -> IORef Int -> TVar Bool -> TVar Int -> TVar (Maybe SomeException) -> Array EncryptionLevel (TVar [ReceivedPacket]) -> IOArray EncryptionLevel Cipher -> IOArray EncryptionLevel Coder -> IOArray Bool Coder1RTT -> IOArray EncryptionLevel Protector -> IORef (Maybe (Coder, Protector)) -> IORef (Bool, PacketNumber) -> IORef Negotiated -> IORef AuthCIDs -> IORef AuthCIDs -> Buffer -> SizedBuffer -> Buffer -> IORef (IO ()) -> IORef Bool -> IORef Bool -> IORef Int -> IORef Int -> LDCC -> Connection
+ Network.QUIC.Internal: Connection :: ConnState -> DebugLogger -> QLogger -> Hooks -> ~Send -> ~Recv -> RecvQ -> DatagramQ -> IORef (Socket, TVar Bool) -> IORef [Socket] -> (CID -> StatelessResetToken) -> ThreadManager -> ThreadId -> Rate -> IORef RoleInfo -> IORef VersionInfo -> VersionInfo -> Parameters -> IORef CIDDB -> IORef Parameters -> TVar CIDDB -> IORef PeerInfo -> InputQ -> CryptoQ -> OutputQ -> Rate -> TVar Int -> Shared -> IORef Int -> IORef (IO ()) -> Array EncryptionLevel (IORef PacketNumber) -> Array EncryptionLevel (IORef IntSet) -> TVar StreamTable -> TVar (IntMap Departed) -> TVar Concurrency -> TVar Concurrency -> IORef Concurrency -> IORef Concurrency -> IORef OpenedStreams -> IORef OpenedStreams -> TVar TxFlow -> IORef RxFlow -> TVar MigrationState -> IORef Bool -> IORef Microseconds -> IORef Int -> IORef Int -> TVar Bool -> TVar Int -> TVar (Maybe SomeException) -> TVar (Maybe SomeException) -> TVar Bool -> Array EncryptionLevel (TVar [ReceivedPacket]) -> IOArray EncryptionLevel Cipher -> IOArray EncryptionLevel Coder -> IOArray Bool Coder1RTT -> IOArray EncryptionLevel Protector -> IORef (Maybe (Coder, Protector)) -> IORef (Bool, PacketNumber) -> IORef Negotiated -> IORef AuthCIDs -> IORef AuthCIDs -> Buffer -> SizedBuffer -> Buffer -> IORef (IO ()) -> IORef Bool -> IORef Bool -> IORef Int -> IORef Int -> LDCC -> Connection
- Network.QUIC.Internal: RecvStreamQ :: TQueue ByteString -> IORef (Maybe ByteString) -> IORef Bool -> RecvStreamQ
+ Network.QUIC.Internal: RecvStreamQ :: TQueue ByteString -> TVar (Maybe ByteString) -> TVar Bool -> RecvStreamQ
- Network.QUIC.Internal: [endOfStream] :: RecvStreamQ -> IORef Bool
+ Network.QUIC.Internal: [endOfStream] :: RecvStreamQ -> TVar Bool
- Network.QUIC.Internal: [pendingData] :: RecvStreamQ -> IORef (Maybe ByteString)
+ Network.QUIC.Internal: [pendingData] :: RecvStreamQ -> TVar (Maybe ByteString)
- Network.QUIC.Internal: ldccTimer :: LDCC -> IO ()
+ Network.QUIC.Internal: ldccTimer :: STM () -> LDCC -> IO ()
- Network.QUIC.Internal: resender :: LDCC -> IO ()
+ Network.QUIC.Internal: resender :: STM () -> LDCC -> IO ()
- Network.QUIC.Internal: type Recv = IO ReceivedPacket
+ Network.QUIC.Internal: type Recv = STM ReceivedPacket
- Network.QUIC.Internal: waitAntiAmplificationFree :: Connection -> PathInfo -> Int -> IO ()
+ Network.QUIC.Internal: waitAntiAmplificationFree :: Connection -> PathInfo -> Int -> IO Bool

Files

ChangeLog.md view
@@ -1,5 +1,40 @@ # ChangeLog +## 0.3.25++From the v0.3 branch: main goes on to 0.4, whose types change.  Fixes+#269, a client decrypting forged 0-RTT packets.  Adds+`waitAcceptableSTM`, `waitReadableSTM` and `waitFinishedSTM`.++* Give up waiting for a state once the connection is closed+  [#243](https://github.com/kazu-yamamoto/quic/pull/243)+* Wake what waits on the connection however it ends+  [#244](https://github.com/kazu-yamamoto/quic/pull/244)+* Leave the socket to the connection when the client reader goes idle+  [#245](https://github.com/kazu-yamamoto/quic/pull/245)+* Add waitAcceptableSTM and waitReadableSTM+  [#246](https://github.com/kazu-yamamoto/quic/pull/246)+* Give the application time to finish once the protocol threads fail+  [#247](https://github.com/kazu-yamamoto/quic/pull/247)+* Wait for deadlines in STM instead of System.Timeout+  [#248](https://github.com/kazu-yamamoto/quic/pull/248)+* Restart the idle timer on the first ack-eliciting packet sent+  [#249](https://github.com/kazu-yamamoto/quic/pull/249)+* Let the protocol threads return when the connection ends+  [#250](https://github.com/kazu-yamamoto/quic/pull/250)+* Keep transport parameter keys as the 62-bit integers they are+  [#251](https://github.com/kazu-yamamoto/quic/pull/251)+* Export waitFinishedSTM+  [#256](https://github.com/kazu-yamamoto/quic/pull/256)+* Take a refused send for loss (part of)+  [#263](https://github.com/kazu-yamamoto/quic/pull/263)+* Keep the client reader on receive errors (part of)+  [#265](https://github.com/kazu-yamamoto/quic/pull/265)+* Ask the protocol threads to end on the application's failure, rather than cancel them+  [#266](https://github.com/kazu-yamamoto/quic/pull/266)+* Drop a 0-RTT packet the client receives without decrypting it+  [#269](https://github.com/kazu-yamamoto/quic/issues/269)+ ## 0.3.24  `sendDatagram` throws `ConnectionIsClosed` for a DATAGRAM too large for a
Network/QUIC.hs view
@@ -28,6 +28,7 @@     stream,     unidirectionalStream,     acceptStream,+    waitAcceptableSTM,      -- ** Closing     closeStream,@@ -42,6 +43,7 @@      -- * IO     recvStream,+    waitReadableSTM,     resetReceived,     sendStream,     sendStreamMany,@@ -73,6 +75,7 @@     wait0RTTReady,     wait1RTTReady,     waitEstablished,+    waitFinishedSTM,      -- * Exceptions and Errors     QUICException (..),
Network/QUIC/Client/Reader.hs view
@@ -17,7 +17,7 @@ import qualified Data.ByteString as BS import Data.Functor (($>)) import Data.List (intersect)-import Network.Socket (Socket, getSocketName)+import Network.Socket (Socket, getSocketName, isClosedSocketError) import qualified Network.Socket.ByteString as NSB  import Network.QUIC.Common@@ -26,6 +26,7 @@ import Network.QUIC.Crypto import Network.QUIC.Exception import Network.QUIC.Imports+import Network.QUIC.Logger (bhow) import Network.QUIC.Packet import Network.QUIC.Parameters import Network.QUIC.Qlog@@ -34,7 +35,7 @@ import Network.QUIC.Types  -- What ended a wait in 'readerClient'.-data ReaderEnd = Retired | TimedOut+data ReaderEnd = Retired | Ended  -- | The reader of a client's socket.  It returns when the socket is --   retired, which is how 'rebind' ends the reader of the socket it@@ -80,28 +81,34 @@             yield             wait     loop recv = do-        mito <- getIdleTimeout conn-        expired <- case mito of-            Nothing -> newTVarIO False-            Just (Microseconds ito) -> registerDelay ito         ebs <--            recv $-                ((readTVar retired >>= STM.check) $> Retired)-                    `orElse` ((readTVar expired >>= STM.check) $> TimedOut)+            recvAgain $+                recv $+                    ((readTVar retired >>= STM.check) $> Retired)+                        `orElse` (connectionEndedSTM conn $> Ended)         case ebs of             -- 'leave' has it.             Left Retired -> return ()-            -- What ends the connection on an idle timeout is the-            -- receiver throwing 'ConnectionIsTimeout'; this thread only-            -- stops reading.  The socket goes the same way as a retired-            -- one, because the sender may be inside a send on it.-            Left TimedOut -> retireSocket conn s0+            -- The connection has ended, on an idle timeout or otherwise;+            -- the closer reads for itself.  The socket is still the+            -- connection's, and 'leave' leaves it to the closer.  On the+            -- retired list, the sender closed it before the receiver had+            -- timed out and sent on it closed, so the connection ended+            -- with EBADF instead.+            Left Ended -> return ()             Right bs -> do                 now <- getTimeMicrosecond                 let quicBit = greaseQuicBit $ getMyParameters conn                 pkts <- decodePackets bs (not quicBit)                 mapM_ (putQ now) pkts                 loop recv+    -- An error such as ECONNREFUSED, from an ICMP message on a connected+    -- socket, used to end the reader and leave the connection deaf until+    -- its idle timeout.  A socket closed under the receive is not retried.+    recvAgain rcv = rcv `E.catch` \e ->+        if isClosedSocketError e+            then E.throwIO e+            else logAction ("recv again: " <> bhow e) >> recvAgain rcv     logAction msg = connDebugLog conn ("debug: readerClient: " <> msg)     putQ _ (PacketIB BrokenPacket _) = return ()     putQ t (PacketIV pkt@(VersionNegotiationPacket dCID sCID peerVers)) = do@@ -177,8 +184,8 @@     let ok = calculateIntegrityTag ver remoteCID pseudo0 == tag     return (dCID == localCID && ok) -recvClient :: RecvQ -> IO ReceivedPacket-recvClient = readRecvQ+recvClient :: RecvQ -> STM ReceivedPacket+recvClient = readRecvQSTM  ---------------------------------------------------------------- @@ -231,7 +238,7 @@ -- Co -> Sn: RetireConnectionID(So) -- Cn <- Sn: NewConnectionID (receiver) controlConnection' conn ChangeServerCID = do-    mn <- timeout (Microseconds 1000000) "controlConnection' 1" $ waitPeerCID conn -- fixme+    mn <- waitPeerCIDWithin conn (Microseconds 1000000) -- fixme     case mn of         Nothing -> return False         Just cidInfo -> do@@ -275,7 +282,7 @@ -- Cn <- Sn: PathResponse (processFrame) controlConnection' conn ActiveMigration = do     -- Changing peer CID-    mn <- timeout (Microseconds 1000000) "controlConnection' 2" $ waitPeerCID conn -- fixme+    mn <- waitPeerCIDWithin conn (Microseconds 1000000) -- fixme     case mn of         Nothing -> return False         mcidinfo -> do
Network/QUIC/Client/Run.hs view
@@ -7,7 +7,6 @@     migrate, ) where -import Control.Concurrent.Async import Control.Concurrent.STM import qualified Control.Exception as E import qualified Network.Socket as NS@@ -100,25 +99,23 @@                 mainDone conn                 return r             ldcc = connLDCC conn-        let s1 = labelMe "handshaker" >> handshaker-            s2 = labelMe "sender" >> sender conn-            s3 = labelMe "receiver" >> receiver conn-            s4 = labelMe "resender" >> resender ldcc-            s5 = labelMe "ldccTimer" >> ldccTimer ldcc+        let rec = recordingEnd conn+            s1 = labelMe "handshaker" >> rec handshaker+            s2 = labelMe "sender" >> rec (sender conn)+            s3 = labelMe "receiver" >> rec (receiver conn)+            s4 = labelMe "resender" >> rec (resender ended ldcc)+            s5 = labelMe "ldccTimer" >> rec (ldccTimer ended ldcc)             s6 = labelMe "QUIC client" >> client-            c1 = labelMe "concurrently1" >> concurrently_ s1 s2-            c2 = labelMe "concurrently2" >> concurrently_ c1 s3-            c3 = labelMe "concurrently3" >> concurrently_ c2 s4-            c4 = labelMe "concurrently4" >> concurrently_ c3 s5-            c4' = labelMe "concurrently4'" >> concurrently_ c4 s7-            s7 = labelMe "abort watcher" >> watchAbortRequest conn+            s7 = labelMe "abort watcher" >> rec (watchAbortRequest conn)+            ended = connectionEndedSTM conn+            protocol = runProtocolThreads [s1, s2, s3, s4, s5, s7]             c5 =                 labelMe "concurrently5"-                    >> concurrently (c4' `E.catches` handlers) s6+                    >> concurrentlyApp conn (protocol `E.catches` handlers) s6             -- A peer closing with NO_ERROR leaves the application to finish:             -- what waits on the peer gives up with 'ConnectionIsClosed'.             handlers =-                [ E.Handler $ \(_ :: InternalControl) -> return ()+                [ E.Handler exitedNormally                 , E.Handler $ \e -> case e of                     ConnectionIsClosed _ -> return ()                     _ -> E.throwIO e@@ -126,6 +123,7 @@             runThreads = snd <$> c5         when (ccWatchDog conf) $ forkManaged conn "QUIC watchDog" $ watchDog (void $ migrate conn)         ex <- E.try runThreads >>= abortRequested conn+        setConnectionEnd conn $ either id (const endedNormally) ex         sendFinal conn         setConnectionClosed conn         closure conn ldcc ex
Network/QUIC/Closer.hs view
@@ -106,9 +106,12 @@         let (recvWithin, clos) = case mrecvbuf of                 Nothing ->                     -- The server reads its datagrams from a queue, not from-                    -- a socket, and a timeout does reach a thread waiting-                    -- on one.-                    ( \tmo -> isJust <$> timeout tmo "closer" (void $ connRecv conn)+                    -- a socket: the deadline is waited for beside it.+                    ( \(Microseconds us) -> do+                        expired <- registerDelay us+                        atomically $+                            (True <$ connRecv conn)+                                `orElse` (False <$ (readTVar expired >>= check))                     , return ()                     )                 Just recvbuf ->@@ -147,8 +150,9 @@         -- stopping lets go of its sockets as soon as its connections have         -- ended, and a CONNECTION_CLOSE still waiting its turn on a thread         -- of its own misses them.  The closer repeats it for a peer that-        -- did not hear it, which is what it is for.-        send+        -- did not hear it, which is what it is for.  It failing would+        -- replace why the connection ended, and leak what is freed below.+        sendOrLose conn send         writeIORef (connCloserOwnsSocket conn) True         void $ forkFinally (closer conn pto send recvWithin hook) $ \e -> do             case e of
Network/QUIC/Connection/Crypto.hs view
@@ -4,6 +4,7 @@ module Network.QUIC.Connection.Crypto (     setEncryptionLevel,     waitEncryptionLevel,+    waitEncryptionLevelSTM,     putOffCrypto,     --     getCipher,@@ -58,7 +59,10 @@     atomically $ modifyTVar' (pendingQ ! lvl) (rpkt :)  waitEncryptionLevel :: Connection -> EncryptionLevel -> IO ()-waitEncryptionLevel Connection{..} lvl = atomically $ do+waitEncryptionLevel conn = atomically . waitEncryptionLevelSTM conn++waitEncryptionLevelSTM :: Connection -> EncryptionLevel -> STM ()+waitEncryptionLevelSTM Connection{..} lvl = do     l <- readTVar $ encryptionLevel connState     check (l >= lvl) 
Network/QUIC/Connection/Migration.hs view
@@ -19,6 +19,7 @@     addPeerCID,     isPeerCIDConsistent,     waitPeerCID,+    waitPeerCIDWithin,     choosePeerCIDForPrivacy,     setPeerStatelessResetToken,     isStatelessRestTokenValid,@@ -40,7 +41,7 @@  import Network.QUIC.Connection.Misc import Network.QUIC.Connection.Queue-import Network.QUIC.Connection.Timeout (timeout)+import Network.QUIC.Connection.Timeout (waitWithin) import Network.QUIC.Connection.Types import Network.QUIC.Connector import Network.QUIC.Imports@@ -156,18 +157,28 @@  -- | Only for the internal "migration" API waitPeerCID :: Connection -> IO CIDInfo-waitPeerCID conn@Connection{..} = do-    r <- atomically $ do-        let ref = peerCIDDB-        db <- readTVar ref-        mncid <- pickPeerCID conn-        check $ isJust mncid-        let u = usedCIDInfo db-        setPeerCID conn (fromJust mncid) True-        return u+waitPeerCID conn = do+    r <- atomically $ waitPeerCIDSTM conn     qlogCIDUpdate conn $ Remote $ cidInfoCID r     return r +-- | 'waitPeerCID', giving up after the time given.+waitPeerCIDWithin :: Connection -> Microseconds -> IO (Maybe CIDInfo)+waitPeerCIDWithin conn tmo = do+    mr <- waitWithin tmo $ waitPeerCIDSTM conn+    forM_ mr $ \r -> qlogCIDUpdate conn $ Remote $ cidInfoCID r+    return mr++waitPeerCIDSTM :: Connection -> STM CIDInfo+waitPeerCIDSTM conn@Connection{..} = do+    let ref = peerCIDDB+    db <- readTVar ref+    mncid <- pickPeerCID conn+    check $ isJust mncid+    let u = usedCIDInfo db+    setPeerCID conn (fromJust mncid) True+    return u+ pickPeerCID :: Connection -> STM (Maybe CIDInfo) pickPeerCID Connection{..} = do     db <- readTVar peerCIDDB@@ -416,7 +427,7 @@ validateMigration conn pathInfo cidChanged = do     mold <-         if cidChanged-            then timeout (Microseconds 100000) "validateMigration" $ waitPeerCID conn+            then waitPeerCIDWithin conn (Microseconds 100000)             else return Nothing -- PathChallenge only, no RetireConnectionID     oldPathInfo <- getPathInfo conn     -- assumed that this PathInfo is not stored in PeerInfo
Network/QUIC/Connection/Misc.hs view
@@ -42,18 +42,25 @@     requestEnd,     watchAbortRequest,     abortRequested,+    concurrentlyApp,+    runProtocolThreads,+    appGracePeriod, ) where +import Control.Concurrent.Async (pollSTM, wait, waitCatchSTM, withAsync) import Control.Concurrent.STM (     TVar,     atomically,     modifyTVar',+    orElse,     readTVar,     readTVarIO,+    registerDelay,     retry,     writeTVar,  ) import qualified Control.Exception as E+import qualified Control.Monad.STM as STM import Network.Socket (SockAddr, Socket, unsafeClose) import qualified System.ThreadManager as T @@ -358,8 +365,70 @@  -- | Waiting for 'requestEnd' and raising what it was asked with: --   one of a connection's protocol threads, so that it ends the connection---   as any of them failing does.+--   as any of them failing does.  Returning once it has ended otherwise. watchAbortRequest :: Connection -> IO ()-watchAbortRequest Connection{..} = do-    e <- atomically $ readTVar connAbortRequest >>= maybe retry return-    E.throwIO e+watchAbortRequest conn@Connection{..} = do+    me <-+        atomically $+            (Just <$> (readTVar connAbortRequest >>= maybe retry return))+                `orElse` (Nothing <$ connectionEndedSTM conn)+    mapM_ E.throwIO me++----------------------------------------------------------------++-- | 'Control.Concurrent.Async.concurrently' for the protocol threads and+--   the application.  When the protocol threads fail, the application is+--   not cancelled at once: what it waits on in the connection throws why+--   the connection ended, and it has 'appGracePeriod' to finish by itself.+--   Only then is it cancelled.  The protocol threads' exception is thrown+--   either way, as it was.+--+--   When the application fails, the protocol threads are asked to end the+--   connection with its exception ('requestEnd') and given the same grace.+--   They used to be cancelled at once, in the middle of a send at worst.+concurrentlyApp :: Connection -> IO a -> IO b -> IO (a, b)+concurrentlyApp conn protocol app =+    withAsync protocol $ \ap' -> withAsync app $ \aa -> do+        r <-+            atomically $ (Left <$> waitCatchSTM ap') `orElse` (Right <$> waitCatchSTM aa)+        case r of+            Left (Right x) -> (,) x <$> wait aa+            Left (Left e) -> do+                expired <- registerDelay appGracePeriod+                atomically $+                    void (waitCatchSTM aa) `orElse` (readTVar expired >>= STM.check)+                E.throwIO e+            Right (Right y) -> (,y) <$> wait ap'+            Right (Left e) -> do+                requestEnd conn e+                expired <- registerDelay appGracePeriod+                atomically $+                    void (waitCatchSTM ap') `orElse` (readTVar expired >>= STM.check)+                E.throwIO e++-- | Running the protocol threads until each has returned.  When one+--   fails, the connection has ended and the others see it and return by+--   themselves; those still running after 'appGracePeriod' are cancelled+--   as a last resort.  The first failure is rethrown.+runProtocolThreads :: [IO ()] -> IO ()+runProtocolThreads = go []+  where+    go as (act : acts) = withAsync act $ \a -> go (a : as) acts+    go as [] = do+        mfailed <- atomically $ do+            rs <- mapM pollSTM as+            case [e | Just (Left e) <- rs] of+                e : _ -> return $ Just e+                []+                    | all isJust rs -> return Nothing+                    | otherwise -> retry+        forM_ mfailed $ \e -> do+            expired <- registerDelay appGracePeriod+            atomically $+                mapM_ waitCatchSTM as `orElse` (readTVar expired >>= STM.check)+            E.throwIO e++-- | How long the application, and then each protocol thread, has to+--   finish by itself once the protocol threads have failed (microseconds).+appGracePeriod :: Int+appGracePeriod = 1000000
Network/QUIC/Connection/Queue.hs view
@@ -1,6 +1,7 @@ module Network.QUIC.Connection.Queue where  import Control.Concurrent.STM+import Control.Monad (void)  import Network.QUIC.Connection.Types import Network.QUIC.Recovery (StreamResets)@@ -10,15 +11,26 @@ ----------------------------------------------------------------  takeInput :: Connection -> IO Input-takeInput conn = atomically $ readTQueue (inputQ conn) `orElse` peerClosedSTM conn+takeInput conn = atomically $ readTQueue (inputQ conn) `orElse` waitFinishedSTM conn +-- | Waiting until 'Network.QUIC.acceptStream' would not block: a stream+--   the peer opened is waiting, or the connection has ended.+--+--   @since 0.4.0+waitAcceptableSTM :: Connection -> STM ()+waitAcceptableSTM conn =+    void (peekTQueue $ inputQ conn) `orElse` connectionEndedSTM conn+ putInput :: Connection -> Input -> IO () putInput conn inp = atomically $ writeTQueue (inputQ conn) inp  ----------------------------------------------------------------  takeCrypto :: Connection -> IO Crypto-takeCrypto conn = atomically $ readTQueue (cryptoQ conn)+takeCrypto = atomically . takeCryptoSTM++takeCryptoSTM :: Connection -> STM Crypto+takeCryptoSTM conn = readTQueue (cryptoQ conn)  putCrypto :: Connection -> Crypto -> IO () putCrypto conn inp = atomically $ writeTQueue (cryptoQ conn) inp
Network/QUIC/Connection/State.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-}  module Network.QUIC.Connection.State (@@ -37,6 +38,7 @@ import Network.QUIC.Connector import Network.QUIC.Imports import Network.QUIC.Recovery+import Network.QUIC.Types (QUICException (..))  ---------------------------------------------------------------- @@ -79,28 +81,26 @@  -- | Waiting until 0-RTT data can be sent. wait0RTTReady :: Connection -> IO ()-wait0RTTReady conn@Connection{..} = atomically $ ready `orElse` peerClosedSTM conn-  where-    ready = do-        cs <- readTVar $ connectionState connState-        check (cs >= ReadyFor0RTT && cs /= Closed)+wait0RTTReady conn = waitState conn ReadyFor0RTT  -- | Waiting until 1-RTT data can be sent. wait1RTTReady :: Connection -> IO ()-wait1RTTReady conn@Connection{..} = atomically $ ready `orElse` peerClosedSTM conn-  where-    ready = do-        cs <- readTVar $ connectionState connState-        check (cs >= ReadyFor1RTT && cs /= Closed)+wait1RTTReady conn = waitState conn ReadyFor1RTT  -- | For clients, waiting until HANDSHAKE_DONE is received. --   For servers, waiting until a TLS stack reports that the handshake is complete. waitEstablished :: Connection -> IO ()-waitEstablished conn@Connection{..} = atomically $ ready `orElse` peerClosedSTM conn+waitEstablished conn = waitState conn Established++-- | A closed connection reaches no state any more: 'ConnectionIsClosed'+--   is thrown then, rather than waiting for ever.+waitState :: Connection -> ConnectionState -> IO ()+waitState conn@Connection{..} st = atomically $ ready `orElse` waitFinishedSTM conn   where     ready = do         cs <- readTVar $ connectionState connState-        check (cs >= Established && cs /= Closed)+        when (cs == Closed) $ throwSTM $ ConnectionIsClosed "connection is closed"+        check (cs >= st)  ---------------------------------------------------------------- @@ -165,12 +165,18 @@ setAddressValidated PathInfo{..} = atomically $ writeTVar addressValidated True  -- Three times rule for anti amplification-waitAntiAmplificationFree :: Connection -> PathInfo -> Int -> IO ()-waitAntiAmplificationFree Connection{..} pathInfo siz = do++-- | 'False' if the connection ends before the path is free.+waitAntiAmplificationFree :: Connection -> PathInfo -> Int -> IO Bool+waitAntiAmplificationFree conn@Connection{..} pathInfo siz = do     ok <- checkAntiAmplificationFree pathInfo siz-    unless ok $ do-        beforeAntiAmp connLDCC-        atomically (checkAntiAmplificationFreeSTM pathInfo siz >>= check)+    if ok+        then return True+        else do+            beforeAntiAmp connLDCC+            atomically $+                (True <$ (checkAntiAmplificationFreeSTM pathInfo siz >>= check))+                    `orElse` (False <$ connectionEndedSTM conn)  -- setLossDetectionTimer is called eventually. 
Network/QUIC/Connection/Stream.hs view
@@ -51,7 +51,7 @@  get :: Connection -> TVar Concurrency -> IO Int get conn tvar = atomically $ do-    checkPeerClosedSTM conn+    checkConnectionEndSTM conn     conc@Concurrency{..} <- readTVar tvar     let streamType = currentStream .&. 0b11         StreamIdBase base = maxStreams
Network/QUIC/Connection/Timeout.hs view
@@ -1,5 +1,6 @@ module Network.QUIC.Connection.Timeout (     timeout,+    waitWithin,     fire,     fire',     cfire,@@ -7,6 +8,7 @@ ) where  import Control.Concurrent+import Control.Concurrent.STM import qualified Control.Exception as E import Network.QUIC.Event import qualified System.Timeout as ST@@ -18,6 +20,13 @@  timeout :: Microseconds -> String -> IO a -> IO (Maybe a) timeout (Microseconds ms) _ action = ST.timeout ms action++-- | Waiting for an STM action, giving up after the time given.  The+--   deadline is waited for beside it rather than thrown at it.+waitWithin :: Microseconds -> STM a -> IO (Maybe a)+waitWithin (Microseconds us) act = do+    expired <- registerDelay us+    atomically $ (Just <$> act) `orElse` (Nothing <$ (readTVar expired >>= check))  fire :: Connection -> Microseconds -> TimeoutCallback -> IO () fire conn (Microseconds microseconds) action = do
Network/QUIC/Connection/Types.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StrictData #-}  module Network.QUIC.Connection.Types where@@ -231,7 +232,7 @@ ----------------------------------------------------------------  type Send = Buffer -> Int -> IO ()-type Recv = IO ReceivedPacket+type Recv = STM ReceivedPacket  -- For migration, two SockAddr for the peer are contained. data PeerInfo = PeerInfo@@ -349,6 +350,12 @@     , connAbortRequest  :: TVar (Maybe E.SomeException)     -- ^ How 'Network.QUIC.Connection.Misc.requestEnd' asked the connection     --   to end, for its protocol threads to act on.+    , connEnd           :: TVar (Maybe E.SomeException)+    -- ^ Why the connection ended, however it did: what a wait on the+    --   connection throws.  The first reason recorded stays.+    , connAckElicitingSent :: TVar Bool+    -- ^ Whether an ack-eliciting packet went out since a packet was last+    --   received: the first one restarts the idle timer (RFC 9000 10.1).     , -- TLS       pendingQ          :: Array EncryptionLevel (TVar [ReceivedPacket])     , ciphers           :: IOArray EncryptionLevel Cipher@@ -465,6 +472,8 @@     connDone          <- newTVarIO False     peerLimitsReset   <- newTVarIO 0     connAbortRequest  <- newTVarIO Nothing+    connEnd           <- newTVarIO Nothing+    connAckElicitingSent <- newTVarIO False     connRetiredSocks  <- newIORef []     -- TLS     pendingQ          <- makePendingQ@@ -635,24 +644,76 @@ mainDone conn = atomically $ writeTVar (connDone conn) True  -- | The peer has closed the connection: we drain, so nothing is sent back---   (RFC 9000 Sec 10.2.2), and what is waiting on the peer gives up.+--   (RFC 9000 Sec 10.2.2), and what is waiting on the connection gives up. setPeerClosed :: Connection -> ReasonPhrase -> IO () setPeerClosed conn reason = do     writeIORef (connCloseSent conn) True     atomically $ writeTVar (sharedCloseReceived $ shared conn) $ Just reason+    setConnectionEnd conn $ E.toException $ ConnectionIsClosed reason  isPeerClosed :: Connection -> IO Bool isPeerClosed conn = isJust <$> readTVarIO (sharedCloseReceived $ shared conn) --- | Waiting for the peer to close, then throwing 'ConnectionIsClosed'.---   An alternative for a wait on the peer.-peerClosedSTM :: Connection -> STM a-peerClosedSTM conn = do-    mr <- readTVar $ sharedCloseReceived $ shared conn-    case mr of-        Nothing -> retry-        Just reason -> throwSTM $ ConnectionIsClosed reason+-- | Recording why the connection ended, unless a reason is recorded+--   already.  Asynchronous exceptions say nothing of why: they are the+--   connection being taken down after it ended.+setConnectionEnd :: Connection -> E.SomeException -> IO ()+setConnectionEnd conn se+    -- 'Abort' is asynchronous only in its type: the abort watcher throws it.+    | isAsyncException se && isNothing (E.fromException se :: Maybe Abort) = return ()+    | otherwise = atomically $ modifyTVar' (connEnd conn) (<|> Just (endReason se)) --- | Throwing 'ConnectionIsClosed' if the peer has closed.-checkPeerClosedSTM :: Connection -> STM ()-checkPeerClosedSTM conn = peerClosedSTM conn `orElse` return ()+-- | What a wait on the connection is told: what the application knows.+endReason :: E.SomeException -> E.SomeException+endReason se+    | Just (Abort err desc) <- E.fromException se =+        E.toException $ ApplicationProtocolErrorIsSent err desc+    | Just ExitConnection <- E.fromException se = endedNormally+    | Just (_ :: InternalControl) <- E.fromException se =+        E.toException $ BadThingHappen se+    | otherwise = se++-- | Recording a synchronous exception as why the connection ended, and+--   throwing it on.  For each protocol thread: which of them ends the+--   connection first records it, before the others are taken down.+recordingEnd :: Connection -> IO a -> IO a+recordingEnd conn action =+    action `E.catch` \se -> setConnectionEnd conn se >> E.throwIO se++-- | The protocol threads ending as they should: the application is done.+--   Any other 'InternalControl' is a failure, not an ending: taken for one,+--   every protocol thread was gone and the application waited for ever.+exitedNormally :: InternalControl -> IO ()+exitedNormally ExitConnection = return ()+exitedNormally e = E.throwIO e++-- | Why a connection which ended normally did, for those still waiting.+endedNormally :: E.SomeException+endedNormally = E.toException $ ConnectionIsClosed "connection is closed"++isConnectionEnded :: Connection -> IO Bool+isConnectionEnded conn = isJust <$> readTVarIO (connEnd conn)+++-- | Waiting until the connection has finished, however it did, and then+--   throwing why: what 'Network.QUIC.acceptStream', 'Network.QUIC.recvStream'+--   and the like throw once it has.  It never returns, so it can be+--   composed with a wait of the caller's own to give up on that wait.+--+--   @since 0.4.0+waitFinishedSTM :: Connection -> STM a+waitFinishedSTM conn = readTVar (connEnd conn) >>= maybe retry throwSTM++-- | Waiting for the connection to end, without throwing.+connectionEndedSTM :: Connection -> STM ()+connectionEndedSTM conn = readTVar (connEnd conn) >>= check . isJust++-- | Telling the idle timer that an ack-eliciting packet was sent.+ackElicitingSent :: Connection -> IO ()+ackElicitingSent conn = atomically $ do+    sent <- readTVar $ connAckElicitingSent conn+    unless sent $ writeTVar (connAckElicitingSent conn) True++-- | Throwing why the connection ended, if it has.+checkConnectionEndSTM :: Connection -> STM ()+checkConnectionEndSTM conn = waitFinishedSTM conn `orElse` return ()
Network/QUIC/Connection/Types.hs-boot view
@@ -4,4 +4,5 @@  data Connection -peerClosedSTM :: Connection -> STM a+waitFinishedSTM :: Connection -> STM a+connectionEndedSTM :: Connection -> STM ()
Network/QUIC/Handshake.hs view
@@ -3,6 +3,7 @@  module Network.QUIC.Handshake where +import Control.Concurrent.STM (atomically, orElse) import qualified Control.Exception as E import qualified Data.ByteString.Short as Short import Data.List (intersect)@@ -46,8 +47,11 @@ sendCryptoData :: Connection -> Output -> IO () sendCryptoData = putOutput +-- | Throwing why the connection ended, if it does first: the handshaker+--   is the thread waiting here, and it ends with that. recvCryptoData :: Connection -> IO Crypto-recvCryptoData = takeCrypto+recvCryptoData conn =+    atomically $ takeCryptoSTM conn `orElse` waitFinishedSTM conn  recvTLS     :: Connection
Network/QUIC/IO.hs view
@@ -130,7 +130,7 @@ checkBlocked :: Stream -> Int -> Bool -> STM (Either Blocked Int) checkBlocked s len wait = do     let conn = streamConnection s-    checkPeerClosedSTM conn+    checkConnectionEndSTM conn     strmFlow <- readStreamFlowTx s     connFlow <- readConnectionFlowTx conn     let strmWindow = txWindowSize strmFlow@@ -181,7 +181,7 @@         receiveOnly =             (isClient conn && isServerInitiatedUnidirectional sid)                 || (isServer conn && isClientInitiatedUnidirectional sid)-    closed <- (||) <$> isConnectionClosed conn <*> isPeerClosed conn+    closed <- (||) <$> isConnectionClosed conn <*> isConnectionEnded conn     sclosed <- isTxStreamClosed s     unless (receiveOnly || closed || sclosed) $ do         setTxStreamClosed s@@ -203,7 +203,7 @@         sendOnly =             (isClient conn && isClientInitiatedUnidirectional sid)                 || (isServer conn && isServerInitiatedUnidirectional sid)-    closed <- (||) <$> isConnectionClosed conn <*> isPeerClosed conn+    closed <- (||) <$> isConnectionClosed conn <*> isConnectionEnded conn     final <- rxFinal <$> getRxBounds s     unless (sendOnly || closed || isJust final) $ stopStream s aerr @@ -362,4 +362,4 @@  -- | Receiving a DATAGRAM frame in STM. recvDatagramSTM :: Connection -> STM ByteString-recvDatagramSTM conn = readDatagramQSTM (connRecvDatagramQ conn) `orElse` peerClosedSTM conn+recvDatagramSTM conn = readDatagramQSTM (connRecvDatagramQ conn) `orElse` waitFinishedSTM conn
Network/QUIC/Parameters.hs view
@@ -16,8 +16,8 @@  import qualified Control.Exception as E import qualified Data.ByteString as BS-import Data.IntSet (IntSet)-import qualified Data.IntSet as IntSet+import Data.Set (Set)+import qualified Data.Set as Set import qualified Data.ByteString.Short as Short import Network.Control import System.IO.Unsafe (unsafeDupablePerformIO)@@ -31,7 +31,9 @@ decodeParameters :: ByteString -> Maybe Parameters decodeParameters bs = decodeParameterList bs >>= fromParameterList -newtype Key = Key Word32 deriving (Eq, Show)+-- | A variable-length integer, as on the wire: one past 32 bits is not+--   another parameter with the low bits of its own.+newtype Key = Key Int64 deriving (Eq, Ord, Show) type Value = ByteString  type ParameterList = [(Key, Value)]@@ -193,18 +195,16 @@ -- on the key as it arrived, before anything decides whether it means -- something here. fromParameterList :: ParameterList -> Maybe Parameters-fromParameterList kvs0 = go IntSet.empty params kvs0+fromParameterList kvs0 = go Set.empty params kvs0   where     params = baseParameters-    go :: IntSet -> Parameters -> ParameterList -> Maybe Parameters+    go :: Set Key -> Parameters -> ParameterList -> Maybe Parameters     go _ x [] = Just x-    go seen x (kv@(Key k, _) : kvs)-        | key `IntSet.member` seen = Nothing+    go seen x (kv@(key, _) : kvs)+        | key `Set.member` seen = Nothing         | otherwise = do             x' <- update x kv-            go (IntSet.insert key seen) x' kvs-      where-        key = fromIntegral k+            go (Set.insert key seen) x' kvs     update x (OriginalDestinationConnectionId, v) =         Just x{originalDestinationConnectionId = Just (toCID v)}     update x (MaxIdleTimeout, v) =@@ -312,7 +312,7 @@         mapM_ (put wbuf) kvs   where     put wbuf (Key k, v) = do-        encodeInt' wbuf $ fromIntegral k+        encodeInt' wbuf k         encodeInt' wbuf $ fromIntegral $ BS.length v         copyByteString wbuf v @@ -331,7 +331,7 @@         if rest1 == 0             then return $ Just (build [])             else do-                key <- fromIntegral <$> decodeInt' rbuf+                key <- decodeInt' rbuf                 len <- fromIntegral <$> decodeInt' rbuf                 val <- extractByteString rbuf len                 go rbuf (build . ((Key key, val) :))
Network/QUIC/Receiver.hs view
@@ -8,7 +8,17 @@     processReceivedPacketHandshake, ) where +import Control.Concurrent.STM (+    atomically,+    orElse,+    readTVar,+    readTVarIO,+    registerDelay,+    retry,+    writeTVar,+ ) import qualified Control.Exception as E+import qualified Control.Monad.STM as STM import qualified Data.ByteString as BS import Network.Socket (SockAddr, Socket) import Network.TLS (AlertDescription (..))@@ -32,18 +42,16 @@ receiver :: Connection -> IO () receiver conn = handleLogT logAction body   where-    body = do-        loopHandshake-        loopEstablished+    body = loopHandshake+    -- 'Nothing' once another thread has ended the connection.     recvTimeout = do         -- The spec says that CC is not sent when timeout.         -- But we intentionally sends CC when timeout.+        -- Waited for beside the packet rather than thrown at the wait.         mito <- getIdleTimeout conn-        mx <- case mito of-            Nothing -> Just <$> connRecv conn-            Just ito -> timeout ito "recvTimeout" $ connRecv conn-        case mx of-            Nothing -> do+        got <- waitIdle mito+        case got of+            Expired -> do                 st <- getConnectionState conn                 let msg0                         | isClient conn = "Client"@@ -51,57 +59,91 @@                     msg = msg0 ++ " " ++ show st                 qlogDebug conn $ Debug "recv timeout"                 E.throwIO $ ConnectionIsTimeout msg-            Just x -> return x+            Got x -> do+                atomically $ writeTVar (connAckElicitingSent conn) False+                return $ Just x+            _ -> return Nothing+    ended = Ended <$ connectionEndedSTM conn+    -- RFC 9000 Sec 10.1: the timer restarts on receiving a packet and on+    -- the first ack-eliciting packet sent after that.+    waitIdle Nothing = atomically $ ended `orElse` (Got <$> connRecv conn)+    waitIdle mito@(Just (Microseconds us)) = do+        sent0 <- readTVarIO $ connAckElicitingSent conn+        expired <- registerDelay us+        let restarted+                | sent0 = retry+                | otherwise = readTVar (connAckElicitingSent conn) >>= STM.check+        r <-+            atomically $+                ended+                    `orElse` (Got <$> connRecv conn)+                    `orElse` (Restarted <$ restarted)+                    `orElse` (Expired <$ (readTVar expired >>= STM.check))+        case r of+            Restarted -> waitIdle mito+            _ -> return r     loopHandshake = do-        rpkt <- recvTimeout-        processReceivedPacketHandshake conn rpkt-        established <- isConnectionEstablished conn-        unless established loopHandshake-    loopEstablished = forever $ do-        rpkt <- recvTimeout-        let CryptPacket hdr _ = rpCryptPacket rpkt-            cid = headerMyCID hdr-        -- Before 'setMyCID' below, which makes it the one in use.-        cidChanged <- (/= cid) <$> getMyCID conn-        included <- myCIDsInclude conn cid-        case included of-            Just nseq -> do-                -- RFC 9000 Sec 5.1.1: If an endpoint provided fewer-                -- connection IDs than the peer's-                -- active_connection_id_limit, it MAY supply a new-                -- connection ID when it receives a packet with a-                -- previously unused connection ID.-                shouldUpdate <- shouldUpdateMyCID conn nseq-                capOK <- checkPeerCIDCapacity conn-                when (shouldUpdate && capOK) $ do-                    setMyCID conn cid-                    cidInfo <- getNewMyCID conn-                    when (isServer conn) $ do-                        register <- getRegister conn-                        register (cidInfoCID cidInfo) conn-                    sent <- readIORef (sentRetirePriorTo conn)-                    writeIORef (sentRetirePriorTo conn) False-                    unless sent $-                        sendFrames conn RTT1Level [NewConnectionID cidInfo 0]-                processReceivedPacket' conn (Just cidChanged) rpkt-                shouldUpdatePeer <--                    if shouldUpdate-                        then shouldUpdatePeerCID conn-                        else return False-                when shouldUpdatePeer $ choosePeerCIDForPrivacy conn-            _ -> do-                qlogDropped conn (hdr, "unknown_connection_id" :: String)-                connDebugLog conn $ bhow cid <> " is unknown"+        mrpkt <- recvTimeout+        -- Not 'forM_', which would leave each loop a frame to return to.+        case mrpkt of+            Nothing -> return ()+            Just rpkt -> do+                processReceivedPacketHandshake conn rpkt+                established <- isConnectionEstablished conn+                if established then loopEstablished else loopHandshake+    loopEstablished = do+        mrpkt <- recvTimeout+        case mrpkt of+            Nothing -> return ()+            Just rpkt -> do+                let CryptPacket hdr _ = rpCryptPacket rpkt+                    cid = headerMyCID hdr+                -- Before 'setMyCID' below, which makes it the one in use.+                cidChanged <- (/= cid) <$> getMyCID conn+                included <- myCIDsInclude conn cid+                case included of+                    Just nseq -> do+                        -- RFC 9000 Sec 5.1.1: If an endpoint provided fewer+                        -- connection IDs than the peer's+                        -- active_connection_id_limit, it MAY supply a new+                        -- connection ID when it receives a packet with a+                        -- previously unused connection ID.+                        shouldUpdate <- shouldUpdateMyCID conn nseq+                        capOK <- checkPeerCIDCapacity conn+                        when (shouldUpdate && capOK) $ do+                            setMyCID conn cid+                            cidInfo <- getNewMyCID conn+                            when (isServer conn) $ do+                                register <- getRegister conn+                                register (cidInfoCID cidInfo) conn+                            sent <- readIORef (sentRetirePriorTo conn)+                            writeIORef (sentRetirePriorTo conn) False+                            unless sent $+                                sendFrames conn RTT1Level [NewConnectionID cidInfo 0]+                        processReceivedPacket' conn (Just cidChanged) rpkt+                        shouldUpdatePeer <-+                            if shouldUpdate+                                then shouldUpdatePeerCID conn+                                else return False+                        when shouldUpdatePeer $ choosePeerCIDForPrivacy conn+                    _ -> do+                        qlogDropped conn (hdr, "unknown_connection_id" :: String)+                        connDebugLog conn $ bhow cid <> " is unknown"+                loopEstablished     logAction msg = connDebugLog conn ("debug: receiver: " <> msg) +data Got = Got ReceivedPacket | Restarted | Expired | Ended+ processReceivedPacketHandshake :: Connection -> ReceivedPacket -> IO ()-processReceivedPacketHandshake conn rpkt = do+processReceivedPacketHandshake conn rpkt+    | serverZeroRTT conn rpkt = dropServerZeroRTT conn rpkt+    | otherwise = processReceivedPacketHandshake' conn rpkt++processReceivedPacketHandshake' :: Connection -> ReceivedPacket -> IO ()+processReceivedPacketHandshake' conn rpkt = do     let CryptPacket hdr crypt = rpCryptPacket rpkt         lvl = rpEncryptionLevel rpkt-        msg =-            "processReceivedPacketHandshake "-                ++ if isServer conn then "Server" else "Client"-    mx <- timeout (Microseconds 10000) msg $ waitEncryptionLevel conn lvl+    mx <- waitWithin (Microseconds 10000) $ waitEncryptionLevelSTM conn lvl     case mx of         Nothing -> do             putOffCrypto conn lvl rpkt@@ -178,12 +220,25 @@ -- | With whether the packet came on a CID other than the one in use, once --   the handshake is over: only then may the peer migrate. processReceivedPacket' :: Connection -> Maybe Bool -> ReceivedPacket -> IO ()-processReceivedPacket' conn mcidChanged rpkt = do-    let CryptPacket _ crypt = rpCryptPacket rpkt-    mplain <- decryptReceived conn rpkt $ decryptCrypt conn crypt lvl-    processDecrypted conn mcidChanged rpkt mplain+processReceivedPacket' conn mcidChanged rpkt+    | serverZeroRTT conn rpkt = dropServerZeroRTT conn rpkt+    | otherwise = do+        let CryptPacket _ crypt = rpCryptPacket rpkt+        mplain <- decryptReceived conn rpkt $ decryptCrypt conn crypt lvl+        processDecrypted conn mcidChanged rpkt mplain   where     lvl = rpEncryptionLevel rpkt++-- | RFC 9001 Sec 5.6: a server sends no 0-RTT packet, and the client's key+--   for receiving one comes of an empty secret that anyone can derive.+--   Decrypted, a forged one could close the connection or answer a request.+serverZeroRTT :: Connection -> ReceivedPacket -> Bool+serverZeroRTT conn rpkt = isClient conn && rpEncryptionLevel rpkt == RTT0Level++dropServerZeroRTT :: Connection -> ReceivedPacket -> IO ()+dropServerZeroRTT conn rpkt = do+    let CryptPacket hdr _ = rpCryptPacket rpkt+    qlogDropped conn (hdr, "0-RTT from the server" :: String)  -- | Counting the packet for the path, then decrypting it as given. decryptReceived
Network/QUIC/Recovery/Interface.hs view
@@ -50,16 +50,28 @@         unless (any spAckEliciting packets) $ sendPing ldcc lvl         setLossDetectionTimer ldcc -resender :: LDCC -> IO ()-resender ldcc@LDCC{..} = forever $ do-    atomically $ do-        lostPackets <- readTVar lostCandidates-        check (lostPackets /= emptySentPackets)-    delay $ Microseconds 10000 -- fixme-    packets <- atomically $ do-        SentPackets pkts <- readTVar lostCandidates-        writeTVar lostCandidates emptySentPackets-        return pkts-    when (packets /= Seq.empty) $ do-        onPacketsLost ldcc packets-        retransmit ldcc packets+-- | Returning once @stop@ does.+resender :: STM () -> LDCC -> IO ()+resender stop ldcc@LDCC{..} = loop+  where+    loop = do+        lost <-+            atomically $+                ( do+                    lostPackets <- readTVar lostCandidates+                    check (lostPackets /= emptySentPackets)+                    return True+                )+                    `orElse` (False <$ stop)+        when lost $ do+            resend+            loop+    resend = do+        delay $ Microseconds 10000 -- fixme+        packets <- atomically $ do+            SentPackets pkts <- readTVar lostCandidates+            writeTVar lostCandidates emptySentPackets+            return pkts+        when (packets /= Seq.empty) $ do+            onPacketsLost ldcc packets+            retransmit ldcc packets
Network/QUIC/Recovery/Timer.hs view
@@ -121,13 +121,23 @@             then atomically $ writeTVar timerInfoQ $ Next tmi             else updateLossDetectionTimer' ldcc tmi -ldccTimer :: LDCC -> IO ()-ldccTimer ldcc@LDCC{..} = forever $ do-    atomically $ do-        x <- readTVar timerInfoQ-        check (x /= Empty)-    delay timerGranularity-    updateWithNext ldcc+-- | Returning once @stop@ does.+ldccTimer :: STM () -> LDCC -> IO ()+ldccTimer stop ldcc@LDCC{..} = loop+  where+    loop = do+        next <-+            atomically $+                ( do+                    x <- readTVar timerInfoQ+                    check (x /= Empty)+                    return True+                )+                    `orElse` (False <$ stop)+        when next $ do+            delay timerGranularity+            updateWithNext ldcc+            loop  updateWithNext :: LDCC -> IO () updateWithNext ldcc@LDCC{..} = do
Network/QUIC/Sender.hs view
@@ -1,6 +1,8 @@ {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}  module Network.QUIC.Sender (+    sendOrLose,     sender,     mkHeader,     sendFinal,@@ -21,6 +23,7 @@ import Network.QUIC.Crypto (confidentialityLimit) import Network.QUIC.Exception import Network.QUIC.Imports+import Network.QUIC.Logger (bhow) import Network.QUIC.Packet import Network.QUIC.Qlog import Network.QUIC.Recovery@@ -49,7 +52,7 @@ sendPacketTo _ _ [] = return () sendPacketTo conn mdst spkts0 = getMaxPacketSize conn >>= go   where-    send pathInfo buf bytes = case mdst of+    send pathInfo buf bytes = sendOrLose conn $ case mdst of         Nothing -> connSend conn buf bytes         Just _ -> do             s <- maybe (getSocket conn) return $ pathSocket pathInfo@@ -72,17 +75,25 @@     -- ack-eliciting and so is not a probe; twenty seconds later the idle     -- timeout ends it.     ackOnly = all (not . spAckEliciting) spkts0+    waitWindow maxSiz = case mdst of+        _ | ackOnly -> return Nothing+        -- For another path: the PTO probe is for the path in use, so+        -- it is left for that and only the window is waited for.+        Just _ -> Nothing <$ checkWindowOpenSTM ldcc maxSiz+        Nothing ->+            (Just <$> takePingSTM ldcc)+                `orElse` (Nothing <$ checkWindowOpenSTM ldcc maxSiz)     go maxSiz = do-        mx <- case mdst of-            _ | ackOnly -> return Nothing-            -- For another path: the PTO probe is for the path in use, so-            -- it is left for that and only the window is waited for.-            Just _ -> Nothing <$ atomically (checkWindowOpenSTM ldcc maxSiz)-            Nothing ->-                atomically-                    ( (Just <$> takePingSTM ldcc)-                        `orElse` (Nothing <$ checkWindowOpenSTM ldcc maxSiz)-                    )+        -- Once the connection has ended, nothing acknowledges the bytes in+        -- flight and the window stays shut: what does not fit is dropped.+        emx <-+            atomically $+                (Right <$> waitWindow maxSiz)+                    `orElse` (Left () <$ connectionEndedSTM conn)+        case emx of+            Left () -> return ()+            Right mx -> send1 maxSiz mx+    send1 maxSiz mx =         case mx of             -- A PTO probe is the one packet allowed past a full congestion             -- window.  Normally sendPingPacket is the right way to spend it:@@ -113,11 +124,13 @@                 (sentPackets, leftsiz) <- buildPackets buf0 bufsiz0 maxSiz spkts0 id                 let bytes = bufsiz0 - leftsiz                 pathInfo <- maybe (getPathInfo conn) return mdst-                when (isServer conn) $-                    waitAntiAmplificationFree conn pathInfo bytes+                free <-+                    if isServer conn+                        then waitAntiAmplificationFree conn pathInfo bytes+                        else return True                 -- If the secret of this level (e.g. HandshakeLevel)                 -- is already dropped, bytes is 0.-                when (bytes > 0) $ do+                when (free && bytes > 0) $ do                     now <- getTimeMicrosecond                     send pathInfo buf0 bytes                     addTxBytes conn bytes@@ -126,6 +139,7 @@                         let sentPacket = sentPacket0{spTimeSent = now}                         qlogSent conn sentPacket now                         onPacketSent ldcc sentPacket+                    when (any spAckEliciting sentPackets) $ ackElicitingSent conn                     -- RFC 9001 Sec 6.6: "Endpoints MUST count the number of                     -- encrypted packets for each set of keys.  If the total                     -- number of encrypted packets with the same key exceeds@@ -233,7 +247,7 @@                 (bytes, padlen) <- encodePlainPacket conn sizbuf ping (Just maxSiz)                 when (bytes > 0) $ do                     now <- getTimeMicrosecond-                    connSend conn buf bytes+                    sendOrLose conn $ connSend conn buf bytes                     addTxBytes conn bytes                     addPathTxBytes pathInfo bytes                     let sentPacket0 = fixSentPacket spkt bytes padlen@@ -347,18 +361,25 @@ sender conn = handleLogT logAction loop   where     loop = do-        exit <- atomically $ do-            done <- readTVar $ connDone conn-            a <- isEmptyPingSTM (connLDCC conn)-            b <- isEmptyOutputSTM conn-            c <- isEmptyStreamSTM conn-            if done-                then return (a && b && c)-                else if (not a || not b || not c) then return False else retry-        if exit-            then-                E.throwIO ExitConnection-            else do+        next <-+            -- Another thread has ended it: 'sendFinal' sends the rest, and+            -- an application that saw the end and returned is not a normal+            -- end, which is what 'ExitConnection' would say.+            atomically $+                (Ended <$ connectionEndedSTM conn)+                    `orElse` ( do+                                done <- readTVar $ connDone conn+                                a <- isEmptyPingSTM (connLDCC conn)+                                b <- isEmptyOutputSTM conn+                                c <- isEmptyStreamSTM conn+                                if done+                                    then return $ if a && b && c then Exit else Send+                                    else if (not a || not b || not c) then return Send else retry+                             )+        case next of+            Exit -> E.throwIO ExitConnection+            Ended -> return ()+            Send -> do                 -- Between two sends, so this thread is not inside a call                 -- on any of them.                 closeRetiredSockets conn@@ -366,14 +387,27 @@                 loop     logAction msg = connDebugLog conn ("debug: sender: " <> msg) +data Next = Send | Exit | Ended+ sendP :: Connection -> IO ()-sendP conn = do-    x <--        atomically-            ( (SwPing <$> takePingSTM (connLDCC conn))-                `orElse` (SwOut <$> takeOutputSTM conn)-                `orElse` (SwStrm <$> takeSendStreamQSTM conn)-            )+sendP conn = atomically (takeSwitch conn) >>= sendSwitch conn++-- | 'sendP' if something is queued, whether it was.+sendPNow :: Connection -> IO Bool+sendPNow conn = do+    mx <- atomically $ (Just <$> takeSwitch conn) `orElse` return Nothing+    case mx of+        Nothing -> return False+        Just x -> True <$ sendSwitch conn x++takeSwitch :: Connection -> STM Switch+takeSwitch conn =+    (SwPing <$> takePingSTM (connLDCC conn))+        `orElse` (SwOut <$> takeOutputSTM conn)+        `orElse` (SwStrm <$> takeSendStreamQSTM conn)++sendSwitch :: Connection -> Switch -> IO ()+sendSwitch conn x =     case x of         SwPing lvl -> sendPingPacket conn lvl         SwOut out -> sendOutput conn out@@ -385,14 +419,13 @@     closed <- isPeerClosed conn     unless closed $ loop 30   where-    msg = "sendFinal " ++ if isServer conn then "Server" else "Client"+    -- What is queued already, without waiting for more.  A timeout of+    -- 10 usec around 'sendP' did this, and could cut a send short.     loop :: Int -> IO ()     loop 0 = return ()     loop n = do-        mx <- timeout (Microseconds 10) msg $ sendP conn-        case mx of-            Nothing -> return ()-            Just () -> loop (n - 1)+        sent <- sendPNow conn+        when sent $ loop (n - 1)  ---------------------------------------------------------------- @@ -706,3 +739,12 @@       where         len = BS.length b         siz = siz0 + len++----------------------------------------------------------------++-- | A datagram the socket would not take is lost like any other, and+--   recovery sends what it carried again.  ENETUNREACH while the network+--   changes used to end the connection that migration is there to save.+sendOrLose :: Connection -> IO () -> IO ()+sendOrLose conn io = io `E.catch` \(e :: E.IOException) ->+    connDebugLog conn $ "send: " <> bhow e
Network/QUIC/Server/Reader.hs view
@@ -501,13 +501,10 @@             newdCID <- newCID             retryToken <-                 generateRetryToken peerVer scTicketLifetime newdCID sCID dCID peersa-            mnewtoken <--                timeout (Microseconds 100000) "sendRetry" $ encryptToken tokenMgr retryToken-            case mnewtoken of-                Nothing -> logAction "retry token stacked"-                Just newtoken -> do-                    bss <- encodeRetryPacket $ RetryPacket peerVer sCID newdCID newtoken (Left dCID)-                    send' bss+            -- It reads an IORef and encrypts: nothing to time out.+            newtoken <- encryptToken tokenMgr retryToken+            bss <- encodeRetryPacket $ RetryPacket peerVer sCID newdCID newtoken (Left dCID)+            send' bss ---------------------------------------------------------------- dispatch     Dispatch{..}@@ -579,5 +576,5 @@                 -- (RFC 9000 Sec 9).                 writeRecvQ (connRecvQ conn) $ mkReceivedPacket cpkt tim siz lvl -recvServer :: RecvQ -> IO ReceivedPacket-recvServer = readRecvQ+recvServer :: RecvQ -> STM ReceivedPacket+recvServer = readRecvQSTM
Network/QUIC/Server/Run.hs view
@@ -254,42 +254,38 @@                     mainDone conn                 ldcc = connLDCC conn             -- Each says why it ended, as the sender and the receiver-            -- already did.  'concurrently_' cancels the others as soon as one-            -- of them fails, so the one that did not end in AsyncCancelled is-            -- the one that ended the connection -- and it was these four that-            -- said nothing, leaving a log of two cancelled threads and no-            -- reason anywhere.+            -- already did.  The one that failed is the one that ended the+            -- connection, and the others return when they see it ended -- it+            -- was these four that said nothing, leaving no reason anywhere.             ---            -- Being cancelled is not worth a line: the sender and the-            -- receiver already say when the connection is taken down from-            -- outside, and everything else follows them.+            -- Being cancelled, the last resort, is not worth a line: the+            -- sender and the receiver already say when the connection is+            -- taken down from outside, and everything else follows them.             let named nm act =                     act `E.catch` \e -> do                         case E.fromException e of                             Just AsyncCancelled -> return ()                             Nothing -> connDebugLog conn $ "debug: " <> nm <> ": " <> bhow e                         E.throwIO e-            let s1 = labelMe "handshaker" >> named "handshaker" handshaker-                s2 = labelMe "sender" >> sender conn-                s3 = labelMe "receiver" >> receiver conn-                s4 = labelMe "resender" >> named "resender" (resender ldcc)-                s5 = labelMe "ldccTimer" >> named "ldccTimer" (ldccTimer ldcc)+            let rec = recordingEnd conn+                s1 = labelMe "handshaker" >> rec (named "handshaker" handshaker)+                s2 = labelMe "sender" >> rec (sender conn)+                s3 = labelMe "receiver" >> rec (receiver conn)+                s4 = labelMe "resender" >> rec (named "resender" (resender ended ldcc))+                s5 = labelMe "ldccTimer" >> rec (named "ldccTimer" (ldccTimer ended ldcc))                 s6 = labelMe "QUIC server" >> named "server" server-                c1 = labelMe "concurrently1" >> concurrently_ s1 s2-                c2 = labelMe "concurrently2" >> concurrently_ c1 s3-                c3 = labelMe "concurrently3" >> concurrently_ c2 s4-                c4 = labelMe "concurrently4" >> concurrently_ c3 s5-                c4' = labelMe "concurrently4'" >> concurrently_ c4 s7-                s7 = labelMe "abort watcher" >> watchAbortRequest conn+                s7 = labelMe "abort watcher" >> rec (watchAbortRequest conn)+                ended = connectionEndedSTM conn+                protocol = runProtocolThreads [s1, s2, s3, s4, s5, s7]                 -- Telling the peer here, and not below, because here is the-                -- one place where it can be done at all: the nested-                -- 'concurrently_'s above have waited for every protocol+                -- one place where it can be done at all:+                -- 'runProtocolThreads' has waited for every protocol                 -- thread, so the encode buffer is ours alone -- it is shared                 -- with the sender -- and the application is still running, so                 -- nothing has begun waiting for it yet.                 --                 -- Below, after 'runThreads', is too late.  The-                -- 'concurrently_' on this line cancels the application when+                -- 'concurrentlyApp' on this line cancels the application when                 -- the protocol threads fail and then waits for it, under                 -- 'uninterruptibleMask_', for as long as it takes to unwind.                 -- The CONNECTION_CLOSE waited with it, and a peer told@@ -307,11 +303,15 @@                         closure conn ldcc (Left e)                 c5 =                     labelMe "concurrently5"-                        >> concurrently_-                            (tellThenRaise (c4' `E.catch` \(_ :: InternalControl) -> return ()))-                            s6+                        >> void+                            ( concurrentlyApp+                                conn+                                (tellThenRaise (protocol `E.catch` exitedNormally))+                                s6+                            )                 runThreads = c5             ex <- E.try runThreads >>= abortRequested conn+            setConnectionEnd conn $ either id (const endedNormally) ex             sendFinal conn             setConnectionClosed conn             closure conn ldcc ex
Network/QUIC/Stream.hs view
@@ -47,6 +47,7 @@      -- * Reass     takeRecvStreamQwithSize,+    waitReadableSTM,     putRxStreamData,     putRxCryptoData,     FlowCntl (..),@@ -65,6 +66,7 @@ ) where  import Network.QUIC.Stream.Misc+import Network.QUIC.Stream.Queue (waitReadableSTM) import Network.QUIC.Stream.Reass import Network.QUIC.Stream.Table import Network.QUIC.Stream.Types
Network/QUIC/Stream/Queue.hs view
@@ -3,9 +3,14 @@ module Network.QUIC.Stream.Queue where  import Control.Concurrent.STM+import Control.Monad (unless, void) import Data.ByteString (ByteString)+import Data.Maybe (isJust) -import {-# SOURCE #-} Network.QUIC.Connection.Types (peerClosedSTM)+import {-# SOURCE #-} Network.QUIC.Connection.Types (+    waitFinishedSTM,+    connectionEndedSTM,+ ) import Network.QUIC.Stream.Types  putRecvStreamQ :: Stream -> ByteString -> IO ()@@ -14,7 +19,21 @@ takeRecvStreamQ :: Stream -> IO ByteString takeRecvStreamQ Stream{..} =     atomically $-        readTQueue (recvStreamQ streamRecvQ) `orElse` peerClosedSTM streamConnection+        readTQueue (recvStreamQ streamRecvQ) `orElse` waitFinishedSTM streamConnection++-- | Waiting until 'Network.QUIC.recvStream' would not block: something+--   is pending from a read before, the end of the stream has been read,+--   something is in the queue (data, a FIN or a reset), or the connection+--   has ended.+--+--   @since 0.4.0+waitReadableSTM :: Stream -> STM ()+waitReadableSTM Stream{..} = do+    eos <- readTVar $ endOfStream streamRecvQ+    pending <- readTVar $ pendingData streamRecvQ+    unless (eos || isJust pending) $+        void (peekTQueue $ recvStreamQ streamRecvQ)+            `orElse` connectionEndedSTM streamConnection  tryTakeRecvStreamQ :: Stream -> IO (Maybe ByteString) tryTakeRecvStreamQ Stream{..} = atomically $ tryReadTQueue $ recvStreamQ streamRecvQ
Network/QUIC/Stream/Reass.hs view
@@ -10,6 +10,7 @@     tryReassemble, ) where +import Control.Concurrent.STM import qualified Data.ByteString as BS import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map@@ -23,19 +24,19 @@ ----------------------------------------------------------------  getEndOfStream :: Stream -> IO Bool-getEndOfStream Stream{..} = readIORef $ endOfStream streamRecvQ+getEndOfStream Stream{..} = readTVarIO $ endOfStream streamRecvQ  setEndOfStream :: Stream -> IO ()-setEndOfStream Stream{..} = writeIORef (endOfStream streamRecvQ) True+setEndOfStream Stream{..} = atomically $ writeTVar (endOfStream streamRecvQ) True  readPendingData :: Stream -> IO (Maybe ByteString)-readPendingData Stream{..} = readIORef $ pendingData streamRecvQ+readPendingData Stream{..} = readTVarIO $ pendingData streamRecvQ  writePendingData :: Stream -> ByteString -> IO ()-writePendingData Stream{..} bs = writeIORef (pendingData streamRecvQ) $ Just bs+writePendingData Stream{..} bs = atomically $ writeTVar (pendingData streamRecvQ) $ Just bs  clearPendingData :: Stream -> IO ()-clearPendingData Stream{..} = writeIORef (pendingData streamRecvQ) Nothing+clearPendingData Stream{..} = atomically $ writeTVar (pendingData streamRecvQ) Nothing  ---------------------------------------------------------------- 
Network/QUIC/Stream/Types.hs view
@@ -21,7 +21,10 @@ import qualified Data.Map.Strict as Map import Network.Control -import {-# SOURCE #-} Network.QUIC.Connection.Types (Connection, peerClosedSTM)+import {-# SOURCE #-} Network.QUIC.Connection.Types (+    Connection,+    waitFinishedSTM,+ ) import Network.QUIC.Imports import Network.QUIC.Types @@ -104,7 +107,7 @@ waitFinTx :: Stream -> IO () waitFinTx s =     atomically $-        takeTMVar (streamSyncFinTx s) `orElse` peerClosedSTM (streamConnection s)+        takeTMVar (streamSyncFinTx s) `orElse` waitFinishedSTM (streamConnection s)  ---------------------------------------------------------------- @@ -150,13 +153,13 @@  data RecvStreamQ = RecvStreamQ     { recvStreamQ :: TQueue ByteString-    , pendingData :: IORef (Maybe ByteString)-    , endOfStream :: IORef Bool+    , pendingData :: TVar (Maybe ByteString)+    , endOfStream :: TVar Bool     }  newRecvStreamQ :: IO RecvStreamQ newRecvStreamQ = do     recvStreamQ <- newTQueueIO-    pendingData <- newIORef Nothing-    endOfStream <- newIORef False+    pendingData <- newTVarIO Nothing+    endOfStream <- newTVarIO False     return RecvStreamQ{..}
Network/QUIC/Types/Queue.hs view
@@ -55,7 +55,11 @@         <*> pure budget  readRecvQ :: RecvQ -> IO ReceivedPacket-readRecvQ (RecvQ q qlen qbytes _ (RecvBudget _ used)) = atomically $ do+readRecvQ = atomically . readRecvQSTM++-- | 'readRecvQ' in STM, for a wait to give up on beside it.+readRecvQSTM :: RecvQ -> STM ReceivedPacket+readRecvQSTM (RecvQ q qlen qbytes _ (RecvBudget _ used)) = do     x <- readTQueue q     let n = rpReceivedBytes x     modifyTVar' qlen (subtract 1)
quic.cabal view
@@ -1,6 +1,6 @@ cabal-version:      2.0 name:               quic-version:            0.3.24+version:            0.3.25 license:            BSD3 license-file:       LICENSE maintainer:         kazu@iij.ad.jp@@ -132,11 +132,11 @@         bytestring >=0.10,         containers,         crypto-token >=0.2.1 && <0.3,-        crypton >=2.1.0 && <2.3,-        crypton-x509 >=1.9.0 && <1.11,+        crypton >=2.1.0 && <2.4,+        crypton-x509 >=1.9.0 && <1.12,         crypton-x509-store >=1.9.0 && <1.11,         crypton-x509-system >=1.9.0 && <1.11,-        crypton-x509-validation >=1.9.0 && <1.11,+        crypton-x509-validation >=1.9.0 && <1.12,         fast-logger >=3.2.8 && <3.3,         filepath,         iproute >=1.7.12 && <1.9,@@ -148,7 +148,7 @@         serialise,         stm >=2.5 && <2.6,         time-manager >=0.5 && <0.6,-        tls >=2.5.1 && <2.6,+        tls >=2.5.1 && <2.7,         unix-time >=0.4.12 && <0.7      if os(linux)
test/Config.hs view
@@ -170,6 +170,8 @@       --   datagram to the server from another socket, which answers       --   nothing: an on-path attacker's spurious migration.       ForwardAside (MVar ())+    | -- | Once the MVar is filled, drop every datagram from the server.+      SilenceServer (MVar ())     | -- | As 'ForwardAside', but from an IPv6 socket to the server's       --   @[::1]:15003@, a socket of the server other than the client's.       ForwardAside6 (MVar ())@@ -333,8 +335,11 @@             recordSize scenario False bs             n <- atomicModifyIORef' irefS $ \x -> (x + 1, x)             dropPacket <- shouldDrop scenario False n+            silenced <- case scenario of+                SilenceServer trigger -> isJust <$> tryReadMVar trigger+                _ -> return False             let isCC = BS.length bs < 200-            when (isCC || not dropPacket) $ do+            when (not silenced && (isCC || not dropPacket)) $ do                 mpeer <- readIORef peerRef                 case mpeer of                     Nothing -> return ()
test/IOSpec.hs view
@@ -1,12 +1,22 @@ {-# LANGUAGE NumericUnderscores #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}  module IOSpec where  import Control.Concurrent import Control.Concurrent.Async-import Control.Concurrent.STM (atomically, readTVarIO)+import Control.Concurrent.STM (+    STM,+    atomically,+    check,+    newTVarIO,+    orElse,+    readTVar,+    readTVarIO,+    writeTVar,+ ) import qualified Control.Exception as E import Control.Monad import Data.Bits (shiftR)@@ -383,6 +393,88 @@     describe "the client's socket" $ do         it "is closed when the peer ends the connection" $ do             withPipe (DropClientPacket []) $ testSocketClosed cc sc waitS+    describe "a connection the peer ended with an error" $ do+        it "lets waiting for a state give up" $ do+            withPipe (DropClientPacket []) $ testWaitStateClosed cc sc waitS+        it "lets the application finish by itself" $ do+            withPipe (DropClientPacket []) $ testAppFinishes cc sc waitS+        it "lets the server's application finish by itself" $ do+            withPipe (DropClientPacket []) $ testServerAppFinishes cc sc waitS+        it "cancels an application that does not finish" $ do+            withPipe (DropClientPacket []) $ testAppCancelled cc sc waitS+        it "wakes a thread waiting in acceptStream" $ do+            withPipe (DropClientPacket []) $+                testForkedWait cc sc waitS $+                    \conn -> void $ acceptStream conn+        it "wakes a thread waiting in recvStream" $ do+            withPipe (DropClientPacket []) $+                testForkedWait cc sc waitS $ \conn -> do+                    strm <- stream conn+                    void $ recvStream strm 1024+        it "wakes a thread waiting for a stream the peer allows" $ do+            let sc1 = sc{scParameters = (scParameters sc){initialMaxStreamsBidi = 1}}+            withPipe (DropClientPacket []) $+                testForkedWait cc sc1 waitS $+                    \conn -> void $ stream conn+        it "wakes a thread waiting in waitReadableSTM" $ do+            withPipe (DropClientPacket []) $+                testForkedWait cc sc waitS $ \conn -> do+                    strm <- stream conn+                    atomically $ waitReadableSTM strm+                    void $ recvStream strm 1024+        it "wakes a thread waiting in waitAcceptableSTM" $ do+            withPipe (DropClientPacket []) $+                testForkedWait cc sc waitS $ \conn -> do+                    atomically $ waitAcceptableSTM conn+                    void $ acceptStream conn+        it "wakes a thread waiting in waitFinishedSTM" $ do+            withPipe (DropClientPacket []) $+                testForkedWait cc sc waitS $+                    \conn -> atomically $ waitFinishedSTM conn+        it "wakes a thread waiting for flow control in sendStream" $ do+            withPipe (DropClientPacket []) $+                testForkedWait cc sc waitS $ \conn -> do+                    strm <- stream conn+                    forever $ sendStream strm $ BS.replicate 65536 0+    describe "abortConnection" $ do+        it "wakes a thread waiting in acceptStream at once" $ do+            withPipe (DropClientPacket []) $ testAbortWakes cc sc waitS+    describe "the protocol threads" $ do+        it "return by themselves when one fails" $ do+            ended <- newTVarIO False+            let failing = do+                    atomically $ writeTVar ended True+                    E.throwIO $ userError "failed"+                waiting = atomically $ readTVar ended >>= check+            r <-+                Timeout.timeout 500000 $+                    E.try @E.IOException $+                        runProtocolThreads [waiting, failing, waiting]+            case r of+                Just (Left _) -> return ()+                _ -> expectationFailure $ show r+        it "cancel one that does not return" $ do+            cancelled <- newEmptyMVar+            let stuck =+                    forever (threadDelay 1000000)+                        `E.catch` \(e :: E.SomeAsyncException) ->+                            putMVar cancelled () >> E.throwIO e+                failing = E.throwIO $ userError "failed"+            r <- E.try @E.IOException $ runProtocolThreads [stuck, failing]+            either (const True) (const False) r `shouldBe` True+            tryTakeMVar cancelled `shouldReturn` Just ()+    describe "the idle timeout" $ do+        it "ends a connection with nothing to say" $ do+            withPipe (DropClientPacket []) $ testIdleTimeout cc sc waitS+        it "restarts on the first ack-eliciting packet sent" $ do+            silence <- newEmptyMVar+            withPipe (SilenceServer silence) $+                testIdleRestart cc sc waitS silence+    describe "waiting in STM" $ do+        it "waits for data, and then for what a read leaves" $ do+            withPipe (DropClientPacket []) $ testWaitReadable cc sc waitS+        it "waits for a stream the peer opens" $ do+            withPipe (DropClientPacket []) $ testWaitAcceptable cc sc waitS     describe "the peer closing with NO_ERROR" $ do         it "wakes a client waiting in recvStream" $ do             withPipe (DropClientPacket []) $@@ -1608,6 +1700,264 @@         case msock of             Nothing -> expectationFailure "no socket"             Just sock -> NS.withFdSocket sock return `shouldReturn` (-1)+  where+    server = run sc $ \conn -> do+        strm <- acceptStream conn+        _ <- recvStream strm 1024+        abortConnection conn (ApplicationProtocolError 1) "bye"++-- | A thread the application forked may wait for a state after the+--   connection has ended.  Only a peer closing with NO_ERROR woke it, and+--   one ended otherwise was waited on for ever.+testWaitStateClosed :: C.ClientConfig -> ServerConfig -> IO () -> IO ()+testWaitStateClosed cc sc waitS = do+    ref <- newIORef Nothing+    withAsync server $ \_ -> do+        waitS+        r <- E.try $ C.run cc $ \conn -> do+            writeIORef ref $ Just conn+            strm <- stream conn+            sendStream strm "ping"+            void $ recvStream strm 1024+        case r of+            Left (ApplicationProtocolErrorIsReceived _ _) -> return ()+            _ -> expectationFailure $ show r+        mconn <- readIORef ref+        case mconn of+            Nothing -> expectationFailure "no connection"+            Just conn ->+                forM_ [wait0RTTReady, wait1RTTReady, waitEstablished] $ \waitFor -> do+                    w <- Timeout.timeout 1000000 $ E.try $ waitFor conn+                    case w of+                        Just (Left (ConnectionIsClosed _)) -> return ()+                        Nothing -> expectationFailure "waited for ever"+                        Just ex -> expectationFailure $ show ex+  where+    server = run sc $ \conn -> do+        strm <- acceptStream conn+        _ <- recvStream strm 1024+        abortConnection conn (ApplicationProtocolError 1) "bye"++-- | The application of 'run', waiting on the connection when the peer+--   ends it with an error, is told why rather than cancelled.+testAppFinishes :: C.ClientConfig -> ServerConfig -> IO () -> IO ()+testAppFinishes cc sc waitS = do+    told <- newEmptyMVar+    withAsync abortingServer $ \_ -> do+        waitS+        r <- E.try $ C.run cc $ \conn -> do+            strm <- stream conn+            sendStream strm "ping"+            -- Tidying up takes a moment, which a cancel cut short.+            void (recvStream strm 1024) `E.catch` \(e :: QUICException) -> do+                threadDelay 100000+                putMVar told e+                E.throwIO e+        case r of+            Left (ApplicationProtocolErrorIsReceived _ _) -> return ()+            _ -> expectationFailure $ show r+        w <- tryTakeMVar told+        case w of+            Just (ApplicationProtocolErrorIsReceived _ _) -> return ()+            _ -> expectationFailure $ "the application was told " ++ show w+  where+    abortingServer = run sc $ \conn -> do+        strm <- acceptStream conn+        _ <- recvStream strm 1024+        abortConnection conn (ApplicationProtocolError 1) "bye"++-- | The same for a server's application, the client ending the connection.+testServerAppFinishes :: C.ClientConfig -> ServerConfig -> IO () -> IO ()+testServerAppFinishes cc sc waitS = do+    told <- newEmptyMVar+    let server = run sc $ \conn -> do+            strm <- acceptStream conn+            _ <- recvStream strm 1024+            void (recvStream strm 1024) `E.catch` \(e :: QUICException) -> do+                threadDelay 100000+                putMVar told e+                E.throwIO e+    withAsync server $ \_ -> do+        waitS+        _ <- E.try @QUICException $ C.run cc $ \conn -> do+            strm <- stream conn+            sendStream strm "ping"+            threadDelay 100000+            abortConnection conn (ApplicationProtocolError 1) "bye"+            threadDelay 1000000 :: IO ()+        w <- Timeout.timeout 3000000 $ takeMVar told+        case w of+            Just (ApplicationProtocolErrorIsReceived _ _) -> return ()+            _ -> expectationFailure $ "the application was told " ++ show w++-- | One that goes on with something else is cancelled after the grace+--   period, and 'run' throws why the connection ended.+testAppCancelled :: C.ClientConfig -> ServerConfig -> IO () -> IO ()+testAppCancelled cc sc waitS =+    withAsync server $ \_ -> do+        waitS+        r <- Timeout.timeout 5000000 $ E.try $ C.run cc $ \conn -> do+            strm <- stream conn+            sendStream strm "ping"+            threadDelay 10000000+        case r of+            Just (Left (ApplicationProtocolErrorIsReceived _ _)) -> return ()+            _ -> expectationFailure $ show r+  where+    server = run sc $ \conn -> do+        strm <- acceptStream conn+        _ <- recvStream strm 1024+        abortConnection conn (ApplicationProtocolError 1) "bye"++-- | A connection nobody uses times out on the receiver's deadline, which+--   is waited for beside the packets rather than thrown at the wait.+testIdleTimeout :: C.ClientConfig -> ServerConfig -> IO () -> IO ()+testIdleTimeout cc0 sc waitS =+    withAsync (run sc $ \_ -> threadDelay 10000000) $ \_ -> do+        waitS+        r <- Timeout.timeout 5000000 $ E.try $ C.run cc $ \conn -> do+            waitEstablished conn+            threadDelay 10000000+        case r of+            Just (Left (ConnectionIsTimeout _)) -> return ()+            _ -> expectationFailure $ show r+  where+    cc =+        cc0+            { ccParameters =+                (ccParameters cc0){maxIdleTimeout = Milliseconds 500}+            }++-- | With the server silenced, the client sends after a second, which+--   restarts its 2 sec idle timer: the timeout comes after 3 sec, not 2.+--   Shorter, three times the PTO would be in effect instead.+testIdleRestart+    :: C.ClientConfig -> ServerConfig -> IO () -> MVar () -> IO ()+testIdleRestart cc0 sc waitS silence =+    withAsync (run sc $ \_ -> threadDelay 10000000) $ \_ -> do+        waitS+        ref <- newIORef Nothing+        r <- Timeout.timeout 10000000 $ E.try $ C.run cc $ \conn -> do+            waitEstablished conn+            threadDelay 100000+            putMVar silence ()+            t0 <- getTimeMicrosecond+            threadDelay 1000000+            strm <- stream conn+            sendStream strm "ping"+            -- Thrown when the connection ends, which is what is timed.+            _ <- E.try @QUICException $ recvStream strm 1024+            getElapsedTimeMicrosecond t0 >>= writeIORef ref . Just+        elapsed <- readIORef ref+        case r of+            Just (Left (ConnectionIsTimeout _)) ->+                elapsed `shouldSatisfy` maybe False (>= Microseconds 2600000)+            _ -> expectationFailure $ show r+  where+    cc =+        cc0+            { ccParameters =+                (ccParameters cc0){maxIdleTimeout = Milliseconds 2000}+            }++-- | 'abortConnection' ends the connection for a thread waiting on it,+--   well within the grace period after which it would be cancelled.+testAbortWakes :: C.ClientConfig -> ServerConfig -> IO () -> IO ()+testAbortWakes cc sc waitS =+    withAsync (run sc $ \_ -> threadDelay 10000000) $ \_ -> do+        waitS+        res <- newEmptyMVar+        _ <- E.try @QUICException $ C.run cc $ \conn -> do+            waitEstablished conn+            _ <- forkIO $ E.try (acceptStream conn) >>= putMVar res+            threadDelay 10000+            abortConnection conn (ApplicationProtocolError 1) "bye"+            threadDelay 10000000+        w <- Timeout.timeout 500000 $ takeMVar res+        case w of+            Just (Left (ApplicationProtocolErrorIsSent _ _)) -> return ()+            _ -> expectationFailure $ show w++-- | Whether a wait in STM would return now.+readyNow :: STM () -> IO Bool+readyNow w = atomically $ (True <$ w) `orElse` return False++-- | 'waitReadableSTM' returns when 'recvStream' would not block: for data,+--   for what a read left pending, and for the end of the stream once read.+testWaitReadable :: C.ClientConfig -> ServerConfig -> IO () -> IO ()+testWaitReadable cc sc waitS =+    withAsync server $ \_ -> do+        waitS+        r <- Timeout.timeout 5000000 $ C.run cc $ \conn -> do+            strm <- stream conn+            readyNow (waitReadableSTM strm) `shouldReturn` False+            sendStream strm "ping"+            Timeout.timeout 2000000 (atomically $ waitReadableSTM strm)+                `shouldReturn` Just ()+            recvStream strm 3 `shouldReturn` "abc"+            readyNow (waitReadableSTM strm) `shouldReturn` True+            rest <- recvAll strm+            rest `shouldBe` "def"+            readyNow (waitReadableSTM strm) `shouldReturn` True+        r `shouldBe` Just ()+  where+    server = run sc $ \conn -> do+        strm <- acceptStream conn+        _ <- recvStream strm 1024+        sendStream strm "abcdef"+        shutdownStream strm+        threadDelay 3000000+    recvAll strm = do+        bs <- recvStream strm 1024+        if BS.null bs then return "" else (bs <>) <$> recvAll strm++-- | 'waitAcceptableSTM' returns when 'acceptStream' would not block.+testWaitAcceptable :: C.ClientConfig -> ServerConfig -> IO () -> IO ()+testWaitAcceptable cc sc waitS =+    withAsync server $ \_ -> do+        waitS+        r <- Timeout.timeout 5000000 $ C.run cc $ \conn -> do+            readyNow (waitAcceptableSTM conn) `shouldReturn` False+            strm <- stream conn+            sendStream strm "ping"+            Timeout.timeout 2000000 (atomically $ waitAcceptableSTM conn)+                `shouldReturn` Just ()+            s <- acceptStream conn+            recvStream s 1024 `shouldReturn` "x"+        r `shouldBe` Just ()+  where+    server = run sc $ \conn -> do+        strm <- acceptStream conn+        _ <- recvStream strm 1024+        s <- stream conn+        sendStream s "x"+        threadDelay 3000000++-- | A thread the application forked, waiting on the connection when the+--   peer ends it with an error, is told so.  Only a peer closing with+--   NO_ERROR woke one, and any other ending left it waiting for ever.+testForkedWait+    :: C.ClientConfig -> ServerConfig -> IO () -> (Connection -> IO ()) -> IO ()+testForkedWait cc sc waitS body = do+    res <- newEmptyMVar+    tref <- newIORef Nothing+    withAsync server $ \_ -> do+        waitS+        r <- E.try $ C.run cc $ \conn -> do+            strm <- stream conn+            sendStream strm "ping"+            tid <- forkIO $ E.try (body conn) >>= putMVar res+            writeIORef tref $ Just tid+            void $ recvStream strm 1024+        case r of+            Left (ApplicationProtocolErrorIsReceived _ _) -> return ()+            _ -> expectationFailure $ show r+        w <- Timeout.timeout 1000000 $ takeMVar res+        readIORef tref >>= mapM_ killThread+        case w of+            Just (Left (ApplicationProtocolErrorIsReceived _ _)) -> return ()+            Nothing -> expectationFailure "waited for ever"+            Just ex -> expectationFailure $ show ex   where     server = run sc $ \conn -> do         strm <- acceptStream conn
test/MigrationSpec.hs view
@@ -5,6 +5,7 @@ import Control.Concurrent import Control.Concurrent.Async (concurrently, mapConcurrently, wait, withAsync) import Control.Concurrent.STM+import qualified Control.Exception as E import Control.Monad (forM, forM_, void) import qualified Data.ByteString as BS import qualified Data.ByteString.Short as Short@@ -243,23 +244,23 @@             getSocketName sock `shouldThrow` anyException             atomically $ writeTVar newRetired True -        it "leaves its socket for the sender when the connection goes idle" $ do+        it "leaves its socket to the connection when the connection ends" $ do             (clientConn, _) <- makeConnections serverConf Version1             sock <- getSocket clientConn             peersa <- peerSockAddr <$> getPathInfo clientConn             connect sock peersa-            setMinIdleTimeout clientConn $ Microseconds 100000-            -- Raised to three times the PTO, which is what it waits.-            pto <- getPTO $ connLDCC clientConn             retired <- getSocketRetire clientConn             done <- newEmptyMVar             void $ forkIO $ readerClient retired sock clientConn >> putMVar done ()+            -- As the receiver's idle timeout does.+            setConnectionEnd clientConn $ E.toException $ ConnectionIsTimeout "idle"             returned <--                timeout (3 * pto + Microseconds 2000000) "idle reader" $ takeMVar done+                timeout (Microseconds 2000000) "ended reader" $ takeMVar done             returned `shouldBe` Just ()-            void $ getSocketName sock+            -- The sender, between two sends, does not close it under+            -- the connection.             closeRetiredSockets clientConn-            getSocketName sock `shouldThrow` anyException+            void $ getSocketName sock          it "closes a socket it was left even if nothing drains it" $ do             (clientConn, _) <- makeConnections serverConf Version1
test/PacketSpec.hs view
@@ -128,6 +128,27 @@             clientInitial True `shouldReturn` False             clientInitial False `shouldReturn` True +    -- #269: the client's 0-RTT receive key comes of an empty secret, so+    -- anyone can forge a 0-RTT packet it would decrypt.+    describe "a 0-RTT packet to the client" $+        it "is dropped undecrypted" $ do+            (clientConn, serverConn) <- makeConnections serverConf Version1+            cipher <- getCipher clientConn InitialLevel+            let early conn sec = do+                    setCipher conn RTT0Level cipher+                    initializeCoder conn RTT0Level (sec, ServerTrafficSecret "")+            early clientConn $ ClientTrafficSecret "client"+            -- Anyone's: the server side encrypts with the empty secret.+            early serverConn $ ClientTrafficSecret "forger"+            setConnection0RTTReady clientConn+            -- As soon as the server's Initial is in; below it, the packet is+            -- put off, and decrypted once the level is reached.+            setEncryptionLevel clientConn HandshakeLevel+            let hdr = RTT0 Version1 (toCID "") clientChosenCID+                close = ConnectionCloseApp (ApplicationProtocolError 0) "forged"+            bin <- packetWith serverConn hdr [close]+            processHandshake clientConn bin+     describe "encodePlainPacket" $ do         it "leaves the peer a whole header protection sample" $ do             (senderConn, _) <- makeConnections serverConf Version1@@ -173,13 +194,17 @@ packetFrom     :: Connection -> Header -> Bool -> IO ByteString packetFrom sender hdr corrupt = do-    let ppkt = PlainPacket hdr $ Plain (Flags 0) 0 [Ping] 0-    bin <- BS.createAndTrim 4096 $ \buf ->-        fst <$> encodePlainPacket sender (SizedBuffer buf 2048) ppkt Nothing+    bin <- packetWith sender hdr [Ping]     return $         if corrupt             then BS.snoc (BS.init bin) (BS.last bin `xor` 0xff)             else bin++packetWith :: Connection -> Header -> [Frame] -> IO ByteString+packetWith sender hdr frames = do+    let ppkt = PlainPacket hdr $ Plain (Flags 0) 0 frames 0+    BS.createAndTrim 4096 $ \buf ->+        fst <$> encodePlainPacket sender (SizedBuffer buf 2048) ppkt Nothing  processHandshake :: Connection -> ByteString -> IO () processHandshake conn bin = do
test/ParametersSpec.hs view
@@ -44,6 +44,14 @@         it "accepts two different parameters" $             decodeParameters (BS.pack [0x04, 0x01, 0x20, 0x05, 0x01, 0x21])                 `shouldSatisfy` isJust'+        -- A key is a variable-length integer: 2^32+4 is not initial_max_data,+        -- which is 4, cut to 32 bits.+        it "keeps a key past 32 bits apart from the one it would be cut to" $ do+            let key = [0xc0, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04]+            fmap initialMaxData (decodeParameters (BS.pack (key ++ [0x01, 0x21])))+                `shouldBe` fmap initialMaxData (decodeParameters "")+            decodeParameters (BS.pack (key ++ [0x01, 0x21, 0x04, 0x01, 0x20]))+                `shouldSatisfy` isJust'  -- Parameters has no Eq, so keep only whether one came back. isNothing' :: Maybe Parameters -> Bool