Skip to content

Commit 0aa6d9d

Browse files
Merge branch 'master' into feat/report-changes-listen-addr
2 parents 2c17008 + c93f753 commit 0aa6d9d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

68 files changed

+540
-562
lines changed

core/CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@
99
[PR 3715]: https://github.com/libp2p/rust-libp2p/pull/3715
1010
[PR 3867]: https://github.com/libp2p/rust-libp2p/pull/3867
1111

12+
- Enforce protocol names to be valid UTF8 strings as required by the [spec].
13+
We delete the `ProtocolName` trait and replace it with a requirement for `AsRef<str>`.
14+
See [PR 3746]
15+
16+
[spec]: https://github.com/libp2p/specs/blob/master/connections/README.md#multistream-select
17+
[PR 3746]: https://github.com/libp2p/rust-libp2p/pull/3746
18+
1219
## 0.39.2
1320

1421
- Deprecate `upgrade::from_fn` without replacement as it is not used within `rust-libp2p`.

core/src/either.rs

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use crate::muxing::StreamMuxerEvent;
2222
use crate::{
2323
muxing::StreamMuxer,
2424
transport::{ListenerId, Transport, TransportError, TransportEvent},
25-
Multiaddr, ProtocolName,
25+
Multiaddr,
2626
};
2727
use either::Either;
2828
use futures::prelude::*;
@@ -115,21 +115,6 @@ where
115115
}
116116
}
117117

118-
#[derive(Debug, Clone)]
119-
pub enum EitherName<A, B> {
120-
A(A),
121-
B(B),
122-
}
123-
124-
impl<A: ProtocolName, B: ProtocolName> ProtocolName for EitherName<A, B> {
125-
fn protocol_name(&self) -> &[u8] {
126-
match self {
127-
EitherName::A(a) => a.protocol_name(),
128-
EitherName::B(b) => b.protocol_name(),
129-
}
130-
}
131-
}
132-
133118
impl<A, B> Transport for Either<A, B>
134119
where
135120
B: Transport,

core/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ pub use peer_record::PeerRecord;
127127
pub use signed_envelope::SignedEnvelope;
128128
pub use translation::address_translation;
129129
pub use transport::Transport;
130-
pub use upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeError, UpgradeInfo};
130+
pub use upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeError, UpgradeInfo};
131131

132132
#[derive(Debug, thiserror::Error)]
133133
pub struct DecodeError(String);

core/src/upgrade.rs

Lines changed: 1 addition & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -80,58 +80,11 @@ pub use self::{
8080
pub use crate::Negotiated;
8181
pub use multistream_select::{NegotiatedComplete, NegotiationError, ProtocolError, Version};
8282

83-
/// Types serving as protocol names.
84-
///
85-
/// # Context
86-
///
87-
/// In situations where we provide a list of protocols that we support,
88-
/// the elements of that list are required to implement the [`ProtocolName`] trait.
89-
///
90-
/// Libp2p will call [`ProtocolName::protocol_name`] on each element of that list, and transmit the
91-
/// returned value on the network. If the remote accepts a given protocol, the element
92-
/// serves as the return value of the function that performed the negotiation.
93-
///
94-
/// # Example
95-
///
96-
/// ```
97-
/// use libp2p_core::ProtocolName;
98-
///
99-
/// enum MyProtocolName {
100-
/// Version1,
101-
/// Version2,
102-
/// Version3,
103-
/// }
104-
///
105-
/// impl ProtocolName for MyProtocolName {
106-
/// fn protocol_name(&self) -> &[u8] {
107-
/// match *self {
108-
/// MyProtocolName::Version1 => b"/myproto/1.0",
109-
/// MyProtocolName::Version2 => b"/myproto/2.0",
110-
/// MyProtocolName::Version3 => b"/myproto/3.0",
111-
/// }
112-
/// }
113-
/// }
114-
/// ```
115-
///
116-
pub trait ProtocolName {
117-
/// The protocol name as bytes. Transmitted on the network.
118-
///
119-
/// **Note:** Valid protocol names must start with `/` and
120-
/// not exceed 140 bytes in length.
121-
fn protocol_name(&self) -> &[u8];
122-
}
123-
124-
impl<T: AsRef<[u8]>> ProtocolName for T {
125-
fn protocol_name(&self) -> &[u8] {
126-
self.as_ref()
127-
}
128-
}
129-
13083
/// Common trait for upgrades that can be applied on inbound substreams, outbound substreams,
13184
/// or both.
13285
pub trait UpgradeInfo {
13386
/// Opaque type representing a negotiable protocol.
134-
type Info: ProtocolName + Clone;
87+
type Info: AsRef<str> + Clone;
13588
/// Iterator returned by `protocol_info`.
13689
type InfoIter: IntoIterator<Item = Self::Info>;
13790

core/src/upgrade/apply.rs

Lines changed: 17 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,14 @@
1818
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
1919
// DEALINGS IN THE SOFTWARE.
2020

21-
use crate::upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeError};
21+
use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeError};
2222
use crate::{connection::ConnectedPoint, Negotiated};
2323
use futures::{future::Either, prelude::*};
2424
use log::debug;
2525
use multistream_select::{self, DialerSelectFuture, ListenerSelectFuture};
26-
use std::{iter, mem, pin::Pin, task::Context, task::Poll};
26+
use std::{mem, pin::Pin, task::Context, task::Poll};
2727

