message handling and serv registration

This commit is contained in:
2025-12-30 20:18:18 +01:00
parent ced0c992e7
commit cc09fab16d
6 changed files with 178 additions and 39 deletions

View File

@@ -0,0 +1,95 @@
use crate::{
cryptographic_signature::{CryptographicSignature, sign_message},
messages_channels::MultipleSenders,
messages_structure::HandshakeMessage,
registration,
};
use std::sync::{Arc, Mutex};
use std::{collections::HashMap, net::SocketAddr};
pub enum EventType {
ServerHelloReply,
PeerHelloReply,
PeerHello,
}
/*pub fn handle_recevied_message(
messages_list: &mut HashMap<i32, EventType>,
recevied_message: &Vec<u8>,
crypto_pair: &CryptographicSignature,
socket_addr: &SocketAddr,
senders: &MultipleSenders,
) {
let message_id: [u8; 4] = recevied_message[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id);
let eventtype = messages_list.get(&id);
match eventtype {
Some(EventType::ServerHelloReply) => {
registration::register_ip_addresses(
&crypto_pair,
socket_addr.ip().to_string(),
&senders,
messages_list,
);
}
Some(_) => print!("Not implemented"),
None => print!("Message not found"),
}
}*/
pub fn handle_recevied_message(
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
recevied_message: &Vec<u8>,
crypto_pair: &CryptographicSignature,
socket_addr: &SocketAddr,
senders: &MultipleSenders,
) {
if recevied_message.len() < 4 {
return;
} // Basic safety check
let message_id: [u8; 4] = recevied_message[0..4].try_into().expect("size error");
let id = i32::from_be_bytes(message_id);
// Lock the mutex to access the HashMap
let list = messages_list.lock().unwrap();
let eventtype = list.get(&id); // Clone the enum so we can release the lock if needed
match eventtype {
Some(EventType::ServerHelloReply) => {
/*registration::register_ip_addresses(
crypto_pair,
socket_addr.to_string(),
senders,
&messages_list, // Pass the mutable reference inside the lock
546,
);*/
}
Some(_) => print!("Not implemented"),
None => {
let message_type = recevied_message[4];
if message_type == 1 {
let username_size = crypto_pair.username.len();
let hello_handshake = HandshakeMessage::helloReply(
id as u32,
username_size as u16 + 4,
crypto_pair.username.clone(),
);
//HandshakeMessage::display(&hello_handshake);
let hello_handshake_serialized = hello_handshake.serialize();
let message_signed = sign_message(crypto_pair, &hello_handshake_serialized);
senders.send_via(0, message_signed, socket_addr.to_string());
let mut list = messages_list.lock().expect("Failed to lock messages_list");
match list.get(&id) {
Some(_) => {
list.remove(&id);
}
None => {
list.insert(id, EventType::ServerHelloReply);
}
}
}
print!("Message not found for ID: {}", id)
}
}
}