Files
p2p/client-network/src/registration.rs

143 lines
4.5 KiB
Rust

use bytes::Bytes;
use crate::cryptographic_signature::{CryptographicSignature, formatPubKey, sign_message};
use crate::message_handling::EventType;
use crate::messages_channels::{Message, MultipleSenders};
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};
///
/// sends the cryptographic signature to the server using a PUT request over the HTTP API.
///
pub async fn register_with_the_server(
crypto_pair: &Arc<CryptographicSignature>,
server_uri: &String,
) -> Result<(), reqwest::Error> {
let client = reqwest::Client::new();
let uri = format!("{0}/peers/{1}/key", server_uri, crypto_pair.username);
let encoded_point = crypto_pair.pub_key.to_encoded_point(false);
let pubkey_bytes = encoded_point.as_ref().to_vec();
let pubkey_bytes_minus = pubkey_bytes[1..].to_vec();
let res = client.put(uri).body(pubkey_bytes_minus).send().await?;
if res.status().is_success() {
let str = hex::encode(res.bytes().await?);
println!("Successfully registered with the server : {}", str);
} else {
eprintln!(
"Failed to register with the server. Status: {}",
res.status()
);
}
println!("register ip adresses");
Ok(())
}
///
/// sends a get request to the server to get the socket address of the given peer
///
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?;
if res.status().is_success() {
println!("Successfully retreived the addresses.");
} else {
eprintln!(
"Failed to register with the server. Status: {}",
res.status()
);
}
let body: Bytes = res.bytes().await?;
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.
///
pub fn register_ip_addresses(
crypto_pair: &CryptographicSignature,
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(
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(&id) {
Some(_) => {
list.remove(&id);
}
None => {
list.insert(id, EventType::ServerHelloReply);
}
}
// 3. Perform the insertion
/*let mut buf = [0u8; 1024];
socket.recv_from(&mut buf).expect("receive failed");
let hello_handshake_received = UDPMessage::parse(buf.to_vec());
hello_handshake_received.display();*/
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
/*///
/// does the procedure to register with the server
///
#[tokio::test]
async fn registering_with_server() {
let username = String::from("gameixtreize");
let server_uri = String::from("https://jch.irif.fr:8443");
let crypto_pair = CryptographicSignature::new(username);
if let Err(e) = register_with_the_server(crypto_pair, server_uri).await {
eprintln!("Error during registration: {}", e);
}
}*/
/*///
/// retreives the socket address of a given peer
///
#[tokio::test]
async fn retreive_socket_addr() {
let username = String::from("ipjkndqfshjldfsjlbsdfjhhj");
match get_socket_address(username).await {
Ok(body) => {
println!("{:?}", body);
}
Err(e) => {
eprintln!("Erreur HTTP: {}", e);
}
}
}*/
}