2020-01-17 14:27:28 +01:00
|
|
|
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
|
2019-01-07 11:33:07 +01:00
|
|
|
// This file is part of Parity Ethereum.
|
2016-02-05 13:40:41 +01:00
|
|
|
|
2019-01-07 11:33:07 +01:00
|
|
|
// Parity Ethereum is free software: you can redistribute it and/or modify
|
2016-02-05 13:40:41 +01:00
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
|
2019-01-07 11:33:07 +01:00
|
|
|
// Parity Ethereum is distributed in the hope that it will be useful,
|
2016-02-05 13:40:41 +01:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
|
|
|
|
// You should have received a copy of the GNU General Public License
|
2019-01-07 11:33:07 +01:00
|
|
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
2016-02-05 13:40:41 +01:00
|
|
|
|
2019-06-03 19:21:29 +02:00
|
|
|
use std::{io, str};
|
2016-12-09 19:36:40 +01:00
|
|
|
use std::collections::HashMap;
|
2019-06-03 19:21:29 +02:00
|
|
|
use std::net::SocketAddr;
|
2018-03-14 12:29:52 +01:00
|
|
|
use std::time::{Duration, Instant};
|
2016-12-09 19:36:40 +01:00
|
|
|
|
2019-06-03 19:21:29 +02:00
|
|
|
use ethereum_types::H256;
|
2019-06-19 12:20:50 +02:00
|
|
|
use log::{debug, trace, warn};
|
2015-12-02 12:07:46 +01:00
|
|
|
use mio::*;
|
2019-06-03 19:21:29 +02:00
|
|
|
use mio::deprecated::{EventLoop, Handler};
|
2016-06-02 11:49:56 +02:00
|
|
|
use mio::tcp::*;
|
2019-06-19 12:20:50 +02:00
|
|
|
use parity_snappy as snappy;
|
2019-06-03 19:21:29 +02:00
|
|
|
use rlp::{EMPTY_LIST_RLP, Rlp, RlpStream};
|
|
|
|
|
2019-06-19 12:20:50 +02:00
|
|
|
use ethcore_io::{IoContext, StreamToken};
|
2019-06-17 08:44:59 +02:00
|
|
|
use network::{DisconnectReason, Error, PeerCapabilityInfo, ProtocolId, SessionInfo};
|
2019-02-07 15:27:09 +01:00
|
|
|
use network::client_version::ClientVersion;
|
2019-06-03 19:21:29 +02:00
|
|
|
use network::SessionCapabilityInfo;
|
2019-06-19 12:20:50 +02:00
|
|
|
|
|
|
|
use crate::{
|
|
|
|
connection::{Connection, EncryptedConnection, MAX_PAYLOAD_SIZE, Packet},
|
|
|
|
handshake::Handshake,
|
|
|
|
host::HostInfo,
|
|
|
|
node_table::NodeId,
|
|
|
|
};
|
2016-02-02 20:58:12 +01:00
|
|
|
|
2016-11-03 16:12:25 +01:00
|
|
|
// Timeout must be less than (interval - 1).
|
2018-04-14 21:35:58 +02:00
|
|
|
const PING_TIMEOUT: Duration = Duration::from_secs(60);
|
|
|
|
const PING_INTERVAL: Duration = Duration::from_secs(120);
|
2017-10-19 14:41:11 +02:00
|
|
|
const MIN_PROTOCOL_VERSION: u32 = 4;
|
|
|
|
const MIN_COMPRESSION_PROTOCOL_VERSION: u32 = 5;
|
2015-12-02 12:07:46 +01:00
|
|
|
|
2016-12-09 19:36:40 +01:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
enum ProtocolState {
|
|
|
|
// Packets pending protocol on_connect event return.
|
|
|
|
Pending(Vec<(Vec<u8>, u8)>),
|
|
|
|
// Protocol connected.
|
|
|
|
Connected,
|
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Peer session over encrypted connection.
|
|
|
|
/// When created waits for Hello packet exchange and signals ready state.
|
2018-08-17 16:04:03 +02:00
|
|
|
/// Sends and receives protocol packets and handles basic packets such as ping/pong and disconnect.
|
2015-12-02 12:07:46 +01:00
|
|
|
pub struct Session {
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Shared session information
|
2015-12-02 20:11:13 +01:00
|
|
|
pub info: SessionInfo,
|
2018-08-17 16:04:03 +02:00
|
|
|
/// Session ready flag. Set after successful Hello packet exchange
|
2015-12-02 20:11:13 +01:00
|
|
|
had_hello: bool,
|
2016-02-20 01:10:27 +01:00
|
|
|
/// Session is no longer active flag.
|
|
|
|
expired: bool,
|
2018-03-14 12:29:52 +01:00
|
|
|
ping_time: Instant,
|
|
|
|
pong_time: Option<Instant>,
|
2016-06-02 11:49:56 +02:00
|
|
|
state: State,
|
2017-03-20 19:14:29 +01:00
|
|
|
// Protocol states -- accumulates pending packets until signaled as ready.
|
|
|
|
protocol_states: HashMap<ProtocolId, ProtocolState>,
|
2017-10-19 14:41:11 +02:00
|
|
|
compression: bool,
|
2016-06-02 11:49:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
enum State {
|
|
|
|
Handshake(Handshake),
|
|
|
|
Session(EncryptedConnection),
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Structure used to report various session events.
|
2015-12-17 11:42:30 +01:00
|
|
|
pub enum SessionData {
|
|
|
|
None,
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Session is ready to send/receive packets.
|
2015-12-17 11:42:30 +01:00
|
|
|
Ready,
|
2016-01-10 22:42:27 +01:00
|
|
|
/// A packet has been received
|
2015-12-17 11:42:30 +01:00
|
|
|
Packet {
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Packet data
|
2015-12-17 11:42:30 +01:00
|
|
|
data: Vec<u8>,
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Packet protocol ID
|
2016-09-28 14:21:59 +02:00
|
|
|
protocol: [u8; 3],
|
2016-05-23 11:46:01 +02:00
|
|
|
/// Zero based packet ID
|
2015-12-17 11:42:30 +01:00
|
|
|
packet_id: u8,
|
|
|
|
},
|
2016-06-13 15:35:21 +02:00
|
|
|
/// Session has more data to be read
|
|
|
|
Continue,
|
2015-12-17 11:42:30 +01:00
|
|
|
}
|
|
|
|
|
2015-12-02 20:11:13 +01:00
|
|
|
const PACKET_HELLO: u8 = 0x80;
|
|
|
|
const PACKET_DISCONNECT: u8 = 0x01;
|
|
|
|
const PACKET_PING: u8 = 0x02;
|
|
|
|
const PACKET_PONG: u8 = 0x03;
|
|
|
|
const PACKET_GET_PEERS: u8 = 0x04;
|
|
|
|
const PACKET_PEERS: u8 = 0x05;
|
|
|
|
const PACKET_USER: u8 = 0x10;
|
|
|
|
const PACKET_LAST: u8 = 0x7f;
|
|
|
|
|
2015-12-03 15:11:40 +01:00
|
|
|
impl Session {
|
2018-08-17 16:04:03 +02:00
|
|
|
/// Create a new session out of completed handshake. This clones the handshake connection object
|
|
|
|
/// and leaves the handshake in limbo to be de-registered from the event loop.
|
2016-06-02 11:49:56 +02:00
|
|
|
pub fn new<Message>(io: &IoContext<Message>, socket: TcpStream, token: StreamToken, id: Option<&NodeId>,
|
2018-03-28 08:45:36 +02:00
|
|
|
nonce: &H256, host: &HostInfo) -> Result<Session, Error>
|
2016-10-20 14:49:12 +02:00
|
|
|
where Message: Send + Clone + Sync + 'static {
|
2016-06-02 11:49:56 +02:00
|
|
|
let originated = id.is_some();
|
2020-02-10 18:29:21 +01:00
|
|
|
let mut handshake = Handshake::new(token, id, socket, nonce);
|
2016-10-12 20:18:59 +02:00
|
|
|
let local_addr = handshake.connection.local_addr_str();
|
2016-12-27 12:53:56 +01:00
|
|
|
handshake.start(io, host, originated)?;
|
2016-06-02 11:49:56 +02:00
|
|
|
Ok(Session {
|
|
|
|
state: State::Handshake(handshake),
|
2015-12-02 20:11:13 +01:00
|
|
|
had_hello: false,
|
|
|
|
info: SessionInfo {
|
2016-06-02 11:49:56 +02:00
|
|
|
id: id.cloned(),
|
2019-02-07 15:27:09 +01:00
|
|
|
client_version: ClientVersion::from(""),
|
2015-12-02 20:11:13 +01:00
|
|
|
protocol_version: 0,
|
|
|
|
capabilities: Vec::new(),
|
2016-10-12 20:18:59 +02:00
|
|
|
peer_capabilities: Vec::new(),
|
2018-04-14 21:35:58 +02:00
|
|
|
ping: None,
|
2018-05-31 13:38:46 +02:00
|
|
|
originated,
|
2016-10-12 20:18:59 +02:00
|
|
|
remote_address: "Handshake".to_owned(),
|
|
|
|
local_address: local_addr,
|
2015-12-02 20:11:13 +01:00
|
|
|
},
|
2018-03-14 12:29:52 +01:00
|
|
|
ping_time: Instant::now(),
|
|
|
|
pong_time: None,
|
2016-02-20 01:10:27 +01:00
|
|
|
expired: false,
|
2017-03-20 19:14:29 +01:00
|
|
|
protocol_states: HashMap::new(),
|
2017-10-19 14:41:11 +02:00
|
|
|
compression: false,
|
2016-06-02 11:49:56 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-11-13 14:37:08 +01:00
|
|
|
fn complete_handshake<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), Error> where Message: Send + Sync + Clone {
|
2016-06-02 11:49:56 +02:00
|
|
|
let connection = if let State::Handshake(ref mut h) = self.state {
|
2018-05-31 13:38:46 +02:00
|
|
|
self.info.id = Some(h.id);
|
2016-10-12 20:18:59 +02:00
|
|
|
self.info.remote_address = h.connection.remote_addr_str();
|
2016-12-27 12:53:56 +01:00
|
|
|
EncryptedConnection::new(h)?
|
2016-06-02 11:49:56 +02:00
|
|
|
} else {
|
|
|
|
panic!("Unexpected state");
|
2015-12-02 20:11:13 +01:00
|
|
|
};
|
2016-06-02 11:49:56 +02:00
|
|
|
self.state = State::Session(connection);
|
2016-12-27 12:53:56 +01:00
|
|
|
self.write_hello(io, host)?;
|
2016-06-02 11:49:56 +02:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn connection(&self) -> &Connection {
|
|
|
|
match self.state {
|
|
|
|
State::Handshake(ref h) => &h.connection,
|
|
|
|
State::Session(ref s) => &s.connection,
|
|
|
|
}
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
2015-12-02 20:11:13 +01:00
|
|
|
|
2016-02-12 09:52:32 +01:00
|
|
|
/// Get id of the remote peer
|
2016-06-02 11:49:56 +02:00
|
|
|
pub fn id(&self) -> Option<&NodeId> {
|
|
|
|
self.info.id.as_ref()
|
2016-02-12 09:52:32 +01:00
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Check if session is ready to send/receive data
|
2016-01-10 14:02:01 +01:00
|
|
|
pub fn is_ready(&self) -> bool {
|
|
|
|
self.had_hello
|
|
|
|
}
|
|
|
|
|
2016-02-20 01:10:27 +01:00
|
|
|
/// Mark this session as inactive to be deleted lated.
|
|
|
|
pub fn set_expired(&mut self) {
|
|
|
|
self.expired = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if this session is expired.
|
|
|
|
pub fn expired(&self) -> bool {
|
2018-10-10 23:17:17 +02:00
|
|
|
self.expired
|
2016-02-20 01:10:27 +01:00
|
|
|
}
|
|
|
|
|
2016-05-02 14:48:30 +02:00
|
|
|
/// Check if this session is over and there is nothing to be sent.
|
|
|
|
pub fn done(&self) -> bool {
|
2016-06-02 11:49:56 +02:00
|
|
|
self.expired() && !self.connection().is_sending()
|
2016-02-14 12:11:18 +01:00
|
|
|
}
|
|
|
|
|
2016-02-15 19:54:27 +01:00
|
|
|
/// Get remote peer address
|
|
|
|
pub fn remote_addr(&self) -> io::Result<SocketAddr> {
|
2016-06-02 11:49:56 +02:00
|
|
|
self.connection().remote_addr()
|
2016-02-15 19:54:27 +01:00
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Readable IO handler. Returns packet data if available.
|
2017-11-13 14:37:08 +01:00
|
|
|
pub fn readable<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<SessionData, Error> where Message: Send + Sync + Clone {
|
2016-02-20 01:10:27 +01:00
|
|
|
if self.expired() {
|
2016-05-23 11:46:01 +02:00
|
|
|
return Ok(SessionData::None)
|
2016-02-20 01:10:27 +01:00
|
|
|
}
|
2016-06-02 11:49:56 +02:00
|
|
|
let mut create_session = false;
|
|
|
|
let mut packet_data = None;
|
|
|
|
match self.state {
|
|
|
|
State::Handshake(ref mut h) => {
|
2016-12-27 12:53:56 +01:00
|
|
|
h.readable(io, host)?;
|
2016-06-02 11:49:56 +02:00
|
|
|
if h.done() {
|
|
|
|
create_session = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
State::Session(ref mut c) => {
|
2016-12-27 12:53:56 +01:00
|
|
|
match c.readable(io)? {
|
2016-06-02 11:49:56 +02:00
|
|
|
data @ Some(_) => packet_data = data,
|
|
|
|
None => return Ok(SessionData::None)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if let Some(data) = packet_data {
|
2018-05-31 13:38:46 +02:00
|
|
|
return Ok(self.read_packet(io, &data, host)?);
|
2016-06-02 11:49:56 +02:00
|
|
|
}
|
|
|
|
if create_session {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.complete_handshake(io, host)?;
|
2016-06-13 18:55:24 +02:00
|
|
|
io.update_registration(self.token()).unwrap_or_else(|e| debug!(target: "network", "Token registration error: {:?}", e));
|
2015-12-17 11:42:30 +01:00
|
|
|
}
|
2016-06-02 11:49:56 +02:00
|
|
|
Ok(SessionData::None)
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
2015-12-02 20:11:13 +01:00
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Writable IO handler. Sends pending packets.
|
2017-11-13 14:37:08 +01:00
|
|
|
pub fn writable<Message>(&mut self, io: &IoContext<Message>, _host: &HostInfo) -> Result<(), Error> where Message: Send + Sync + Clone {
|
2016-06-02 11:49:56 +02:00
|
|
|
match self.state {
|
|
|
|
State::Handshake(ref mut h) => h.writable(io),
|
|
|
|
State::Session(ref mut s) => s.writable(io),
|
|
|
|
}
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
2015-12-02 20:11:13 +01:00
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Checks if peer supports given capability
|
2016-09-28 14:21:59 +02:00
|
|
|
pub fn have_capability(&self, protocol: [u8; 3]) -> bool {
|
2015-12-17 11:42:30 +01:00
|
|
|
self.info.capabilities.iter().any(|c| c.protocol == protocol)
|
|
|
|
}
|
|
|
|
|
2016-09-06 15:31:13 +02:00
|
|
|
/// Checks if peer supports given capability
|
2016-09-28 14:21:59 +02:00
|
|
|
pub fn capability_version(&self, protocol: [u8; 3]) -> Option<u8> {
|
2016-09-06 15:31:13 +02:00
|
|
|
self.info.capabilities.iter().filter_map(|c| if c.protocol == protocol { Some(c.version) } else { None }).max()
|
|
|
|
}
|
|
|
|
|
2016-02-19 22:09:06 +01:00
|
|
|
/// Register the session socket with the event loop
|
2017-11-13 14:37:08 +01:00
|
|
|
pub fn register_socket<Host:Handler<Timeout = Token>>(&self, reg: Token, event_loop: &mut EventLoop<Host>) -> Result<(), Error> {
|
2016-02-20 01:10:27 +01:00
|
|
|
if self.expired() {
|
|
|
|
return Ok(());
|
|
|
|
}
|
2016-12-27 12:53:56 +01:00
|
|
|
self.connection().register_socket(reg, event_loop)?;
|
2016-02-19 22:09:06 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Update registration with the event loop. Should be called at the end of the IO handler.
|
2017-11-13 14:37:08 +01:00
|
|
|
pub fn update_socket<Host:Handler>(&self, reg:Token, event_loop: &mut EventLoop<Host>) -> Result<(), Error> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.connection().update_socket(reg, event_loop)?;
|
2016-06-02 11:49:56 +02:00
|
|
|
Ok(())
|
2016-01-10 14:02:01 +01:00
|
|
|
}
|
|
|
|
|
2016-01-22 18:13:59 +01:00
|
|
|
/// Delete registration
|
2017-11-13 14:37:08 +01:00
|
|
|
pub fn deregister_socket<Host:Handler>(&self, event_loop: &mut EventLoop<Host>) -> Result<(), Error> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.connection().deregister_socket(event_loop)?;
|
2016-06-02 11:49:56 +02:00
|
|
|
Ok(())
|
2016-01-22 18:13:59 +01:00
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Send a protocol packet to peer.
|
2017-11-13 14:37:08 +01:00
|
|
|
pub fn send_packet<Message>(&mut self, io: &IoContext<Message>, protocol: Option<[u8; 3]>, packet_id: u8, data: &[u8]) -> Result<(), Error>
|
2016-06-13 18:55:24 +02:00
|
|
|
where Message: Send + Sync + Clone {
|
2017-10-19 14:41:11 +02:00
|
|
|
if protocol.is_some() && (self.info.capabilities.is_empty() || !self.had_hello) {
|
|
|
|
debug!(target: "network", "Sending to unconfirmed session {}, protocol: {:?}, packet: {}", self.token(), protocol.as_ref().map(|p| str::from_utf8(&p[..]).unwrap_or("??")), packet_id);
|
2019-06-17 08:44:59 +02:00
|
|
|
return Err(Error::BadProtocol);
|
2016-03-15 11:20:19 +01:00
|
|
|
}
|
2016-03-05 23:09:51 +01:00
|
|
|
if self.expired() {
|
2019-06-17 08:44:59 +02:00
|
|
|
return Err(Error::Expired);
|
2016-03-05 23:09:51 +01:00
|
|
|
}
|
2015-12-17 11:42:30 +01:00
|
|
|
let mut i = 0usize;
|
2017-10-19 14:41:11 +02:00
|
|
|
let pid = match protocol {
|
|
|
|
Some(protocol) => {
|
|
|
|
while protocol != self.info.capabilities[i].protocol {
|
|
|
|
i += 1;
|
|
|
|
if i == self.info.capabilities.len() {
|
|
|
|
debug!(target: "network", "Unknown protocol: {:?}", protocol);
|
|
|
|
return Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
self.info.capabilities[i].id_offset + packet_id
|
|
|
|
},
|
|
|
|
None => packet_id
|
|
|
|
};
|
2015-12-17 11:42:30 +01:00
|
|
|
let mut rlp = RlpStream::new();
|
2018-05-31 13:38:46 +02:00
|
|
|
rlp.append(&(u32::from(pid)));
|
2017-10-19 14:41:11 +02:00
|
|
|
let mut compressed = Vec::new();
|
|
|
|
let mut payload = data; // create a reference with local lifetime
|
|
|
|
if self.compression {
|
|
|
|
if payload.len() > MAX_PAYLOAD_SIZE {
|
2019-06-17 08:44:59 +02:00
|
|
|
return Err(Error::OversizedPacket);
|
2017-10-19 14:41:11 +02:00
|
|
|
}
|
|
|
|
let len = snappy::compress_into(&payload, &mut compressed);
|
|
|
|
trace!(target: "network", "compressed {} to {}", payload.len(), len);
|
|
|
|
payload = &compressed[0..len];
|
|
|
|
}
|
|
|
|
rlp.append_raw(payload, 1);
|
|
|
|
self.send(io, &rlp.drain())
|
2015-12-17 11:42:30 +01:00
|
|
|
}
|
|
|
|
|
2016-02-02 20:58:12 +01:00
|
|
|
/// Keep this session alive. Returns false if ping timeout happened
|
2016-02-11 21:10:41 +01:00
|
|
|
pub fn keep_alive<Message>(&mut self, io: &IoContext<Message>) -> bool where Message: Send + Sync + Clone {
|
2016-06-02 11:49:56 +02:00
|
|
|
if let State::Handshake(_) = self.state {
|
|
|
|
return true;
|
|
|
|
}
|
2018-03-14 12:29:52 +01:00
|
|
|
let timed_out = if let Some(pong) = self.pong_time {
|
2018-04-14 21:35:58 +02:00
|
|
|
pong.duration_since(self.ping_time) > PING_TIMEOUT
|
2016-02-02 20:58:12 +01:00
|
|
|
} else {
|
2018-04-14 21:35:58 +02:00
|
|
|
self.ping_time.elapsed() > PING_TIMEOUT
|
2016-02-02 20:58:12 +01:00
|
|
|
};
|
|
|
|
|
2018-04-14 21:35:58 +02:00
|
|
|
if !timed_out && self.ping_time.elapsed() > PING_INTERVAL {
|
2016-06-13 18:55:24 +02:00
|
|
|
if let Err(e) = self.send_ping(io) {
|
2016-02-02 20:58:12 +01:00
|
|
|
debug!("Error sending ping message: {:?}", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
!timed_out
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn token(&self) -> StreamToken {
|
2016-06-02 11:49:56 +02:00
|
|
|
self.connection().token()
|
2016-02-02 20:58:12 +01:00
|
|
|
}
|
|
|
|
|
2017-03-20 19:14:29 +01:00
|
|
|
/// Signal that a subprotocol has handled the connection successfully and
|
2016-12-09 19:36:40 +01:00
|
|
|
/// get all pending packets in order received.
|
|
|
|
pub fn mark_connected(&mut self, protocol: ProtocolId) -> Vec<(ProtocolId, u8, Vec<u8>)> {
|
|
|
|
match self.protocol_states.insert(protocol, ProtocolState::Connected) {
|
2017-03-20 19:14:29 +01:00
|
|
|
None => Vec::new(),
|
2016-12-09 19:36:40 +01:00
|
|
|
Some(ProtocolState::Connected) => {
|
|
|
|
debug!(target: "network", "Protocol {:?} marked as connected more than once", protocol);
|
|
|
|
Vec::new()
|
|
|
|
}
|
2017-03-20 19:14:29 +01:00
|
|
|
Some(ProtocolState::Pending(pending)) =>
|
2016-12-09 19:36:40 +01:00
|
|
|
pending.into_iter().map(|(data, id)| (protocol, id, data)).collect(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-31 13:38:46 +02:00
|
|
|
fn read_packet<Message>(&mut self, io: &IoContext<Message>, packet: &Packet, host: &HostInfo) -> Result<SessionData, Error>
|
2016-06-13 18:55:24 +02:00
|
|
|
where Message: Send + Sync + Clone {
|
2015-12-17 11:42:30 +01:00
|
|
|
if packet.data.len() < 2 {
|
2019-06-17 08:44:59 +02:00
|
|
|
return Err(Error::BadProtocol);
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
2015-12-17 11:42:30 +01:00
|
|
|
let packet_id = packet.data[0];
|
2015-12-02 20:11:13 +01:00
|
|
|
if packet_id != PACKET_HELLO && packet_id != PACKET_DISCONNECT && !self.had_hello {
|
2019-06-17 08:44:59 +02:00
|
|
|
return Err(Error::BadProtocol);
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
2017-10-19 14:41:11 +02:00
|
|
|
let data = if self.compression {
|
|
|
|
let compressed = &packet.data[1..];
|
|
|
|
if snappy::decompressed_len(&compressed)? > MAX_PAYLOAD_SIZE {
|
2019-06-17 08:44:59 +02:00
|
|
|
return Err(Error::OversizedPacket);
|
2017-10-19 14:41:11 +02:00
|
|
|
}
|
|
|
|
snappy::decompress(&compressed)?
|
|
|
|
} else {
|
|
|
|
packet.data[1..].to_owned()
|
|
|
|
};
|
2015-12-02 20:11:13 +01:00
|
|
|
match packet_id {
|
2015-12-17 11:42:30 +01:00
|
|
|
PACKET_HELLO => {
|
2018-04-16 15:52:12 +02:00
|
|
|
let rlp = Rlp::new(&data); //TODO: validate rlp expected size
|
2016-12-27 12:53:56 +01:00
|
|
|
self.read_hello(io, &rlp, host)?;
|
2015-12-17 11:42:30 +01:00
|
|
|
Ok(SessionData::Ready)
|
2016-01-08 15:52:43 +01:00
|
|
|
},
|
2016-02-17 14:07:26 +01:00
|
|
|
PACKET_DISCONNECT => {
|
2018-04-16 15:52:12 +02:00
|
|
|
let rlp = Rlp::new(&data);
|
2016-12-27 12:53:56 +01:00
|
|
|
let reason: u8 = rlp.val_at(0)?;
|
2016-06-13 15:35:21 +02:00
|
|
|
if self.had_hello {
|
2017-02-17 12:20:25 +01:00
|
|
|
debug!(target:"network", "Disconnected: {}: {:?}", self.token(), DisconnectReason::from_u8(reason));
|
2016-06-13 15:35:21 +02:00
|
|
|
}
|
2019-06-17 08:44:59 +02:00
|
|
|
Err(Error::Disconnect(DisconnectReason::from_u8(reason)))
|
2016-02-17 14:07:26 +01:00
|
|
|
}
|
2015-12-17 11:42:30 +01:00
|
|
|
PACKET_PING => {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.send_pong(io)?;
|
2016-06-13 15:35:21 +02:00
|
|
|
Ok(SessionData::Continue)
|
2016-02-02 20:58:12 +01:00
|
|
|
},
|
|
|
|
PACKET_PONG => {
|
2018-03-14 12:29:52 +01:00
|
|
|
let time = Instant::now();
|
|
|
|
self.pong_time = Some(time);
|
2018-04-14 21:35:58 +02:00
|
|
|
self.info.ping = Some(time.duration_since(self.ping_time));
|
2016-06-13 15:35:21 +02:00
|
|
|
Ok(SessionData::Continue)
|
2016-01-08 15:52:43 +01:00
|
|
|
},
|
2015-12-17 11:42:30 +01:00
|
|
|
PACKET_GET_PEERS => Ok(SessionData::None), //TODO;
|
|
|
|
PACKET_PEERS => Ok(SessionData::None),
|
2019-06-19 12:20:50 +02:00
|
|
|
PACKET_USER ..= PACKET_LAST => {
|
2015-12-17 11:42:30 +01:00
|
|
|
let mut i = 0usize;
|
2016-10-27 16:20:11 +02:00
|
|
|
while packet_id >= self.info.capabilities[i].id_offset + self.info.capabilities[i].packet_count {
|
2015-12-17 11:42:30 +01:00
|
|
|
i += 1;
|
|
|
|
if i == self.info.capabilities.len() {
|
2016-06-02 11:49:56 +02:00
|
|
|
debug!(target: "network", "Unknown packet: {:?}", packet_id);
|
2016-06-13 15:35:21 +02:00
|
|
|
return Ok(SessionData::Continue)
|
2015-12-17 11:42:30 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// map to protocol
|
|
|
|
let protocol = self.info.capabilities[i].protocol;
|
2016-12-10 14:20:34 +01:00
|
|
|
let protocol_packet_id = packet_id - self.info.capabilities[i].id_offset;
|
2016-12-09 19:36:40 +01:00
|
|
|
|
|
|
|
match *self.protocol_states.entry(protocol).or_insert_with(|| ProtocolState::Pending(Vec::new())) {
|
|
|
|
ProtocolState::Connected => {
|
2016-12-10 14:20:34 +01:00
|
|
|
trace!(target: "network", "Packet {} mapped to {:?}:{}, i={}, capabilities={:?}", packet_id, protocol, protocol_packet_id, i, self.info.capabilities);
|
2018-05-31 13:38:46 +02:00
|
|
|
Ok(SessionData::Packet { data, protocol, packet_id: protocol_packet_id } )
|
2016-12-09 19:36:40 +01:00
|
|
|
}
|
|
|
|
ProtocolState::Pending(ref mut pending) => {
|
|
|
|
trace!(target: "network", "Packet {} deferred until protocol connection event completion", packet_id);
|
2017-10-19 14:41:11 +02:00
|
|
|
pending.push((data, protocol_packet_id));
|
2016-12-09 19:36:40 +01:00
|
|
|
|
|
|
|
Ok(SessionData::Continue)
|
|
|
|
}
|
|
|
|
}
|
2015-12-02 20:11:13 +01:00
|
|
|
},
|
|
|
|
_ => {
|
2016-06-02 11:49:56 +02:00
|
|
|
debug!(target: "network", "Unknown packet: {:?}", packet_id);
|
2016-06-13 15:35:21 +02:00
|
|
|
Ok(SessionData::Continue)
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-13 14:37:08 +01:00
|
|
|
fn write_hello<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), Error> where Message: Send + Sync + Clone {
|
2015-12-02 20:11:13 +01:00
|
|
|
let mut rlp = RlpStream::new();
|
2016-01-10 14:02:01 +01:00
|
|
|
rlp.append_raw(&[PACKET_HELLO as u8], 0);
|
2016-01-27 12:14:57 +01:00
|
|
|
rlp.begin_list(5)
|
2015-12-02 20:11:13 +01:00
|
|
|
.append(&host.protocol_version)
|
2017-12-02 10:08:04 +01:00
|
|
|
.append(&host.client_version())
|
2017-03-20 19:14:29 +01:00
|
|
|
.append_list(&host.capabilities)
|
2016-03-20 11:35:46 +01:00
|
|
|
.append(&host.local_endpoint.address.port())
|
2015-12-02 20:11:13 +01:00
|
|
|
.append(host.id());
|
2017-10-19 14:41:11 +02:00
|
|
|
self.send(io, &rlp.drain())
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
|
|
|
|
2018-04-16 15:52:12 +02:00
|
|
|
fn read_hello<Message>(&mut self, io: &IoContext<Message>, rlp: &Rlp, host: &HostInfo) -> Result<(), Error>
|
2016-06-13 18:55:24 +02:00
|
|
|
where Message: Send + Sync + Clone {
|
2016-12-27 12:53:56 +01:00
|
|
|
let protocol = rlp.val_at::<u32>(0)?;
|
2019-02-07 15:27:09 +01:00
|
|
|
let client_version_string = rlp.val_at::<String>(1)?;
|
|
|
|
let client_version = ClientVersion::from(client_version_string);
|
2017-03-22 14:41:46 +01:00
|
|
|
let peer_caps: Vec<PeerCapabilityInfo> = rlp.list_at(2)?;
|
2016-12-27 12:53:56 +01:00
|
|
|
let id = rlp.val_at::<NodeId>(4)?;
|
2015-12-02 20:11:13 +01:00
|
|
|
|
|
|
|
// Intersect with host capabilities
|
|
|
|
// Leave only highset mutually supported capability version
|
2015-12-17 11:42:30 +01:00
|
|
|
let mut caps: Vec<SessionCapabilityInfo> = Vec::new();
|
2016-01-19 12:14:29 +01:00
|
|
|
for hc in &host.capabilities {
|
2015-12-17 11:42:30 +01:00
|
|
|
if peer_caps.iter().any(|c| c.protocol == hc.protocol && c.version == hc.version) {
|
|
|
|
caps.push(SessionCapabilityInfo {
|
|
|
|
protocol: hc.protocol,
|
|
|
|
version: hc.version,
|
|
|
|
id_offset: 0,
|
|
|
|
packet_count: hc.packet_count,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
caps.retain(|c| host.capabilities.iter().any(|hc| hc.protocol == c.protocol && hc.version == c.version));
|
2015-12-02 20:11:13 +01:00
|
|
|
let mut i = 0;
|
|
|
|
while i < caps.len() {
|
|
|
|
if caps.iter().any(|c| c.protocol == caps[i].protocol && c.version > caps[i].version) {
|
|
|
|
caps.remove(i);
|
2017-10-19 14:41:11 +02:00
|
|
|
} else {
|
2015-12-02 20:11:13 +01:00
|
|
|
i += 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-17 16:04:03 +02:00
|
|
|
// Sort capabilities alphabetically.
|
2016-10-24 16:24:35 +02:00
|
|
|
caps.sort();
|
|
|
|
|
2015-12-17 11:42:30 +01:00
|
|
|
i = 0;
|
|
|
|
let mut offset: u8 = PACKET_USER;
|
|
|
|
while i < caps.len() {
|
|
|
|
caps[i].id_offset = offset;
|
|
|
|
offset += caps[i].packet_count;
|
|
|
|
i += 1;
|
|
|
|
}
|
2016-10-25 18:40:01 +02:00
|
|
|
debug!(target: "network", "Hello: {} v{} {} {:?}", client_version, protocol, id, caps);
|
2017-10-05 17:20:23 +02:00
|
|
|
let protocol = ::std::cmp::min(protocol, host.protocol_version);
|
2016-10-12 20:18:59 +02:00
|
|
|
self.info.protocol_version = protocol;
|
2016-01-15 00:50:48 +01:00
|
|
|
self.info.client_version = client_version;
|
2015-12-17 11:42:30 +01:00
|
|
|
self.info.capabilities = caps;
|
2017-03-20 19:14:29 +01:00
|
|
|
self.info.peer_capabilities = peer_caps;
|
2016-02-16 19:08:58 +01:00
|
|
|
if self.info.capabilities.is_empty() {
|
2016-03-05 23:09:51 +01:00
|
|
|
trace!(target: "network", "No common capabilities with peer.");
|
2018-05-31 13:38:46 +02:00
|
|
|
return Err(self.disconnect(io, DisconnectReason::UselessPeer));
|
2016-02-16 19:08:58 +01:00
|
|
|
}
|
2017-10-19 14:41:11 +02:00
|
|
|
if protocol < MIN_PROTOCOL_VERSION {
|
2016-03-05 23:09:51 +01:00
|
|
|
trace!(target: "network", "Peer protocol version mismatch: {}", protocol);
|
2018-05-31 13:38:46 +02:00
|
|
|
return Err(self.disconnect(io, DisconnectReason::UselessPeer));
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
2017-10-19 14:41:11 +02:00
|
|
|
self.compression = protocol >= MIN_COMPRESSION_PROTOCOL_VERSION;
|
|
|
|
self.send_ping(io)?;
|
2015-12-02 20:11:13 +01:00
|
|
|
self.had_hello = true;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2018-03-14 12:29:52 +01:00
|
|
|
/// Send ping packet
|
2017-11-13 14:37:08 +01:00
|
|
|
pub fn send_ping<Message>(&mut self, io: &IoContext<Message>) -> Result<(), Error> where Message: Send + Sync + Clone {
|
2017-10-19 14:41:11 +02:00
|
|
|
self.send_packet(io, None, PACKET_PING, &EMPTY_LIST_RLP)?;
|
2018-03-14 12:29:52 +01:00
|
|
|
self.ping_time = Instant::now();
|
|
|
|
self.pong_time = None;
|
2016-02-02 20:58:12 +01:00
|
|
|
Ok(())
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
|
|
|
|
2017-11-13 14:37:08 +01:00
|
|
|
fn send_pong<Message>(&mut self, io: &IoContext<Message>) -> Result<(), Error> where Message: Send + Sync + Clone {
|
2017-10-19 14:41:11 +02:00
|
|
|
self.send_packet(io, None, PACKET_PONG, &EMPTY_LIST_RLP)
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
|
|
|
|
2016-02-02 14:54:46 +01:00
|
|
|
/// Disconnect this session
|
2017-11-13 14:37:08 +01:00
|
|
|
pub fn disconnect<Message>(&mut self, io: &IoContext<Message>, reason: DisconnectReason) -> Error where Message: Send + Sync + Clone {
|
2016-06-02 11:49:56 +02:00
|
|
|
if let State::Session(_) = self.state {
|
|
|
|
let mut rlp = RlpStream::new();
|
|
|
|
rlp.begin_list(1);
|
|
|
|
rlp.append(&(reason as u32));
|
2017-10-19 14:41:11 +02:00
|
|
|
self.send_packet(io, None, PACKET_DISCONNECT, &rlp.drain()).ok();
|
2016-06-02 11:49:56 +02:00
|
|
|
}
|
2019-06-17 08:44:59 +02:00
|
|
|
Error::Disconnect(reason)
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
|
|
|
|
2017-11-13 14:37:08 +01:00
|
|
|
fn send<Message>(&mut self, io: &IoContext<Message>, data: &[u8]) -> Result<(), Error> where Message: Send + Sync + Clone {
|
2016-06-02 11:49:56 +02:00
|
|
|
match self.state {
|
|
|
|
State::Handshake(_) => {
|
|
|
|
warn!(target:"network", "Unexpected send request");
|
|
|
|
},
|
|
|
|
State::Session(ref mut s) => {
|
2017-10-19 14:41:11 +02:00
|
|
|
s.send_packet(io, data)?
|
2016-06-02 11:49:56 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
Ok(())
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|