This commit is contained in:
John Smith 2021-11-27 19:56:56 -05:00
parent 028e02f942
commit 45489d0e9c
9 changed files with 109 additions and 94 deletions

View File

@ -10,7 +10,7 @@ pub trait TcpProtocolHandler: TcpProtocolHandlerClone + Send + Sync {
&self,
stream: AsyncPeekStream,
peer_addr: SocketAddr,
) -> SendPinBoxFuture<Result<bool, ()>>;
) -> SendPinBoxFuture<Result<bool, String>>;
}
pub trait TcpProtocolHandlerClone {

View File

@ -125,9 +125,12 @@ impl RawTcpProtocolHandler {
self,
stream: AsyncPeekStream,
socket_addr: SocketAddr,
) -> Result<bool, ()> {
) -> Result<bool, String> {
let mut peekbuf: [u8; PEEK_DETECT_LEN] = [0u8; PEEK_DETECT_LEN];
let peeklen = stream.peek(&mut peekbuf).await.map_err(drop)?;
let peeklen = stream
.peek(&mut peekbuf)
.await
.map_err(|e| format!("could not peek tcp stream: {}", e))?;
assert_eq!(peeklen, PEEK_DETECT_LEN);
let conn = NetworkConnection::RawTcp(RawTcpNetworkConnection::new(stream));
@ -150,12 +153,13 @@ impl RawTcpProtocolHandler {
network_manager: NetworkManager,
preferred_local_address: Option<SocketAddr>,
remote_socket_addr: SocketAddr,
) -> Result<NetworkConnection, ()> {
) -> Result<NetworkConnection, String> {
// Make a low level socket that can connect to the remote socket address
// and attempt to reuse the local address that our listening socket uses
// for hole-punch compatibility
let domain = Domain::for_address(remote_socket_addr);
let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP)).map_err(drop)?;
let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))
.map_err(|e| format!("could not create tcp socket: {}", e))?;
if let Err(e) = socket.set_linger(None) {
warn!("Couldn't set TCP linger: {}", e);
}
@ -183,12 +187,16 @@ impl RawTcpProtocolHandler {
// Connect to the remote address
let remote_socket2_addr = socket2::SockAddr::from(remote_socket_addr);
socket.connect(&remote_socket2_addr).map_err(drop)?;
socket
.connect(&remote_socket2_addr)
.map_err(|e| format!("couln't connect tcp: {}", e))?;
let std_stream: std::net::TcpStream = socket.into();
let ts = TcpStream::from(std_stream);
// See what local address we ended up with and turn this into a stream
let local_address = ts.local_addr().map_err(drop)?;
let local_address = ts
.local_addr()
.map_err(|e| format!("couldn't get local address for tcp socket: {}", e))?;
let ps = AsyncPeekStream::new(ts);
let peer_addr = PeerAddress::new(
Address::from_socket_addr(remote_socket_addr),
@ -227,7 +235,7 @@ impl TcpProtocolHandler for RawTcpProtocolHandler {
&self,
stream: AsyncPeekStream,
peer_addr: SocketAddr,
) -> SendPinBoxFuture<Result<bool, ()>> {
) -> SendPinBoxFuture<Result<bool, String>> {
Box::pin(self.clone().on_accept_async(stream, peer_addr))
}
}

View File

@ -168,7 +168,7 @@ impl WebsocketProtocolHandler {
self,
ps: AsyncPeekStream,
socket_addr: SocketAddr,
) -> Result<bool, ()> {
) -> Result<bool, String> {
let request_path_len = self.inner.request_path.len() + 2;
let mut peekbuf: Vec<u8> = vec![0u8; request_path_len];
match io::timeout(
@ -179,8 +179,7 @@ impl WebsocketProtocolHandler {
{
Ok(_) => (),
Err(e) => {
trace!("failed to peek stream: {:?}", e);
return Err(());
return Err(format!("failed to peek stream: {:?}", e));
}
}
// Check for websocket path
@ -198,8 +197,7 @@ impl WebsocketProtocolHandler {
let ws_stream = match accept_async(ps).await {
Ok(s) => s,
Err(e) => {
trace!("failed websockets handshake: {:?}", e);
return Err(());
return Err(format!("failed websockets handshake: {:?}", e));
}
};
@ -234,7 +232,7 @@ impl WebsocketProtocolHandler {
pub async fn connect(
network_manager: NetworkManager,
dial_info: &DialInfo,
) -> Result<NetworkConnection, ()> {
) -> Result<NetworkConnection, String> {
let (tls, request, domain, port, protocol_type) = match &dial_info {
DialInfo::WS(di) => (
false,
@ -255,9 +253,13 @@ impl WebsocketProtocolHandler {
let tcp_stream = TcpStream::connect(format!("{}:{}", &domain, &port))
.await
.map_err(drop)?;
let local_addr = tcp_stream.local_addr().map_err(drop)?;
let peer_socket_addr = tcp_stream.peer_addr().map_err(drop)?;
.map_err(|e| format!("failed to connect tcp stream: {}", e))?;
let local_addr = tcp_stream
.local_addr()
.map_err(|e| format!("can't get local address for tcp stream: {}", e))?;
let peer_socket_addr = tcp_stream
.peer_addr()
.map_err(|e| format!("can't get peer address for tcp stream: {}", e))?;
let peer_addr = PeerAddress::new(
Address::from_socket_addr(peer_socket_addr),
peer_socket_addr.port(),
@ -266,8 +268,13 @@ impl WebsocketProtocolHandler {
if tls {
let connector = TlsConnector::default();
let tls_stream = connector.connect(domain, tcp_stream).await.map_err(drop)?;
let (ws_stream, _response) = client_async(request, tls_stream).await.map_err(drop)?;
let tls_stream = connector
.connect(domain, tcp_stream)
.await
.map_err(|e| format!("can't connect tls: {}", e))?;
let (ws_stream, _response) = client_async(request, tls_stream)
.await
.map_err(|e| format!("wss negotation failed: {}", e))?;
let conn = NetworkConnection::Wss(WebsocketNetworkConnection::new(tls, ws_stream));
network_manager
.on_new_connection(
@ -277,7 +284,9 @@ impl WebsocketProtocolHandler {
.await?;
Ok(conn)
} else {
let (ws_stream, _response) = client_async(request, tcp_stream).await.map_err(drop)?;
let (ws_stream, _response) = client_async(request, tcp_stream)
.await
.map_err(|e| format!("ws negotiate failed: {}", e))?;
let conn = NetworkConnection::Ws(WebsocketNetworkConnection::new(tls, ws_stream));
network_manager
.on_new_connection(
@ -295,7 +304,7 @@ impl TcpProtocolHandler for WebsocketProtocolHandler {
&self,
stream: AsyncPeekStream,
peer_addr: SocketAddr,
) -> SystemPinBoxFuture<Result<bool, ()>> {
) -> SystemPinBoxFuture<Result<bool, String>> {
Box::pin(self.clone().on_accept_async(stream, peer_addr))
}
}

View File

@ -24,7 +24,7 @@ pub struct Network {
impl Network {
fn new_inner(network_manager: NetworkManager) -> NetworkInner {
NetworkInner {
network_manager: network_manager,
network_manager,
stop_network: Eventual::new(),
network_needs_restart: false,
//join_handle: None,

View File

@ -7,7 +7,6 @@ use web_sys::WebSocket;
use ws_stream_wasm::*;
struct WebsocketNetworkConnectionInner {
_ws_meta: WsMeta,
ws_stream: WsStream,
ws: WebSocket,
}
@ -36,11 +35,10 @@ impl WebsocketNetworkConnection {
pub fn new(tls: bool, ws_meta: WsMeta, ws_stream: WsStream) -> Self {
let ws = ws_stream.wrapped().clone();
Self {
tls: tls,
tls,
inner: Arc::new(Mutex::new(WebsocketNetworkConnectionInner {
_ws_meta: ws_meta,
ws_stream: ws_stream,
ws: ws,
ws_stream,
ws,
})),
}
}
@ -91,19 +89,19 @@ impl WebsocketProtocolHandler {
pub async fn connect(
network_manager: NetworkManager,
dial_info: &DialInfo,
) -> Result<NetworkConnection, ()> {
) -> Result<NetworkConnection, String> {
let url = dial_info.to_url_string(None);
let (tls, host, port, protocol_type) = match dial_info {
DialInfo::WS(ws) => (false, ws.fqdn.clone(), ws.port, ProtocolType::WS),
DialInfo::WSS(wss) => (true, wss.fqdn.clone(), wss.port, ProtocolType::WSS),
_ => return Err(()),
_ => return Err("wrong protocol for WebsocketProtocolHandler".to_owned()),
};
let peer_addr = PeerAddress::new(Address::from_str(&host)?, port, protocol_type);
let (ws, wsio) = match WsMeta::connect(url, None).await {
Ok(conn) => conn,
Err(_) => return Err(()),
Err(e) => return Err(format!("couldn't connect to WS url: {}", e)),
};
let conn = NetworkConnection::WS(WebsocketNetworkConnection::new(tls, ws, wsio));

View File

@ -16,7 +16,7 @@ pub struct TableStore {
impl TableStore {
fn new_inner(config: VeilidConfig) -> TableStoreInner {
TableStoreInner {
config: config,
config,
opened: BTreeMap::new(),
}
}

View File

@ -37,7 +37,7 @@ impl<T> Clone for Receiver<T> {
pub fn channel<T>(cap: usize) -> (Sender<T>, Receiver<T>) {
let imp = Channel {
items: VecDeque::with_capacity(cap),
cap: cap,
cap,
eventual: Eventual::new(),
};

View File

@ -263,17 +263,20 @@ impl NetworkManager {
&self,
descriptor: ConnectionDescriptor,
conn: NetworkConnection,
) -> Result<(), ()> {
) -> Result<(), String> {
let tx = self
.inner
.lock()
.connection_add_channel_tx
.as_ref()
.ok_or(())?
.ok_or("connection channel isn't open yet".to_owned())?
.clone();
let this = self.clone();
let receiver_loop_future = Self::process_connection(this, descriptor, conn);
Ok(tx.try_send(receiver_loop_future).await.map_err(drop)?)
Ok(tx
.try_send(receiver_loop_future)
.await
.map_err(|_| "connection loop stopped".to_owned())?)
}
// Connection receiver loop

View File

@ -37,7 +37,7 @@ impl ValueKey {
pub fn new_subkey(key: DHTKey, subkey: String) -> Self {
Self {
key,
subkey: if subkey.len() == 0 {
subkey: if subkey.is_empty() {
None
} else {
Some(subkey)
@ -131,37 +131,39 @@ impl Address {
Address::Hostname(h) => format!("{}:{}", h.clone(), port),
}
}
pub fn resolve(&self) -> Result<IpAddr, ()> {
pub fn resolve(&self) -> Result<IpAddr, String> {
match self {
Self::IPV4(a) => Ok(IpAddr::V4(a.clone())),
Self::IPV6(a) => Ok(IpAddr::V6(a.clone())),
Self::Hostname(h) => h.parse().map_err(drop),
Self::IPV4(a) => Ok(IpAddr::V4(*a)),
Self::IPV6(a) => Ok(IpAddr::V6(*a)),
Self::Hostname(h) => h
.parse()
.map_err(|e| format!("Failed to parse hostname: {}", e)),
}
}
pub fn address(&self) -> Result<IpAddr, ()> {
pub fn address(&self) -> Result<IpAddr, String> {
match self {
Self::IPV4(a) => Ok(IpAddr::V4(a.clone())),
Self::IPV6(a) => Ok(IpAddr::V6(a.clone())),
Self::Hostname(_) => Err(()),
Self::IPV4(a) => Ok(IpAddr::V4(*a)),
Self::IPV6(a) => Ok(IpAddr::V6(*a)),
Self::Hostname(h) => Err(format!("Address not available for hostname: {}", h)),
}
}
pub fn to_socket_addr(&self, port: u16) -> Result<SocketAddr, ()> {
pub fn to_socket_addr(&self, port: u16) -> Result<SocketAddr, String> {
let addr = self.address()?;
Ok(SocketAddr::new(addr, port))
}
}
impl core::str::FromStr for Address {
type Err = ();
fn from_str(host: &str) -> Result<Address, ()> {
if let Some(addr) = Ipv4Addr::from_str(host).ok() {
type Err = String;
fn from_str(host: &str) -> Result<Address, String> {
if let Ok(addr) = Ipv4Addr::from_str(host) {
Ok(Address::IPV4(addr))
} else if let Some(addr) = Ipv6Addr::from_str(host).ok() {
} else if let Ok(addr) = Ipv6Addr::from_str(host) {
Ok(Address::IPV6(addr))
} else if !host.is_empty() {
Ok(Address::Hostname(host.to_string()))
} else {
Err(())
Err("unable to convert address to string".to_owned())
}
}
}
@ -260,11 +262,8 @@ impl DialInfo {
pub fn try_udp_v4(&self) -> Option<SocketAddrV4> {
match self {
Self::UDP(v) => match v.address.to_socket_addr(v.port).ok() {
Some(x) => match x {
SocketAddr::V4(v4) => Some(v4),
_ => None,
},
None => None,
Some(SocketAddr::V4(v4)) => Some(v4),
_ => None,
},
_ => None,
}
@ -273,11 +272,8 @@ impl DialInfo {
pub fn try_udp_v6(&self) -> Option<SocketAddrV6> {
match self {
Self::UDP(v) => match v.address.to_socket_addr(v.port).ok() {
Some(x) => match x {
SocketAddr::V6(v6) => Some(v6),
_ => None,
},
None => None,
Some(SocketAddr::V6(v6)) => Some(v6),
_ => None,
},
_ => None,
}
@ -286,11 +282,8 @@ impl DialInfo {
pub fn try_tcp_v4(&self) -> Option<SocketAddrV4> {
match self {
Self::TCP(v) => match v.address.to_socket_addr(v.port).ok() {
Some(x) => match x {
SocketAddr::V4(v4) => Some(v4),
_ => None,
},
None => None,
Some(SocketAddr::V4(v4)) => Some(v4),
_ => None,
},
_ => None,
}
@ -299,11 +292,8 @@ impl DialInfo {
pub fn try_tcp_v6(&self) -> Option<SocketAddrV6> {
match self {
Self::TCP(v) => match v.address.to_socket_addr(v.port).ok() {
Some(x) => match x {
SocketAddr::V6(v6) => Some(v6),
_ => None,
},
None => None,
Some(SocketAddr::V6(v6)) => Some(v6),
_ => None,
},
_ => None,
}
@ -381,32 +371,38 @@ impl DialInfo {
}
}
pub fn resolve(&self) -> Result<IpAddr, ()> {
pub fn resolve(&self) -> Result<IpAddr, String> {
match self {
Self::UDP(di) => {
let addr = di.address.resolve()?;
return Ok(addr);
Ok(addr)
}
Self::TCP(di) => {
let addr = di.address.resolve()?;
return Ok(addr);
Ok(addr)
}
Self::WS(di) => {
let addr: IpAddr = di.fqdn.parse().map_err(drop)?;
return Ok(addr);
let addr: IpAddr = di
.fqdn
.parse()
.map_err(|e| format!("Failed to parse WS fqdn: {}", e))?;
Ok(addr)
}
Self::WSS(di) => {
let addr: IpAddr = di.fqdn.parse().map_err(drop)?;
return Ok(addr);
let addr: IpAddr = di
.fqdn
.parse()
.map_err(|e| format!("Failed to parse WS fqdn: {}", e))?;
Ok(addr)
}
}
}
pub fn address(&self) -> Result<IpAddr, ()> {
pub fn address(&self) -> Result<IpAddr, String> {
match self {
Self::UDP(di) => di.address.address(),
Self::TCP(di) => di.address.address(),
Self::WS(_) => Err(()),
Self::WSS(_) => Err(()),
Self::WS(_) => Err("Address not available for WS protocol".to_owned()),
Self::WSS(_) => Err("Address not available for WSS protocol".to_owned()),
}
}
pub fn port(&self) -> u16 {
@ -417,20 +413,20 @@ impl DialInfo {
Self::WSS(di) => di.port,
}
}
pub fn path(&self) -> Result<String, ()> {
pub fn path(&self) -> Result<String, String> {
match self {
Self::UDP(_) => Err(()),
Self::TCP(_) => Err(()),
Self::UDP(_) => Err("path not available for udp protocol".to_owned()),
Self::TCP(_) => Err("path not available for tcp protocol".to_owned()),
Self::WS(di) => Ok(di.path.clone()),
Self::WSS(di) => Ok(di.path.clone()),
}
}
pub fn to_socket_addr(&self) -> Result<SocketAddr, ()> {
pub fn to_socket_addr(&self) -> Result<SocketAddr, String> {
match self {
Self::UDP(di) => Ok(SocketAddr::new(di.address.address()?, di.port)),
Self::TCP(di) => Ok(SocketAddr::new(di.address.address()?, di.port)),
Self::WS(_) => Err(()),
Self::WSS(_) => Err(()),
Self::WS(_) => Err("Can not directly convert WS hostname to socket addr".to_owned()),
Self::WSS(_) => Err("Can not directly convert WSS hostname to socket addr".to_owned()),
}
}
@ -507,7 +503,7 @@ impl PeerAddress {
}
}
pub fn to_socket_addr(&self) -> Result<SocketAddr, ()> {
pub fn to_socket_addr(&self) -> Result<SocketAddr, String> {
self.address.to_socket_addr(self.port)
}
pub fn protocol_address_type(&self) -> ProtocolAddressType {
@ -564,8 +560,8 @@ pub struct NodeDialInfoSingle {
}
impl core::str::FromStr for NodeDialInfoSingle {
type Err = ();
fn from_str(url: &str) -> Result<NodeDialInfoSingle, ()> {
type Err = String;
fn from_str(url: &str) -> Result<NodeDialInfoSingle, String> {
let mut cur_url = url;
let proto;
if url.starts_with("udp://") {
@ -581,18 +577,18 @@ impl core::str::FromStr for NodeDialInfoSingle {
cur_url = &cur_url[6..];
proto = ProtocolType::WSS;
} else {
return Err(());
return Err("unknown protocol".to_owned());
}
// parse out node id if we have one
let node_id = match cur_url.find('@') {
Some(x) => {
let n = NodeId::new(DHTKey::try_decode(&cur_url[0..x]).map_err(drop)?);
let n = NodeId::new(DHTKey::try_decode(&cur_url[0..x])?);
cur_url = &cur_url[x + 1..];
n
}
None => {
return Err(());
return Err("NodeDialInfoSingle is missing the node id".to_owned());
}
};
@ -614,13 +610,14 @@ impl core::str::FromStr for NodeDialInfoSingle {
}
}
None => {
return Err(());
return Err("NodeDialInfoSingle is missing the port".to_owned());
}
};
// parse out port
let pathstart = cur_url.find('/').unwrap_or(cur_url.len());
let port = u16::from_str(&cur_url[0..pathstart]).map_err(drop)?;
let port =
u16::from_str(&cur_url[0..pathstart]).map_err(|e| format!("port is invalid: {}", e))?;
cur_url = &cur_url[pathstart..];
// build NodeDialInfoSingle