Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: don't spam re-connect attempts if something goes wrong when connecting to a derp server #1113

Merged
merged 3 commits into from
Jun 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions src/hp/derp/client_conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -905,4 +905,80 @@ mod tests {
io_handle.await??;
Ok(())
}

#[tokio::test]
async fn test_client_conn_read_err() -> Result<()> {
let _guard = crate::test_utils::setup_logging();

let (_send_queue_s, send_queue_r) = mpsc::channel(10);
let (_disco_send_queue_s, disco_send_queue_r) = mpsc::channel(10);
let (_peer_gone_s, peer_gone_r) = mpsc::channel(10);
let (mesh_update_s, mesh_update_r) = mpsc::channel(10);

let preferred = Arc::from(AtomicBool::from(true));
let key = PublicKey::from([1u8; PUBLIC_KEY_LENGTH]);
let (io, mut io_rw) = tokio::io::duplex(1024);
let (server_channel_s, mut server_channel_r) = mpsc::channel(10);

println!("-- create client conn");
let conn_io = ClientConnIo::<MockPacketForwarder> {
can_mesh: true,
io: MaybeTlsStream::Test(io),
timeout: None,
send_queue: send_queue_r,
disco_send_queue: disco_send_queue_r,
peer_gone: peer_gone_r,
mesh_update_r,
mesh_update_s: mesh_update_s.clone(),

key: key.clone(),
server_channel: server_channel_s,
preferred: Arc::clone(&preferred),
};

let done = CancellationToken::new();
let io_done = done.clone();

println!("-- run client conn");
let io_handle = tokio::task::spawn(async move { conn_io.run(io_done).await });

// send packet
println!(" send packet");
let data = b"hello world!";
let target = PublicKey::from([0x10; PUBLIC_KEY_LENGTH]);

crate::hp::derp::client::send_packet(&mut io_rw, &None, target.clone(), data).await?;
let msg = server_channel_r.recv().await.unwrap();
match msg {
ServerMessage::SendPacket((got_target, packet)) => {
assert_eq!(target, got_target);
assert_eq!(key, packet.src);
assert_eq!(&data[..], &packet.bytes);
println!(" send packet success");
}
m => {
bail!("expected ServerMessage::SendPacket, got {m:?}");
}
}

println!("-- drop io");
drop(io_rw);

// expect task to complete after encountering an error
if let Err(err) = tokio::time::timeout(Duration::from_secs(1), io_handle).await?? {
if let Some(io_err) = err.downcast_ref::<std::io::Error>() {
if io_err.kind() == std::io::ErrorKind::UnexpectedEof {
println!(" task closed successfully with `UnexpectedEof` error");
} else {
bail!("expected `UnexpectedEof` error, got unknown error: {io_err:?}");
}
} else {
bail!("expected `std::io::Error`, got `None`");
}
} else {
bail!("expected task to finish in `UnexpectedEof` error, got `Ok(())`");
}

Ok(())
}
}
50 changes: 48 additions & 2 deletions src/hp/derp/http/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use tokio::net::TcpStream;
use tokio::sync::oneshot;
use tokio::sync::Mutex;
use tokio::task::JoinSet;
use tracing::{debug, warn};
use tracing::{debug, instrument, warn};

use crate::hp::derp::client_conn::Io;
use crate::hp::derp::{
Expand All @@ -40,6 +40,8 @@ pub enum ClientError {
NoClient,
#[error("error sending a packet")]
Send,
#[error("error receiving a packet")]
Receive,
#[error("connect timeout")]
ConnectTimeout,
#[error("DERP region is not available")]
Expand Down Expand Up @@ -712,9 +714,10 @@ impl Client {

/// Reads a message from the server. Returns the message and the `conn_get`, or the number of
/// re-connections this Client has ever made
#[instrument(skip(self))]
pub async fn recv_detail(&self) -> Result<(ReceivedMessage, usize), ClientError> {
loop {
debug!("recv_detail");
debug!("recv_detail tick");
let (client, conn_gen) = self.connect().await?;
match client.recv().await {
Ok(msg) => {
Expand All @@ -736,6 +739,8 @@ impl Client {
if self.inner.is_closed.load(Ordering::SeqCst) {
return Err(ClientError::Closed);
}
// TODO(ramfox): more specific error?
return Err(ClientError::Receive);
}
}
}
Expand Down Expand Up @@ -878,3 +883,44 @@ impl rustls::client::ServerCertVerifier for NoCertVerifier {
Ok(rustls::client::ServerCertVerified::assertion())
}
}

#[cfg(test)]
mod tests {
use super::*;

use crate::hp::key::node::SecretKey;
use anyhow::Result;

#[tokio::test]
async fn test_recv_detail_connect_error() -> Result<()> {
let key = SecretKey::generate();
let bad_region = DerpRegion {
region_id: 1,
avoid: false,
nodes: vec![DerpNode {
name: "test_node".to_string(),
region_id: 1,
host_name: "bad.url".into(),
stun_only: false,
stun_port: 0,
stun_test_ip: None,
ipv4: UseIpv4::Some("35.175.99.112".parse().unwrap()),
ipv6: UseIpv6::Disabled,
derp_port: 443,
}],
region_code: "test_region".to_string(),
};

let client = ClientBuilder::new().new_region(key.clone(), move || {
let region = bad_region.clone();
Box::pin(async move { Some(region) })
});

// ensure that the client will bubble up any connection error & not
// just loop ad infinitum attempting to connect
if (client.recv_detail().await).is_ok() {
bail!("expected client with bad derp region detail to return with an error");
}
Ok(())
}
}