rqbit/crates/librqbit/src/peer_connection.rs

451 lines
16 KiB
Rust
Raw Normal View History

2023-11-20 13:29:12 +00:00
use std::{
net::SocketAddr,
2024-08-08 00:35:32 +01:00
sync::Arc,
2023-11-20 13:29:12 +00:00
time::{Duration, Instant},
};
2023-12-05 22:19:58 +00:00
use anyhow::{bail, Context};
use buffers::{ByteBuf, ByteBufOwned};
2021-07-03 19:10:59 +01:00
use clone_to_owned::CloneToOwned;
use librqbit_core::{
hash_id::Id20,
lengths::{ChunkInfo, ValidPieceIndex},
peer_id::try_decode_peer_id,
};
2023-12-05 23:24:24 +00:00
use parking_lot::RwLock;
2021-07-03 19:10:59 +01:00
use peer_binary_protocol::{
2024-09-29 10:13:51 +01:00
extended::{handshake::ExtendedHandshake, ExtendedMessage, PeerIP},
serialize_piece_preamble, Handshake, Message, MessageOwned, PIECE_MESSAGE_DEFAULT_LEN,
};
2023-12-02 15:35:26 +00:00
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
2021-07-03 19:10:59 +01:00
use tokio::time::timeout;
2024-05-17 23:57:25 +01:00
use tracing::{debug, trace};
2024-08-08 00:35:32 +01:00
use crate::{read_buf::ReadBuf, spawn_utils::BlockingSpawner, stream_connect::StreamConnector};
2021-09-29 19:10:32 +01:00
2021-07-02 10:12:48 +01:00
pub trait PeerConnectionHandler {
2023-11-20 13:29:12 +00:00
fn on_connected(&self, _connection_time: Duration) {}
2024-08-28 18:02:25 +01:00
fn should_send_bitfield(&self) -> bool;
2023-11-24 18:28:46 +00:00
fn serialize_bitfield_message_to_buf(&self, buf: &mut Vec<u8>) -> anyhow::Result<usize>;
2023-12-05 17:01:30 +00:00
fn on_handshake<B>(&self, handshake: Handshake<B>) -> anyhow::Result<()>;
2021-07-03 00:22:46 +01:00
fn on_extended_handshake(
&self,
extended_handshake: &ExtendedHandshake<ByteBuf>,
) -> anyhow::Result<()>;
2024-05-03 12:47:57 +01:00
async fn on_received_message(&self, msg: Message<ByteBuf<'_>>) -> anyhow::Result<()>;
2024-05-03 16:59:49 +01:00
fn should_transmit_have(&self, id: ValidPieceIndex) -> bool;
2021-07-02 10:12:48 +01:00
fn on_uploaded_bytes(&self, bytes: u32);
fn read_chunk(&self, chunk: &ChunkInfo, buf: &mut [u8]) -> anyhow::Result<()>;
2024-08-14 10:53:25 +01:00
fn update_my_extended_handshake(
&self,
_handshake: &mut ExtendedHandshake<ByteBuf>,
) -> anyhow::Result<()> {
Ok(())
}
2021-07-02 10:12:48 +01:00
}
#[derive(Debug)]
pub enum WriterRequest {
Message(MessageOwned),
ReadChunkRequest(ChunkInfo),
2024-05-01 15:23:11 +01:00
Disconnect(anyhow::Result<()>),
}
2023-12-02 15:35:26 +00:00
#[serde_as]
#[derive(Default, Debug, Copy, Clone, Serialize, Deserialize)]
2021-07-13 14:59:44 +01:00
pub struct PeerConnectionOptions {
2023-12-02 15:35:26 +00:00
#[serde_as(as = "Option<serde_with::DurationSeconds>")]
2021-07-13 14:59:44 +01:00
pub connect_timeout: Option<Duration>,
2023-12-02 15:35:26 +00:00
#[serde_as(as = "Option<serde_with::DurationSeconds>")]
pub read_write_timeout: Option<Duration>,
2023-12-02 15:35:26 +00:00
#[serde_as(as = "Option<serde_with::DurationSeconds>")]
2021-07-13 14:59:44 +01:00
pub keep_alive_interval: Option<Duration>,
}
2023-12-05 20:08:37 +00:00
pub(crate) struct PeerConnection<H> {
2021-07-02 10:12:48 +01:00
handler: H,
addr: SocketAddr,
2021-07-12 21:59:08 +01:00
info_hash: Id20,
peer_id: Id20,
2021-07-13 14:59:44 +01:00
options: PeerConnectionOptions,
2021-09-29 19:10:32 +01:00
spawner: BlockingSpawner,
2024-08-08 00:35:32 +01:00
connector: Arc<StreamConnector>,
}
pub(crate) async fn with_timeout<T, E>(
timeout_value: Duration,
fut: impl std::future::Future<Output = Result<T, E>>,
) -> anyhow::Result<T>
where
E: Into<anyhow::Error>,
{
2023-11-19 12:50:11 +00:00
match timeout(timeout_value, fut).await {
Ok(v) => v.map_err(Into::into),
Err(_) => anyhow::bail!("timeout at {timeout_value:?}"),
}
}
2021-07-02 13:00:46 +01:00
2025-01-30 11:24:43 +00:00
struct ManagePeerArgs<R, W> {
handshake_supports_extended: bool,
read_buf: ReadBuf,
write_buf: Vec<u8>,
read: R,
write: W,
outgoing_chan: tokio::sync::mpsc::UnboundedReceiver<WriterRequest>,
have_broadcast: tokio::sync::broadcast::Receiver<ValidPieceIndex>,
}
2021-07-02 10:12:48 +01:00
impl<H: PeerConnectionHandler> PeerConnection<H> {
2021-07-13 14:59:44 +01:00
pub fn new(
addr: SocketAddr,
info_hash: Id20,
peer_id: Id20,
handler: H,
options: Option<PeerConnectionOptions>,
2021-09-29 19:10:32 +01:00
spawner: BlockingSpawner,
2024-08-08 00:35:32 +01:00
connector: Arc<StreamConnector>,
2021-07-13 14:59:44 +01:00
) -> Self {
2021-07-02 10:12:48 +01:00
PeerConnection {
handler,
2021-07-02 10:21:19 +01:00
addr,
2021-07-02 10:12:48 +01:00
info_hash,
peer_id,
2021-09-29 19:10:32 +01:00
spawner,
2021-07-13 14:59:44 +01:00
options: options.unwrap_or_default(),
2024-08-08 00:35:32 +01:00
connector,
2021-07-02 10:12:48 +01:00
}
}
2023-12-03 12:14:50 +00:00
// By the time this is called:
// read_buf should start with valuable data. The handshake should be removed from it.
2023-12-05 17:01:30 +00:00
pub async fn manage_peer_incoming(
&self,
outgoing_chan: tokio::sync::mpsc::UnboundedReceiver<WriterRequest>,
read_buf: ReadBuf,
handshake: Handshake<ByteBufOwned>,
mut conn: tokio::net::TcpStream,
have_broadcast: tokio::sync::broadcast::Receiver<ValidPieceIndex>,
2023-12-05 17:01:30 +00:00
) -> anyhow::Result<()> {
use tokio::io::AsyncWriteExt;
let rwtimeout = self
.options
.read_write_timeout
.unwrap_or_else(|| Duration::from_secs(10));
if handshake.info_hash != self.info_hash.0 {
anyhow::bail!("wrong info hash");
}
2023-12-05 22:19:58 +00:00
if handshake.peer_id == self.peer_id.0 {
bail!("looks like we are connecting to ourselves");
}
trace!(
"incoming connection: id={:?}",
2023-12-24 16:53:02 -06:00
try_decode_peer_id(Id20::new(handshake.peer_id))
);
let mut write_buf = Vec::<u8>::with_capacity(PIECE_MESSAGE_DEFAULT_LEN);
let handshake = Handshake::new(self.info_hash, self.peer_id);
handshake.serialize(&mut write_buf);
with_timeout(rwtimeout, conn.write_all(&write_buf))
.await
.context("error writing handshake")?;
write_buf.clear();
2025-01-30 11:24:43 +00:00
let handshake_supports_extended = handshake.supports_extended();
2023-12-05 20:02:54 +00:00
self.handler.on_handshake(handshake)?;
let (read, write) = conn.into_split();
2025-01-30 11:24:43 +00:00
self.manage_peer(ManagePeerArgs {
handshake_supports_extended,
read_buf,
write_buf,
read,
write,
outgoing_chan,
have_broadcast,
2025-01-30 11:24:43 +00:00
})
.await
2023-12-05 17:01:30 +00:00
}
pub async fn manage_peer_outgoing(
&self,
outgoing_chan: tokio::sync::mpsc::UnboundedReceiver<WriterRequest>,
have_broadcast: tokio::sync::broadcast::Receiver<ValidPieceIndex>,
) -> anyhow::Result<()> {
use tokio::io::AsyncWriteExt;
let rwtimeout = self
.options
.read_write_timeout
.unwrap_or_else(|| Duration::from_secs(10));
let connect_timeout = self
.options
.connect_timeout
.unwrap_or_else(|| Duration::from_secs(10));
2023-11-20 13:29:12 +00:00
let now = Instant::now();
let (mut read, mut write) =
with_timeout(connect_timeout, self.connector.connect(self.addr))
.await
.context("error connecting")?;
2023-11-20 13:29:12 +00:00
self.handler.on_connected(now.elapsed());
2021-07-04 11:36:16 +01:00
let mut write_buf = Vec::<u8>::with_capacity(PIECE_MESSAGE_DEFAULT_LEN);
2021-07-02 10:12:48 +01:00
let handshake = Handshake::new(self.info_hash, self.peer_id);
handshake.serialize(&mut write_buf);
with_timeout(rwtimeout, write.write_all(&write_buf))
.await
.context("error writing handshake")?;
write_buf.clear();
let mut read_buf = ReadBuf::new();
let h = read_buf
.read_handshake(&mut read, rwtimeout)
.await
.context("error reading handshake")?;
2025-01-30 11:24:43 +00:00
let handshake_supports_extended = h.supports_extended();
2024-08-28 17:44:46 +01:00
trace!(
2024-08-29 12:48:14 +01:00
peer_id=?Id20::new(h.peer_id),
2024-08-28 17:44:46 +01:00
decoded_id=?try_decode_peer_id(Id20::new(h.peer_id)),
"connected",
);
2021-07-13 13:16:59 +01:00
if h.info_hash != self.info_hash.0 {
anyhow::bail!("info hash does not match");
}
2023-12-05 22:19:58 +00:00
if h.peer_id == self.peer_id.0 {
bail!("looks like we are connecting to ourselves");
}
2021-07-03 00:22:46 +01:00
self.handler.on_handshake(h)?;
2025-01-30 11:24:43 +00:00
self.manage_peer(ManagePeerArgs {
handshake_supports_extended,
read_buf,
write_buf,
read,
write,
outgoing_chan,
have_broadcast,
2025-01-30 11:24:43 +00:00
})
.await
}
async fn manage_peer(
&self,
2025-01-30 11:24:43 +00:00
args: ManagePeerArgs<
impl tokio::io::AsyncRead + Send + Unpin,
impl tokio::io::AsyncWrite + Send + Unpin,
>,
) -> anyhow::Result<()> {
2025-01-30 11:24:43 +00:00
let ManagePeerArgs {
handshake_supports_extended,
mut read_buf,
mut write_buf,
mut read,
mut write,
mut outgoing_chan,
mut have_broadcast,
} = args;
use tokio::io::AsyncWriteExt;
let rwtimeout = self
.options
.read_write_timeout
.unwrap_or_else(|| Duration::from_secs(10));
let extended_handshake: RwLock<Option<ExtendedHandshake<ByteBufOwned>>> = RwLock::new(None);
2023-12-05 23:24:24 +00:00
let extended_handshake_ref = &extended_handshake;
let supports_extended = handshake_supports_extended;
2021-07-02 13:00:46 +01:00
if supports_extended {
2024-08-14 10:53:25 +01:00
let mut my_extended = ExtendedHandshake::new();
2024-08-29 13:08:55 +01:00
my_extended.v = Some(ByteBuf(crate::client_name_and_version().as_bytes()));
2024-09-29 10:13:51 +01:00
my_extended.yourip = Some(PeerIP(self.addr.ip()));
2024-08-14 10:53:25 +01:00
self.handler
.update_my_extended_handshake(&mut my_extended)?;
let my_extended = Message::Extended(ExtendedMessage::Handshake(my_extended));
2023-11-19 12:50:11 +00:00
trace!("sending extended handshake: {:?}", &my_extended);
my_extended
2024-08-25 12:53:28 +01:00
.serialize(&mut write_buf, &Default::default)
.unwrap();
with_timeout(rwtimeout, write.write_all(&write_buf))
.await
.context("error writing extended handshake")?;
write_buf.clear();
}
let writer = async move {
2021-07-13 14:59:44 +01:00
let keep_alive_interval = self
.options
.keep_alive_interval
.unwrap_or_else(|| Duration::from_secs(120));
2024-08-28 18:02:25 +01:00
if self.handler.should_send_bitfield() {
2023-11-24 18:28:46 +00:00
let len = self
.handler
2023-11-24 18:28:46 +00:00
.serialize_bitfield_message_to_buf(&mut write_buf)?;
with_timeout(rwtimeout, write.write_all(&write_buf[..len]))
2023-11-24 18:28:46 +00:00
.await
.context("error writing bitfield to peer")?;
trace!("sent bitfield");
}
let len = MessageOwned::Unchoke.serialize(&mut write_buf, &Default::default)?;
with_timeout(rwtimeout, write.write_all(&write_buf[..len]))
.await
.context("error writing unchoke")?;
trace!("sent unchoke");
2024-05-17 23:57:25 +01:00
let mut broadcast_closed = false;
loop {
let req = loop {
break tokio::select! {
2024-05-17 23:57:25 +01:00
r = have_broadcast.recv(), if !broadcast_closed => match r {
2024-05-03 16:59:49 +01:00
Ok(id) => {
if self.handler.should_transmit_have(id) {
WriterRequest::Message(MessageOwned::Have(id.get()))
} else {
continue
}
},
2024-05-17 23:57:25 +01:00
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
broadcast_closed = true;
debug!("broadcast channel closed, will not poll it anymore");
continue
},
_ => continue
},
r = timeout(keep_alive_interval, outgoing_chan.recv()) => match r {
Ok(Some(msg)) => msg,
Ok(None) => {
anyhow::bail!("closing writer, channel closed");
}
Err(_) => WriterRequest::Message(MessageOwned::KeepAlive),
}
};
};
let mut uploaded_add = None;
2024-05-01 15:23:11 +01:00
trace!("about to send: {:?}", &req);
let len = match req {
2023-12-05 23:24:24 +00:00
WriterRequest::Message(msg) => msg.serialize(&mut write_buf, &|| {
extended_handshake_ref
.read()
.as_ref()
.map(|e| e.peer_extended_messages())
.unwrap_or_default()
2023-12-05 23:24:24 +00:00
})?,
WriterRequest::ReadChunkRequest(chunk) => {
2024-03-29 20:32:08 +00:00
#[allow(unused_mut)]
let mut skip_reading_for_e2e_tests = false;
#[cfg(test)]
{
2024-03-29 20:32:08 +00:00
use tracing::warn;
// This is poor-mans fault injection for running e2e tests.
use crate::tests::test_util::TestPeerMetadata;
let tpm = TestPeerMetadata::from_peer_id(self.peer_id);
use rand::Rng;
2025-06-05 11:38:50 +01:00
if rand::rng().random_bool(tpm.disconnect_probability()) {
bail!("disconnecting, to simulate failure in tests");
}
2024-04-24 14:19:04 +01:00
#[allow(clippy::cast_possible_truncation)]
2025-06-05 11:38:50 +01:00
let sleep_ms = (rand::rng().random::<f64>()
* (tpm.max_random_sleep_ms as f64))
as u64;
tokio::time::sleep(Duration::from_millis(sleep_ms)).await;
2024-03-29 20:32:08 +00:00
2025-06-05 11:38:50 +01:00
if rand::rng().random_bool(tpm.bad_data_probability()) {
2024-03-29 20:32:08 +00:00
warn!("will NOT actually read the data to simulate a malicious peer that sends garbage");
write_buf.fill(0);
skip_reading_for_e2e_tests = true;
}
}
// this whole section is an optimization
write_buf.resize(PIECE_MESSAGE_DEFAULT_LEN, 0);
2024-05-01 15:23:11 +01:00
let preamble_len = serialize_piece_preamble(&chunk, &mut write_buf);
let full_len = preamble_len + chunk.size as usize;
write_buf.resize(full_len, 0);
2024-03-29 20:32:08 +00:00
if !skip_reading_for_e2e_tests {
self.spawner
.spawn_block_in_place(|| {
self.handler
2024-05-01 15:23:11 +01:00
.read_chunk(&chunk, &mut write_buf[preamble_len..])
2024-03-29 20:32:08 +00:00
})
.with_context(|| format!("error reading chunk {chunk:?}"))?;
}
2021-09-29 19:10:32 +01:00
uploaded_add = Some(chunk.size);
full_len
}
2024-05-01 15:23:11 +01:00
WriterRequest::Disconnect(res) => {
2023-12-05 23:44:29 +00:00
trace!("disconnect requested, closing writer");
2024-05-01 15:23:11 +01:00
return res;
2023-11-18 00:20:49 +00:00
}
};
with_timeout(rwtimeout, write.write_all(&write_buf[..len]))
.await
.context("error writing the message to peer")?;
if let Some(uploaded_add) = uploaded_add {
2021-07-02 10:12:48 +01:00
self.handler.on_uploaded_bytes(uploaded_add)
}
}
// For type inference.
#[allow(unreachable_code)]
Ok::<_, anyhow::Error>(())
};
let reader = async move {
loop {
let message = read_buf
.read_message(&mut read, rwtimeout)
.await
.context("error reading message")?;
trace!("received: {:?}", &message);
if let Message::Extended(ExtendedMessage::Handshake(h)) = &message {
*extended_handshake_ref.write() = Some(h.clone_to_owned(None));
self.handler.on_extended_handshake(h)?;
} else {
self.handler
.on_received_message(message)
2024-05-03 12:47:57 +01:00
.await
.context("error in handler.on_received_message()")?;
}
}
// For type inference.
#[allow(unreachable_code)]
Ok::<_, anyhow::Error>(())
};
2023-12-29 18:54:08 -05:00
tokio::select! {
2023-12-05 23:44:29 +00:00
r = reader => {
2024-05-17 23:57:25 +01:00
trace!(result=?r, "reader is done, exiting");
2023-12-05 23:44:29 +00:00
r
}
r = writer => {
2024-05-17 23:57:25 +01:00
trace!(result=?r, "writer is done, exiting");
2023-12-05 23:44:29 +00:00
r
}
2023-12-29 18:54:08 -05:00
}
}
}