Initial commit: aquatic, udp bittorrent tracker

This commit is contained in:
Joakim Frostegård 2020-04-04 22:08:32 +02:00
commit ace2e1a296
18 changed files with 1386 additions and 0 deletions

View file

@ -0,0 +1,8 @@
[package]
name = "bittorrent_udp"
version = "0.1.0"
authors = ["Joakim Frostegård <joakim.frostegard@gmail.com>"]
edition = "2018"
[dependencies]
byteorder = "1"

View file

@ -0,0 +1,21 @@
use crate::types;
pub fn event_from_i32(i: i32) -> types::AnnounceEvent {
match i {
1 => types::AnnounceEvent::Completed,
2 => types::AnnounceEvent::Started,
3 => types::AnnounceEvent::Stopped,
_ => types::AnnounceEvent::None
}
}
pub fn event_to_i32(event: types::AnnounceEvent) -> i32 {
match event {
types::AnnounceEvent::None => 0,
types::AnnounceEvent::Completed => 1,
types::AnnounceEvent::Started => 2,
types::AnnounceEvent::Stopped => 3
}
}

View file

@ -0,0 +1,6 @@
pub mod common;
pub mod requests;
pub mod responses;
pub use self::requests::*;
pub use self::responses::*;

View file

@ -0,0 +1,187 @@
use byteorder::{ReadBytesExt, WriteBytesExt, NetworkEndian};
use std::io;
use std::io::Read;
use std::net::Ipv4Addr;
use crate::types;
use super::common::*;
const MAGIC_NUMBER: i64 = 4_497_486_125_440;
pub fn request_to_bytes(request: &types::Request) -> Vec<u8> {
let mut bytes = Vec::new();
match request {
types::Request::Connect(r) => {
bytes.write_i64::<NetworkEndian>(MAGIC_NUMBER).unwrap();
bytes.write_i32::<NetworkEndian>(0).unwrap();
bytes.write_i32::<NetworkEndian>(r.transaction_id.0).unwrap();
},
types::Request::Announce(r) => {
bytes.write_i64::<NetworkEndian>(r.connection_id.0).unwrap();
bytes.write_i32::<NetworkEndian>(1).unwrap();
bytes.write_i32::<NetworkEndian>(r.transaction_id.0).unwrap();
bytes.extend(r.info_hash.0.iter());
bytes.extend(r.peer_id.0.iter());
bytes.write_i64::<NetworkEndian>(r.bytes_downloaded.0).unwrap();
bytes.write_i64::<NetworkEndian>(r.bytes_left.0).unwrap();
bytes.write_i64::<NetworkEndian>(r.bytes_uploaded.0).unwrap();
bytes.write_i32::<NetworkEndian>(event_to_i32(r.event)).unwrap();
bytes.extend(&r.ip_address.map_or([0; 4], |ip| ip.octets()));
bytes.write_u32::<NetworkEndian>(0).unwrap(); // IP
bytes.write_u32::<NetworkEndian>(r.key.0).unwrap();
bytes.write_i32::<NetworkEndian>(r.peers_wanted.0).unwrap();
bytes.write_u16::<NetworkEndian>(r.port.0).unwrap();
},
types::Request::Scrape(r) => {
bytes.write_i64::<NetworkEndian>(r.connection_id.0).unwrap();
bytes.write_i32::<NetworkEndian>(2).unwrap();
bytes.write_i32::<NetworkEndian>(r.transaction_id.0).unwrap();
for info_hash in &r.info_hashes {
bytes.extend(info_hash.0.iter());
}
}
_ => () // Invalid requests should never happen
}
bytes
}
pub fn request_from_bytes(
bytes: &[u8],
max_scrape_torrents: u8,
) -> types::Request {
match try_request_from_bytes(bytes, max_scrape_torrents){
Ok(request) => request,
Err(_) => types::Request::Error
}
}
fn try_request_from_bytes(
bytes: &[u8],
max_scrape_torrents: u8,
) -> Result<types::Request,io::Error> {
let mut bytes = io::Cursor::new(bytes);
let connection_id = bytes.read_i64::<NetworkEndian>()?;
let action = bytes.read_i32::<NetworkEndian>()?;
let transaction_id = bytes.read_i32::<NetworkEndian>()?;
match action {
// Connect
0 => {
if connection_id == MAGIC_NUMBER {
Ok(types::Request::Connect(types::ConnectRequest {
transaction_id:types::TransactionId(transaction_id)
}))
}
else {
Ok(types::Request::Invalid(types::InvalidRequest {
transaction_id:types::TransactionId(transaction_id),
message:
"Please send protocol identifier in connect request"
.to_string()
}))
}
},
// Announce
1 => {
let mut info_hash = [0; 20];
let mut peer_id = [0; 20];
let mut ip = [0; 4];
bytes.read_exact(&mut info_hash)?;
bytes.read_exact(&mut peer_id)?;
let bytes_downloaded = bytes.read_i64::<NetworkEndian>()?;
let bytes_left = bytes.read_i64::<NetworkEndian>()?;
let bytes_uploaded = bytes.read_i64::<NetworkEndian>()?;
let event = bytes.read_i32::<NetworkEndian>()?;
bytes.read_exact(&mut ip)?;
let key = bytes.read_u32::<NetworkEndian>()?;
let peers_wanted = bytes.read_i32::<NetworkEndian>()?;
let port = bytes.read_u16::<NetworkEndian>()?;
let opt_ip = if ip == [0; 4] {
None
}
else {
Some(Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]))
};
Ok(types::Request::Announce(types::AnnounceRequest {
connection_id: types::ConnectionId(connection_id),
transaction_id: types::TransactionId(transaction_id),
info_hash: types::InfoHash(info_hash),
peer_id: types::PeerId(peer_id),
bytes_downloaded: types::NumberOfBytes(bytes_downloaded),
bytes_uploaded: types::NumberOfBytes(bytes_uploaded),
bytes_left: types::NumberOfBytes(bytes_left),
event: event_from_i32(event),
ip_address: opt_ip,
key: types::PeerKey(key),
peers_wanted: types::NumberOfPeers(peers_wanted),
port: types::Port(port)
}))
},
// Scrape
2 => {
let mut info_hashes = Vec::new();
let mut info_hash = [0; 20];
let mut i = 0;
loop {
if i > max_scrape_torrents {
return Ok(types::Request::Invalid(types::InvalidRequest {
transaction_id: types::TransactionId(transaction_id),
message: format!(
"Too many torrents. Maximum is {}",
max_scrape_torrents
)
}));
}
if bytes.read_exact(&mut info_hash).is_err(){
break
}
info_hashes.push(types::InfoHash(info_hash));
i += 1;
}
Ok(types::Request::Scrape(types::ScrapeRequest {
connection_id: types::ConnectionId(connection_id),
transaction_id: types::TransactionId(transaction_id),
info_hashes
}))
}
_ => Ok(types::Request::Invalid(types::InvalidRequest {
transaction_id: types::TransactionId(transaction_id),
message: "Invalid action".to_string()
}))
}
}

