This commit is contained in:
John Smith 2021-11-26 21:25:45 -05:00
parent 8e23cb1d98
commit d1f728954c
7 changed files with 61 additions and 77 deletions

View File

@ -71,7 +71,7 @@ impl Network {
fn new_inner(network_manager: NetworkManager) -> NetworkInner { fn new_inner(network_manager: NetworkManager) -> NetworkInner {
NetworkInner { NetworkInner {
routing_table: network_manager.routing_table(), routing_table: network_manager.routing_table(),
network_manager: network_manager, network_manager,
network_needs_restart: false, network_needs_restart: false,
udp_listen: false, udp_listen: false,
udp_static_public_dialinfo: false, udp_static_public_dialinfo: false,
@ -131,28 +131,22 @@ impl Network {
fn load_certs(path: &Path) -> io::Result<Vec<Certificate>> { fn load_certs(path: &Path) -> io::Result<Vec<Certificate>> {
let cvec = certs(&mut BufReader::new(File::open(path)?)) let cvec = certs(&mut BufReader::new(File::open(path)?))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid TLS certificate"))?; .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid TLS certificate"))?;
Ok(cvec.into_iter().map(|c| Certificate(c)).collect()) Ok(cvec.into_iter().map(Certificate).collect())
} }
fn load_keys(path: &Path) -> io::Result<Vec<PrivateKey>> { fn load_keys(path: &Path) -> io::Result<Vec<PrivateKey>> {
{ {
match rsa_private_keys(&mut BufReader::new(File::open(path)?)) { if let Ok(v) = rsa_private_keys(&mut BufReader::new(File::open(path)?)) {
Ok(v) => { if !v.is_empty() {
if v.len() > 0 { return Ok(v.into_iter().map(PrivateKey).collect());
return Ok(v.into_iter().map(|x| PrivateKey(x)).collect());
}
} }
Err(_) => (),
} }
} }
{ {
match pkcs8_private_keys(&mut BufReader::new(File::open(path)?)) { if let Ok(v) = pkcs8_private_keys(&mut BufReader::new(File::open(path)?)) {
Ok(v) => { if !v.is_empty() {
if v.len() > 0 { return Ok(v.into_iter().map(PrivateKey).collect());
return Ok(v.into_iter().map(|x| PrivateKey(x)).collect());
}
} }
Err(_) => (),
} }
} }
@ -171,7 +165,7 @@ impl Network {
); );
let certs = Self::load_certs(&PathBuf::from(&c.network.tls.certificate_path))?; let certs = Self::load_certs(&PathBuf::from(&c.network.tls.certificate_path))?;
trace!("loaded {} certificates", certs.len()); trace!("loaded {} certificates", certs.len());
if certs.len() == 0 { if certs.is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Certificates at {} could not be loaded.\nEnsure it is in PEM format, beginning with '-----BEGIN CERTIFICATE-----'",c.network.tls.certificate_path))); return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Certificates at {} could not be loaded.\nEnsure it is in PEM format, beginning with '-----BEGIN CERTIFICATE-----'",c.network.tls.certificate_path)));
} }
// //
@ -181,7 +175,7 @@ impl Network {
); );
let mut keys = Self::load_keys(&PathBuf::from(&c.network.tls.private_key_path))?; let mut keys = Self::load_keys(&PathBuf::from(&c.network.tls.private_key_path))?;
trace!("loaded {} keys", keys.len()); trace!("loaded {} keys", keys.len());
if keys.len() == 0 { if keys.is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Private key at {} could not be loaded.\nEnsure it is unencrypted and in RSA or PKCS8 format, beginning with '-----BEGIN RSA PRIVATE KEY-----' or '-----BEGIN PRIVATE KEY-----'",c.network.tls.private_key_path))); return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("Private key at {} could not be loaded.\nEnsure it is unencrypted and in RSA or PKCS8 format, beginning with '-----BEGIN RSA PRIVATE KEY-----' or '-----BEGIN PRIVATE KEY-----'",c.network.tls.private_key_path)));
} }
@ -222,7 +216,7 @@ impl Network {
tls_acceptor: &TlsAcceptor, tls_acceptor: &TlsAcceptor,
stream: AsyncPeekStream, stream: AsyncPeekStream,
addr: SocketAddr, addr: SocketAddr,
protocol_handlers: &Vec<Box<dyn TcpProtocolHandler>>, protocol_handlers: &[Box<dyn TcpProtocolHandler>],
tls_connection_initial_timeout: u64, tls_connection_initial_timeout: u64,
) { ) {
match tls_acceptor.accept(stream).await { match tls_acceptor.accept(stream).await {
@ -243,9 +237,7 @@ impl Network {
Ok(()) => (), Ok(()) => (),
Err(_) => return, Err(_) => return,
} }
self.clone() self.clone().try_handlers(ps, addr, protocol_handlers).await;
.try_handlers(ps, addr, &protocol_handlers)
.await;
} }
Err(e) => { Err(e) => {
debug!("TLS stream failed handshake: {}", e); debug!("TLS stream failed handshake: {}", e);
@ -257,7 +249,7 @@ impl Network {
&self, &self,
stream: AsyncPeekStream, stream: AsyncPeekStream,
addr: SocketAddr, addr: SocketAddr,
protocol_handlers: &Vec<Box<dyn TcpProtocolHandler>>, protocol_handlers: &[Box<dyn TcpProtocolHandler>],
) { ) {
for ah in protocol_handlers.iter() { for ah in protocol_handlers.iter() {
if ah.on_accept(stream.clone(), addr).await == Ok(true) { if ah.on_accept(stream.clone(), addr).await == Ok(true) {
@ -359,11 +351,12 @@ impl Network {
// read a chunk of the stream // read a chunk of the stream
trace!("reading chunk"); trace!("reading chunk");
if let Err(_) = io::timeout( if io::timeout(
Duration::from_micros(connection_initial_timeout), Duration::from_micros(connection_initial_timeout),
ps.peek_exact(&mut first_packet), ps.peek_exact(&mut first_packet),
) )
.await .await
.is_err()
{ {
// If we fail to get a packet within the connection initial timeout // If we fail to get a packet within the connection initial timeout
// then we punt this connection // then we punt this connection
@ -380,7 +373,7 @@ impl Network {
.try_tls_handlers( .try_tls_handlers(
ls.tls_acceptor.as_ref().unwrap(), ls.tls_acceptor.as_ref().unwrap(),
ps, ps,
addr.clone(), addr,
&ls.tls_protocol_handlers, &ls.tls_protocol_handlers,
tls_connection_initial_timeout, tls_connection_initial_timeout,
) )
@ -388,7 +381,7 @@ impl Network {
} else { } else {
trace!("not TLS"); trace!("not TLS");
this.clone() this.clone()
.try_handlers(ps, addr.clone(), &ls.protocol_handlers) .try_handlers(ps, addr, &ls.protocol_handlers)
.await; .await;
} }
}) })
@ -424,13 +417,13 @@ impl Network {
.to_socket_addrs() .to_socket_addrs()
.await .await
.map_err(|e| format!("Unable to resolve address: {}\n{}", address, e))?; .map_err(|e| format!("Unable to resolve address: {}\n{}", address, e))?;
while let Some(addr) = sockaddrs.next() { for addr in &mut sockaddrs {
let ldi_addrs = Self::translate_unspecified_address(&*(self.inner.lock()), &addr); let ldi_addrs = Self::translate_unspecified_address(&*(self.inner.lock()), &addr);
// see if we've already bound to this already // see if we've already bound to this already
// if not, spawn a listener // if not, spawn a listener
if !self.inner.lock().listener_states.contains_key(&addr) { if !self.inner.lock().listener_states.contains_key(&addr) {
self.clone().spawn_socket_listener(addr.clone()).await?; self.clone().spawn_socket_listener(addr).await?;
} }
let ls = if let Some(ls) = self.inner.lock().listener_states.get_mut(&addr) { let ls = if let Some(ls) = self.inner.lock().listener_states.get_mut(&addr) {
@ -448,13 +441,13 @@ impl Network {
.push(new_tcp_protocol_handler( .push(new_tcp_protocol_handler(
self.inner.lock().network_manager.clone(), self.inner.lock().network_manager.clone(),
true, true,
addr.clone(), addr,
)); ));
} else { } else {
ls.write().protocol_handlers.push(new_tcp_protocol_handler( ls.write().protocol_handlers.push(new_tcp_protocol_handler(
self.inner.lock().network_manager.clone(), self.inner.lock().network_manager.clone(),
false, false,
addr.clone(), addr,
)); ));
} }
@ -540,7 +533,7 @@ impl Network {
let _processed = protocol_handler let _processed = protocol_handler
.clone() .clone()
.on_message(&data[..size], socket_addr.clone()) .on_message(&data[..size], socket_addr)
.await; .await;
} }
trace!("UDP listener task stopped"); trace!("UDP listener task stopped");
@ -558,7 +551,7 @@ impl Network {
fn translate_unspecified_address(inner: &NetworkInner, from: &SocketAddr) -> Vec<SocketAddr> { fn translate_unspecified_address(inner: &NetworkInner, from: &SocketAddr) -> Vec<SocketAddr> {
if !from.ip().is_unspecified() { if !from.ip().is_unspecified() {
vec![from.clone()] vec![*from]
} else { } else {
let mut out = Vec::<SocketAddr>::with_capacity(inner.interfaces.len()); let mut out = Vec::<SocketAddr>::with_capacity(inner.interfaces.len());
for (_, intf) in inner.interfaces.iter() { for (_, intf) in inner.interfaces.iter() {
@ -583,7 +576,7 @@ impl Network {
.to_socket_addrs() .to_socket_addrs()
.await .await
.map_err(|e| format!("Unable to resolve address: {}\n{}", address, e))?; .map_err(|e| format!("Unable to resolve address: {}\n{}", address, e))?;
while let Some(addr) = sockaddrs.next() { for addr in &mut sockaddrs {
// see if we've already bound to this already // see if we've already bound to this already
// if not, spawn a listener // if not, spawn a listener
if !self.inner.lock().udp_protocol_handlers.contains_key(&addr) { if !self.inner.lock().udp_protocol_handlers.contains_key(&addr) {
@ -610,7 +603,7 @@ impl Network {
listen_socket_addr: &SocketAddr, listen_socket_addr: &SocketAddr,
peer_socket_addr: &SocketAddr, peer_socket_addr: &SocketAddr,
) -> bool { ) -> bool {
let ldi_addrs = Self::translate_unspecified_address(inner, &listen_socket_addr); let ldi_addrs = Self::translate_unspecified_address(inner, listen_socket_addr);
// xxx POSSIBLE CONCERN (verify this?) // xxx POSSIBLE CONCERN (verify this?)
// xxx will need to be reworked to search routing table information if we // xxx will need to be reworked to search routing table information if we
// xxx allow systems to be dual homed with multiple interfaces eventually // xxx allow systems to be dual homed with multiple interfaces eventually
@ -633,7 +626,7 @@ impl Network {
) -> Option<RawUdpProtocolHandler> { ) -> Option<RawUdpProtocolHandler> {
// if our last communication with this peer came from a particular udp protocol handler, use it // if our last communication with this peer came from a particular udp protocol handler, use it
if let Some(sa) = local_socket_addr { if let Some(sa) = local_socket_addr {
if let Some(ph) = self.inner.lock().udp_protocol_handlers.get(&sa) { if let Some(ph) = self.inner.lock().udp_protocol_handlers.get(sa) {
return Some(ph.clone()); return Some(ph.clone());
} }
} }
@ -690,7 +683,7 @@ impl Network {
let network_manager = self.inner.lock().network_manager.clone(); let network_manager = self.inner.lock().network_manager.clone();
if let Some(entry) = network_manager if let Some(entry) = network_manager
.connection_table() .connection_table()
.get_connection(&descriptor) .get_connection(descriptor)
{ {
// connection exists, send over it // connection exists, send over it
entry entry
@ -839,7 +832,7 @@ impl Network {
.map_err(|e| format!("Unable to resolve address: {}\n{}", public_address, e))?; .map_err(|e| format!("Unable to resolve address: {}\n{}", public_address, e))?;
// Add all resolved addresses as public dialinfo // Add all resolved addresses as public dialinfo
while let Some(pdi_addr) = public_sockaddrs.next() { for pdi_addr in &mut public_sockaddrs {
routing_table.register_public_dial_info( routing_table.register_public_dial_info(
DialInfo::udp_from_socketaddr(pdi_addr), DialInfo::udp_from_socketaddr(pdi_addr),
Some(NetworkClass::Server), Some(NetworkClass::Server),
@ -896,7 +889,7 @@ impl Network {
// Add static public dialinfo if it's configured // Add static public dialinfo if it's configured
if let Some(public_address) = public_address.as_ref() { if let Some(public_address) = public_address.as_ref() {
let (public_fqdn, public_port) = split_port(&public_address).map_err(|_| { let (public_fqdn, public_port) = split_port(public_address).map_err(|_| {
"invalid WS public address, port not specified correctly".to_owned() "invalid WS public address, port not specified correctly".to_owned()
})?; })?;
@ -948,7 +941,7 @@ impl Network {
// Add static public dialinfo if it's configured // Add static public dialinfo if it's configured
if let Some(public_address) = public_address.as_ref() { if let Some(public_address) = public_address.as_ref() {
let (public_fqdn, public_port) = split_port(&public_address).map_err(|_| { let (public_fqdn, public_port) = split_port(public_address).map_err(|_| {
"invalid WSS public address, port not specified correctly".to_owned() "invalid WSS public address, port not specified correctly".to_owned()
})?; })?;
@ -1005,7 +998,7 @@ impl Network {
.map_err(|e| format!("Unable to resolve address: {}\n{}", public_address, e))?; .map_err(|e| format!("Unable to resolve address: {}\n{}", public_address, e))?;
// Add all resolved addresses as public dialinfo // Add all resolved addresses as public dialinfo
while let Some(pdi_addr) = public_sockaddrs.next() { for pdi_addr in &mut public_sockaddrs {
routing_table.register_public_dial_info( routing_table.register_public_dial_info(
DialInfo::tcp_from_socketaddr(pdi_addr), DialInfo::tcp_from_socketaddr(pdi_addr),
None, None,
@ -1144,8 +1137,7 @@ impl Network {
{ {
let need_udpv4_dialinfo = routing_table let need_udpv4_dialinfo = routing_table
.public_dial_info_for_protocol_address_type(ProtocolAddressType::UDPv4) .public_dial_info_for_protocol_address_type(ProtocolAddressType::UDPv4)
.len() .is_empty();
== 0;
if need_udpv4_dialinfo { if need_udpv4_dialinfo {
// If we have no public UDPv4 dialinfo, then we need to run a NAT check // If we have no public UDPv4 dialinfo, then we need to run a NAT check
// ensure the singlefuture is running for this // ensure the singlefuture is running for this
@ -1163,9 +1155,7 @@ impl Network {
{ {
let need_tcpv4_dialinfo = routing_table let need_tcpv4_dialinfo = routing_table
.public_dial_info_for_protocol_address_type(ProtocolAddressType::TCPv4) .public_dial_info_for_protocol_address_type(ProtocolAddressType::TCPv4)
.len() .is_empty();
== 0;
if need_tcpv4_dialinfo { if need_tcpv4_dialinfo {
// If we have no public TCPv4 dialinfo, then we need to run a NAT check // If we have no public TCPv4 dialinfo, then we need to run a NAT check
// ensure the singlefuture is running for this // ensure the singlefuture is running for this

View File

@ -34,7 +34,7 @@ impl Eq for RawTcpNetworkConnection {}
impl RawTcpNetworkConnection { impl RawTcpNetworkConnection {
fn new_inner(stream: AsyncPeekStream) -> RawTcpNetworkConnectionInner { fn new_inner(stream: AsyncPeekStream) -> RawTcpNetworkConnectionInner {
RawTcpNetworkConnectionInner { stream: stream } RawTcpNetworkConnectionInner { stream }
} }
pub fn new(stream: AsyncPeekStream) -> Self { pub fn new(stream: AsyncPeekStream) -> Self {
@ -81,8 +81,7 @@ impl RawTcpNetworkConnection {
return Err(()); return Err(());
} }
let mut out: Vec<u8> = Vec::with_capacity(len); let mut out: Vec<u8> = vec![0u8; len];
out.resize(len, 0u8);
inner.stream.read_exact(&mut out).await.map_err(drop)?; inner.stream.read_exact(&mut out).await.map_err(drop)?;
Ok(out) Ok(out)
}) })
@ -111,8 +110,8 @@ impl RawTcpProtocolHandler {
local_address: SocketAddr, local_address: SocketAddr,
) -> RawTcpProtocolHandlerInner { ) -> RawTcpProtocolHandlerInner {
RawTcpProtocolHandlerInner { RawTcpProtocolHandlerInner {
network_manager: network_manager, network_manager,
local_address: local_address, local_address,
} }
} }
@ -139,7 +138,7 @@ impl RawTcpProtocolHandler {
); );
let (network_manager, local_address) = { let (network_manager, local_address) = {
let inner = self.inner.lock(); let inner = self.inner.lock();
(inner.network_manager.clone(), inner.local_address.clone()) (inner.network_manager.clone(), inner.local_address)
}; };
network_manager network_manager
.on_new_connection(ConnectionDescriptor::new(peer_addr, local_address), conn) .on_new_connection(ConnectionDescriptor::new(peer_addr, local_address), conn)
@ -189,7 +188,7 @@ impl RawTcpProtocolHandler {
let ts = TcpStream::from(std_stream); let ts = TcpStream::from(std_stream);
// See what local address we ended up with and turn this into a stream // See what local address we ended up with and turn this into a stream
let local_address = ts.local_addr().map_err(drop)?.clone(); let local_address = ts.local_addr().map_err(drop)?;
let ps = AsyncPeekStream::new(ts); let ps = AsyncPeekStream::new(ts);
let peer_addr = PeerAddress::new( let peer_addr = PeerAddress::new(
Address::from_socket_addr(remote_socket_addr), Address::from_socket_addr(remote_socket_addr),

View File

@ -19,8 +19,8 @@ impl RawUdpProtocolHandler {
socket: Arc<UdpSocket>, socket: Arc<UdpSocket>,
) -> RawUdpProtocolHandlerInner { ) -> RawUdpProtocolHandlerInner {
RawUdpProtocolHandlerInner { RawUdpProtocolHandlerInner {
network_manager: network_manager, network_manager,
socket: socket, socket,
} }
} }

View File

@ -30,7 +30,7 @@ impl Network {
) -> Result<(SocketAddr, NodeRef), String> { ) -> Result<(SocketAddr, NodeRef), String> {
let routing_table = self.routing_table(); let routing_table = self.routing_table();
let peers = routing_table.get_fast_nodes_of_type(protocol_address_type); let peers = routing_table.get_fast_nodes_of_type(protocol_address_type);
if peers.len() == 0 { if peers.is_empty() {
return Err(format!("no peers of type '{:?}'", protocol_address_type)); return Err(format!("no peers of type '{:?}'", protocol_address_type));
} }
for peer in peers { for peer in peers {
@ -98,8 +98,8 @@ impl Network {
async fn try_port_mapping( async fn try_port_mapping(
&self, &self,
local_addr: SocketAddr, _local_addr: SocketAddr,
protocol_address_type: ProtocolAddressType, _protocol_address_type: ProtocolAddressType,
) -> Option<SocketAddr> { ) -> Option<SocketAddr> {
//xxx //xxx
None None
@ -150,7 +150,7 @@ impl Network {
// There is -some NAT- // There is -some NAT-
// Attempt a UDP port mapping via all available and enabled mechanisms // Attempt a UDP port mapping via all available and enabled mechanisms
if let Some(external_mapped) = self if let Some(external_mapped) = self
.try_port_mapping(local1.clone(), ProtocolAddressType::UDPv4) .try_port_mapping(local1, ProtocolAddressType::UDPv4)
.await .await
{ {
// Got a port mapping, let's use it // Got a port mapping, let's use it
@ -248,7 +248,7 @@ impl Network {
Ok(()) Ok(())
} }
pub async fn update_tcpv4_dialinfo_task_routine(self, l: u64, t: u64) -> Result<(), String> { pub async fn update_tcpv4_dialinfo_task_routine(self, _l: u64, _t: u64) -> Result<(), String> {
trace!("looking for tcpv4 public dial info"); trace!("looking for tcpv4 public dial info");
// xxx // xxx
//Err("unimplemented".to_owned()) //Err("unimplemented".to_owned())

View File

@ -2,7 +2,7 @@ use cfg_if::*;
use keyring::{Keyring, KeyringError}; use keyring::{Keyring, KeyringError};
fn keyring_name(namespace: &str) -> String { fn keyring_name(namespace: &str) -> String {
if namespace.len() == 0 { if namespace.is_empty() {
"veilid".to_owned() "veilid".to_owned()
} else { } else {
format!("veilid_{}", namespace) format!("veilid_{}", namespace)

View File

@ -17,7 +17,7 @@ pub struct TableStore {
impl TableStore { impl TableStore {
fn new_inner(config: VeilidConfig) -> TableStoreInner { fn new_inner(config: VeilidConfig) -> TableStoreInner {
TableStoreInner { TableStoreInner {
config: config, config,
opened: BTreeMap::new(), opened: BTreeMap::new(),
} }
} }
@ -33,18 +33,15 @@ impl TableStore {
pub async fn terminate(&self) { pub async fn terminate(&self) {
assert!( assert!(
self.inner.lock().opened.len() == 0, self.inner.lock().opened.is_empty(),
"all open databases should have been closed" "all open databases should have been closed"
); );
} }
pub fn on_table_db_drop(&self, table: String) { pub fn on_table_db_drop(&self, table: String) {
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
match inner.opened.remove(&table) { if inner.opened.remove(&table).is_none() {
Some(_) => (), unreachable!("should have removed an item");
None => {
assert!(false, "should have removed an item");
}
} }
} }
@ -73,8 +70,8 @@ impl TableStore {
} }
let c = inner.config.get(); let c = inner.config.get();
let namespace = c.namespace.clone(); let namespace = c.namespace.clone();
Ok(if namespace.len() == 0 { Ok(if namespace.is_empty() {
format!("{}", table) table.to_string()
} else { } else {
format!("_ns_{}_{}", namespace, table) format!("_ns_{}_{}", namespace, table)
}) })

View File

@ -15,8 +15,8 @@ pub struct NetworkInterface {
impl NetworkInterface { impl NetworkInterface {
pub fn new(name: String, is_loopback: bool) -> Self { pub fn new(name: String, is_loopback: bool) -> Self {
Self { Self {
name: name, name,
is_loopback: is_loopback, is_loopback,
addrs: Vec::new(), addrs: Vec::new(),
} }
} }
@ -28,19 +28,17 @@ impl NetworkInterface {
} }
pub fn primary_ipv4(&self) -> Option<Ipv4Addr> { pub fn primary_ipv4(&self) -> Option<Ipv4Addr> {
for x in self.addrs.iter() { for x in self.addrs.iter() {
match x { if let IfAddr::V4(a) = x {
IfAddr::V4(a) => return Some(a.ip.clone()), return Some(a.ip);
_ => (), }
};
} }
None None
} }
pub fn primary_ipv6(&self) -> Option<Ipv6Addr> { pub fn primary_ipv6(&self) -> Option<Ipv6Addr> {
for x in self.addrs.iter() { for x in self.addrs.iter() {
match x { if let IfAddr::V6(a) = x {
IfAddr::V6(a) => return Some(a.ip.clone()), return Some(a.ip);
_ => (), }
};
} }
None None
} }