From d13a543f13aeb0b33422b44e5c7197c0ce994393 Mon Sep 17 00:00:00 2001 From: arnaucube Date: Sat, 20 Jun 2020 18:59:52 +0200 Subject: [PATCH] Add msg byte constructions --- src/lib.rs | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index abf2cd2..459a8d6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -404,6 +404,87 @@ fn bytes_to_ip(b: &[u8; 4]) -> String { Ipv4Addr::new(b[0], b[1], b[2], b[3]).to_string() } +fn msg_handshake(info_hash: Vec) -> Vec { + let mut b: [u8; 68] = [0; 68]; + b[0] = 19; + b[1..20].clone_from_slice(b"BitTorrent protocol"); // TODO use constant for the string + + b[28..48].clone_from_slice(&info_hash); + + b.to_vec() +} + +fn msg_choke() -> Vec { + let mut b: [u8; 5] = [0; 5]; + BigEndian::write_u32(&mut b[0..4], 1); + b.to_vec() +} +fn msg_unchoke() -> Vec { + let mut b: [u8; 5] = [0; 5]; + BigEndian::write_u32(&mut b[0..4], 1); + b[4] = 1; + b.to_vec() +} +fn msg_interested() -> Vec { + let mut b: [u8; 5] = [0; 5]; + BigEndian::write_u32(&mut b[0..4], 1); + b[4] = 2; + b.to_vec() +} +fn msg_notinterested() -> Vec { + let mut b: [u8; 5] = [0; 5]; + BigEndian::write_u32(&mut b[0..4], 1); + b[4] = 3; + b.to_vec() +} +fn msg_have(payload: Payload) -> Vec { + let mut b: [u8; 9] = [0; 9]; + BigEndian::write_u32(&mut b[0..4], 5); + b[4] = 4; + BigEndian::write_u32(&mut b[5..9], payload.index); // TODO REVIEW CHECK payload.index + b.to_vec() +} +fn msg_bitfield(bitfield: Vec) -> Vec { + let mut b: [u8; 14] = [0; 14]; + BigEndian::write_u32(&mut b[0..4], bitfield.len() as u32); + b[4] = 5; + b[5..].clone_from_slice(&bitfield); + b.to_vec() +} +fn msg_request(payload: &Payload) -> Vec { + let mut b: [u8; 17] = [0; 17]; + BigEndian::write_u32(&mut b[0..4], 13); + b[4] = 6; + BigEndian::write_u32(&mut b[5..9], payload.index); + BigEndian::write_u32(&mut b[9..13], payload.begin); + BigEndian::write_u32(&mut b[13..17], payload.length); + b.to_vec() +} +fn msg_piece(payload: Payload) -> Vec { + let mut b: [u8; 13] = [0; 13]; // TODO payload.block.length + BigEndian::write_u32(&mut b[0..4], payload.block.length+9); + b[4] = 7; + BigEndian::write_u32(&mut b[5..9], payload.index); + BigEndian::write_u32(&mut b[9..13], payload.begin); + b[13..].clone_from_slice(&payload.block.bytes); + b.to_vec() +} +fn msg_cancel(payload: Payload) -> Vec { + let mut b: [u8; 17] = [0; 17]; + BigEndian::write_u32(&mut b[0..4], 13); + b[4] = 8; + BigEndian::write_u32(&mut b[5..9], payload.index); + BigEndian::write_u32(&mut b[9..13], payload.begin); + BigEndian::write_u32(&mut b[13..17], payload.length); + b.to_vec() +} +fn msg_port(port: u16) -> Vec { + let mut b: [u8; 7] = [0; 7]; + BigEndian::write_u32(&mut b[0..4], 3); + b[4] = 9; + BigEndian::write_u16(&mut b[5..7], port); + b.to_vec() +} #[cfg(test)]