Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow serving into subnet only #16

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub struct Server {
socket: UdpSocket,
src: SocketAddr,
server_ip: Ipv4Addr,
broadcast_ip: Ipv4Addr,
}

pub trait Handler {
Expand Down Expand Up @@ -52,14 +53,26 @@ impl Server {
pub fn serve<H: Handler>(
udp_soc: UdpSocket,
server_ip: Ipv4Addr,
handler: H,
) -> std::io::Error {
Self::serve_in_subnet(udp_soc, server_ip, Ipv4Addr::UNSPECIFIED, handler)
}

pub fn serve_in_subnet<H: Handler>(
udp_soc: UdpSocket,
server_ip: Ipv4Addr,
subnet_mask: Ipv4Addr,
mut handler: H,
) -> std::io::Error {
let mut in_buf: [u8; 1500] = [0; 1500];
let mut s = Server {
out_buf: Cell::new([0; 1500]),
socket: udp_soc,
server_ip,
src: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0),
broadcast_ip: ((u32::from(server_ip) & u32::from(subnet_mask))
| (u32::from(Ipv4Addr::BROADCAST) & !(u32::from(subnet_mask))))
.into(),
src: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
};
loop {
match s.socket.recv_from(&mut in_buf) {
Expand Down Expand Up @@ -128,18 +141,16 @@ impl Server {
/// Checks the packet see if it was intended for this DHCP server (as opposed to some other also on the network).
pub fn for_this_server(&self, packet: &Packet) -> bool {
match packet.option(options::SERVER_IDENTIFIER) {
Some(DhcpOption::ServerIdentifier(x)) => {
x == &self.server_ip
},
Some(DhcpOption::ServerIdentifier(x)) => x == &self.server_ip,
_ => false,
}
}

/// Encodes and sends a DHCP packet back to the client.
pub fn send(&self, p: Packet) -> std::io::Result<usize> {
let mut addr = self.src;
if p.broadcast || addr.ip() == IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)) {
addr.set_ip(IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255)));
if p.broadcast || addr.ip().is_unspecified() {
addr.set_ip(IpAddr::V4(self.broadcast_ip));
}
self.socket.send_to(p.encode(&mut self.out_buf.get()), addr)
}
Expand Down