View file

@ -0,0 +1,231 @@
use byteorder::{ReadBytesExt, WriteBytesExt, NetworkEndian};
use std::io;
use std::io::Read;
use std::net::{IpAddr, Ipv6Addr, Ipv4Addr};
use crate::types;
pub fn response_to_bytes(
response: &types::Response,
ip_version: types::IpVersion
) -> Vec<u8> {
let mut bytes = Vec::new();
match response {
types::Response::Connect(r) => {
bytes.write_i32::<NetworkEndian>(0).unwrap();
bytes.write_i32::<NetworkEndian>(r.transaction_id.0).unwrap();
bytes.write_i64::<NetworkEndian>(r.connection_id.0).unwrap();
},
types::Response::Announce(r) => {
bytes.write_i32::<NetworkEndian>(1).unwrap();
bytes.write_i32::<NetworkEndian>(r.transaction_id.0).unwrap();
bytes.write_i32::<NetworkEndian>(r.announce_interval.0).unwrap();
bytes.write_i32::<NetworkEndian>(r.leechers.0).unwrap();
bytes.write_i32::<NetworkEndian>(r.seeders.0).unwrap();
// Write peer IPs and ports. Silently ignore peers with wrong
// IP version
for peer in r.peers.iter(){
let mut correct = false;
match peer.ip_address {
IpAddr::V4(ip) => {
if let types::IpVersion::IPv4 = ip_version {
bytes.extend(&ip.octets());
correct = true;
}
},
IpAddr::V6(ip) => {
if let types::IpVersion::IPv6 = ip_version {
bytes.extend(&ip.octets());
correct = true;
}
}
}
if correct {
bytes.write_u16::<NetworkEndian>(peer.port.0).unwrap();
}
}
},
types::Response::Scrape(r) => {
bytes.write_i32::<NetworkEndian>(2).unwrap();
bytes.write_i32::<NetworkEndian>(r.transaction_id.0).unwrap();
for torrent_stat in r.torrent_stats.iter(){
bytes.write_i32::<NetworkEndian>(torrent_stat.seeders.0)
.unwrap();
bytes.write_i32::<NetworkEndian>(torrent_stat.completed.0)
.unwrap();
bytes.write_i32::<NetworkEndian>(torrent_stat.leechers.0)
.unwrap();
}
},
types::Response::Error(r) => {
bytes.write_i32::<NetworkEndian>(3).unwrap();
bytes.write_i32::<NetworkEndian>(r.transaction_id.0).unwrap();
bytes.extend(r.message.as_bytes().iter());
},
}
bytes
}
pub fn response_from_bytes(
bytes: &[u8],
ip_version: types::IpVersion,
) -> Result<types::Response, io::Error> {
let mut bytes = io::Cursor::new(bytes);
let action = bytes.read_i32::<NetworkEndian>()?;
let transaction_id = bytes.read_i32::<NetworkEndian>()?;
match action {
// Connect
0 => {
let connection_id = bytes.read_i64::<NetworkEndian>()?;
Ok(types::Response::Connect(types::ConnectResponse {
connection_id: types::ConnectionId(connection_id),
transaction_id: types::TransactionId(transaction_id)
}))
},
// Announce
1 => {
let announce_interval = bytes.read_i32::<NetworkEndian>()?;
let leechers = bytes.read_i32::<NetworkEndian>()?;
let seeders = bytes.read_i32::<NetworkEndian>()?;
let mut peers = Vec::new();
loop {
let mut opt_ip_address = None;
match ip_version {
types::IpVersion::IPv4 => {
let mut ip_bytes = [0; 4];
if bytes.read_exact(&mut ip_bytes).is_ok() {
opt_ip_address = Some(IpAddr::V4(Ipv4Addr::new(
ip_bytes[0],
ip_bytes[1],
ip_bytes[2],
ip_bytes[3],
)));
}
},
types::IpVersion::IPv6 => {
let mut ip_bytes = [0; 16];
if bytes.read_exact(&mut ip_bytes).is_ok() {
let mut ip_bytes_ref = &ip_bytes[..];
opt_ip_address = Some(IpAddr::V6(Ipv6Addr::new(
ip_bytes_ref.read_u16::<NetworkEndian>()?,
ip_bytes_ref.read_u16::<NetworkEndian>()?,
ip_bytes_ref.read_u16::<NetworkEndian>()?,
ip_bytes_ref.read_u16::<NetworkEndian>()?,
ip_bytes_ref.read_u16::<NetworkEndian>()?,
ip_bytes_ref.read_u16::<NetworkEndian>()?,
ip_bytes_ref.read_u16::<NetworkEndian>()?,
ip_bytes_ref.read_u16::<NetworkEndian>()?,
)));
}
},
}
if let Some(ip_address) = opt_ip_address {
if let Ok(port) = bytes.read_u16::<NetworkEndian>() {
peers.push(types::ResponsePeer {
ip_address,
port: types::Port(port),
});
}
else {
break;
}
}
else {
break;
}
}
Ok(types::Response::Announce(types::AnnounceResponse {
transaction_id: types::TransactionId(transaction_id),
announce_interval: types::AnnounceInterval(announce_interval),
leechers: types::NumberOfPeers(leechers),
seeders: types::NumberOfPeers(seeders),
peers
}))
},
// Scrape
2 => {
let mut stats = Vec::new();
// TODO: transition to while let && when available
loop {
if let Ok(seeders) = bytes.read_i32::<NetworkEndian>() {
if let Ok(downloaded) = bytes.read_i32::<NetworkEndian>() {
if let Ok(leechers) = bytes.read_i32::<NetworkEndian>() {
stats.push(types::TorrentScrapeStatistics {
seeders: types::NumberOfPeers(seeders),
completed: types::NumberOfDownloads(downloaded),
leechers: types::NumberOfPeers(leechers)
});
}
else {
break;
}
}
else {
break;
}
}
else {
break;
}
}
Ok(types::Response::Scrape(types::ScrapeResponse {
transaction_id: types::TransactionId(transaction_id),
torrent_stats: stats
}))
},
// Error
3 => {
let mut message_bytes = Vec::new();
bytes.read_to_end(&mut message_bytes)?;
let message = match String::from_utf8(message_bytes) {
Ok(message) => message,
Err(_) => "".to_string()
};
Ok(types::Response::Error(types::ErrorResponse {
transaction_id: types::TransactionId(transaction_id),
message
}))
},
_ => {
Ok(types::Response::Error(types::ErrorResponse {
transaction_id: types::TransactionId(transaction_id),
message: "Invalid action".to_string()
}))
}
}
}

