2019-08-27 21:46:12 +00:00
|
|
|
## Nim-LibP2P
|
2019-09-24 17:48:23 +00:00
|
|
|
## Copyright (c) 2019 Status Research & Development GmbH
|
2019-08-27 21:46:12 +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.
|
|
|
|
|
2020-06-24 15:08:44 +00:00
|
|
|
import tables,
|
|
|
|
sequtils,
|
|
|
|
options,
|
|
|
|
sets,
|
2020-07-08 00:33:05 +00:00
|
|
|
algorithm,
|
|
|
|
oids
|
2020-06-24 15:08:44 +00:00
|
|
|
|
|
|
|
import chronos,
|
|
|
|
chronicles,
|
|
|
|
metrics
|
|
|
|
|
2020-06-19 17:29:43 +00:00
|
|
|
import stream/connection,
|
2019-09-11 19:03:30 +00:00
|
|
|
transports/transport,
|
|
|
|
multistream,
|
2020-06-17 04:14:02 +00:00
|
|
|
multiaddress,
|
2019-09-06 07:13:47 +00:00
|
|
|
protocols/protocol,
|
2019-09-14 13:55:52 +00:00
|
|
|
protocols/secure/secure,
|
2019-09-11 19:03:30 +00:00
|
|
|
peerinfo,
|
|
|
|
protocols/identify,
|
|
|
|
protocols/pubsub/pubsub,
|
2019-09-06 07:13:47 +00:00
|
|
|
muxers/muxer,
|
2020-07-01 06:25:09 +00:00
|
|
|
peerid
|
2019-08-28 19:12:15 +00:00
|
|
|
|
2019-09-12 02:10:38 +00:00
|
|
|
logScope:
|
2020-06-10 08:48:01 +00:00
|
|
|
topics = "switch"
|
2019-09-12 02:10:38 +00:00
|
|
|
|
2019-12-04 04:44:54 +00:00
|
|
|
#TODO: General note - use a finite state machine to manage the different
|
2019-12-08 21:06:58 +00:00
|
|
|
# steps of connections establishing and upgrading. This makes everything
|
|
|
|
# more robust and less prone to ordering attacks - i.e. muxing can come if
|
|
|
|
# and only if the channel has been secured (i.e. if a secure manager has been
|
2019-12-04 04:44:54 +00:00
|
|
|
# previously provided)
|
|
|
|
|
2020-06-16 20:43:45 +00:00
|
|
|
declareGauge(libp2p_peers, "total connected peers")
|
2020-06-11 14:45:59 +00:00
|
|
|
declareCounter(libp2p_dialed_peers, "dialed peers")
|
|
|
|
declareCounter(libp2p_failed_dials, "failed dials")
|
|
|
|
declareCounter(libp2p_failed_upgrade, "peers failed upgrade")
|
|
|
|
|
2020-06-24 15:08:44 +00:00
|
|
|
const MaxConnectionsPerPeer = 5
|
|
|
|
|
2019-08-28 19:12:15 +00:00
|
|
|
type
|
2020-06-24 15:08:44 +00:00
|
|
|
NoPubSubException* = object of CatchableError
|
|
|
|
TooManyConnections* = object of CatchableError
|
|
|
|
|
|
|
|
Direction {.pure.} = enum
|
|
|
|
In, Out
|
|
|
|
|
|
|
|
ConnectionHolder = object
|
|
|
|
dir: Direction
|
|
|
|
conn: Connection
|
|
|
|
|
|
|
|
MuxerHolder = object
|
|
|
|
dir: Direction
|
|
|
|
muxer: Muxer
|
|
|
|
handle: Future[void]
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2019-08-28 19:12:15 +00:00
|
|
|
Switch* = ref object of RootObj
|
2019-08-30 05:17:07 +00:00
|
|
|
peerInfo*: PeerInfo
|
2020-06-24 15:08:44 +00:00
|
|
|
connections*: Table[string, seq[ConnectionHolder]]
|
|
|
|
muxed*: Table[string, seq[MuxerHolder]]
|
2019-08-30 05:17:07 +00:00
|
|
|
transports*: seq[Transport]
|
|
|
|
protocols*: seq[LPProtocol]
|
2019-09-04 22:00:39 +00:00
|
|
|
muxers*: Table[string, MuxerProvider]
|
2020-02-04 16:16:21 +00:00
|
|
|
ms*: MultistreamSelect
|
2019-09-04 01:50:17 +00:00
|
|
|
identity*: Identify
|
2019-09-06 07:13:47 +00:00
|
|
|
streamHandler*: StreamHandler
|
2020-06-01 17:49:25 +00:00
|
|
|
secureManagers*: seq[Secure]
|
2019-09-11 19:03:30 +00:00
|
|
|
pubSub*: Option[PubSub]
|
2020-06-24 15:08:44 +00:00
|
|
|
dialLock: Table[string, AsyncLock]
|
2020-07-08 00:33:05 +00:00
|
|
|
cleanUpLock: Table[string, AsyncLock]
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-06-24 15:08:44 +00:00
|
|
|
proc newNoPubSubException(): ref NoPubSubException {.inline.} =
|
2019-09-11 19:03:30 +00:00
|
|
|
result = newException(NoPubSubException, "no pubsub provided!")
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2020-06-24 15:08:44 +00:00
|
|
|
proc newTooManyConnections(): ref TooManyConnections {.inline.} =
|
|
|
|
result = newException(TooManyConnections, "too many connections for peer")
|
|
|
|
|
|
|
|
proc disconnect*(s: Switch, peer: PeerInfo) {.async, gcsafe.}
|
2020-07-08 00:33:05 +00:00
|
|
|
proc subscribePeer*(s: Switch, peerInfo: PeerInfo) {.async, gcsafe.}
|
2020-06-24 15:08:44 +00:00
|
|
|
|
|
|
|
proc selectConn(s: Switch, peerInfo: PeerInfo): Connection =
|
|
|
|
## select the "best" connection according to some criteria
|
|
|
|
##
|
|
|
|
## Ideally when the connection's stats are available
|
|
|
|
## we'd select the fastest, but for now we simply pick an outgoing
|
|
|
|
## connection first if none is available, we pick the first outgoing
|
|
|
|
##
|
|
|
|
|
|
|
|
if isNil(peerInfo):
|
|
|
|
return
|
|
|
|
|
|
|
|
let conns = s.connections
|
|
|
|
.getOrDefault(peerInfo.id)
|
|
|
|
# it should be OK to sort on each
|
|
|
|
# access as there should only be
|
|
|
|
# up to MaxConnectionsPerPeer entries
|
|
|
|
.sorted(
|
|
|
|
proc(a, b: ConnectionHolder): int =
|
|
|
|
if a.dir < b.dir: -1
|
|
|
|
elif a.dir == b.dir: 0
|
|
|
|
else: 1
|
|
|
|
, SortOrder.Descending)
|
|
|
|
|
|
|
|
if conns.len > 0:
|
|
|
|
return conns[0].conn
|
|
|
|
|
|
|
|
proc selectMuxer(s: Switch, conn: Connection): Muxer =
|
|
|
|
## select the muxer for the supplied connection
|
|
|
|
##
|
|
|
|
|
|
|
|
if isNil(conn):
|
|
|
|
return
|
|
|
|
|
|
|
|
if not(isNil(conn.peerInfo)) and conn.peerInfo.id in s.muxed:
|
|
|
|
if s.muxed[conn.peerInfo.id].len > 0:
|
|
|
|
let muxers = s.muxed[conn.peerInfo.id]
|
|
|
|
.filterIt( it.muxer.connection == conn )
|
|
|
|
if muxers.len > 0:
|
|
|
|
return muxers[0].muxer
|
|
|
|
|
|
|
|
proc storeConn(s: Switch,
|
|
|
|
muxer: Muxer,
|
|
|
|
dir: Direction,
|
|
|
|
handle: Future[void] = nil) {.async.} =
|
|
|
|
## store the connection and muxer
|
|
|
|
##
|
2020-06-29 15:15:31 +00:00
|
|
|
if isNil(muxer):
|
|
|
|
return
|
|
|
|
|
|
|
|
let conn = muxer.connection
|
|
|
|
if isNil(conn):
|
|
|
|
return
|
|
|
|
|
|
|
|
let id = conn.peerInfo.id
|
|
|
|
if s.connections.getOrDefault(id).len > MaxConnectionsPerPeer:
|
|
|
|
warn "disconnecting peer, too many connections", peer = $conn.peerInfo,
|
|
|
|
conns = s.connections
|
|
|
|
.getOrDefault(id).len
|
|
|
|
await s.disconnect(conn.peerInfo)
|
|
|
|
raise newTooManyConnections()
|
|
|
|
|
|
|
|
s.connections.mgetOrPut(
|
|
|
|
id,
|
|
|
|
newSeq[ConnectionHolder]())
|
|
|
|
.add(ConnectionHolder(conn: conn, dir: dir))
|
|
|
|
|
|
|
|
s.muxed.mgetOrPut(
|
|
|
|
muxer.connection.peerInfo.id,
|
|
|
|
newSeq[MuxerHolder]())
|
|
|
|
.add(MuxerHolder(muxer: muxer, handle: handle, dir: dir))
|
2020-06-24 15:08:44 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
trace "storred connection", connections = s.connections.len
|
|
|
|
libp2p_peers.set(s.connections.len.int64)
|
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc secure(s: Switch, conn: Connection): Future[Connection] {.async, gcsafe.} =
|
2020-06-01 17:49:25 +00:00
|
|
|
if s.secureManagers.len <= 0:
|
2019-09-09 23:17:45 +00:00
|
|
|
raise newException(CatchableError, "No secure managers registered!")
|
|
|
|
|
2020-06-01 17:49:25 +00:00
|
|
|
let manager = await s.ms.select(conn, s.secureManagers.mapIt(it.codec))
|
2020-06-22 21:38:48 +00:00
|
|
|
if manager.len == 0:
|
2019-09-06 07:13:47 +00:00
|
|
|
raise newException(CatchableError, "Unable to negotiate a secure channel!")
|
2019-09-09 23:17:45 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
trace "securing connection", codec = manager
|
2020-06-20 10:56:55 +00:00
|
|
|
let secureProtocol = s.secureManagers.filterIt(it.codec == manager)
|
|
|
|
# ms.select should deal with the correctness of this
|
|
|
|
# let's avoid duplicating checks but detect if it fails to do it properly
|
2020-06-21 09:14:19 +00:00
|
|
|
doAssert(secureProtocol.len > 0)
|
2020-06-20 10:56:55 +00:00
|
|
|
result = await secureProtocol[0].secure(conn, true)
|
2019-08-31 17:58:49 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
proc identify(s: Switch, conn: Connection) {.async, gcsafe.} =
|
2019-09-04 01:50:17 +00:00
|
|
|
## identify the connection
|
2019-09-28 19:54:32 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if (await s.ms.select(conn, s.identity.codec)):
|
|
|
|
let info = await s.identity.identify(conn, conn.peerInfo)
|
2019-12-07 16:36:39 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if info.pubKey.isNone and isNil(conn):
|
|
|
|
raise newException(CatchableError,
|
|
|
|
"no public key provided and no existing peer identity found")
|
2019-12-10 20:50:35 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if isNil(conn.peerInfo):
|
|
|
|
conn.peerInfo = PeerInfo.init(info.pubKey.get())
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if info.addrs.len > 0:
|
|
|
|
conn.peerInfo.addrs = info.addrs
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if info.agentVersion.isSome:
|
|
|
|
conn.peerInfo.agentVersion = info.agentVersion.get()
|
2020-06-09 18:42:52 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if info.protoVersion.isSome:
|
|
|
|
conn.peerInfo.protoVersion = info.protoVersion.get()
|
2020-06-09 18:42:52 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if info.protos.len > 0:
|
|
|
|
conn.peerInfo.protocols = info.protos
|
2020-06-11 14:45:59 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
trace "identify: identified remote peer", peer = $conn.peerInfo
|
2019-09-06 07:13:47 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
proc mux(s: Switch, conn: Connection) {.async, gcsafe.} =
|
2019-09-04 01:50:17 +00:00
|
|
|
## mux incoming connection
|
2019-09-28 19:54:32 +00:00
|
|
|
|
2020-06-21 09:14:19 +00:00
|
|
|
trace "muxing connection", peer = $conn
|
2019-09-04 22:00:39 +00:00
|
|
|
let muxers = toSeq(s.muxers.keys)
|
2019-09-13 20:04:46 +00:00
|
|
|
if muxers.len == 0:
|
2019-09-23 21:51:28 +00:00
|
|
|
warn "no muxers registered, skipping upgrade flow"
|
2019-09-13 20:04:46 +00:00
|
|
|
return
|
|
|
|
|
2019-09-04 22:00:39 +00:00
|
|
|
let muxerName = await s.ms.select(conn, muxers)
|
2019-09-06 07:13:47 +00:00
|
|
|
if muxerName.len == 0 or muxerName == "na":
|
2020-06-21 09:14:19 +00:00
|
|
|
debug "no muxer available, early exit", peer = $conn
|
2019-09-04 22:00:39 +00:00
|
|
|
return
|
|
|
|
|
2019-09-14 15:55:58 +00:00
|
|
|
# create new muxer for connection
|
2019-09-04 22:00:39 +00:00
|
|
|
let muxer = s.muxers[muxerName].newMuxer(conn)
|
2020-06-20 10:56:55 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
trace "found a muxer", name = muxerName, peer = $conn
|
2020-06-20 10:56:55 +00:00
|
|
|
|
2019-09-04 22:00:39 +00:00
|
|
|
# install stream handler
|
2019-09-06 07:13:47 +00:00
|
|
|
muxer.streamHandler = s.streamHandler
|
2019-09-04 22:00:39 +00:00
|
|
|
|
2019-09-14 15:55:58 +00:00
|
|
|
# new stream for identify
|
2019-12-04 04:44:54 +00:00
|
|
|
var stream = await muxer.newStream()
|
2020-06-29 15:15:31 +00:00
|
|
|
var handlerFut: Future[void]
|
|
|
|
|
|
|
|
defer:
|
|
|
|
if not(isNil(stream)):
|
|
|
|
await stream.close() # close identify stream
|
|
|
|
|
2020-06-08 23:42:27 +00:00
|
|
|
# call muxer handler, this should
|
|
|
|
# not end until muxer ends
|
2020-06-29 15:15:31 +00:00
|
|
|
handlerFut = muxer.handle()
|
2019-09-08 07:43:33 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
# do identify first, so that we have a
|
|
|
|
# PeerInfo in case we didn't before
|
|
|
|
await s.identify(stream)
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-06-24 15:08:44 +00:00
|
|
|
if isNil(conn.peerInfo):
|
|
|
|
await muxer.close()
|
2020-06-29 15:15:31 +00:00
|
|
|
raise newException(CatchableError,
|
|
|
|
"unable to identify peer, aborting upgrade")
|
2020-06-24 15:08:44 +00:00
|
|
|
|
2019-09-05 15:19:39 +00:00
|
|
|
# store it in muxed connections if we have a peer for it
|
2020-06-24 15:08:44 +00:00
|
|
|
trace "adding muxer for peer", peer = conn.peerInfo.id
|
|
|
|
await s.storeConn(muxer, Direction.Out, handlerFut)
|
2019-09-04 22:00:39 +00:00
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
proc cleanupConn(s: Switch, conn: Connection) {.async, gcsafe.} =
|
2020-06-29 15:15:31 +00:00
|
|
|
if isNil(conn):
|
|
|
|
return
|
|
|
|
|
|
|
|
if isNil(conn.peerInfo):
|
|
|
|
return
|
|
|
|
|
|
|
|
let id = conn.peerInfo.id
|
2020-07-08 00:33:05 +00:00
|
|
|
let lock = s.cleanUpLock.mgetOrPut(id, newAsyncLock())
|
2020-06-24 15:08:44 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
try:
|
|
|
|
await lock.acquire()
|
|
|
|
trace "cleaning up connection for peer", peerId = id
|
2020-06-29 15:15:31 +00:00
|
|
|
if id in s.muxed:
|
2020-07-08 00:33:05 +00:00
|
|
|
let muxerHolder = s.muxed[id]
|
|
|
|
.filterIt(
|
|
|
|
it.muxer.connection == conn
|
|
|
|
)
|
|
|
|
|
|
|
|
if muxerHolder.len > 0:
|
|
|
|
await muxerHolder[0].muxer.close()
|
|
|
|
if not(isNil(muxerHolder[0].handle)):
|
|
|
|
await muxerHolder[0].handle
|
|
|
|
|
|
|
|
if id in s.muxed:
|
|
|
|
s.muxed[id].keepItIf(
|
|
|
|
it.muxer.connection != conn
|
|
|
|
)
|
|
|
|
|
|
|
|
if s.muxed[id].len == 0:
|
|
|
|
s.muxed.del(id)
|
|
|
|
|
|
|
|
if s.pubSub.isSome:
|
|
|
|
await s.pubSub.get()
|
|
|
|
.unsubscribePeer(conn.peerInfo)
|
|
|
|
|
|
|
|
if id in s.connections:
|
|
|
|
s.connections[id].keepItIf(
|
|
|
|
it.conn != conn
|
2020-06-24 15:08:44 +00:00
|
|
|
)
|
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
if s.connections[id].len == 0:
|
|
|
|
s.connections.del(id)
|
2020-05-23 17:12:28 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
# TODO: Investigate cleanupConn() always called twice for one peer.
|
|
|
|
if not(conn.peerInfo.isClosed()):
|
|
|
|
conn.peerInfo.close()
|
|
|
|
finally:
|
|
|
|
await conn.close()
|
2020-07-09 20:21:47 +00:00
|
|
|
libp2p_peers.set(s.connections.len.int64)
|
2020-05-23 17:12:28 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
if lock.locked():
|
|
|
|
lock.release()
|
2020-05-23 17:12:28 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc disconnect*(s: Switch, peer: PeerInfo) {.async, gcsafe.} =
|
2020-06-24 15:08:44 +00:00
|
|
|
let connections = s.connections.getOrDefault(peer.id)
|
|
|
|
for connHolder in connections:
|
|
|
|
if not isNil(connHolder.conn):
|
|
|
|
await s.cleanupConn(connHolder.conn)
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2019-12-10 20:50:35 +00:00
|
|
|
proc getMuxedStream(s: Switch, peerInfo: PeerInfo): Future[Connection] {.async, gcsafe.} =
|
2019-09-28 19:54:32 +00:00
|
|
|
# if there is a muxer for the connection
|
|
|
|
# use it instead to create a muxed stream
|
2020-06-24 15:08:44 +00:00
|
|
|
|
|
|
|
let muxer = s.selectMuxer(s.selectConn(peerInfo)) # always get the first muxer here
|
|
|
|
if not(isNil(muxer)):
|
|
|
|
return await muxer.newStream()
|
2019-09-28 19:54:32 +00:00
|
|
|
|
2019-09-12 12:02:25 +00:00
|
|
|
proc upgradeOutgoing(s: Switch, conn: Connection): Future[Connection] {.async, gcsafe.} =
|
2020-06-29 15:15:31 +00:00
|
|
|
logScope:
|
|
|
|
conn = $conn
|
|
|
|
oid = $conn.oid
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-06-24 15:08:44 +00:00
|
|
|
let sconn = await s.secure(conn) # secure the connection
|
|
|
|
if isNil(sconn):
|
2020-06-29 15:15:31 +00:00
|
|
|
raise newException(CatchableError,
|
|
|
|
"unable to secure connection, stopping upgrade")
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
trace "upgrading connection"
|
2020-06-24 15:08:44 +00:00
|
|
|
await s.mux(sconn) # mux it if possible
|
2020-06-29 15:15:31 +00:00
|
|
|
if isNil(sconn.peerInfo):
|
2020-06-24 15:08:44 +00:00
|
|
|
await sconn.close()
|
2020-06-29 15:15:31 +00:00
|
|
|
raise newException(CatchableError,
|
|
|
|
"unable to mux connection, stopping upgrade")
|
2019-12-13 15:25:07 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
trace "succesfully upgraded outgoing connection", uoid = sconn.oid
|
|
|
|
return sconn
|
2019-09-04 22:00:39 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc upgradeIncoming(s: Switch, conn: Connection) {.async, gcsafe.} =
|
2020-06-24 15:08:44 +00:00
|
|
|
trace "upgrading incoming connection", conn = $conn, oid = conn.oid
|
2019-09-28 19:54:32 +00:00
|
|
|
let ms = newMultistream()
|
2019-09-04 01:50:17 +00:00
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
# secure incoming connections
|
|
|
|
proc securedHandler (conn: Connection,
|
|
|
|
proto: string)
|
|
|
|
{.async, gcsafe, closure.} =
|
2020-06-29 15:15:31 +00:00
|
|
|
|
|
|
|
var sconn: Connection
|
|
|
|
trace "Securing connection", oid = conn.oid
|
|
|
|
let secure = s.secureManagers.filterIt(it.codec == proto)[0]
|
|
|
|
|
2020-05-15 03:56:56 +00:00
|
|
|
try:
|
2020-06-29 15:15:31 +00:00
|
|
|
sconn = await secure.secure(conn, false)
|
|
|
|
if isNil(sconn):
|
2020-05-15 03:56:56 +00:00
|
|
|
return
|
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
defer:
|
|
|
|
await sconn.close()
|
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
# add the muxer
|
|
|
|
for muxer in s.muxers.values:
|
|
|
|
ms.addHandler(muxer.codec, muxer)
|
|
|
|
|
2020-05-15 03:56:56 +00:00
|
|
|
# handle subsequent requests
|
2020-06-29 15:15:31 +00:00
|
|
|
await ms.handle(sconn)
|
2020-05-23 17:12:28 +00:00
|
|
|
|
2020-05-15 03:56:56 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "ending secured handler", err = exc.msg
|
2019-09-28 19:54:32 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if (await ms.select(conn)): # just handshake
|
|
|
|
# add the secure handlers
|
|
|
|
for k in s.secureManagers:
|
|
|
|
ms.addHandler(k.codec, securedHandler)
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
# handle secured connections
|
|
|
|
await ms.handle(conn)
|
2020-02-21 01:14:39 +00:00
|
|
|
|
2020-02-25 22:13:05 +00:00
|
|
|
proc internalConnect(s: Switch,
|
|
|
|
peer: PeerInfo): Future[Connection] {.async.} =
|
2020-06-24 15:08:44 +00:00
|
|
|
|
|
|
|
if s.peerInfo.peerId == peer.peerId:
|
|
|
|
raise newException(CatchableError, "can't dial self!")
|
|
|
|
|
2019-12-04 04:44:54 +00:00
|
|
|
let id = peer.id
|
2020-06-24 15:08:44 +00:00
|
|
|
var conn: Connection
|
2020-07-08 00:33:05 +00:00
|
|
|
let lock = s.dialLock.mgetOrPut(id, newAsyncLock())
|
2020-05-23 17:12:28 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
defer:
|
2020-06-24 15:08:44 +00:00
|
|
|
if lock.locked():
|
|
|
|
lock.release()
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
await lock.acquire()
|
|
|
|
trace "about to dial peer", peer = id
|
|
|
|
conn = s.selectConn(peer)
|
|
|
|
if conn.isNil or conn.closed:
|
|
|
|
trace "Dialing peer", peer = id
|
|
|
|
for t in s.transports: # for each transport
|
|
|
|
for a in peer.addrs: # for each address
|
|
|
|
if t.handles(a): # check if it can dial it
|
|
|
|
trace "Dialing address", address = $a
|
|
|
|
try:
|
|
|
|
conn = await t.dial(a)
|
|
|
|
libp2p_dialed_peers.inc()
|
|
|
|
except CancelledError as exc:
|
|
|
|
trace "dialing canceled", exc = exc.msg
|
|
|
|
raise
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "dialing failed", exc = exc.msg
|
|
|
|
libp2p_failed_dials.inc()
|
|
|
|
continue
|
|
|
|
|
|
|
|
# make sure to assign the peer to the connection
|
|
|
|
conn.peerInfo = peer
|
|
|
|
try:
|
|
|
|
conn = await s.upgradeOutgoing(conn)
|
|
|
|
except CatchableError as exc:
|
|
|
|
if not(isNil(conn)):
|
|
|
|
await conn.close()
|
|
|
|
|
|
|
|
trace "Unable to establish outgoing link", exc = exc.msg
|
|
|
|
raise exc
|
|
|
|
|
|
|
|
if isNil(conn):
|
|
|
|
libp2p_failed_upgrade.inc()
|
|
|
|
continue
|
|
|
|
|
|
|
|
conn.closeEvent.wait()
|
|
|
|
.addCallback do(udata: pointer):
|
|
|
|
asyncCheck s.cleanupConn(conn)
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
trace "Reusing existing connection", oid = conn.oid
|
|
|
|
|
|
|
|
if isNil(conn):
|
|
|
|
raise newException(CatchableError,
|
|
|
|
"Unable to establish outgoing link")
|
|
|
|
|
|
|
|
if conn.closed or conn.atEof:
|
|
|
|
await conn.close()
|
|
|
|
raise newException(CatchableError,
|
|
|
|
"Connection dead on arrival")
|
|
|
|
|
|
|
|
doAssert(conn.peerInfo.id in s.connections,
|
|
|
|
"connection not tracked!")
|
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
trace "dial succesfull", oid = $conn.oid,
|
|
|
|
peer = $conn.peerInfo
|
|
|
|
|
|
|
|
await s.subscribePeer(peer)
|
2020-06-29 15:15:31 +00:00
|
|
|
return conn
|
2020-02-25 22:13:05 +00:00
|
|
|
|
|
|
|
proc connect*(s: Switch, peer: PeerInfo) {.async.} =
|
2020-07-08 00:33:05 +00:00
|
|
|
discard await s.internalConnect(peer)
|
2020-02-25 22:13:05 +00:00
|
|
|
|
|
|
|
proc dial*(s: Switch,
|
|
|
|
peer: PeerInfo,
|
|
|
|
proto: string):
|
|
|
|
Future[Connection] {.async.} =
|
2020-07-08 00:33:05 +00:00
|
|
|
let conn = await s.internalConnect(peer)
|
2020-02-25 22:13:05 +00:00
|
|
|
let stream = await s.getMuxedStream(peer)
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
proc cleanup() {.async.} =
|
|
|
|
if not(isNil(stream)):
|
|
|
|
await stream.close()
|
|
|
|
|
|
|
|
if not(isNil(conn)):
|
|
|
|
await conn.close()
|
|
|
|
|
|
|
|
try:
|
|
|
|
if isNil(stream):
|
|
|
|
await conn.close()
|
|
|
|
raise newException(CatchableError, "Couldn't get muxed stream")
|
2020-02-21 01:14:39 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
trace "Attempting to select remote", proto = proto, oid = conn.oid
|
|
|
|
if not await s.ms.select(stream, proto):
|
|
|
|
await stream.close()
|
|
|
|
raise newException(CatchableError, "Unable to select sub-protocol " & proto)
|
|
|
|
|
|
|
|
return stream
|
|
|
|
except CancelledError as exc:
|
|
|
|
trace "dial canceled"
|
|
|
|
await cleanup()
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "error dialing"
|
|
|
|
await cleanup()
|
|
|
|
raise exc
|
2020-06-29 15:15:31 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc mount*[T: LPProtocol](s: Switch, proto: T) {.gcsafe.} =
|
2019-08-31 17:58:49 +00:00
|
|
|
if isNil(proto.handler):
|
2019-12-04 04:44:54 +00:00
|
|
|
raise newException(CatchableError,
|
2020-06-27 17:33:34 +00:00
|
|
|
"Protocol has to define a handle method or proc")
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-09-06 07:13:47 +00:00
|
|
|
if proto.codec.len == 0:
|
2019-12-04 04:44:54 +00:00
|
|
|
raise newException(CatchableError,
|
2020-06-27 17:33:34 +00:00
|
|
|
"Protocol has to define a codec string")
|
2019-08-31 18:52:56 +00:00
|
|
|
|
2019-08-31 17:58:49 +00:00
|
|
|
s.ms.addHandler(proto.codec, proto)
|
2019-08-28 02:30:53 +00:00
|
|
|
|
2020-05-05 15:55:02 +00:00
|
|
|
proc start*(s: Switch): Future[seq[Future[void]]] {.async, gcsafe.} =
|
2020-06-09 18:42:52 +00:00
|
|
|
trace "starting switch for peer", peerInfo = shortLog(s.peerInfo)
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2019-08-31 18:52:56 +00:00
|
|
|
proc handle(conn: Connection): Future[void] {.async, closure, gcsafe.} =
|
2019-09-04 22:00:39 +00:00
|
|
|
try:
|
2020-06-29 15:15:31 +00:00
|
|
|
defer:
|
2020-05-23 17:12:28 +00:00
|
|
|
await s.cleanupConn(conn)
|
2020-06-29 15:15:31 +00:00
|
|
|
|
|
|
|
await s.upgradeIncoming(conn) # perform upgrade on incoming connection
|
2020-05-15 03:56:56 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2019-12-04 04:44:54 +00:00
|
|
|
except CatchableError as exc:
|
2020-03-27 14:25:52 +00:00
|
|
|
trace "Exception occurred in Switch.start", exc = exc.msg
|
2020-02-25 22:13:05 +00:00
|
|
|
|
2019-09-12 00:15:04 +00:00
|
|
|
var startFuts: seq[Future[void]]
|
2019-08-28 02:30:53 +00:00
|
|
|
for t in s.transports: # for each transport
|
2019-09-28 19:54:32 +00:00
|
|
|
for i, a in s.peerInfo.addrs:
|
2019-08-28 02:30:53 +00:00
|
|
|
if t.handles(a): # check if it handles the multiaddr
|
2020-05-05 15:55:02 +00:00
|
|
|
var server = await t.listen(a, handle)
|
2019-09-28 19:54:32 +00:00
|
|
|
s.peerInfo.addrs[i] = t.ma # update peer's address
|
2019-09-12 00:15:04 +00:00
|
|
|
startFuts.add(server)
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
if s.pubSub.isSome:
|
|
|
|
await s.pubSub.get().start()
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-06-24 15:08:44 +00:00
|
|
|
info "started libp2p node", peer = $s.peerInfo, addrs = s.peerInfo.addrs
|
2019-09-12 00:15:04 +00:00
|
|
|
result = startFuts # listen for incoming connections
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc stop*(s: Switch) {.async.} =
|
2020-06-29 15:15:31 +00:00
|
|
|
trace "stopping switch"
|
|
|
|
|
|
|
|
# we want to report errors but we do not want to fail
|
|
|
|
# or crash here, cos we need to clean possibly MANY items
|
|
|
|
# and any following conn/transport won't be cleaned up
|
|
|
|
if s.pubSub.isSome:
|
|
|
|
await s.pubSub.get().stop()
|
|
|
|
|
|
|
|
for conns in toSeq(s.connections.values):
|
|
|
|
for conn in conns:
|
2020-05-27 20:46:25 +00:00
|
|
|
try:
|
2020-06-29 15:15:31 +00:00
|
|
|
await s.cleanupConn(conn.conn)
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2020-05-27 20:46:25 +00:00
|
|
|
except CatchableError as exc:
|
2020-06-29 15:15:31 +00:00
|
|
|
warn "error cleaning up connections"
|
2019-09-06 07:13:47 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
for t in s.transports:
|
|
|
|
try:
|
|
|
|
await t.close()
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
warn "error cleaning up transports"
|
|
|
|
|
|
|
|
trace "switch stopped"
|
2020-04-21 01:24:42 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
proc subscribePeer*(s: Switch, peerInfo: PeerInfo) {.async, gcsafe.} =
|
2019-09-12 02:10:38 +00:00
|
|
|
## Subscribe to pub sub peer
|
2020-06-29 15:15:31 +00:00
|
|
|
if s.pubSub.isSome and not(s.pubSub.get().connected(peerInfo)):
|
|
|
|
trace "about to subscribe to pubsub peer", peer = peerInfo.shortLog()
|
|
|
|
var stream: Connection
|
|
|
|
try:
|
|
|
|
stream = await s.getMuxedStream(peerInfo)
|
|
|
|
except CancelledError as exc:
|
|
|
|
if not(isNil(stream)):
|
|
|
|
await stream.close()
|
|
|
|
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "exception in subscribe to peer", peer = peerInfo.shortLog,
|
|
|
|
exc = exc.msg
|
|
|
|
if not(isNil(stream)):
|
|
|
|
await stream.close()
|
|
|
|
|
|
|
|
if isNil(stream):
|
2020-06-19 17:29:25 +00:00
|
|
|
trace "unable to subscribe to peer", peer = peerInfo.shortLog
|
|
|
|
return
|
2020-06-18 02:12:32 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
if not await s.ms.select(stream, s.pubSub.get().codec):
|
|
|
|
if not(isNil(stream)):
|
|
|
|
await stream.close()
|
|
|
|
return
|
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
s.pubSub.get().subscribePeer(stream)
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-03-04 19:45:14 +00:00
|
|
|
proc subscribe*(s: Switch, topic: string,
|
|
|
|
handler: TopicHandler): Future[void] =
|
2019-09-12 02:10:38 +00:00
|
|
|
## subscribe to a pubsub topic
|
2019-09-11 19:03:30 +00:00
|
|
|
if s.pubSub.isNone:
|
2020-03-04 19:45:14 +00:00
|
|
|
var retFuture = newFuture[void]("Switch.subscribe")
|
|
|
|
retFuture.fail(newNoPubSubException())
|
|
|
|
return retFuture
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
return s.pubSub.get().subscribe(topic, handler)
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-03-04 19:45:14 +00:00
|
|
|
proc unsubscribe*(s: Switch, topics: seq[TopicPair]): Future[void] =
|
2019-09-12 02:10:38 +00:00
|
|
|
## unsubscribe from topics
|
2019-09-11 19:03:30 +00:00
|
|
|
if s.pubSub.isNone:
|
2020-03-04 19:45:14 +00:00
|
|
|
var retFuture = newFuture[void]("Switch.unsubscribe")
|
|
|
|
retFuture.fail(newNoPubSubException())
|
|
|
|
return retFuture
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
return s.pubSub.get().unsubscribe(topics)
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
proc publish*(s: Switch, topic: string, data: seq[byte]): Future[int] =
|
2019-09-12 02:10:38 +00:00
|
|
|
# pubslish to pubsub topic
|
2019-09-11 19:03:30 +00:00
|
|
|
if s.pubSub.isNone:
|
2020-07-08 00:33:05 +00:00
|
|
|
var retFuture = newFuture[int]("Switch.publish")
|
2020-03-04 19:45:14 +00:00
|
|
|
retFuture.fail(newNoPubSubException())
|
|
|
|
return retFuture
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
return s.pubSub.get().publish(topic, data)
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
proc addValidator*(s: Switch,
|
|
|
|
topics: varargs[string],
|
|
|
|
hook: ValidatorHandler) =
|
|
|
|
# add validator
|
|
|
|
if s.pubSub.isNone:
|
|
|
|
raise newNoPubSubException()
|
|
|
|
|
|
|
|
s.pubSub.get().addValidator(topics, hook)
|
|
|
|
|
|
|
|
proc removeValidator*(s: Switch,
|
|
|
|
topics: varargs[string],
|
|
|
|
hook: ValidatorHandler) =
|
|
|
|
# pubslish to pubsub topic
|
|
|
|
if s.pubSub.isNone:
|
|
|
|
raise newNoPubSubException()
|
|
|
|
|
|
|
|
s.pubSub.get().removeValidator(topics, hook)
|
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
proc muxerHandler(s: Switch, muxer: Muxer) {.async, gcsafe.} =
|
|
|
|
var stream = await muxer.newStream()
|
|
|
|
defer:
|
|
|
|
if not(isNil(stream)):
|
|
|
|
await stream.close()
|
|
|
|
|
|
|
|
try:
|
|
|
|
# once we got a muxed connection, attempt to
|
|
|
|
# identify it
|
|
|
|
await s.identify(stream)
|
|
|
|
if isNil(stream.peerInfo):
|
|
|
|
await muxer.close()
|
|
|
|
return
|
|
|
|
|
|
|
|
muxer.connection.peerInfo = stream.peerInfo
|
|
|
|
|
|
|
|
# store muxer and muxed connection
|
|
|
|
await s.storeConn(muxer, Direction.In)
|
|
|
|
|
|
|
|
muxer.connection.closeEvent.wait()
|
|
|
|
.addCallback do(udata: pointer):
|
|
|
|
asyncCheck s.cleanupConn(muxer.connection)
|
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
trace "got new muxer", peer = $muxer.connection.peerInfo
|
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
# try establishing a pubsub connection
|
2020-07-08 00:33:05 +00:00
|
|
|
await s.subscribePeer(muxer.connection.peerInfo)
|
2020-06-29 15:15:31 +00:00
|
|
|
|
|
|
|
except CancelledError as exc:
|
|
|
|
await muxer.close()
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
await muxer.close()
|
|
|
|
libp2p_failed_upgrade.inc()
|
|
|
|
trace "exception in muxer handler", exc = exc.msg
|
|
|
|
|
2019-09-06 07:13:47 +00:00
|
|
|
proc newSwitch*(peerInfo: PeerInfo,
|
|
|
|
transports: seq[Transport],
|
|
|
|
identity: Identify,
|
2019-09-09 17:33:32 +00:00
|
|
|
muxers: Table[string, MuxerProvider],
|
2020-06-01 06:41:32 +00:00
|
|
|
secureManagers: openarray[Secure] = [],
|
2019-09-11 19:03:30 +00:00
|
|
|
pubSub: Option[PubSub] = none(PubSub)): Switch =
|
2020-07-07 11:14:11 +00:00
|
|
|
if secureManagers.len == 0:
|
|
|
|
raise (ref CatchableError)(msg: "Provide at least one secure manager")
|
|
|
|
|
|
|
|
result = Switch(
|
|
|
|
peerInfo: peerInfo,
|
|
|
|
ms: newMultistream(),
|
|
|
|
transports: transports,
|
|
|
|
connections: initTable[string, seq[ConnectionHolder]](),
|
|
|
|
muxed: initTable[string, seq[MuxerHolder]](),
|
|
|
|
identity: identity,
|
|
|
|
muxers: muxers,
|
|
|
|
secureManagers: @secureManagers,
|
|
|
|
)
|
2019-09-06 07:13:47 +00:00
|
|
|
|
|
|
|
let s = result # can't capture result
|
2019-12-08 21:06:58 +00:00
|
|
|
result.streamHandler = proc(stream: Connection) {.async, gcsafe.} =
|
2020-05-23 19:25:53 +00:00
|
|
|
try:
|
2020-06-09 18:42:52 +00:00
|
|
|
trace "handling connection for", peerInfo = $stream
|
2020-06-29 15:15:31 +00:00
|
|
|
defer:
|
|
|
|
if not(isNil(stream)):
|
2020-05-23 19:25:53 +00:00
|
|
|
await stream.close()
|
2020-06-29 15:15:31 +00:00
|
|
|
await s.ms.handle(stream) # handle incoming connection
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2020-05-23 19:25:53 +00:00
|
|
|
except CatchableError as exc:
|
2020-06-02 17:32:42 +00:00
|
|
|
trace "exception in stream handler", exc = exc.msg
|
2019-09-06 07:13:47 +00:00
|
|
|
|
|
|
|
result.mount(identity)
|
|
|
|
for key, val in muxers:
|
|
|
|
val.streamHandler = result.streamHandler
|
2020-06-29 15:15:31 +00:00
|
|
|
val.muxerHandler = proc(muxer: Muxer): Future[void] =
|
|
|
|
s.muxerHandler(muxer)
|
2020-05-21 17:33:48 +00:00
|
|
|
|
2019-09-11 19:03:30 +00:00
|
|
|
if pubSub.isSome:
|
|
|
|
result.pubSub = pubSub
|
|
|
|
result.mount(pubSub.get())
|