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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
//! DHCPv4 and BOOTP client implementation
//!
//! Implements RFC 2131 (DHCP) and RFC 951 (BOOTP)

use super::*;

use tokio::time::sleep;

// Conditional debug logging macro with line numbers
#[cfg(feature = "dhcp-debug")]
macro_rules! dhcp_debug {
    ($($arg:tt)*) => {
        debug!("[{}:{}] {}", file!(), line!(), format!($($arg)*))
    };
}

#[cfg(not(feature = "dhcp-debug"))]
macro_rules! dhcp_debug {
    ($($arg:tt)*) => {};
}

#[cfg(feature = "dhcp-debug")]
macro_rules! dhcp_info {
    ($($arg:tt)*) => {
        info!("[{}:{}] {}", file!(), line!(), format!($($arg)*))
    };
}

#[cfg(not(feature = "dhcp-debug"))]
macro_rules! dhcp_info {
    ($($arg:tt)*) => {};
}

/// DHCPv4 client state
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dhcpv4State {
    Init,
    Selecting,
    Requesting,
    Bound,
    Renewing,
    Rebinding,
    InitReboot,
}

impl std::fmt::Display for Dhcpv4State {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Init => write!(f, "INIT"),
            Self::Selecting => write!(f, "SELECTING"),
            Self::Requesting => write!(f, "REQUESTING"),
            Self::Bound => write!(f, "BOUND"),
            Self::Renewing => write!(f, "RENEWING"),
            Self::Rebinding => write!(f, "REBINDING"),
            Self::InitReboot => write!(f, "INIT-REBOOT"),
        }
    }
}

/// DHCPv4 lease
#[derive(Debug, Clone)]
pub struct Dhcpv4Lease {
    pub ip_address: Ipv4Addr,
    pub subnet_mask: Option<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 server_id: Ipv4Addr,
    pub acquired_at: SystemTime,
}

impl Dhcpv4Lease {
    pub fn expires_at(&self) -> SystemTime {
        self.acquired_at + self.lease_time
    }

    pub fn renewal_at(&self) -> SystemTime {
        self.acquired_at + self.renewal_time
    }

    pub fn rebinding_at(&self) -> SystemTime {
        self.acquired_at + self.rebinding_time
    }

    pub fn is_expired(&self) -> bool {
        SystemTime::now() > self.expires_at()
    }

    pub fn needs_renewal(&self) -> bool {
        SystemTime::now() > self.renewal_at()
    }

    pub fn needs_rebinding(&self) -> bool {
        SystemTime::now() > self.rebinding_at()
    }

    pub fn to_info(&self) -> Dhcpv4LeaseInfo {
        Dhcpv4LeaseInfo {
            ip_address: self.ip_address,
            subnet_mask: self.subnet_mask.unwrap_or(Ipv4Addr::new(255, 255, 255, 0)),
            router: self.router,
            dns_servers: self.dns_servers.clone(),
            domain_name: self.domain_name.clone(),
            ntp_servers: self.ntp_servers.clone(),
            lease_time: self.lease_time,
            renewal_time: self.renewal_time,
            rebinding_time: self.rebinding_time,
            acquired_at: self.acquired_at,
            expires_at: self.expires_at(),
        }
    }
}

/// DHCPv4 client
pub struct Dhcpv4Client {
    interface: String,
    mac_address: [u8; 6],
    state: Arc<RwLock<Dhcpv4State>>,
    config: Dhcpv4Config,
    lease: Arc<RwLock<Option<Dhcpv4Lease>>>,
    servers: Arc<RwLock<Vec<DhcpServer>>>,
    security: SecurityContext,
    shutdown: Arc<Mutex<bool>>,
    xid: Arc<Mutex<u32>>,
    offered_ip: Arc<RwLock<Option<Ipv4Addr>>>,  // Store offered IP from OFFER
    selected_server: Arc<RwLock<Option<Ipv4Addr>>>,  // Store selected server ID
    wifi_config: Option<WifiNetworkConfig>,  // WiFi configuration if wireless interface
}

impl std::fmt::Debug for Dhcpv4Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Dhcpv4Client")
            .field("interface", &self.interface)
            .field("mac_address", &self.mac_address)
            .finish()
    }
}

impl Dhcpv4Client {
    /// Create a new DHCPv4 client
    pub fn new(
        interface: &str,
        config: Dhcpv4Config,
        security: SecurityConfig,
        wifi_config: Option<WifiNetworkConfig>,
    ) -> Result<Self> {
        // Validate interface name to prevent command injection
        validate_interface_name(interface)?;

        dhcp_debug!("========================================");
        dhcp_debug!("DEBUG: Dhcpv4Client::new() called");
        dhcp_debug!("  interface: {}", interface);

        let mac_address = Self::get_mac_address(interface)?;

        dhcp_debug!("  MAC address: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
               mac_address[0], mac_address[1], mac_address[2],
               mac_address[3], mac_address[4], mac_address[5]);

        let security_ctx = SecurityContext::new(security);
        security_ctx.validate_mac_address(&mac_address)?;

        let xid = SecurityContext::generate_xid();
        dhcp_debug!("  Generated transaction ID: 0x{:08x}", xid);
        dhcp_debug!("DEBUG: Dhcpv4Client created successfully");
        dhcp_debug!("========================================");

        Ok(Self {
            interface: interface.to_string(),
            mac_address,
            state: Arc::new(RwLock::new(Dhcpv4State::Init)),
            config,
            lease: Arc::new(RwLock::new(None)),
            servers: Arc::new(RwLock::new(Vec::new())),
            security: security_ctx,
            shutdown: Arc::new(Mutex::new(false)),
            xid: Arc::new(Mutex::new(xid)),
            offered_ip: Arc::new(RwLock::new(None)),
            selected_server: Arc::new(RwLock::new(None)),
            wifi_config,
        })
    }

