Skip to content

Commit

Permalink
chore: apply rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
hails committed May 21, 2019
1 parent 13220ed commit cb7db7b
Show file tree
Hide file tree
Showing 2 changed files with 118 additions and 118 deletions.
196 changes: 98 additions & 98 deletions src/announce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,120 +19,120 @@ use itertools::Itertools;

#[derive(Serialize, Debug)]
pub struct TrackerAnnounce {
#[serde(skip_serializing)]
pub info_hash: String,
#[serde(skip_serializing)]
info_hash_bytes: [u8; 20],
pub peer_id: String,
pub uploaded: u32,
pub downloaded: u32,
pub left: u32,
pub port: u32,
pub compact: String,
#[serde(skip_serializing)]
pub info_hash: String,
#[serde(skip_serializing)]
info_hash_bytes: [u8; 20],
pub peer_id: String,
pub uploaded: u32,
pub downloaded: u32,
pub left: u32,
pub port: u32,
pub compact: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TrackerResponse {
#[serde(rename = "failure reason")]
failure_reason: Option<String>,
pub complete: Option<u32>,
pub incomplete: Option<u32>,
pub interval: Option<u32>,
#[serde(rename = "peers")]
peers_bin: Option<ByteBuf>,
pub peers: Option<Vec<(String, u16)>>,
#[serde(rename = "failure reason")]
failure_reason: Option<String>,
pub complete: Option<u32>,
pub incomplete: Option<u32>,
pub interval: Option<u32>,
#[serde(rename = "peers")]
peers_bin: Option<ByteBuf>,
pub peers: Option<Vec<(String, u16)>>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TrackerResponsePeer {
pub ip: String,
// pub port:
pub ip: String,
// pub port:
}

pub fn announce(
announce_info: TrackerAnnounce,
tracker_url: &String,
announce_info: TrackerAnnounce,
tracker_url: &String,
) -> Result<TrackerResponse, Error> {
let announce_info = TrackerAnnounce {
info_hash: announce_info
.info_hash_bytes
.into_iter()
.map(|byte| percent_encode_byte(*byte))
.collect(),
..announce_info
};

let qs = serde_urlencoded::to_string(&announce_info).unwrap();

let announce_url = format!(
"{}?{}&info_hash={}",
tracker_url, qs, announce_info.info_hash
);

let mut response = reqwest::get(&announce_url)?;
let mut buf: Vec<u8> = vec![];
response.copy_to(&mut buf)?;

let mut tracker_response: TrackerResponse = de::from_bytes(&buf)?;

match &tracker_response.failure_reason {
Some(_) => panic!("FAILED"),
None => (),
}

let mut peers: Vec<(String, u16)> = vec![];

for mut chunk in &tracker_response
.clone()
.peers_bin
.unwrap()
.into_iter()
.chunks(6)
{
let ip: String = format!("{}", chunk.by_ref().take(4).format("."));
let port: Vec<_> = chunk.by_ref().take(2).collect();
peers.push((ip, ((port[0] as u16) << 8 | port[1] as u16)));
}

match &tracker_response.peers_bin {
Some(_) => tracker_response.peers = Some(peers),
None => tracker_response.peers = None,
}

Ok(tracker_response)
let announce_info = TrackerAnnounce {
info_hash: announce_info
.info_hash_bytes
.into_iter()
.map(|byte| percent_encode_byte(*byte))
.collect(),
..announce_info
};

let qs = serde_urlencoded::to_string(&announce_info).unwrap();

let announce_url = format!(
"{}?{}&info_hash={}",
tracker_url, qs, announce_info.info_hash
);

let mut response = reqwest::get(&announce_url)?;
let mut buf: Vec<u8> = vec![];
response.copy_to(&mut buf)?;

let mut tracker_response: TrackerResponse = de::from_bytes(&buf)?;

match &tracker_response.failure_reason {
Some(_) => panic!("FAILED"),
None => (),
}

let mut peers: Vec<(String, u16)> = vec![];

for mut chunk in &tracker_response
.clone()
.peers_bin
.unwrap()
.into_iter()
.chunks(6)
{
let ip: String = format!("{}", chunk.by_ref().take(4).format("."));
let port: Vec<_> = chunk.by_ref().take(2).collect();
peers.push((ip, ((port[0] as u16) << 8 | port[1] as u16)));
}

match &tracker_response.peers_bin {
Some(_) => tracker_response.peers = Some(peers),
None => tracker_response.peers = None,
}

Ok(tracker_response)
}

pub fn generate_announce(torrent: &Torrent) -> Result<TrackerAnnounce, Error> {
let torrent_info = serde_bencode::to_bytes(&torrent.info)?;
let info_hash = Sha1::from(&torrent_info).digest();

let peer_id = format!("-RS0001-{}", random_numbers());
assert!(peer_id.len() == 20, "peer_id should have 20 bytes");

Ok(TrackerAnnounce {
info_hash: "".to_owned(),
info_hash_bytes: info_hash.bytes(),
peer_id,
uploaded: 0,
downloaded: 0,
left: 0,
port: 0,
compact: "1".to_string(),
})
let torrent_info = serde_bencode::to_bytes(&torrent.info)?;
let info_hash = Sha1::from(&torrent_info).digest();

let peer_id = format!("-RS0001-{}", random_numbers());
assert!(peer_id.len() == 20, "peer_id should have 20 bytes");

Ok(TrackerAnnounce {
info_hash: "".to_owned(),
info_hash_bytes: info_hash.bytes(),
peer_id,
uploaded: 0,
downloaded: 0,
left: 0,
port: 0,
compact: "1".to_string(),
})
}

fn random_numbers() -> String {
const CHARSET: &[u8] = b"0123456789";
const PASSWORD_LEN: usize = 12;
let mut rng = rand::thread_rng();

let password: String = (0..PASSWORD_LEN)
.map(|_| {
let idx = rng.gen_range(0, CHARSET.len());
// This is safe because `idx` is in range of `CHARSET`
char::from(unsafe { *CHARSET.get_unchecked(idx) })
})
.collect();

password
const CHARSET: &[u8] = b"0123456789";
const PASSWORD_LEN: usize = 12;
let mut rng = rand::thread_rng();

let password: String = (0..PASSWORD_LEN)
.map(|_| {
let idx = rng.gen_range(0, CHARSET.len());
// This is safe because `idx` is in range of `CHARSET`
char::from(unsafe { *CHARSET.get_unchecked(idx) })
})
.collect();

password
}
40 changes: 20 additions & 20 deletions src/torrent_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,37 @@ use serde_bytes::ByteBuf;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Torrent {
pub announce: String,
// #[serde(rename = "announce-list")]
pub announce_list: Option<Vec<String>>,
#[serde(rename = "creation date")]
pub creation_date: i32,
pub info: TorrentInfo,
pub announce: String,
// #[serde(rename = "announce-list")]
pub announce_list: Option<Vec<String>>,
#[serde(rename = "creation date")]
pub creation_date: i32,
pub info: TorrentInfo,
}

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Clone)]
pub struct TorrentInfo {
pub name: String,
pub pieces: ByteBuf,
#[serde(rename = "piece length")]
pub piece_length: u32,
pub length: Option<u32>,
pub md5sum: Option<String>,
pub files: Option<Vec<TorrentInfoFile>>,
pub name: String,
pub pieces: ByteBuf,
#[serde(rename = "piece length")]
pub piece_length: u32,
pub length: Option<u32>,
pub md5sum: Option<String>,
pub files: Option<Vec<TorrentInfoFile>>,
}

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Clone)]
pub struct TorrentInfoFile {
pub length: u32,
pub md5sum: Option<String>,
pub path: String,
pub length: u32,
pub md5sum: Option<String>,
pub path: String,
}

pub fn parse(torrent: &mut BufRead) -> Result<Torrent, Error> {
let mut contents = Vec::new();
torrent.read_to_end(&mut contents)?;
let mut contents = Vec::new();
torrent.read_to_end(&mut contents)?;

let parsed = de::from_bytes::<Torrent>(&contents)?;
let parsed = de::from_bytes::<Torrent>(&contents)?;

Ok(parsed)
Ok(parsed)
}

0 comments on commit cb7db7b

Please sign in to comment.