nim-libp2p/libp2p/switch.nim

164 lines
5.6 KiB
Nim
Raw Normal View History

2019-08-27 21:46:12 +00:00
## Nim-LibP2P
## Copyright (c) 2018 Status Research & Development GmbH
## 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.
2019-09-04 22:00:39 +00:00
import tables, sequtils, options, strformat
2019-08-27 21:46:12 +00:00
import chronos
2019-09-01 17:31:24 +00:00
import connection, transport,
stream/lpstream,
2019-08-31 17:58:49 +00:00
multistream, protocol,
2019-09-04 01:50:17 +00:00
peerinfo, multiaddress,
2019-09-04 22:00:39 +00:00
identify, muxers/muxer,
peer
type
Switch* = ref object of RootObj
2019-08-30 05:17:07 +00:00
peerInfo*: PeerInfo
connections*: TableRef[string, Connection]
2019-09-04 22:00:39 +00:00
muxed*: TableRef[string, Muxer]
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]
2019-08-30 05:17:07 +00:00
ms*: MultisteamSelect
2019-09-04 01:50:17 +00:00
identity*: Identify
2019-08-27 21:46:12 +00:00
2019-09-04 22:00:39 +00:00
proc handleConn(s: Switch, conn: Connection): Future[Connection] {.async, gcsafe.}
2019-09-04 01:50:17 +00:00
proc newSwitch*(peerInfo: PeerInfo,
transports: seq[Transport],
identity: Identify,
2019-09-04 22:00:39 +00:00
muxers: Table[string, MuxerProvider]): Switch =
2019-08-28 02:30:53 +00:00
new result
result.peerInfo = peerInfo
result.ms = newMultistream()
result.transports = transports
result.connections = newTable[string, Connection]()
2019-09-04 22:00:39 +00:00
result.muxed = newTable[string, Muxer]()
2019-09-04 01:50:17 +00:00
result.identity = identity
result.muxers = muxers
result.ms.addHandler(IdentifyCodec, identity)
2019-08-31 17:58:49 +00:00
proc secure(s: Switch, conn: Connection) {.async, gcsafe.} =
## secure the incoming connection
discard
2019-09-04 22:00:39 +00:00
proc identify(s: Switch, conn: Connection) {.async, gcsafe.} =
2019-09-04 01:50:17 +00:00
## identify the connection
2019-09-04 22:00:39 +00:00
s.peerInfo.protocols = await s.ms.list(conn) # update protos before engagin in identify
let info = await s.identity.identify(conn, conn.peerInfo)
let id = if conn.peerInfo.isSome: conn.peerInfo.get().peerId.pretty else: ""
if s.connections.contains(id):
let connection = s.connections[id]
var peerInfo = conn.peerInfo.get()
peerInfo.peerId = PeerID.init(info.pubKey) # we might not have a peerId at all
peerInfo.addrs = info.addrs
peerInfo.protocols = info.protos
2019-09-04 01:50:17 +00:00
2019-09-04 22:00:39 +00:00
proc mux(s: Switch, conn: Connection): Future[void] {.async, gcsafe.} =
2019-09-04 01:50:17 +00:00
## mux incoming connection
2019-09-04 22:00:39 +00:00
let muxers = toSeq(s.muxers.keys)
let muxerName = await s.ms.select(conn, muxers)
if muxerName.len == 0:
return
let muxer = s.muxers[muxerName].newMuxer(conn)
# install stream handler
muxer.streamHandler = proc (stream: Connection) {.async, gcsafe.} =
try:
2019-09-05 15:19:39 +00:00
# TODO: figure out proper way of handling this.
# Perhaps it's ok to discard this Future and handle
# errors elsewere?
asyncCheck s.ms.handle(stream) # handle incoming connection
2019-09-04 22:00:39 +00:00
finally:
await stream.close()
# do identify first, so that we have a
# PeerInfo in case we didn't before
let stream = await muxer.newStream()
await s.identify(stream)
2019-09-04 01:50:17 +00:00
2019-09-05 15:19:39 +00:00
# store it in muxed connections if we have a peer for it
# TODO: We should make sure that this are cleaned up properly
# on exit even if there is no peer for it. This shouldn't
# happen once secio is in place, but still something to keep
# in mind
2019-09-04 22:00:39 +00:00
if conn.peerInfo.isSome:
s.muxed[conn.peerInfo.get().peerId.pretty] = muxer
proc handleConn(s: Switch, conn: Connection): Future[Connection] {.async, gcsafe.} =
2019-09-04 01:50:17 +00:00
## perform upgrade flow
2019-09-04 22:00:39 +00:00
if conn.peerInfo.isSome:
let id = conn.peerInfo.get().peerId.pretty
if s.connections.contains(id):
# if we already have a connection for this peer,
# close the incoming connection and return the
# existing one
await conn.close()
return s.connections[id]
s.connections[id] = conn
await s.secure(conn) # secure the connection
2019-09-05 15:19:39 +00:00
# await s.mux(conn) # mux it if possible
2019-09-04 22:00:39 +00:00
result = conn
proc cleanupConn(s: Switch, conn: Connection) {.async, gcsafe.} =
let id = if conn.peerInfo.isSome: conn.peerInfo.get().peerId.pretty else: ""
if conn.peerInfo.isSome:
if s.muxed.contains(id):
await s.muxed[id].close
if s.connections.contains(id):
await s.connections[id].close()
2019-09-04 01:50:17 +00:00
2019-09-05 15:19:39 +00:00
proc dial*(s: Switch,
peer: PeerInfo,
proto: string = ""):
Future[Connection] {.async.} =
2019-08-31 17:58:49 +00:00
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
2019-09-04 22:00:39 +00:00
var conn = await t.dial(a)
conn = await s.handleConn(conn)
if s.muxed.contains(peer.peerId.pretty):
conn = await s.muxed[peer.peerId.pretty].newStream()
if (await s.ms.select(conn, proto)).len == 0:
2019-08-31 18:52:56 +00:00
raise newException(CatchableError,
2019-09-04 22:00:39 +00:00
&"Unable to select protocol: {proto}")
result = conn
2019-08-27 21:46:12 +00:00
2019-08-31 17:58:49 +00:00
proc mount*[T: LPProtocol](s: Switch, proto: T) =
if isNil(proto.handler):
raise newException(CatchableError,
"Protocol has to define a handle method or proc")
2019-08-27 21:46:12 +00:00
2019-08-31 18:52:56 +00:00
if len(proto.codec) <= 0:
raise newException(CatchableError,
"Protocol has to define a codec string")
2019-08-31 17:58:49 +00:00
s.ms.addHandler(proto.codec, proto)
2019-08-28 02:30:53 +00:00
proc start*(s: Switch) {.async.} =
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:
2019-09-05 15:19:39 +00:00
# TODO: figure out proper way of handling this.
# Perhaps it's ok to discard this Future and handle
# errors elsewere?
asyncCheck s.ms.handle(conn) # handle incoming connection
2019-09-04 22:00:39 +00:00
except:
await s.cleanupConn(conn)
2019-08-27 21:46:12 +00:00
2019-08-28 02:30:53 +00:00
for t in s.transports: # for each transport
for a in s.peerInfo.addrs:
if t.handles(a): # check if it handles the multiaddr
await t.listen(a, handle) # listen for incoming connections
2019-08-27 21:46:12 +00:00
2019-08-28 02:30:53 +00:00
proc stop*(s: Switch) {.async.} =
2019-08-31 17:58:49 +00:00
await allFutures(s.transports.mapIt(it.close()))