crdhcpc 0.1.1

Standalone DHCP Client for Linux with DHCPv4, DHCPv6, PXE, and Dynamic DNS support
Documentation
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Secure DHCP Client Implementation
//!
//! This module provides a comprehensive DHCP client supporting:
//! - DHCPv4 and BOOTP
//! - DHCPv6
//! - PXE boot
//! - Dynamic DNS updates
//! - Load balancing and failover
//! - TFTP client for PXE
//! - Security hardening

// dhcproto is re-exported by submodules

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::time::{Duration, SystemTime};
use std::sync::Arc;
use tokio::sync::{RwLock, Mutex};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{debug, info, warn, error};

// Protocol module for Unix socket communication
pub mod protocol;

// Re-export protocol types for convenience
pub use protocol::{
    UnixServer, ServerConfig, DaemonClient, UnixClient, ClientConfig,
    JsonRpcRequest, JsonRpcResponse, JsonRpcError, ProtocolError, ProtocolResult,
};

// Submodules
mod v4_client;
mod v6_client;
mod pxe;
mod ddns;
mod tftp_client;
mod failover;
mod security;
mod config;
mod raw_socket;
mod wifi;
pub mod control;

pub use v4_client::*;
pub use v6_client::*;
pub use pxe::*;
pub use ddns::*;
pub use tftp_client::*;
pub use failover::*;
pub use security::*;
pub use config::*;
pub use raw_socket::*;
pub use wifi::*;
pub use control::*;

/// DHCP client errors
#[derive(Error, Debug)]
pub enum DhcpClientError {
    #[error("Network error: {0}")]
    Network(#[from] std::io::Error),

    #[error("Timeout: {0}")]
    Timeout(String),

    #[error("Invalid message: {0}")]
    InvalidMessage(String),

    #[error("Invalid configuration: {0}")]
    InvalidConfig(String),

    #[error("Server error: {0}")]
    ServerError(String),

    #[error("Security violation: {0}")]
    SecurityViolation(String),

    #[error("No lease available")]
    NoLease,

    #[error("Interface not found: {0}")]
    InterfaceNotFound(String),

    #[error("Invalid interface name: {0}")]
    InvalidInterfaceName(String),

    #[error("DNS update failed: {0}")]
    DnsUpdateFailed(String),

    #[error("TFTP transfer failed: {0}")]
    TftpFailed(String),

    #[error("PXE error: {0}")]
    PxeError(String),

    #[error("WiFi error: {0}")]
    WifiError(String),
}

// Convert anyhow::Error to DhcpClientError
impl From<anyhow::Error> for DhcpClientError {
    fn from(err: anyhow::Error) -> Self {
        DhcpClientError::WifiError(err.to_string())
    }
}

pub type Result<T> = std::result::Result<T, DhcpClientError>;

/// Validate network interface name to prevent command injection
/// Interface names should only contain alphanumeric chars, hyphens, and underscores
pub fn validate_interface_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(DhcpClientError::InvalidInterfaceName(
            "Interface name cannot be empty".to_string(),
        ));
    }
    if name.len() > 15 {
        return Err(DhcpClientError::InvalidInterfaceName(
            format!("Interface name too long (max 15 chars): {}", name),
        ));
    }
    if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
        return Err(DhcpClientError::InvalidInterfaceName(
            format!("Interface name contains invalid characters: {}", name),
        ));
    }
    Ok(())
}

/// DHCP server information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DhcpServer {
    pub address: IpAddr,
    pub last_response: Option<SystemTime>,
    pub response_time: Option<Duration>,
    pub failures: u32,
    pub healthy: bool,
}

impl DhcpServer {
    pub fn new(address: IpAddr) -> Self {
        Self {
            address,
            last_response: None,
            response_time: None,
            failures: 0,
            healthy: true,
        }
    }

    pub fn mark_success(&mut self, response_time: Duration) {
        self.last_response = Some(SystemTime::now());
        self.response_time = Some(response_time);
        self.failures = 0;
        self.healthy = true;
    }

