-- | Listen loop for the Switch.
--
-- Accepts inbound connections, applies connection gating policy,
-- upgrades to secure multiplexed connections, and dispatches
-- inbound streams to registered protocol handlers.
module LibP2P.Switch.Listen
  ( -- * Connection gating
    ConnectionGater (..)
  , defaultConnectionGater
    -- * Inbound connection handling
  , handleInbound
    -- * Stream dispatch
  , streamAcceptLoop
  , dispatchStream
    -- * Listen orchestration
  , switchListen
  , acceptLoop
  , switchListenAddrs
  , switchWithdrawListener
  ) where

import Control.Concurrent.Async (async, cancel)
import Control.Concurrent.STM (atomically, readTVar, writeTChan, writeTVar)
import Control.Exception (SomeException, catch, finally, try)
import Data.List (find, partition)
import qualified Data.Map.Strict as Map
import LibP2P.Multiaddr (Multiaddr)
import LibP2P.MultistreamSelect.Negotiation
  ( NegotiationResult (..)
  , StreamIO (..)
  , closeQuietly
  , negotiateResponder
  )
import LibP2P.Protocol.Identify (pushIdentify)
import LibP2P.Switch.ConnPool (addConn)
import LibP2P.Switch.Connection (closeConnection)
import LibP2P.Switch.ResourceManager
  ( Direction (..)
  , releaseStream
  , reserveStream
  )
import LibP2P.Switch.Types
  ( ActiveListener (..)
  , Connection (..)
  , ConnectionGater (..)
  , MuxerSession (..)
  , Switch (..)
  , SwitchEvent (..)
  , defaultConnectionGater
  )
import LibP2P.Switch.Upgrade (upgradeWithSwitchConfig)
import LibP2P.Transport (Listener (..), RawConnection (..), Transport (..))

-- | Handle a single inbound connection: gate → upgrade → pool → stream accept loop.
--
-- This function blocks until the connection closes. Each accepted connection
-- should be spawned in its own async thread from the accept loop.
handleInbound :: Switch -> RawConnection -> IO ()
handleInbound :: Switch -> RawConnection -> IO ()
handleInbound Switch
sw RawConnection
rawConn = do
  gater <- STM ConnectionGater -> IO ConnectionGater
forall a. STM a -> IO a
atomically (STM ConnectionGater -> IO ConnectionGater)
-> STM ConnectionGater -> IO ConnectionGater
forall a b. (a -> b) -> a -> b
$ TVar ConnectionGater -> STM ConnectionGater
forall a. TVar a -> STM a
readTVar (Switch -> TVar ConnectionGater
swConnectionGater Switch
sw)
  -- Gate 1: check remote address before any upgrade work
  allowed <- runGate (gateAccept gater (rcRemoteAddr rawConn))
  if not allowed
    then rcClose rawConn
    else do
      -- Upgrade: negotiated secure channel + configured Yamux session
      conn <- upgradeWithSwitchConfig (swConfig sw) (swResourceMgr sw) Inbound (swIdentityKey sw) rawConn
      -- Gate 2: check remote PeerId after security handshake
      secured <- runGate (gateSecured gater (connPeerId conn))
      if not secured
        then muxClose (connSession conn)
        else do
          atomically $ do
            addConn (swConnPool sw) conn
            writeTChan (swEvents sw)
              (Connected (connPeerId conn) Inbound (connRemoteAddr conn))
          notifiers <- atomically $ readTVar (swNotifiers sw)
          mapM_ (\Connection -> IO ()
f -> IO () -> IO (Async ())
forall a. IO a -> IO (Async a)
async (IO () -> IO (Async ())) -> IO () -> IO (Async ())
forall a b. (a -> b) -> a -> b
$ Connection -> IO ()
f Connection
conn) notifiers
          streamAcceptLoop sw conn `finally` closeConnection sw conn

-- | A faulty policy hook fails closed instead of leaking a connection.
runGate :: IO Bool -> IO Bool
runGate :: IO Bool -> IO Bool
runGate IO Bool
action = IO Bool
action IO Bool -> (SomeException -> IO Bool) -> IO Bool
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(SomeException
_ :: SomeException) -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False

-- | Accept inbound streams and dispatch to registered protocol handlers.
--
-- Runs forever, accepting streams from the muxer and spawning a handler
-- thread for each. Uses multistream-select to negotiate the protocol,
-- then dispatches to the registered StreamHandler.
streamAcceptLoop :: Switch -> Connection -> IO ()
streamAcceptLoop :: Switch -> Connection -> IO ()
streamAcceptLoop Switch
sw Connection
conn = IO ()
loop
  where
    loop :: IO ()
