2022-07-01 18:19:57 +00:00
|
|
|
# Nim-LibP2P
|
2024-03-03 17:13:37 +00:00
|
|
|
# Copyright (c) 2023-2024 Status Research & Development GmbH
|
2022-07-01 18:19:57 +00:00
|
|
|
# Licensed under either of
|
|
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
# at your option.
|
|
|
|
# This file may not be copied, modified, or distributed except according to
|
|
|
|
# those terms.
|
|
|
|
|
|
|
|
## TCP transport implementation
|
2019-08-20 16:18:15 +00:00
|
|
|
|
2023-06-07 11:12:49 +00:00
|
|
|
{.push raises: [].}
|
2021-05-21 16:27:01 +00:00
|
|
|
|
2023-05-18 08:24:17 +00:00
|
|
|
import std/[sequtils]
|
2020-11-19 02:06:42 +00:00
|
|
|
import chronos, chronicles
|
2024-05-14 05:10:34 +00:00
|
|
|
import
|
|
|
|
./transport,
|
|
|
|
../wire,
|
|
|
|
../multiaddress,
|
|
|
|
../stream/connection,
|
|
|
|
../stream/chronosstream,
|
|
|
|
../upgrademngrs/upgrade,
|
|
|
|
../utility
|
2019-08-20 16:18:15 +00:00
|
|
|
|
2019-09-12 00:15:04 +00:00
|
|
|
logScope:
|
2020-12-01 17:34:27 +00:00
|
|
|
topics = "libp2p tcptransport"
|
2019-09-12 00:15:04 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
export transport, connection, upgrade
|
2020-11-28 08:05:12 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
const TcpTransportTrackerName* = "libp2p.tcptransport"
|
2020-04-21 01:24:42 +00:00
|
|
|
|
|
|
|
type
|
2024-05-14 05:10:34 +00:00
|
|
|
AcceptFuture = typeof(default(StreamServer).accept())
|
|
|
|
|
2020-04-21 01:24:42 +00:00
|
|
|
TcpTransport* = ref object of Transport
|
2021-11-24 20:01:12 +00:00
|
|
|
servers*: seq[StreamServer]
|
2020-11-19 02:06:42 +00:00
|
|
|
clients: array[Direction, seq[StreamTransport]]
|
2020-05-18 19:04:05 +00:00
|
|
|
flags: set[ServerFlags]
|
2023-04-06 13:23:35 +00:00
|
|
|
clientFlags: set[SocketFlags]
|
2024-05-14 05:10:34 +00:00
|
|
|
acceptFuts: seq[AcceptFuture]
|
2023-06-07 12:27:32 +00:00
|
|
|
connectionsTimeout: Duration
|
2024-05-14 05:10:34 +00:00
|
|
|
stopping: bool
|
2020-04-21 01:24:42 +00:00
|
|
|
|
2023-04-06 13:23:35 +00:00
|
|
|
TcpTransportError* = object of transport.TransportError
|
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
proc connHandler*(
|
|
|
|
self: TcpTransport,
|
|
|
|
client: StreamTransport,
|
|
|
|
observedAddr: Opt[MultiAddress],
|
|
|
|
dir: Direction,
|
|
|
|
): Connection =
|
|
|
|
trace "Handling tcp connection",
|
|
|
|
address = $observedAddr,
|
|
|
|
dir = $dir,
|
|
|
|
clients = self.clients[Direction.In].len + self.clients[Direction.Out].len
|
2020-11-01 22:23:26 +00:00
|
|
|
|
|
|
|
let conn = Connection(
|
|
|
|
ChronosStream.init(
|
2020-11-25 19:34:48 +00:00
|
|
|
client = client,
|
|
|
|
dir = dir,
|
2023-06-07 12:27:32 +00:00
|
|
|
observedAddr = observedAddr,
|
2024-05-14 05:10:34 +00:00
|
|
|
timeout = self.connectionsTimeout,
|
|
|
|
)
|
|
|
|
)
|
2020-11-01 22:23:26 +00:00
|
|
|
|
2024-03-01 17:06:26 +00:00
|
|
|
proc onClose() {.async: (raises: []).} =
|
2024-05-14 05:10:34 +00:00
|
|
|
await noCancel client.join()
|
2020-11-25 13:35:25 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
trace "Cleaning up client", addrs = $client.remoteAddress, conn
|
2020-11-19 02:06:42 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
self.clients[dir].keepItIf(it != client)
|
2024-03-01 17:06:26 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
# Propagate the chronos client being closed to the connection
|
|
|
|
# TODO This is somewhat dubious since it's the connection that owns the
|
|
|
|
# client, but it allows the transport to close all connections when
|
|
|
|
# shutting down (also dubious! it would make more sense that the owner
|
|
|
|
# of all connections closes them, or the next read detects the closed
|
|
|
|
# socket and does the right thing..)
|
2020-11-19 02:06:42 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
await conn.close()
|
2020-11-19 02:06:42 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
trace "Cleaned up client", addrs = $client.remoteAddress, conn
|
2020-05-23 17:10:01 +00:00
|
|
|
|
2021-03-18 15:20:36 +00:00
|
|
|
self.clients[dir].add(client)
|
2024-05-14 05:10:34 +00:00
|
|
|
|
2020-11-19 02:06:42 +00:00
|
|
|
asyncSpawn onClose()
|
2020-11-02 20:35:26 +00:00
|
|
|
|
2020-11-19 02:06:42 +00:00
|
|
|
return conn
|
|
|
|
|
2021-06-30 08:59:30 +00:00
|
|
|
proc new*(
|
2024-05-14 05:10:34 +00:00
|
|
|
T: typedesc[TcpTransport],
|
|
|
|
flags: set[ServerFlags] = {},
|
|
|
|
upgrade: Upgrade,
|
|
|
|
connectionsTimeout = 10.minutes,
|
|
|
|
): T {.public.} =
|
|
|
|
T(
|
|
|
|
flags: flags,
|
|
|
|
clientFlags:
|
|
|
|
if ServerFlags.TcpNoDelay in flags:
|
|
|
|
{SocketFlags.TcpNoDelay}
|
|
|
|
else:
|
|
|
|
default(set[SocketFlags])
|
|
|
|
,
|
|
|
|
upgrader: upgrade,
|
|
|
|
networkReachability: NetworkReachability.Unknown,
|
|
|
|
connectionsTimeout: connectionsTimeout,
|
|
|
|
)
|
|
|
|
|
|
|
|
method start*(self: TcpTransport, addrs: seq[MultiAddress]): Future[void] =
|
|
|
|
## Start transport listening to the given addresses - for dial-only transports,
|
|
|
|
## start with an empty list
|
|
|
|
|
|
|
|
# TODO remove `impl` indirection throughout when `raises` is added to base
|
|
|
|
|
|
|
|
proc impl(
|
|
|
|
self: TcpTransport, addrs: seq[MultiAddress]
|
|
|
|
): Future[void] {.async: (raises: [transport.TransportError, CancelledError]).} =
|
|
|
|
if self.running:
|
|
|
|
warn "TCP transport already running"
|
|
|
|
return
|
2020-05-18 17:05:34 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
trace "Starting TCP transport"
|
2020-04-21 01:24:42 +00:00
|
|
|
|
2023-04-06 13:23:35 +00:00
|
|
|
self.flags.incl(ServerFlags.ReusePort)
|
2020-04-21 01:24:42 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
var supported: seq[MultiAddress]
|
|
|
|
var initialized = false
|
|
|
|
try:
|
|
|
|
for i, ma in addrs:
|
|
|
|
if not self.handles(ma):
|
|
|
|
trace "Invalid address detected, skipping!", address = ma
|
|
|
|
continue
|
2021-11-24 20:01:12 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
let
|
|
|
|
ta = initTAddress(ma).expect("valid address per handles check above")
|
|
|
|
server =
|
|
|
|
try:
|
|
|
|
createStreamServer(ta, flags = self.flags)
|
|
|
|
except common.TransportError as exc:
|
|
|
|
raise (ref TcpTransportError)(msg: exc.msg, parent: exc)
|
|
|
|
|
|
|
|
self.servers &= server
|
|
|
|
|
|
|
|
trace "Listening on", address = ma
|
|
|
|
supported.add(
|
|
|
|
MultiAddress.init(server.sock.getLocalAddress()).expect(
|
|
|
|
"Can init from local address"
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
initialized = true
|
|
|
|
finally:
|
|
|
|
if not initialized:
|
|
|
|
# Clean up partial success on exception
|
|
|
|
await noCancel allFutures(self.servers.mapIt(it.closeWait()))
|
|
|
|
reset(self.servers)
|
2021-11-24 20:01:12 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
try:
|
|
|
|
await procCall Transport(self).start(supported)
|
|
|
|
except CatchableError:
|
|
|
|
raiseAssert "Base method does not raise"
|
2020-11-19 02:06:42 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
trackCounter(TcpTransportTrackerName)
|
2020-04-11 04:08:25 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
impl(self, addrs)
|
2019-08-20 16:18:15 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
method stop*(self: TcpTransport): Future[void] =
|
|
|
|
## Stop the transport and close all connections it created
|
|
|
|
proc impl(self: TcpTransport) {.async: (raises: []).} =
|
|
|
|
trace "Stopping TCP transport"
|
|
|
|
self.stopping = true
|
|
|
|
defer:
|
|
|
|
self.stopping = false
|
|
|
|
|
|
|
|
if self.running:
|
|
|
|
# Reset the running flag
|
|
|
|
try:
|
|
|
|
await noCancel procCall Transport(self).stop()
|
|
|
|
except CatchableError: # TODO remove when `accept` is annotated with raises
|
|
|
|
raiseAssert "doesn't actually raise"
|
|
|
|
|
|
|
|
# Stop each server by closing the socket - this will cause all accept loops
|
|
|
|
# to fail - since the running flag has been reset, it's also safe to close
|
|
|
|
# all known clients since no more of them will be added
|
|
|
|
await noCancel allFutures(
|
|
|
|
self.servers.mapIt(it.closeWait()) &
|
|
|
|
self.clients[Direction.In].mapIt(it.closeWait()) &
|
|
|
|
self.clients[Direction.Out].mapIt(it.closeWait())
|
|
|
|
)
|
|
|
|
|
|
|
|
self.servers = @[]
|
|
|
|
|
|
|
|
for acceptFut in self.acceptFuts:
|
|
|
|
if acceptFut.completed():
|
|
|
|
await acceptFut.value().closeWait()
|
|
|
|
self.acceptFuts = @[]
|
|
|
|
|
|
|
|
if self.clients[Direction.In].len != 0 or self.clients[Direction.Out].len != 0:
|
|
|
|
# Future updates could consider turning this warn into an assert since
|
|
|
|
# it should never happen if the shutdown code is correct
|
|
|
|
warn "Couldn't clean up clients",
|
|
|
|
len = self.clients[Direction.In].len + self.clients[Direction.Out].len
|
|
|
|
|
|
|
|
trace "Transport stopped"
|
|
|
|
untrackCounter(TcpTransportTrackerName)
|
|
|
|
else:
|
|
|
|
# For legacy reasons, `stop` on a transpart that wasn't started is
|
|
|
|
# expected to close outgoing connections created by the transport
|
2022-08-01 12:31:22 +00:00
|
|
|
warn "TCP transport already stopped"
|
2021-11-24 20:01:12 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
doAssert self.clients[Direction.In].len == 0,
|
|
|
|
"No incoming connections possible without start"
|
|
|
|
await noCancel allFutures(self.clients[Direction.Out].mapIt(it.closeWait()))
|
2021-11-24 20:01:12 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
impl(self)
|
2020-11-19 02:06:42 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
method accept*(self: TcpTransport): Future[Connection] =
|
|
|
|
## accept a new TCP connection, returning nil on non-fatal errors
|
2020-11-19 02:06:42 +00:00
|
|
|
##
|
2024-05-14 05:10:34 +00:00
|
|
|
## Raises an exception when the transport is broken and cannot be used for
|
|
|
|
## accepting further connections
|
|
|
|
# TODO returning nil for non-fatal errors is problematic in that error
|
|
|
|
# information is lost and must be logged here instead of being
|
|
|
|
# available to the caller - further refactoring should propagate errors
|
|
|
|
# to the caller instead
|
|
|
|
proc impl(
|
|
|
|
self: TcpTransport
|
|
|
|
): Future[Connection] {.async: (raises: [transport.TransportError, CancelledError]).} =
|
|
|
|
if not self.running:
|
|
|
|
raise newTransportClosedError()
|
2021-11-24 20:01:12 +00:00
|
|
|
|
|
|
|
if self.acceptFuts.len <= 0:
|
2024-05-14 05:10:34 +00:00
|
|
|
self.acceptFuts = self.servers.mapIt(it.accept())
|
2021-11-24 20:01:12 +00:00
|
|
|
|
|
|
|
let
|
2024-05-14 05:10:34 +00:00
|
|
|
finished =
|
|
|
|
try:
|
|
|
|
await one(self.acceptFuts)
|
|
|
|
except ValueError:
|
|
|
|
raise (ref TcpTransportError)(msg: "No listeners configured")
|
|
|
|
|
2021-11-24 20:01:12 +00:00
|
|
|
index = self.acceptFuts.find(finished)
|
2024-05-14 05:10:34 +00:00
|
|
|
transp =
|
|
|
|
try:
|
|
|
|
await finished
|
|
|
|
except TransportTooManyError as exc:
|
|
|
|
debug "Too many files opened", exc = exc.msg
|
|
|
|
return nil
|
|
|
|
except TransportAbortedError as exc:
|
|
|
|
debug "Connection aborted", exc = exc.msg
|
|
|
|
return nil
|
|
|
|
except TransportUseClosedError as exc:
|
|
|
|
raise newTransportClosedError(exc)
|
|
|
|
except TransportOsError as exc:
|
|
|
|
raise (ref TcpTransportError)(msg: exc.msg, parent: exc)
|
|
|
|
except common.TransportError as exc: # Needed for chronos 4.0.0 support
|
|
|
|
raise (ref TcpTransportError)(msg: exc.msg, parent: exc)
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
|
|
|
|
if not self.running: # Stopped while waiting
|
|
|
|
await transp.closeWait()
|
|
|
|
raise newTransportClosedError()
|
2021-11-24 20:01:12 +00:00
|
|
|
|
|
|
|
self.acceptFuts[index] = self.servers[index].accept()
|
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
let remote =
|
|
|
|
try:
|
|
|
|
transp.remoteAddress
|
|
|
|
except TransportOsError as exc:
|
|
|
|
# The connection had errors / was closed before `await` returned control
|
|
|
|
await transp.closeWait()
|
|
|
|
debug "Cannot read remote address", exc = exc.msg
|
|
|
|
return nil
|
2019-08-20 16:18:15 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
let observedAddr =
|
|
|
|
MultiAddress.init(remote).expect("Can initialize from remote address")
|
|
|
|
self.connHandler(transp, Opt.some(observedAddr), Direction.In)
|
2020-11-19 02:06:42 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
impl(self)
|
2019-08-22 00:23:13 +00:00
|
|
|
|
2024-05-14 05:10:34 +00:00
|
|
|
method dial*(
|
|
|
|
self: TcpTransport,
|
|
|
|
hostname: string,
|
|
|
|
address: MultiAddress,
|
|
|
|
peerId: Opt[PeerId] = Opt.none(PeerId),
|
|
|
|
): Future[Connection] =
|
|
|
|
## dial a peer
|
|
|
|
proc impl(
|
|
|
|
self: TcpTransport, hostname: string, address: MultiAddress, peerId: Opt[PeerId]
|
|
|
|
): Future[Connection] {.async: (raises: [transport.TransportError, CancelledError]).} =
|
|
|
|
if self.stopping:
|
|
|
|
raise newTransportClosedError()
|
|
|
|
|
|
|
|
let ta = initTAddress(address).valueOr:
|
|
|
|
raise (ref TcpTransportError)(msg: "Unsupported address: " & $address)
|
|
|
|
|
|
|
|
trace "Dialing remote peer", address = $address
|
|
|
|
let transp =
|
|
|
|
try:
|
|
|
|
await(
|
|
|
|
if self.networkReachability == NetworkReachability.NotReachable and
|
|
|
|
self.addrs.len > 0:
|
|
|
|
let local = initTAddress(self.addrs[0]).expect("self address is valid")
|
|
|
|
self.clientFlags.incl(SocketFlags.ReusePort)
|
|
|
|
connect(ta, flags = self.clientFlags, localAddress = local)
|
|
|
|
else:
|
|
|
|
connect(ta, flags = self.clientFlags)
|
|
|
|
)
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
raise (ref TcpTransportError)(msg: exc.msg, parent: exc)
|
|
|
|
|
|
|
|
# If `stop` is called after `connect` but before `await` returns, we might
|
|
|
|
# end up with a race condition where `stop` returns but not all connections
|
|
|
|
# have been closed - we drop connections in this case in order not to leak
|
|
|
|
# them
|
|
|
|
if self.stopping:
|
|
|
|
# Stopped while waiting for new connection
|
|
|
|
await transp.closeWait()
|
|
|
|
raise newTransportClosedError()
|
|
|
|
|
|
|
|
let observedAddr =
|
|
|
|
try:
|
|
|
|
MultiAddress.init(transp.remoteAddress).expect("remote address is valid")
|
|
|
|
except TransportOsError as exc:
|
|
|
|
await transp.closeWait()
|
|
|
|
raise (ref TcpTransportError)(msg: exc.msg)
|
|
|
|
|
|
|
|
self.connHandler(transp, Opt.some(observedAddr), Direction.Out)
|
|
|
|
|
|
|
|
impl(self, hostname, address, peerId)
|
|
|
|
|
|
|
|
method handles*(t: TcpTransport, address: MultiAddress): bool =
|
2019-12-04 04:44:54 +00:00
|
|
|
if procCall Transport(t).handles(address):
|
2021-05-21 16:27:01 +00:00
|
|
|
if address.protocols.isOk:
|
2024-05-08 12:33:26 +00:00
|
|
|
return TCP.match(address)
|