    /// Get MAC address for interface
    fn get_mac_address(interface: &str) -> Result<[u8; 6]> {
        // Read MAC address from /sys/class/net/{interface}/address
        // With retry logic to handle interfaces that take time to appear
        use std::fs;
        use std::thread;
        use std::time::Duration;

        let mac_path = format!("/sys/class/net/{}/address", interface);

        // Retry parameters: 10 attempts over 5 seconds
        let max_attempts = 10;
        let retry_delay = Duration::from_millis(500);

        let mut last_error = String::new();

        for attempt in 1..=max_attempts {
            match fs::read_to_string(&mac_path) {
                Ok(mac_str) => {
                    let mac_str = mac_str.trim();
                    let parts: Vec<&str> = mac_str.split(':').collect();

                    if parts.len() != 6 {
                        return Err(DhcpClientError::InterfaceNotFound(
                            format!("Invalid MAC address format for interface {}", interface)
                        ));
                    }

                    let mut mac = [0u8; 6];
                    for (i, part) in parts.iter().enumerate() {
                        mac[i] = u8::from_str_radix(part, 16)
                            .map_err(|_| DhcpClientError::InterfaceNotFound(
                                format!("Invalid MAC address for interface {}", interface)
                            ))?;
                    }

                    if attempt > 1 {
                        debug!("Successfully read MAC address for {} after {} attempts", interface, attempt);
                    }
                    return Ok(mac);
                }
                Err(e) => {
                    last_error = format!("Attempt {}/{}: {}", attempt, max_attempts, e);

                    if attempt < max_attempts {
                        debug!("Interface {} not ready, retrying in {:?}... (attempt {}/{})",
                               interface, retry_delay, attempt, max_attempts);
                        thread::sleep(retry_delay);
                    }
                }
            }
        }

        Err(DhcpClientError::InterfaceNotFound(
            format!("Interface {} not found after {} attempts ({}). Last error: {}",
                    interface, max_attempts, mac_path, last_error)
        ))
    }

    /// Get interface name
    pub fn interface(&self) -> &str {
        &self.interface
    }

    /// Get current status
    pub fn get_status(&self) -> Dhcpv4Status {
        let state = self.state.blocking_read();
        let lease = self.lease.blocking_read();
        let servers = self.servers.blocking_read();

        Dhcpv4Status {
            interface: self.interface.clone(),
            state: state.to_string(),
            lease: lease.as_ref().map(|l| l.to_info()),
            servers: servers.clone(),
        }
    }

    /// Run the DHCP client
    pub async fn run(&self) -> Result<()> {
        info!("========================================");
        info!("Starting DHCPv4 client on {}", self.interface);
        info!("========================================");

        // NOTE: WiFi setup is commented out. For WiFi interfaces, ensure WiFi connection
        // is already established using external tools like wpa_supplicant or NetworkManager
        // before starting the DHCP client.
        //
        // Example: sudo wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant.conf
        //
        // Uncomment the lines below to enable automatic WiFi connection management:
        // if let Err(e) = self.setup_wifi_connection().await {
        //     warn!("WiFi setup failed (continuing anyway): {}", e);
        // }

        // Bring up the link layer BEFORE starting DHCP operations
        if let Err(e) = self.bring_up_interface().await {
            warn!("Failed to bring up interface {} (continuing anyway): {}", self.interface, e);
        }

        loop {
            // Check if we should shutdown
            if *self.shutdown.lock().await {
                info!("DHCPv4 client shutting down on {}", self.interface);
                break;
            }

            let state = self.state.read().await.clone();
            dhcp_debug!("----------------------------------------");
            dhcp_debug!("DEBUG: Current state: {}", state);
            dhcp_debug!("----------------------------------------");

            match state {
                Dhcpv4State::Init => {
                    dhcp_info!("STATE: INIT -> Sending DISCOVER and waiting for OFFER");
                    // Create socket, send DISCOVER, and keep socket open for receiving
                    let socket = self.do_discover().await?;
                    dhcp_debug!("DEBUG: State transition: INIT -> SELECTING");
                    *self.state.write().await = Dhcpv4State::Selecting;

                    // Immediately wait for OFFER on the same socket (avoids race condition)
                    dhcp_info!("STATE: SELECTING -> Waiting for OFFER");
                    if let Some(server) = self.wait_for_offer(socket).await? {
                        dhcp_info!("STATE: SELECTING -> Received offer from {}", server.address);

                        // Send REQUEST and keep socket open for receiving ACK
                        let request_socket = self.do_request(&server).await?;
                        dhcp_debug!("DEBUG: State transition: SELECTING -> REQUESTING");
                        *self.state.write().await = Dhcpv4State::Requesting;

                        // Immediately wait for ACK on the same socket (avoids race condition)
                        dhcp_info!("STATE: REQUESTING -> Waiting for ACK");
                        if let Some(lease) = self.wait_for_ack(request_socket).await? {
                            // RFC 2131/RFC 5227: Perform ARP probe before accepting the lease
                            dhcp_info!("Performing ARP probe for {} before accepting lease", lease.ip_address);

                            match self.arp_probe(lease.ip_address).await {
                                Ok(true) => {
                                    // Conflict detected! Send DECLINE and restart
                                    warn!("IP address {} is already in use! Sending DHCPDECLINE", lease.ip_address);
                                    if let Err(e) = self.decline(lease.ip_address, lease.server_id).await {
                                        error!("Failed to send DHCPDECLINE: {}", e);
                                    }
                                    // State is already set to INIT by decline(), loop will restart
                                    continue;
                                }
                                Ok(false) => {
                                    // No conflict, proceed with lease
                                    dhcp_info!("ARP probe passed, IP {} is available", lease.ip_address);
                                }
                                Err(e) => {
                                    // ARP probe failed, but continue anyway (best effort)
                                    warn!("ARP probe failed (continuing anyway): {}", e);
                                }
                            }

                            *self.lease.write().await = Some(lease.clone());
                            dhcp_debug!("DEBUG: State transition: REQUESTING -> BOUND");
                            *self.state.write().await = Dhcpv4State::Bound;
                            dhcp_info!("DHCPv4 lease acquired on {}: {:?}", self.interface,
                                  self.lease.read().await.as_ref().map(|l| l.ip_address));

                            // Apply the lease to the interface
                            dhcp_info!("Configuring interface {} with lease", self.interface);
                            if let Err(e) = self.apply_lease(&lease).await {
                                error!("Failed to apply lease to {}: {}", self.interface, e);
                            } else {
                                info!("✓ Interface {} configured successfully", self.interface);
                            }
                        } else {
                            dhcp_info!("STATE: REQUESTING -> No ACK received, starting over");
                            dhcp_debug!("DEBUG: State transition: REQUESTING -> INIT");
                            *self.state.write().await = Dhcpv4State::Init;
                            dhcp_info!("  Sleeping {} seconds before retry", self.config.timeout);
                            sleep(Duration::from_secs(self.config.timeout)).await;
                        }
                    } else {
                        dhcp_info!("STATE: SELECTING -> No offer received, retrying");
                        dhcp_debug!("DEBUG: State transition: SELECTING -> INIT");
                        *self.state.write().await = Dhcpv4State::Init;
                        dhcp_info!("  Sleeping {} seconds before retry", self.config.timeout);
                        sleep(Duration::from_secs(self.config.timeout)).await;
                    }
                }
                Dhcpv4State::Selecting => {
                    // This state is now handled inline with Init above
                    // Transition to Init if we somehow end up here
                    dhcp_debug!("DEBUG: In Selecting state unexpectedly, transitioning to Init");
                    *self.state.write().await = Dhcpv4State::Init;
                }
                Dhcpv4State::Requesting => {
                    // This state is now handled inline with Init/Selecting above
                    // Transition to Init if we somehow end up here
                    dhcp_info!("STATE: REQUESTING -> Unexpectedly in this state, starting over");
                    *self.state.write().await = Dhcpv4State::Init;
                }
                Dhcpv4State::Bound => {
                    // Wait for renewal time
                    if let Some(lease) = self.lease.read().await.as_ref() {
                        let now = SystemTime::now();
                        let renewal_at = lease.renewal_at();

                        if now >= renewal_at {
                            *self.state.write().await = Dhcpv4State::Renewing;
                        } else {
                            let wait_time = renewal_at.duration_since(now).unwrap_or(Duration::from_secs(60));
                            sleep(wait_time.min(Duration::from_secs(60))).await;
                        }
                    } else {
                        *self.state.write().await = Dhcpv4State::Init;
                    }
                }
                Dhcpv4State::Renewing => {
                    if let Err(e) = self.do_renew().await {
                        warn!("Renewal failed on {}: {}", self.interface, e);

                        // Check if we should rebind
                        if let Some(lease) = self.lease.read().await.as_ref() {
                            if lease.needs_rebinding() {
                                *self.state.write().await = Dhcpv4State::Rebinding;
                            }
                        }
                    } else {
                        *self.state.write().await = Dhcpv4State::Bound;
                    }
                }
                Dhcpv4State::Rebinding => {
                    if let Err(e) = self.do_rebind().await {
                        warn!("Rebinding failed on {}: {}", self.interface, e);

                        // Check if lease expired
                        if let Some(lease) = self.lease.read().await.as_ref() {
                            if lease.is_expired() {
                                *self.lease.write().await = None;
                                *self.state.write().await = Dhcpv4State::Init;
                            }
                        }
                    } else {
                        *self.state.write().await = Dhcpv4State::Bound;
                    }
                }
                Dhcpv4State::InitReboot => {
                    // Try to reacquire previous lease
                    *self.state.write().await = Dhcpv4State::Init;
                }
            }

            // Small sleep to avoid busy loop
            sleep(Duration::from_millis(100)).await;
        }

        Ok(())
    }

