{- | Background AutoNAT v1 reachability probing.

The client only probes peers that already have a direct connection. It never
dials a peer merely to ask for a dial-back, bounds each request with a
timeout, probes one peer at a time, and throttles repeated requests to the
same peer.
-}
module LibP2P.NAT.AutoNAT.Service (
  AutoNATClientConfig (..),
  defaultAutoNATClientConfig,
  AutoNATClientService,
  startAutoNATClient,
  autoNATClientStatus,
  stopAutoNATClient,
) where

import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (Async, async, cancel)
import Control.Concurrent.STM (
  TVar,
  atomically,
  newTVarIO,
  readTVar,
  writeTVar,
 )
import Control.Exception (
  SomeAsyncException,
  SomeException,
  bracket,
  fromException,
  tryJust,
 )
import Control.Monad (filterM, forever)
import Data.List (sortOn)
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Time.Clock (UTCTime, diffUTCTime, getCurrentTime)
import LibP2P.Crypto.PeerId (PeerId)
import LibP2P.Multiaddr (Multiaddr, isRelayedAddr)
import LibP2P.MultistreamSelect.Negotiation (
  NegotiationResult (..),
  closeQuietly,
  negotiateInitiator,
 )
import LibP2P.NAT.AutoNAT (
  NATStatus (..),
  probeNATStatusPure,
  requestAutoNAT,
 )
import LibP2P.NAT.AutoNAT.Message (
  AutoNATDialResponse,
  autoNATProtocolId,
 )
import LibP2P.Switch (registerSwitchShutdownAction)
import LibP2P.Switch.ConnPool (allConns)
import LibP2P.Switch.Connection (newStream)
import LibP2P.Switch.Listen (switchListenAddrs)
import LibP2P.Switch.Types (
  ConnState (..),
  Connection (..),
  Switch (..),
 )
import System.Timeout (timeout)

-- | AutoNAT client scheduling and resource bounds.
data AutoNATClientConfig = AutoNATClientConfig
  { AutoNATClientConfig -> Int
ancThreshold :: !Int
  -- ^ A status requires strictly more agreeing reports than this value.
  , AutoNATClientConfig -> Int
ancBootDelayMicros :: !Int
  -- ^ Delay before the first probe cycle.
  , AutoNATClientConfig -> Int
ancRetryIntervalMicros :: !Int
  -- ^ Delay while reachability is unknown.
  , AutoNATClientConfig -> Int
ancRefreshIntervalMicros :: !Int
  -- ^ Delay after reaching a public or private decision.
  , AutoNATClientConfig -> Int
ancRequestTimeoutMicros :: !Int
  -- ^ Timeout for one peer's complete stream negotiation and request.
  , AutoNATClientConfig -> Int
ancPeerThrottleMicros :: !Int
  -- ^ Minimum interval before probing the same peer again.
  , AutoNATClientConfig -> Int
ancMaxPeers :: !Int
  {- ^ Maximum peers queried in one cycle. Requests are sequential, so the
  number of outstanding requests is always at most one.
  -}
  }
  deriving (Int -> AutoNATClientConfig -> ShowS
[AutoNATClientConfig] -> ShowS
AutoNATClientConfig -> String
(Int -> AutoNATClientConfig -> ShowS)
-> (AutoNATClientConfig -> String)
-> ([AutoNATClientConfig] -> ShowS)
-> Show AutoNATClientConfig
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AutoNATClientConfig -> ShowS
showsPrec :: Int -> AutoNATClientConfig -> ShowS
$cshow :: AutoNATClientConfig -> String
show :: AutoNATClientConfig -> String
$cshowList :: [AutoNATClientConfig] -> ShowS
showList :: [AutoNATClientConfig] -> ShowS
Show, AutoNATClientConfig -> AutoNATClientConfig -> Bool
(AutoNATClientConfig -> AutoNATClientConfig -> Bool)
-> (AutoNATClientConfig -> AutoNATClientConfig -> Bool)
-> Eq AutoNATClientConfig
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AutoNATClientConfig -> AutoNATClientConfig -> Bool
== :: AutoNATClientConfig -> AutoNATClientConfig -> Bool
$c/= :: AutoNATClientConfig -> AutoNATClientConfig -> Bool
/= :: AutoNATClientConfig -> AutoNATClientConfig -> Bool
Eq)

