2022-07-01 18:19:57 +00:00
|
|
|
# Nim-LibP2P
|
2024-03-12 20:05:53 +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.
|
2019-08-30 05:16:55 +00:00
|
|
|
|
2023-06-07 11:12:49 +00:00
|
|
|
{.push raises: [].}
|
2021-05-21 16:27:01 +00:00
|
|
|
|
2022-12-01 11:20:40 +00:00
|
|
|
import std/[strutils, sequtils, tables]
|
2020-06-03 02:21:11 +00:00
|
|
|
import chronos, chronicles, stew/byteutils
|
2020-06-19 17:29:43 +00:00
|
|
|
import stream/connection, protocols/protocol
|
2019-08-30 05:16:55 +00:00
|
|
|
|
2019-09-11 21:06:10 +00:00
|
|
|
logScope:
|
2020-12-01 17:34:27 +00:00
|
|
|
topics = "libp2p multistream"
|
2019-09-11 21:06:10 +00:00
|
|
|
|
2020-01-07 08:02:37 +00:00
|
|
|
const
|
2023-03-08 11:30:19 +00:00
|
|
|
MsgSize = 1024
|
|
|
|
Codec = "/multistream/1.0.0"
|
2019-10-04 16:04:21 +00:00
|
|
|
|
2023-03-08 11:30:19 +00:00
|
|
|
Na = "na\n"
|
|
|
|
Ls = "ls\n"
|
2019-08-30 05:16:55 +00:00
|
|
|
|
|
|
|
type
|
2023-06-07 11:12:49 +00:00
|
|
|
Matcher* = proc(proto: string): bool {.gcsafe, raises: [].}
|
2019-08-30 05:16:55 +00:00
|
|
|
|
2021-06-02 13:39:10 +00:00
|
|
|
MultiStreamError* = object of LPError
|
|
|
|
|
2022-12-01 11:20:40 +00:00
|
|
|
HandlerHolder* = ref object
|
2020-09-21 09:16:29 +00:00
|
|
|
protos*: seq[string]
|
2019-09-06 00:16:49 +00:00
|
|
|
protocol*: LPProtocol
|
|
|
|
match*: Matcher
|
2022-12-01 11:20:40 +00:00
|
|
|
openedStreams: CountTable[PeerId]
|
2019-08-30 05:16:55 +00:00
|
|
|
|
2020-02-04 16:16:21 +00:00
|
|
|
MultistreamSelect* = ref object of RootObj
|
2019-08-30 05:16:55 +00:00
|
|
|
handlers*: seq[HandlerHolder]
|
|
|
|
codec*: string
|
|
|
|
|
2021-06-07 07:32:08 +00:00
|
|
|
proc new*(T: typedesc[MultistreamSelect]): T =
|
2023-03-08 11:30:19 +00:00
|
|
|
T(codec: Codec)
|
2021-06-07 07:32:08 +00:00
|
|
|
|
2020-07-28 14:03:22 +00:00
|
|
|
template validateSuffix(str: string): untyped =
|
2024-03-12 20:05:53 +00:00
|
|
|
if str.endsWith("\n"):
|
|
|
|
str.removeSuffix("\n")
|
|
|
|
else:
|
|
|
|
raise (ref MultiStreamError)(msg: "MultistreamSelect failed, malformed message")
|
|
|
|
|
|
|
|
proc select*(
|
|
|
|
_: MultistreamSelect | type MultistreamSelect, conn: Connection, proto: seq[string]
|
|
|
|
): Future[string] {.async: (raises: [CancelledError, LPStreamError, MultiStreamError]).} =
|
2023-03-08 11:30:19 +00:00
|
|
|
trace "initiating handshake", conn, codec = Codec
|
2019-08-30 05:16:55 +00:00
|
|
|
## select a remote protocol
|
2023-03-08 11:30:19 +00:00
|
|
|
await conn.writeLp(Codec & "\n") # write handshake
|
2019-08-30 05:16:55 +00:00
|
|
|
if proto.len() > 0:
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "selecting proto", conn, proto = proto[0]
|
2019-09-05 15:19:15 +00:00
|
|
|
await conn.writeLp((proto[0] & "\n")) # select proto
|
2019-08-30 05:16:55 +00:00
|
|
|
|
2020-09-09 17:12:08 +00:00
|
|
|
var s = string.fromBytes((await conn.readLp(MsgSize))) # read ms header
|
2020-07-28 14:03:22 +00:00
|
|
|
validateSuffix(s)
|
|
|
|
|
2020-06-22 21:38:48 +00:00
|
|
|
if s != Codec:
|
2020-09-09 17:12:08 +00:00
|
|
|
notice "handshake failed", conn, codec = s
|
2024-03-12 20:05:53 +00:00
|
|
|
raise (ref MultiStreamError)(msg: "MultistreamSelect handshake failed")
|
2020-07-28 14:03:22 +00:00
|
|
|
else:
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "multistream handshake success", conn
|
2019-08-30 05:16:55 +00:00
|
|
|
|
2019-09-04 18:31:13 +00:00
|
|
|
if proto.len() == 0: # no protocols, must be a handshake call
|
2020-06-22 21:38:48 +00:00
|
|
|
return Codec
|
|
|
|
else:
|
2020-09-09 17:12:08 +00:00
|
|
|
s = string.fromBytes(await conn.readLp(MsgSize)) # read the first proto
|
2020-07-28 14:03:22 +00:00
|
|
|
validateSuffix(s)
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "reading first requested proto", conn
|
2020-06-22 21:38:48 +00:00
|
|
|
if s == proto[0]:
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "successfully selected ", conn, proto = proto[0]
|
2022-08-01 12:31:22 +00:00
|
|
|
conn.protocol = proto[0]
|
2020-06-22 21:38:48 +00:00
|
|
|
return proto[0]
|
|
|
|
elif proto.len > 1:
|
|
|
|
# Try to negotiate alternatives
|
|
|
|
let protos = proto[1 ..< proto.len()]
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "selecting one of several protos", conn, protos = protos
|
2020-06-22 21:38:48 +00:00
|
|
|
for p in protos:
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "selecting proto", conn, proto = p
|
2020-06-22 21:38:48 +00:00
|
|
|
await conn.writeLp((p & "\n")) # select proto
|
2020-09-09 17:12:08 +00:00
|
|
|
s = string.fromBytes(await conn.readLp(MsgSize)) # read the first proto
|
2020-07-28 14:03:22 +00:00
|
|
|
validateSuffix(s)
|
2020-06-22 21:38:48 +00:00
|
|
|
if s == p:
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "selected protocol", conn, protocol = s
|
2022-08-01 12:31:22 +00:00
|
|
|
conn.protocol = s
|
2020-06-22 21:38:48 +00:00
|
|
|
return s
|
|
|
|
return ""
|
|
|
|
else:
|
|
|
|
# No alternatives, fail
|
|
|
|
return ""
|
2019-09-04 18:31:13 +00:00
|
|
|
|
2024-03-12 20:05:53 +00:00
|
|
|
proc select*(
|
|
|
|
_: MultistreamSelect | type MultistreamSelect, conn: Connection, proto: string
|
|
|
|
): Future[bool] {.async: (raises: [CancelledError, LPStreamError, MultiStreamError]).} =
|
2020-01-07 08:02:37 +00:00
|
|
|
if proto.len > 0:
|
2024-03-12 20:05:53 +00:00
|
|
|
(await MultistreamSelect.select(conn, @[proto])) == proto
|
2020-01-07 08:02:37 +00:00
|
|
|
else:
|
2024-03-12 20:05:53 +00:00
|
|
|
(await MultistreamSelect.select(conn, @[])) == Codec
|
2019-09-04 20:15:55 +00:00
|
|
|
|
2024-03-12 20:05:53 +00:00
|
|
|
proc select*(
|
|
|
|
m: MultistreamSelect, conn: Connection
|
|
|
|
): Future[bool] {.
|
|
|
|
async: (raises: [CancelledError, LPStreamError, MultiStreamError], raw: true)
|
|
|
|
.} =
|
2019-09-08 07:43:33 +00:00
|
|
|
m.select(conn, "")
|
2019-08-30 05:16:55 +00:00
|
|
|
|
2024-03-12 20:05:53 +00:00
|
|
|
proc list*(
|
|
|
|
m: MultistreamSelect, conn: Connection
|
|
|
|
): Future[seq[string]] {.
|
|
|
|
async: (raises: [CancelledError, LPStreamError, MultiStreamError])
|
|
|
|
.} =
|
2019-08-30 05:16:55 +00:00
|
|
|
## list remote protos requests on connection
|
2019-09-06 06:49:01 +00:00
|
|
|
if not await m.select(conn):
|
2019-08-30 05:16:55 +00:00
|
|
|
return
|
|
|
|
|
2023-03-08 11:30:19 +00:00
|
|
|
await conn.writeLp(Ls) # send ls
|
2019-08-30 05:16:55 +00:00
|
|
|
|
|
|
|
var list = newSeq[string]()
|
2020-09-09 17:12:08 +00:00
|
|
|
let ms = string.fromBytes(await conn.readLp(MsgSize))
|
2019-08-30 05:16:55 +00:00
|
|
|
for s in ms.split("\n"):
|
|
|
|
if s.len() > 0:
|
|
|
|
list.add(s)
|
|
|
|
|
|
|
|
result = list
|
|
|
|
|
2023-03-08 11:30:19 +00:00
|
|
|
proc handle*(
|
2024-03-12 20:05:53 +00:00
|
|
|
_: type MultistreamSelect,
|
|
|
|
conn: Connection,
|
|
|
|
protos: seq[string],
|
|
|
|
matchers = newSeq[Matcher](),
|
|
|
|
active: bool = false,
|
|
|
|
): Future[string] {.async: (raises: [CancelledError, LPStreamError, MultiStreamError]).} =
|
2023-03-08 11:30:19 +00:00
|
|
|
trace "Starting multistream negotiation", conn, handshaked = active
|
|
|
|
var handshaked = active
|
|
|
|
while not conn.atEof:
|
|
|
|
var ms = string.fromBytes(await conn.readLp(MsgSize))
|
|
|
|
validateSuffix(ms)
|
|
|
|
|
|
|
|
if not handshaked and ms != Codec:
|
|
|
|
debug "expected handshake message", conn, instead = ms
|
2024-03-12 20:05:53 +00:00
|
|
|
raise (ref MultiStreamError)(
|
|
|
|
msg: "MultistreamSelect handling failed, invalid first message"
|
|
|
|
)
|
2023-03-08 11:30:19 +00:00
|
|
|
|
|
|
|
trace "handle: got request", conn, ms
|
|
|
|
if ms.len() <= 0:
|
|
|
|
trace "handle: invalid proto", conn
|
|
|
|
await conn.writeLp(Na)
|
|
|
|
|
|
|
|
case ms
|
|
|
|
of "ls":
|
|
|
|
trace "handle: listing protos", conn
|
|
|
|
#TODO this doens't seem to follow spec, each protocol
|
|
|
|
# should be length prefixed. Not very important
|
|
|
|
# since LS is getting deprecated
|
|
|
|
await conn.writeLp(protos.join("\n") & "\n")
|
|
|
|
of Codec:
|
|
|
|
if not handshaked:
|
|
|
|
await conn.writeLp(Codec & "\n")
|
|
|
|
handshaked = true
|
|
|
|
else:
|
|
|
|
trace "handle: sending `na` for duplicate handshake while handshaked", conn
|
|
|
|
await conn.writeLp(Na)
|
|
|
|
elif ms in protos or matchers.anyIt(it(ms)):
|
|
|
|
trace "found handler", conn, protocol = ms
|
|
|
|
await conn.writeLp(ms & "\n")
|
|
|
|
conn.protocol = ms
|
|
|
|
return ms
|
|
|
|
else:
|
|
|
|
trace "no handlers", conn, protocol = ms
|
|
|
|
await conn.writeLp(Na)
|
|
|
|
|
2024-03-12 20:05:53 +00:00
|
|
|
proc handle*(
|
|
|
|
m: MultistreamSelect, conn: Connection, active: bool = false
|
|
|
|
) {.async: (raises: [CancelledError]).} =
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "Starting multistream handler", conn, handshaked = active
|
2023-03-08 11:30:19 +00:00
|
|
|
var
|
|
|
|
protos: seq[string]
|
|
|
|
matchers: seq[Matcher]
|
|
|
|
for h in m.handlers:
|
2024-03-12 20:05:53 +00:00
|
|
|
if h.match != nil:
|
2023-03-08 11:30:19 +00:00
|
|
|
matchers.add(h.match)
|
|
|
|
for proto in h.protos:
|
|
|
|
protos.add(proto)
|
|
|
|
|
2020-05-23 17:10:22 +00:00
|
|
|
try:
|
2023-03-08 11:30:19 +00:00
|
|
|
let ms = await MultistreamSelect.handle(conn, protos, matchers, active)
|
|
|
|
for h in m.handlers:
|
2024-03-12 20:05:53 +00:00
|
|
|
if (h.match != nil and h.match(ms)) or h.protos.contains(ms):
|
2023-03-08 11:30:19 +00:00
|
|
|
trace "found handler", conn, protocol = ms
|
|
|
|
|
|
|
|
var protocolHolder = h
|
|
|
|
let maxIncomingStreams = protocolHolder.protocol.maxIncomingStreams
|
2024-03-12 20:05:53 +00:00
|
|
|
if protocolHolder.openedStreams.getOrDefault(conn.peerId) >= maxIncomingStreams:
|
2023-03-08 11:30:19 +00:00
|
|
|
debug "Max streams for protocol reached, blocking new stream",
|
|
|
|
conn, protocol = ms, maxIncomingStreams
|
|
|
|
return
|
|
|
|
protocolHolder.openedStreams.inc(conn.peerId)
|
|
|
|
try:
|
|
|
|
await protocolHolder.protocol.handler(conn, ms)
|
|
|
|
finally:
|
|
|
|
protocolHolder.openedStreams.inc(conn.peerId, -1)
|
|
|
|
if protocolHolder.openedStreams[conn.peerId] == 0:
|
|
|
|
protocolHolder.openedStreams.del(conn.peerId)
|
|
|
|
return
|
|
|
|
debug "no handlers", conn, ms
|
2020-06-29 15:15:31 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2020-05-23 17:10:22 +00:00
|
|
|
except CatchableError as exc:
|
2020-09-09 17:12:08 +00:00
|
|
|
trace "Exception in multistream", conn, msg = exc.msg
|
2020-05-23 17:10:22 +00:00
|
|
|
finally:
|
2020-09-09 17:12:08 +00:00
|
|
|
await conn.close()
|
|
|
|
|
|
|
|
trace "Stopped multistream handler", conn
|
2019-08-30 05:16:55 +00:00
|
|
|
|
2020-08-15 19:50:31 +00:00
|
|
|
proc addHandler*(
|
|
|
|
m: MultistreamSelect,
|
2020-09-21 09:16:29 +00:00
|
|
|
codecs: seq[string],
|
2020-08-15 19:50:31 +00:00
|
|
|
protocol: LPProtocol,
|
|
|
|
matcher: Matcher = nil,
|
|
|
|
) =
|
2020-09-21 09:16:29 +00:00
|
|
|
trace "registering protocols", protos = codecs
|
|
|
|
m.handlers.add(HandlerHolder(protos: codecs, protocol: protocol, match: matcher))
|
2024-06-11 15:18:06 +00:00
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
proc addHandler*(
|
|
|
|
m: MultistreamSelect, codec: string, protocol: LPProtocol, matcher: Matcher = nil
|
|
|
|
) =
|
|
|
|
addHandler(m, @[codec], protocol, matcher)
|
|
|
|
|
2024-03-28 08:42:31 +00:00
|
|
|
proc addHandler*[E](
|
|
|
|
m: MultistreamSelect,
|
|
|
|
codec: string,
|
|
|
|
handler:
|
|
|
|
LPProtoHandler |
|
|
|
|
proc(conn: Connection, proto: string): InternalRaisesFuture[void, E],
|
|
|
|
matcher: Matcher = nil,
|
|
|
|
) =
|
2019-09-14 13:55:52 +00:00
|
|
|
## helper to allow registering pure handlers
|
2020-09-21 09:16:29 +00:00
|
|
|
trace "registering proto handler", proto = codec
|
2019-09-14 13:55:52 +00:00
|
|
|
let protocol = new LPProtocol
|
|
|
|
protocol.codec = codec
|
|
|
|
protocol.handler = handler
|
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
m.handlers.add(HandlerHolder(protos: @[codec], protocol: protocol, match: matcher))
|
2022-06-30 09:21:33 +00:00
|
|
|
|
2024-03-12 20:05:53 +00:00
|
|
|
proc start*(m: MultistreamSelect) {.async: (raises: [CancelledError]).} =
|
2024-03-21 07:19:57 +00:00
|
|
|
# Nim 1.6.18: Using `mapIt` results in a seq of `.Raising([])`
|
2024-05-08 12:33:26 +00:00
|
|
|
# TODO https://github.com/nim-lang/Nim/issues/23445
|
2024-03-21 07:19:57 +00:00
|
|
|
var futs = newSeqOfCap[Future[void].Raising([CancelledError])](m.handlers.len)
|
|
|
|
for it in m.handlers:
|
|
|
|
futs.add it.protocol.start()
|
2024-03-12 20:05:53 +00:00
|
|
|
try:
|
|
|
|
await allFutures(futs)
|
|
|
|
for fut in futs:
|
|
|
|
await fut
|
|
|
|
except CancelledError as exc:
|
|
|
|
var pending: seq[Future[void].Raising([])]
|
2024-03-21 07:19:57 +00:00
|
|
|
doAssert m.handlers.len == futs.len, "Handlers modified while starting"
|
2024-03-12 20:05:53 +00:00
|
|
|
for i, fut in futs:
|
|
|
|
if not fut.finished:
|
2024-05-08 12:33:26 +00:00
|
|
|
pending.add fut.cancelAndWait()
|
2024-03-12 20:05:53 +00:00
|
|
|
elif fut.completed:
|
2024-03-21 07:19:57 +00:00
|
|
|
pending.add m.handlers[i].protocol.stop()
|
2024-03-12 20:05:53 +00:00
|
|
|
else:
|
|
|
|
static:
|
|
|
|
doAssert typeof(fut).E is (CancelledError,)
|
|
|
|
await noCancel allFutures(pending)
|
|
|
|
raise exc
|
|
|
|
|
|
|
|
proc stop*(m: MultistreamSelect) {.async: (raises: []).} =
|
|
|
|
# Nim 1.6.18: Using `mapIt` results in a seq of `.Raising([CancelledError])`
|
|
|
|
var futs = newSeqOfCap[Future[void].Raising([])](m.handlers.len)
|
|
|
|
for it in m.handlers:
|
|
|
|
futs.add it.protocol.stop()
|
|
|
|
await noCancel allFutures(futs)
|
|
|
|
for fut in futs:
|
|
|
|
await fut
|