From 9fc33804d03618cd5134682308d5c2c7f8b24d14 Mon Sep 17 00:00:00 2001 From: wikano Date: Fri, 9 Jan 2026 01:03:40 +0100 Subject: [PATCH] manage handshake wiip --- client-network/src/cryptographic_signature.rs | 8 +- client-network/src/lib.rs | 1 + client-network/src/message_handling.rs | 63 +++-- client-network/src/messages_structure.rs | 215 ++---------------- client-network/src/peers_refresh.rs | 68 ++++++ client-network/src/registration.rs | 2 +- 6 files changed, 145 insertions(+), 212 deletions(-) create mode 100644 client-network/src/peers_refresh.rs diff --git a/client-network/src/cryptographic_signature.rs b/client-network/src/cryptographic_signature.rs index 8a857ed..e278ca1 100644 --- a/client-network/src/cryptographic_signature.rs +++ b/client-network/src/cryptographic_signature.rs @@ -1,6 +1,5 @@ use std::io::Read; -use crate::messages_structure::HandshakeMessage; use bytes::Bytes; use p256::EncodedPoint; use p256::ecdsa::{ @@ -148,10 +147,7 @@ mod tests { println!("pubkey : {}", formatted_pubkey); } - /// - /// signs a message - /// - #[test] + /*#[test] fn signing_message() { let username = String::from("gamixtreize"); let crypto_pair = CryptographicSignature::new(username.clone()); @@ -160,5 +156,5 @@ mod tests { let signed_message = sign_message(&crypto_pair, &ser); println!("unsigned_message: {:?}", ser); println!("signed_message: {:?}", signed_message); - } + }*/ } diff --git a/client-network/src/lib.rs b/client-network/src/lib.rs index 86ce7cf..ccdd77a 100644 --- a/client-network/src/lib.rs +++ b/client-network/src/lib.rs @@ -4,6 +4,7 @@ mod datum_parsing; mod message_handling; mod messages_channels; mod messages_structure; +mod peers_refresh; mod registration; mod server_communication; diff --git a/client-network/src/message_handling.rs b/client-network/src/message_handling.rs index 8c3d430..50e11ca 100644 --- a/client-network/src/message_handling.rs +++ b/client-network/src/message_handling.rs @@ -4,7 +4,7 @@ use crate::{ CryptographicSignature, get_peer_key, sign_message, verify_signature, }, messages_channels::MultipleSenders, - messages_structure::{HandshakeMessage, constructMessage}, + messages_structure::construct_message, registration, }; use std::sync::{Arc, Mutex}; @@ -19,7 +19,7 @@ pub enum EventType { const ID: usize = 4; const TYPE: usize = 5; const LENGTH: usize = 7; -const EXTENSIONS: usize = 32; +const EXTENSIONS: usize = 4; const SIGNATURE: usize = 64; const PING: u8 = 0; @@ -50,8 +50,11 @@ pub fn handle_recevied_message( let message_id: [u8; 4] = recevied_message[0..4].try_into().expect("size error"); let id = i32::from_be_bytes(message_id); + parse_message(recevied_message, received_name, id, crypto_pair, cmd_tx) + //TODO + // Lock the mutex to access the HashMap - let list = messages_list.lock().unwrap(); + /*let list = messages_list.lock().unwrap(); let eventtype = list.get(&id); // Clone the enum so we can release the lock if needed match eventtype { @@ -113,7 +116,7 @@ pub fn handle_recevied_message( } print!("Message not found for ID: {}", id) } - } + }*/ } pub fn ping(received_message: Vec, socket_addr: String) {} @@ -140,9 +143,11 @@ pub fn parse_message( received_message: Vec, received_name: String, id: i32, - username: String, - crypto_pair: &CryptographicSignature + crypto_pair: &CryptographicSignature, + cmd_tx: crossbeam_channel::Sender, ) -> Option> { + let cmd_tx_clone = cmd_tx.clone(); + let id_bytes: [u8; 4] = received_message[0..ID] .try_into() .expect("Taille incorrecte"); @@ -176,35 +181,62 @@ pub fn parse_message( } _ => {} } + + // Message handling + let mut constructed_message: Option> = None; match msgtype { // PING // // envoie un OK + PING => { + constructed_message = construct_message(OK, Vec::new(), id, crypto_pair); + } // // OK // + // rien ? // si NATTRAVERSALREQUEST alors // // ERROR // // affiche un msg d'erreur - // + ERROR => { + if let Ok(err_received) = + String::from_utf8(received_message[LENGTH..(msg_length + LENGTH)].to_vec()) + { + let err_msg = format!( + "Error received from peer {} : {}", + String::from(received_name), + err_received + ); + let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg)); + } else { + let err_msg = format!( + "Error received from peer {} : N/A", + String::from(received_name), + ); + let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg)); + } + } // HELLO // // envoie une hello reply // HELLO => { - let username_size = username.len(); - let helloreply = constructMessage(msgtype, payload, &id, crypto_pair) - let hello_handshake = - HandshakeMessage::helloReply(id as u32, username_size as u16 + 4, username.clone()); - //HandshakeMessage::display(&hello_handshake); - let hello_handshake_serialized = hello_handshake.serialize(); - return Some(hello_handshake_serialized); + let mut payload = Vec::new(); + + payload.extend_from_slice(&0u32.to_be_bytes()); + payload.extend_from_slice(&crypto_pair.username.clone().as_bytes()); + + let helloreply = construct_message(HELLOREPLY, payload, id, crypto_pair); + + return helloreply; } // HELLOREPLY // - // envoie un root request + // + // ajoute a la liste des peers handshake + HELLOREPLY => {} // // ROOTREQUEST // @@ -285,4 +317,5 @@ pub fn parse_message( // envoie OK à S puis envoie un ping à S _ => return None, } + constructed_message } diff --git a/client-network/src/messages_structure.rs b/client-network/src/messages_structure.rs index f62a2da..b0cac34 100644 --- a/client-network/src/messages_structure.rs +++ b/client-network/src/messages_structure.rs @@ -6,7 +6,7 @@ use crate::{ const ID: usize = 4; const TYPE: usize = 5; const LENGTH: usize = 7; -const EXTENSIONS: usize = 32; +const EXTENSIONS: usize = 4; const SIGNATURE: usize = 64; const PING: u8 = 0; @@ -22,7 +22,7 @@ const DATUM: u8 = 132; const NATTRAVERSALREQUEST: u8 = 4; const NATTRAVERSALREQUEST2: u8 = 5; -pub fn constructMessage( +pub fn construct_message( msgtype: u8, payload: Vec, id: i32, @@ -30,204 +30,39 @@ pub fn constructMessage( ) -> Option> { let mut message = Vec::new(); - message.extend_from_slice(&id); + // ID + // type + message.extend_from_slice(&id.to_be_bytes()); + message.push(msgtype); match msgtype { HELLO | HELLOREPLY => { + // length + message.extend_from_slice(&(EXTENSIONS + payload.len()).to_be_bytes()); message.extend_from_slice(&payload); let signature = sign_message(crypto_pair, &message); message.extend_from_slice(&signature); return Some(message); } + PING | OK => { + message.extend_from_slice(&0u16.to_be_bytes()); + return Some(message); + } + ERROR | ROOTREQUEST | DATUMREQUEST => { + message.extend_from_slice(&payload.len().to_be_bytes()); + message.extend_from_slice(&payload); + return Some(message); + } + ROOTREPLY | NODATUM | DATUM | NATTRAVERSALREQUEST => { + message.extend_from_slice(&payload.len().to_be_bytes()); + message.extend_from_slice(&payload); + let signature = sign_message(crypto_pair, &message); + message.extend_from_slice(&signature); + return Some(message); + } + _ => {} } None } - -pub struct UDPMessage { - id: u32, - msg_type: u8, - length: u16, - body: Vec, - signature: Vec, -} - -pub struct HandshakeMessage { - pub id: u32, - msg_type: u8, - length: u16, - extensions: u32, - pub name: Vec, - pub signature: Vec, -} - -pub struct DatumRootRequest { - pub id: u32, - msg_type: u8, - length: u16, - hash: Vec, -} - -pub struct DatumReply { - pub id: u32, - msg_type: u8, - length: u16, - hash: Vec, - value: Vec, - signature: Vec, -} - -impl UDPMessage { - pub fn ping(id: u32) -> UDPMessage { - UDPMessage { - id: id, - msg_type: 0, - length: 0, - body: vec![0; 985], - signature: vec![0; 32], - } - } - - pub fn error(id: u32) -> UDPMessage { - UDPMessage { - id: id, - msg_type: 129, - length: 0, - body: vec![0; 985], - signature: vec![0; 32], - } - } - - pub fn parse(received_message: Vec) -> UDPMessage { - let id_bytes: [u8; 4] = received_message[0..4] - .try_into() - .expect("Taille incorrecte"); - let length_bytes: [u8; 2] = received_message[5..7] - .try_into() - .expect("Taille incorrecte"); - let msg_length = u16::from_be_bytes(length_bytes); - let name_bytes = &received_message[7..msg_length as usize + 8]; - let signature_bytes = - &received_message[msg_length as usize + 8..msg_length as usize + 9 + 32]; - UDPMessage { - id: u32::from_be_bytes(id_bytes), - msg_type: received_message[4], - length: u16::from_be_bytes(length_bytes), - body: name_bytes.to_vec(), - signature: signature_bytes.to_vec(), - } - } - - pub fn display(&self) { - println!("ID: {:?}", self.id); - println!("Message Type: {}", self.msg_type); - println!("Length: {:?}", self.length); - let good_length = usize::min(self.length as usize, 985); - println!("name: {:?}", &self.body[..good_length]); - println!("Signature: {:?}", self.signature); - } -} - -impl HandshakeMessage { - pub fn display(&self) { - println!("ID: {:?}", self.id); - println!("Message Type: {}", self.msg_type); - println!("Length: {:?}", self.length); - println!("extensions: {:?}", self.extensions); - println!("name: {:?}", &self.name[..(self.length - 4) as usize]); - println!("Signature: {:?}", self.signature); - } - pub fn hello(id: u32, length: u16, username: String) -> HandshakeMessage { - let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec(); - HandshakeMessage { - id: id, - msg_type: 1, - length: length, - extensions: 0, - name: name_vec, - signature: vec![0; 64], - } - } - - pub fn helloReply(id: u32, length: u16, username: String) -> HandshakeMessage { - let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec(); - HandshakeMessage { - id: id, - msg_type: 130, - length: length, - extensions: 0, - name: name_vec, - signature: vec![0; 64], - } - } - - pub fn serialize(&self) -> Vec { - let mut out = Vec::with_capacity(4 + 1 + 2 + 4 + self.name.len() + self.signature.len()); - - // id: u32 little-endian - out.extend_from_slice(&self.id.to_be_bytes()); - - // msg_type: u8 - out.push(self.msg_type); - - out.extend_from_slice(&self.length.to_be_bytes()); - - out.extend_from_slice(&self.extensions.to_be_bytes()); - - out.extend_from_slice(&self.name); - - out.extend_from_slice(&self.signature); - - out - } - - pub fn parse(received_message: Vec) -> HandshakeMessage { - let id_bytes: [u8; 4] = received_message[0..4] - .try_into() - .expect("Taille incorrecte"); - let length_bytes: [u8; 2] = received_message[5..7] - .try_into() - .expect("Taille incorrecte"); - let msg_length = u16::from_be_bytes(length_bytes); - let extensions_bytes: [u8; 4] = received_message[7..11] - .try_into() - .expect("Taille incorrecte"); - let name_bytes = &received_message[11..(11 + msg_length - 4) as usize]; - let signature_bytes = - &received_message[(11 + msg_length - 4) as usize..(11 + msg_length - 4 + 64) as usize]; - HandshakeMessage { - id: u32::from_be_bytes(id_bytes), - msg_type: received_message[4], - length: u16::from_be_bytes(length_bytes), - extensions: u32::from_be_bytes(extensions_bytes), - name: name_bytes.to_vec(), - signature: signature_bytes.to_vec(), - } - } -} - -#[cfg(test)] -mod tests { - // Note this useful idiom: importing names from outer (for mod tests) scope. - use super::*; - - /// creates an handshake message - #[tokio::test] - async fn creating_handshake_msg() { - let username = String::from("charlie_kirk"); - let handshake = HandshakeMessage::hello(0, 12, username); - handshake.display(); - } - - /// parses an handshake message - #[tokio::test] - async fn parse_handshakemessage() { - let username = String::from("charlie_kirk"); - let handshake = HandshakeMessage::hello(0, 12, username); - let ser = handshake.serialize(); - let parsed = HandshakeMessage::parse(ser); - handshake.display(); - parsed.display(); - } -} diff --git a/client-network/src/peers_refresh.rs b/client-network/src/peers_refresh.rs new file mode 100644 index 0000000..32ddac9 --- /dev/null +++ b/client-network/src/peers_refresh.rs @@ -0,0 +1,68 @@ +// this class consists of a thread that will re send pings every time the first element +// of the stack is at the correct unix time + +use std::{ + collections::{HashMap, VecDeque}, + net::SocketAddr, + thread, + time::{self, SystemTime}, +}; + +pub struct PeerInfo { + username: String, + ip: SocketAddr, +} + +pub struct HandshakeHistory { + time_k_hash_v: HashMap, + hash_k_peerinfo_v: HashMap, + times_to_check: VecDeque, +} + +impl HandshakeHistory { + pub fn new() -> HandshakeHistory { + HandshakeHistory { + time_k_hash_v: HashMap::new(), + hash_k_peerinfo_v: HashMap::new(), + times_to_check: VecDeque::new(), + } + } + + pub fn update_handshake(&self) { + thread::spawn(move || { + // adds 10 seconds in the queue every 10 seconds + self.times_to_check.insert(index, value); + }); + } + + pub fn add_new_handshake(&mut self, hash: u64, username: String, ip: SocketAddr) { + let current_time: u64 = SystemTime::now() + .duration_since(time::UNIX_EPOCH) + .expect("system time before UNIX EPOCH") + .as_secs(); + println!("time:{}", current_time); + self.time_k_hash_v.insert(current_time, hash); + self.hash_k_peerinfo_v + .insert(hash, PeerInfo { username, ip }); + } +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr}; + + use super::*; + + /// + /// creates a cryptographic signature + /// + #[test] + fn creating_cryptographic_signature() { + let mut hh = HandshakeHistory::new(); + hh.add_new_handshake( + 20, + "putain".to_string(), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1), + ); + } +} diff --git a/client-network/src/registration.rs b/client-network/src/registration.rs index 52f3198..bbbc57b 100644 --- a/client-network/src/registration.rs +++ b/client-network/src/registration.rs @@ -4,7 +4,6 @@ use getrandom::Error; use crate::cryptographic_signature::{CryptographicSignature, formatPubKey, sign_message}; use crate::message_handling::EventType; use crate::messages_channels::{Message, MultipleSenders}; -use crate::messages_structure::{HandshakeMessage, UDPMessage}; use std::collections::HashMap; use std::net::SocketAddr; use std::net::UdpSocket; @@ -98,6 +97,7 @@ pub fn register_ip_addresses( socket.recv_from(&mut buf).expect("receive failed"); let hello_handshake_received = UDPMessage::parse(buf.to_vec()); hello_handshake_received.display();*/ + //TODO } #[cfg(test)]