2017-11-02 11:58:02 +01:00
|
|
|
// Copyright 2017 Parity Technologies (UK) Ltd.
|
2018-03-07 16:20:55 +01:00
|
|
|
//
|
|
|
|
// 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
|
2017-11-02 11:58:02 +01:00
|
|
|
// Software is furnished to do so, subject to the following conditions:
|
|
|
|
//
|
2018-03-07 16:20:55 +01:00
|
|
|
// The above copyright notice and this permission notice shall be included in
|
2017-11-02 11:58:02 +01:00
|
|
|
// all copies or substantial portions of the Software.
|
|
|
|
//
|
2018-03-07 16:20:55 +01:00
|
|
|
// 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
|
2017-11-02 11:58:02 +01:00
|
|
|
// DEALINGS IN THE SOFTWARE.
|
|
|
|
|
|
|
|
//! Implementation of the libp2p `Transport` trait for TCP/IP.
|
2017-12-04 16:05:37 +01:00
|
|
|
//!
|
|
|
|
//! Uses [the *tokio* library](https://tokio.rs).
|
2018-03-07 16:20:55 +01:00
|
|
|
//!
|
2017-12-04 16:05:37 +01:00
|
|
|
//! # Usage
|
2018-03-07 16:20:55 +01:00
|
|
|
//!
|
2017-12-04 16:05:37 +01:00
|
|
|
//! Example:
|
|
|
|
//!
|
|
|
|
//! ```
|
|
|
|
//! extern crate libp2p_tcp_transport;
|
|
|
|
//! use libp2p_tcp_transport::TcpConfig;
|
|
|
|
//!
|
|
|
|
//! # fn main() {
|
2018-07-16 12:15:27 +02:00
|
|
|
//! let tcp = TcpConfig::new();
|
2017-12-04 16:05:37 +01:00
|
|
|
//! # }
|
|
|
|
//! ```
|
|
|
|
//!
|
|
|
|
//! The `TcpConfig` structs implements the `Transport` trait of the `swarm` library. See the
|
|
|
|
//! documentation of `swarm` and of libp2p in general to learn how to use the `Transport` trait.
|
2017-11-02 11:58:02 +01:00
|
|
|
|
2018-03-07 16:20:55 +01:00
|
|
|
extern crate futures;
|
2018-05-16 12:59:36 +02:00
|
|
|
extern crate libp2p_core as swarm;
|
2018-03-15 16:08:49 +01:00
|
|
|
#[macro_use]
|
|
|
|
extern crate log;
|
2018-03-07 16:20:55 +01:00
|
|
|
extern crate multiaddr;
|
2018-08-08 17:54:15 +02:00
|
|
|
extern crate tk_listen;
|
2018-07-21 13:01:59 +02:00
|
|
|
extern crate tokio_io;
|
2018-07-16 12:15:27 +02:00
|
|
|
extern crate tokio_tcp;
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
extern crate tokio_current_thread;
|
2017-09-18 16:52:51 +02:00
|
|
|
|
2018-08-09 14:04:15 +02:00
|
|
|
use futures::{future, future::FutureResult, prelude::*, Async, Poll};
|
2018-09-20 19:51:00 +02:00
|
|
|
use multiaddr::{Protocol, Multiaddr, ToMultiaddr};
|
2018-08-09 14:04:15 +02:00
|
|
|
use std::fmt;
|
2018-07-21 13:01:59 +02:00
|
|
|
use std::io::{Error as IoError, Read, Write};
|
2018-05-14 15:55:16 +02:00
|
|
|
use std::iter;
|
|
|
|
use std::net::SocketAddr;
|
2018-08-08 17:54:15 +02:00
|
|
|
use std::time::Duration;
|
2017-11-02 11:58:02 +01:00
|
|
|
use swarm::Transport;
|
2018-08-09 14:04:15 +02:00
|
|
|
use tk_listen::{ListenExt, SleepOnError};
|
2018-07-21 13:01:59 +02:00
|
|
|
use tokio_io::{AsyncRead, AsyncWrite};
|
2018-08-09 14:04:15 +02:00
|
|
|
use tokio_tcp::{ConnectFuture, Incoming, TcpListener, TcpStream};
|
2017-09-18 16:52:51 +02:00
|
|
|
|
2017-12-04 16:05:37 +01:00
|
|
|
/// Represents the configuration for a TCP/IP transport capability for libp2p.
|
2017-11-02 11:58:02 +01:00
|
|
|
///
|
2018-07-16 12:15:27 +02:00
|
|
|
/// The TCP sockets created by libp2p will need to be progressed by running the futures and streams
|
|
|
|
/// obtained by libp2p through the tokio reactor.
|
2018-07-17 11:55:18 +02:00
|
|
|
#[derive(Debug, Clone, Default)]
|
2018-08-08 17:54:15 +02:00
|
|
|
pub struct TcpConfig {
|
2018-09-11 12:04:35 +02:00
|
|
|
/// How long a listener should sleep after receiving an error, before trying again.
|
2018-08-08 17:54:15 +02:00
|
|
|
sleep_on_error: Duration,
|
2018-09-11 12:04:35 +02:00
|
|
|
/// Size of the recv buffer size to set for opened sockets, or `None` to keep default.
|
|
|
|
recv_buffer_size: Option<usize>,
|
|
|
|
/// Size of the send buffer size to set for opened sockets, or `None` to keep default.
|
|
|
|
send_buffer_size: Option<usize>,
|
|
|
|
/// TTL to set for opened sockets, or `None` to keep default.
|
|
|
|
ttl: Option<u32>,
|
|
|
|
/// Keep alive duration to set for opened sockets, or `None` to keep default.
|
|
|
|
keepalive: Option<Option<Duration>>,
|
|
|
|
/// `TCP_NODELAY` to set for opened sockets, or `None` to keep default.
|
|
|
|
nodelay: Option<bool>,
|
2018-08-08 17:54:15 +02:00
|
|
|
}
|
2017-09-18 17:25:04 +02:00
|
|
|
|
2017-12-04 16:05:37 +01:00
|
|
|
impl TcpConfig {
|
2018-07-16 12:15:27 +02:00
|
|
|
/// Creates a new configuration object for TCP/IP.
|
2017-12-04 16:05:37 +01:00
|
|
|
#[inline]
|
2018-07-16 12:15:27 +02:00
|
|
|
pub fn new() -> TcpConfig {
|
2018-08-08 17:54:15 +02:00
|
|
|
TcpConfig {
|
|
|
|
sleep_on_error: Duration::from_millis(100),
|
2018-09-11 12:04:35 +02:00
|
|
|
recv_buffer_size: None,
|
|
|
|
send_buffer_size: None,
|
|
|
|
ttl: None,
|
|
|
|
keepalive: None,
|
|
|
|
nodelay: None,
|
2018-08-08 17:54:15 +02:00
|
|
|
}
|
2017-10-23 11:45:35 +02:00
|
|
|
}
|
2018-09-11 12:04:35 +02:00
|
|
|
|
|
|
|
/// Sets the size of the recv buffer size to set for opened sockets.
|
|
|
|
#[inline]
|
|
|
|
pub fn recv_buffer_size(mut self, value: usize) -> Self {
|
|
|
|
self.recv_buffer_size = Some(value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sets the size of the send buffer size to set for opened sockets.
|
|
|
|
#[inline]
|
|
|
|
pub fn send_buffer_size(mut self, value: usize) -> Self {
|
|
|
|
self.send_buffer_size = Some(value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sets the TTL to set for opened sockets.
|
|
|
|
#[inline]
|
|
|
|
pub fn ttl(mut self, value: u32) -> Self {
|
|
|
|
self.ttl = Some(value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sets the keep alive pinging duration to set for opened sockets.
|
|
|
|
#[inline]
|
|
|
|
pub fn keepalive(mut self, value: Option<Duration>) -> Self {
|
|
|
|
self.keepalive = Some(value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sets the `TCP_NODELAY` to set for opened sockets.
|
|
|
|
#[inline]
|
|
|
|
pub fn nodelay(mut self, value: bool) -> Self {
|
|
|
|
self.nodelay = Some(value);
|
|
|
|
self
|
|
|
|
}
|
2017-09-18 17:25:04 +02:00
|
|
|
}
|
2017-09-18 16:52:51 +02:00
|
|
|
|
2017-12-04 16:05:37 +01:00
|
|
|
impl Transport for TcpConfig {
|
2018-07-21 13:01:59 +02:00
|
|
|
type Output = TcpTransStream;
|
2018-08-09 14:04:15 +02:00
|
|
|
type Listener = TcpListenStream;
|
2018-06-19 14:38:55 +02:00
|
|
|
type ListenerUpgrade = FutureResult<(Self::Output, Self::MultiaddrFuture), IoError>;
|
|
|
|
type MultiaddrFuture = FutureResult<Multiaddr, IoError>;
|
2018-08-09 14:04:15 +02:00
|
|
|
type Dial = TcpDialFut;
|
2017-10-23 11:45:35 +02:00
|
|
|
|
2017-11-24 16:10:34 +01:00
|
|
|
fn listen_on(self, addr: Multiaddr) -> Result<(Self::Listener, Multiaddr), (Self, Multiaddr)> {
|
2017-10-23 11:45:35 +02:00
|
|
|
if let Ok(socket_addr) = multiaddr_to_socketaddr(&addr) {
|
2018-07-16 12:15:27 +02:00
|
|
|
let listener = TcpListener::bind(&socket_addr);
|
2017-11-24 16:10:34 +01:00
|
|
|
// We need to build the `Multiaddr` to return from this function. If an error happened,
|
|
|
|
// just return the original multiaddr.
|
|
|
|
let new_addr = match listener {
|
|
|
|
Ok(ref l) => if let Ok(new_s_addr) = l.local_addr() {
|
2018-03-07 16:20:55 +01:00
|
|
|
new_s_addr.to_multiaddr().expect(
|
|
|
|
"multiaddr generated from socket addr is \
|
|
|
|
always valid",
|
|
|
|
)
|
2017-11-24 16:10:34 +01:00
|
|
|
} else {
|
|
|
|
addr
|
2018-03-07 16:20:55 +01:00
|
|
|
},
|
2017-11-24 16:10:34 +01:00
|
|
|
Err(_) => addr,
|
|
|
|
};
|
2017-12-19 18:09:17 +01:00
|
|
|
|
2018-05-17 15:14:13 +02:00
|
|
|
debug!("Now listening on {}", new_addr);
|
2018-08-08 17:54:15 +02:00
|
|
|
let sleep_on_error = self.sleep_on_error;
|
2018-08-09 14:04:15 +02:00
|
|
|
let inner = listener
|
|
|
|
.map_err(Some)
|
|
|
|
.map(move |l| l.incoming().sleep_on_error(sleep_on_error));
|
2018-09-11 12:04:35 +02:00
|
|
|
Ok((
|
|
|
|
TcpListenStream {
|
|
|
|
inner,
|
|
|
|
config: self,
|
|
|
|
},
|
|
|
|
new_addr,
|
|
|
|
))
|
2017-10-23 11:45:35 +02:00
|
|
|
} else {
|
2017-11-02 11:58:02 +01:00
|
|
|
Err((self, addr))
|
2017-10-23 11:45:35 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-02 11:58:02 +01:00
|
|
|
fn dial(self, addr: Multiaddr) -> Result<Self::Dial, (Self, Multiaddr)> {
|
2017-10-23 11:45:35 +02:00
|
|
|
if let Ok(socket_addr) = multiaddr_to_socketaddr(&addr) {
|
2018-07-02 10:51:10 +02:00
|
|
|
// As an optimization, we check that the address is not of the form `0.0.0.0`.
|
|
|
|
// If so, we instantly refuse dialing instead of going through the kernel.
|
|
|
|
if socket_addr.port() != 0 && !socket_addr.ip().is_unspecified() {
|
|
|
|
debug!("Dialing {}", addr);
|
2018-08-09 14:04:15 +02:00
|
|
|
Ok(TcpDialFut {
|
|
|
|
inner: TcpStream::connect(&socket_addr),
|
2018-09-11 12:04:35 +02:00
|
|
|
config: self,
|
2018-08-09 14:04:15 +02:00
|
|
|
addr: Some(addr),
|
|
|
|
})
|
2018-07-02 10:51:10 +02:00
|
|
|
} else {
|
|
|
|
debug!("Instantly refusing dialing {}, as it is invalid", addr);
|
|
|
|
Err((self, addr))
|
|
|
|
}
|
2017-10-23 11:45:35 +02:00
|
|
|
} else {
|
2017-11-02 11:58:02 +01:00
|
|
|
Err((self, addr))
|
2017-10-23 11:45:35 +02:00
|
|
|
}
|
|
|
|
}
|
2018-02-08 13:50:16 +01:00
|
|
|
|
|
|
|
fn nat_traversal(&self, server: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr> {
|
2018-08-09 14:04:15 +02:00
|
|
|
// Check that `server` only has two components and retreive them.
|
|
|
|
let mut server_protocols_iter = server.iter();
|
|
|
|
let server_proto1 = server_protocols_iter.next()?;
|
|
|
|
let server_proto2 = server_protocols_iter.next()?;
|
|
|
|
if server_protocols_iter.next().is_some() {
|
|
|
|
return None;
|
|
|
|
}
|
2018-02-08 13:50:16 +01:00
|
|
|
|
2018-08-09 14:04:15 +02:00
|
|
|
// Check that `observed` only has two components and retreive them.
|
|
|
|
let mut observed_protocols_iter = observed.iter();
|
|
|
|
let observed_proto1 = observed_protocols_iter.next()?;
|
|
|
|
let observed_proto2 = observed_protocols_iter.next()?;
|
|
|
|
if observed_protocols_iter.next().is_some() {
|
2018-02-08 13:50:16 +01:00
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check that `server` is a valid TCP/IP address.
|
2018-08-09 14:04:15 +02:00
|
|
|
match (&server_proto1, &server_proto2) {
|
2018-09-20 19:51:00 +02:00
|
|
|
(&Protocol::Ip4(_), &Protocol::Tcp(_))
|
|
|
|
| (&Protocol::Ip6(_), &Protocol::Tcp(_)) => {}
|
2018-02-08 13:50:16 +01:00
|
|
|
_ => return None,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check that `observed` is a valid TCP/IP address.
|
2018-08-09 14:04:15 +02:00
|
|
|
match (&observed_proto1, &observed_proto2) {
|
2018-09-20 19:51:00 +02:00
|
|
|
(&Protocol::Ip4(_), &Protocol::Tcp(_))
|
|
|
|
| (&Protocol::Ip6(_), &Protocol::Tcp(_)) => {}
|
2018-02-08 13:50:16 +01:00
|
|
|
_ => return None,
|
|
|
|
}
|
|
|
|
|
2018-08-09 14:04:15 +02:00
|
|
|
let result = iter::once(observed_proto1.clone())
|
|
|
|
.chain(iter::once(server_proto2.clone()))
|
2018-02-08 13:50:16 +01:00
|
|
|
.collect();
|
|
|
|
Some(result)
|
|
|
|
}
|
2017-09-18 16:52:51 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// This type of logic should probably be moved into the multiaddr package
|
2017-11-24 16:10:34 +01:00
|
|
|
fn multiaddr_to_socketaddr(addr: &Multiaddr) -> Result<SocketAddr, ()> {
|
2018-08-09 14:04:15 +02:00
|
|
|
let mut iter = addr.iter();
|
|
|
|
let proto1 = iter.next().ok_or(())?;
|
|
|
|
let proto2 = iter.next().ok_or(())?;
|
2017-10-23 11:45:35 +02:00
|
|
|
|
2018-08-09 14:04:15 +02:00
|
|
|
if iter.next().is_some() {
|
2017-12-15 17:29:54 +01:00
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
|
2018-08-09 14:04:15 +02:00
|
|
|
match (proto1, proto2) {
|
2018-09-20 19:51:00 +02:00
|
|
|
(Protocol::Ip4(ip), Protocol::Tcp(port)) => Ok(SocketAddr::new(ip.into(), port)),
|
|
|
|
(Protocol::Ip6(ip), Protocol::Tcp(port)) => Ok(SocketAddr::new(ip.into(), port)),
|
2018-08-09 14:04:15 +02:00
|
|
|
_ => Err(()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-11 12:04:35 +02:00
|
|
|
/// Applies the socket configuration parameters to a socket.
|
|
|
|
fn apply_config(config: &TcpConfig, socket: &TcpStream) -> Result<(), IoError> {
|
|
|
|
if let Some(recv_buffer_size) = config.recv_buffer_size {
|
|
|
|
socket.set_recv_buffer_size(recv_buffer_size)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(send_buffer_size) = config.send_buffer_size {
|
|
|
|
socket.set_send_buffer_size(send_buffer_size)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(ttl) = config.ttl {
|
|
|
|
socket.set_ttl(ttl)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(keepalive) = config.keepalive {
|
|
|
|
socket.set_keepalive(keepalive)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(nodelay) = config.nodelay {
|
|
|
|
socket.set_nodelay(nodelay)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2018-08-09 14:04:15 +02:00
|
|
|
/// Future that dials a TCP/IP address.
|
|
|
|
#[derive(Debug)]
|
2018-09-04 18:30:57 +08:00
|
|
|
#[must_use = "futures do nothing unless polled"]
|
2018-08-09 14:04:15 +02:00
|
|
|
pub struct TcpDialFut {
|
|
|
|
inner: ConnectFuture,
|
2018-09-11 12:04:35 +02:00
|
|
|
/// Original configuration.
|
|
|
|
config: TcpConfig,
|
2018-08-09 14:04:15 +02:00
|
|
|
/// Address we're dialing. Extracted when the `Future` finishes.
|
|
|
|
addr: Option<Multiaddr>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Future for TcpDialFut {
|
|
|
|
type Item = (TcpTransStream, FutureResult<Multiaddr, IoError>);
|
|
|
|
type Error = IoError;
|
|
|
|
|
|
|
|
fn poll(&mut self) -> Poll<(TcpTransStream, FutureResult<Multiaddr, IoError>), IoError> {
|
|
|
|
match self.inner.poll() {
|
|
|
|
Ok(Async::Ready(stream)) => {
|
2018-09-11 12:04:35 +02:00
|
|
|
apply_config(&self.config, &stream)?;
|
2018-08-09 14:04:15 +02:00
|
|
|
let addr = self
|
|
|
|
.addr
|
|
|
|
.take()
|
|
|
|
.expect("TcpDialFut polled again after finished");
|
|
|
|
let out = TcpTransStream { inner: stream };
|
|
|
|
Ok(Async::Ready((out, future::ok(addr))))
|
|
|
|
}
|
|
|
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
|
|
|
Err(err) => {
|
|
|
|
let addr = self
|
|
|
|
.addr
|
|
|
|
.as_ref()
|
|
|
|
.expect("TcpDialFut polled again after finished");
|
|
|
|
debug!("Error while dialing {:?} => {:?}", addr, err);
|
|
|
|
Err(err)
|
|
|
|
}
|
2017-10-23 11:45:35 +02:00
|
|
|
}
|
2018-08-09 14:04:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Stream that listens on an TCP/IP address.
|
|
|
|
pub struct TcpListenStream {
|
|
|
|
inner: Result<SleepOnError<Incoming>, Option<IoError>>,
|
2018-09-11 12:04:35 +02:00
|
|
|
/// Original configuration.
|
|
|
|
config: TcpConfig,
|
2018-08-09 14:04:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Stream for TcpListenStream {
|
|
|
|
type Item = FutureResult<(TcpTransStream, FutureResult<Multiaddr, IoError>), IoError>;
|
|
|
|
type Error = IoError;
|
|
|
|
|
|
|
|
fn poll(
|
|
|
|
&mut self,
|
|
|
|
) -> Poll<
|
|
|
|
Option<FutureResult<(TcpTransStream, FutureResult<Multiaddr, IoError>), IoError>>,
|
|
|
|
IoError,
|
|
|
|
> {
|
|
|
|
let inner = match self.inner {
|
|
|
|
Ok(ref mut inc) => inc,
|
|
|
|
Err(ref mut err) => {
|
|
|
|
return Err(err.take().expect("poll called again after error"));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
match inner.poll() {
|
|
|
|
Ok(Async::Ready(Some(sock))) => {
|
2018-09-11 12:04:35 +02:00
|
|
|
match apply_config(&self.config, &sock) {
|
|
|
|
Ok(()) => (),
|
|
|
|
Err(err) => return Ok(Async::Ready(Some(future::err(err)))),
|
|
|
|
};
|
|
|
|
|
2018-08-09 14:04:15 +02:00
|
|
|
let addr = match sock.peer_addr() {
|
|
|
|
// TODO: remove this expect()
|
|
|
|
Ok(addr) => addr
|
|
|
|
.to_multiaddr()
|
|
|
|
.expect("generating a multiaddr from a socket addr never fails"),
|
|
|
|
Err(err) => return Ok(Async::Ready(Some(future::err(err)))),
|
|
|
|
};
|
|
|
|
|
|
|
|
debug!("Incoming connection from {}", addr);
|
|
|
|
let ret = future::ok((TcpTransStream { inner: sock }, future::ok(addr)));
|
|
|
|
Ok(Async::Ready(Some(ret)))
|
|
|
|
}
|
|
|
|
Ok(Async::Ready(None)) => Ok(Async::Ready(None)),
|
|
|
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
|
|
|
Err(()) => unreachable!("sleep_on_error never produces an error"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Debug for TcpListenStream {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match self.inner {
|
|
|
|
Ok(_) => write!(f, "TcpListenStream"),
|
|
|
|
Err(None) => write!(f, "TcpListenStream(Errored)"),
|
|
|
|
Err(Some(ref err)) => write!(f, "TcpListenStream({:?})", err),
|
2017-10-23 11:45:35 +02:00
|
|
|
}
|
|
|
|
}
|
2017-09-18 16:52:51 +02:00
|
|
|
}
|
|
|
|
|
2018-07-21 13:01:59 +02:00
|
|
|
/// Wraps around a `TcpStream` and adds logging for important events.
|
2018-08-09 14:04:15 +02:00
|
|
|
#[derive(Debug)]
|
2018-07-21 13:01:59 +02:00
|
|
|
pub struct TcpTransStream {
|
2018-08-09 14:04:15 +02:00
|
|
|
inner: TcpStream,
|
2018-07-21 13:01:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Read for TcpTransStream {
|
|
|
|
#[inline]
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
|
|
|
|
self.inner.read(buf)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-09 14:04:15 +02:00
|
|
|
impl AsyncRead for TcpTransStream {}
|
2018-07-21 13:01:59 +02:00
|
|
|
|
|
|
|
impl Write for TcpTransStream {
|
|
|
|
#[inline]
|
|
|
|
fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
|
|
|
|
self.inner.write(buf)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn flush(&mut self) -> Result<(), IoError> {
|
|
|
|
self.inner.flush()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncWrite for TcpTransStream {
|
|
|
|
#[inline]
|
|
|
|
fn shutdown(&mut self) -> Poll<(), IoError> {
|
|
|
|
AsyncWrite::shutdown(&mut self.inner)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for TcpTransStream {
|
|
|
|
#[inline]
|
|
|
|
fn drop(&mut self) {
|
|
|
|
if let Ok(addr) = self.inner.peer_addr() {
|
|
|
|
debug!("Dropped TCP connection to {:?}", addr);
|
|
|
|
} else {
|
|
|
|
debug!("Dropped TCP connection to undeterminate peer");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-30 15:55:57 +02:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2018-03-07 16:20:55 +01:00
|
|
|
use super::{multiaddr_to_socketaddr, TcpConfig};
|
2017-10-23 11:45:35 +02:00
|
|
|
use futures::stream::Stream;
|
2018-07-11 11:14:40 +02:00
|
|
|
use futures::Future;
|
2017-10-23 11:45:35 +02:00
|
|
|
use multiaddr::Multiaddr;
|
2018-05-14 15:55:16 +02:00
|
|
|
use std;
|
|
|
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
2017-11-02 11:58:02 +01:00
|
|
|
use swarm::Transport;
|
2018-07-16 12:15:27 +02:00
|
|
|
use tokio_current_thread;
|
2018-05-14 15:55:16 +02:00
|
|
|
use tokio_io;
|
2017-10-23 11:45:35 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn multiaddr_to_tcp_conversion() {
|
|
|
|
use std::net::Ipv6Addr;
|
|
|
|
|
2018-03-07 16:20:55 +01:00
|
|
|
assert!(
|
|
|
|
multiaddr_to_socketaddr(&"/ip4/127.0.0.1/udp/1234".parse::<Multiaddr>().unwrap())
|
|
|
|
.is_err()
|
|
|
|
);
|
2017-11-16 23:59:38 +08:00
|
|
|
|
2017-10-23 11:45:35 +02:00
|
|
|
assert_eq!(
|
2017-12-28 18:07:49 +01:00
|
|
|
multiaddr_to_socketaddr(&"/ip4/127.0.0.1/tcp/12345".parse::<Multiaddr>().unwrap()),
|
2017-10-23 11:45:35 +02:00
|
|
|
Ok(SocketAddr::new(
|
|
|
|
IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
|
|
|
|
12345,
|
|
|
|
))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
2018-08-09 14:04:15 +02:00
|
|
|
multiaddr_to_socketaddr(
|
|
|
|
&"/ip4/255.255.255.255/tcp/8080"
|
|
|
|
.parse::<Multiaddr>()
|
|
|
|
.unwrap()
|
|
|
|
),
|
2017-10-23 11:45:35 +02:00
|
|
|
Ok(SocketAddr::new(
|
|
|
|
IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255)),
|
|
|
|
8080,
|
|
|
|
))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
2017-12-28 18:07:49 +01:00
|
|
|
multiaddr_to_socketaddr(&"/ip6/::1/tcp/12345".parse::<Multiaddr>().unwrap()),
|
2017-10-23 11:45:35 +02:00
|
|
|
Ok(SocketAddr::new(
|
|
|
|
IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
|
|
|
|
12345,
|
|
|
|
))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
2018-08-09 14:04:15 +02:00
|
|
|
multiaddr_to_socketaddr(
|
|
|
|
&"/ip6/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/tcp/8080"
|
|
|
|
.parse::<Multiaddr>()
|
|
|
|
.unwrap()
|
|
|
|
),
|
2017-10-23 11:45:35 +02:00
|
|
|
Ok(SocketAddr::new(
|
|
|
|
IpAddr::V6(Ipv6Addr::new(
|
2018-07-11 11:14:40 +02:00
|
|
|
65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
|
2017-10-23 11:45:35 +02:00
|
|
|
)),
|
|
|
|
8080,
|
|
|
|
))
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn communicating_between_dialer_and_listener() {
|
|
|
|
use std::io::Write;
|
|
|
|
|
|
|
|
std::thread::spawn(move || {
|
2017-12-28 18:07:49 +01:00
|
|
|
let addr = "/ip4/127.0.0.1/tcp/12345".parse::<Multiaddr>().unwrap();
|
2018-07-16 12:15:27 +02:00
|
|
|
let tcp = TcpConfig::new();
|
2018-03-07 10:49:11 +01:00
|
|
|
let listener = tcp.listen_on(addr).unwrap().0.for_each(|sock| {
|
|
|
|
sock.and_then(|(sock, _)| {
|
2017-12-19 18:09:17 +01:00
|
|
|
// Define what to do with the socket that just connected to us
|
|
|
|
// Which in this case is read 3 bytes
|
|
|
|
let handle_conn = tokio_io::io::read_exact(sock, [0; 3])
|
|
|
|
.map(|(_, buf)| assert_eq!(buf, [1, 2, 3]))
|
|
|
|
.map_err(|err| panic!("IO error {:?}", err));
|
2017-10-23 11:45:35 +02:00
|
|
|
|
2017-12-19 18:09:17 +01:00
|
|
|
// Spawn the future as a concurrent task
|
2018-07-16 12:15:27 +02:00
|
|
|
tokio_current_thread::spawn(handle_conn);
|
2017-10-23 11:45:35 +02:00
|
|
|
|
2017-12-19 18:09:17 +01:00
|
|
|
Ok(())
|
|
|
|
})
|
2017-10-23 11:45:35 +02:00
|
|
|
});
|
|
|
|
|
2018-07-16 12:15:27 +02:00
|
|
|
tokio_current_thread::block_on_all(listener).unwrap();
|
2017-10-23 11:45:35 +02:00
|
|
|
});
|
|
|
|
std::thread::sleep(std::time::Duration::from_millis(100));
|
2017-12-28 18:07:49 +01:00
|
|
|
let addr = "/ip4/127.0.0.1/tcp/12345".parse::<Multiaddr>().unwrap();
|
2018-07-16 12:15:27 +02:00
|
|
|
let tcp = TcpConfig::new();
|
2017-10-23 11:45:35 +02:00
|
|
|
// Obtain a future socket through dialing
|
|
|
|
let socket = tcp.dial(addr.clone()).unwrap();
|
|
|
|
// Define what to do with the socket once it's obtained
|
2018-07-16 12:15:27 +02:00
|
|
|
let action = socket.then(|sock| -> Result<(), ()> {
|
|
|
|
sock.unwrap().0.write(&[0x1, 0x2, 0x3]).unwrap();
|
|
|
|
Ok(())
|
2017-10-23 11:45:35 +02:00
|
|
|
});
|
|
|
|
// Execute the future in our event loop
|
2018-07-16 12:15:27 +02:00
|
|
|
tokio_current_thread::block_on_all(action).unwrap();
|
2017-10-23 11:45:35 +02:00
|
|
|
std::thread::sleep(std::time::Duration::from_millis(100));
|
|
|
|
}
|
2017-11-24 16:10:34 +01:00
|
|
|
|
|
|
|
#[test]
|
2018-01-02 16:00:08 +01:00
|
|
|
fn replace_port_0_in_returned_multiaddr_ipv4() {
|
2018-07-16 12:15:27 +02:00
|
|
|
let tcp = TcpConfig::new();
|
2017-11-24 16:10:34 +01:00
|
|
|
|
2017-12-28 18:07:49 +01:00
|
|
|
let addr = "/ip4/127.0.0.1/tcp/0".parse::<Multiaddr>().unwrap();
|
2017-11-24 16:10:34 +01:00
|
|
|
assert!(addr.to_string().contains("tcp/0"));
|
|
|
|
|
|
|
|
let (_, new_addr) = tcp.listen_on(addr).unwrap();
|
|
|
|
assert!(!new_addr.to_string().contains("tcp/0"));
|
|
|
|
}
|
2017-12-15 17:29:54 +01:00
|
|
|
|
2018-01-02 16:00:08 +01:00
|
|
|
#[test]
|
|
|
|
fn replace_port_0_in_returned_multiaddr_ipv6() {
|
2018-07-16 12:15:27 +02:00
|
|
|
let tcp = TcpConfig::new();
|
2018-01-02 16:00:08 +01:00
|
|
|
|
2017-12-28 18:07:49 +01:00
|
|
|
let addr: Multiaddr = "/ip6/::1/tcp/0".parse().unwrap();
|
2018-01-02 16:00:08 +01:00
|
|
|
assert!(addr.to_string().contains("tcp/0"));
|
|
|
|
|
|
|
|
let (_, new_addr) = tcp.listen_on(addr).unwrap();
|
|
|
|
assert!(!new_addr.to_string().contains("tcp/0"));
|
|
|
|
}
|
|
|
|
|
2017-12-15 17:29:54 +01:00
|
|
|
#[test]
|
|
|
|
fn larger_addr_denied() {
|
2018-07-16 12:15:27 +02:00
|
|
|
let tcp = TcpConfig::new();
|
2017-12-15 17:29:54 +01:00
|
|
|
|
2018-03-07 16:20:55 +01:00
|
|
|
let addr = "/ip4/127.0.0.1/tcp/12345/tcp/12345"
|
|
|
|
.parse::<Multiaddr>()
|
|
|
|
.unwrap();
|
2017-12-15 17:29:54 +01:00
|
|
|
assert!(tcp.listen_on(addr).is_err());
|
|
|
|
}
|
2018-02-08 13:50:16 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn nat_traversal() {
|
2018-07-16 12:15:27 +02:00
|
|
|
let tcp = TcpConfig::new();
|
2018-02-08 13:50:16 +01:00
|
|
|
|
|
|
|
let server = "/ip4/127.0.0.1/tcp/10000".parse::<Multiaddr>().unwrap();
|
|
|
|
let observed = "/ip4/80.81.82.83/tcp/25000".parse::<Multiaddr>().unwrap();
|
|
|
|
|
|
|
|
let out = tcp.nat_traversal(&server, &observed);
|
2018-03-07 16:20:55 +01:00
|
|
|
assert_eq!(
|
|
|
|
out.unwrap(),
|
|
|
|
"/ip4/80.81.82.83/tcp/10000".parse::<Multiaddr>().unwrap()
|
|
|
|
);
|
2018-02-08 13:50:16 +01:00
|
|
|
}
|
2017-09-18 16:52:51 +02:00
|
|
|
}
|