From b2f2ecf5ef45ef604cdf1a4449ca9cb6ec9a2794 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20Frosteg=C3=A5rd?= Date: Sun, 27 Aug 2023 18:36:54 +0200 Subject: [PATCH] udp: integration: improve invalid connection id test --- aquatic_udp/tests/integration.rs | 57 +++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 16 deletions(-) diff --git a/aquatic_udp/tests/integration.rs b/aquatic_udp/tests/integration.rs index 3903b43..602b2f4 100644 --- a/aquatic_udp/tests/integration.rs +++ b/aquatic_udp/tests/integration.rs @@ -1,6 +1,6 @@ use std::{ collections::{hash_map::RandomState, HashSet}, - io::Cursor, + io::{Cursor, ErrorKind}, net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket}, time::Duration, }; @@ -107,29 +107,54 @@ fn test_announce_with_invalid_connection_id() -> anyhow::Result<()> { config.network.address.set_port(TRACKER_PORT); + run_tracker(config); + let tracker_addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, TRACKER_PORT)); let peer_addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)); - run_tracker(config); - let socket = UdpSocket::bind(peer_addr)?; + socket.set_read_timeout(Some(Duration::from_secs(1)))?; - let res_response = announce( - &socket, - tracker_addr, - ConnectionId(0), - 1, - InfoHash([0; 20]), - 100, - false, - ); + // Make sure that the tracker in fact responds to requests + let connection_id = connect(&socket, tracker_addr).with_context(|| "connect")?; - // No response should be sent by tracker. Ideally, we would like to test - // that the error is in fact a would-block one on the socket. - assert!(matches!(res_response, Err(_))); + let mut buffer = [0u8; BUFFER_SIZE]; - Ok(()) + { + let mut buffer = Cursor::new(&mut buffer[..]); + + let request = Request::Announce(AnnounceRequest { + connection_id: ConnectionId(!connection_id.0), + transaction_id: TransactionId(0), + info_hash: InfoHash([0; 20]), + peer_id: PeerId([0; 20]), + bytes_downloaded: NumberOfBytes(0), + bytes_uploaded: NumberOfBytes(0), + bytes_left: NumberOfBytes(0), + event: AnnounceEvent::Started, + ip_address: None, + key: PeerKey(0), + peers_wanted: NumberOfPeers(-1), + port: Port(1), + }); + + request + .write(&mut buffer) + .with_context(|| "write request")?; + + let bytes_written = buffer.position() as usize; + + socket + .send_to(&(buffer.into_inner())[..bytes_written], tracker_addr) + .with_context(|| "send request")?; + } + + match socket.recv_from(&mut buffer) { + Ok(_) => Err(anyhow::anyhow!("received response")), + Err(err) if err.kind() == ErrorKind::WouldBlock => Ok(()), + Err(err) => Err(err.into()), + } } // FIXME: should ideally try different ports and use sync primitives to find