    pub fn mark_failure(&mut self) {
        self.failures += 1;
        if self.failures >= 3 {
            self.healthy = false;
        }
    }
}

/// Unified DHCP client manager
#[derive(Debug)]
pub struct DhcpClientManager {
    v4_clients: Arc<RwLock<Vec<Arc<Dhcpv4Client>>>>,
    v6_clients: Arc<RwLock<Vec<Arc<Dhcpv6Client>>>>,
    config: Arc<RwLock<DhcpClientConfig>>,
    running: Arc<Mutex<bool>>,
}

impl DhcpClientManager {
    /// Create a new DHCP client manager
    pub fn new(config: DhcpClientConfig) -> Self {
        Self {
            v4_clients: Arc::new(RwLock::new(Vec::new())),
            v6_clients: Arc::new(RwLock::new(Vec::new())),
            config: Arc::new(RwLock::new(config)),
            running: Arc::new(Mutex::new(false)),
        }
    }

    /// Start DHCP client on an interface
    pub async fn start_interface(&self, interface: &str) -> Result<()> {
        let config = self.config.read().await;

        if !config.enabled {
            return Err(DhcpClientError::InvalidConfig("DHCP client is disabled".to_string()));
        }

        // Start DHCPv4 client if enabled
        if config.dhcpv4.enabled {
            // Get WiFi configuration for this interface if auto_connect is enabled
            let wifi_config = if config.wifi.auto_connect {
                config.wifi.networks.get(interface).cloned()
            } else {
                None
            };

            let v4_client = Dhcpv4Client::new(
                interface,
                config.dhcpv4.clone(),
                config.security.clone(),
                wifi_config,
            )?;
            let v4_client = Arc::new(v4_client);

            // Spawn the client task
            let client_clone = v4_client.clone();
            let interface_clone = interface.to_string();
            tokio::spawn(async move {
                if let Err(e) = client_clone.run().await {
                    error!("DHCPv4 client error on {}: {}", interface_clone, e);
                }
            });

            self.v4_clients.write().await.push(v4_client);
        }

        // Start DHCPv6 client if enabled
        if config.dhcpv6.enabled {
            let v6_client = Dhcpv6Client::new(interface, config.dhcpv6.clone(), config.security.clone())?;
            let v6_client = Arc::new(v6_client);

            // Spawn the client task
            let client_clone = v6_client.clone();
            let interface_clone = interface.to_string();
            tokio::spawn(async move {
                if let Err(e) = client_clone.run().await {
                    error!("DHCPv6 client error on {}: {}", interface_clone, e);
                }
            });

            self.v6_clients.write().await.push(v6_client);
        }

        *self.running.lock().await = true;
        info!("Started DHCP client on interface {}", interface);

        Ok(())
    }

    /// Stop DHCP client on an interface
    pub async fn stop_interface(&self, interface: &str) -> Result<()> {
        // Stop all v4 clients on this interface
        let mut v4_clients = self.v4_clients.write().await;
        v4_clients.retain(|client| {
            if client.interface() == interface {
                // Client will be dropped and stopped
                false
            } else {
                true
            }
        });

        // Stop all v6 clients on this interface
        let mut v6_clients = self.v6_clients.write().await;
        v6_clients.retain(|client| {
            if client.interface() == interface {
                false
            } else {
                true
            }
        });

        info!("Stopped DHCP client on interface {}", interface);
        Ok(())
    }

    /// Get status of all DHCP clients
    pub async fn get_status(&self) -> DhcpClientStatus {
        let v4_clients = self.v4_clients.read().await;
        let v6_clients = self.v6_clients.read().await;

        let v4_status: Vec<Dhcpv4Status> = v4_clients.iter()
            .map(|c| c.get_status())
            .collect();

        let v6_status: Vec<Dhcpv6Status> = v6_clients.iter()
            .map(|c| c.get_status())
            .collect();

        DhcpClientStatus {
            running: *self.running.lock().await,
            v4_clients: v4_status,
            v6_clients: v6_status,
        }
    }