{- | go-libp2p scheduling defaults, with four peers per cycle to satisfy the
AutoNAT v1 requirement for more than three agreeing dial reports.
-}
defaultAutoNATClientConfig :: AutoNATClientConfig
defaultAutoNATClientConfig :: AutoNATClientConfig
defaultAutoNATClientConfig =
  AutoNATClientConfig
    { ancThreshold :: Int
ancThreshold = Int
3
    , ancBootDelayMicros :: Int
ancBootDelayMicros = Int
15 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
    , ancRetryIntervalMicros :: Int
ancRetryIntervalMicros = Int
90 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
    , ancRefreshIntervalMicros :: Int
ancRefreshIntervalMicros = Int
15 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
minute
    , ancRequestTimeoutMicros :: Int
ancRequestTimeoutMicros = Int
30 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
    , ancPeerThrottleMicros :: Int
ancPeerThrottleMicros = Int
90 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second
    , ancMaxPeers :: Int
ancMaxPeers = Int
4
    }
 where
  second :: Int
second = Int
1000000
  minute :: Int
minute = Int
60 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
second

-- | Handle for observing and stopping the background client.
data AutoNATClientService = AutoNATClientService
  { AutoNATClientService -> TVar NATStatus
acsStatus :: !(TVar NATStatus)
  , AutoNATClientService -> Async ()
acsWorker :: !(Async ())
  }

-- | Start periodic reachability probing and attach its lifetime to the Switch.
startAutoNATClient :: Switch -> AutoNATClientConfig -> IO AutoNATClientService
startAutoNATClient :: Switch -> AutoNATClientConfig -> IO AutoNATClientService
startAutoNATClient Switch
sw AutoNATClientConfig
config = do
  AutoNATClientConfig -> IO ()
validateConfig AutoNATClientConfig
config
  status <- NATStatus -> IO (TVar NATStatus)
forall a. a -> IO (TVar a)
newTVarIO NATStatus
NATUnknown
  recent <- newTVarIO Map.empty
  worker <- async (clientLoop sw config status recent)
  let service = TVar NATStatus -> Async () -> AutoNATClientService
AutoNATClientService TVar NATStatus
status Async ()
worker
  registerSwitchShutdownAction sw (stopAutoNATClient service)
  pure service

-- | Read the most recently aggregated reachability status.
autoNATClientStatus :: AutoNATClientService -> IO NATStatus
autoNATClientStatus :: AutoNATClientService -> IO NATStatus
autoNATClientStatus AutoNATClientService
service = STM NATStatus -> IO NATStatus
forall a. STM a -> IO a
atomically (STM NATStatus -> IO NATStatus) -> STM NATStatus -> IO NATStatus
forall a b. (a -> b) -> a -> b
$ TVar NATStatus -> STM NATStatus
forall a. TVar a -> STM a
readTVar (AutoNATClientService -> TVar NATStatus
acsStatus AutoNATClientService
service)

-- | Stop the client and cancel any in-flight request.
stopAutoNATClient :: AutoNATClientService -> IO ()
stopAutoNATClient :: AutoNATClientService -> IO ()
stopAutoNATClient = Async () -> IO ()
forall a. Async a -> IO ()
cancel (Async () -> IO ())
-> (AutoNATClientService -> Async ())
-> AutoNATClientService
-> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AutoNATClientService -> Async ()
acsWorker

validateConfig :: AutoNATClientConfig -> IO ()
validateConfig :: AutoNATClientConfig -> IO ()
validateConfig AutoNATClientConfig
config
  | AutoNATClientConfig -> Int
ancThreshold AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"threshold must be non-negative"
  | AutoNATClientConfig -> Int
ancBootDelayMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"boot delay must be non-negative"
  | AutoNATClientConfig -> Int
ancRetryIntervalMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"retry interval must be non-negative"
  | AutoNATClientConfig -> Int
ancRefreshIntervalMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"refresh interval must be non-negative"
  | AutoNATClientConfig -> Int
ancRequestTimeoutMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"request timeout must be positive"
  | AutoNATClientConfig -> Int
ancPeerThrottleMicros AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 = String -> IO ()
forall {a}. String -> IO a
invalid String
"peer throttle must be non-negative"
  | AutoNATClientConfig -> Int
ancMaxPeers AutoNATClientConfig
config Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= AutoNATClientConfig -> Int
ancThreshold AutoNATClientConfig
config =
      String -> IO ()
forall {a}. String -> IO a
invalid String
"max peers must be greater than the decision threshold"
  | Bool
otherwise = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
 where
  invalid :: String -> IO a
invalid = IOError -> IO a
forall a. IOError -> IO a
ioError (IOError -> IO a) -> (String -> IOError) -> String -> IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IOError
userError (String -> IOError) -> ShowS -> String -> IOError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String
"invalid AutoNAT client configuration: " String -> ShowS
forall a. [a] -> [a] -> [a]
++)

clientLoop ::
  Switch ->
  AutoNATClientConfig ->
  TVar NATStatus ->
  TVar (Map.Map PeerId UTCTime) ->
  IO ()
clientLoop :: Switch
-> AutoNATClientConfig
-> TVar NATStatus
-> TVar (Map PeerId UTCTime)
-> IO ()
clientLoop Switch
sw AutoNATClientConfig
config TVar NATStatus
status TVar (Map PeerId UTCTime)
recent = do
  Int -> IO ()
threadDelay (AutoNATClientConfig -> Int
ancBootDelayMicros AutoNATClientConfig
config)
  IO () -> IO ()
forall (f :: * -> *) a b. Applicative f => f a -> f b
forever (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
    result <- Switch
-> AutoNATClientConfig -> TVar (Map PeerId UTCTime) -> IO NATStatus
runProbeCycle Switch
sw AutoNATClientConfig
config TVar (Map PeerId UTCTime)
recent
    atomically $ writeTVar status result
    threadDelay $ case result of
      NATStatus
NATUnknown -> AutoNATClientConfig -> Int
ancRetryIntervalMicros AutoNATClientConfig
config
      NATStatus
_ -> AutoNATClientConfig -> Int
ancRefreshIntervalMicros AutoNATClientConfig
config

runProbeCycle ::
  Switch ->
  AutoNATClientConfig ->
  TVar (Map.Map PeerId UTCTime) ->
  IO NATStatus
runProbeCycle :: Switch
-> AutoNATClientConfig -> TVar (Map PeerId UTCTime) -> IO NATStatus
runProbeCycle Switch
sw AutoNATClientConfig
config TVar (Map PeerId UTCTime)
recentVar = do
  now <- IO UTCTime
getCurrentTime
  connections <- connectedProbeCandidates sw
  recent <- atomically $ readTVar recentVar
  let oldestFirst = (Connection -> Maybe UTCTime) -> [Connection] -> [Connection]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\Connection
conn -> PeerId -> Map PeerId UTCTime -> Maybe UTCTime
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Connection -> PeerId
connPeerId Connection
conn) Map PeerId UTCTime
recent) [Connection]
connections
      eligible =
        Int -> [Connection] -> [Connection]
forall a. Int -> [a] -> [a]
take
          (AutoNATClientConfig -> Int
ancMaxPeers AutoNATClientConfig
config)
          ((Connection -> Bool) -> [Connection] -> [Connection]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Connection -> Bool) -> Connection -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AutoNATClientConfig
-> UTCTime -> Map PeerId UTCTime -> PeerId -> Bool
throttled AutoNATClientConfig
config UTCTime
now Map PeerId UTCTime
recent (PeerId -> Bool) -> (Connection -> PeerId) -> Connection -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Connection -> PeerId
connPeerId) [Connection]
oldestFirst)
      updated = (Connection -> Map PeerId UTCTime -> Map PeerId UTCTime)
