2018-11-04 09:47:15 +01:00
|
|
|
// Copyright 2018 Parity Technologies (UK) Ltd.
|
|
|
|
//
|
|
|
|
// Permission is hereby granted, free of charge, to any person obtaining a
|
|
|
|
// copy of this software and associated documentation files (the "Software"),
|
|
|
|
// to deal in the Software without restriction, including without limitation
|
|
|
|
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
|
|
// and/or sell copies of the Software, and to permit persons to whom the
|
|
|
|
// Software is furnished to do so, subject to the following conditions:
|
|
|
|
//
|
|
|
|
// The above copyright notice and this permission notice shall be included in
|
|
|
|
// all copies or substantial portions of the Software.
|
|
|
|
//
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
|
|
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
|
|
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
|
|
// DEALINGS IN THE SOFTWARE.
|
|
|
|
|
2020-08-10 12:54:55 +02:00
|
|
|
use futures::prelude::*;
|
2020-01-13 14:34:43 +01:00
|
|
|
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
|
2020-08-10 12:54:55 +02:00
|
|
|
use libp2p_swarm::NegotiatedSubstream;
|
2019-04-16 15:57:29 +02:00
|
|
|
use rand::{distributions, prelude::*};
|
2019-11-25 10:45:04 +01:00
|
|
|
use std::{io, iter, time::Duration};
|
2020-08-10 12:54:55 +02:00
|
|
|
use void::Void;
|
2019-04-25 15:08:06 +02:00
|
|
|
use wasm_timer::Instant;
|
2018-11-04 09:47:15 +01:00
|
|
|
|
2020-08-10 12:54:55 +02:00
|
|
|
/// The `Ping` protocol upgrade.
|
2018-11-04 09:47:15 +01:00
|
|
|
///
|
2020-08-10 12:54:55 +02:00
|
|
|
/// The ping protocol sends 32 bytes of random data in configurable
|
|
|
|
/// intervals over a single outbound substream, expecting to receive
|
|
|
|
/// the same bytes as a response. At the same time, incoming pings
|
|
|
|
/// on inbound substreams are answered by sending back the received bytes.
|
2019-01-28 15:06:07 +01:00
|
|
|
///
|
2020-08-10 12:54:55 +02:00
|
|
|
/// At most a single inbound and outbound substream is kept open at
|
|
|
|
/// any time. In case of a ping timeout or another error on a substream, the
|
|
|
|
/// substream is dropped. If a configurable number of consecutive
|
|
|
|
/// outbound pings fail, the connection is closed.
|
2019-01-28 15:06:07 +01:00
|
|
|
///
|
2020-08-10 12:54:55 +02:00
|
|
|
/// Successful pings report the round-trip time.
|
2019-04-16 15:57:29 +02:00
|
|
|
///
|
|
|
|
/// > **Note**: The round-trip time of a ping may be subject to delays induced
|
|
|
|
/// > by the underlying transport, e.g. in the case of TCP there is
|
|
|
|
/// > Nagle's algorithm, delayed acks and similar configuration options
|
|
|
|
/// > which can affect latencies especially on otherwise low-volume
|
|
|
|
/// > connections.
|
2019-01-28 15:06:07 +01:00
|
|
|
#[derive(Default, Debug, Copy, Clone)]
|
|
|
|
pub struct Ping;
|
2018-11-04 09:47:15 +01:00
|
|
|
|
2020-02-04 10:28:00 +01:00
|
|
|
const PING_SIZE: usize = 32;
|
|
|
|
|
2019-01-28 15:06:07 +01:00
|
|
|
impl UpgradeInfo for Ping {
|
2018-12-11 15:13:10 +01:00
|
|
|
type Info = &'static [u8];
|
|
|
|
type InfoIter = iter::Once<Self::Info>;
|
2018-11-04 09:47:15 +01:00
|
|
|
|
2018-12-11 15:13:10 +01:00
|
|
|
fn protocol_info(&self) -> Self::InfoIter {
|
|
|
|
iter::once(b"/ipfs/ping/1.0.0")
|
2018-11-04 09:47:15 +01:00
|
|
|
}
|
2018-11-15 17:41:11 +01:00
|
|
|
}
|
2018-11-04 09:47:15 +01:00
|
|
|
|
2020-08-10 12:54:55 +02:00
|
|
|
impl InboundUpgrade<NegotiatedSubstream> for Ping {
|
|
|
|
type Output = NegotiatedSubstream;
|
|
|
|
type Error = Void;
|
|
|
|
type Future = future::Ready<Result<Self::Output, Self::Error>>;
|
|
|
|
|
|
|
|
fn upgrade_inbound(self, stream: NegotiatedSubstream, _: Self::Info) -> Self::Future {
|
|
|
|
future::ok(stream)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl OutboundUpgrade<NegotiatedSubstream> for Ping {
|
|
|
|
type Output = NegotiatedSubstream;
|
|
|
|
type Error = Void;
|
|
|
|
type Future = future::Ready<Result<Self::Output, Self::Error>>;
|
|
|
|
|
|
|
|
fn upgrade_outbound(self, stream: NegotiatedSubstream, _: Self::Info) -> Self::Future {
|
|
|
|
future::ok(stream)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sends a ping and waits for the pong.
|
|
|
|
pub async fn send_ping<S>(mut stream: S) -> io::Result<(S, Duration)>
|
2018-11-15 17:41:11 +01:00
|
|
|
where
|
2021-08-11 13:12:12 +02:00
|
|
|
S: AsyncRead + AsyncWrite + Unpin,
|
2018-11-15 17:41:11 +01:00
|
|
|
{
|
2020-08-10 12:54:55 +02:00
|
|
|
let payload: [u8; PING_SIZE] = thread_rng().sample(distributions::Standard);
|
|
|
|
log::debug!("Preparing ping payload {:?}", payload);
|
|
|
|
stream.write_all(&payload).await?;
|
2020-09-28 10:57:02 +02:00
|
|
|
stream.flush().await?;
|
2020-08-10 12:54:55 +02:00
|
|
|
let started = Instant::now();
|
|
|
|
let mut recv_payload = [0u8; PING_SIZE];
|
2020-09-28 10:57:02 +02:00
|
|
|
log::debug!("Awaiting pong for {:?}", payload);
|
2020-08-10 12:54:55 +02:00
|
|
|
stream.read_exact(&mut recv_payload).await?;
|
|
|
|
if recv_payload == payload {
|
|
|
|
Ok((stream, started.elapsed()))
|
|
|
|
} else {
|
2021-08-11 13:12:12 +02:00
|
|
|
Err(io::Error::new(
|
|
|
|
io::ErrorKind::InvalidData,
|
|
|
|
"Ping payload mismatch",
|
|
|
|
))
|
2018-11-04 09:47:15 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-10 12:54:55 +02:00
|
|
|
/// Waits for a ping and sends a pong.
|
|
|
|
pub async fn recv_ping<S>(mut stream: S) -> io::Result<S>
|
2018-11-15 17:41:11 +01:00
|
|
|
where
|
2021-08-11 13:12:12 +02:00
|
|
|
S: AsyncRead + AsyncWrite + Unpin,
|
2018-11-04 09:47:15 +01:00
|
|
|
{
|
2020-08-10 12:54:55 +02:00
|
|
|
let mut payload = [0u8; PING_SIZE];
|
2020-09-28 10:57:02 +02:00
|
|
|
log::debug!("Waiting for ping ...");
|
2020-08-10 12:54:55 +02:00
|
|
|
stream.read_exact(&mut payload).await?;
|
2020-09-28 10:57:02 +02:00
|
|
|
log::debug!("Sending pong for {:?}", payload);
|
2020-08-10 12:54:55 +02:00
|
|
|
stream.write_all(&payload).await?;
|
|
|
|
stream.flush().await?;
|
|
|
|
Ok(stream)
|
2018-11-04 09:47:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2020-08-10 12:54:55 +02:00
|
|
|
use super::*;
|
2019-04-16 15:57:29 +02:00
|
|
|
use libp2p_core::{
|
|
|
|
multiaddr::multiaddr,
|
2021-08-11 13:12:12 +02:00
|
|
|
transport::{memory::MemoryTransport, ListenerEvent, Transport},
|
2019-04-16 15:57:29 +02:00
|
|
|
};
|
|
|
|
use rand::{thread_rng, Rng};
|
|
|
|
use std::time::Duration;
|
2018-11-04 09:47:15 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn ping_pong() {
|
2019-04-16 15:57:29 +02:00
|
|
|
let mem_addr = multiaddr![Memory(thread_rng().gen::<u64>())];
|
|
|
|
let mut listener = MemoryTransport.listen_on(mem_addr).unwrap();
|
|
|
|
|
|
|
|
let listener_addr =
|
2019-11-25 17:33:59 +01:00
|
|
|
if let Some(Some(Ok(ListenerEvent::NewAddress(a)))) = listener.next().now_or_never() {
|
2019-04-16 15:57:29 +02:00
|
|
|
a
|
|
|
|
} else {
|
|
|
|
panic!("MemoryTransport not listening on an address!");
|
|
|
|
};
|
2020-06-12 17:41:04 +02:00
|
|
|
|
2019-11-25 17:33:59 +01:00
|
|
|
async_std::task::spawn(async move {
|
|
|
|
let listener_event = listener.next().await.unwrap();
|
|
|
|
let (listener_upgrade, _) = listener_event.unwrap().into_upgrade().unwrap();
|
|
|
|
let conn = listener_upgrade.await.unwrap();
|
2020-08-10 12:54:55 +02:00
|
|
|
recv_ping(conn).await.unwrap();
|
2019-11-25 17:33:59 +01:00
|
|
|
});
|
2018-11-04 09:47:15 +01:00
|
|
|
|
2019-11-25 17:33:59 +01:00
|
|
|
async_std::task::block_on(async move {
|
|
|
|
let c = MemoryTransport.dial(listener_addr).unwrap().await.unwrap();
|
2020-08-10 12:54:55 +02:00
|
|
|
let (_, rtt) = send_ping(c).await.unwrap();
|
2019-11-25 17:33:59 +01:00
|
|
|
assert!(rtt > Duration::from_secs(0));
|
|
|
|
});
|
2018-11-04 09:47:15 +01:00
|
|
|
}
|
|
|
|
}
|