    /// Renew lease on an interface
    pub async fn renew_interface(&self, interface: &str) -> Result<()> {
        // Renew v4 lease
        let v4_clients = self.v4_clients.read().await;
        for client in v4_clients.iter() {
            if client.interface() == interface {
                client.renew().await?;
            }
        }

        // Renew v6 lease
        let v6_clients = self.v6_clients.read().await;
        for client in v6_clients.iter() {
            if client.interface() == interface {
                client.renew().await?;
            }
        }

        Ok(())
    }

    /// Release lease on an interface
    pub async fn release_interface(&self, interface: &str) -> Result<()> {
        // Release v4 lease
        let v4_clients = self.v4_clients.read().await;
        for client in v4_clients.iter() {
            if client.interface() == interface {
                client.release().await?;
            }
        }

        // Release v6 lease
        let v6_clients = self.v6_clients.read().await;
        for client in v6_clients.iter() {
            if client.interface() == interface {
                client.release().await?;
            }
        }

        Ok(())
    }

    /// Get configuration
    pub async fn get_config(&self) -> DhcpClientConfig {
        self.config.read().await.clone()
    }

    /// Update configuration
    pub async fn set_config(&self, config: DhcpClientConfig) -> Result<()> {
        *self.config.write().await = config;
        Ok(())
    }
}

/// Overall DHCP client status
#[derive(Debug, Serialize, Deserialize)]
pub struct DhcpClientStatus {
    pub running: bool,
    pub v4_clients: Vec<Dhcpv4Status>,
    pub v6_clients: Vec<Dhcpv6Status>,
}

/// DHCPv4 client status
#[derive(Debug, Serialize, Deserialize)]
pub struct Dhcpv4Status {
    pub interface: String,
    pub state: String,
    pub lease: Option<Dhcpv4LeaseInfo>,
    pub servers: Vec<DhcpServer>,
}

/// DHCPv6 client status
#[derive(Debug, Serialize, Deserialize)]
pub struct Dhcpv6Status {
    pub interface: String,
    pub state: String,
    pub ia_na: Option<Dhcpv6IaNaInfo>,
    pub ia_pd: Option<Dhcpv6IaPdInfo>,
    pub servers: Vec<DhcpServer>,
}

/// DHCPv4 lease information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dhcpv4LeaseInfo {
    pub ip_address: Ipv4Addr,
    pub subnet_mask: Ipv4Addr,
    pub router: Option<Ipv4Addr>,
    pub dns_servers: Vec<Ipv4Addr>,
    pub domain_name: Option<String>,
    pub ntp_servers: Vec<Ipv4Addr>,
    pub lease_time: Duration,
    pub renewal_time: Duration,
    pub rebinding_time: Duration,
    pub acquired_at: SystemTime,
    pub expires_at: SystemTime,
}

/// DHCPv6 IA_NA information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dhcpv6IaNaInfo {
    pub addresses: Vec<Ipv6Addr>,
    pub preferred_lifetime: Duration,
    pub valid_lifetime: Duration,
    pub acquired_at: SystemTime,
}

/// DHCPv6 IA_PD information (Prefix Delegation)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dhcpv6IaPdInfo {
    pub prefix: Ipv6Addr,
    pub prefix_len: u8,
    pub preferred_lifetime: Duration,
    pub valid_lifetime: Duration,
    pub acquired_at: SystemTime,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_dhcp_client_manager_creation() {
        let config = DhcpClientConfig::default();
        let manager = DhcpClientManager::new(config);

        let status = manager.get_status().await;
        assert!(!status.running);
        assert_eq!(status.v4_clients.len(), 0);
        assert_eq!(status.v6_clients.len(), 0);
    }

    #[test]
    fn test_dhcp_server() {
        let mut server = DhcpServer::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));
        assert!(server.healthy);
        assert_eq!(server.failures, 0);

        server.mark_failure();
        assert_eq!(server.failures, 1);
        assert!(server.healthy);

        server.mark_failure();
        server.mark_failure();
        assert_eq!(server.failures, 3);
        assert!(!server.healthy);

        server.mark_success(Duration::from_millis(10));
        assert_eq!(server.failures, 0);
        assert!(server.healthy);
    }
}