mirror of
https://github.com/pj1234678/RustyDHCP.git
synced 2025-10-26 00:15:41 +08:00
Merge pull request #3 from junderw/junderw/minor-fixes
Some minor fixes.
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/target
|
||||
Cargo.lock
|
||||
@@ -8,6 +8,7 @@ fn main() {
|
||||
server::Server::serve(
|
||||
UdpSocket::bind("0.0.0.0:67").unwrap(),
|
||||
Ipv4Addr::new(0, 0, 0, 0),
|
||||
Ipv4Addr::new(0, 0, 0, 0),
|
||||
MyServer {},
|
||||
);
|
||||
}
|
||||
@@ -24,7 +25,9 @@ impl server::Handler for MyServer {
|
||||
};
|
||||
println!(
|
||||
"{}\t{}\t{}\tOnline",
|
||||
time::OffsetDateTime::now_local().format("%Y-%m-%dT%H:%M:%S"),
|
||||
time::OffsetDateTime::try_now_local()
|
||||
.unwrap()
|
||||
.format("%Y-%m-%dT%H:%M:%S"),
|
||||
chaddr(&in_packet.chaddr),
|
||||
Ipv4Addr::from(req_ip)
|
||||
);
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
#[macro_use(u32_bytes, bytes_u32)]
|
||||
extern crate dhcp4r;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::net::{Ipv4Addr, UdpSocket};
|
||||
use std::ops::Add;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
|
||||
use dhcp4r::{options, packet, server};
|
||||
|
||||
@@ -24,10 +21,9 @@ const LEASE_DURATION_SECS: u32 = 86400;
|
||||
const LEASE_NUM: u32 = 252;
|
||||
|
||||
// Derived constants
|
||||
const IP_START_NUM: u32 = bytes_u32!(IP_START);
|
||||
const IP_START_NUM: u32 = u32::from_be_bytes(IP_START);
|
||||
const INFINITE_LEASE: Option<Instant> = None; // Special value for infinite lease
|
||||
|
||||
|
||||
fn main() {
|
||||
let socket = UdpSocket::bind("0.0.0.0:67").unwrap();
|
||||
socket.set_broadcast(true).unwrap();
|
||||
@@ -79,7 +75,6 @@ impl server::Handler for MyServer {
|
||||
fn handle_request(&mut self, server: &server::Server, in_packet: packet::Packet) {
|
||||
match in_packet.message_type() {
|
||||
Ok(options::MessageType::Discover) => {
|
||||
|
||||
// Otherwise prefer existing (including expired if available)
|
||||
if let Some(ip) = self.current_lease(&in_packet.chaddr) {
|
||||
println!("Sending Reply to discover");
|
||||
@@ -129,7 +124,13 @@ impl server::Handler for MyServer {
|
||||
nak(server, in_packet, "Requested IP not available");
|
||||
return;
|
||||
}
|
||||
self.leases.insert(req_ip, (in_packet.chaddr, Some(Instant::now().add(self.lease_duration))));
|
||||
self.leases.insert(
|
||||
req_ip,
|
||||
(
|
||||
in_packet.chaddr,
|
||||
Some(Instant::now().add(self.lease_duration)),
|
||||
),
|
||||
);
|
||||
println!("Sending Reply to Request");
|
||||
reply(server, options::MessageType::Ack, in_packet, &req_ip);
|
||||
}
|
||||
@@ -163,7 +164,6 @@ impl MyServer {
|
||||
}
|
||||
}
|
||||
fn current_lease(&self, chaddr: &[u8; 6]) -> Option<Ipv4Addr> {
|
||||
|
||||
for (i, v) in &self.leases {
|
||||
if v.0 == *chaddr {
|
||||
return Some(*i);
|
||||
|
||||
26
src/lib.rs
26
src/lib.rs
@@ -1,33 +1,7 @@
|
||||
|
||||
|
||||
pub mod options;
|
||||
pub mod packet;
|
||||
pub mod server;
|
||||
|
||||
/// Converts a u32 to 4 bytes (Big endian)
|
||||
#[macro_export]
|
||||
macro_rules! u32_bytes {
|
||||
( $x:expr ) => {
|
||||
[
|
||||
($x >> 24) as u8,
|
||||
($x >> 16) as u8,
|
||||
($x >> 8) as u8,
|
||||
$x as u8,
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
/// Converts 4 bytes to a u32 (Big endian)
|
||||
#[macro_export]
|
||||
macro_rules! bytes_u32 {
|
||||
( $x:expr ) => {
|
||||
($x[0] as u32) * (1 << 24)
|
||||
+ ($x[1] as u32) * (1 << 16)
|
||||
+ ($x[2] as u32) * (1 << 8)
|
||||
+ ($x[3] as u32)
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
|
||||
@@ -19,8 +19,6 @@ pub enum ErrorKind {
|
||||
|
||||
type IResult<I, O> = Result<(I, O), CustomErr<I>>;
|
||||
|
||||
|
||||
|
||||
/// DHCP Packet Structure
|
||||
#[derive(Debug)]
|
||||
pub struct Packet {
|
||||
@@ -87,10 +85,12 @@ pub fn decode_option(input: &[u8]) -> IResult<&[u8], DhcpOption> {
|
||||
let (input, len) = custom_be_u8(input)?;
|
||||
let (input, data) = custom_take(len.into())(input)?;
|
||||
let option = match code {
|
||||
DHCP_MESSAGE_TYPE => DhcpOption::DhcpMessageType(match MessageType::from(custom_be_u8(data)?.1) {
|
||||
DHCP_MESSAGE_TYPE => {
|
||||
DhcpOption::DhcpMessageType(match MessageType::from(custom_be_u8(data)?.1) {
|
||||
Ok(x) => x,
|
||||
Err(_) => return Err(CustomErr::UnrecognizedMessageType),
|
||||
}),
|
||||
})
|
||||
}
|
||||
SERVER_IDENTIFIER => DhcpOption::ServerIdentifier(decode_ipv4(data)?.1),
|
||||
PARAMETER_REQUEST_LIST => DhcpOption::ParameterRequestList(data.to_vec()),
|
||||
REQUESTED_IP_ADDRESS => DhcpOption::RequestedIpAddress(decode_ipv4(data)?.1),
|
||||
@@ -133,7 +133,7 @@ fn custom_tag<'a>(tag: &'static [u8]) -> impl Fn(&'a [u8]) -> IResult<&'a [u8],
|
||||
}
|
||||
}
|
||||
fn custom_be_u8(input: &[u8]) -> IResult<&[u8], u8> {
|
||||
if input.len() < 1 {
|
||||
if input.is_empty() {
|
||||
return Err(CustomErr::InvalidHlen);
|
||||
}
|
||||
|
||||
@@ -174,7 +174,6 @@ fn decode(input: &[u8]) -> IResult<&[u8], Packet> {
|
||||
let (input, giaddr) = decode_ipv4(input)?;
|
||||
|
||||
if hlen != 6 {
|
||||
|
||||
return Err(CustomErr::InvalidHlen);
|
||||
}
|
||||
let (_, chaddr) = custom_take(6usize)(input)?;
|
||||
@@ -182,22 +181,16 @@ fn decode(input: &[u8]) -> IResult<&[u8], Packet> {
|
||||
let input = options_input;
|
||||
let (input, _) = custom_tag(&COOKIE)(input)?;
|
||||
|
||||
|
||||
let mut options = Vec::new();
|
||||
let mut rest = input;
|
||||
|
||||
loop {
|
||||
match decode_option(rest) {
|
||||
Ok((new_rest, option)) => {
|
||||
while let Ok((new_rest, option)) = decode_option(rest) {
|
||||
rest = new_rest;
|
||||
options.push(option);
|
||||
if rest.starts_with(&[END]) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let input = rest.split_at(1).1; // Skip the END tag byte
|
||||
|
||||
@@ -223,18 +216,12 @@ fn decode(input: &[u8]) -> IResult<&[u8], Packet> {
|
||||
|
||||
impl Packet {
|
||||
pub fn from(input: &[u8]) -> Result<Packet, CustomErr<&[u8]>> {
|
||||
|
||||
Ok(decode(input)?.1)
|
||||
}
|
||||
|
||||
/// Extracts requested option payload from packet if available
|
||||
pub fn option(&self, code: u8) -> Option<&DhcpOption> {
|
||||
for option in &self.options {
|
||||
if option.code() == code {
|
||||
return Some(&option);
|
||||
}
|
||||
}
|
||||
None
|
||||
self.options.iter().find(|&option| option.code() == code)
|
||||
}
|
||||
|
||||
/// Convenience function for extracting a packet's message type.
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
//! This is a convenience module that simplifies the writing of a DHCP server service.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
|
||||
|
||||
@@ -5,8 +7,6 @@ use crate::options;
|
||||
use crate::options::{DhcpOption, MessageType};
|
||||
use crate::packet::*;
|
||||
|
||||
///! This is a convenience module that simplifies the writing of a DHCP server service.
|
||||
|
||||
pub struct Server {
|
||||
out_buf: Cell<[u8; 1500]>,
|
||||
socket: UdpSocket,
|
||||
@@ -22,12 +22,12 @@ pub trait Handler {
|
||||
pub fn filter_options_by_req(opts: &mut Vec<DhcpOption>, req_params: &[u8]) {
|
||||
let mut pos = 0;
|
||||
let h = &[
|
||||
options::DHCP_MESSAGE_TYPE as u8,
|
||||
options::SERVER_IDENTIFIER as u8,
|
||||
options::SUBNET_MASK as u8,
|
||||
options::IP_ADDRESS_LEASE_TIME as u8,
|
||||
options::DOMAIN_NAME_SERVER as u8,
|
||||
options::ROUTER as u8,
|
||||
options::DHCP_MESSAGE_TYPE,
|
||||
options::SERVER_IDENTIFIER,
|
||||
options::SUBNET_MASK,
|
||||
options::IP_ADDRESS_LEASE_TIME,
|
||||
options::DOMAIN_NAME_SERVER,
|
||||
options::ROUTER,
|
||||
] as &[u8];
|
||||
|
||||
// Process options from req_params
|
||||
@@ -84,7 +84,6 @@ impl Server {
|
||||
server_ip,
|
||||
broadcast_ip,
|
||||
src: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0),
|
||||
|
||||
};
|
||||
loop {
|
||||
match s.socket.recv_from(&mut in_buf) {
|
||||
@@ -133,7 +132,7 @@ impl Server {
|
||||
if let Some(DhcpOption::ParameterRequestList(prl)) =
|
||||
req_packet.option(options::PARAMETER_REQUEST_LIST)
|
||||
{
|
||||
filter_options_by_req(&mut opts, &prl);
|
||||
filter_options_by_req(&mut opts, prl);
|
||||
}
|
||||
|
||||
self.send(Packet {
|
||||
@@ -154,9 +153,7 @@ 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,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user