-> Map PeerId UTCTime -> [Connection] -> Map PeerId UTCTime
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (\Connection
conn -> PeerId -> UTCTime -> Map PeerId UTCTime -> Map PeerId UTCTime
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (Connection -> PeerId
connPeerId Connection
conn) UTCTime
now) Map PeerId UTCTime
recent [Connection]
eligible
      connectedPeers = [PeerId] -> Set PeerId
forall a. Ord a => [a] -> Set a
Set.fromList ((Connection -> PeerId) -> [Connection] -> [PeerId]
forall a b. (a -> b) -> [a] -> [b]
map Connection -> PeerId
connPeerId [Connection]
connections)
  atomically $ writeTVar recentVar (Map.restrictKeys updated connectedPeers)
  addrs <- switchListenAddrs sw
  results <- mapM (probePeer sw config addrs) eligible
  pure (probeNATStatusPure (ancThreshold config) results)

connectedProbeCandidates :: Switch -> IO [Connection]
connectedProbeCandidates :: Switch -> IO [Connection]
connectedProbeCandidates Switch
sw = STM [Connection] -> IO [Connection]
forall a. STM a -> IO a
atomically (STM [Connection] -> IO [Connection])
-> STM [Connection] -> IO [Connection]
forall a b. (a -> b) -> a -> b
$ do
  connections <- TVar (Map PeerId [Connection]) -> STM [Connection]
allConns (Switch -> TVar (Map PeerId [Connection])
swConnPool Switch
sw)
  openDirect <- filterM isOpenDirect connections
  pure (Map.elems (Map.fromList [(connPeerId conn, conn) | conn <- openDirect]))
 where
  isOpenDirect :: Connection -> STM Bool
isOpenDirect Connection
conn = do
    state <- TVar ConnState -> STM ConnState
forall a. TVar a -> STM a
readTVar (Connection -> TVar ConnState
connState Connection
conn)
    pure (state == ConnOpen && not (isRelayedAddr (connRemoteAddr conn)))

probePeer ::
  Switch ->
  AutoNATClientConfig ->
  [Multiaddr] ->
  Connection ->
  IO (Either String AutoNATDialResponse)
probePeer :: Switch
-> AutoNATClientConfig
-> [Multiaddr]
-> Connection
-> IO (Either String AutoNATDialResponse)
probePeer Switch
sw AutoNATClientConfig
config [Multiaddr]
addrs Connection
conn = do
  outcome <- (SomeException -> Maybe SomeException)
-> IO (Maybe (Either String AutoNATDialResponse))
-> IO
     (Either SomeException (Maybe (Either String AutoNATDialResponse)))
forall e b a.
Exception e =>
(e -> Maybe b) -> IO a -> IO (Either b a)
tryJust SomeException -> Maybe SomeException
synchronousException (IO (Maybe (Either String AutoNATDialResponse))
 -> IO
      (Either SomeException (Maybe (Either String AutoNATDialResponse))))
-> IO (Maybe (Either String AutoNATDialResponse))
-> IO
     (Either SomeException (Maybe (Either String AutoNATDialResponse)))
forall a b. (a -> b) -> a -> b
$ Int
-> IO (Either String AutoNATDialResponse)
-> IO (Maybe (Either String AutoNATDialResponse))
forall a. Int -> IO a -> IO (Maybe a)
timeout (AutoNATClientConfig -> Int
ancRequestTimeoutMicros AutoNATClientConfig
config) (IO (Either String AutoNATDialResponse)
 -> IO (Maybe (Either String AutoNATDialResponse)))
-> IO (Either String AutoNATDialResponse)
-> IO (Maybe (Either String AutoNATDialResponse))
forall a b. (a -> b) -> a -> b
$ do
    opened <- Switch -> Connection -> IO (Either StreamOpenError StreamIO)
newStream Switch
sw Connection
conn
    case opened of
      Left StreamOpenError
