2021-07-02 10:12:48 +01:00
|
|
|
use std::{net::SocketAddr, time::Duration};
|
2021-06-28 12:30:23 +01:00
|
|
|
|
|
|
|
|
use anyhow::Context;
|
2021-07-02 10:12:48 +01:00
|
|
|
use log::{debug, trace};
|
2021-06-28 12:30:23 +01:00
|
|
|
use tokio::time::timeout;
|
|
|
|
|
|
|
|
|
|
use crate::{
|
2021-07-02 10:12:48 +01:00
|
|
|
buffers::ByteBuf,
|
2021-06-28 16:09:20 +01:00
|
|
|
lengths::ChunkInfo,
|
2021-06-28 12:30:23 +01:00
|
|
|
peer_binary_protocol::{
|
2021-06-28 16:09:20 +01:00
|
|
|
serialize_piece_preamble, Handshake, Message, MessageBorrowed, MessageDeserializeError,
|
2021-07-02 10:12:48 +01:00
|
|
|
MessageOwned, PIECE_MESSAGE_DEFAULT_LEN,
|
2021-06-28 12:30:23 +01:00
|
|
|
},
|
|
|
|
|
peer_id::try_decode_peer_id,
|
|
|
|
|
};
|
|
|
|
|
|
2021-07-02 10:12:48 +01:00
|
|
|
pub trait PeerConnectionHandler {
|
|
|
|
|
fn get_have_bytes(&self) -> u64;
|
|
|
|
|
fn serialize_bitfield_message_to_buf(&self, buf: &mut Vec<u8>) -> Option<usize>;
|
|
|
|
|
fn on_handshake(&self, handshake: Handshake);
|
|
|
|
|
fn on_received_message(&self, msg: Message<ByteBuf<'_>>) -> anyhow::Result<()>;
|
|
|
|
|
fn on_uploaded_bytes(&self, bytes: u32);
|
|
|
|
|
fn read_chunk(&self, chunk: &ChunkInfo, buf: &mut [u8]) -> anyhow::Result<()>;
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-28 16:09:20 +01:00
|
|
|
#[derive(Debug)]
|
|
|
|
|
pub enum WriterRequest {
|
|
|
|
|
Message(MessageOwned),
|
|
|
|
|
ReadChunkRequest(ChunkInfo),
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-02 10:12:48 +01:00
|
|
|
pub struct PeerConnection<H> {
|
|
|
|
|
handler: H,
|
|
|
|
|
addr: SocketAddr,
|
|
|
|
|
info_hash: [u8; 20],
|
|
|
|
|
peer_id: [u8; 20],
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
|
|
|
|
|
2021-07-02 10:12:48 +01:00
|
|
|
impl<H: PeerConnectionHandler> PeerConnection<H> {
|
|
|
|
|
pub fn new(addr: SocketAddr, info_hash: [u8; 20], peer_id: [u8; 20], handler: H) -> Self {
|
|
|
|
|
PeerConnection {
|
|
|
|
|
handler,
|
2021-07-02 10:21:19 +01:00
|
|
|
addr,
|
2021-07-02 10:12:48 +01:00
|
|
|
info_hash,
|
|
|
|
|
peer_id,
|
|
|
|
|
}
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
2021-07-02 10:12:48 +01:00
|
|
|
pub fn into_handler(self) -> H {
|
|
|
|
|
self.handler
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
|
|
|
|
pub async fn manage_peer(
|
|
|
|
|
&self,
|
2021-07-02 10:12:48 +01:00
|
|
|
mut outgoing_chan: tokio::sync::mpsc::UnboundedReceiver<WriterRequest>,
|
2021-06-28 12:30:23 +01:00
|
|
|
) -> anyhow::Result<()> {
|
|
|
|
|
use tokio::io::AsyncReadExt;
|
|
|
|
|
use tokio::io::AsyncWriteExt;
|
2021-07-02 10:12:48 +01:00
|
|
|
let mut conn = tokio::net::TcpStream::connect(self.addr)
|
2021-06-28 12:30:23 +01:00
|
|
|
.await
|
|
|
|
|
.context("error connecting")?;
|
2021-07-02 10:12:48 +01:00
|
|
|
let handshake = Handshake::new(self.info_hash, self.peer_id);
|
2021-06-28 12:30:23 +01:00
|
|
|
conn.write_all(&handshake.serialize())
|
|
|
|
|
.await
|
|
|
|
|
.context("error writing handshake")?;
|
2021-06-28 20:40:13 +01:00
|
|
|
let mut read_buf = vec![0u8; PIECE_MESSAGE_DEFAULT_LEN * 2];
|
2021-06-28 12:30:23 +01:00
|
|
|
let read_bytes = conn
|
|
|
|
|
.read(&mut read_buf)
|
|
|
|
|
.await
|
|
|
|
|
.context("error reading handshake")?;
|
|
|
|
|
if read_bytes == 0 {
|
|
|
|
|
anyhow::bail!("bad handshake");
|
|
|
|
|
}
|
|
|
|
|
let (h, hlen) = Handshake::deserialize(&read_buf[..read_bytes])
|
|
|
|
|
.map_err(|e| anyhow::anyhow!("error deserializing handshake: {:?}", e))?;
|
|
|
|
|
|
|
|
|
|
let mut read_so_far = 0usize;
|
|
|
|
|
debug!(
|
|
|
|
|
"connected peer {}: {:?}",
|
2021-07-02 10:12:48 +01:00
|
|
|
self.addr,
|
2021-06-28 12:30:23 +01:00
|
|
|
try_decode_peer_id(h.peer_id)
|
|
|
|
|
);
|
2021-07-02 10:12:48 +01:00
|
|
|
if h.info_hash != self.info_hash {
|
2021-06-28 12:30:23 +01:00
|
|
|
anyhow::bail!("info hash does not match");
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-02 10:12:48 +01:00
|
|
|
self.handler.on_handshake(h);
|
2021-06-28 12:30:23 +01:00
|
|
|
|
|
|
|
|
if read_bytes > hlen {
|
|
|
|
|
read_buf.copy_within(hlen..read_bytes, 0);
|
|
|
|
|
read_so_far = read_bytes - hlen;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let (mut read_half, mut write_half) = tokio::io::split(conn);
|
|
|
|
|
|
|
|
|
|
let writer = async move {
|
2021-06-28 20:40:13 +01:00
|
|
|
let mut buf = Vec::<u8>::with_capacity(PIECE_MESSAGE_DEFAULT_LEN);
|
2021-06-28 12:30:23 +01:00
|
|
|
let keep_alive_interval = Duration::from_secs(120);
|
|
|
|
|
|
2021-07-02 10:12:48 +01:00
|
|
|
if self.handler.get_have_bytes() > 0 {
|
|
|
|
|
if let Some(len) = self.handler.serialize_bitfield_message_to_buf(&mut buf) {
|
|
|
|
|
write_half
|
|
|
|
|
.write_all(&buf[..len])
|
|
|
|
|
.await
|
|
|
|
|
.context("error writing bitfield to peer")?;
|
|
|
|
|
debug!("sent bitfield to {}", self.addr);
|
|
|
|
|
}
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
loop {
|
2021-06-28 16:09:20 +01:00
|
|
|
let req = match timeout(keep_alive_interval, outgoing_chan.recv()).await {
|
2021-06-28 12:30:23 +01:00
|
|
|
Ok(Some(msg)) => msg,
|
|
|
|
|
Ok(None) => {
|
|
|
|
|
anyhow::bail!("closing writer, channel closed")
|
|
|
|
|
}
|
2021-06-28 16:09:20 +01:00
|
|
|
Err(_) => WriterRequest::Message(MessageOwned::KeepAlive),
|
2021-06-28 12:30:23 +01:00
|
|
|
};
|
|
|
|
|
|
2021-06-28 16:37:15 +01:00
|
|
|
let mut uploaded_add = None;
|
2021-06-28 12:30:23 +01:00
|
|
|
|
2021-06-28 16:09:20 +01:00
|
|
|
let len = match &req {
|
|
|
|
|
WriterRequest::Message(msg) => msg.serialize(&mut buf),
|
|
|
|
|
WriterRequest::ReadChunkRequest(chunk) => {
|
|
|
|
|
// this whole section is an optimization
|
2021-06-28 21:06:00 +01:00
|
|
|
buf.resize(PIECE_MESSAGE_DEFAULT_LEN, 0);
|
2021-06-28 16:09:20 +01:00
|
|
|
let preamble_len = serialize_piece_preamble(&chunk, &mut buf);
|
|
|
|
|
let full_len = preamble_len + chunk.size as usize;
|
|
|
|
|
buf.resize(full_len, 0);
|
2021-07-02 10:12:48 +01:00
|
|
|
self.handler
|
|
|
|
|
.read_chunk(chunk, &mut buf[preamble_len..])
|
2021-07-01 19:17:44 +01:00
|
|
|
.with_context(|| format!("error reading chunk {:?}", chunk))?;
|
2021-06-28 16:37:15 +01:00
|
|
|
uploaded_add = Some(chunk.size);
|
2021-06-28 16:09:20 +01:00
|
|
|
full_len
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2021-07-02 10:12:48 +01:00
|
|
|
debug!("sending to {}: {:?}, length={}", self.addr, &req, len);
|
2021-06-28 12:30:23 +01:00
|
|
|
|
|
|
|
|
write_half
|
|
|
|
|
.write_all(&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)
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// For type inference.
|
|
|
|
|
#[allow(unreachable_code)]
|
|
|
|
|
Ok::<_, anyhow::Error>(())
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let reader = async move {
|
|
|
|
|
loop {
|
2021-06-28 16:37:15 +01:00
|
|
|
let (message, size) = loop {
|
2021-06-28 12:30:23 +01:00
|
|
|
match MessageBorrowed::deserialize(&read_buf[..read_so_far]) {
|
|
|
|
|
Ok((msg, size)) => {
|
2021-06-28 16:37:15 +01:00
|
|
|
break (msg, size);
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
|
|
|
|
Err(MessageDeserializeError::NotEnoughData(d, _)) => {
|
|
|
|
|
if read_buf.len() < read_so_far + d {
|
|
|
|
|
read_buf.reserve(d);
|
|
|
|
|
read_buf.resize(read_buf.capacity(), 0);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let size = read_half
|
|
|
|
|
.read(&mut read_buf[read_so_far..])
|
|
|
|
|
.await
|
|
|
|
|
.context("error reading from peer")?;
|
|
|
|
|
if size == 0 {
|
|
|
|
|
anyhow::bail!(
|
|
|
|
|
"disconnected while reading, read so far: {}",
|
|
|
|
|
read_so_far
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
read_so_far += size;
|
|
|
|
|
}
|
|
|
|
|
Err(e) => return Err(e.into()),
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2021-07-02 10:12:48 +01:00
|
|
|
trace!("received from {}: {:?}", self.addr, &message);
|
2021-06-28 12:30:23 +01:00
|
|
|
|
2021-07-02 10:12:48 +01:00
|
|
|
self.handler
|
|
|
|
|
.on_received_message(message)
|
|
|
|
|
.context("error in handler.on_received_message()")?;
|
2021-06-28 16:37:15 +01:00
|
|
|
|
|
|
|
|
if read_so_far > size {
|
|
|
|
|
read_buf.copy_within(size..read_so_far, 0);
|
|
|
|
|
}
|
|
|
|
|
read_so_far -= size;
|
2021-06-28 12:30:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// For type inference.
|
|
|
|
|
#[allow(unreachable_code)]
|
|
|
|
|
Ok::<_, anyhow::Error>(())
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let r = tokio::select! {
|
|
|
|
|
r = reader => {r}
|
|
|
|
|
r = writer => {r}
|
|
|
|
|
};
|
2021-07-02 10:12:48 +01:00
|
|
|
debug!("{}: either reader or writer are done, exiting", self.addr);
|
2021-06-28 12:30:23 +01:00
|
|
|
r
|
|
|
|
|
}
|
|
|
|
|
}
|