2017-11-22 10:58:06 +01:00
|
|
|
// Copyright 2017 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.
|
|
|
|
|
|
|
|
//! Handles the `/ipfs/ping/1.0.0` protocol. This allows pinging a remote node and waiting for an
|
|
|
|
//! answer.
|
|
|
|
//!
|
|
|
|
//! # Usage
|
|
|
|
//!
|
|
|
|
//! Create a `Ping` struct, which implements the `ConnectionUpgrade` trait. When used as a
|
|
|
|
//! connection upgrade, it will produce a tuple of type `(Pinger, impl Future<Item = ()>)` which
|
|
|
|
//! are named the *pinger* and the *ponger*.
|
|
|
|
//!
|
|
|
|
//! The *pinger* has a method named `ping` which will send a ping to the remote, while the *ponger*
|
|
|
|
//! is a future that will process the data received on the socket and will be signalled only when
|
|
|
|
//! the connection closes.
|
|
|
|
//!
|
|
|
|
//! # About timeouts
|
|
|
|
//!
|
|
|
|
//! For technical reasons, this crate doesn't handle timeouts. The action of pinging returns a
|
|
|
|
//! future that is signalled only when the remote answers. If the remote is not responsive, the
|
|
|
|
//! future will never be signalled.
|
|
|
|
//!
|
|
|
|
//! For implementation reasons, resources allocated for a ping are only ever fully reclaimed after
|
|
|
|
//! a pong has been received by the remote. Therefore if you repeatidely ping a non-responsive
|
|
|
|
//! remote you will end up using more and memory memory (albeit the amount is very very small every
|
|
|
|
//! time), even if you destroy the future returned by `ping`.
|
|
|
|
//!
|
|
|
|
//! This is probably not a problem in practice, because the nature of the ping protocol is to
|
|
|
|
//! determine whether a remote is still alive, and any reasonable user of this crate will close
|
|
|
|
//! connections to non-responsive remotes.
|
|
|
|
//!
|
2017-12-06 13:36:41 +01:00
|
|
|
//! # Example
|
|
|
|
//!
|
|
|
|
//! ```no_run
|
|
|
|
//! extern crate futures;
|
|
|
|
//! extern crate libp2p_ping;
|
2018-05-16 12:59:36 +02:00
|
|
|
//! extern crate libp2p_core;
|
2017-12-06 13:36:41 +01:00
|
|
|
//! extern crate libp2p_tcp_transport;
|
2018-10-25 05:26:37 -04:00
|
|
|
//! extern crate tokio;
|
2018-03-07 16:20:55 +01:00
|
|
|
//!
|
2018-09-20 16:55:57 +02:00
|
|
|
//! use futures::{Future, Stream};
|
2018-08-06 17:16:27 +02:00
|
|
|
//! use libp2p_ping::{Ping, PingOutput};
|
2018-05-16 12:59:36 +02:00
|
|
|
//! use libp2p_core::Transport;
|
2018-10-25 05:26:37 -04:00
|
|
|
//! use tokio::runtime::current_thread::Runtime;
|
2018-03-07 16:20:55 +01:00
|
|
|
//!
|
2017-12-06 13:36:41 +01:00
|
|
|
//! # fn main() {
|
2018-07-16 12:15:27 +02:00
|
|
|
//! let ping_finished_future = libp2p_tcp_transport::TcpConfig::new()
|
2018-09-20 16:55:57 +02:00
|
|
|
//! .with_upgrade(Ping::default())
|
2018-05-16 12:59:36 +02:00
|
|
|
//! .dial("127.0.0.1:12345".parse::<libp2p_core::Multiaddr>().unwrap()).unwrap_or_else(|_| panic!())
|
2018-10-17 10:17:40 +01:00
|
|
|
//! .and_then(|out| {
|
2018-08-06 17:16:27 +02:00
|
|
|
//! match out {
|
2018-09-06 09:54:35 +02:00
|
|
|
//! PingOutput::Ponger(processing) => Box::new(processing) as Box<Future<Item = _, Error = _> + Send>,
|
2018-09-20 16:55:57 +02:00
|
|
|
//! PingOutput::Pinger(mut pinger) => {
|
|
|
|
//! pinger.ping(());
|
|
|
|
//! let f = pinger.into_future().map(|_| ()).map_err(|(err, _)| err);
|
2018-09-06 09:54:35 +02:00
|
|
|
//! Box::new(f) as Box<Future<Item = _, Error = _> + Send>
|
2018-08-06 17:16:27 +02:00
|
|
|
//! },
|
|
|
|
//! }
|
2017-12-06 13:36:41 +01:00
|
|
|
//! });
|
2018-03-07 16:20:55 +01:00
|
|
|
//!
|
2017-12-06 13:36:41 +01:00
|
|
|
//! // Runs until the ping arrives.
|
2018-10-25 05:26:37 -04:00
|
|
|
//! let mut rt = Runtime::new().unwrap();
|
|
|
|
//! let _ = rt.block_on(ping_finished_future).unwrap();
|
2017-12-06 13:36:41 +01:00
|
|
|
//! # }
|
|
|
|
//! ```
|
|
|
|
//!
|
2017-11-22 10:58:06 +01:00
|
|
|
|
|
|
|
extern crate bytes;
|
|
|
|
extern crate futures;
|
2018-05-16 12:59:36 +02:00
|
|
|
extern crate libp2p_core;
|
2018-02-14 18:24:59 +01:00
|
|
|
#[macro_use]
|
|
|
|
extern crate log;
|
2017-11-22 10:58:06 +01:00
|
|
|
extern crate multistream_select;
|
|
|
|
extern crate parking_lot;
|
|
|
|
extern crate rand;
|
2018-06-22 16:12:23 +02:00
|
|
|
extern crate tokio_codec;
|
2017-11-22 10:58:06 +01:00
|
|
|
extern crate tokio_io;
|
|
|
|
|
2018-03-07 16:20:55 +01:00
|
|
|
use bytes::{BufMut, Bytes, BytesMut};
|
2018-09-20 16:55:57 +02:00
|
|
|
use futures::{prelude::*, future::{FutureResult, IntoFuture}, task};
|
2018-06-19 14:38:55 +02:00
|
|
|
use libp2p_core::{ConnectionUpgrade, Endpoint};
|
2018-08-06 17:16:27 +02:00
|
|
|
use rand::{distributions::Standard, prelude::*, rngs::EntropyRng};
|
2018-09-20 16:55:57 +02:00
|
|
|
use std::collections::VecDeque;
|
2017-11-22 10:58:06 +01:00
|
|
|
use std::io::Error as IoError;
|
2018-09-20 16:55:57 +02:00
|
|
|
use std::{iter, marker::PhantomData, mem};
|
2018-06-22 16:12:23 +02:00
|
|
|
use tokio_codec::{Decoder, Encoder, Framed};
|
2018-05-14 15:55:16 +02:00
|
|
|
use tokio_io::{AsyncRead, AsyncWrite};
|
2017-11-22 10:58:06 +01:00
|
|
|
|
|
|
|
/// Represents a prototype for an upgrade to handle the ping protocol.
|
|
|
|
///
|
|
|
|
/// According to the design of libp2p, this struct would normally contain the configuration options
|
|
|
|
/// for the protocol, but in the case of `Ping` no configuration is required.
|
2018-09-20 19:53:31 +02:00
|
|
|
#[derive(Debug, Copy, Clone)]
|
2018-09-20 16:55:57 +02:00
|
|
|
pub struct Ping<TUserData = ()>(PhantomData<TUserData>);
|
|
|
|
|
2018-09-20 19:53:31 +02:00
|
|
|
impl<TUserData> Default for Ping<TUserData> {
|
|
|
|
#[inline]
|
|
|
|
fn default() -> Self {
|
|
|
|
Ping(PhantomData)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
/// Output of a `Ping` upgrade.
|
|
|
|
pub enum PingOutput<TSocket, TUserData> {
|
|
|
|
/// We are on the dialing side.
|
|
|
|
Pinger(PingDialer<TSocket, TUserData>),
|
2018-08-06 17:16:27 +02:00
|
|
|
/// We are on the listening side.
|
2018-09-20 16:55:57 +02:00
|
|
|
Ponger(PingListener<TSocket>),
|
2018-08-06 17:16:27 +02:00
|
|
|
}
|
|
|
|
|
2018-10-17 10:17:40 +01:00
|
|
|
impl<TSocket, TUserData> ConnectionUpgrade<TSocket> for Ping<TUserData>
|
2018-03-07 16:20:55 +01:00
|
|
|
where
|
2018-09-20 16:55:57 +02:00
|
|
|
TSocket: AsyncRead + AsyncWrite,
|
2017-11-22 10:58:06 +01:00
|
|
|
{
|
2018-03-07 16:20:55 +01:00
|
|
|
type NamesIter = iter::Once<(Bytes, Self::UpgradeIdentifier)>;
|
|
|
|
type UpgradeIdentifier = ();
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn protocol_names(&self) -> Self::NamesIter {
|
|
|
|
iter::once(("/ipfs/ping/1.0.0".into(), ()))
|
|
|
|
}
|
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
type Output = PingOutput<TSocket, TUserData>;
|
2018-10-17 10:17:40 +01:00
|
|
|
type Future = FutureResult<Self::Output, IoError>;
|
2018-03-07 16:20:55 +01:00
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn upgrade(
|
|
|
|
self,
|
2018-09-20 16:55:57 +02:00
|
|
|
socket: TSocket,
|
2018-03-07 16:20:55 +01:00
|
|
|
_: Self::UpgradeIdentifier,
|
2018-08-06 17:16:27 +02:00
|
|
|
endpoint: Endpoint,
|
2018-03-07 16:20:55 +01:00
|
|
|
) -> Self::Future {
|
2018-08-06 17:16:27 +02:00
|
|
|
let out = match endpoint {
|
|
|
|
Endpoint::Dialer => upgrade_as_dialer(socket),
|
|
|
|
Endpoint::Listener => upgrade_as_listener(socket),
|
2018-03-07 16:20:55 +01:00
|
|
|
};
|
|
|
|
|
2018-10-17 10:17:40 +01:00
|
|
|
Ok(out).into_future()
|
2018-08-06 17:16:27 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Upgrades a connection from the dialer side.
|
2018-09-20 16:55:57 +02:00
|
|
|
fn upgrade_as_dialer<TSocket, TUserData>(socket: TSocket) -> PingOutput<TSocket, TUserData>
|
|
|
|
where TSocket: AsyncRead + AsyncWrite,
|
|
|
|
{
|
|
|
|
let dialer = PingDialer {
|
|
|
|
inner: Framed::new(socket, Codec),
|
|
|
|
need_writer_flush: false,
|
|
|
|
needs_close: false,
|
|
|
|
sent_pings: VecDeque::with_capacity(4),
|
2018-08-06 17:16:27 +02:00
|
|
|
rng: EntropyRng::default(),
|
2018-09-20 16:55:57 +02:00
|
|
|
pings_to_send: VecDeque::with_capacity(4),
|
2018-08-06 17:16:27 +02:00
|
|
|
};
|
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
PingOutput::Pinger(dialer)
|
2017-11-22 10:58:06 +01:00
|
|
|
}
|
|
|
|
|
2018-08-06 17:16:27 +02:00
|
|
|
/// Upgrades a connection from the listener side.
|
2018-09-20 16:55:57 +02:00
|
|
|
fn upgrade_as_listener<TSocket, TUserData>(socket: TSocket) -> PingOutput<TSocket, TUserData>
|
|
|
|
where TSocket: AsyncRead + AsyncWrite,
|
|
|
|
{
|
|
|
|
let listener = PingListener {
|
|
|
|
inner: Framed::new(socket, Codec),
|
|
|
|
state: PingListenerState::Listening,
|
|
|
|
};
|
2018-08-06 17:16:27 +02:00
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
PingOutput::Ponger(listener)
|
2018-08-06 17:16:27 +02:00
|
|
|
}
|
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
/// Sends pings and receives the pongs.
|
|
|
|
///
|
|
|
|
/// Implements `Stream`. The stream indicates when we receive a pong.
|
|
|
|
pub struct PingDialer<TSocket, TUserData> {
|
|
|
|
/// The underlying socket.
|
|
|
|
inner: Framed<TSocket, Codec>,
|
|
|
|
/// If true, need to flush the sink.
|
|
|
|
need_writer_flush: bool,
|
|
|
|
/// If true, need to close the sink.
|
|
|
|
needs_close: bool,
|
|
|
|
/// List of pings that have been sent to the remote and that are waiting for an answer.
|
|
|
|
sent_pings: VecDeque<(Bytes, TUserData)>,
|
|
|
|
/// Random number generator for the ping payload.
|
2018-07-18 18:47:58 +02:00
|
|
|
rng: EntropyRng,
|
2018-09-20 16:55:57 +02:00
|
|
|
/// List of pings to send to the remote.
|
|
|
|
pings_to_send: VecDeque<(Bytes, TUserData)>,
|
2017-11-22 10:58:06 +01:00
|
|
|
}
|
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
impl<TSocket, TUserData> PingDialer<TSocket, TUserData> {
|
|
|
|
/// Sends a ping to the remote.
|
2018-03-07 16:20:55 +01:00
|
|
|
///
|
2018-09-20 16:55:57 +02:00
|
|
|
/// The stream will produce an event containing the user data when we receive the pong.
|
|
|
|
pub fn ping(&mut self, user_data: TUserData) {
|
2018-07-18 18:47:58 +02:00
|
|
|
let payload: [u8; 32] = self.rng.sample(Standard);
|
2018-05-17 15:14:13 +02:00
|
|
|
debug!("Preparing for ping with payload {:?}", payload);
|
2018-09-20 16:55:57 +02:00
|
|
|
self.pings_to_send.push_back((Bytes::from(payload.to_vec()), user_data));
|
2018-03-07 16:20:55 +01:00
|
|
|
}
|
2017-11-22 10:58:06 +01:00
|
|
|
}
|
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
impl<TSocket, TUserData> Stream for PingDialer<TSocket, TUserData>
|
|
|
|
where TSocket: AsyncRead + AsyncWrite,
|
|
|
|
{
|
|
|
|
type Item = TUserData;
|
|
|
|
type Error = IoError;
|
|
|
|
|
|
|
|
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
2018-09-21 10:06:04 +02:00
|
|
|
if self.needs_close {
|
|
|
|
match self.inner.close() {
|
|
|
|
Ok(Async::Ready(())) => return Ok(Async::Ready(None)),
|
|
|
|
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
while let Some((ping, user_data)) = self.pings_to_send.pop_front() {
|
|
|
|
match self.inner.start_send(ping.clone()) {
|
|
|
|
Ok(AsyncSink::Ready) => self.need_writer_flush = true,
|
|
|
|
Ok(AsyncSink::NotReady(_)) => {
|
|
|
|
self.pings_to_send.push_front((ping, user_data));
|
|
|
|
break;
|
|
|
|
},
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
|
|
|
|
self.sent_pings.push_back((ping, user_data));
|
2018-07-18 18:47:58 +02:00
|
|
|
}
|
2018-09-20 16:55:57 +02:00
|
|
|
|
|
|
|
if self.need_writer_flush {
|
|
|
|
match self.inner.poll_complete() {
|
|
|
|
Ok(Async::Ready(())) => self.need_writer_flush = false,
|
|
|
|
Ok(Async::NotReady) => (),
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
loop {
|
|
|
|
match self.inner.poll() {
|
|
|
|
Ok(Async::Ready(Some(pong))) => {
|
|
|
|
if let Some(pos) = self.sent_pings.iter().position(|&(ref p, _)| p == &pong) {
|
|
|
|
let (_, user_data) = self.sent_pings.remove(pos)
|
|
|
|
.expect("Grabbed a valid position just above");
|
|
|
|
return Ok(Async::Ready(Some(user_data)));
|
|
|
|
} else {
|
2018-09-21 10:06:04 +02:00
|
|
|
debug!("Received pong that doesn't match what we sent: {:?}", pong);
|
2018-09-20 16:55:57 +02:00
|
|
|
}
|
|
|
|
},
|
|
|
|
Ok(Async::NotReady) => break,
|
|
|
|
Ok(Async::Ready(None)) => {
|
|
|
|
// Notify the current task so that we poll again.
|
|
|
|
self.needs_close = true;
|
|
|
|
task::current().notify();
|
|
|
|
return Ok(Async::NotReady);
|
|
|
|
}
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Async::NotReady)
|
2018-07-18 18:47:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-20 16:55:57 +02:00
|
|
|
/// Listens to incoming pings and answers them.
|
|
|
|
///
|
|
|
|
/// Implements `Future`. The future terminates when the underlying socket closes.
|
|
|
|
pub struct PingListener<TSocket> {
|
|
|
|
/// The underlying socket.
|
|
|
|
inner: Framed<TSocket, Codec>,
|
|
|
|
/// State of the listener.
|
|
|
|
state: PingListenerState,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
enum PingListenerState {
|
|
|
|
/// We are waiting for the next ping on the socket.
|
|
|
|
Listening,
|
|
|
|
/// We are trying to send a pong.
|
|
|
|
Sending(Bytes),
|
|
|
|
/// We are flusing the underlying sink.
|
|
|
|
Flushing,
|
|
|
|
/// We are shutting down everything.
|
|
|
|
Closing,
|
|
|
|
/// A panic happened during the processing.
|
|
|
|
Poisoned,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<TSocket> Future for PingListener<TSocket>
|
|
|
|
where TSocket: AsyncRead + AsyncWrite
|
|
|
|
{
|
|
|
|
type Item = ();
|
|
|
|
type Error = IoError;
|
|
|
|
|
|
|
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
|
|
|
loop {
|
|
|
|
match mem::replace(&mut self.state, PingListenerState::Poisoned) {
|
|
|
|
PingListenerState::Listening => {
|
|
|
|
match self.inner.poll() {
|
|
|
|
Ok(Async::Ready(Some(payload))) => {
|
2018-10-29 20:38:32 +11:00
|
|
|
debug!("Received ping (payload={:?}); sending back", payload);
|
2018-09-20 16:55:57 +02:00
|
|
|
self.state = PingListenerState::Sending(payload.freeze())
|
|
|
|
},
|
|
|
|
Ok(Async::Ready(None)) => self.state = PingListenerState::Closing,
|
|
|
|
Ok(Async::NotReady) => {
|
|
|
|
self.state = PingListenerState::Listening;
|
|
|
|
return Ok(Async::NotReady);
|
|
|
|
},
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
PingListenerState::Sending(data) => {
|
|
|
|
match self.inner.start_send(data) {
|
|
|
|
Ok(AsyncSink::Ready) => self.state = PingListenerState::Flushing,
|
|
|
|
Ok(AsyncSink::NotReady(data)) => {
|
|
|
|
self.state = PingListenerState::Sending(data);
|
|
|
|
return Ok(Async::NotReady);
|
|
|
|
},
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
PingListenerState::Flushing => {
|
|
|
|
match self.inner.poll_complete() {
|
|
|
|
Ok(Async::Ready(())) => self.state = PingListenerState::Listening,
|
|
|
|
Ok(Async::NotReady) => {
|
|
|
|
self.state = PingListenerState::Flushing;
|
|
|
|
return Ok(Async::NotReady);
|
|
|
|
},
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
PingListenerState::Closing => {
|
|
|
|
match self.inner.close() {
|
|
|
|
Ok(Async::Ready(())) => return Ok(Async::Ready(())),
|
|
|
|
Ok(Async::NotReady) => {
|
|
|
|
self.state = PingListenerState::Closing;
|
|
|
|
return Ok(Async::NotReady);
|
|
|
|
},
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
PingListenerState::Poisoned => panic!("Poisoned or errored PingListener"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-11-22 10:58:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Implementation of the `Codec` trait of tokio-io. Splits frames into groups of 32 bytes.
|
|
|
|
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
|
|
|
|
struct Codec;
|
|
|
|
|
|
|
|
impl Decoder for Codec {
|
2018-03-07 16:20:55 +01:00
|
|
|
type Item = BytesMut;
|
|
|
|
type Error = IoError;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<BytesMut>, IoError> {
|
|
|
|
if buf.len() >= 32 {
|
|
|
|
Ok(Some(buf.split_to(32)))
|
|
|
|
} else {
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
}
|
2017-11-22 10:58:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Encoder for Codec {
|
2018-03-07 16:20:55 +01:00
|
|
|
type Item = Bytes;
|
|
|
|
type Error = IoError;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn encode(&mut self, mut data: Bytes, buf: &mut BytesMut) -> Result<(), IoError> {
|
2018-09-20 16:55:57 +02:00
|
|
|
if !data.is_empty() {
|
2018-03-07 16:20:55 +01:00
|
|
|
let split = 32 * (1 + ((data.len() - 1) / 32));
|
2018-07-20 09:49:17 +02:00
|
|
|
buf.reserve(split);
|
2018-03-07 16:20:55 +01:00
|
|
|
buf.put(data.split_to(split));
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2017-11-22 10:58:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2018-10-25 05:26:37 -04:00
|
|
|
extern crate tokio;
|
2018-07-16 12:15:27 +02:00
|
|
|
extern crate tokio_tcp;
|
2018-03-07 16:20:55 +01:00
|
|
|
|
2018-10-25 05:26:37 -04:00
|
|
|
use self::tokio::runtime::current_thread::Runtime;
|
2018-07-16 12:15:27 +02:00
|
|
|
use self::tokio_tcp::TcpListener;
|
|
|
|
use self::tokio_tcp::TcpStream;
|
2018-08-06 17:16:27 +02:00
|
|
|
use super::{Ping, PingOutput};
|
2018-10-17 10:17:40 +01:00
|
|
|
use futures::{Future, Stream};
|
|
|
|
use libp2p_core::{ConnectionUpgrade, Endpoint};
|
2018-03-07 16:20:55 +01:00
|
|
|
|
2018-08-06 17:16:27 +02:00
|
|
|
// TODO: rewrite tests with the MemoryTransport
|
|
|
|
|
2018-03-07 16:20:55 +01:00
|
|
|
#[test]
|
|
|
|
fn ping_pong() {
|
2018-07-16 12:15:27 +02:00
|
|
|
let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap();
|
2018-03-07 16:20:55 +01:00
|
|
|
let listener_addr = listener.local_addr().unwrap();
|
|
|
|
|
|
|
|
let server = listener
|
|
|
|
.incoming()
|
|
|
|
.into_future()
|
|
|
|
.map_err(|(e, _)| e.into())
|
|
|
|
.and_then(|(c, _)| {
|
2018-09-20 16:55:57 +02:00
|
|
|
Ping::<()>::default().upgrade(
|
2018-07-16 12:15:27 +02:00
|
|
|
c.unwrap(),
|
2018-03-07 16:20:55 +01:00
|
|
|
(),
|
|
|
|
Endpoint::Listener,
|
|
|
|
)
|
|
|
|
})
|
2018-10-17 10:17:40 +01:00
|
|
|
.and_then(|out| match out {
|
2018-08-06 17:16:27 +02:00
|
|
|
PingOutput::Ponger(service) => service,
|
|
|
|
_ => unreachable!(),
|
2018-03-07 16:20:55 +01:00
|
|
|
});
|
|
|
|
|
2018-07-16 12:15:27 +02:00
|
|
|
let client = TcpStream::connect(&listener_addr)
|
2018-03-07 16:20:55 +01:00
|
|
|
.map_err(|e| e.into())
|
|
|
|
.and_then(|c| {
|
2018-09-20 16:55:57 +02:00
|
|
|
Ping::<()>::default().upgrade(
|
2018-03-07 16:20:55 +01:00
|
|
|
c,
|
|
|
|
(),
|
|
|
|
Endpoint::Dialer,
|
|
|
|
)
|
|
|
|
})
|
2018-10-17 10:17:40 +01:00
|
|
|
.and_then(|out| match out {
|
2018-09-20 16:55:57 +02:00
|
|
|
PingOutput::Pinger(mut pinger) => {
|
|
|
|
pinger.ping(());
|
|
|
|
pinger.into_future().map(|_| ()).map_err(|_| panic!())
|
|
|
|
},
|
2018-08-06 17:16:27 +02:00
|
|
|
_ => unreachable!(),
|
|
|
|
})
|
|
|
|
.map(|_| ());
|
2018-10-25 05:26:37 -04:00
|
|
|
let mut rt = Runtime::new().unwrap();
|
|
|
|
let _ = rt.block_on(server.select(client).map_err(|_| panic!())).unwrap();
|
2018-03-07 16:20:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn multipings() {
|
|
|
|
// Check that we can send multiple pings in a row and it will still work.
|
2018-07-16 12:15:27 +02:00
|
|
|
let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap();
|
2018-03-07 16:20:55 +01:00
|
|
|
let listener_addr = listener.local_addr().unwrap();
|
|
|
|
|
|
|
|
let server = listener
|
|
|
|
.incoming()
|
|
|
|
.into_future()
|
|
|
|
.map_err(|(e, _)| e.into())
|
|
|
|
.and_then(|(c, _)| {
|
2018-09-20 16:55:57 +02:00
|
|
|
Ping::<u32>::default().upgrade(
|
2018-07-16 12:15:27 +02:00
|
|
|
c.unwrap(),
|
2018-03-07 16:20:55 +01:00
|
|
|
(),
|
|
|
|
Endpoint::Listener,
|
|
|
|
)
|
|
|
|
})
|
2018-10-17 10:17:40 +01:00
|
|
|
.and_then(|out| match out {
|
2018-08-06 17:16:27 +02:00
|
|
|
PingOutput::Ponger(service) => service,
|
|
|
|
_ => unreachable!(),
|
|
|
|
});
|
2018-03-07 16:20:55 +01:00
|
|
|
|
2018-07-16 12:15:27 +02:00
|
|
|
let client = TcpStream::connect(&listener_addr)
|
2018-03-07 16:20:55 +01:00
|
|
|
.map_err(|e| e.into())
|
|
|
|
.and_then(|c| {
|
2018-09-20 16:55:57 +02:00
|
|
|
Ping::<u32>::default().upgrade(
|
2018-03-07 16:20:55 +01:00
|
|
|
c,
|
|
|
|
(),
|
|
|
|
Endpoint::Dialer,
|
|
|
|
)
|
|
|
|
})
|
2018-10-17 10:17:40 +01:00
|
|
|
.and_then(|out| match out {
|
2018-09-20 16:55:57 +02:00
|
|
|
PingOutput::Pinger(mut pinger) => {
|
|
|
|
for n in 0..20 {
|
|
|
|
pinger.ping(n);
|
|
|
|
}
|
|
|
|
|
|
|
|
pinger
|
|
|
|
.take(20)
|
|
|
|
.collect()
|
|
|
|
.map(|val| { assert_eq!(val, (0..20).collect::<Vec<_>>()); })
|
2018-08-06 17:16:27 +02:00
|
|
|
.map_err(|_| panic!())
|
2018-09-20 16:55:57 +02:00
|
|
|
},
|
2018-08-06 17:16:27 +02:00
|
|
|
_ => unreachable!(),
|
2018-03-07 16:20:55 +01:00
|
|
|
});
|
2018-10-25 05:26:37 -04:00
|
|
|
let mut rt = Runtime::new().unwrap();
|
|
|
|
let _ = rt.block_on(server.select(client)).unwrap_or_else(|_| panic!());
|
2018-03-07 16:20:55 +01:00
|
|
|
}
|
2017-11-22 10:58:06 +01:00
|
|
|
}
|