Skip to content

Commit

Permalink
dhcp: introduce working implementation for the server
Browse files Browse the repository at this point in the history
  • Loading branch information
joaofl committed Dec 31, 2024
1 parent 2555c0e commit 7364f85
Show file tree
Hide file tree
Showing 4 changed files with 198 additions and 26 deletions.
45 changes: 19 additions & 26 deletions src/servers/dhcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ use async_trait::async_trait;
use std::path::PathBuf;
use super::Server;
use crate::utils::validation;
use std::net::IpAddr;
use std::net::{IpAddr, Ipv4Addr};
use std::sync::Arc;
use crate::servers::Protocol;

use std::str::FromStr;
use log::{debug, info};
// use std::time::Duration;
use log::debug;

use std::net::UdpSocket;
use dhcp4r::server as dhcp_server;
use crate::servers::dhcp_server::MyServer;

#[async_trait]
pub trait DHCPRunner {
Expand Down Expand Up @@ -40,37 +42,28 @@ impl DHCPRunner for Server {

let bind_address = self.bind_address;
let port = self.port;
let path = self.path.to_string_lossy().to_string();
let ip_port = format!("{}:{}", bind_address, port);

tokio::spawn(async move {

loop {
debug!("DHCP runner started... Waiting command to connect...");
let m = receiver.recv().await.unwrap();
debug!("Message received");

if m.connect {
info!("Connecting...");
// Define new server
// let _ = libundhcp::Server::with_fs(path)
// .passive_ports(50000..65535)
// .metrics()
// .shutdown_indicator(async move {
// loop {
// info!("Connected. Waiting command to disconnect...");
// let _ = receiver.recv().await.unwrap();
// break;
// }
// debug!("Gracefully terminating the DHCP server");
// // Give a few seconds to potential ongoing connections to finish,
// // otherwise finish immediately
// libundhcp::options::Shutdown::new().grace_period(Duration::from_secs(5))
// })
// .build()
// .unwrap()
// .listen(format!("{}:{}", bind_address, port))
// .await.expect("Error starting the HTTP server...");
break;

debug!("DHCP server started on {}", ip_port);

let ms = MyServer::default();

let socket = UdpSocket::bind("0.0.0.0:67").unwrap();
socket.set_broadcast(true).unwrap();

let ipv4: Ipv4Addr = bind_address.clone().to_string().parse().unwrap();
dhcp_server::Server::serve(socket, ipv4, ms);

debug!("DHCP server stopped");
}
}
});
Expand Down
175 changes: 175 additions & 0 deletions src/servers/dhcp_server/dhcp_server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@

use dhcp4r::{options, packet, server};
use dhcp4r::bytes_u32;

use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::time::{Duration, Instant};

use std::ops::Add;

use log::{debug, info};


// Server configuration
const LEASE_DURATION_SECS: u32 = 7200;
const IP_START: [u8; 4] = [172, 16, 1, 100];
const SUBNET_MASK: Ipv4Addr = Ipv4Addr::new(255, 255, 255, 0);
const DNS_IPS: [Ipv4Addr; 2] = [
// Google DNS servers
Ipv4Addr::new(8, 8, 8, 8),
Ipv4Addr::new(4, 4, 4, 4),
];
const ROUTER_IP: Ipv4Addr = Ipv4Addr::new(172, 16, 1, 254);
const LEASE_NUM: u32 = 100;

// Derived constants
const IP_START_NUM: u32 = bytes_u32!(IP_START);



pub struct MyServer {
pub leases: HashMap<Ipv4Addr, ([u8; 6], Instant)>,
pub last_lease: u32,
}

impl Default for MyServer {
fn default() -> Self {
MyServer {
leases: HashMap::new(),
last_lease: 0,
}
}
}


impl server::Handler for MyServer {
fn handle_request(&mut self, server: &server::Server, in_packet: packet::Packet) {

debug!("Request received");

match in_packet.message_type() {
Ok(options::MessageType::Discover) => {
// Prefer client's choice if available
if let Some(options::DhcpOption::RequestedIpAddress(addr)) =
in_packet.option(options::REQUESTED_IP_ADDRESS)
{
let addr = *addr;
if self.available(&in_packet.chaddr, &addr) {
reply(server, options::MessageType::Offer, in_packet, &addr);
return;
}
}
// Otherwise prefer existing (including expired if available)
if let Some(ip) = self.current_lease(&in_packet.chaddr) {
reply(server, options::MessageType::Offer, in_packet, &ip);
return;
}
// Otherwise choose a free ip if available
for _ in 0..LEASE_NUM {
self.last_lease = (self.last_lease + 1) % LEASE_NUM;
if self.available(
&in_packet.chaddr,
&((IP_START_NUM + &self.last_lease).into()),
) {
reply(
server,
options::MessageType::Offer,
in_packet,
&((IP_START_NUM + &self.last_lease).into()),
);
break;
}
}
}

Ok(options::MessageType::Request) => {
// Ignore requests to alternative DHCP server
if !server.for_this_server(&in_packet) {
return;
}
let req_ip = match in_packet.option(options::REQUESTED_IP_ADDRESS) {
Some(options::DhcpOption::RequestedIpAddress(x)) => *x,
_ => in_packet.ciaddr,
};
if !&self.available(&in_packet.chaddr, &req_ip) {
nak(server, in_packet, "Requested IP not available");
return;
}
self.leases.insert(
req_ip,
(in_packet.chaddr, Instant::now().add(
Duration::new(LEASE_DURATION_SECS as u64, 0))
),
);
reply(server, options::MessageType::Ack, in_packet, &req_ip);
}

Ok(options::MessageType::Release) | Ok(options::MessageType::Decline) => {
// Ignore requests to alternative DHCP server
if !server.for_this_server(&in_packet) {
return;
}
if let Some(ip) = self.current_lease(&in_packet.chaddr) {
self.leases.remove(&ip);
}
}

// TODO - not necessary but support for dhcp4r::INFORM might be nice
_ => {}
}
}
}

impl MyServer {
fn available(&self, chaddr: &[u8; 6], addr: &Ipv4Addr) -> bool {
let pos: u32 = (*addr).into();
pos >= IP_START_NUM
&& pos < IP_START_NUM + LEASE_NUM
&& match self.leases.get(addr) {
Some(x) => x.0 == *chaddr || Instant::now().gt(&x.1),
None => true,
}
}

fn current_lease(&self, chaddr: &[u8; 6]) -> Option<Ipv4Addr> {
for (i, v) in &self.leases {
if &v.0 == chaddr {
return Some(*i);
}
}
return None;
}
}

fn reply(
s: &server::Server,
msg_type: options::MessageType,
req_packet: packet::Packet,
offer_ip: &Ipv4Addr,
) {
let _ = s.reply(
msg_type,
vec![
options::DhcpOption::IpAddressLeaseTime(LEASE_DURATION_SECS),
options::DhcpOption::SubnetMask(SUBNET_MASK),
options::DhcpOption::Router(vec![ROUTER_IP]),
options::DhcpOption::DomainNameServer(DNS_IPS.to_vec()),
],
*offer_ip,
req_packet,
);
info!("offered {:?}", offer_ip);
}

fn nak(s: &server::Server, req_packet: packet::Packet, message: &str) {
let _ = s.reply(
options::MessageType::Nak,
vec![options::DhcpOption::Message(message.to_string())],
Ipv4Addr::new(0, 0, 0, 0),
req_packet,
);
}



3 changes: 3 additions & 0 deletions src/servers/dhcp_server/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub use dhcp_server::*;

pub mod dhcp_server;
1 change: 1 addition & 0 deletions src/servers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub use tftp::*;

// Import and re-export the submodule files.
pub mod dhcp;
pub mod dhcp_server;
pub mod ftp;
pub mod http;
pub mod server;
Expand Down

0 comments on commit 7364f85

Please sign in to comment.