openethereum/util/src/network/host.rs

744 lines
25 KiB
Rust
Raw Normal View History

2016-01-13 13:56:48 +01:00
use std::net::{SocketAddr};
use std::collections::{HashMap};
use std::hash::{Hasher};
2015-11-29 11:50:28 +01:00
use std::str::{FromStr};
2016-01-21 16:48:37 +01:00
use std::sync::*;
use std::ops::*;
2015-11-29 11:50:28 +01:00
use mio::*;
use mio::tcp::*;
use mio::udp::*;
use hash::*;
use crypto::*;
2016-01-09 10:27:41 +01:00
use sha3::Hashable;
2015-12-02 20:11:13 +01:00
use rlp::*;
use network::handshake::Handshake;
2015-12-17 11:42:30 +01:00
use network::session::{Session, SessionData};
use error::*;
use io::*;
use network::NetworkProtocolHandler;
use network::node::*;
2016-01-24 18:53:54 +01:00
use network::stats::NetworkStats;
2016-01-15 00:50:48 +01:00
type Slab<T> = ::slab::Slab<T, usize>;
2015-11-29 11:50:28 +01:00
2016-01-04 13:49:32 +01:00
const _DEFAULT_PORT: u16 = 30304;
2015-11-29 11:50:28 +01:00
const MAX_CONNECTIONS: usize = 1024;
2016-01-08 13:49:00 +01:00
const IDEAL_PEERS: u32 = 10;
2015-11-29 11:50:28 +01:00
2016-01-14 16:52:10 +01:00
const MAINTENANCE_TIMEOUT: u64 = 1000;
2015-11-29 11:50:28 +01:00
#[derive(Debug)]
2016-01-23 02:36:58 +01:00
/// Network service configuration
pub struct NetworkConfiguration {
/// IP address to listen for incoming connections
pub listen_address: SocketAddr,
/// IP address to advertise
pub public_address: SocketAddr,
/// Enable NAT configuration
pub nat_enabled: bool,
/// Enable discovery
pub discovery_enabled: bool,
/// Pin to boot nodes only
pub pin: bool,
/// List of initial node addresses
pub boot_nodes: Vec<String>,
2016-01-24 18:53:54 +01:00
/// Use provided node key instead of default
pub use_secret: Option<Secret>,
2015-11-29 11:50:28 +01:00
}
impl NetworkConfiguration {
2016-01-23 02:36:58 +01:00
/// Create a new instance of default settings.
pub fn new() -> NetworkConfiguration {
2016-01-08 13:49:00 +01:00
NetworkConfiguration {
listen_address: SocketAddr::from_str("0.0.0.0:30304").unwrap(),
public_address: SocketAddr::from_str("0.0.0.0:30304").unwrap(),
nat_enabled: true,
discovery_enabled: true,
pin: false,
boot_nodes: Vec::new(),
2016-01-24 18:53:54 +01:00
use_secret: None,
2016-01-08 13:49:00 +01:00
}
}
2016-01-24 18:53:54 +01:00
/// Create new default configuration with sepcified listen port.
pub fn new_with_port(port: u16) -> NetworkConfiguration {
let mut config = NetworkConfiguration::new();
config.listen_address = SocketAddr::from_str(&format!("0.0.0.0:{}", port)).unwrap();
config.public_address = SocketAddr::from_str(&format!("0.0.0.0:{}", port)).unwrap();
config
}
2015-11-29 11:50:28 +01:00
}
// Tokens
2016-01-13 15:08:36 +01:00
//const TOKEN_BEGIN: usize = USER_TOKEN_START; // TODO: ICE in rustc 1.7.0-nightly (49c382779 2016-01-12)
const TOKEN_BEGIN: usize = 32;
const TCP_ACCEPT: usize = TOKEN_BEGIN + 1;
const IDLE: usize = TOKEN_BEGIN + 2;
const NODETABLE_RECEIVE: usize = TOKEN_BEGIN + 3;
const NODETABLE_MAINTAIN: usize = TOKEN_BEGIN + 4;
const NODETABLE_DISCOVERY: usize = TOKEN_BEGIN + 5;
const FIRST_CONNECTION: usize = TOKEN_BEGIN + 16;
2015-11-29 11:50:28 +01:00
const LAST_CONNECTION: usize = FIRST_CONNECTION + MAX_CONNECTIONS - 1;
2015-12-17 11:42:30 +01:00
2016-01-10 22:42:27 +01:00
/// Protocol handler level packet id
2015-12-22 22:23:43 +01:00
pub type PacketId = u8;
2016-01-10 22:42:27 +01:00
/// Protocol / handler id
2015-12-17 11:42:30 +01:00
pub type ProtocolId = &'static str;
2015-11-29 11:50:28 +01:00
2016-01-10 22:42:27 +01:00
/// Messages used to communitate with the event loop from other threads.
2016-01-21 16:48:37 +01:00
#[derive(Clone)]
pub enum NetworkIoMessage<Message> where Message: Send + Sync + Clone {
2016-01-10 22:42:27 +01:00
/// Register a new protocol handler.
2015-12-17 11:42:30 +01:00
AddHandler {
/// Handler shared instance.
2016-01-21 16:48:37 +01:00
handler: Arc<NetworkProtocolHandler<Message> + Sync>,
/// Protocol Id.
2015-12-17 11:42:30 +01:00
protocol: ProtocolId,
/// Supported protocol versions.
2015-12-17 11:42:30 +01:00
versions: Vec<u8>,
},
/// Register a new protocol timer
2016-01-21 16:48:37 +01:00
AddTimer {
/// Protocol Id.
2016-01-21 16:48:37 +01:00
protocol: ProtocolId,
/// Timer token.
2016-01-21 16:48:37 +01:00
token: TimerToken,
/// Timer delay in milliseconds.
2016-01-21 16:48:37 +01:00
delay: u64,
},
/// User message
2016-01-13 23:13:57 +01:00
User(Message),
2015-11-29 11:50:28 +01:00
}
2016-01-10 22:42:27 +01:00
/// Local (temporary) peer session ID.
2015-12-22 22:23:43 +01:00
pub type PeerId = usize;
2015-12-17 11:42:30 +01:00
2015-12-02 20:11:13 +01:00
#[derive(Debug, PartialEq, Eq)]
2016-01-10 22:42:27 +01:00
/// Protocol info
2015-12-02 20:11:13 +01:00
pub struct CapabilityInfo {
2015-12-17 11:42:30 +01:00
pub protocol: ProtocolId,
pub version: u8,
2016-01-10 22:42:27 +01:00
/// Total number of packet IDs this protocol support.
2015-12-17 11:42:30 +01:00
pub packet_count: u8,
2015-12-02 20:11:13 +01:00
}
impl Encodable for CapabilityInfo {
2016-01-27 12:14:57 +01:00
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(2);
s.append(&self.protocol);
s.append(&self.version);
2015-12-02 20:11:13 +01:00
}
}
2016-01-10 22:42:27 +01:00
/// IO access point. This is passed to all IO handlers and provides an interface to the IO subsystem.
2016-01-21 16:48:37 +01:00
pub struct NetworkContext<'s, Message> where Message: Send + Sync + Clone + 'static, 's {
io: &'s IoContext<NetworkIoMessage<Message>>,
2016-01-13 13:56:48 +01:00
protocol: ProtocolId,
2016-01-21 16:48:37 +01:00
connections: Arc<RwLock<Slab<SharedConnectionEntry>>>,
session: Option<StreamToken>,
2015-12-17 11:42:30 +01:00
}
2016-01-21 16:48:37 +01:00
impl<'s, Message> NetworkContext<'s, Message> where Message: Send + Sync + Clone + 'static, {
/// Create a new network IO access point. Takes references to all the data that can be updated within the IO handler.
2016-01-21 16:48:37 +01:00
fn new(io: &'s IoContext<NetworkIoMessage<Message>>,
2016-01-13 13:56:48 +01:00
protocol: ProtocolId,
2016-01-21 16:48:37 +01:00
session: Option<StreamToken>, connections: Arc<RwLock<Slab<SharedConnectionEntry>>>) -> NetworkContext<'s, Message> {
NetworkContext {
io: io,
2015-12-17 11:42:30 +01:00
protocol: protocol,
session: session,
2015-12-22 22:23:43 +01:00
connections: connections,
2015-12-17 11:42:30 +01:00
}
}
2015-12-30 12:23:36 +01:00
/// Send a packet over the network to another peer.
2016-01-21 16:48:37 +01:00
pub fn send(&self, peer: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
if let Some(connection) = self.connections.read().unwrap().get(peer).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Session(ref mut s) => {
2016-01-21 16:48:37 +01:00
s.send_packet(self.protocol, packet_id as u8, &data).unwrap_or_else(|e| {
warn!(target: "net", "Send error: {:?}", e);
}); //TODO: don't copy vector data
},
_ => warn!(target: "net", "Send: Peer is not connected yet")
2015-12-22 22:23:43 +01:00
}
2016-01-21 16:48:37 +01:00
} else {
warn!(target: "net", "Send: Peer does not exist")
2015-12-22 22:23:43 +01:00
}
2015-12-17 11:42:30 +01:00
Ok(())
}
2015-12-30 12:23:36 +01:00
/// Respond to a current network message. Panics if no there is no packet in the context.
2016-01-21 16:48:37 +01:00
pub fn respond(&self, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
2015-12-22 22:23:43 +01:00
match self.session {
Some(session) => self.send(session, packet_id, data),
2015-12-17 11:42:30 +01:00
None => {
panic!("Respond: Session does not exist")
}
}
}
2015-12-30 12:23:36 +01:00
/// Disable current protocol capability for given peer. If no capabilities left peer gets disconnected.
2016-01-21 16:48:37 +01:00
pub fn disable_peer(&self, _peer: PeerId) {
2015-12-22 22:23:43 +01:00
//TODO: remove capability, disconnect if no capabilities left
2015-12-02 20:11:13 +01:00
}
2015-12-28 11:41:51 +01:00
2016-01-21 16:48:37 +01:00
/// Register a new IO timer. 'IoHandler::timeout' will be called with the token.
pub fn register_timer(&self, token: TimerToken, ms: u64) -> Result<(), UtilError> {
self.io.message(NetworkIoMessage::AddTimer {
token: token,
delay: ms,
protocol: self.protocol,
});
Ok(())
}
2016-01-14 16:52:10 +01:00
/// Returns peer identification string
pub fn peer_info(&self, peer: PeerId) -> String {
if let Some(connection) = self.connections.read().unwrap().get(peer).cloned() {
if let ConnectionEntry::Session(ref s) = *connection.lock().unwrap().deref() {
return s.info.client_version.clone()
2016-01-14 16:52:10 +01:00
}
}
"unknown".to_owned()
2016-01-14 16:52:10 +01:00
}
2015-12-17 11:42:30 +01:00
}
2016-01-10 22:42:27 +01:00
/// Shared host information
pub struct HostInfo {
2016-01-10 22:42:27 +01:00
/// Our private and public keys.
2016-01-08 13:49:00 +01:00
keys: KeyPair,
2016-01-10 22:42:27 +01:00
/// Current network configuration
2016-01-08 13:49:00 +01:00
config: NetworkConfiguration,
2016-01-10 22:42:27 +01:00
/// Connection nonce.
2015-12-02 20:11:13 +01:00
nonce: H256,
2016-01-10 22:42:27 +01:00
/// RLPx protocol version
2015-12-02 20:11:13 +01:00
pub protocol_version: u32,
2016-01-10 22:42:27 +01:00
/// Client identifier
2015-12-02 20:11:13 +01:00
pub client_version: String,
2016-01-10 22:42:27 +01:00
/// TCP connection port.
2015-12-02 20:11:13 +01:00
pub listen_port: u16,
2016-01-10 22:42:27 +01:00
/// Registered capabilities (handlers)
2015-12-02 20:11:13 +01:00
pub capabilities: Vec<CapabilityInfo>
}
impl HostInfo {
2016-01-10 22:42:27 +01:00
/// Returns public key
pub fn id(&self) -> &NodeId {
self.keys.public()
}
2016-01-10 22:42:27 +01:00
/// Returns secret key
pub fn secret(&self) -> &Secret {
self.keys.secret()
}
2016-01-10 22:42:27 +01:00
/// Increments and returns connection nonce.
pub fn next_nonce(&mut self) -> H256 {
self.nonce = self.nonce.sha3();
2016-01-19 12:14:29 +01:00
self.nonce.clone()
}
}
2015-12-02 12:07:46 +01:00
enum ConnectionEntry {
Handshake(Handshake),
Session(Session)
}
2016-01-21 16:48:37 +01:00
type SharedConnectionEntry = Arc<Mutex<ConnectionEntry>>;
#[derive(Copy, Clone)]
struct ProtocolTimer {
pub protocol: ProtocolId,
pub token: TimerToken, // Handler level token
}
2016-01-10 22:42:27 +01:00
/// Root IO handler. Manages protocol handlers, IO timers and network connections.
2016-01-21 16:48:37 +01:00
pub struct Host<Message> where Message: Send + Sync + Clone {
pub info: RwLock<HostInfo>,
udp_socket: Mutex<UdpSocket>,
tcp_listener: Mutex<TcpListener>,
connections: Arc<RwLock<Slab<SharedConnectionEntry>>>,
nodes: RwLock<HashMap<NodeId, Node>>,
handlers: RwLock<HashMap<ProtocolId, Arc<NetworkProtocolHandler<Message>>>>,
timers: RwLock<HashMap<TimerToken, ProtocolTimer>>,
timer_counter: RwLock<usize>,
2016-01-24 18:53:54 +01:00
stats: Arc<NetworkStats>,
2015-11-29 11:50:28 +01:00
}
2016-01-21 16:48:37 +01:00
impl<Message> Host<Message> where Message: Send + Sync + Clone {
2016-01-23 02:36:58 +01:00
/// Create a new instance
pub fn new(config: NetworkConfiguration) -> Host<Message> {
2016-01-08 13:49:00 +01:00
let addr = config.listen_address;
// Setup the server socket
2016-01-21 16:48:37 +01:00
let tcp_listener = TcpListener::bind(&addr).unwrap();
2016-01-08 13:49:00 +01:00
let udp_socket = UdpSocket::bound(&addr).unwrap();
2016-01-21 16:48:37 +01:00
let mut host = Host::<Message> {
info: RwLock::new(HostInfo {
2016-01-24 18:53:54 +01:00
keys: if let Some(ref secret) = config.use_secret { KeyPair::from_secret(secret.clone()).unwrap() } else { KeyPair::create().unwrap() },
config: config,
2015-12-02 20:11:13 +01:00
nonce: H256::random(),
protocol_version: 4,
2016-01-19 12:14:29 +01:00
client_version: "parity".to_owned(),
listen_port: 0,
2015-12-17 11:42:30 +01:00
capabilities: Vec::new(),
2016-01-21 16:48:37 +01:00
}),
udp_socket: Mutex::new(udp_socket),
tcp_listener: Mutex::new(tcp_listener),
connections: Arc::new(RwLock::new(Slab::new_starting_at(FIRST_CONNECTION, MAX_CONNECTIONS))),
nodes: RwLock::new(HashMap::new()),
handlers: RwLock::new(HashMap::new()),
timers: RwLock::new(HashMap::new()),
timer_counter: RwLock::new(LAST_CONNECTION + 1),
2016-01-24 18:53:54 +01:00
stats: Arc::new(NetworkStats::default()),
2016-01-21 16:48:37 +01:00
};
let port = host.info.read().unwrap().config.listen_address.port();
host.info.write().unwrap().deref_mut().listen_port = port;
/*
match ::ifaces::Interface::get_all().unwrap().into_iter().filter(|x| x.kind == ::ifaces::Kind::Packet && x.addr.is_some()).next() {
Some(iface) => config.public_address = iface.addr.unwrap(),
None => warn!("No public network interface"),
*/
2016-01-23 02:36:58 +01:00
let boot_nodes = host.info.read().unwrap().config.boot_nodes.clone();
for n in boot_nodes {
host.add_node(&n);
2016-01-23 02:36:58 +01:00
}
2016-01-21 16:48:37 +01:00
host
2016-01-08 13:49:00 +01:00
}
2015-11-29 11:50:28 +01:00
2016-01-24 18:53:54 +01:00
pub fn stats(&self) -> Arc<NetworkStats> {
self.stats.clone()
}
2016-01-21 16:48:37 +01:00
pub fn add_node(&mut self, id: &str) {
2015-11-29 11:50:28 +01:00
match Node::from_str(id) {
Err(e) => { warn!("Could not add node: {:?}", e); },
2015-12-02 12:07:46 +01:00
Ok(n) => {
2016-01-21 16:48:37 +01:00
self.nodes.write().unwrap().insert(n.id.clone(), n);
2015-12-02 12:07:46 +01:00
}
2015-11-29 11:50:28 +01:00
}
}
2016-01-21 16:48:37 +01:00
pub fn client_version(&self) -> String {
self.info.read().unwrap().client_version.clone()
}
pub fn client_id(&self) -> NodeId {
self.info.read().unwrap().id().clone()
}
fn maintain_network(&self, io: &IoContext<NetworkIoMessage<Message>>) {
self.connect_peers(io);
2016-01-08 13:49:00 +01:00
}
2015-11-29 11:50:28 +01:00
fn have_session(&self, id: &NodeId) -> bool {
self.connections.read().unwrap().iter().any(|e| match *e.lock().unwrap().deref() { ConnectionEntry::Session(ref s) => s.info.id.eq(&id), _ => false })
2015-11-29 11:50:28 +01:00
}
fn connecting_to(&self, id: &NodeId) -> bool {
self.connections.read().unwrap().iter().any(|e| match *e.lock().unwrap().deref() { ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false })
2015-11-29 11:50:28 +01:00
}
2016-01-21 16:48:37 +01:00
fn connect_peers(&self, io: &IoContext<NetworkIoMessage<Message>>) {
2015-11-29 11:50:28 +01:00
struct NodeInfo {
id: NodeId,
peer_type: PeerType
}
let mut to_connect: Vec<NodeInfo> = Vec::new();
let mut req_conn = 0;
//TODO: use nodes from discovery here
//for n in self.node_buckets.iter().flat_map(|n| &n.nodes).map(|id| NodeInfo { id: id.clone(), peer_type: self.nodes.get(id).unwrap().peer_type}) {
2016-01-21 16:48:37 +01:00
let pin = self.info.read().unwrap().deref().config.pin;
for n in self.nodes.read().unwrap().values().map(|n| NodeInfo { id: n.id.clone(), peer_type: n.peer_type }) {
2015-11-29 11:50:28 +01:00
let connected = self.have_session(&n.id) || self.connecting_to(&n.id);
let required = n.peer_type == PeerType::Required;
if connected && required {
req_conn += 1;
}
2016-01-21 16:48:37 +01:00
else if !connected && (!pin || required) {
2015-11-29 11:50:28 +01:00
to_connect.push(n);
}
}
2016-01-19 12:14:29 +01:00
for n in &to_connect {
2015-11-29 11:50:28 +01:00
if n.peer_type == PeerType::Required {
if req_conn < IDEAL_PEERS {
2016-01-13 13:56:48 +01:00
self.connect_peer(&n.id, io);
2015-11-29 11:50:28 +01:00
}
req_conn += 1;
}
}
2016-01-21 16:48:37 +01:00
if !pin {
2015-11-29 11:50:28 +01:00
let pending_count = 0; //TODO:
let peer_count = 0;
let mut open_slots = IDEAL_PEERS - peer_count - pending_count + req_conn;
if open_slots > 0 {
2016-01-19 12:14:29 +01:00
for n in &to_connect {
2015-11-29 11:50:28 +01:00
if n.peer_type == PeerType::Optional && open_slots > 0 {
open_slots -= 1;
2016-01-13 13:56:48 +01:00
self.connect_peer(&n.id, io);
2015-11-29 11:50:28 +01:00
}
}
}
}
2016-01-08 13:49:00 +01:00
}
2015-11-29 11:50:28 +01:00
2016-01-19 12:14:29 +01:00
#[allow(single_match)]
2016-01-21 16:48:37 +01:00
fn connect_peer(&self, id: &NodeId, io: &IoContext<NetworkIoMessage<Message>>) {
2015-11-29 11:50:28 +01:00
if self.have_session(id)
{
warn!("Aborted connect. Node already connected.");
return;
}
2016-01-21 16:48:37 +01:00
if self.connecting_to(id) {
2015-11-29 11:50:28 +01:00
warn!("Aborted connect. Node already connecting.");
return;
}
let socket = {
2016-01-21 16:48:37 +01:00
let address = {
let mut nodes = self.nodes.write().unwrap();
let node = nodes.get_mut(id).unwrap();
node.last_attempted = Some(::time::now());
node.endpoint.address
};
match TcpStream::connect(&address) {
Ok(socket) => socket,
Err(_) => {
warn!("Cannot connect to node");
return;
}
2015-11-29 11:50:28 +01:00
}
};
2016-01-24 18:53:54 +01:00
self.create_connection(socket, Some(id), io);
}
2015-11-29 11:50:28 +01:00
2016-01-24 18:53:54 +01:00
#[allow(block_in_if_condition_stmt)]
fn create_connection(&self, socket: TcpStream, id: Option<&NodeId>, io: &IoContext<NetworkIoMessage<Message>>) {
2016-01-21 16:48:37 +01:00
let nonce = self.info.write().unwrap().next_nonce();
2016-01-22 18:13:59 +01:00
let mut connections = self.connections.write().unwrap();
if connections.insert_with(|token| {
2016-01-24 18:53:54 +01:00
let mut handshake = Handshake::new(token, id, socket, &nonce, self.stats.clone()).expect("Can't create handshake");
handshake.start(io, &self.info.read().unwrap(), id.is_some()).and_then(|_| io.register_stream(token)).unwrap_or_else (|e| {
2016-01-21 16:48:37 +01:00
debug!(target: "net", "Handshake create error: {:?}", e);
});
Arc::new(Mutex::new(ConnectionEntry::Handshake(handshake)))
}).is_none() {
warn!("Max connections reached");
}
}
2015-11-29 11:50:28 +01:00
2016-01-24 18:53:54 +01:00
fn accept(&self, io: &IoContext<NetworkIoMessage<Message>>) {
2016-01-10 22:42:27 +01:00
trace!(target: "net", "accept");
2016-01-24 18:53:54 +01:00
loop {
let socket = match self.tcp_listener.lock().unwrap().accept() {
Ok(None) => break,
Ok(Some((sock, _addr))) => sock,
Err(e) => {
warn!("Error accepting connection: {:?}", e);
break
},
};
self.create_connection(socket, None, io);
}
io.update_registration(TCP_ACCEPT).expect("Error registering TCP listener");
2015-11-29 11:50:28 +01:00
}
2016-01-19 12:14:29 +01:00
#[allow(single_match)]
2016-01-21 16:48:37 +01:00
fn connection_writable(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
2015-12-02 12:07:46 +01:00
let mut create_session = false;
2016-01-21 16:48:37 +01:00
let mut kill = false;
if let Some(connection) = self.connections.read().unwrap().get(token).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Handshake(ref mut h) => {
2016-01-21 16:48:37 +01:00
match h.writable(io, &self.info.read().unwrap()) {
Err(e) => {
debug!(target: "net", "Handshake write error: {:?}", e);
kill = true;
},
Ok(_) => ()
}
if h.done() {
create_session = true;
}
},
ConnectionEntry::Session(ref mut s) => {
2016-01-21 16:48:37 +01:00
match s.writable(io, &self.info.read().unwrap()) {
Err(e) => {
debug!(target: "net", "Session write error: {:?}", e);
kill = true;
},
Ok(_) => ()
}
io.update_registration(token).unwrap_or_else(|e| debug!(target: "net", "Session registration error: {:?}", e));
}
2016-01-08 13:55:44 +01:00
}
2016-01-22 01:27:51 +01:00
}
2015-12-02 12:07:46 +01:00
if kill {
2016-01-21 16:48:37 +01:00
self.kill_connection(token, io); //TODO: mark connection as dead an check in kill_connection
2016-01-13 13:56:48 +01:00
return;
} else if create_session {
self.start_session(token, io);
2016-01-21 16:48:37 +01:00
io.update_registration(token).unwrap_or_else(|e| debug!(target: "net", "Session registration error: {:?}", e));
2016-01-10 14:02:01 +01:00
}
2015-11-29 11:50:28 +01:00
}
2015-12-17 11:42:30 +01:00
2016-01-21 16:48:37 +01:00
fn connection_closed(&self, token: TimerToken, io: &IoContext<NetworkIoMessage<Message>>) {
2016-01-13 13:56:48 +01:00
self.kill_connection(token, io);
2016-01-10 14:02:01 +01:00
}
2015-12-17 11:42:30 +01:00
2016-01-21 16:48:37 +01:00
fn connection_readable(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
2015-12-22 22:23:43 +01:00
let mut ready_data: Vec<ProtocolId> = Vec::new();
let mut packet_data: Option<(ProtocolId, PacketId, Vec<u8>)> = None;
2016-01-21 16:48:37 +01:00
let mut create_session = false;
let mut kill = false;
if let Some(connection) = self.connections.read().unwrap().get(token).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Handshake(ref mut h) => {
if let Err(e) = h.readable(io, &self.info.read().unwrap()) {
debug!(target: "net", "Handshake read error: {:?}", e);
kill = true;
2016-01-21 16:48:37 +01:00
}
if h.done() {
create_session = true;
}
},
ConnectionEntry::Session(ref mut s) => {
2016-01-21 16:48:37 +01:00
match s.readable(io, &self.info.read().unwrap()) {
Err(e) => {
debug!(target: "net", "Handshake read error: {:?}", e);
kill = true;
},
Ok(SessionData::Ready) => {
for (p, _) in self.handlers.read().unwrap().iter() {
if s.have_capability(p) {
ready_data.push(p);
}
2015-12-17 11:42:30 +01:00
}
2016-01-21 16:48:37 +01:00
},
Ok(SessionData::Packet {
data,
protocol,
packet_id,
}) => {
match self.handlers.read().unwrap().get(protocol) {
None => { warn!(target: "net", "No handler found for protocol: {:?}", protocol) },
Some(_) => packet_data = Some((protocol, packet_id, data)),
}
},
Ok(SessionData::None) => {},
}
}
2016-01-08 13:55:44 +01:00
}
2016-01-22 01:27:51 +01:00
}
2015-12-02 12:07:46 +01:00
if kill {
2016-01-21 16:48:37 +01:00
self.kill_connection(token, io); //TODO: mark connection as dead an check in kill_connection
2016-01-13 13:56:48 +01:00
return;
2016-01-21 16:48:37 +01:00
} else if create_session {
2016-01-13 13:56:48 +01:00
self.start_session(token, io);
2016-01-21 16:48:37 +01:00
io.update_registration(token).unwrap_or_else(|e| debug!(target: "net", "Session registration error: {:?}", e));
2015-12-02 12:07:46 +01:00
}
2015-12-22 22:23:43 +01:00
for p in ready_data {
2016-01-21 16:48:37 +01:00
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
h.connected(&NetworkContext::new(io, p, Some(token), self.connections.clone()), &token);
2015-12-22 22:23:43 +01:00
}
if let Some((p, packet_id, data)) = packet_data {
2016-01-21 16:48:37 +01:00
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
h.read(&NetworkContext::new(io, p, Some(token), self.connections.clone()), &token, packet_id, &data[1..]);
2016-01-10 14:02:01 +01:00
}
2016-01-21 16:48:37 +01:00
io.update_registration(token).unwrap_or_else(|e| debug!(target: "net", "Token registration error: {:?}", e));
2015-11-29 11:50:28 +01:00
}
2016-01-21 16:48:37 +01:00
fn start_session(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
2016-01-23 02:36:58 +01:00
let mut connections = self.connections.write().unwrap();
connections.replace_with(token, |c| {
2016-01-21 16:48:37 +01:00
match Arc::try_unwrap(c).ok().unwrap().into_inner().unwrap() {
ConnectionEntry::Handshake(h) => {
let session = Session::new(h, io, &self.info.read().unwrap()).expect("Session creation error");
io.update_registration(token).expect("Error updating session registration");
2016-01-24 18:53:54 +01:00
self.stats.inc_sessions();
2016-01-21 16:48:37 +01:00
Some(Arc::new(Mutex::new(ConnectionEntry::Session(session))))
},
_ => { None } // handshake expired
2015-12-02 12:07:46 +01:00
}
2016-01-21 16:48:37 +01:00
}).ok();
2015-11-29 11:50:28 +01:00
}
2016-01-21 16:48:37 +01:00
fn connection_timeout(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
2016-01-13 13:56:48 +01:00
self.kill_connection(token, io)
2015-12-02 12:07:46 +01:00
}
2016-01-08 13:55:44 +01:00
2016-01-21 16:48:37 +01:00
fn kill_connection(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
2016-01-10 14:02:01 +01:00
let mut to_disconnect: Vec<ProtocolId> = Vec::new();
2016-01-21 16:48:37 +01:00
{
let mut connections = self.connections.write().unwrap();
if let Some(connection) = connections.get(token).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Handshake(_) => {
2016-01-21 16:48:37 +01:00
connections.remove(token);
},
ConnectionEntry::Session(ref mut s) if s.is_ready() => {
2016-01-21 16:48:37 +01:00
for (p, _) in self.handlers.read().unwrap().iter() {
if s.have_capability(p) {
to_disconnect.push(p);
}
}
connections.remove(token);
},
_ => {},
2016-01-10 14:02:01 +01:00
}
2016-01-21 16:48:37 +01:00
}
2016-01-22 18:13:59 +01:00
io.deregister_stream(token).expect("Error deregistering stream");
2016-01-10 14:02:01 +01:00
}
for p in to_disconnect {
2016-01-21 16:48:37 +01:00
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
h.disconnected(&NetworkContext::new(io, p, Some(token), self.connections.clone()), &token);
2016-01-15 00:50:48 +01:00
}
2015-11-29 11:50:28 +01:00
}
2016-01-08 13:55:44 +01:00
}
2015-11-29 11:50:28 +01:00
2016-01-21 16:48:37 +01:00
impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Message: Send + Sync + Clone + 'static {
/// Initialize networking
2016-01-21 16:48:37 +01:00
fn initialize(&self, io: &IoContext<NetworkIoMessage<Message>>) {
io.register_stream(TCP_ACCEPT).expect("Error registering TCP listener");
io.register_stream(NODETABLE_RECEIVE).expect("Error registering UDP listener");
io.register_timer(IDLE, MAINTENANCE_TIMEOUT).expect("Error registering Network idle timer");
//io.register_timer(NODETABLE_MAINTAIN, 7200);
}
2016-01-21 16:48:37 +01:00
fn stream_hup(&self, io: &IoContext<NetworkIoMessage<Message>>, stream: StreamToken) {
trace!(target: "net", "Hup: {}", stream);
match stream {
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_closed(stream, io),
_ => warn!(target: "net", "Unexpected hup"),
};
}
2016-01-21 16:48:37 +01:00
fn stream_readable(&self, io: &IoContext<NetworkIoMessage<Message>>, stream: StreamToken) {
match stream {
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_readable(stream, io),
NODETABLE_RECEIVE => {},
2016-01-13 15:08:36 +01:00
TCP_ACCEPT => self.accept(io),
_ => panic!("Received unknown readable token"),
2016-01-08 13:55:44 +01:00
}
}
2016-01-21 16:48:37 +01:00
fn stream_writable(&self, io: &IoContext<NetworkIoMessage<Message>>, stream: StreamToken) {
match stream {
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_writable(stream, io),
2016-01-21 16:48:37 +01:00
NODETABLE_RECEIVE => {},
_ => panic!("Received unknown writable token"),
2015-11-29 11:50:28 +01:00
}
2016-01-08 13:55:44 +01:00
}
2016-01-08 13:49:00 +01:00
2016-01-21 16:48:37 +01:00
fn timeout(&self, io: &IoContext<NetworkIoMessage<Message>>, token: TimerToken) {
match token {
IDLE => self.maintain_network(io),
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_timeout(token, io),
2016-01-08 13:55:44 +01:00
NODETABLE_DISCOVERY => {},
NODETABLE_MAINTAIN => {},
_ => match self.timers.read().unwrap().get(&token).cloned() {
Some(timer) => match self.handlers.read().unwrap().get(timer.protocol).cloned() {
2016-01-21 16:48:37 +01:00
None => { warn!(target: "net", "No handler found for protocol: {:?}", timer.protocol) },
Some(h) => { h.timeout(&NetworkContext::new(io, timer.protocol, None, self.connections.clone()), timer.token); }
},
None => { warn!("Unknown timer token: {}", token); } // timer is not registerd through us
2015-12-17 11:42:30 +01:00
}
}
2016-01-08 13:55:44 +01:00
}
2015-12-17 11:42:30 +01:00
2016-01-21 16:48:37 +01:00
fn message(&self, io: &IoContext<NetworkIoMessage<Message>>, message: &NetworkIoMessage<Message>) {
2016-01-19 12:14:29 +01:00
match *message {
NetworkIoMessage::AddHandler {
2016-01-21 16:48:37 +01:00
ref handler,
ref protocol,
ref versions
2016-01-08 13:55:44 +01:00
} => {
2016-01-21 16:48:37 +01:00
let h = handler.clone();
h.initialize(&NetworkContext::new(io, protocol, None, self.connections.clone()));
self.handlers.write().unwrap().insert(protocol, h);
let mut info = self.info.write().unwrap();
2016-01-08 13:55:44 +01:00
for v in versions {
2016-01-21 16:48:37 +01:00
info.capabilities.push(CapabilityInfo { protocol: protocol, version: *v, packet_count:0 });
2016-01-08 13:55:44 +01:00
}
},
NetworkIoMessage::AddTimer {
2016-01-21 16:48:37 +01:00
ref protocol,
ref delay,
ref token,
} => {
let handler_token = {
let mut timer_counter = self.timer_counter.write().unwrap();
let counter = timer_counter.deref_mut();
let handler_token = *counter;
*counter += 1;
handler_token
};
self.timers.write().unwrap().insert(handler_token, ProtocolTimer { protocol: protocol, token: *token });
io.register_timer(handler_token, *delay).expect("Error registering timer");
},
2016-01-19 12:14:29 +01:00
NetworkIoMessage::User(ref message) => {
2016-01-21 16:48:37 +01:00
for (p, h) in self.handlers.read().unwrap().iter() {
h.message(&NetworkContext::new(io, p, None, self.connections.clone()), &message);
2015-12-28 11:41:51 +01:00
}
}
2015-11-29 11:50:28 +01:00
}
}
2016-01-21 16:48:37 +01:00
fn register_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage<Message>>>) {
match stream {
FIRST_CONNECTION ... LAST_CONNECTION => {
if let Some(connection) = self.connections.read().unwrap().get(stream).cloned() {
match *connection.lock().unwrap().deref() {
ConnectionEntry::Handshake(ref h) => h.register_socket(reg, event_loop).expect("Error registering socket"),
ConnectionEntry::Session(_) => warn!("Unexpected session stream registration")
2016-01-21 16:48:37 +01:00
}
2016-01-21 23:33:52 +01:00
} else {} // expired
2016-01-21 16:48:37 +01:00
}
NODETABLE_RECEIVE => event_loop.register(self.udp_socket.lock().unwrap().deref(), Token(NODETABLE_RECEIVE), EventSet::all(), PollOpt::edge()).expect("Error registering stream"),
TCP_ACCEPT => event_loop.register(self.tcp_listener.lock().unwrap().deref(), Token(TCP_ACCEPT), EventSet::all(), PollOpt::edge()).expect("Error registering stream"),
2016-01-21 23:33:52 +01:00
_ => warn!("Unexpected stream registration")
2016-01-21 16:48:37 +01:00
}
}
2016-01-22 18:13:59 +01:00
fn deregister_stream(&self, stream: StreamToken, event_loop: &mut EventLoop<IoManager<NetworkIoMessage<Message>>>) {
match stream {
FIRST_CONNECTION ... LAST_CONNECTION => {
let mut connections = self.connections.write().unwrap();
if let Some(connection) = connections.get(stream).cloned() {
match *connection.lock().unwrap().deref() {
ConnectionEntry::Handshake(ref h) => h.deregister_socket(event_loop).expect("Error deregistering socket"),
ConnectionEntry::Session(ref s) => s.deregister_socket(event_loop).expect("Error deregistering session socket"),
}
connections.remove(stream);
}
},
NODETABLE_RECEIVE => event_loop.deregister(self.udp_socket.lock().unwrap().deref()).unwrap(),
TCP_ACCEPT => event_loop.deregister(self.tcp_listener.lock().unwrap().deref()).unwrap(),
_ => warn!("Unexpected stream deregistration")
}
}
2016-01-21 16:48:37 +01:00
fn update_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage<Message>>>) {
match stream {
FIRST_CONNECTION ... LAST_CONNECTION => {
if let Some(connection) = self.connections.read().unwrap().get(stream).cloned() {
match *connection.lock().unwrap().deref() {
ConnectionEntry::Handshake(ref h) => h.update_socket(reg, event_loop).expect("Error updating socket"),
ConnectionEntry::Session(ref s) => s.update_socket(reg, event_loop).expect("Error updating socket"),
2016-01-21 16:48:37 +01:00
}
2016-01-21 23:33:52 +01:00
} else {} // expired
2016-01-21 16:48:37 +01:00
}
NODETABLE_RECEIVE => event_loop.reregister(self.udp_socket.lock().unwrap().deref(), Token(NODETABLE_RECEIVE), EventSet::all(), PollOpt::edge()).expect("Error reregistering stream"),
TCP_ACCEPT => event_loop.reregister(self.tcp_listener.lock().unwrap().deref(), Token(TCP_ACCEPT), EventSet::all(), PollOpt::edge()).expect("Error reregistering stream"),
_ => warn!("Unexpected stream update")
}
}
2016-01-08 13:55:44 +01:00
}