Skip to content

Commit

Permalink
using lambdas, refactor that later
Browse files Browse the repository at this point in the history
  • Loading branch information
joalopez1206 committed Jan 26, 2025
1 parent e875e31 commit 6c1f96e
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions src/nameserver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::message::DnsMessage;
use crate::message::rcode::Rcode;

/// Structure to represent a Name Server
#[derive (Debug)]
#[derive (Debug, Clone)]
pub struct NameServer {
zone: Vec<ResourceRecord>, // Each zone is associated with a domain.
shared_sock: Arc<Mutex<UdpSocket>>,
Expand All @@ -24,23 +24,45 @@ impl NameServer {
}

pub async fn run(&mut self, addr: &str) -> io::Result<()> {
let mut buf = vec![];
let mut buf = vec![0u8; 1024]; // Specify a buffer size for receiving data.
self.init(addr).await?;

let shared_sock = self.shared_sock.clone();
let zone = self.zone.clone(); // Clone the zone for use in the spawned tasks.

loop {
let (len, src) = self.shared_sock.lock().await.recv_from(&mut buf).await?;
let (len, src) = shared_sock.lock().await.recv_from(&mut buf).await?;
println!("Received {} bytes from {:?}", len, addr);

// Spawn a new task to process the request

let data = buf[..len].to_vec();
let socket_clone = self.shared_sock.clone();
let zone_clone = zone.clone();
let socket_clone = shared_sock.clone();
// Handle the request concurrently

tokio::spawn(async move {
// Handle the request concurrently!!! Important
self.handle_request(socket_clone, data, src).await;
let message = DnsMessage::from_bytes(&data).expect("Error parsing the message");

// Search for resource records in the cloned zone
let rrs_to_add = NameServer::search_query(&zone_clone, &message);

if !rrs_to_add.is_empty() {
let mut message = message;
NameServer::add_rrs(&mut message, &rrs_to_add);

let response = message.to_bytes();
let mut sock = socket_clone.lock().await;

if let Err(e) = sock.send_to(&response, src).await {
eprintln!("Failed to send response to {}: {}", src, e);
} else {
println!("Sent response to {:?}", src);
}
}
});
}
}

async fn handle_request(&self, socket: Arc<Mutex<UdpSocket>>,
/*async fn handle_request(&self, socket: Arc<Mutex<UdpSocket>>,
data: Vec<u8>,
addr: std::net::SocketAddr) {
let mut message = DnsMessage::from_bytes(&data).expect("Error al parsear el mensaje");
Expand All @@ -58,7 +80,7 @@ impl NameServer {
} else {
println!("Sent response to {:?}", addr);
}
}
}*/

fn add_rrs(msg :&mut DnsMessage, rrs: &Vec<ResourceRecord>) {
msg.set_answer(rrs.clone());
Expand All @@ -79,7 +101,7 @@ impl NameServer {
qclass == rr.get_rclass()
&& qtype == rr.get_rtype()
&& qname == rr.get_name())
.collect()
.cloned().collect()
}
}

Expand Down

0 comments on commit 6c1f96e

Please sign in to comment.