loop = do
      -- Accept the next inbound stream from the muxer
      result <- IO (Maybe StreamIO)
safeAccept
      case result of
        Maybe StreamIO
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()  -- Muxer closed or error, stop the loop
        Just StreamIO
stream -> do
          -- Spawn handler for this stream, continue accepting
          _ <- IO () -> IO (Async ())
forall a. IO a -> IO (Async a)
async (IO () -> IO (Async ())) -> IO () -> IO (Async ())
forall a b. (a -> b) -> a -> b
$ Switch -> Connection -> StreamIO -> IO ()
dispatchAccountedStream Switch
sw Connection
conn StreamIO
stream
          loop
    -- Catch exceptions from muxAcceptStream (e.g. session shutdown)
    safeAccept :: IO (Maybe StreamIO)
safeAccept =
      (StreamIO -> Maybe StreamIO
forall a. a -> Maybe a
Just (StreamIO -> Maybe StreamIO) -> IO StreamIO -> IO (Maybe StreamIO)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> MuxerSession -> IO StreamIO
muxAcceptStream (Connection -> MuxerSession
connSession Connection
conn))
        IO (Maybe StreamIO)
-> (SomeException -> IO (Maybe StreamIO)) -> IO (Maybe StreamIO)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(SomeException
_ :: SomeException) -> Maybe StreamIO -> IO (Maybe StreamIO)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe StreamIO
forall a. Maybe a
Nothing)

-- | Dispatch a single inbound stream to the appropriate protocol handler.
--
-- Runs multistream-select as responder to determine which protocol
-- the remote peer wants, then looks up and invokes the registered handler.
dispatchStream :: Switch -> Connection -> StreamIO -> IO ()
dispatchStream :: Switch -> Connection -> StreamIO -> IO ()
dispatchStream Switch
sw Connection
conn StreamIO
stream = do
  reserved <- STM (Either ResourceError ResourceScope)
-> IO (Either ResourceError ResourceScope)
forall a. STM a -> IO a
atomically (STM (Either ResourceError ResourceScope)
 -> IO (Either ResourceError ResourceScope))
-> STM (Either ResourceError ResourceScope)
-> IO (Either ResourceError ResourceScope)
forall a b. (a -> b) -> a -> b
$
    ResourceManager
-> ResourceScope
-> Direction
-> STM (Either ResourceError ResourceScope)
reserveStream (Switch -> ResourceManager
swResourceMgr Switch
sw) (Connection -> ResourceScope
connResourceScope Connection
conn) Direction
Inbound
  case reserved of
    Left ResourceError
_ -> StreamIO -> IO ()
closeQuietly StreamIO
stream
    Right ResourceScope
