wip messages creation & handling
This commit is contained in:
@@ -108,11 +108,10 @@ pub fn sign_message(crypto_pair: &CryptographicSignature, message: &Vec<u8>) ->
|
|||||||
let digest = Sha256::digest(&message[..7 + msg_length as usize]);
|
let digest = Sha256::digest(&message[..7 + msg_length as usize]);
|
||||||
let signature = crypto_pair.priv_key.sign_prehash_recoverable(&digest);
|
let signature = crypto_pair.priv_key.sign_prehash_recoverable(&digest);
|
||||||
|
|
||||||
let message_length = 12 + msg_length as usize + 32;
|
let message_length = 7 + msg_length as usize + 64;
|
||||||
let mut signed_message = Vec::with_capacity(message_length);
|
let mut signed_message = Vec::with_capacity(message_length);
|
||||||
println!("{}", message_length);
|
println!("{}", message_length);
|
||||||
signed_message.extend_from_slice(&message[..8 + msg_length as usize]);
|
signed_message.extend_from_slice(&message[..7 + msg_length as usize]);
|
||||||
signed_message.pop();
|
|
||||||
println!("signed_tmp:{:?}", signed_message);
|
println!("signed_tmp:{:?}", signed_message);
|
||||||
match signature {
|
match signature {
|
||||||
Ok(signature) => {
|
Ok(signature) => {
|
||||||
@@ -123,7 +122,7 @@ pub fn sign_message(crypto_pair: &CryptographicSignature, message: &Vec<u8>) ->
|
|||||||
let s_bytes = s.to_bytes();
|
let s_bytes = s.to_bytes();
|
||||||
signed_message.extend_from_slice(&r_bytes[..32]);
|
signed_message.extend_from_slice(&r_bytes[..32]);
|
||||||
signed_message.extend_from_slice(&s_bytes[..32]);
|
signed_message.extend_from_slice(&s_bytes[..32]);
|
||||||
println!("signed:{:?}", signed_message);
|
println!("signed:{:?}, len: {}", signed_message, signed_message.len());
|
||||||
signed_message
|
signed_message
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
|||||||
@@ -187,6 +187,7 @@ pub fn start_p2p_executor(
|
|||||||
start_receving_thread(
|
start_receving_thread(
|
||||||
sd,
|
sd,
|
||||||
*first, // copie le SocketAddr (implémente Copy pour SocketAddr)
|
*first, // copie le SocketAddr (implémente Copy pour SocketAddr)
|
||||||
|
event_tx.clone(), //
|
||||||
);
|
);
|
||||||
register_ip_addresses(
|
register_ip_addresses(
|
||||||
sd.cryptopair_ref(),
|
sd.cryptopair_ref(),
|
||||||
|
|||||||
@@ -7,8 +7,11 @@ use crate::{
|
|||||||
messages_structure::construct_message,
|
messages_structure::construct_message,
|
||||||
registration,
|
registration,
|
||||||
};
|
};
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
use std::{collections::HashMap, net::SocketAddr};
|
use std::{collections::HashMap, net::SocketAddr};
|
||||||
|
use std::{
|
||||||
|
net::IpAddr,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
pub enum EventType {
|
pub enum EventType {
|
||||||
ServerHelloReply,
|
ServerHelloReply,
|
||||||
@@ -42,6 +45,8 @@ pub fn handle_recevied_message(
|
|||||||
socket_addr: &SocketAddr,
|
socket_addr: &SocketAddr,
|
||||||
senders: &MultipleSenders,
|
senders: &MultipleSenders,
|
||||||
server_name: &String,
|
server_name: &String,
|
||||||
|
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
|
||||||
|
ip: SocketAddr,
|
||||||
) {
|
) {
|
||||||
if recevied_message.len() < 4 {
|
if recevied_message.len() < 4 {
|
||||||
return;
|
return;
|
||||||
@@ -50,8 +55,31 @@ pub fn handle_recevied_message(
|
|||||||
let message_id: [u8; 4] = recevied_message[0..4].try_into().expect("size error");
|
let message_id: [u8; 4] = recevied_message[0..4].try_into().expect("size error");
|
||||||
let id = i32::from_be_bytes(message_id);
|
let id = i32::from_be_bytes(message_id);
|
||||||
|
|
||||||
parse_message(recevied_message, received_name, id, crypto_pair, cmd_tx)
|
let mut is_resp_to_server_handshake = false;
|
||||||
//TODO
|
|
||||||
|
if recevied_message[4] == HELLO {
|
||||||
|
let length_bytes: [u8; 2] = recevied_message[TYPE..LENGTH]
|
||||||
|
.try_into()
|
||||||
|
.expect("Taille incorrecte");
|
||||||
|
let msg_length = u16::from_be_bytes(length_bytes) as usize;
|
||||||
|
let ilength = u16::from_be_bytes(length_bytes);
|
||||||
|
let received_name =
|
||||||
|
&recevied_message[LENGTH + EXTENSIONS..LENGTH + EXTENSIONS + ilength as usize];
|
||||||
|
let name = String::from_utf8(received_name.to_vec()).expect("wrong name");
|
||||||
|
if name.clone() == server_name.clone() {
|
||||||
|
is_resp_to_server_handshake = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let resp = parse_message(recevied_message.to_vec(), id, crypto_pair, cmd_tx, ip);
|
||||||
|
|
||||||
|
match resp {
|
||||||
|
None => {}
|
||||||
|
Some(resp_msg) => {
|
||||||
|
println!("msg_sent:{:?}", resp_msg);
|
||||||
|
senders.send_via(0, resp_msg, ip.to_string(), is_resp_to_server_handshake);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Lock the mutex to access the HashMap
|
// Lock the mutex to access the HashMap
|
||||||
/*let list = messages_list.lock().unwrap();
|
/*let list = messages_list.lock().unwrap();
|
||||||
@@ -119,32 +147,12 @@ pub fn handle_recevied_message(
|
|||||||
}*/
|
}*/
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn ping(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn ok(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn error(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn hello(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn hello_reply(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn root_request(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn root_reply(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn datum_request(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn no_datum(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn datum(received_message: Vec<u8>, socket_addr: String) {}
|
|
||||||
|
|
||||||
pub fn parse_message(
|
pub fn parse_message(
|
||||||
received_message: Vec<u8>,
|
received_message: Vec<u8>,
|
||||||
received_name: String,
|
|
||||||
id: i32,
|
id: i32,
|
||||||
crypto_pair: &CryptographicSignature,
|
crypto_pair: &CryptographicSignature,
|
||||||
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
|
cmd_tx: crossbeam_channel::Sender<NetworkEvent>,
|
||||||
|
ip: SocketAddr,
|
||||||
) -> Option<Vec<u8>> {
|
) -> Option<Vec<u8>> {
|
||||||
let cmd_tx_clone = cmd_tx.clone();
|
let cmd_tx_clone = cmd_tx.clone();
|
||||||
|
|
||||||
@@ -163,20 +171,32 @@ pub fn parse_message(
|
|||||||
// verify signature
|
// verify signature
|
||||||
match msgtype {
|
match msgtype {
|
||||||
HELLO | HELLOREPLY | ROOTREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => {
|
HELLO | HELLOREPLY | ROOTREPLY | NODATUM | NATTRAVERSALREQUEST | NATTRAVERSALREQUEST2 => {
|
||||||
let peer_pubkey = tokio::runtime::Runtime::new()
|
let ilength = u16::from_be_bytes(length_bytes);
|
||||||
.unwrap()
|
let received_name =
|
||||||
.block_on(get_peer_key(&received_name))
|
&received_message[LENGTH + EXTENSIONS..LENGTH + EXTENSIONS + ilength as usize];
|
||||||
.expect("failed to retrieve public key");
|
let received_username = String::from_utf8(received_name.to_vec());
|
||||||
let signature: [u8; SIGNATURE] = received_message
|
match received_username {
|
||||||
[LENGTH + msg_length..LENGTH + msg_length + SIGNATURE]
|
Ok(username) => {
|
||||||
.try_into()
|
let peer_pubkey = tokio::runtime::Runtime::new()
|
||||||
.expect("Taille incorrecte");
|
.unwrap()
|
||||||
if !verify_signature(peer_pubkey, &received_message) {
|
.block_on(get_peer_key(&username))
|
||||||
println!(
|
.expect("failed to retrieve public key");
|
||||||
"incorrect signature from given peer: {}, ignoring message of type {} with id {}",
|
let signature: [u8; SIGNATURE] = received_message
|
||||||
&received_name, received_message[ID], id
|
[LENGTH + msg_length..LENGTH + msg_length + SIGNATURE]
|
||||||
);
|
.try_into()
|
||||||
return None;
|
.expect("Taille incorrecte");
|
||||||
|
if !verify_signature(peer_pubkey, &received_message) {
|
||||||
|
println!(
|
||||||
|
"incorrect signature from given peer: {}, ignoring message of type {} with id {}",
|
||||||
|
&username, received_message[ID], id
|
||||||
|
);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("incorrect name: {}", e);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
@@ -204,17 +224,10 @@ pub fn parse_message(
|
|||||||
if let Ok(err_received) =
|
if let Ok(err_received) =
|
||||||
String::from_utf8(received_message[LENGTH..(msg_length + LENGTH)].to_vec())
|
String::from_utf8(received_message[LENGTH..(msg_length + LENGTH)].to_vec())
|
||||||
{
|
{
|
||||||
let err_msg = format!(
|
let err_msg = format!("Error received from peer {} : {}", ip, err_received);
|
||||||
"Error received from peer {} : {}",
|
|
||||||
String::from(received_name),
|
|
||||||
err_received
|
|
||||||
);
|
|
||||||
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg));
|
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg));
|
||||||
} else {
|
} else {
|
||||||
let err_msg = format!(
|
let err_msg = format!("Error received from peer {} : N/A", ip,);
|
||||||
"Error received from peer {} : N/A",
|
|
||||||
String::from(received_name),
|
|
||||||
);
|
|
||||||
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg));
|
let _ = cmd_tx_clone.send(NetworkEvent::Error(err_msg));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -253,7 +253,11 @@ impl MultipleSenders {
|
|||||||
});
|
});
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
pub fn start_receving_thread(shared_data: &P2PSharedData, socket_addr: SocketAddr) {
|
pub fn start_receving_thread(
|
||||||
|
shared_data: &P2PSharedData,
|
||||||
|
socket_addr: SocketAddr,
|
||||||
|
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();
|
||||||
@@ -274,6 +278,8 @@ pub fn start_receving_thread(shared_data: &P2PSharedData, socket_addr: SocketAdd
|
|||||||
&socket_addr,
|
&socket_addr,
|
||||||
&senders_clone,
|
&senders_clone,
|
||||||
&servername_clone,
|
&servername_clone,
|
||||||
|
cmd_tx.clone(),
|
||||||
|
src,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Err(e) => eprintln!("Erreur de réception: {}", e),
|
Err(e) => eprintln!("Erreur de réception: {}", e),
|
||||||
|
|||||||
@@ -39,7 +39,9 @@ pub fn construct_message(
|
|||||||
match msgtype {
|
match msgtype {
|
||||||
HELLO | HELLOREPLY => {
|
HELLO | HELLOREPLY => {
|
||||||
// length
|
// length
|
||||||
message.extend_from_slice(&(EXTENSIONS + payload.len()).to_be_bytes());
|
let a = payload.len() as u16;
|
||||||
|
println!("payload size:{}", a);
|
||||||
|
message.extend_from_slice(&a.to_be_bytes());
|
||||||
message.extend_from_slice(&payload);
|
message.extend_from_slice(&payload);
|
||||||
let signature = sign_message(crypto_pair, &message);
|
let signature = sign_message(crypto_pair, &message);
|
||||||
message.extend_from_slice(&signature);
|
message.extend_from_slice(&signature);
|
||||||
|
|||||||
@@ -3,9 +3,12 @@
|
|||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::{HashMap, VecDeque},
|
collections::{HashMap, VecDeque},
|
||||||
net::SocketAddr,
|
net::{AddrParseError, SocketAddr},
|
||||||
|
ops::Add,
|
||||||
|
process::Command,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
thread,
|
thread,
|
||||||
time::{self, SystemTime},
|
time::{self, Duration, SystemTime},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub struct PeerInfo {
|
pub struct PeerInfo {
|
||||||
@@ -14,24 +17,36 @@ pub struct PeerInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct HandshakeHistory {
|
pub struct HandshakeHistory {
|
||||||
time_k_hash_v: HashMap<u64, u64>,
|
time_k_ip_v: HashMap<u64, u64>,
|
||||||
hash_k_peerinfo_v: HashMap<u64, PeerInfo>,
|
ip_k_peerinfo_v: HashMap<u64, PeerInfo>,
|
||||||
times_to_check: VecDeque<u64>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HandshakeHistory {
|
impl HandshakeHistory {
|
||||||
pub fn new() -> HandshakeHistory {
|
pub fn new() -> HandshakeHistory {
|
||||||
HandshakeHistory {
|
HandshakeHistory {
|
||||||
time_k_hash_v: HashMap::new(),
|
time_k_ip_v: HashMap::new(),
|
||||||
hash_k_peerinfo_v: HashMap::new(),
|
ip_k_peerinfo_v: HashMap::new(),
|
||||||
times_to_check: VecDeque::new(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_handshake(&self) {
|
pub fn update_handshake(&mut self) {
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
|
let mut times_to_check = VecDeque::new();
|
||||||
|
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
|
// adds 10 seconds in the queue every 10 seconds
|
||||||
self.times_to_check.insert(index, value);
|
loop {
|
||||||
|
let mut child = Command::new("sleep").arg("9").spawn().unwrap();
|
||||||
|
let _result = child.wait().unwrap();
|
||||||
|
for n in 0..9 {
|
||||||
|
// push 9 successive seconds
|
||||||
|
times_to_check.push_back(current_time + n);
|
||||||
|
// gestion d'erreur si verrou mort
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,9 +56,9 @@ impl HandshakeHistory {
|
|||||||
.expect("system time before UNIX EPOCH")
|
.expect("system time before UNIX EPOCH")
|
||||||
.as_secs();
|
.as_secs();
|
||||||
println!("time:{}", current_time);
|
println!("time:{}", current_time);
|
||||||
self.time_k_hash_v.insert(current_time, hash);
|
/*self.time_k_hash_v.insert(current_time, hash);
|
||||||
self.hash_k_peerinfo_v
|
self.hash_k_peerinfo_v
|
||||||
.insert(hash, PeerInfo { username, ip });
|
.insert(hash, PeerInfo { username, ip });*/
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use getrandom::Error;
|
|||||||
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 std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::net::UdpSocket;
|
use std::net::UdpSocket;
|
||||||
@@ -72,17 +73,17 @@ pub fn register_ip_addresses(
|
|||||||
messages_list: &Mutex<HashMap<i32, EventType>>,
|
messages_list: &Mutex<HashMap<i32, EventType>>,
|
||||||
id: i32,
|
id: i32,
|
||||||
) {
|
) {
|
||||||
let username_size = crypto_pair.username.len();
|
let mut payload = Vec::new();
|
||||||
let hello_handshake = HandshakeMessage::hello(
|
payload.extend_from_slice(&0u32.to_be_bytes());
|
||||||
id as u32,
|
payload.extend_from_slice(&crypto_pair.username.clone().as_bytes());
|
||||||
username_size as u16 + 4,
|
let hello_handshake = construct_message(1, payload, id, crypto_pair);
|
||||||
crypto_pair.username.clone(),
|
match hello_handshake {
|
||||||
);
|
Some(handshake_message) => {
|
||||||
//HandshakeMessage::display(&hello_handshake);
|
senders.send_via(0, handshake_message, server_uri, false);
|
||||||
let hello_handshake_serialized = hello_handshake.serialize();
|
}
|
||||||
let message_signed = sign_message(crypto_pair, &hello_handshake_serialized);
|
None => {}
|
||||||
senders.send_via(0, message_signed, server_uri, false);
|
}
|
||||||
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(_) => {
|
||||||
list.remove(&id);
|
list.remove(&id);
|
||||||
@@ -91,7 +92,7 @@ pub fn register_ip_addresses(
|
|||||||
list.insert(id, EventType::ServerHelloReply);
|
list.insert(id, EventType::ServerHelloReply);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
println!("message sent: {}", &id);
|
println!("message sent: {}", &id);*/
|
||||||
// 3. Perform the insertion
|
// 3. Perform the insertion
|
||||||
/*let mut buf = [0u8; 1024];
|
/*let mut buf = [0u8; 1024];
|
||||||
socket.recv_from(&mut buf).expect("receive failed");
|
socket.recv_from(&mut buf).expect("receive failed");
|
||||||
|
|||||||
Reference in New Issue
Block a user