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

@@ -7,6 +7,7 @@ use crate::messages_structure::{HandshakeMessage, UDPMessage};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::net::UdpSocket;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
///
@@ -39,7 +40,7 @@ pub async fn register_with_the_server(
/// sends a get request to the server to get the socket address of the given peer
///
async fn get_socket_address(username: String) -> Result<Bytes, reqwest::Error> {
pub async fn get_socket_address(username: String) -> Result<Bytes, reqwest::Error> {
let client = reqwest::Client::new();
let uri = format!("https://jch.irif.fr:8443/peers/{}/addresses", username);
let res = client.get(uri).send().await?;
@@ -55,6 +56,20 @@ async fn get_socket_address(username: String) -> Result<Bytes, reqwest::Error> {
Ok(body)
}
pub fn parse_addresses(input: &String) -> Vec<SocketAddr> {
let mut addrs = Vec::new();
for line in input.lines() {
let s = line.trim();
if s.is_empty() {
continue;
}
if let Ok(sock) = SocketAddr::from_str(s) {
addrs.push(sock);
}
}
addrs
}
///
/// registers the IP addresses by sending a Hello request to the server.
///
@@ -63,21 +78,25 @@ pub fn register_ip_addresses(
server_uri: String,
senders: &MultipleSenders,
messages_list: &Arc<Mutex<HashMap<i32, EventType>>>,
id: i32,
) {
let username_size = crypto_pair.username.len();
let hello_handshake =
HandshakeMessage::hello(545, username_size as u16 + 4, crypto_pair.username.clone());
let hello_handshake = HandshakeMessage::hello(
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, server_uri);
let mut list = messages_list.lock().expect("Failed to lock messages_list");
match list.get(&545) {
match list.get(&id) {
Some(_) => {
list.remove(&545);
list.remove(&id);
}
None => {
list.insert(545, EventType::ServerHelloReply);
list.insert(id, EventType::ServerHelloReply);
}
}
// 3. Perform the insertion