streamScope -> Switch -> Connection -> StreamIO -> IO ()
dispatchAccountedStream Switch
sw Connection
conn StreamIO
stream
      IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` STM () -> IO ()
forall a. STM a -> IO a
atomically (ResourceManager -> ResourceScope -> STM ()
releaseStream (Switch -> ResourceManager
swResourceMgr Switch
sw) ResourceScope
streamScope)

-- | Dispatch a stream whose muxer already created its resource scope.
dispatchAccountedStream :: Switch -> Connection -> StreamIO -> IO ()
dispatchAccountedStream :: Switch -> Connection -> StreamIO -> IO ()
dispatchAccountedStream Switch
sw Connection
conn StreamIO
stream = IO ()
negotiateAndDispatch
  where
    negotiateAndDispatch :: IO ()
negotiateAndDispatch = do
      -- Get the list of supported protocols from the Switch
      supportedProtos <- STM [ProtocolId] -> IO [ProtocolId]
forall a. STM a -> IO a
atomically (STM [ProtocolId] -> IO [ProtocolId])
-> STM [ProtocolId] -> IO [ProtocolId]
forall a b. (a -> b) -> a -> b
$
        Map ProtocolId (Connection -> StreamIO -> IO ()) -> [ProtocolId]
forall k a. Map k a -> [k]
Map.keys (Map ProtocolId (Connection -> StreamIO -> IO ()) -> [ProtocolId])
-> STM (Map ProtocolId (Connection -> StreamIO -> IO ()))
-> STM [ProtocolId]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> STM (Map ProtocolId (Connection -> StreamIO -> IO ()))
readProtos
      -- Run multistream-select responder. A failed or aborted
      -- negotiation never reaches a handler, so dispatch closes.
      -- go-libp2p resets on mux negotiation failure for the same reason.
      negotiated <- try (negotiateResponder stream supportedProtos)
      case negotiated of
        Left (SomeException
_ :: SomeException) -> StreamIO -> IO ()
closeQuietly StreamIO
stream
        Right NegotiationResult
NoProtocol -> StreamIO -> IO ()
closeQuietly StreamIO
stream
        Right (Accepted ProtocolId
proto) -> do
          mHandler <- ProtocolId -> IO (Maybe (Connection -> StreamIO -> IO ()))
lookupHandler ProtocolId
proto
          case mHandler of
            Just Connection -> StreamIO -> IO ()
handler -> Connection -> StreamIO -> IO ()
handler Connection
conn StreamIO
stream
            -- Protocol vanished from the registry after listing:
            -- no handler will close, so dispatch must.
            Maybe (Connection -> StreamIO -> IO ())
Nothing -> StreamIO -> IO ()
closeQuietly StreamIO
stream
    readProtos :: STM (Map ProtocolId (Connection -> StreamIO -> IO ()))
readProtos = TVar (Map ProtocolId (Connection -> StreamIO -> IO ()))
-> STM (Map ProtocolId (Connection -> StreamIO -> IO ()))
forall a. TVar a -> STM a
readTVar (Switch -> TVar (Map ProtocolId (Connection -> StreamIO -> IO ()))
swProtocols Switch
sw)
    lookupHandler :: ProtocolId -> IO (Maybe (Connection -> StreamIO -> IO ()))
lookupHandler ProtocolId
proto = STM (Maybe (Connection -> StreamIO -> IO ()))
-> IO (Maybe (Connection -> StreamIO -> IO ()))
forall a. STM a -> IO a
atomically (STM (Maybe (Connection -> StreamIO -> IO ()))
 -> IO (Maybe (Connection -> StreamIO -> IO ())))
-> STM (Maybe (Connection -> StreamIO -> IO ()))
-> IO (Maybe (Connection -> StreamIO -> IO ()))
forall a b. (a -> b) -> a -> b
$
      ProtocolId
-> Map ProtocolId (Connection -> StreamIO -> IO ())
-> Maybe (Connection -> StreamIO -> IO ())
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ProtocolId
proto (Map ProtocolId (Connection -> StreamIO -> IO ())
 -> Maybe (Connection -> StreamIO -> IO ()))
-> STM (Map ProtocolId (Connection -> StreamIO -> IO ()))
-> STM (Maybe (Connection -> StreamIO -> IO ()))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TVar (Map ProtocolId (Connection -> StreamIO -> IO ()))
-> STM (Map ProtocolId (Connection -> StreamIO -> IO ()))
forall a. TVar a -> STM a
readTVar (Switch -> TVar (Map ProtocolId (Connection -> StreamIO -> IO ()))
swProtocols Switch
sw)

-- | Start listening on the given addresses.
--
-- Stores the supplied gater on the Switch, then selects a transport for each
-- address, binds a listener, and spawns an accept loop. The same policy applies
-- to subsequent outbound dials. Returns the actual bound addresses.
-- Fails if the switch is already closed.
switchListen :: Switch -> ConnectionGater -> [Multiaddr] -> IO [Multiaddr]
switchListen :: Switch -> ConnectionGater -> [Multiaddr] -> IO [Multiaddr]
switchListen Switch
sw ConnectionGater
gater [Multiaddr]
addrs = do
  closed <- STM Bool -> IO Bool
forall a. STM a -> IO a
atomically (STM Bool -> IO Bool) -> STM Bool -> IO Bool
forall a b. (a -> b) -> a -> b
$ TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar (Switch -> TVar Bool
swClosed Switch
sw)
  if closed
    then fail "switchListen: switch is closed"
    else do
      atomically $ writeTVar (swConnectionGater sw) gater
      transports <- atomically $ readTVar (swTransports sw)
      activeListeners <- mapM (bindAndListen transports sw) addrs
      let newListeners = [[ActiveListener]] -> [ActiveListener]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[ActiveListener]]
activeListeners
      atomically $ do
        existing <- readTVar (swListeners sw)
        writeTVar (swListeners sw) (existing ++ newListeners)
      -- Listen addresses changed: push updated identify info to
      -- connected peers in the background (specs/identify push).
      _ <- async (pushIdentify sw)
      pure (map alAddress newListeners)
  where
    -- Find a transport for the address, bind, and spawn accept loop
    bindAndListen :: t Transport -> Switch -> Multiaddr -> IO [ActiveListener]
bindAndListen t Transport
transports Switch
sw' Multiaddr
addr = do
      case (Transport -> Bool) -> t Transport -> Maybe Transport
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\Transport
t -> Transport -> Multiaddr -> Bool
transportCanDial Transport
t Multiaddr
addr) t Transport
transports of
        Maybe Transport
Nothing -> String -> IO [ActiveListener]
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO [ActiveListener]) -> String -> IO [ActiveListener]
forall a b. (a -> b) -> a -> b
$ String
"switchListen: no transport for " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Multiaddr -> String
forall a. Show a => a -> String
show Multiaddr
addr
        Just Transport
transport -> do
          listener <- Transport -> Multiaddr -> IO Listener
transportListen Transport
transport Multiaddr
addr
          loopThread <- async $ acceptLoop sw' listener
          pure [ActiveListener
            { alListener   = listener
            , alAcceptLoop = loopThread
            , alAddress    = listenerAddr listener
            }]

-- | Accept loop: forever accepts connections and spawns handleInbound threads.
-- Catches exceptions from individual connections without stopping the loop.
-- Stops when the listener is closed (accept throws).
acceptLoop :: Switch -> Listener -> IO ()
acceptLoop :: Switch -> Listener -> IO ()
acceptLoop Switch
sw Listener
listener = IO ()
loop
  where
    loop :: IO ()
loop = do
      result <- (RawConnection -> Either () RawConnection
forall a b. b -> Either a b
Right (RawConnection -> Either () RawConnection)
-> IO RawConnection -> IO (Either () RawConnection)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Listener -> IO RawConnection
listenerAccept Listener
listener)
                  IO (Either () RawConnection)
-> (SomeException -> IO (Either () RawConnection))
-> IO (Either () RawConnection)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(SomeException
_ :: SomeException) -> Either () RawConnection -> IO (Either () RawConnection)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either () RawConnection
forall a b. a -> Either a b
Left ()))
      case result of
        Left () -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()  -- Listener closed, stop
        Right RawConnection
rawConn -> do
          _ <- IO () -> IO (Async ())
forall a. IO a -> IO (Async a)
async (IO () -> IO (Async ())) -> IO () -> IO (Async ())
forall a b. (a -> b) -> a -> b
$ Switch -> RawConnection -> IO ()
handleInbound Switch
sw RawConnection
rawConn
                         IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
          loop

-- | Get the current listen addresses from all active listeners.
switchListenAddrs :: Switch -> IO [Multiaddr]
switchListenAddrs :: Switch -> IO [Multiaddr]
switchListenAddrs Switch
sw = STM [Multiaddr] -> IO [Multiaddr]
forall a. STM a -> IO a
atomically (STM [Multiaddr] -> IO [Multiaddr])
-> STM [Multiaddr] -> IO [Multiaddr]
forall a b. (a -> b) -> a -> b
$ do
  listeners <- TVar [ActiveListener] -> STM [ActiveListener]
forall a. TVar a -> STM a
readTVar (Switch -> TVar [ActiveListener]
swListeners Switch
sw)
  pure (map alAddress listeners)

-- | Withdraw the listener bound to the given address: cancel its accept
-- loop, close the underlying transport listener, and remove it from the
-- Switch's listener set so 'switchListenAddrs' stops reporting it.
--
-- For listeners whose reachability guarantee can lapse independently of
-- the Switch's own lifetime (e.g. a circuit relay reservation that
-- expired or was refused on refresh), this withdraws just that one
-- address without tearing down the rest of the Switch. A no-op if no
-- listener is bound to the address (already withdrawn, or never was).
switchWithdrawListener :: Switch -> Multiaddr -> IO ()
switchWithdrawListener :: Switch -> Multiaddr -> IO ()
switchWithdrawListener Switch
sw Multiaddr
addr = do
  withdrawn <- STM [ActiveListener] -> IO [ActiveListener]
forall a. STM a -> IO a
atomically (STM [ActiveListener] -> IO [ActiveListener])
-> STM [ActiveListener] -> IO [ActiveListener]
forall a b. (a -> b) -> a -> b
$ do
    listeners <- TVar [ActiveListener] -> STM [ActiveListener]
forall a. TVar a -> STM a
readTVar (Switch -> TVar [ActiveListener]
swListeners Switch
sw)
    let (removed, remaining) = partition ((== addr) . alAddress) listeners
    writeTVar (swListeners sw) remaining
    pure removed
  mapM_ closeListener withdrawn
  where
    closeListener :: ActiveListener -> IO ()
closeListener ActiveListener
al = do
      Async () -> IO ()
forall a. Async a -> IO ()
cancel (ActiveListener -> Async ()
alAcceptLoop ActiveListener
al) IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
      Listener -> IO ()
listenerClose (ActiveListener -> Listener
alListener ActiveListener
al) IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())