View file

@ -0,0 +1,2 @@
pub mod converters;
pub mod types;

View file

@ -0,0 +1,50 @@
use std::net;
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub enum IpVersion {
IPv4,
IPv6
}
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct AnnounceInterval (pub i32);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct InfoHash (pub [u8; 20]);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct ConnectionId (pub i64);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct TransactionId (pub i32);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct NumberOfBytes (pub i64);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct NumberOfPeers (pub i32);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct NumberOfDownloads (pub i32);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct Port (pub u16);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, PartialOrd, Ord)]
pub struct PeerId (pub [u8; 20]);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct PeerKey (pub u32);
#[derive(Hash, PartialEq, Eq, Clone, Debug)]
pub struct ResponsePeer {
pub ip_address: net::IpAddr,
pub port: Port,
}

View file

@ -0,0 +1,7 @@
pub mod common;
pub mod request;
pub mod response;
pub use self::common::*;
pub use self::request::*;
pub use self::response::*;

View file

@ -0,0 +1,59 @@
use std::net::Ipv4Addr;
use super::common::*;
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub enum AnnounceEvent {
Started,
Stopped,
Completed,
None
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ConnectRequest {
pub transaction_id: TransactionId
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct AnnounceRequest {
pub connection_id: ConnectionId,
pub transaction_id: TransactionId,
pub info_hash: InfoHash,
pub peer_id: PeerId,
pub bytes_downloaded: NumberOfBytes,
pub bytes_uploaded: NumberOfBytes,
pub bytes_left: NumberOfBytes,
pub event: AnnounceEvent,
pub ip_address: Option<Ipv4Addr>,
pub key: PeerKey,
pub peers_wanted: NumberOfPeers,
pub port: Port
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ScrapeRequest {
pub connection_id: ConnectionId,
pub transaction_id: TransactionId,
pub info_hashes: Vec<InfoHash>
}
/// This is used for returning specific errors from the parser
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct InvalidRequest {
pub transaction_id: TransactionId,
pub message: String
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Request {
Connect(ConnectRequest),
Announce(AnnounceRequest),
Scrape(ScrapeRequest),
Invalid(InvalidRequest),
/// Should ideally only be used when no transaction id can be parsed,
/// but is currently also used as a catch-all for non-specific errors
Error,
}

View file

@ -0,0 +1,45 @@
use super::common::*;
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub struct TorrentScrapeStatistics {
pub seeders: NumberOfPeers,
pub completed: NumberOfDownloads,
pub leechers: NumberOfPeers
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ConnectResponse {
pub connection_id: ConnectionId,
pub transaction_id: TransactionId
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct AnnounceResponse {
pub transaction_id: TransactionId,
pub announce_interval: AnnounceInterval,
pub leechers: NumberOfPeers,
pub seeders: NumberOfPeers,
pub peers: Vec<ResponsePeer>
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ScrapeResponse {
pub transaction_id: TransactionId,
pub torrent_stats: Vec<TorrentScrapeStatistics>
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ErrorResponse {
pub transaction_id: TransactionId,
pub message: String
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Response {
Connect(ConnectResponse),
Announce(AnnounceResponse),
Scrape(ScrapeResponse),
Error(ErrorResponse),
}