morpheus_network/state/dhcp.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
//! DHCP client state machine.
//!
//! Wraps smoltcp's DHCP client with non-blocking state tracking.
//! Does NOT implement DHCP protocol itself—relies on smoltcp.
//!
//! # States
//! Init → Discovering → Bound | Failed
//!
//! # Usage
//!
//! ```ignore
//! let mut dhcp = DhcpState::new();
//! dhcp.start(now_tsc);
//!
//! loop {
//! iface.poll(...); // smoltcp handles DHCP internally
//!
//! // Check if smoltcp has assigned an IP
//! let has_ip = iface.ipv4_addr().is_some();
//!
//! match dhcp.step(has_ip, now_tsc, timeout_ticks) {
//! StepResult::Pending => continue,
//! StepResult::Done => {
//! let config = dhcp.config().unwrap();
//! break;
//! }
//! StepResult::Timeout => panic!("DHCP timeout"),
//! StepResult::Failed => panic!("DHCP failed"),
//! }
//! }
//! ```
//!
//! # Reference
//! NETWORK_IMPL_GUIDE.md §5.3
use super::{StateError, StepResult, TscTimestamp};
use core::net::Ipv4Addr;
// ═══════════════════════════════════════════════════════════════════════════
// DHCP ERROR
// ═══════════════════════════════════════════════════════════════════════════
/// DHCP-specific errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DhcpError {
/// Discovery timed out
Timeout,
/// No interface available
NoInterface,
/// Lease expired
LeaseExpired,
}
impl From<DhcpError> for StateError {
fn from(e: DhcpError) -> Self {
match e {
DhcpError::Timeout => StateError::Timeout,
_ => StateError::InterfaceError,
}
}
}
// ═══════════════════════════════════════════════════════════════════════════
// DHCP CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════
/// DHCP configuration obtained from server.
#[derive(Debug, Clone, Copy)]
pub struct DhcpConfig {
/// Assigned IP address
pub ip: Ipv4Addr,
/// Subnet mask as prefix length (e.g., 24 for /24)
pub prefix_len: u8,
/// Default gateway
pub gateway: Option<Ipv4Addr>,
/// Primary DNS server
pub dns: Option<Ipv4Addr>,
}
// ═══════════════════════════════════════════════════════════════════════════
// DHCP STATE MACHINE
// ═══════════════════════════════════════════════════════════════════════════
/// DHCP client state machine.
///
/// Tracks DHCP discovery progress and wraps smoltcp's DHCP socket.
#[derive(Debug)]
pub enum DhcpState {
/// Initial state - not started
Init,
/// DHCP discovery in progress
Discovering {
/// When discovery started
start_tsc: TscTimestamp,
},
/// IP address obtained
Bound {
/// DHCP configuration
config: DhcpConfig,
/// When bound
bound_tsc: TscTimestamp,
},
/// DHCP failed
Failed {
/// Error details
error: DhcpError,
},
}
impl DhcpState {
/// Create new DHCP state machine in init state.
pub fn new() -> Self {
DhcpState::Init
}
/// Start DHCP discovery.
///
/// # Arguments
/// - `now_tsc`: Current TSC timestamp
pub fn start(&mut self, now_tsc: u64) {
*self = DhcpState::Discovering {
start_tsc: TscTimestamp::new(now_tsc),
};
}
/// Step the state machine.
///
/// # Arguments
/// - `dhcp_config`: Current DHCP config from smoltcp (None if not yet configured)
/// - `now_tsc`: Current TSC value
/// - `timeout_ticks`: DHCP timeout in TSC ticks
///
/// # Returns
/// - `Pending`: Still discovering
/// - `Done`: Bound, call `config()` to get configuration
/// - `Timeout`: Discovery timed out
/// - `Failed`: Discovery failed
pub fn step(
&mut self,
dhcp_config: Option<DhcpConfig>,
now_tsc: u64,
timeout_ticks: u64,
) -> StepResult {
match self {
DhcpState::Init => {
// Not started yet
StepResult::Pending
}
DhcpState::Discovering { start_tsc } => {
// Check timeout first
if start_tsc.is_expired(now_tsc, timeout_ticks) {
*self = DhcpState::Failed {
error: DhcpError::Timeout,
};
return StepResult::Timeout;
}
// Check if smoltcp has configured an IP
if let Some(config) = dhcp_config {
*self = DhcpState::Bound {
config,
bound_tsc: TscTimestamp::new(now_tsc),
};
return StepResult::Done;
}
// Still discovering
StepResult::Pending
}
DhcpState::Bound { .. } => StepResult::Done,
DhcpState::Failed { error } => {
if *error == DhcpError::Timeout {
StepResult::Timeout
} else {
StepResult::Failed
}
}
}
}
/// Get DHCP configuration (if bound).
pub fn config(&self) -> Option<&DhcpConfig> {
match self {
DhcpState::Bound { config, .. } => Some(config),
_ => None,
}
}
/// Get assigned IP address (if bound).
pub fn ip(&self) -> Option<Ipv4Addr> {
self.config().map(|c| c.ip)
}
/// Get gateway (if bound and available).
pub fn gateway(&self) -> Option<Ipv4Addr> {
self.config().and_then(|c| c.gateway)
}
/// Get DNS server (if bound and available).
pub fn dns(&self) -> Option<Ipv4Addr> {
self.config().and_then(|c| c.dns)
}
/// Get error (if failed).
pub fn error(&self) -> Option<DhcpError> {
match self {
DhcpState::Failed { error } => Some(*error),
_ => None,
}
}
/// Check if DHCP is complete (bound or failed).
pub fn is_terminal(&self) -> bool {
matches!(self, DhcpState::Bound { .. } | DhcpState::Failed { .. })
}
/// Check if successfully bound.
pub fn is_bound(&self) -> bool {
matches!(self, DhcpState::Bound { .. })
}
/// Check if still discovering.
pub fn is_discovering(&self) -> bool {
matches!(self, DhcpState::Discovering { .. })
}
}
impl Default for DhcpState {
fn default() -> Self {
Self::new()
}
}