2828
pub(crate) use multistream_select::Version;
29-
use smallvec::SmallVec;
30-
use std::fmt;
3129

3230
// TODO: Still needed?
3331
/// Applies an upgrade to the inbound and outbound direction of a connection or substream.
@@ -55,14 +53,9 @@ where
5553
C: AsyncRead + AsyncWrite + Unpin,
5654
U: InboundUpgrade<Negotiated<C>>,
5755
{
58-
let iter = up
59-
.protocol_info()
60-
.into_iter()
61-
.map(NameWrap as fn(_) -> NameWrap<_>);
62-
let future = multistream_select::listener_select_proto(conn, iter);
6356
InboundUpgradeApply {
6457
inner: InboundUpgradeApplyState::Init {
65-
future,
58+
future: multistream_select::listener_select_proto(conn, up.protocol_info().into_iter()),
6659
upgrade: up,
6760
},
6861
}
@@ -74,14 +67,9 @@ where
7467
C: AsyncRead + AsyncWrite + Unpin,
7568
U: OutboundUpgrade<Negotiated<C>>,
7669
{
77-
let iter = up
78-
.protocol_info()
79-
.into_iter()
80-
.map(NameWrap as fn(_) -> NameWrap<_>);
81-
let future = multistream_select::dialer_select_proto(conn, iter, v);
8270
OutboundUpgradeApply {
8371
inner: OutboundUpgradeApplyState::Init {
84-
future,
72+
future: multistream_select::dialer_select_proto(conn, up.protocol_info(), v),
8573
upgrade: up,
8674
},
8775
}
@@ -96,18 +84,19 @@ where
9684
inner: InboundUpgradeApplyState<C, U>,
9785
}
9886

87+
#[allow(clippy::large_enum_variant)]
9988
enum InboundUpgradeApplyState<C, U>
10089
where
10190
C: AsyncRead + AsyncWrite + Unpin,
10291
U: InboundUpgrade<Negotiated<C>>,
10392
{
10493
Init {
105-
future: ListenerSelectFuture<C, NameWrap<U::Info>>,
94+
future: ListenerSelectFuture<C, U::Info>,
10695
upgrade: U,
10796
},
10897
Upgrade {
10998
future: Pin<Box<U::Future>>,
110-
name: SmallVec<[u8; 32]>,
99+
name: String,
111100
},
112101
Undefined,
113102
}
@@ -140,10 +129,9 @@ where
140129
return Poll::Pending;
141130
}
142131
};
143-
let name = SmallVec::from_slice(info.protocol_name());
144132
self.inner = InboundUpgradeApplyState::Upgrade {
145-
future: Box::pin(upgrade.upgrade_inbound(io, info.0)),
146-
name,
133+
future: Box::pin(upgrade.upgrade_inbound(io, info.clone())),
134+
name: info.as_ref().to_owned(),
147135
};
148136
}
149137
InboundUpgradeApplyState::Upgrade { mut future, name } => {
@@ -153,14 +141,11 @@ where
153141
return Poll::Pending;
154142
}
155143
Poll::Ready(Ok(x)) => {
156-
log::trace!("Upgraded inbound stream to {}", DisplayProtocolName(name));
144+
log::trace!("Upgraded inbound stream to {name}");
157145
return Poll::Ready(Ok(x));
158146
}
159147
Poll::Ready(Err(e)) => {
160-
debug!(
161-
"Failed to upgrade inbound stream to {}",
162-
DisplayProtocolName(name)
163-
);
148+
debug!("Failed to upgrade inbound stream to {name}");
164149
return Poll::Ready(Err(UpgradeError::Apply(e)));
165150
}
166151
}
@@ -188,12 +173,12 @@ where
188173
U: OutboundUpgrade<Negotiated<C>>,
189174
{
190175
Init {
191-
future: DialerSelectFuture<C, NameWrapIter<<U::InfoIter as IntoIterator>::IntoIter>>,
176+
future: DialerSelectFuture<C, <U::InfoIter as IntoIterator>::IntoIter>,
192177
upgrade: U,
193178
},
194179
Upgrade {
195180
future: Pin<Box<U::Future>>,
196-
name: SmallVec<[u8; 32]>,
181+
name: String,
197182
},
198183
Undefined,
199184
}
@@ -226,10 +211,9 @@ where
226211
return Poll::Pending;
227212
}
228213
};
229-
let name = SmallVec::from_slice(info.protocol_name());
230214
self.inner = OutboundUpgradeApplyState::Upgrade {
231-
future: Box::pin(upgrade.upgrade_outbound(connection, info.0)),
232-
name,
215+
future: Box::pin(upgrade.upgrade_outbound(connection, info.clone())),
216+
name: info.as_ref().to_owned(),
233217
};
234218
}
235219
OutboundUpgradeApplyState::Upgrade { mut future, name } => {
@@ -239,17 +223,11 @@ where
239223
return Poll::Pending;
240224
}
241225
Poll::Ready(Ok(x)) => {
242-
log::trace!(
243-
"Upgraded outbound stream to {}",
244-
DisplayProtocolName(name)
245-
);
226+
log::trace!("Upgraded outbound stream to {name}",);
246227
return Poll::Ready(Ok(x));
247228
}
248229
Poll::Ready(Err(e)) => {
249-
debug!(
250-
"Failed to upgrade outbound stream to {}",
251-
DisplayProtocolName(name)
252-
);
230+
debug!("Failed to upgrade outbound stream to {name}",);
253231
return Poll::Ready(Err(UpgradeError::Apply(e)));
254232
}
255233
}
@@ -261,51 +239,3 @@ where
261239
}
262240
}
263241
}
264-
265-
type NameWrapIter<I> = iter::Map<I, fn(<I as Iterator>::Item) -> NameWrap<<I as Iterator>::Item>>;
266-
267-
/// Wrapper type to expose an `AsRef<[u8]>` impl for all types implementing `ProtocolName`.
268-
#[derive(Clone)]
269-
struct NameWrap<N>(N);
270-
271-
impl<N: ProtocolName> AsRef<[u8]> for NameWrap<N> {
272-
fn as_ref(&self) -> &[u8] {
273-
self.0.protocol_name()
274-
}
275-
}
276-
277-
/// Wrapper for printing a [`ProtocolName`] that is expected to be mostly ASCII
278-
pub(crate) struct DisplayProtocolName<N>(pub(crate) N);
279-
280-
impl<N: ProtocolName> fmt::Display for DisplayProtocolName<N> {
281-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282-
use fmt::Write;
283-
for byte in self.0.protocol_name() {
284-
if (b' '..=b'~').contains(byte) {
285-
f.write_char(char::from(*byte))?;
286-
} else {
287-
write!(f, "<{byte:02X}>")?;
288-
}
289-
}
290-
Ok(())
291-
}
292-
}
293-
294-
#[cfg(test)]
295-
mod tests {
296-
use super::*;
297-
298-
#[test]
299-
fn display_protocol_name() {
300-
assert_eq!(DisplayProtocolName(b"/hello/1.0").to_string(), "/hello/1.0");
301-
assert_eq!(DisplayProtocolName("/hellö/").to_string(), "/hell<C3><B6>/");
302-
assert_eq!(
303-
DisplayProtocolName((0u8..=255).collect::<Vec<_>>()).to_string(),
304-
(0..32)
305-
.map(|c| format!("<{c:02X}>"))
306-
.chain((32..127).map(|c| format!("{}", char::from_u32(c).unwrap())))
307-
.chain((127..256).map(|c| format!("<{c:02X}>")))
308-
.collect::<String>()
309-
);
310-
}
311-
}