err -> Either String AutoNATDialResponse
-> IO (Either String AutoNATDialResponse)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (String -> Either String AutoNATDialResponse
forall a b. a -> Either a b
Left (StreamOpenError -> String
forall a. Show a => a -> String
show StreamOpenError
err))
      Right StreamIO
stream -> IO StreamIO
-> (StreamIO -> IO ())
-> (StreamIO -> IO (Either String AutoNATDialResponse))
-> IO (Either String AutoNATDialResponse)
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket (StreamIO -> IO StreamIO
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure StreamIO
stream) StreamIO -> IO ()
closeQuietly ((StreamIO -> IO (Either String AutoNATDialResponse))
 -> IO (Either String AutoNATDialResponse))
-> (StreamIO -> IO (Either String AutoNATDialResponse))
-> IO (Either String AutoNATDialResponse)
forall a b. (a -> b) -> a -> b
$ \StreamIO
openedStream -> do
        negotiated <- StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiateInitiator StreamIO
openedStream [ProtocolId
autoNATProtocolId]
        case negotiated of
          NegotiationResult
NoProtocol -> Either String AutoNATDialResponse
-> IO (Either String AutoNATDialResponse)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (String -> Either String AutoNATDialResponse
forall a b. a -> Either a b
Left String
"peer does not support AutoNAT v1")
          Accepted ProtocolId
_ -> StreamIO
-> PeerId -> [Multiaddr] -> IO (Either String AutoNATDialResponse)
requestAutoNAT StreamIO
openedStream (Switch -> PeerId
swLocalPeerId Switch
sw) [Multiaddr]
addrs
  pure $ case outcome of
    Left (SomeException
err :: SomeException) -> String -> Either String AutoNATDialResponse
forall a b. a -> Either a b
Left (SomeException -> String
forall a. Show a => a -> String
show SomeException
err)
    Right Maybe (Either String AutoNATDialResponse)
Nothing -> String -> Either String AutoNATDialResponse
forall a b. a -> Either a b
Left String
"AutoNAT request timed out"
    Right (Just Either String AutoNATDialResponse
result) -> Either String AutoNATDialResponse
result

throttled ::
  AutoNATClientConfig ->
  UTCTime ->
  Map.Map PeerId UTCTime ->
  PeerId ->
  Bool
throttled :: AutoNATClientConfig
-> UTCTime -> Map PeerId UTCTime -> PeerId -> Bool
throttled AutoNATClientConfig
config UTCTime
now Map PeerId UTCTime
recent PeerId
peerId =
  case PeerId -> Map PeerId UTCTime -> Maybe UTCTime
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PeerId
peerId Map PeerId UTCTime
recent of
    Maybe UTCTime
Nothing -> Bool
False
    Just UTCTime
probedAt -> UTCTime -> UTCTime -> Int
elapsedMicros UTCTime
now UTCTime
probedAt Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< AutoNATClientConfig -> Int
ancPeerThrottleMicros AutoNATClientConfig
config

synchronousException :: SomeException -> Maybe SomeException
synchronousException :: SomeException -> Maybe SomeException
synchronousException SomeException
err = case SomeException -> Maybe SomeAsyncException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
err :: Maybe SomeAsyncException of
  Just SomeAsyncException
_ -> Maybe SomeException
forall a. Maybe a
Nothing
  Maybe SomeAsyncException
Nothing -> SomeException -> Maybe SomeException
forall a. a -> Maybe a
Just SomeException
err

elapsedMicros :: UTCTime -> UTCTime -> Int
elapsedMicros :: UTCTime -> UTCTime -> Int
elapsedMicros UTCTime
later UTCTime
earlier = Double -> Int
forall b. Integral b => Double -> b
forall a b. (RealFrac a, Integral b) => a -> b
floor (NominalDiffTime -> Double
forall a b. (Real a, Fractional b) => a -> b
realToFrac (UTCTime -> UTCTime -> NominalDiffTime
diffUTCTime UTCTime
later UTCTime
earlier) Double -> Double -> Double
forall a. Num a => a -> a -> a
* (Double
1000000 :: Double))