2 Commits

Author SHA1 Message Date
98fcc1a0b2 wip handling root request 2026-01-13 02:32:48 +01:00
8e279d9e24 wip datum 2026-01-11 22:12:08 +01:00
9 changed files with 466 additions and 225 deletions

View File

@@ -49,11 +49,11 @@ pub struct P2PClientApp {
impl P2PClientApp { impl P2PClientApp {
pub fn new(cmd_tx: Sender<NetworkCommand>, event_rx: Receiver<NetworkEvent>) -> Self { pub fn new(cmd_tx: Sender<NetworkCommand>, event_rx: Receiver<NetworkEvent>) -> Self {
let (root_hash, tree_content) = MerkleNode::generate_base_tree(); //let (root_hash, tree_content) = MerkleNode::generate_base_tree();
let mut loaded_fs = HashMap::new(); let mut loaded_fs = HashMap::new();
let tree = MerkleTree::new(tree_content, root_hash); //let tree = MerkleTree::new(tree_content, root_hash);
loaded_fs.insert("bob".to_string(), tree); //loaded_fs.insert("bob".to_string(), tree);
Self { Self {
remaining: std::time::Duration::from_secs(0), remaining: std::time::Duration::from_secs(0),
@@ -123,23 +123,24 @@ impl eframe::App for P2PClientApp {
NetworkEvent::FileTreeReceived(_peer_id, _) => { NetworkEvent::FileTreeReceived(_peer_id, _) => {
todo!(); todo!();
// self.loaded_tree_nodes.insert(_peer_id, tree); //self.loaded_tree_nodes.insert(_peer_id, tree);
self.status_message = "🔄 File tree updated successfully.".to_string(); //self.status_message = "🔄 File tree updated successfully.".to_string();
} }
NetworkEvent::FileTreeRootReceived(peer_id, root_hash) => { NetworkEvent::FileTreeRootReceived(peer_id, root_hash) => {
todo!(); // todo!();
// self.status_message = format!("🔄 Received Merkle Root from {}: {}", peer_id, &root_hash[..8]); self.status_message = format!(
// "🔄 Received Merkle Root from {}: {}",
// peer_id,
// self.active_peer_id = Some(peer_id.clone()); &root_hash[..8]
// );
//
// // Request the content of the root directory immediately //self.active_peer_id = Some(peer_id.clone());
// let _ = self.network_cmd_tx.send(NetworkCommand::RequestDirectoryContent(
// peer_id, // Request the content of the root directory immediately
// root_hash, /*let _ = self
// )); .network_cmd_tx
.send(NetworkCommand::RequestDirectoryContent(peer_id, root_hash));*/
} }
NetworkEvent::Connected(ip) => { NetworkEvent::Connected(ip) => {
self.server_status = ServerStatus::Connected; self.server_status = ServerStatus::Connected;
@@ -360,11 +361,11 @@ impl eframe::App for P2PClientApp {
.loaded_fs .loaded_fs
.contains_key(self.active_peer.as_ref().unwrap()) .contains_key(self.active_peer.as_ref().unwrap())
{ {
todo!(); //todo!();
// let _ = self.network_cmd_tx.send(NetworkCommand::RequestDirectoryContent( let _ = self.network_cmd_tx.send(NetworkCommand::Discover(
// peer.clone(), peer.clone(),
// peer.clone(), "root".to_string(),
// )); ));
} }
} }
selectable.context_menu(|ui| { selectable.context_menu(|ui| {
@@ -508,7 +509,13 @@ impl P2PClientApp {
entry.content_hash, entry.content_hash,
tree, tree,
depth + 1, depth + 1,
Some(entry.filename), Some(
entry
.filename
.as_slice()
.try_into()
.expect("incorrect size"),
),
); );
} }
}); });
@@ -529,7 +536,7 @@ impl P2PClientApp {
.enabled(true) .enabled(true)
.show(ui, |ui| { .show(ui, |ui| {
for child in &node.children_hashes { for child in &node.children_hashes {
self.draw_file_node(ui, child.clone(), tree, depth + 1, None); self.draw_file_node(ui, child.content_hash, tree, depth + 1, None);
} }
}); });
} }

View File

@@ -80,7 +80,7 @@ impl MerkleTree {
} }
} }
fn generate_random_file_node( /*fn generate_random_file_node(
storage: &mut HashMap<NodeHash, MerkleNode>, storage: &mut HashMap<NodeHash, MerkleNode>,
) -> Result<NodeHash, String> { ) -> Result<NodeHash, String> {
let mut rng = rng(); let mut rng = rng();
@@ -110,9 +110,9 @@ fn generate_random_file_node(
storage.insert(hash, node); storage.insert(hash, node);
Ok(hash) Ok(hash)
} }
} }*/
fn generate_random_directory_node( /*fn generate_random_directory_node(
depth: u32, depth: u32,
max_depth: u32, max_depth: u32,
storage: &mut HashMap<NodeHash, MerkleNode>, storage: &mut HashMap<NodeHash, MerkleNode>,
@@ -172,7 +172,7 @@ fn generate_random_directory_node(
storage.insert(hash, node); storage.insert(hash, node);
Ok(hash) Ok(hash)
} }
} }*/
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ChunkNode { pub struct ChunkNode {
@@ -208,7 +208,7 @@ impl ChunkNode {
// Helper struct // Helper struct
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct DirectoryEntry { pub struct DirectoryEntry {
pub filename: [u8; FILENAME_HASH_SIZE], pub filename: Vec<u8>,
pub content_hash: NodeHash, pub content_hash: NodeHash,
} }
@@ -240,7 +240,7 @@ pub struct BigNode {
} }
impl BigNode { impl BigNode {
pub fn new(children_hashes: Vec<NodeHash>) -> Result<Self, String> { /*pub fn new(children_hashes: Vec<NodeHash>) -> Result<Self, String> {
let n = children_hashes.len(); let n = children_hashes.len();
if n < MIN_BIG_CHILDREN || n > MAX_BIG_CHILDREN { if n < MIN_BIG_CHILDREN || n > MAX_BIG_CHILDREN {
return Err(format!( return Err(format!(
@@ -249,16 +249,17 @@ impl BigNode {
)); ));
} }
Ok(BigNode { children_hashes }) Ok(BigNode { children_hashes })
} }*/
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct BigDirectoryNode { pub struct BigDirectoryNode {
pub children_hashes: Vec<NodeHash>, //pub children_hashes: Vec<NodeHash>,
pub children_hashes: Vec<DirectoryEntry>,
} }
impl BigDirectoryNode { impl BigDirectoryNode {
pub fn new(children_hashes: Vec<NodeHash>) -> Result<Self, String> { /*pub fn new(children_hashes: Vec<NodeHash>) -> Result<Self, String> {
let n = children_hashes.len(); let n = children_hashes.len();
if n < MIN_BIG_CHILDREN || n > MAX_BIG_CHILDREN { if n < MIN_BIG_CHILDREN || n > MAX_BIG_CHILDREN {
return Err(format!( return Err(format!(
@@ -267,6 +268,14 @@ impl BigDirectoryNode {
)); ));
} }
Ok(BigDirectoryNode { children_hashes }) Ok(BigDirectoryNode { children_hashes })
}*/
pub fn new(entries: Vec<DirectoryEntry>) -> Result<Self, String> {
if entries.len() > MAX_DIRECTORY_ENTRIES {
return Err(format!("Directory exceeds {} bytes", entries.len()));
}
Ok(BigDirectoryNode {
children_hashes: entries,
})
} }
} }
@@ -301,14 +310,14 @@ impl MerkleNode {
} }
MerkleNode::BigDirectory(node) => { MerkleNode::BigDirectory(node) => {
for hash in &node.children_hashes { for hash in &node.children_hashes {
bytes.extend_from_slice(hash); bytes.extend_from_slice(&hash.content_hash);
} }
} }
} }
bytes bytes
} }
pub fn generate_random_tree( /*pub fn generate_random_tree(
max_depth: u32, max_depth: u32,
) -> Result<(NodeHash, HashMap<NodeHash, MerkleNode>), String> { ) -> Result<(NodeHash, HashMap<NodeHash, MerkleNode>), String> {
let mut storage = HashMap::new(); let mut storage = HashMap::new();
@@ -317,9 +326,9 @@ impl MerkleNode {
let root_hash = generate_random_directory_node(0, max_depth, &mut storage)?; let root_hash = generate_random_directory_node(0, max_depth, &mut storage)?;
Ok((root_hash, storage)) Ok((root_hash, storage))
} }*/
pub fn generate_base_tree() -> (NodeHash, HashMap<NodeHash, MerkleNode>) { /*pub fn generate_base_tree() -> (NodeHash, HashMap<NodeHash, MerkleNode>) {
let mut res = HashMap::new(); let mut res = HashMap::new();
let node1 = MerkleNode::Chunk(ChunkNode::new_random()); let node1 = MerkleNode::Chunk(ChunkNode::new_random());
@@ -369,5 +378,5 @@ impl MerkleNode {
res.insert(root_hash, root); res.insert(root_hash, root);
(root_hash, res) (root_hash, res)
} }*/
} }

View File

@@ -1 +1,96 @@
fn parse_received_datum(recevied_datum: Vec<u8>) {} use crate::{BigDirectoryNode, DirectoryEntry, DirectoryNode, MerkleNode, MerkleTree, NodeHash};
use sha2::{Digest, Sha256};
const CHUNK: u8 = 0;
const DIRECTORY: u8 = 1;
const BIG: u8 = 2;
const BIGDIRECTORY: u8 = 3;
fn parse_received_datum(recevied_datum: Vec<u8>, datum_length: usize, mut tree: MerkleTree) {
if datum_length > recevied_datum.len() {
return;
}
if datum_length < 32 + 64 {
return;
}
let hash_name: [u8; 32] = recevied_datum[..32].try_into().expect("error");
let sigstart = datum_length - 64;
let value = &recevied_datum[32..sigstart];
let value_slice = value.to_vec();
let signature: [u8; 32] = recevied_datum[sigstart..datum_length]
.try_into()
.expect("Taille incorrecte");
let datum_type = value_slice[0];
match datum_type {
CHUNK => {
tree.data.insert(
hash_name,
MerkleNode::Chunk(crate::ChunkNode { data: value_slice }),
);
}
DIRECTORY => {
let nb_entries = value_slice[1];
let mut dir_entries = Vec::new();
let mut offset = 1 as usize;
for i in 0..nb_entries {
offset = (offset as u8 + 64 * i) as usize;
let name = &recevied_datum[offset..offset + 32];
let mut hash = [0u8; 32];
hash.copy_from_slice(&recevied_datum[offset + 32..offset + 64]);
// envoyer un datum request
dir_entries.push(DirectoryEntry {
filename: name.to_vec(),
content_hash: hash,
});
}
let current = DirectoryNode::new(dir_entries);
match current {
Ok(current_node) => {
tree.data
.insert(hash_name, MerkleNode::Directory(current_node));
}
Err(e) => {
println!("{}", e);
}
}
}
BIG => {
let chlidren: Vec<NodeHash> = Vec::new();
tree.data.insert(
hash_name,
MerkleNode::Big(crate::BigNode {
children_hashes: chlidren,
}),
);
}
BIGDIRECTORY => {
let nb_entries = value_slice[1];
let mut dir_entries = Vec::new();
let mut offset = 1 as usize;
for i in 0..nb_entries {
offset = (offset as u8 + 64 * i) as usize;
let name = &recevied_datum[offset..offset + 32];
let mut hash = [0u8; 32];
hash.copy_from_slice(&recevied_datum[offset + 32..offset + 64]);
// envoyer un datum request
dir_entries.push(DirectoryEntry {
filename: name.to_vec(),
content_hash: hash,
});
}
let current = BigDirectoryNode::new(dir_entries);
match current {
Ok(current_node) => {
tree.data
.insert(hash_name, MerkleNode::BigDirectory(current_node));
}
Err(e) => {
println!("{}", e);
}
}
}
_ => {}
}
}

View File

@@ -12,8 +12,10 @@ use crate::{
cryptographic_signature::CryptographicSignature, cryptographic_signature::CryptographicSignature,
message_handling::EventType, message_handling::EventType,
messages_channels::{MultipleSenders, start_receving_thread}, messages_channels::{MultipleSenders, start_receving_thread},
messages_structure::construct_message,
peers_refresh::HandshakeHistory,
registration::{ registration::{
get_socket_address, parse_addresses, register_ip_addresses, register_with_the_server, get_socket_address, parse_addresses, perform_handshake, register_with_the_server,
}, },
server_communication::{generate_id, get_peer_list}, server_communication::{generate_id, get_peer_list},
}; };
@@ -33,6 +35,7 @@ pub struct P2PSharedData {
shared_messageslist: Arc<Mutex<HashMap<i32, EventType>>>, shared_messageslist: Arc<Mutex<HashMap<i32, EventType>>>,
shared_senders: Arc<MultipleSenders>, shared_senders: Arc<MultipleSenders>,
server_name: Arc<Mutex<String>>, server_name: Arc<Mutex<String>>,
handshake_peers: Arc<HandshakeHistory>,
} }
impl P2PSharedData { impl P2PSharedData {
@@ -51,12 +54,14 @@ impl P2PSharedData {
let senders = MultipleSenders::new(1, &shared_socket, cmd_tx); let senders = MultipleSenders::new(1, &shared_socket, cmd_tx);
let shared_senders = Arc::new(senders); let shared_senders = Arc::new(senders);
let server_name = Arc::new(Mutex::new("".to_string())); let server_name = Arc::new(Mutex::new("".to_string()));
let handhsake_peers = Arc::new(HandshakeHistory::new());
Ok(P2PSharedData { Ok(P2PSharedData {
shared_socket: shared_socket, shared_socket: shared_socket,
shared_cryptopair: shared_cryptopair, shared_cryptopair: shared_cryptopair,
shared_messageslist: shared_messageslist, shared_messageslist: shared_messageslist,
shared_senders: shared_senders, shared_senders: shared_senders,
server_name: server_name, server_name: server_name,
handshake_peers: handhsake_peers,
}) })
} }
pub fn socket(&self) -> Arc<UdpSocket> { pub fn socket(&self) -> Arc<UdpSocket> {
@@ -87,6 +92,9 @@ impl P2PSharedData {
pub fn cryptopair_ref(&self) -> &CryptographicSignature { pub fn cryptopair_ref(&self) -> &CryptographicSignature {
&*self.shared_cryptopair &*self.shared_cryptopair
} }
pub fn handshake_ref(&self) -> &HandshakeHistory {
&*self.handshake_peers
}
pub fn messages_list_ref(&self) -> &Mutex<HashMap<i32, EventType>> { pub fn messages_list_ref(&self) -> &Mutex<HashMap<i32, EventType>> {
&*self.shared_messageslist &*self.shared_messageslist
@@ -115,6 +123,8 @@ pub enum NetworkCommand {
RequestChunk(String, String), RequestChunk(String, String),
Disconnect(), Disconnect(),
ResetServerPeer(), ResetServerPeer(),
Discover(String, String),
GetChildren(String, String),
// ... // ...
} }
@@ -173,61 +183,11 @@ pub fn start_p2p_executor(
match cmd { match cmd {
NetworkCommand::ServerHandshake(username, ip) => { NetworkCommand::ServerHandshake(username, ip) => {
if let Some(sd) = shared_data.as_ref() { if let Some(sd) = shared_data.as_ref() {
println!("username:{}, ip:{}", username, ip); start_receving_thread(
let server_addr_query = get_socket_address(username.clone(), ip); sd,
event_tx.clone(), //
match server_addr_query.await { );
Ok(sockaddr_bytes) => { perform_handshake(&sd, username, ip, event_tx.clone());
match String::from_utf8(sockaddr_bytes.to_vec()) {
Ok(s) => {
let addresses = parse_addresses(&s);
if let Some(first) = addresses.first() {
sd.set_servername(username);
// first: &SocketAddr
start_receving_thread(
sd,
*first, // copie le SocketAddr (implémente Copy pour SocketAddr)
event_tx.clone(), //
);
register_ip_addresses(
sd.cryptopair_ref(),
first.to_string(),
sd.senders_ref(),
sd.messages_list_ref(),
generate_id(),
);
//let res = event_tx
// .send(NetworkEvent::());
} else {
//let res = event_tx.send(NetworkEvent::Error());
let err_msg = format!(
"no valid socket addresses found in: {}",
s
)
.to_string();
let res =
event_tx.send(NetworkEvent::Error(err_msg));
}
}
Err(e) => {
//let res = event_tx.send(NetworkEvent::Error());
let err_msg = format!(
"invalid UTF-8 in socket address bytes: {}",
e
)
.to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg));
}
}
}
Err(e) => {
let err_msg =
format!("failed to retreive socket address: {}", e)
.to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg));
}
}
} }
} }
NetworkCommand::ConnectPeer(addr) => { NetworkCommand::ConnectPeer(addr) => {
@@ -240,6 +200,12 @@ pub fn start_p2p_executor(
NetworkCommand::RequestFileTree(_) => { NetworkCommand::RequestFileTree(_) => {
println!("[Network] RequestFileTree() called"); println!("[Network] RequestFileTree() called");
} }
NetworkCommand::Discover(username, hash) => {
// envoie un handshake au peer, puis un root request
}
NetworkCommand::GetChildren(username, hash) => {
// envoie un datum request au peer
}
NetworkCommand::RequestDirectoryContent(_, _) => { NetworkCommand::RequestDirectoryContent(_, _) => {
println!("[Network] RequestDirectoryContent() called"); println!("[Network] RequestDirectoryContent() called");
} }

View File

@@ -5,7 +5,9 @@ use crate::{
}, },
messages_channels::MultipleSenders, messages_channels::MultipleSenders,
messages_structure::construct_message, messages_structure::construct_message,
peers_refresh::HandshakeHistory,
registration, registration,
server_communication::generate_id,
}; };
use std::{collections::HashMap, net::SocketAddr}; use std::{collections::HashMap, net::SocketAddr};
use std::{ use std::{
@@ -14,9 +16,7 @@ use std::{
}; };
pub enum EventType { pub enum EventType {
ServerHelloReply, SendRootRequest,
PeerHelloReply,
PeerHello,
} }
const ID: usize = 4; const ID: usize = 4;
@@ -42,11 +42,12 @@ pub fn handle_recevied_message(
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>, messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
recevied_message: &Vec<u8>, recevied_message: &Vec<u8>,
crypto_pair: &CryptographicSignature, crypto_pair: &CryptographicSignature,
socket_addr: &SocketAddr, //socket_addr: &SocketAddr,
senders: &MultipleSenders, senders: &MultipleSenders,
server_name: &String, server_name: &String,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>, cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
ip: SocketAddr, ip: SocketAddr,
handshake_history: HandshakeHistory,
) { ) {
if recevied_message.len() < 4 { if recevied_message.len() < 4 {
return; return;
@@ -70,13 +71,27 @@ pub fn handle_recevied_message(
} }
} }
let resp = parse_message(recevied_message.to_vec(), id, crypto_pair, cmd_tx, ip); let resp = parse_message(
recevied_message.to_vec(),
id,
crypto_pair,
cmd_tx,
ip,
messages_list,
handshake_history,
);
match resp { match resp {
None => {} None => {}
Some(resp_msg) => { Some(resp_msg) => {
println!("msg_sent:{:?}", resp_msg); println!("msg_sent:{:?}", resp_msg);
senders.send_via(0, resp_msg, ip.to_string(), is_resp_to_server_handshake); senders.send_via(
0,
resp_msg,
ip.to_string(),
is_resp_to_server_handshake,
messages_list,
);
} }
} }
@@ -152,6 +167,8 @@ pub fn parse_message(
crypto_pair: &CryptographicSignature, crypto_pair: &CryptographicSignature,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>, cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
ip: SocketAddr, ip: SocketAddr,
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
handhsake_history: HandshakeHistory,
) -> Option<Vec<u8>> { ) -> Option<Vec<u8>> {
let cmd_tx_clone = cmd_tx.clone(); let cmd_tx_clone = cmd_tx.clone();
@@ -166,7 +183,6 @@ pub fn parse_message(
.expect("Taille incorrecte"); .expect("Taille incorrecte");
let msg_length = u16::from_be_bytes(length_bytes) as usize; let msg_length = u16::from_be_bytes(length_bytes) as usize;
// verify signature // verify signature
match msgtype { match msgtype {
HELLO | HELLOREPLY | ROOTREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => { HELLO | HELLOREPLY | ROOTREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => {
@@ -176,10 +192,13 @@ pub fn parse_message(
let received_username = String::from_utf8(received_name.to_vec()); let received_username = String::from_utf8(received_name.to_vec());
match received_username { match received_username {
Ok(username) => { Ok(username) => {
let peer_pubkey = tokio::runtime::Runtime::new() let peer_pubkey = match handhsake_history.get_peer_info_username(username) {
.unwrap() Some(peerinfo) => peerinfo.pubkey,
.block_on(get_peer_key(&username)) _ => tokio::runtime::Runtime::new()
.expect("failed to retrieve public key"); .unwrap()
.block_on(get_peer_key(&username))
.expect("failed to retrieve public key"),
};
let signature: [u8; SIGNATURE] = received_message let signature: [u8; SIGNATURE] = received_message
[LENGTH + msg_length..LENGTH + msg_length + SIGNATURE] [LENGTH + msg_length..LENGTH + msg_length + SIGNATURE]
.try_into() .try_into()
@@ -248,7 +267,30 @@ pub fn parse_message(
// //
// //
// ajoute a la liste des peers handshake // ajoute a la liste des peers handshake
HELLOREPLY => {} HELLOREPLY => {
// ajoute a la liste des peers handshake
handhsake_history.add_new_handshake(hash, username, ip);
// verifie s'il faut renvoyer un root request
let guard = messages_list.lock().expect("Échec du verrouillage");
let res = guard.get(&id);
match res {
Some(ev) => {
match ev {
EventType::SendRootRequest => {
// envoyer la root request
let rootrequest = construct_message(
ROOTREQUEST,
Vec::new(),
generate_id(),
crypto_pair,
);
return rootrequest;
}
}
}
None => {}
}
}
// //
// ROOTREQUEST // ROOTREQUEST
// //
@@ -256,7 +298,20 @@ pub fn parse_message(
// //
// ROOTREPLY // ROOTREPLY
// //
// envoie un datum request ROOTREPLY => {
// recuperer le pseudo du peers ayant repondu
// envoyer le hash a la gui
let received_hash = String::from_utf8(received_message[LENGTH..(32 + LENGTH)].to_vec());
match received_hash {
Ok(hash) => {
cmd_tx_clone.send(NetworkEvent::FileTreeRootReceived());
}
Err(e) => {
println!("{}", e);
}
}
}
// //
// DATUMREQUEST // DATUMREQUEST
// //
@@ -328,6 +383,6 @@ pub fn parse_message(
// //
// envoie OK à S puis envoie un ping à S // envoie OK à S puis envoie un ping à S
_ => return None, _ => return None,
} };
constructed_message constructed_message
} }

View File

@@ -2,6 +2,7 @@ use crate::P2PSharedData;
use crate::cryptographic_signature::CryptographicSignature; use crate::cryptographic_signature::CryptographicSignature;
use crate::message_handling::EventType; use crate::message_handling::EventType;
use crate::message_handling::handle_recevied_message; use crate::message_handling::handle_recevied_message;
use crate::peers_refresh::HandshakeHistory;
use std::collections::HashMap; use std::collections::HashMap;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::net::UdpSocket; use std::net::UdpSocket;
@@ -21,9 +22,9 @@ pub struct MultipleSenders {
} }
pub struct Message { pub struct Message {
payload: Vec<u8>, pub payload: Vec<u8>,
address: String, pub address: String,
is_resp_to_server_handshake: bool, pub is_resp_to_server_handshake: bool,
} }
struct RetryMessage { struct RetryMessage {
@@ -205,85 +206,90 @@ impl MultipleSenders {
data: Vec<u8>, data: Vec<u8>,
remote_addr: String, remote_addr: String,
is_resp_to_server_handshake: bool, is_resp_to_server_handshake: bool,
messages_list: &Mutex<HashMap<i32, EventType>>,
) { ) {
println!( println!(
"is_resp_to_server_handshake {}", "is_resp_to_server_handshake {}",
is_resp_to_server_handshake is_resp_to_server_handshake
); );
let msg_to_send = Message {
payload: data.clone(),
address: remote_addr,
is_resp_to_server_handshake,
};
if let Some(sender) = self.senders.get(channel_idx) { if let Some(sender) = self.senders.get(channel_idx) {
let _ = sender.send(Message { let _ = sender.send(msg_to_send);
payload: data, let mut guard = messages_list.lock().expect("Échec du verrouillage");
address: remote_addr, let id = i32::from_be_bytes(data[..4].try_into().unwrap());
is_resp_to_server_handshake, guard.insert(id, EventType::SendRootRequest);
});
} }
} }
}
/*pub fn start_receving_thread( /*pub fn start_receving_thread(
socket: &Arc<UdpSocket>, socket: &Arc<UdpSocket>,
messages_list: &Arc<HashMap<i32, EventType>>, messages_list: &Arc<HashMap<i32, EventType>>,
crypto_pair: &Arc<CryptographicSignature>, crypto_pair: &Arc<CryptographicSignature>,
socket_addr: SocketAddr, socket_addr: SocketAddr,
senders: &Arc<MultipleSenders>, senders: &Arc<MultipleSenders>,
) { ) {
let sock_clone = Arc::clone(socket); let sock_clone = Arc::clone(socket);
let cryptopair_clone = Arc::clone(crypto_pair); let cryptopair_clone = Arc::clone(crypto_pair);
let senders_clone = Arc::clone(senders); let senders_clone = Arc::clone(senders);
let messages_clone = Arc::clone(messages_list); let messages_clone = Arc::clone(messages_list);
thread::spawn(move || { thread::spawn(move || {
let mut buf = [0u8; 1024]; let mut buf = [0u8; 1024];
loop { loop {
match sock_clone.recv_from(&mut buf) { match sock_clone.recv_from(&mut buf) {
Ok((amt, src)) => { Ok((amt, src)) => {
handle_recevied_message( handle_recevied_message(
&messages_clone, &messages_clone,
&buf.to_vec(), &buf.to_vec(),
&cryptopair_clone, &cryptopair_clone,
&socket_addr, &socket_addr,
&senders_clone, &senders_clone,
); );
println!("Reçu {} octets de {}: {:?}", amt, src, &buf[..amt]); println!("Reçu {} octets de {}: {:?}", amt, src, &buf[..amt]);
}
Err(e) => eprintln!("Erreur de réception: {}", e),
} }
Err(e) => eprintln!("Erreur de réception: {}", e),
} }
} });
}); }*/
}*/
pub fn start_receving_thread( pub fn start_receving_thread(
shared_data: &P2PSharedData, shared_data: &P2PSharedData,
socket_addr: SocketAddr, cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
cmd_tx: crossbeam_channel::Sender<NetworkEvent>, ) {
) { let sock_clone = shared_data.socket();
let sock_clone = shared_data.socket(); let cryptopair_clone = shared_data.cryptopair();
let cryptopair_clone = shared_data.cryptopair(); let senders_clone = shared_data.senders();
let senders_clone = shared_data.senders(); let messages_clone = shared_data.messages_list();
let messages_clone = shared_data.messages_list(); let servername_clone = shared_data.servername();
let servername_clone = shared_data.servername(); let handshake_history = HandshakeHistory::new();
thread::spawn(move || { thread::spawn(move || {
let mut buf = [0u8; 1024]; let mut buf = [0u8; 1024];
loop { loop {
match sock_clone.recv_from(&mut buf) { match sock_clone.recv_from(&mut buf) {
Ok((amt, src)) => { Ok((amt, src)) => {
let received_data = buf[..amt].to_vec(); let received_data = buf[..amt].to_vec();
println!("Reçu {} octets de {}: {:?}", amt, src, received_data); println!("Reçu {} octets de {}: {:?}", amt, src, received_data);
handle_recevied_message( handle_recevied_message(
&messages_clone, &messages_clone,
&received_data, &received_data,
&cryptopair_clone, &cryptopair_clone,
&socket_addr, &senders_clone,
&senders_clone, &servername_clone,
&servername_clone, cmd_tx.clone(),
cmd_tx.clone(), src,
src, handshake_history,
); );
}
Err(e) => eprintln!("Erreur de réception: {}", e),
} }
Err(e) => eprintln!("Erreur de réception: {}", e),
} }
} });
}); }
} }

View File

@@ -14,7 +14,7 @@ const OK: u8 = 128;
const ERROR: u8 = 129; const ERROR: u8 = 129;
const HELLO: u8 = 1; const HELLO: u8 = 1;
const HELLOREPLY: u8 = 130; const HELLOREPLY: u8 = 130;
const ROOTREQUEST: u8 = 2; pub const ROOTREQUEST: u8 = 2;
const ROOTREPLY: u8 = 131; const ROOTREPLY: u8 = 131;
const DATUMREQUEST: u8 = 3; const DATUMREQUEST: u8 = 3;
const NODATUM: u8 = 133; const NODATUM: u8 = 133;
@@ -46,11 +46,11 @@ pub fn construct_message(
let signature = sign_message(crypto_pair, &message); let signature = sign_message(crypto_pair, &message);
return Some(signature); return Some(signature);
} }
PING | OK => { PING | OK | ROOTREQUEST => {
message.extend_from_slice(&0u16.to_be_bytes()); message.extend_from_slice(&0u16.to_be_bytes());
return Some(message); return Some(message);
} }
ERROR | ROOTREQUEST | DATUMREQUEST => { ERROR | DATUMREQUEST => {
message.extend_from_slice(&payload.len().to_be_bytes()); message.extend_from_slice(&payload.len().to_be_bytes());
message.extend_from_slice(&payload); message.extend_from_slice(&payload);
return Some(message); return Some(message);

View File

@@ -11,54 +11,113 @@ use std::{
time::{self, Duration, SystemTime}, time::{self, Duration, SystemTime},
}; };
use crate::NetworkEvent;
use crate::{
P2PSharedData, construct_message, generate_id, messages_structure,
registration::perform_handshake,
};
use crossbeam_channel::{Receiver, Sender};
use p256::ecdsa::VerifyingKey;
#[derive(Debug, Clone)]
pub struct PeerInfo { pub struct PeerInfo {
username: String, username: String,
ip: SocketAddr, pub pubkey: VerifyingKey,
pub ip: SocketAddr,
} }
pub struct HandshakeHistory { pub struct HandshakeHistory {
time_k_ip_v: HashMap<u64, u64>, //time_k_ip_v: HashMap<u64, u64>,
ip_k_peerinfo_v: HashMap<u64, PeerInfo>, username_k_peerinfo_v: HashMap<String, PeerInfo>,
ip_k_peerinfo_v: HashMap<String, PeerInfo>,
} }
impl HandshakeHistory { impl HandshakeHistory {
pub fn new() -> HandshakeHistory { pub fn new() -> HandshakeHistory {
HandshakeHistory { HandshakeHistory {
time_k_ip_v: HashMap::new(), //time_k_ip_v: HashMap::new(),
//ip_k_peerinfo_v: HashMap::new(),
username_k_peerinfo_v: HashMap::new(),
ip_k_peerinfo_v: HashMap::new(), ip_k_peerinfo_v: HashMap::new(),
} }
} }
pub fn update_handshake(&mut self) { /*pub fn update_handshake(&self) {
let hashmap_shared = Arc::new(self.username_k_peerinfo_v);
thread::spawn(move || { thread::spawn(move || {
let mut times_to_check = VecDeque::new(); let selfhashmap = hashmap_shared.clone();
let current_time: u64 = SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.expect("system time before UNIX EPOCH")
.add(Duration::from_secs(10))
.as_secs();
// adds 10 seconds in the queue every 10 seconds
loop { loop {
let mut child = Command::new("sleep").arg("9").spawn().unwrap(); for peer in selfhashmap.keys() {
let _result = child.wait().unwrap(); let peer_ip = selfhashmap.get(peer);
for n in 0..9 { // send ping
// push 9 successive seconds
times_to_check.push_back(current_time + n);
// gestion d'erreur si verrou mort
} }
let mut child = Command::new("sleep").arg("10").spawn().unwrap();
let _result = child.wait().unwrap();
}
});
}*/
pub fn get_peer_info_username(&self, username: String) -> Option<&PeerInfo> {
self.username_k_peerinfo_v.get(&username).clone()
}
pub fn get_peer_info_ip(&self, ip: String) -> Option<&PeerInfo> {
self.ip_k_peerinfo_v.get(&ip).clone()
}
pub fn update_handshake(&self) {
// clone the map so we own it (cheap if PeerInfo is Clone)
let map_clone: Arc<HashMap<String, PeerInfo>> =
Arc::new(self.username_k_peerinfo_v.clone());
//let map_ip_clone: Arc<HashMap<String, PeerInfo>> = Arc::new(self.ip_k_peerinfo_v.clone());
let map_for_thread = Arc::clone(&map_clone);
thread::spawn(move || {
loop {
// Arc<HashMap<..>> derefs to &HashMap so these reads work
for (peer, peerinfo) in map_for_thread.iter() {
// send ping to peerinfo
}
thread::sleep(Duration::from_secs(10));
} }
}); });
} }
pub fn add_new_handshake(&mut self, hash: u64, username: String, ip: SocketAddr) { pub fn add_new_handshake(&mut self, hash: VerifyingKey, username: String, ip: SocketAddr) {
let current_time: u64 = SystemTime::now() let peerinfo = PeerInfo {
.duration_since(time::UNIX_EPOCH) username: username.clone(),
.expect("system time before UNIX EPOCH") pubkey: hash,
.as_secs(); ip,
println!("time:{}", current_time); };
/*self.time_k_hash_v.insert(current_time, hash); self.username_k_peerinfo_v
self.hash_k_peerinfo_v .insert(username, peerinfo.clone());
.insert(hash, PeerInfo { username, ip });*/ self.ip_k_peerinfo_v
.insert(ip.to_string(), peerinfo.clone());
}
}
pub fn perform_discover(
username: String,
hash: String,
sd: &P2PSharedData,
server_ip: String,
event_tx: Sender<NetworkEvent>,
) {
// first, sends handshake
if hash == "root" {
perform_handshake(sd, username, server_ip, event_tx);
if let Some(data) = construct_message(
messages_structure::ROOTREQUEST,
Vec::new(),
generate_id(),
sd.cryptopair_ref(),
) {
if let Some(peerinfo) = sd.handshake_ref() {
sd.senders_ref()
.send_via(0, data, peerinfo.ip.to_string(), false);
}
}
} else {
// envoyer un datum request
} }
} }
@@ -68,10 +127,7 @@ mod tests {
use super::*; use super::*;
/// /*#[test]
/// creates a cryptographic signature
///
#[test]
fn creating_cryptographic_signature() { fn creating_cryptographic_signature() {
let mut hh = HandshakeHistory::new(); let mut hh = HandshakeHistory::new();
hh.add_new_handshake( hh.add_new_handshake(
@@ -79,5 +135,5 @@ mod tests {
"putain".to_string(), "putain".to_string(),
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1),
); );
} }*/
} }

View File

@@ -1,10 +1,14 @@
use bytes::Bytes; use bytes::Bytes;
use getrandom::Error; use getrandom::Error;
use crate::NetworkEvent;
use crate::P2PSharedData;
use crate::cryptographic_signature::{CryptographicSignature, formatPubKey, sign_message}; use crate::cryptographic_signature::{CryptographicSignature, formatPubKey, sign_message};
use crate::message_handling::EventType; use crate::message_handling::EventType;
use crate::messages_channels::{Message, MultipleSenders}; use crate::messages_channels::{Message, MultipleSenders};
use crate::messages_structure::construct_message; use crate::messages_structure::construct_message;
use crate::server_communication::generate_id;
use crossbeam_channel::{Receiver, Sender};
use std::collections::HashMap; use std::collections::HashMap;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::net::UdpSocket; use std::net::UdpSocket;
@@ -66,23 +70,66 @@ pub fn parse_addresses(input: &String) -> Vec<SocketAddr> {
/// ///
/// registers the IP addresses by sending a Hello request to the server. /// registers the IP addresses by sending a Hello request to the server.
/// ///
pub fn register_ip_addresses( pub async fn perform_handshake(
crypto_pair: &CryptographicSignature, sd: &P2PSharedData,
server_uri: String, username: String,
senders: &MultipleSenders, ip: String,
messages_list: &Mutex<HashMap<i32, EventType>>, event_tx: Sender<NetworkEvent>,
id: i32,
) { ) {
let mut payload = Vec::new(); let crypto_pair = sd.cryptopair_ref();
payload.extend_from_slice(&0u32.to_be_bytes()); let senders = sd.senders_ref();
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes()); let messages_list = sd.messages_list_ref();
let hello_handshake = construct_message(1, payload, id, crypto_pair); let id = generate_id();
match hello_handshake { let server_addr_query = get_socket_address(username.clone(), ip.clone());
Some(handshake_message) => {
senders.send_via(0, handshake_message, server_uri, false); match server_addr_query.await {
Ok(sockaddr_bytes) => {
match String::from_utf8(sockaddr_bytes.to_vec()) {
Ok(s) => {
let addresses = parse_addresses(&s);
if let Some(first) = addresses.first() {
sd.set_servername(username);
// first: &SocketAddr
let mut payload = Vec::new();
payload.extend_from_slice(&0u32.to_be_bytes());
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes());
let hello_handshake = construct_message(1, payload, id, crypto_pair);
match hello_handshake {
Some(handshake_message) => {
senders.send_via(
0,
handshake_message,
first.to_string(),
false,
messages_list,
);
}
None => {}
}
//let res = event_tx
// .send(NetworkEvent::());
} else {
//let res = event_tx.send(NetworkEvent::Error());
let err_msg =
format!("no valid socket addresses found in: {}", s).to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg));
}
}
Err(e) => {
//let res = event_tx.send(NetworkEvent::Error());
let err_msg =
format!("invalid UTF-8 in socket address bytes: {}", e).to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg));
}
}
}
Err(e) => {
let err_msg = format!("failed to retreive socket address: {}", e).to_string();
let res = event_tx.send(NetworkEvent::Error(err_msg));
} }
None => {}
} }
/*let mut list = messages_list.lock().expect("Failed to lock messages_list"); /*let mut list = messages_list.lock().expect("Failed to lock messages_list");
match list.get(&id) { match list.get(&id) {
Some(_) => { Some(_) => {