core/src/upgrade/denied.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use void::Void;
2929
pub struct DeniedUpgrade;
3030

3131
impl UpgradeInfo for DeniedUpgrade {
32-
type Info = &'static [u8];
32+
type Info = &'static str;
3333
type InfoIter = iter::Empty<Self::Info>;
3434

3535
fn protocol_info(&self) -> Self::InfoIter {

core/src/upgrade/either.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
// DEALINGS IN THE SOFTWARE.
2020

2121
use crate::{
22-
either::{EitherFuture, EitherName},
22+
either::EitherFuture,
2323
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo},
2424
};
2525
use either::Either;
@@ -31,16 +31,16 @@ where
3131
A: UpgradeInfo,
3232
B: UpgradeInfo,
3333
{
34-
type Info = EitherName<A::Info, B::Info>;
34+
type Info = Either<A::Info, B::Info>;
3535
type InfoIter = Either<
3636
Map<<A::InfoIter as IntoIterator>::IntoIter, fn(A::Info) -> Self::Info>,
3737
Map<<B::InfoIter as IntoIterator>::IntoIter, fn(B::Info) -> Self::Info>,
3838
>;
3939

4040
fn protocol_info(&self) -> Self::InfoIter {
4141
match self {
42-
Either::Left(a) => Either::Left(a.protocol_info().into_iter().map(EitherName::A)),
43-
Either::Right(b) => Either::Right(b.protocol_info().into_iter().map(EitherName::B)),
42+
Either::Left(a) => Either::Left(a.protocol_info().into_iter().map(Either::Left)),
43+
Either::Right(b) => Either::Right(b.protocol_info().into_iter().map(Either::Right)),
4444
}
4545
}
4646
}
@@ -56,10 +56,10 @@ where
5656

5757
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
5858
match (self, info) {
59-
(Either::Left(a), EitherName::A(info)) => {
59+
(Either::Left(a), Either::Left(info)) => {
6060
EitherFuture::First(a.upgrade_inbound(sock, info))
6161
}
62-
(Either::Right(b), EitherName::B(info)) => {
62+
(Either::Right(b), Either::Right(info)) => {
6363
EitherFuture::Second(b.upgrade_inbound(sock, info))
6464
}
6565
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_inbound"),
@@ -78,10 +78,10 @@ where
7878

7979
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
8080
match (self, info) {
81-
(Either::Left(a), EitherName::A(info)) => {
81+
(Either::Left(a), Either::Left(info)) => {
8282
EitherFuture::First(a.upgrade_outbound(sock, info))
8383
}
84-
(Either::Right(b), EitherName::B(info)) => {
84+
(Either::Right(b), Either::Right(info)) => {
8585
EitherFuture::Second(b.upgrade_outbound(sock, info))
8686
}
8787
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_outbound"),

0 commit comments

Comments
 (0)