multistream_select/lib.rs
1// Copyright 2017 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! # Multistream-select Protocol Negotiation
22//!
23//! This crate implements the `multistream-select` protocol, which is the protocol
24//! used by libp2p to negotiate which application-layer protocol to use with the
25//! remote on a connection or substream.
26//!
27//! > **Note**: This crate is used primarily by core components of *libp2p* and it
28//! > is usually not used directly on its own.
29//!
30//! ## Roles
31//!
32//! Two peers using the multistream-select negotiation protocol on an I/O stream
33//! are distinguished by their role as a _dialer_ (or _initiator_) or as a _listener_
34//! (or _responder_). Thereby the dialer plays the active part, driving the protocol,
35//! whereas the listener reacts to the messages received.
36//!
37//! The dialer has two options: it can either pick a protocol from the complete list
38//! of protocols that the listener supports, or it can directly suggest a protocol.
39//! Either way, a selected protocol is sent to the listener who can either accept (by
40//! echoing the same protocol) or reject (by responding with a message stating
41//! "not available"). If a suggested protocol is not available, the dialer may
42//! suggest another protocol. This process continues until a protocol is agreed upon,
43//! yielding a [`Negotiated`] stream, or the dialer has run out of
44//! alternatives.
45//!
46//! See [`dialer_select_proto`] and [`listener_select_proto`].
47//!
48//! ## [`Negotiated`]
49//!
50//! A `Negotiated` represents an I/O stream that has settled on a protocol
51//! to use. By default, with [`Version::V1`], protocol negotiation is always
52//! at least one dedicated round-trip message exchange, before application
53//! data for the negotiated protocol can be sent by the dialer. There is
54//! a variant [`Version::V1Lazy`] that permits 0-RTT negotiation if the
55//! dialer only supports a single protocol. In that case, when a dialer
56//! settles on a protocol to use, the [`DialerSelectFuture`] yields a
57//! [`Negotiated`] I/O stream before the negotiation
58//! data has been flushed. It is then expecting confirmation for that protocol
59//! as the first messages read from the stream. This behaviour allows the dialer
60//! to immediately send data relating to the negotiated protocol together with the
61//! remaining negotiation message(s). Note, however, that a dialer that performs
62//! multiple 0-RTT negotiations in sequence for different protocols layered on
63//! top of each other may trigger undesirable behaviour for a listener not
64//! supporting one of the intermediate protocols. See
65//! [`dialer_select_proto`] and the documentation of [`Version::V1Lazy`] for further details.
66//!
67//! ## Examples
68//!
69//! For a dialer:
70//!
71//! ```no_run
72//! use async_std::net::TcpStream;
73//! use futures::prelude::*;
74//! use multistream_select::{dialer_select_proto, Version};
75//!
76//! async_std::task::block_on(async move {
77//! let socket = TcpStream::connect("127.0.0.1:10333").await.unwrap();
78//!
79//! let protos = vec!["/echo/1.0.0", "/echo/2.5.0"];
80//! let (protocol, _io) = dialer_select_proto(socket, protos, Version::V1)
81//! .await
82//! .unwrap();
83//!
84//! println!("Negotiated protocol: {:?}", protocol);
85//! // You can now use `_io` to communicate with the remote.
86//! });
87//! ```
88
89#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
90
91mod dialer_select;
92mod length_delimited;
93mod listener_select;
94mod negotiated;
95mod protocol;
96
97pub use self::{
98 dialer_select::{dialer_select_proto, DialerSelectFuture},
99 listener_select::{listener_select_proto, ListenerSelectFuture},
100 negotiated::{Negotiated, NegotiatedComplete, NegotiationError},
101 protocol::ProtocolError,
102};
103
104/// Supported multistream-select versions.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
106pub enum Version {
107 /// Version 1 of the multistream-select protocol. See [1] and [2].
108 ///
109 /// [1]: https://github.com/libp2p/specs/blob/master/connections/README.md#protocol-negotiation
110 /// [2]: https://github.com/multiformats/multistream-select
111 #[default]
112 V1,
113 /// A "lazy" variant of version 1 that is identical on the wire but whereby
114 /// the dialer delays flushing protocol negotiation data in order to combine
115 /// it with initial application data, thus performing 0-RTT negotiation.
116 ///
117 /// This strategy is only applicable for the node with the role of "dialer"
118 /// in the negotiation and only if the dialer supports just a single
119 /// application protocol. In that case the dialer immedidately "settles"
120 /// on that protocol, buffering the negotiation messages to be sent
121 /// with the first round of application protocol data (or an attempt
122 /// is made to read from the `Negotiated` I/O stream).
123 ///
124 /// A listener will behave identically to `V1`. This ensures interoperability with `V1`.
125 /// Notably, it will immediately send the multistream header as well as the protocol
126 /// confirmation, resulting in multiple frames being sent on the underlying transport.
127 /// Nevertheless, if the listener supports the protocol that the dialer optimistically
128 /// settled on, it can be a 0-RTT negotiation.
129 ///
130 /// > **Note**: `V1Lazy` is specific to `rust-libp2p`. The wire protocol is identical to `V1`
131 /// > and generally interoperable with peers only supporting `V1`. Nevertheless, there is a
132 /// > pitfall that is rarely encountered: When nesting multiple protocol negotiations, the
133 /// > listener should either be known to support all of the dialer's optimistically chosen
134 /// > protocols or there is must be no intermediate protocol without a payload and none of
135 /// > the protocol payloads must have the potential for being mistaken for a multistream-select
136 /// > protocol message. This avoids rare edge-cases whereby the listener may not recognize
137 /// > upgrade boundaries and erroneously process a request despite not supporting one of
138 /// > the intermediate protocols that the dialer committed to. See [1] and [2].
139 ///
140 /// [1]: https://github.com/multiformats/go-multistream/issues/20
141 /// [2]: https://github.com/libp2p/rust-libp2p/pull/1212
142 V1Lazy,
143 // Draft: https://github.com/libp2p/specs/pull/95
144 // V2,
145}
146
147#[cfg(test)]
148impl quickcheck::Arbitrary for Version {
149 fn arbitrary(g: &mut quickcheck::Gen) -> Self {
150 *g.choose(&[Version::V1, Version::V1Lazy])
151 .expect("slice not empty")
152 }
153}