    /// Send DHCPDISCOVER and return socket for receiving
    async fn do_discover(&self) -> Result<DhcpRawSocket> {
        use crate::raw_socket::*;

        dhcp_debug!("========================================");
        dhcp_debug!("DEBUG: do_discover() called");
        dhcp_debug!("  interface: {}", self.interface);
        dhcp_debug!("  MAC address: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
               self.mac_address[0], self.mac_address[1], self.mac_address[2],
               self.mac_address[3], self.mac_address[4], self.mac_address[5]);

        dhcp_debug!("DEBUG: Checking rate limit...");
        self.security.check_rate_limit(&self.interface).await?;
        dhcp_debug!("DEBUG: Rate limit check passed");

        // Get transaction ID
        let xid = *self.xid.lock().await;
        dhcp_debug!("DEBUG: Using transaction ID: 0x{:08x}", xid);

        // Get hostname
        let hostname = self.config.hostname.as_deref();

        // Ensure link is up before creating socket and sending packets
        dhcp_info!("Ensuring link is up before sending DISCOVER");
        if let Err(e) = self.bring_up_interface().await {
            warn!("Failed to bring up interface {} before DISCOVER: {}", self.interface, e);
        }

        // Create raw socket FIRST before sending (using Link layer - recommended for DHCP)
        // This socket will be used for both sending and receiving to avoid race conditions
        dhcp_info!("Creating raw socket for DHCP (send and receive)");
        let socket = DhcpRawSocket::new(RawSocketType::LinkLayer, Some(&self.interface))
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to create raw socket: {}", e)
            )))?;

        // Build DISCOVER packet
        dhcp_info!("Building DHCP DISCOVER packet");
        let packet = build_dhcp_discover_link_frame(self.mac_address, xid, hostname);

        // Send packet
        dhcp_info!("Sending DHCP DISCOVER packet ({} bytes)", packet.len());
        socket.send(&packet)
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to send DISCOVER: {}", e)
            )))?;

        info!("DHCP DISCOVER sent on {}", self.interface);
        dhcp_debug!("========================================");

        // Return the socket for receiving responses
        Ok(socket)
    }

    /// Wait for DHCPOFFER using the provided socket
    async fn wait_for_offer(&self, socket: DhcpRawSocket) -> Result<Option<DhcpServer>> {
        use crate::raw_socket::*;

        dhcp_debug!("========================================");
        dhcp_debug!("DEBUG: wait_for_offer() called");
        dhcp_debug!("  interface: {}", self.interface);

        // Use the socket that was already created before sending DISCOVER
        dhcp_info!("Waiting for DHCP OFFER on existing socket");

        let timeout = Duration::from_secs(self.config.timeout);
        let mut buf = vec![0u8; 1500];  // Standard MTU size
        let my_xid = *self.xid.lock().await;

        dhcp_info!("Waiting for DHCP OFFER (timeout: {} seconds)", self.config.timeout);

        // Try to receive packets for the timeout duration
        let start = std::time::Instant::now();
        while start.elapsed() < timeout {
            match socket.recv(&mut buf, Duration::from_secs(1)) {
                Ok(size) => {
                    dhcp_debug!("DEBUG: Received packet of {} bytes", size);

                    // Parse DHCP packet
                    match parse_dhcp_packet(&buf[..size]) {
                        Ok((msg_type, xid, dhcp_msg)) => {
                            dhcp_debug!("DEBUG: Parsed DHCP packet: type={}, xid=0x{:08x}", msg_type, xid);

                            // Check if it's for us
                            if xid != my_xid {
                                dhcp_debug!("DEBUG: XID mismatch (expected 0x{:08x}, got 0x{:08x}), ignoring", my_xid, xid);
                                continue;
                            }

                            // Check if it's an OFFER (type 2)
                            if msg_type != 2 {
                                dhcp_debug!("DEBUG: Not an OFFER (type={}), ignoring", msg_type);
                                continue;
                            }

                            // Extract server ID and offered IP
                            match (extract_server_id(&dhcp_msg), extract_offered_ip(&dhcp_msg)) {
                                (Ok(server_id), Ok(offered_ip)) => {
                                    dhcp_info!("Received DHCP OFFER from {} offering {}", server_id, offered_ip);

                                    // Validate the offer
                                    if let Err(e) = self.security.validate_ipv4_address(&offered_ip) {
                                        warn!("Invalid offered IP address: {}", e);
                                        continue;
                                    }

                                    // Create server object
                                    let mut server = DhcpServer::new(IpAddr::V4(server_id));
                                    server.mark_success(start.elapsed());

                                    // Store offered IP and server ID for REQUEST
                                    *self.offered_ip.write().await = Some(offered_ip);
                                    *self.selected_server.write().await = Some(server_id);

                                    // Add to servers list
                                    let mut servers = self.servers.write().await;
                                    servers.push(server.clone());

                                    dhcp_debug!("========================================");
                                    return Ok(Some(server));
                                }
                                (Err(e1), Err(e2)) => {
                                    warn!("Failed to extract server info: server_id={}, ip={}", e1, e2);
                                }
                                (Err(_e), _) => {
                                    warn!("Failed to extract server info from offer");
                                }
                                (_, Err(_e)) => {
                                    warn!("Failed to extract offered IP from offer");
                                }
                            }
                        }
                        Err(_e) => {
                            dhcp_debug!("DEBUG: Failed to parse packet: {}", _e);
                        }
                    }
                }
                Err(e) => {
                    // Timeout is normal, just continue
                    if e.kind() != std::io::ErrorKind::TimedOut &&
                       e.kind() != std::io::ErrorKind::WouldBlock {
                        dhcp_debug!("DEBUG: Recv error: {}", e);
                    }
                }
            }
        }

        dhcp_info!("No DHCP OFFER received within timeout");
        dhcp_debug!("========================================");
        Ok(None)
    }

    /// Send DHCPREQUEST and return socket for receiving
    async fn do_request(&self, server: &DhcpServer) -> Result<DhcpRawSocket> {
        use crate::raw_socket::*;

        dhcp_debug!("========================================");
        dhcp_debug!("DEBUG: do_request() called");
        dhcp_debug!("  interface: {}", self.interface);
        dhcp_debug!("  server: {}", server.address);

        dhcp_debug!("DEBUG: Checking rate limit...");
        self.security.check_rate_limit(&self.interface).await?;
        dhcp_debug!("DEBUG: Rate limit check passed");

        dhcp_debug!("DEBUG: Validating server...");
        self.security.validate_server(&server.address)?;
        dhcp_debug!("DEBUG: Server validation passed");

        // Get transaction ID
        let xid = *self.xid.lock().await;

        // Get the offered IP and server ID that we stored from wait_for_offer()
        let offered_ip = self.offered_ip.read().await
            .ok_or_else(|| DhcpClientError::InvalidMessage("No offered IP stored".to_string()))?;

        let server_id = self.selected_server.read().await
            .ok_or_else(|| DhcpClientError::InvalidMessage("No server ID stored".to_string()))?;

        dhcp_debug!("DEBUG: Requesting IP {} from server {}", offered_ip, server_id);

        // Get hostname
        let hostname = self.config.hostname.as_deref();

        // Create raw socket FIRST before sending (to avoid race condition)
        // This socket will be used for both sending and receiving
        dhcp_info!("Creating raw socket for DHCP REQUEST (send and receive)");
        let socket = DhcpRawSocket::new(RawSocketType::LinkLayer, Some(&self.interface))
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to create raw socket: {}", e)
            )))?;

        // Build REQUEST packet
        dhcp_info!("Building DHCP REQUEST packet");
        let packet = build_dhcp_request_link_frame(
            self.mac_address,
            xid,
            offered_ip,
            server_id,
            hostname
        );

        // Send packet
        dhcp_info!("Sending DHCP REQUEST packet ({} bytes)", packet.len());
        socket.send(&packet)
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to send REQUEST: {}", e)
            )))?;

        info!("DHCP REQUEST sent to server {} on {}", server_id, self.interface);
        dhcp_debug!("========================================");

        // Return the socket for receiving ACK
        Ok(socket)
    }

    /// Wait for DHCPACK using the provided socket
    async fn wait_for_ack(&self, socket: DhcpRawSocket) -> Result<Option<Dhcpv4Lease>> {
        use crate::raw_socket::*;

        dhcp_debug!("========================================");
        dhcp_debug!("DEBUG: wait_for_ack() called");
        dhcp_debug!("  interface: {}", self.interface);

        // Use the socket that was already created before sending REQUEST
        dhcp_info!("Waiting for DHCP ACK on existing socket");

        let timeout = Duration::from_secs(self.config.timeout);
        let mut buf = vec![0u8; 1500];
        let my_xid = *self.xid.lock().await;

        dhcp_info!("Waiting for DHCP ACK (timeout: {} seconds)", self.config.timeout);

        // Try to receive packets for the timeout duration
        let start = std::time::Instant::now();
        while start.elapsed() < timeout {
            match socket.recv(&mut buf, Duration::from_secs(1)) {
                Ok(size) => {
                    dhcp_debug!("DEBUG: Received packet of {} bytes", size);

                    // Parse DHCP packet
                    match parse_dhcp_packet(&buf[..size]) {
                        Ok((msg_type, xid, dhcp_msg)) => {
                            dhcp_debug!("DEBUG: Parsed DHCP packet: type={}, xid=0x{:08x}", msg_type, xid);

                            // Check if it's for us
                            if xid != my_xid {
                                dhcp_debug!("DEBUG: XID mismatch, ignoring");
                                continue;
                            }

                            // Check if it's an ACK (type 5) or NAK (type 6)
                            if msg_type == 6 {
                                warn!("Received DHCP NAK - server rejected our request");
                                return Ok(None);
                            }

                            if msg_type != 5 {
                                dhcp_debug!("DEBUG: Not an ACK (type={}), ignoring", msg_type);
                                continue;
                            }

                            // Extract full lease information
                            match extract_lease_info(&dhcp_msg) {
                                Ok(lease_info) => {
                                    dhcp_info!("Received DHCP ACK from {}", lease_info.server_id);
                                    dhcp_info!("  IP address: {}", lease_info.ip_address);
                                    dhcp_info!("  Subnet mask: {:?}", lease_info.subnet_mask);
                                    dhcp_info!("  Router: {:?}", lease_info.router);
                                    dhcp_info!("  DNS servers: {:?}", lease_info.dns_servers);
                                    dhcp_info!("  Lease time: {} seconds", lease_info.lease_time);

                                    // Validate lease
                                    self.security.validate_ipv4_address(&lease_info.ip_address)?;
                                    self.security.validate_lease_time(lease_info.lease_time)?;

                                    // Create Dhcpv4Lease object
                                    let lease = Dhcpv4Lease {
                                        ip_address: lease_info.ip_address,
                                        subnet_mask: lease_info.subnet_mask,
                                        router: lease_info.router,
                                        dns_servers: lease_info.dns_servers,
                                        domain_name: lease_info.domain_name,
                                        ntp_servers: lease_info.ntp_servers,
                                        lease_time: Duration::from_secs(lease_info.lease_time as u64),
                                        renewal_time: Duration::from_secs(
                                            lease_info.renewal_time.unwrap_or(lease_info.lease_time / 2) as u64
                                        ),
                                        rebinding_time: Duration::from_secs(
                                            lease_info.rebinding_time.unwrap_or(lease_info.lease_time * 7 / 8) as u64
                                        ),
                                        server_id: lease_info.server_id,
                                        acquired_at: SystemTime::now(),
                                    };

                                    dhcp_debug!("========================================");
                                    return Ok(Some(lease));
                                }
                                Err(_e) => {
                                    warn!("Failed to extract lease information from ACK");
                                }
                            }
                        }
                        Err(_e) => {
                            dhcp_debug!("DEBUG: Failed to parse packet: {}", _e);
                        }
                    }
                }
                Err(e) => {
                    if e.kind() != std::io::ErrorKind::TimedOut &&
                       e.kind() != std::io::ErrorKind::WouldBlock {
                        dhcp_debug!("DEBUG: Recv error: {}", e);
                    }
                }
            }
        }

        dhcp_info!("No DHCP ACK received within timeout");
        dhcp_debug!("========================================");
        Ok(None)
    }

    /// Renew lease
    pub async fn renew(&self) -> Result<()> {
        info!("Renewing DHCP lease on {}", self.interface);
        self.do_renew().await
    }

    async fn do_renew(&self) -> Result<()> {
        use crate::raw_socket::*;

        dhcp_info!("Renewing DHCP lease on {}", self.interface);

        let lease = self.lease.read().await;
        let lease = lease.as_ref().ok_or_else(|| DhcpClientError::NoLease)?;

        // For renewal, we send REQUEST with ciaddr set to current IP
        // and send it directly to the server (not broadcast)
        let xid = *self.xid.lock().await;
        let hostname = self.config.hostname.as_deref();

        dhcp_debug!("DEBUG: Renewing with server {}, IP {}", lease.server_id, lease.ip_address);

        // Create socket
        let socket = DhcpRawSocket::new(RawSocketType::LinkLayer, Some(&self.interface))
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to create raw socket: {}", e)
            )))?;

        // Build REQUEST packet (using link layer frame)
        let packet = build_dhcp_request_link_frame(
            self.mac_address,
            xid,
            lease.ip_address,
            lease.server_id,
            hostname
        );

        // Send packet
        socket.send(&packet)
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to send RENEW: {}", e)
            )))?;

        info!("DHCP RENEW sent on {}", self.interface);

        // Wait for ACK (using the same socket to avoid race condition)
        let _ = lease;  // Release lock before calling wait_for_ack
        if let Some(new_lease) = self.wait_for_ack(socket).await? {
            *self.lease.write().await = Some(new_lease.clone());
            info!("DHCP lease renewed on {}", self.interface);

            // Apply the renewed lease to the interface
            if let Err(e) = self.apply_lease(&new_lease).await {
                warn!("Failed to apply renewed lease to {}: {}", self.interface, e);
            }

            Ok(())
        } else {
            Err(DhcpClientError::Timeout("No ACK received for renewal".to_string()))
        }
    }

    async fn do_rebind(&self) -> Result<()> {
        use crate::raw_socket::*;

        dhcp_info!("Rebinding DHCP lease on {}", self.interface);

        let lease = self.lease.read().await;
        let lease = lease.as_ref().ok_or_else(|| DhcpClientError::NoLease)?;

        // For rebinding, we broadcast REQUEST to any server
        let xid = *self.xid.lock().await;
        let hostname = self.config.hostname.as_deref();

        dhcp_debug!("DEBUG: Rebinding IP {} (broadcasting)", lease.ip_address);

        // Create socket
        let socket = DhcpRawSocket::new(RawSocketType::LinkLayer, Some(&self.interface))
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to create raw socket: {}", e)
            )))?;

        // Build REQUEST packet (with broadcast, using link layer frame)
        let packet = build_dhcp_request_link_frame(
            self.mac_address,
            xid,
            lease.ip_address,
            lease.server_id,  // Include original server, but broadcast anyway
            hostname
        );

        // Send packet
        socket.send(&packet)
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to send REBIND: {}", e)
            )))?;

        info!("DHCP REBIND sent on {}", self.interface);

        // Wait for ACK (using the same socket to avoid race condition)
        let _ = lease;  // Release lock before calling wait_for_ack
        if let Some(new_lease) = self.wait_for_ack(socket).await? {
            *self.lease.write().await = Some(new_lease.clone());
            info!("DHCP lease rebound on {}", self.interface);

            // Apply the rebound lease to the interface
            if let Err(e) = self.apply_lease(&new_lease).await {
                warn!("Failed to apply rebound lease to {}: {}", self.interface, e);
            }

            Ok(())
        } else {
            Err(DhcpClientError::Timeout("No ACK received for rebinding".to_string()))
        }
    }

    /// Setup WiFi connection if this is a wireless interface
    async fn setup_wifi_connection(&self) -> Result<()> {
        use crate::wifi::{WifiManager, WifiConfig, WifiSecurity};

        // Only proceed if WiFi config is provided
        let wifi_net_config = match &self.wifi_config {
            Some(cfg) => cfg,
            None => {
                debug!("No WiFi configuration for {}, skipping WiFi setup", self.interface);
                return Ok(());
            }
        };

        // Check if this is a wireless interface
        let wifi_mgr = WifiManager::new(&self.interface)?;
        if !wifi_mgr.is_wireless().await {
            debug!("Interface {} is not wireless, skipping WiFi setup", self.interface);
            return Ok(());
        }

        info!("Detected wireless interface {}", self.interface);

        // Check if already connected
        if wifi_mgr.is_connected().await? {
            if let Some(current_ssid) = wifi_mgr.get_current_ssid().await? {
                if current_ssid == wifi_net_config.ssid {
                    info!("✓ Already connected to WiFi network \"{}\"", current_ssid);
                    return Ok(());
                } else {
                    info!("Connected to different network \"{}\", disconnecting...", current_ssid);
                    wifi_mgr.disconnect().await?;
                }
            }
        }

        // Convert WifiNetworkConfig to WifiConfig
        let security = match wifi_net_config.security.to_lowercase().as_str() {
            "open" => WifiSecurity::Open,
            "wep" => {
                if let Some(key) = &wifi_net_config.wep_key {
                    WifiSecurity::Wep { key: key.clone() }
                } else {
                    return Err(DhcpClientError::InvalidConfig(
                        "WEP security requires wep_key".to_string()
                    ));
                }
            }
            "wpa" | "wpa2" | "psk" => {
                if let Some(pass) = &wifi_net_config.passphrase {
                    WifiSecurity::WpaPsk { passphrase: pass.clone() }
                } else {
                    return Err(DhcpClientError::InvalidConfig(
                        "WPA/WPA2 security requires passphrase".to_string()
                    ));
                }
            }
            "wpa3" | "sae" => {
                if let Some(pass) = &wifi_net_config.passphrase {
                    WifiSecurity::Wpa3Sae { passphrase: pass.clone() }
                } else {
                    return Err(DhcpClientError::InvalidConfig(
                        "WPA3 security requires passphrase".to_string()
                    ));
                }
            }
            "enterprise" => {
                let identity = wifi_net_config.identity.as_ref()
                    .ok_or_else(|| DhcpClientError::InvalidConfig(
                        "Enterprise security requires identity".to_string()
                    ))?.clone();
                let password = wifi_net_config.password.as_ref()
                    .ok_or_else(|| DhcpClientError::InvalidConfig(
                        "Enterprise security requires password".to_string()
                    ))?.clone();
                WifiSecurity::WpaEnterprise {
                    identity,
                    password,
                    ca_cert: wifi_net_config.ca_cert.clone(),
                }
            }
            _ => {
                return Err(DhcpClientError::InvalidConfig(
                    format!("Unknown security type: {}", wifi_net_config.security)
                ));
            }
        };

        let wifi_config = WifiConfig {
            ssid: wifi_net_config.ssid.clone(),
            security,
            hidden: wifi_net_config.hidden,
            timeout: wifi_net_config.timeout,
        };

        // Connect to WiFi
        info!("Connecting to WiFi network \"{}\"...", wifi_config.ssid);
        wifi_mgr.connect(&wifi_config).await?;

        info!("✓ WiFi connection established on {}", self.interface);
        Ok(())
    }

    /// Bring up the network interface before DHCP operations
    async fn bring_up_interface(&self) -> Result<()> {
        use tokio::process::Command;

        info!("Bringing up interface {} before DHCP operations", self.interface);
        dhcp_debug!("Executing: ip link set {} up", self.interface);

        let output = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            Command::new("ip")
                .args(&["link", "set", &self.interface, "up"])
                .output()
        ).await;

        match output {
            Ok(Ok(result)) => {
                if result.status.success() {
                    info!("✓ Interface {} brought up successfully", self.interface);

                    // Wait for carrier (physical link) to come up
                    let carrier_path = format!("/sys/class/net/{}/carrier", self.interface);
                    let max_wait = std::time::Duration::from_secs(10);
                    let poll_interval = std::time::Duration::from_millis(100);
                    let start = std::time::Instant::now();

                    dhcp_debug!("Waiting for carrier on {} (max {} seconds)", self.interface, max_wait.as_secs());

                    loop {
                        if let Ok(carrier) = tokio::fs::read_to_string(&carrier_path).await {
                            if carrier.trim() == "1" {
                                info!("✓ Carrier detected on {} after {:?}", self.interface, start.elapsed());
                                break;
                            }
                        }
                        if start.elapsed() >= max_wait {
                            warn!("Timeout waiting for carrier on {} (continuing anyway)", self.interface);
                            break;
                        }
                        tokio::time::sleep(poll_interval).await;
                    }

                    Ok(())
                } else {
                    let stderr = String::from_utf8_lossy(&result.stderr);
                    warn!("Failed to bring up interface {}: {}", self.interface, stderr);
                    Err(DhcpClientError::Network(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Failed to bring up interface: {}", stderr)
                    )))
                }
            }
            Ok(Err(e)) => {
                warn!("Failed to execute ip link set up: {}", e);
                Err(DhcpClientError::Network(e))
            }
            Err(_) => {
                warn!("Timeout bringing up interface {} (5 seconds)", self.interface);
                Err(DhcpClientError::Network(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "ip link set up command timed out"
                )))
            }
        }
    }

    /// Apply lease configuration to the interface
    async fn apply_lease(&self, lease: &Dhcpv4Lease) -> Result<()> {
        use tokio::process::Command;

        dhcp_info!("Applying lease configuration to interface {}", self.interface);
        dhcp_info!("  IP: {}", lease.ip_address);
        dhcp_info!("  Netmask: {:?}", lease.subnet_mask);
        dhcp_info!("  Gateway: {:?}", lease.router);
        dhcp_info!("  DNS: {:?}", lease.dns_servers);

        // Calculate CIDR prefix from subnet mask
        let prefix_len = if let Some(mask) = lease.subnet_mask {
            mask.octets().iter().map(|b| b.count_ones()).sum::<u32>()
        } else {
            24 // Default to /24 if no subnet mask provided
        };

        // 1. Try to add the IP address directly (skip flush which can hang)
        dhcp_info!("Setting IP address {}/{} on {}", lease.ip_address, prefix_len, self.interface);
        dhcp_debug!("Executing: ip addr add {}/{} dev {}", lease.ip_address, prefix_len, self.interface);

        // Use timeout to prevent hanging
        let addr_future = Command::new("ip")
            .args(&[
                "addr",
                "add",
                &format!("{}/{}", lease.ip_address, prefix_len),
                "dev",
                &self.interface,
            ])
            .output();

        let addr_output = match tokio::time::timeout(
            std::time::Duration::from_secs(5),
            addr_future
        ).await {
            Ok(Ok(output)) => {
                dhcp_debug!("IP address add command completed, status: {}", output.status);
                output
            }
            Ok(Err(e)) => {
                error!("Failed to execute ip addr add: {}", e);
                return Err(DhcpClientError::Network(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("Failed to execute ip addr add: {}", e)
                )));
            }
            Err(_) => {
                error!("Timeout waiting for ip addr add command (5 seconds)");
                return Err(DhcpClientError::Network(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "ip addr add command timed out after 5 seconds"
                )));
            }
        };

        // If address already exists, delete old IPv4 addresses and retry
        if !addr_output.status.success() {
            let stderr = String::from_utf8_lossy(&addr_output.stderr);
            dhcp_debug!("IP add failed: {}", stderr);

            // Check if it's because address already exists
            if stderr.contains("File exists") || stderr.contains("RTNETLINK answers: File exists") {
                dhcp_info!("Address already exists, removing old IPv4 addresses and retrying");

                // Get list of IPv4 addresses on this interface
                let list_output = Command::new("ip")
                    .args(&["-4", "addr", "show", "dev", &self.interface])
                    .output()
                    .await
                    .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Failed to list IP addresses: {}", e)
                    )))?;

                if list_output.status.success() {
                    let output_str = String::from_utf8_lossy(&list_output.stdout);
                    dhcp_debug!("Current addresses:\n{}", output_str);

                    // Delete each IPv4 address found (best effort)
                    for line in output_str.lines() {
                        if line.trim().starts_with("inet ") {
                            // Extract the address (e.g., "192.168.1.100/24")
                            if let Some(addr_part) = line.trim().split_whitespace().nth(1) {
                                dhcp_info!("Removing old address: {}", addr_part);
                                let _ = Command::new("ip")
                                    .args(&["addr", "del", addr_part, "dev", &self.interface])
                                    .output()
                                    .await;
                            }
                        }
                    }
                }

                // Retry adding the address
                dhcp_info!("Retrying: ip addr add {}/{} dev {}", lease.ip_address, prefix_len, self.interface);
                let retry_output = Command::new("ip")
                    .args(&[
                        "addr",
                        "add",
                        &format!("{}/{}", lease.ip_address, prefix_len),
                        "dev",
                        &self.interface,
                    ])
                    .output()
                    .await
                    .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Failed to execute ip addr add (retry): {}", e)
                    )))?;

                if !retry_output.status.success() {
                    let retry_stderr = String::from_utf8_lossy(&retry_output.stderr);
                    error!("Failed to set IP address after retry. stderr: {}", retry_stderr);
                    return Err(DhcpClientError::Network(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Failed to set IP address: {}", retry_stderr)
                    )));
                }
            } else {
                // Some other error
                error!("Failed to set IP address. stderr: {}", stderr);
                return Err(DhcpClientError::Network(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("Failed to set IP address: {}", stderr)
                )));
            }
        }

        dhcp_info!("✓ IP address {}/{} set successfully on {}", lease.ip_address, prefix_len, self.interface);

        // 3. Bring interface up
        dhcp_info!("Bringing interface {} up", self.interface);
        dhcp_debug!("Executing: ip link set {} up", self.interface);

        let up_future = Command::new("ip")
            .args(&["link", "set", &self.interface, "up"])
            .output();

        let up_output = match tokio::time::timeout(
            std::time::Duration::from_secs(5),
            up_future
        ).await {
            Ok(Ok(output)) => {
                dhcp_debug!("Interface up command completed, status: {}", output.status);
                output
            }
            Ok(Err(e)) => {
                error!("Failed to execute ip link set up: {}", e);
                return Err(DhcpClientError::Network(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("Failed to bring interface up: {}", e)
                )));
            }
            Err(_) => {
                error!("Timeout waiting for ip link set up command (5 seconds)");
                return Err(DhcpClientError::Network(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "ip link set up command timed out after 5 seconds"
                )));
            }
        };

        if !up_output.status.success() {
            let stderr = String::from_utf8_lossy(&up_output.stderr);
            error!("Failed to bring interface up: {}", stderr);
            return Err(DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to bring interface up: {}", stderr)
            )));
        }

        dhcp_info!("✓ Interface {} is up", self.interface);

        // 4. Set default gateway if provided
        if let Some(gateway) = lease.router {
            dhcp_info!("Setting default gateway to {}", gateway);

            // First, delete existing default routes (best effort)
            let _ = Command::new("ip")
                .args(&["route", "del", "default"])
                .output()
                .await;

            // Add new default route
            let route_output = Command::new("ip")
                .args(&[
                    "route",
                    "add",
                    "default",
                    "via",
                    &gateway.to_string(),
                    "dev",
                    &self.interface,
                ])
                .output()
                .await
                .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("Failed to set default route: {}", e)
                )))?;

            if !route_output.status.success() {
                let stderr = String::from_utf8_lossy(&route_output.stderr);
                warn!("Failed to set default route (non-fatal): {}", stderr);
            }
        }

        // 5. Update DNS servers in /etc/resolv.conf
        if !lease.dns_servers.is_empty() {
            dhcp_info!("Updating DNS servers in /etc/resolv.conf");
            if let Err(e) = self.update_resolv_conf(lease).await {
                warn!("Failed to update /etc/resolv.conf (non-fatal): {}", e);
            }
        }

        info!("✓ Successfully applied lease configuration to {}", self.interface);
        Ok(())
    }

    /// Update /etc/resolv.conf with DNS servers
    /// Security: All values are sanitized to prevent injection attacks
    async fn update_resolv_conf(&self, lease: &Dhcpv4Lease) -> Result<()> {
        use tokio::fs;
        use crate::security::{sanitize_domain_name, sanitize_resolv_conf_value};

        let mut content = String::new();
        content.push_str(&format!("# Generated by crdhcpc for {}\n", self.interface));

        // Add domain name if provided (with sanitization)
        if let Some(domain) = &lease.domain_name {
            // Validate domain name per RFC 1123
            if let Some(safe_domain) = sanitize_domain_name(domain) {
                content.push_str(&format!("domain {}\n", safe_domain));
                content.push_str(&format!("search {}\n", safe_domain));
            } else {
                warn!("Rejecting invalid domain name from DHCP: {:?}",
                      sanitize_resolv_conf_value(domain).unwrap_or_else(|| "[unprintable]".to_string()));
            }
        }

        // Add DNS servers (IP addresses are already validated by Ipv4Addr parsing)
        // Ipv4Addr::to_string() produces safe output (e.g., "192.168.1.1")
        for dns in &lease.dns_servers {
            content.push_str(&format!("nameserver {}\n", dns));
        }

        // Only write if we have at least one nameserver
        if lease.dns_servers.is_empty() {
            warn!("No valid DNS servers to write to resolv.conf");
            return Ok(());
        }

        // Write to /etc/resolv.conf atomically via temp file
        let temp_path = "/etc/resolv.conf.crdhcpc.tmp";
        dhcp_debug!("Writing DNS configuration to /etc/resolv.conf");

        // Write to temp file first
        fs::write(temp_path, content.as_bytes())
            .await
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to write temp resolv.conf: {}", e)
            )))?;

        // Atomically rename to target
        fs::rename(temp_path, "/etc/resolv.conf")
            .await
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to rename resolv.conf: {}", e)
            )))?;

        info!("✓ Updated /etc/resolv.conf with {} DNS servers", lease.dns_servers.len());
        Ok(())
    }

    /// Release lease
    pub async fn release(&self) -> Result<()> {
        use crate::raw_socket::*;

        info!("Releasing DHCP lease on {}", self.interface);

        // Get current lease
        let lease = self.lease.read().await;
        if let Some(lease) = lease.as_ref() {
            dhcp_info!("Sending DHCP RELEASE for IP {} to server {}",
                      lease.ip_address, lease.server_id);

            let xid = *self.xid.lock().await;

            // Create socket
            let socket = DhcpRawSocket::new(RawSocketType::LinkLayer, Some(&self.interface))
                .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("Failed to create raw socket: {}", e)
                )))?;

            // Build RELEASE packet (using link layer frame)
            let packet = build_dhcp_release_link_frame(
                self.mac_address,
                xid,
                lease.ip_address,
                lease.server_id
            );

            // Send packet (best effort - don't fail if it doesn't work)
            if let Err(e) = socket.send(&packet) {
                warn!("Failed to send DHCP RELEASE: {}", e);
            } else {
                info!("DHCP RELEASE sent for {} on {}", lease.ip_address, self.interface);
            }
        }

        // Clear lease and reset state
        drop(lease);
        *self.lease.write().await = None;
        *self.state.write().await = Dhcpv4State::Init;
        *self.offered_ip.write().await = None;
        *self.selected_server.write().await = None;

        Ok(())
    }

    /// Decline an offered IP address (RFC 2131)
    ///
    /// Sends DHCPDECLINE to inform the server that the offered IP address
    /// is already in use (detected via ARP probe). The client then returns
    /// to INIT state to request a different address.
    pub async fn decline(&self, declined_ip: Ipv4Addr, server_id: Ipv4Addr) -> Result<()> {
        use crate::raw_socket::*;

        info!("Declining DHCP offer {} from server {} on {}",
              declined_ip, server_id, self.interface);

        let xid = *self.xid.lock().await;

        // Create socket
        let socket = DhcpRawSocket::new(RawSocketType::LinkLayer, Some(&self.interface))
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to create raw socket: {}", e)
            )))?;

        // Build DECLINE packet
        let packet = build_dhcp_decline_link_frame(
            self.mac_address,
            xid,
            declined_ip,
            server_id
        );

        // Send packet
        socket.send(&packet)
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to send DHCP DECLINE: {}", e)
            )))?;

        info!("DHCP DECLINE sent for {} on {}", declined_ip, self.interface);

        // Clear stored offer and reset state to INIT
        *self.offered_ip.write().await = None;
        *self.selected_server.write().await = None;
        *self.state.write().await = Dhcpv4State::Init;

        // RFC 2131: Client SHOULD wait minimum of 10 seconds before restarting
        // configuration process (to avoid flooding server with declines)
        dhcp_info!("Waiting 10 seconds before restarting DHCP process (RFC 2131)");
        sleep(Duration::from_secs(10)).await;

        Ok(())
    }

    /// Perform ARP probe to check for IP address conflict (RFC 5227)
    ///
    /// Returns true if the IP address is already in use (conflict detected),
    /// false if the address appears to be available.
    pub async fn arp_probe(&self, ip_address: Ipv4Addr) -> Result<bool> {
        use crate::raw_socket::arp_probe_address;

        dhcp_info!("Performing ARP probe for {} on {}", ip_address, self.interface);

        // RFC 5227 recommends:
        // - PROBE_NUM = 3 probes
        // - PROBE_MIN = 1 second, PROBE_MAX = 2 seconds between probes
        // - ANNOUNCE_WAIT = 2 seconds after last probe
        // We use slightly shorter timeouts for faster DHCP acquisition
        let probe_count = 3;
        let probe_wait_ms = 500;  // 500ms between probes
        let timeout_ms = 1000;    // 1 second total listen time after probes

        // Run ARP probe in blocking context (it uses std::thread::sleep internally)
        let interface = self.interface.clone();
        let mac = self.mac_address;

        let result = tokio::task::spawn_blocking(move || {
            arp_probe_address(&interface, mac, ip_address, probe_count, probe_wait_ms, timeout_ms)
        }).await
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("ARP probe task failed: {}", e)
            )))?
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("ARP probe failed: {}", e)
            )))?;

        if result {
            warn!("ARP conflict detected for {} on {}", ip_address, self.interface);
        } else {
            dhcp_info!("No ARP conflict for {} on {}", ip_address, self.interface);
        }

        Ok(result)
    }
}

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

    #[test]
    fn test_dhcpv4_state_display() {
        assert_eq!(Dhcpv4State::Init.to_string(), "INIT");
        assert_eq!(Dhcpv4State::Bound.to_string(), "BOUND");
    }

    #[test]
    fn test_lease_times() {
        let lease = Dhcpv4Lease {
            ip_address: Ipv4Addr::new(192, 168, 1, 100),
            subnet_mask: Some(Ipv4Addr::new(255, 255, 255, 0)),
            router: Some(Ipv4Addr::new(192, 168, 1, 1)),
            dns_servers: vec![],
            domain_name: None,
            ntp_servers: vec![],
            lease_time: Duration::from_secs(3600),
            renewal_time: Duration::from_secs(1800),
            rebinding_time: Duration::from_secs(3150),
            server_id: Ipv4Addr::new(192, 168, 1, 1),
            acquired_at: SystemTime::now() - Duration::from_secs(3700),
        };

        assert!(lease.is_expired());
        assert!(lease.needs_renewal());
        assert!(lease.needs_rebinding());
    }
}