Compare commits
3 Commits
92f38c9c12
...
tmp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c852c5bb4a | ||
| 98fcc1a0b2 | |||
| 8e279d9e24 |
@@ -1,5 +1,5 @@
|
|||||||
use client_network::{
|
use client_network::{
|
||||||
MerkleNode, MerkleTree, NetworkCommand, NetworkEvent, NodeHash, filename_to_string,
|
ChunkNode, MerkleNode, MerkleTree, NetworkCommand, NetworkEvent, NodeHash, filename_to_string,
|
||||||
node_hash_to_hex_string,
|
node_hash_to_hex_string,
|
||||||
};
|
};
|
||||||
use crossbeam_channel::{Receiver, Sender};
|
use crossbeam_channel::{Receiver, Sender};
|
||||||
@@ -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),
|
||||||
@@ -124,22 +124,40 @@ impl eframe::App for P2PClientApp {
|
|||||||
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]
|
||||||
|
);*/
|
||||||
|
|
||||||
|
if let Ok(chunknode) = ChunkNode::new(Vec::new()) {
|
||||||
|
let mut data_map: HashMap<NodeHash, MerkleNode> = HashMap::new();
|
||||||
|
data_map.insert(root_hash, MerkleNode::Chunk(chunknode));
|
||||||
|
let tree = MerkleTree {
|
||||||
|
data: data_map,
|
||||||
|
root: root_hash,
|
||||||
|
};
|
||||||
|
match &self.active_peer {
|
||||||
|
Some(activepeer) => {
|
||||||
|
self.loaded_fs.insert(activepeer.clone(), tree);
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("tree created");
|
||||||
|
}
|
||||||
|
|
||||||
// self.status_message = format!("🔄 Received Merkle Root from {}: {}", peer_id, &root_hash[..8]);
|
|
||||||
//
|
|
||||||
//
|
|
||||||
//self.active_peer_id = Some(peer_id.clone());
|
//self.active_peer_id = Some(peer_id.clone());
|
||||||
//
|
|
||||||
//
|
// Request the content of the root directory immediately
|
||||||
// // Request the content of the root directory immediately
|
/*let _ = self
|
||||||
// let _ = self.network_cmd_tx.send(NetworkCommand::RequestDirectoryContent(
|
.network_cmd_tx
|
||||||
// peer_id,
|
.send(NetworkCommand::RequestDirectoryContent(peer_id, root_hash));*/
|
||||||
// root_hash,
|
|
||||||
// ));
|
|
||||||
}
|
}
|
||||||
NetworkEvent::Connected(ip) => {
|
NetworkEvent::Connected(ip) => {
|
||||||
self.server_status = ServerStatus::Connected;
|
self.server_status = ServerStatus::Connected;
|
||||||
@@ -360,11 +378,12 @@ 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(),
|
||||||
// ));
|
self.connected_address.clone(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
selectable.context_menu(|ui| {
|
selectable.context_menu(|ui| {
|
||||||
@@ -508,7 +527,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 +554,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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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::{ROOTREQUEST, 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, String),
|
||||||
|
GetChildren(String, String),
|
||||||
// ...
|
// ...
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,7 +138,7 @@ pub enum NetworkEvent {
|
|||||||
PeerListUpdated(Vec<String>),
|
PeerListUpdated(Vec<String>),
|
||||||
FileTreeReceived(String, Vec<MerkleNode>), // peer_id, content
|
FileTreeReceived(String, Vec<MerkleNode>), // peer_id, content
|
||||||
DataReceived(String, MerkleNode),
|
DataReceived(String, MerkleNode),
|
||||||
FileTreeRootReceived(String, String),
|
FileTreeRootReceived(String, NodeHash),
|
||||||
HandshakeFailed(),
|
HandshakeFailed(),
|
||||||
ServerHandshakeFailed(String),
|
ServerHandshakeFailed(String),
|
||||||
// ...
|
// ...
|
||||||
@@ -163,6 +173,8 @@ pub fn start_p2p_executor(
|
|||||||
// Use tokio to spawn the asynchronous networking logic
|
// Use tokio to spawn the asynchronous networking logic
|
||||||
tokio::task::spawn(async move {
|
tokio::task::spawn(async move {
|
||||||
// P2P/Networking Setup goes here
|
// P2P/Networking Setup goes here
|
||||||
|
let handshake_history = Arc::new(Mutex::new(HandshakeHistory::new()));
|
||||||
|
let handshake_clone = handshake_history.clone();
|
||||||
|
|
||||||
println!("Network executor started.");
|
println!("Network executor started.");
|
||||||
|
|
||||||
@@ -172,62 +184,13 @@ pub fn start_p2p_executor(
|
|||||||
if let Ok(cmd) = cmd_rx.try_recv() {
|
if let Ok(cmd) = cmd_rx.try_recv() {
|
||||||
match cmd {
|
match cmd {
|
||||||
NetworkCommand::ServerHandshake(username, ip) => {
|
NetworkCommand::ServerHandshake(username, ip) => {
|
||||||
|
println!("server handshake called");
|
||||||
if let Some(sd) = shared_data.as_ref() {
|
if let Some(sd) = shared_data.as_ref() {
|
||||||
println!("username:{}, ip:{}", username, ip);
|
start_receving_thread(sd, event_tx.clone(), &handshake_clone);
|
||||||
let server_addr_query = get_socket_address(username.clone(), ip);
|
|
||||||
|
|
||||||
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
|
|
||||||
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 =
|
let res =
|
||||||
event_tx.send(NetworkEvent::Error(err_msg));
|
perform_handshake(&sd, username, ip, event_tx.clone(), true).await;
|
||||||
}
|
} else {
|
||||||
}
|
println!("no shared data");
|
||||||
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 +203,56 @@ pub fn start_p2p_executor(
|
|||||||
NetworkCommand::RequestFileTree(_) => {
|
NetworkCommand::RequestFileTree(_) => {
|
||||||
println!("[Network] RequestFileTree() called");
|
println!("[Network] RequestFileTree() called");
|
||||||
}
|
}
|
||||||
|
NetworkCommand::Discover(username, hash, ip) => {
|
||||||
|
// envoie un handshake au peer, puis un root request
|
||||||
|
if let Some(sd) = shared_data.as_ref() {
|
||||||
|
let res = {
|
||||||
|
let m = handshake_clone.lock().unwrap();
|
||||||
|
m.get_peer_info_username(username.clone()).cloned()
|
||||||
|
};
|
||||||
|
match res {
|
||||||
|
Some(peerinfo) => {
|
||||||
|
// envoyer un root request
|
||||||
|
let rootrequest = construct_message(
|
||||||
|
ROOTREQUEST,
|
||||||
|
Vec::new(),
|
||||||
|
generate_id(),
|
||||||
|
sd.cryptopair_ref(),
|
||||||
|
);
|
||||||
|
|
||||||
|
match rootrequest {
|
||||||
|
None => {}
|
||||||
|
Some(resp_msg) => {
|
||||||
|
println!("msg_sent:{:?}", resp_msg);
|
||||||
|
sd.senders_ref().send_via(
|
||||||
|
0,
|
||||||
|
resp_msg,
|
||||||
|
peerinfo.ip.to_string(),
|
||||||
|
false,
|
||||||
|
sd.messages_list_ref(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// envoyer un handshake
|
||||||
|
let res = perform_handshake(
|
||||||
|
&sd,
|
||||||
|
username,
|
||||||
|
ip,
|
||||||
|
event_tx.clone(),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
println!("no shared data");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NetworkCommand::GetChildren(username, hash) => {
|
||||||
|
// envoie un datum request au peer
|
||||||
|
}
|
||||||
NetworkCommand::RequestDirectoryContent(_, _) => {
|
NetworkCommand::RequestDirectoryContent(_, _) => {
|
||||||
println!("[Network] RequestDirectoryContent() called");
|
println!("[Network] RequestDirectoryContent() called");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
NetworkEvent,
|
NetworkEvent, NodeHash,
|
||||||
cryptographic_signature::{
|
cryptographic_signature::{
|
||||||
CryptographicSignature, get_peer_key, sign_message, verify_signature,
|
CryptographicSignature, get_peer_key, sign_message, verify_signature,
|
||||||
},
|
},
|
||||||
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,
|
||||||
|
handhsake_history: &Arc<Mutex<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,
|
||||||
|
handhsake_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,7 +167,10 @@ 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_mutex: &Arc<Mutex<HandshakeHistory>>,
|
||||||
) -> Option<Vec<u8>> {
|
) -> Option<Vec<u8>> {
|
||||||
|
let mut handhsake_history = handhsake_history_mutex.lock().unwrap();
|
||||||
let cmd_tx_clone = cmd_tx.clone();
|
let cmd_tx_clone = cmd_tx.clone();
|
||||||
|
|
||||||
let id_bytes: [u8; 4] = received_message[0..ID]
|
let id_bytes: [u8; 4] = received_message[0..ID]
|
||||||
@@ -166,20 +184,29 @@ 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 | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => {
|
||||||
let ilength = u16::from_be_bytes(length_bytes);
|
let ilength = u16::from_be_bytes(length_bytes);
|
||||||
println!("name received length: {}", ilength);
|
println!("name received length: {}", ilength);
|
||||||
let received_name = &received_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize];
|
let received_name = &received_message[LENGTH + EXTENSIONS..LENGTH + ilength as usize];
|
||||||
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.clone()) {
|
||||||
|
Some(peerinfo) => peerinfo.pubkey,
|
||||||
|
_ => tokio::runtime::Runtime::new()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.block_on(get_peer_key(&username))
|
.block_on(get_peer_key(&username))
|
||||||
.expect("failed to retrieve public key");
|
.expect("failed to retrieve public key"),
|
||||||
|
};
|
||||||
|
match msgtype {
|
||||||
|
HELLOREPLY => {
|
||||||
|
handhsake_history.add_new_handshake(peer_pubkey, "".to_string(), ip);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
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()
|
||||||
@@ -198,6 +225,22 @@ pub fn parse_message(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ROOTREPLY => {
|
||||||
|
let ilength = u16::from_be_bytes(length_bytes);
|
||||||
|
println!("name received length: {}", ilength);
|
||||||
|
if let Some(peerinfo) = handhsake_history.get_peer_info_ip(ip.to_string()) {
|
||||||
|
if !verify_signature(peerinfo.pubkey, &received_message) {
|
||||||
|
println!(
|
||||||
|
"incorrect signature from given peer: {}, ignoring message of type {} with id {}",
|
||||||
|
&peerinfo.username, received_message[ID], id
|
||||||
|
);
|
||||||
|
return None;
|
||||||
|
} else {
|
||||||
|
println!("signature verified");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,7 +291,40 @@ pub fn parse_message(
|
|||||||
//
|
//
|
||||||
//
|
//
|
||||||
// ajoute a la liste des peers handshake
|
// ajoute a la liste des peers handshake
|
||||||
HELLOREPLY => {}
|
HELLOREPLY => {
|
||||||
|
// ajoute l'username a la liste des peers handshake
|
||||||
|
let received_length = u16::from_be_bytes(
|
||||||
|
received_message[TYPE..LENGTH]
|
||||||
|
.try_into()
|
||||||
|
.expect("incorrect size"),
|
||||||
|
);
|
||||||
|
let received_username =
|
||||||
|
&received_message[LENGTH + EXTENSIONS..LENGTH + received_length as usize];
|
||||||
|
handhsake_history.update_peer_info(
|
||||||
|
ip.to_string(),
|
||||||
|
String::from_utf8(received_username.to_vec()).expect("invalid conversion"),
|
||||||
|
);
|
||||||
|
// 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 +332,26 @@ pub fn parse_message(
|
|||||||
//
|
//
|
||||||
// ROOTREPLY
|
// ROOTREPLY
|
||||||
//
|
//
|
||||||
// envoie un datum request
|
ROOTREPLY => {
|
||||||
|
// recuperer le pseudo du peers ayant repondu
|
||||||
|
let peers_exist = handhsake_history.get_peer_info_ip(ip.to_string());
|
||||||
|
match peers_exist {
|
||||||
|
Some(peerinfo) => {
|
||||||
|
// envoyer le hash a la gui
|
||||||
|
let received_hash: NodeHash = received_message[LENGTH..(32 + LENGTH)]
|
||||||
|
.try_into()
|
||||||
|
.expect("incorrect size");
|
||||||
|
let res = cmd_tx_clone.send(NetworkEvent::FileTreeRootReceived(
|
||||||
|
peerinfo.username.clone(),
|
||||||
|
received_hash,
|
||||||
|
));
|
||||||
|
println!("file tree sent")
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
eprintln!("no peers found");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
//
|
//
|
||||||
// DATUMREQUEST
|
// DATUMREQUEST
|
||||||
//
|
//
|
||||||
@@ -328,6 +423,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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,18 +206,25 @@ 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
|
||||||
);
|
);
|
||||||
if let Some(sender) = self.senders.get(channel_idx) {
|
let msg_to_send = Message {
|
||||||
let _ = sender.send(Message {
|
payload: data.clone(),
|
||||||
payload: data,
|
|
||||||
address: remote_addr,
|
address: remote_addr,
|
||||||
is_resp_to_server_handshake,
|
is_resp_to_server_handshake,
|
||||||
});
|
};
|
||||||
|
if let Some(sender) = self.senders.get(channel_idx) {
|
||||||
|
let _ = sender.send(msg_to_send);
|
||||||
}
|
}
|
||||||
|
if !is_resp_to_server_handshake {
|
||||||
|
let mut guard = messages_list.lock().unwrap();
|
||||||
|
let message_id: [u8; 4] = data[0..4].try_into().expect("size error");
|
||||||
|
let id = i32::from_be_bytes(message_id);
|
||||||
|
guard.insert(id, EventType::SendRootRequest);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,17 +260,20 @@ impl MultipleSenders {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}*/
|
}*/
|
||||||
|
}
|
||||||
|
|
||||||
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>,
|
||||||
|
handshake_history: &Arc<Mutex<HandshakeHistory>>,
|
||||||
) {
|
) {
|
||||||
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_clone = handshake_history.clone();
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
let mut buf = [0u8; 1024];
|
let mut buf = [0u8; 1024];
|
||||||
loop {
|
loop {
|
||||||
@@ -275,11 +286,11 @@ pub fn start_receving_thread(
|
|||||||
&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_clone,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Err(e) => eprintln!("Erreur de réception: {}", e),
|
Err(e) => eprintln!("Erreur de réception: {}", e),
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::{HashMap, VecDeque},
|
collections::{HashMap, VecDeque},
|
||||||
net::{AddrParseError, SocketAddr},
|
net::{AddrParseError, Ipv4Addr, SocketAddr},
|
||||||
ops::Add,
|
ops::Add,
|
||||||
process::Command,
|
process::Command,
|
||||||
sync::{Arc, Mutex},
|
sync::{Arc, Mutex},
|
||||||
@@ -11,54 +11,134 @@ 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,
|
pub 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 update_peer_info(&mut self, ip: String, username: String) {
|
||||||
let current_time: u64 = SystemTime::now()
|
let peerinfo = self.get_peer_info_ip(ip.clone());
|
||||||
.duration_since(time::UNIX_EPOCH)
|
match peerinfo {
|
||||||
.expect("system time before UNIX EPOCH")
|
Some(peer_info) => match ip.parse::<SocketAddr>() {
|
||||||
.as_secs();
|
Ok(addr) => {
|
||||||
println!("time:{}", current_time);
|
let new_peer_info = PeerInfo {
|
||||||
/*self.time_k_hash_v.insert(current_time, hash);
|
username: username.clone(),
|
||||||
self.hash_k_peerinfo_v
|
pubkey: peer_info.pubkey,
|
||||||
.insert(hash, PeerInfo { username, ip });*/
|
ip: addr,
|
||||||
|
};
|
||||||
|
self.ip_k_peerinfo_v.insert(ip, new_peer_info.clone());
|
||||||
|
self.username_k_peerinfo_v.insert(username, new_peer_info);
|
||||||
|
}
|
||||||
|
Err(e) => eprintln!("parse error: {}", e),
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
eprintln!("no peer info found in hashmap")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_new_handshake(&mut self, hash: VerifyingKey, username: String, ip: SocketAddr) {
|
||||||
|
let peerinfo = PeerInfo {
|
||||||
|
username: username.clone(),
|
||||||
|
pubkey: hash,
|
||||||
|
ip,
|
||||||
|
};
|
||||||
|
self.username_k_peerinfo_v
|
||||||
|
.insert(username, peerinfo.clone());
|
||||||
|
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, false);
|
||||||
|
/*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 +148,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 +156,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),
|
||||||
);
|
);
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,67 @@ 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,
|
is_server_handshake: bool,
|
||||||
) {
|
) {
|
||||||
|
println!("username: {}, ip: {}", username.clone(), ip.clone());
|
||||||
|
let crypto_pair = sd.cryptopair_ref();
|
||||||
|
let senders = sd.senders_ref();
|
||||||
|
let messages_list = sd.messages_list_ref();
|
||||||
|
let id = generate_id();
|
||||||
|
let server_addr_query = get_socket_address(username.clone(), ip.clone());
|
||||||
|
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();
|
let mut payload = Vec::new();
|
||||||
payload.extend_from_slice(&0u32.to_be_bytes());
|
payload.extend_from_slice(&0u32.to_be_bytes());
|
||||||
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes());
|
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes());
|
||||||
let hello_handshake = construct_message(1, payload, id, crypto_pair);
|
let hello_handshake = construct_message(1, payload, id, crypto_pair);
|
||||||
match hello_handshake {
|
match hello_handshake {
|
||||||
Some(handshake_message) => {
|
Some(handshake_message) => {
|
||||||
senders.send_via(0, handshake_message, server_uri, false);
|
senders.send_via(
|
||||||
|
0,
|
||||||
|
handshake_message,
|
||||||
|
first.to_string(),
|
||||||
|
is_server_handshake,
|
||||||
|
messages_list,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
None => {}
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*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(_) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user