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
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
//! DHCPv6 client implementation
//!
//! Implements RFC 8415 (DHCPv6)

use super::*;

use std::net::{SocketAddrV6, UdpSocket};
use tokio::time::sleep;

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

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

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

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

// DHCPv6 Constants
const DHCPV6_CLIENT_PORT: u16 = 546;
const DHCPV6_SERVER_PORT: u16 = 547;

// All_DHCP_Relay_Agents_and_Servers multicast address
const ALL_DHCP_RELAY_AGENTS_AND_SERVERS: Ipv6Addr = Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 1, 2);

// DHCPv6 Message Types (RFC 8415)
const DHCPV6_SOLICIT: u8 = 1;
const DHCPV6_ADVERTISE: u8 = 2;
const DHCPV6_REQUEST: u8 = 3;
const DHCPV6_CONFIRM: u8 = 4;
const DHCPV6_RENEW: u8 = 5;
const DHCPV6_REBIND: u8 = 6;
const DHCPV6_REPLY: u8 = 7;
const DHCPV6_RELEASE: u8 = 8;
const DHCPV6_DECLINE: u8 = 9;
const DHCPV6_INFORMATION_REQUEST: u8 = 11;

// DHCPv6 Option Codes (RFC 8415)
const OPTION_CLIENTID: u16 = 1;
const OPTION_SERVERID: u16 = 2;
const OPTION_IA_NA: u16 = 3;
const OPTION_IA_TA: u16 = 4;
const OPTION_IAADDR: u16 = 5;
const OPTION_ORO: u16 = 6;       // Option Request Option
const OPTION_PREFERENCE: u16 = 7;
const OPTION_ELAPSED_TIME: u16 = 8;
const OPTION_STATUS_CODE: u16 = 13;
const OPTION_RAPID_COMMIT: u16 = 14;
const OPTION_DNS_SERVERS: u16 = 23;
const OPTION_DOMAIN_LIST: u16 = 24;
const OPTION_IA_PD: u16 = 25;
const OPTION_IAPREFIX: u16 = 26;

// Status Codes
const STATUS_SUCCESS: u16 = 0;
const STATUS_UNSPEC_FAIL: u16 = 1;
const STATUS_NO_ADDRS_AVAIL: u16 = 2;
const STATUS_NO_BINDING: u16 = 3;
const STATUS_NOT_ON_LINK: u16 = 4;
const STATUS_USE_MULTICAST: u16 = 5;
const STATUS_NO_PREFIX_AVAIL: u16 = 6;

// Authentication Option (RFC 8415 Section 20)
const OPTION_AUTH: u16 = 11;

// Additional DHCPv6 Message Types (RFC 7653 - Active Leasequery)
const DHCPV6_STARTTLS: u8 = 23;

// Authentication Protocols (RFC 8415 Section 20.4)
const AUTH_PROTOCOL_DELAYED: u8 = 2;        // Delayed Authentication (RFC 3315)
const AUTH_PROTOCOL_RECONFIGURE_KEY: u8 = 3; // Reconfigure Key Authentication

// Authentication Algorithms (for Delayed Authentication)
const AUTH_ALGORITHM_HMAC_MD5: u8 = 1;    // HMAC-MD5 (deprecated)
const AUTH_ALGORITHM_HMAC_SHA1: u8 = 2;   // HMAC-SHA1
const AUTH_ALGORITHM_HMAC_SHA256: u8 = 3; // HMAC-SHA256 (recommended)
const AUTH_ALGORITHM_HMAC_SHA384: u8 = 4; // HMAC-SHA384
const AUTH_ALGORITHM_HMAC_SHA512: u8 = 5; // HMAC-SHA512

// Replay Detection Method (RDM)
const RDM_MONOTONIC_COUNTER: u8 = 0; // Monotonically increasing counter

/// DHCPv6 client state
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dhcpv6State {
    Init,
    Solicit,
    Request,
    Confirm,
    Renew,
    Rebind,
    Bound,
}

impl std::fmt::Display for Dhcpv6State {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Init => write!(f, "INIT"),
            Self::Solicit => write!(f, "SOLICIT"),
            Self::Request => write!(f, "REQUEST"),
            Self::Confirm => write!(f, "CONFIRM"),
            Self::Renew => write!(f, "RENEW"),
            Self::Rebind => write!(f, "REBIND"),
            Self::Bound => write!(f, "BOUND"),
        }
    }
}

/// DHCPv6 Identity Association for Non-temporary Addresses (IA_NA)
#[derive(Debug, Clone)]
pub struct Dhcpv6IaNa {
    pub iaid: u32,
    pub addresses: Vec<Ipv6Addr>,
    pub t1: Duration, // Renewal time
    pub t2: Duration, // Rebinding time
    pub preferred_lifetime: Duration,
    pub valid_lifetime: Duration,
    pub acquired_at: SystemTime,
}

impl Dhcpv6IaNa {
    pub fn to_info(&self) -> Dhcpv6IaNaInfo {
        Dhcpv6IaNaInfo {
            addresses: self.addresses.clone(),
            preferred_lifetime: self.preferred_lifetime,
            valid_lifetime: self.valid_lifetime,
            acquired_at: self.acquired_at,
        }
    }

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

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

    pub fn expires_at(&self) -> SystemTime {
        self.acquired_at + self.valid_lifetime
    }

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

/// DHCPv6 Identity Association for Prefix Delegation (IA_PD)
#[derive(Debug, Clone)]
pub struct Dhcpv6IaPd {
    pub iaid: u32,
    pub prefix: Ipv6Addr,
    pub prefix_len: u8,
    pub t1: Duration,
    pub t2: Duration,
    pub preferred_lifetime: Duration,
    pub valid_lifetime: Duration,
    pub acquired_at: SystemTime,
}

impl Dhcpv6IaPd {
    pub fn to_info(&self) -> Dhcpv6IaPdInfo {
        Dhcpv6IaPdInfo {
            prefix: self.prefix,
            prefix_len: self.prefix_len,
            preferred_lifetime: self.preferred_lifetime,
            valid_lifetime: self.valid_lifetime,
            acquired_at: self.acquired_at,
        }
    }
}

/// Server information from ADVERTISE
#[derive(Debug, Clone)]
struct Dhcpv6ServerInfo {
    server_id: Vec<u8>,
    address: Ipv6Addr,
    preference: u8,
    ia_na: Option<Dhcpv6IaNa>,
    ia_pd: Option<Dhcpv6IaPd>,
    dns_servers: Vec<Ipv6Addr>,
    domain_list: Vec<String>,
}

/// DHCPv6 Authentication Context (RFC 8415 Section 20)
#[derive(Debug, Clone)]
pub struct Dhcpv6AuthContext {
    /// Authentication protocol in use
    protocol: u8,
    /// Authentication algorithm
    algorithm: u8,
    /// Pre-shared key (decoded)
    key: Option<Vec<u8>>,
    /// Key ID
    key_id: Option<u32>,
    /// Realm for delayed authentication
    realm: Option<String>,
    /// Replay detection counter
    replay_counter: u64,
    /// Server's last replay counter (for verification)
    server_replay_counter: Option<u64>,
    /// Whether authentication is enabled
    enabled: bool,
    /// Require authentication on server messages
    require_server_auth: bool,
    /// Accept unauthenticated messages (fallback)
    accept_unauthenticated: bool,
}

impl Dhcpv6AuthContext {
    /// Create authentication context from config
    pub fn from_config(config: &Dhcpv6AuthConfig) -> Self {
        let protocol = match config.protocol.as_str() {
            "reconfigure-key" => AUTH_PROTOCOL_RECONFIGURE_KEY,
            _ => AUTH_PROTOCOL_DELAYED,
        };

        let algorithm = match config.algorithm.as_str() {
            "hmac-md5" => AUTH_ALGORITHM_HMAC_MD5,
            "hmac-sha1" => AUTH_ALGORITHM_HMAC_SHA1,
            "hmac-sha384" => AUTH_ALGORITHM_HMAC_SHA384,
            "hmac-sha512" => AUTH_ALGORITHM_HMAC_SHA512,
            _ => AUTH_ALGORITHM_HMAC_SHA256,
        };

        // Decode key from hex or base64
        let key = config.key.as_ref().and_then(|k| {
            // Try hex first
            if let Ok(decoded) = hex::decode(k) {
                return Some(decoded);
            }
            // Try base64
            use base64::Engine;
            if let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(k) {
                return Some(decoded);
            }
            // Try as raw bytes
            if !k.is_empty() {
                return Some(k.as_bytes().to_vec());
            }
            None
        });

        // Generate initial replay counter from current time
        let replay_counter = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        Self {
            protocol,
            algorithm,
            key,
            key_id: config.key_id,
            realm: config.realm.clone(),
            replay_counter,
            server_replay_counter: None,
            enabled: config.enabled,
            require_server_auth: config.require_server_auth,
            accept_unauthenticated: config.accept_unauthenticated,
        }
    }

    /// Increment and return the replay counter
    fn next_replay_counter(&mut self) -> u64 {
        self.replay_counter += 1;
        self.replay_counter
    }

    /// Get the HMAC output length for the current algorithm
    fn hmac_length(&self) -> usize {
        match self.algorithm {
            AUTH_ALGORITHM_HMAC_MD5 => 16,     // MD5 = 128 bits
            AUTH_ALGORITHM_HMAC_SHA1 => 20,    // SHA1 = 160 bits
            AUTH_ALGORITHM_HMAC_SHA256 => 32,  // SHA256 = 256 bits
            AUTH_ALGORITHM_HMAC_SHA384 => 48,  // SHA384 = 384 bits
            AUTH_ALGORITHM_HMAC_SHA512 => 64,  // SHA512 = 512 bits
            _ => 32,
        }
    }

    /// Compute HMAC over the message
    /// For Delayed Authentication, the HMAC is computed over:
    /// - The entire DHCPv6 message with the Authentication Information field set to zeros
    fn compute_hmac(&self, message: &[u8]) -> Option<Vec<u8>> {
        use ring::hmac;

        let key = self.key.as_ref()?;

        let algorithm = match self.algorithm {
            AUTH_ALGORITHM_HMAC_SHA256 => hmac::HMAC_SHA256,
            AUTH_ALGORITHM_HMAC_SHA384 => hmac::HMAC_SHA384,
            AUTH_ALGORITHM_HMAC_SHA512 => hmac::HMAC_SHA512,
            AUTH_ALGORITHM_HMAC_SHA1 => {
                // ring doesn't have SHA1, use SHA256 as fallback with warning
                warn!("HMAC-SHA1 not directly supported by ring, using SHA256");
                hmac::HMAC_SHA256
            }
            AUTH_ALGORITHM_HMAC_MD5 => {
                // MD5 is deprecated and not supported by ring
                warn!("HMAC-MD5 is deprecated and not supported, using SHA256");
                hmac::HMAC_SHA256
            }
            _ => hmac::HMAC_SHA256,
        };

        let signing_key = hmac::Key::new(algorithm, key);
        let tag = hmac::sign(&signing_key, message);
        Some(tag.as_ref().to_vec())
    }

    /// Verify HMAC of received message
    fn verify_hmac(&self, message: &[u8], received_hmac: &[u8]) -> bool {
        use ring::hmac;

        let key = match self.key.as_ref() {
            Some(k) => k,
            None => return false,
        };

        let algorithm = match self.algorithm {
            AUTH_ALGORITHM_HMAC_SHA256 => hmac::HMAC_SHA256,
            AUTH_ALGORITHM_HMAC_SHA384 => hmac::HMAC_SHA384,
            AUTH_ALGORITHM_HMAC_SHA512 => hmac::HMAC_SHA512,
            _ => hmac::HMAC_SHA256,
        };

        let verification_key = hmac::Key::new(algorithm, key);
        hmac::verify(&verification_key, message, received_hmac).is_ok()
    }

    /// Build the Authentication option data
    /// Format (RFC 8415 Section 20.1):
    /// - Protocol (1 byte)
    /// - Algorithm (1 byte)
    /// - RDM (1 byte)
    /// - Replay Detection (8 bytes)
    /// - Authentication Information (variable)
    fn build_auth_option(&mut self, message_without_auth: &[u8]) -> Option<Vec<u8>> {
        if !self.enabled || self.key.is_none() {
            return None;
        }

        let mut auth_data = Vec::new();

        // Protocol
        auth_data.push(self.protocol);

        // Algorithm
        auth_data.push(self.algorithm);

        // RDM (Replay Detection Method)
        auth_data.push(RDM_MONOTONIC_COUNTER);

        // Replay Detection (8 bytes - monotonic counter)
        let replay = self.next_replay_counter();
        auth_data.extend_from_slice(&replay.to_be_bytes());

        // For Delayed Authentication, authentication info contains:
        // - Realm (variable)
        // - Key ID (4 bytes)
        // - HMAC (variable based on algorithm)

        if self.protocol == AUTH_PROTOCOL_DELAYED {
            // Add realm
            if let Some(ref realm) = self.realm {
                auth_data.extend_from_slice(realm.as_bytes());
                auth_data.push(0); // Null terminator
            } else {
                auth_data.push(0); // Empty realm (just null)
            }

            // Add Key ID
            let key_id = self.key_id.unwrap_or(0);
            auth_data.extend_from_slice(&key_id.to_be_bytes());

            // Compute HMAC
            // For HMAC computation, we need to:
            // 1. Build the message with auth option containing zeros for HMAC
            // 2. Compute HMAC over that
            // 3. Replace zeros with actual HMAC

            let hmac_len = self.hmac_length();
            let zeros = vec![0u8; hmac_len];

            // Build temporary auth option with zeros for HMAC
            let mut temp_auth = auth_data.clone();
            temp_auth.extend_from_slice(&zeros);

            // Build full message with this temp auth option
            let mut full_msg = message_without_auth.to_vec();
            // Add auth option header
            full_msg.extend_from_slice(&OPTION_AUTH.to_be_bytes());
            full_msg.extend_from_slice(&(temp_auth.len() as u16).to_be_bytes());
            full_msg.extend_from_slice(&temp_auth);

            // Compute HMAC
            if let Some(hmac) = self.compute_hmac(&full_msg) {
                // Truncate if necessary
                let hmac_to_use = if hmac.len() > hmac_len {
                    &hmac[..hmac_len]
                } else {
                    &hmac
                };
                auth_data.extend_from_slice(hmac_to_use);
            } else {
                return None;
            }
        } else if self.protocol == AUTH_PROTOCOL_RECONFIGURE_KEY {
            // Reconfigure Key authentication
            // Just add the key ID and HMAC
            let key_id = self.key_id.unwrap_or(0);
            auth_data.extend_from_slice(&key_id.to_be_bytes());

            // Compute HMAC over message
            if let Some(hmac) = self.compute_hmac(message_without_auth) {
                auth_data.extend_from_slice(&hmac);
            } else {
                return None;
            }
        }

        Some(auth_data)
    }

    /// Parse and verify Authentication option from received message
    /// Returns (is_valid, replay_counter) if authentication option is present
    fn parse_and_verify_auth(&mut self, message: &[u8], auth_option_data: &[u8]) -> std::result::Result<bool, String> {
        if auth_option_data.len() < 11 {
            return Err("Authentication option too short".to_string());
        }

        let protocol = auth_option_data[0];
        let algorithm = auth_option_data[1];
        let rdm = auth_option_data[2];
        let replay_bytes: [u8; 8] = match auth_option_data[3..11].try_into() {
            Ok(b) => b,
            Err(_) => return Err("Invalid replay detection field".to_string()),
        };
        let replay_counter = u64::from_be_bytes(replay_bytes);

        // Check protocol match
        if protocol != self.protocol {
            return Err(format!("Protocol mismatch: expected {}, got {}", self.protocol, protocol));
        }

        // Check algorithm match
        if algorithm != self.algorithm {
            return Err(format!("Algorithm mismatch: expected {}, got {}", self.algorithm, algorithm));
        }

        // Check RDM
        if rdm != RDM_MONOTONIC_COUNTER {
            return Err(format!("Unsupported RDM: {}", rdm));
        }

        // Check replay counter (must be greater than last seen)
        if let Some(last_counter) = self.server_replay_counter {
            if replay_counter <= last_counter {
                return Err(format!("Replay attack detected: {} <= {}", replay_counter, last_counter));
            }
        }

        // Extract authentication info
        let auth_info = &auth_option_data[11..];

        if self.protocol == AUTH_PROTOCOL_DELAYED {
            // Parse realm, key ID, and HMAC
            // Find null terminator for realm
            let realm_end = match auth_info.iter().position(|&b| b == 0) {
                Some(pos) => pos,
                None => return Err("No realm terminator found".to_string()),
            };

            let _realm = &auth_info[..realm_end];
            let after_realm = &auth_info[realm_end + 1..];

            if after_realm.len() < 4 {
                return Err("Missing key ID".to_string());
            }

            let key_id_bytes: [u8; 4] = match after_realm[..4].try_into() {
                Ok(b) => b,
                Err(_) => return Err("Invalid key ID".to_string()),
            };
            let _key_id = u32::from_be_bytes(key_id_bytes);

            let received_hmac = &after_realm[4..];

            // Verify HMAC
            // Need to reconstruct message with zeros in HMAC field
            let hmac_len = received_hmac.len();

            // Find auth option in original message
            let auth_opt_pos = match self.find_option_position(message, OPTION_AUTH) {
                Some(pos) => pos,
                None => return Err("Cannot find auth option in message".to_string()),
            };

            // Build message with zeros for HMAC
            let mut verify_msg = message.to_vec();
            let hmac_start = auth_opt_pos + 4 + 11 + realm_end + 1 + 4; // option header + protocol+algo+rdm+replay + realm+null + keyid
            if hmac_start + hmac_len <= verify_msg.len() {
                for i in 0..hmac_len {
                    verify_msg[hmac_start + i] = 0;
                }
            }

            if !self.verify_hmac(&verify_msg, received_hmac) {
                return Err("HMAC verification failed".to_string());
            }
        } else {
            // Simple HMAC verification for other protocols
            let received_hmac = auth_info;
            if !self.verify_hmac(message, received_hmac) {
                return Err("HMAC verification failed".to_string());
            }
        }

        // Update replay counter
        self.server_replay_counter = Some(replay_counter);

        Ok(true)
    }

    /// Find option position in message
    fn find_option_position(&self, message: &[u8], option_code: u16) -> Option<usize> {
        if message.len() < 4 {
            return None;
        }

        let mut pos = 4; // Skip message type (1) + transaction ID (3)

        while pos + 4 <= message.len() {
            let opt_code = u16::from_be_bytes([message[pos], message[pos + 1]]);
            let opt_len = u16::from_be_bytes([message[pos + 2], message[pos + 3]]) as usize;

            if opt_code == option_code {
                return Some(pos);
            }

            pos += 4 + opt_len;
        }

        None
    }
}

/// Configuration for DHCPv6 authentication
pub use config::Dhcpv6AuthConfig;

/// Configuration for DHCPv6 TLS
pub use config::Dhcpv6TlsConfig;

/// DHCPv6 TLS Context for STARTTLS support (RFC 7653)
pub struct Dhcpv6TlsContext {
    /// TLS configuration
    config: Dhcpv6TlsConfig,
    /// TLS client configuration (lazy initialized)
    tls_config: Option<Arc<rustls::ClientConfig>>,
    /// Whether TLS has been established
    tls_established: bool,
}

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

impl Dhcpv6TlsContext {
    /// Create a new TLS context from configuration
    pub fn from_config(config: &Dhcpv6TlsConfig) -> Self {
        Self {
            config: config.clone(),
            tls_config: None,
            tls_established: false,
        }
    }

    /// Check if TLS is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Check if TCP should be used
    pub fn use_tcp(&self) -> bool {
        self.config.use_tcp || self.config.enabled
    }

    /// Check if TLS has been established
    pub fn is_tls_established(&self) -> bool {
        self.tls_established
    }

    /// Initialize TLS client configuration
    pub fn init_tls_config(&mut self) -> Result<()> {
        use rustls::ClientConfig;
        use std::fs::File;
        use std::io::BufReader;

        if self.tls_config.is_some() {
            return Ok(());
        }

        let mut root_store = rustls::RootCertStore::empty();

        // Load CA certificates
        if let Some(ref ca_path) = self.config.ca_cert {
            let ca_file = File::open(ca_path)
                .map_err(|e| DhcpClientError::InvalidConfig(
                    format!("Failed to open CA cert file: {}", e)
                ))?;
            let mut ca_reader = BufReader::new(ca_file);
            let certs = rustls_pemfile::certs(&mut ca_reader)
                .collect::<std::result::Result<Vec<_>, _>>()
                .map_err(|e| DhcpClientError::InvalidConfig(
                    format!("Failed to parse CA certs: {}", e)
                ))?;
            for cert in certs {
                root_store.add(cert)
                    .map_err(|e| DhcpClientError::InvalidConfig(
                        format!("Failed to add CA cert: {}", e)
                    ))?;
            }
        } else {
            // Use system root certificates
            root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
        }

        let builder = ClientConfig::builder()
            .with_root_certificates(root_store);

        // Configure client certificate if provided (mutual TLS)
        let tls_config = if let (Some(ref cert_path), Some(ref key_path)) =
            (&self.config.client_cert, &self.config.client_key)
        {
            let cert_file = File::open(cert_path)
                .map_err(|e| DhcpClientError::InvalidConfig(
                    format!("Failed to open client cert: {}", e)
                ))?;
            let mut cert_reader = BufReader::new(cert_file);
            let certs = rustls_pemfile::certs(&mut cert_reader)
                .collect::<std::result::Result<Vec<_>, _>>()
                .map_err(|e| DhcpClientError::InvalidConfig(
                    format!("Failed to parse client certs: {}", e)
                ))?;

            let key_file = File::open(key_path)
                .map_err(|e| DhcpClientError::InvalidConfig(
                    format!("Failed to open client key: {}", e)
                ))?;
            let mut key_reader = BufReader::new(key_file);
            let key = rustls_pemfile::private_key(&mut key_reader)
                .map_err(|e| DhcpClientError::InvalidConfig(
                    format!("Failed to parse client key: {}", e)
                ))?
                .ok_or_else(|| DhcpClientError::InvalidConfig(
                    "No private key found in key file".to_string()
                ))?;

            builder.with_client_auth_cert(certs, key)
                .map_err(|e| DhcpClientError::InvalidConfig(
                    format!("Failed to configure client auth: {}", e)
                ))?
        } else {
            builder.with_no_client_auth()
        };

        self.tls_config = Some(Arc::new(tls_config));
        Ok(())
    }

    /// Get TLS client configuration
    pub fn get_tls_config(&self) -> Option<Arc<rustls::ClientConfig>> {
        self.tls_config.clone()
    }

    /// Mark TLS as established
    pub fn set_tls_established(&mut self, established: bool) {
        self.tls_established = established;
    }

    /// Build STARTTLS message (RFC 7653)
    /// Format: msg-type (1 byte) + transaction-id (3 bytes)
    pub fn build_starttls_message(xid: &[u8; 3]) -> Vec<u8> {
        let mut msg = Vec::with_capacity(4);
        msg.push(DHCPV6_STARTTLS);
        msg.extend_from_slice(xid);
        msg
    }

    /// Parse STARTTLS response
    /// Returns true if server accepts STARTTLS
    pub fn parse_starttls_response(data: &[u8], expected_xid: &[u8; 3]) -> bool {
        if data.len() < 4 {
            return false;
        }

        // Check message type is STARTTLS
        if data[0] != DHCPV6_STARTTLS {
            return false;
        }

        // Check transaction ID matches
        &data[1..4] == expected_xid
    }
}

/// TCP connection wrapper for DHCPv6 over TCP
pub struct Dhcpv6TcpConnection {
    stream: Option<tokio::net::TcpStream>,
    tls_stream: Option<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>,
    server_addr: std::net::SocketAddrV6,
}

impl Dhcpv6TcpConnection {
    /// Create a new TCP connection
    pub async fn connect(server_addr: std::net::SocketAddrV6) -> Result<Self> {
        let stream = tokio::net::TcpStream::connect(server_addr).await
            .map_err(|e| DhcpClientError::Network(e))?;

        Ok(Self {
            stream: Some(stream),
            tls_stream: None,
            server_addr,
        })
    }

    /// Perform STARTTLS upgrade
    pub async fn starttls(
        &mut self,
        tls_config: Arc<rustls::ClientConfig>,
        server_name: &str,
    ) -> Result<()> {
        use tokio_rustls::TlsConnector;

        let stream = self.stream.take()
            .ok_or_else(|| DhcpClientError::InvalidConfig(
                "No TCP stream available for TLS upgrade".to_string()
            ))?;

        let server_name = rustls::pki_types::ServerName::try_from(server_name.to_string())
            .map_err(|_| DhcpClientError::InvalidConfig(
                format!("Invalid server name for TLS: {}", server_name)
            ))?;

        let connector = TlsConnector::from(tls_config);
        let tls_stream = connector.connect(server_name, stream).await
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::ConnectionRefused,
                format!("TLS handshake failed: {}", e)
            )))?;

        self.tls_stream = Some(tls_stream);
        info!("DHCPv6 TLS connection established");
        Ok(())
    }

    /// Send DHCPv6 message over TCP (with or without TLS)
    /// TCP format: 2-byte length prefix + message
    pub async fn send(&mut self, message: &[u8]) -> Result<()> {
        use tokio::io::AsyncWriteExt;

        let len = message.len() as u16;
        let mut buf = Vec::with_capacity(2 + message.len());
        buf.extend_from_slice(&len.to_be_bytes());
        buf.extend_from_slice(message);

        if let Some(ref mut tls_stream) = self.tls_stream {
            tls_stream.write_all(&buf).await
                .map_err(|e| DhcpClientError::Network(e))?;
            tls_stream.flush().await
                .map_err(|e| DhcpClientError::Network(e))?;
        } else if let Some(ref mut stream) = self.stream {
            stream.write_all(&buf).await
                .map_err(|e| DhcpClientError::Network(e))?;
            stream.flush().await
                .map_err(|e| DhcpClientError::Network(e))?;
        } else {
            return Err(DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "No connection available"
            )));
        }

        Ok(())
    }

    /// Receive DHCPv6 message over TCP (with or without TLS)
    pub async fn recv(&mut self, timeout: Duration) -> Result<Vec<u8>> {
        use tokio::io::AsyncReadExt;
        use tokio::time::timeout as tokio_timeout;

        let mut len_buf = [0u8; 2];

        let read_result = if let Some(ref mut tls_stream) = self.tls_stream {
            tokio_timeout(timeout, tls_stream.read_exact(&mut len_buf)).await
        } else if let Some(ref mut stream) = self.stream {
            tokio_timeout(timeout, stream.read_exact(&mut len_buf)).await
        } else {
            return Err(DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "No connection available"
            )));
        };

        match read_result {
            Ok(Ok(_)) => {}
            Ok(Err(e)) => return Err(DhcpClientError::Network(e)),
            Err(_) => return Err(DhcpClientError::Timeout("TCP receive timeout".to_string())),
        }

        let msg_len = u16::from_be_bytes(len_buf) as usize;
        if msg_len > 65535 {
            return Err(DhcpClientError::InvalidMessage(
                format!("Message too large: {} bytes", msg_len)
            ));
        }

        let mut msg_buf = vec![0u8; msg_len];

        let read_result = if let Some(ref mut tls_stream) = self.tls_stream {
            tokio_timeout(timeout, tls_stream.read_exact(&mut msg_buf)).await
        } else if let Some(ref mut stream) = self.stream {
            tokio_timeout(timeout, stream.read_exact(&mut msg_buf)).await
        } else {
            unreachable!()
        };

        match read_result {
            Ok(Ok(_)) => Ok(msg_buf),
            Ok(Err(e)) => Err(DhcpClientError::Network(e)),
            Err(_) => Err(DhcpClientError::Timeout("TCP receive timeout".to_string())),
        }
    }

    /// Check if TLS is active
    pub fn is_tls(&self) -> bool {
        self.tls_stream.is_some()
    }

    /// Close the connection
    pub async fn close(&mut self) {
        use tokio::io::AsyncWriteExt;

        if let Some(ref mut tls_stream) = self.tls_stream {
            let _ = tls_stream.shutdown().await;
        }
        if let Some(ref mut stream) = self.stream {
            let _ = stream.shutdown().await;
        }
        self.tls_stream = None;
        self.stream = None;
    }
}

/// DHCPv6 client
pub struct Dhcpv6Client {
    interface: String,
    mac_address: [u8; 6],
    duid: Vec<u8>,
    state: Arc<RwLock<Dhcpv6State>>,
    config: Dhcpv6Config,
    ia_na: Arc<RwLock<Option<Dhcpv6IaNa>>>,
    ia_pd: Arc<RwLock<Option<Dhcpv6IaPd>>>,
    servers: Arc<RwLock<Vec<DhcpServer>>>,
    security: SecurityContext,
    shutdown: Arc<Mutex<bool>>,
    transaction_id: Arc<Mutex<[u8; 3]>>,
    server_duid: Arc<RwLock<Option<Vec<u8>>>>,
    dns_servers: Arc<RwLock<Vec<Ipv6Addr>>>,
    domain_list: Arc<RwLock<Vec<String>>>,
    iaid: u32,
    /// Authentication context (RFC 8415 Section 20)
    auth_context: Arc<Mutex<Dhcpv6AuthContext>>,
    /// TLS context for STARTTLS (RFC 7653)
    tls_context: Arc<Mutex<Dhcpv6TlsContext>>,
}

impl std::fmt::Debug for Dhcpv6Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Dhcpv6Client")
            .field("interface", &self.interface)
            .field("mac_address", &format!("{: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]))
            .finish()
    }
}

impl Dhcpv6Client {
    /// Create a new DHCPv6 client
    pub fn new(interface: &str, config: Dhcpv6Config, security: SecurityConfig) -> Result<Self> {
        // Validate interface name to prevent command injection
        validate_interface_name(interface)?;

        let mac_address = Self::get_mac_address(interface)?;
        let duid = Self::generate_duid(&mac_address);

        // Generate IAID from interface name hash
        let iaid = Self::generate_iaid(interface);

        // Initialize authentication context
        let auth_context = Dhcpv6AuthContext::from_config(&config.authentication);

        // Initialize TLS context
        let tls_context = Dhcpv6TlsContext::from_config(&config.tls);

        Ok(Self {
            interface: interface.to_string(),
            mac_address,
            duid,
            state: Arc::new(RwLock::new(Dhcpv6State::Init)),
            config,
            ia_na: Arc::new(RwLock::new(None)),
            ia_pd: Arc::new(RwLock::new(None)),
            servers: Arc::new(RwLock::new(Vec::new())),
            security: SecurityContext::new(security),
            shutdown: Arc::new(Mutex::new(false)),
            transaction_id: Arc::new(Mutex::new([0u8; 3])),
            server_duid: Arc::new(RwLock::new(None)),
            dns_servers: Arc::new(RwLock::new(Vec::new())),
            domain_list: Arc::new(RwLock::new(Vec::new())),
            iaid,
            auth_context: Arc::new(Mutex::new(auth_context)),
            tls_context: Arc::new(Mutex::new(tls_context)),
        })
    }

    /// Get MAC address for interface
    fn get_mac_address(interface: &str) -> Result<[u8; 6]> {
        use std::fs;

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

        let mac_str = fs::read_to_string(&mac_path)
            .map_err(|e| DhcpClientError::InterfaceNotFound(
                format!("Failed to read MAC address for {}: {}", interface, e)
            ))?;

        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)
                ))?;
        }

        Ok(mac)
    }

    /// Generate DUID-LLT (Link-layer address plus time)
    fn generate_duid(mac: &[u8; 6]) -> Vec<u8> {
        use std::time::{SystemTime, UNIX_EPOCH};

        let mut duid = Vec::new();

        // DUID Type = 1 (DUID-LLT)
        duid.extend_from_slice(&1u16.to_be_bytes());

        // Hardware type = 1 (Ethernet)
        duid.extend_from_slice(&1u16.to_be_bytes());

        // Time (seconds since Jan 1, 2000 00:00 UTC)
        let epoch_2000 = UNIX_EPOCH + Duration::from_secs(946684800);
        let now = SystemTime::now();
        let time_since = now.duration_since(epoch_2000)
            .unwrap_or(Duration::from_secs(0))
            .as_secs() as u32;
        duid.extend_from_slice(&time_since.to_be_bytes());

        // Link-layer address (MAC)
        duid.extend_from_slice(mac);

        duid
    }

    /// Generate IAID from interface name
    fn generate_iaid(interface: &str) -> u32 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        interface.hash(&mut hasher);
        hasher.finish() as u32
    }

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

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

        Dhcpv6Status {
            interface: self.interface.clone(),
            state: state.to_string(),
            ia_na: ia_na.as_ref().map(|i| i.to_info()),
            ia_pd: ia_pd.as_ref().map(|i| i.to_info()),
            servers: servers.clone(),
        }
    }

    /// Create DHCPv6 UDP socket bound to the interface
    fn create_socket(&self) -> Result<UdpSocket> {
        // Bind to link-local address on the interface
        let bind_addr = SocketAddrV6::new(
            Ipv6Addr::UNSPECIFIED,
            DHCPV6_CLIENT_PORT,
            0,
            self.get_interface_index()?,
        );

        let socket = UdpSocket::bind(bind_addr)
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to bind DHCPv6 socket: {}", e)
            )))?;

        // Set socket options
        socket.set_read_timeout(Some(Duration::from_secs(self.config.timeout)))
            .map_err(|e| DhcpClientError::Network(e))?;

        // Join multicast group
        socket.join_multicast_v6(&ALL_DHCP_RELAY_AGENTS_AND_SERVERS, self.get_interface_index()?)
            .map_err(|e| DhcpClientError::Network(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to join DHCPv6 multicast group: {}", e)
            )))?;

        dhcpv6_debug!("DHCPv6 socket created on {}", self.interface);
        Ok(socket)
    }

    /// Get interface index
    fn get_interface_index(&self) -> Result<u32> {
        use std::ffi::CString;

        let iface_cstr = CString::new(self.interface.as_str())
            .map_err(|_| DhcpClientError::InvalidInterfaceName(
                "Interface name contains null byte".to_string()
            ))?;

        let index = unsafe { libc::if_nametoindex(iface_cstr.as_ptr()) };

        if index == 0 {
            return Err(DhcpClientError::InterfaceNotFound(
                format!("Interface {} not found", self.interface)
            ));
        }

        Ok(index)
    }

    /// Run the DHCPv6 client
    pub async fn run(&self) -> Result<()> {
        info!("========================================");
        info!("Starting DHCPv6 client on {}", self.interface);
        info!("  DUID: {}", hex::encode(&self.duid));
        info!("  IAID: 0x{:08x}", self.iaid);
        info!("========================================");

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

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

            match state {
                Dhcpv6State::Init => {
                    dhcpv6_info!("STATE: INIT -> Sending SOLICIT");

                    match self.do_solicit().await {
                        Ok(Some(server_info)) => {
                            dhcpv6_info!("Received ADVERTISE from server");

                            // Store server DUID
                            *self.server_duid.write().await = Some(server_info.server_id.clone());

                            // Send REQUEST
                            match self.do_request(&server_info).await {
                                Ok(true) => {
                                    *self.state.write().await = Dhcpv6State::Bound;
                                    info!("DHCPv6 lease acquired on {}", self.interface);

                                    // Apply the lease
                                    if let Err(e) = self.apply_lease().await {
                                        error!("Failed to apply DHCPv6 lease: {}", e);
                                    }
                                }
                                Ok(false) => {
                                    warn!("REQUEST failed, restarting");
                                    *self.state.write().await = Dhcpv6State::Init;
                                    sleep(Duration::from_secs(self.config.timeout)).await;
                                }
                                Err(e) => {
                                    warn!("REQUEST error: {}", e);
                                    *self.state.write().await = Dhcpv6State::Init;
                                    sleep(Duration::from_secs(self.config.timeout)).await;
                                }
                            }
                        }
                        Ok(None) => {
                            dhcpv6_info!("No ADVERTISE received, retrying");
                            sleep(Duration::from_secs(self.config.timeout)).await;
                        }
                        Err(e) => {
                            warn!("SOLICIT failed: {}", e);
                            sleep(Duration::from_secs(self.config.timeout)).await;
                        }
                    }
                }
                Dhcpv6State::Solicit | Dhcpv6State::Request => {
                    // These are transient states, go back to Init
                    *self.state.write().await = Dhcpv6State::Init;
                }
                Dhcpv6State::Bound => {
                    // Wait for renewal time
                    if let Some(ia_na) = self.ia_na.read().await.as_ref() {
                        let now = SystemTime::now();
                        let renewal_at = ia_na.renewal_at();

                        if now >= renewal_at {
                            dhcpv6_info!("Renewal time reached, transitioning to RENEW");
                            *self.state.write().await = Dhcpv6State::Renew;
                        } else if ia_na.is_expired() {
                            warn!("Lease expired, returning to INIT");
                            *self.ia_na.write().await = None;
                            *self.state.write().await = Dhcpv6State::Init;
                        } 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 {
                        // No lease, go back to init
                        *self.state.write().await = Dhcpv6State::Init;
                    }
                }
                Dhcpv6State::Renew => {
                    dhcpv6_info!("STATE: RENEW");

                    match self.do_renew().await {
                        Ok(true) => {
                            dhcpv6_info!("Renewal successful");
                            *self.state.write().await = Dhcpv6State::Bound;

                            if let Err(e) = self.apply_lease().await {
                                warn!("Failed to apply renewed lease: {}", e);
                            }
                        }
                        Ok(false) | Err(_) => {
                            // Check if we should rebind
                            if let Some(ia_na) = self.ia_na.read().await.as_ref() {
                                let now = SystemTime::now();
                                if now >= ia_na.rebinding_at() {
                                    dhcpv6_info!("Rebinding time reached, transitioning to REBIND");
                                    *self.state.write().await = Dhcpv6State::Rebind;
                                } else {
                                    // Retry renew
                                    sleep(Duration::from_secs(self.config.timeout)).await;
                                }
                            } else {
                                *self.state.write().await = Dhcpv6State::Init;
                            }
                        }
                    }
                }
                Dhcpv6State::Rebind => {
                    dhcpv6_info!("STATE: REBIND");

                    match self.do_rebind().await {
                        Ok(true) => {
                            dhcpv6_info!("Rebind successful");
                            *self.state.write().await = Dhcpv6State::Bound;

                            if let Err(e) = self.apply_lease().await {
                                warn!("Failed to apply rebound lease: {}", e);
                            }
                        }
                        Ok(false) | Err(_) => {
                            // Check if lease expired
                            if let Some(ia_na) = self.ia_na.read().await.as_ref() {
                                if ia_na.is_expired() {
                                    warn!("Lease expired during rebind, returning to INIT");
                                    *self.ia_na.write().await = None;
                                    *self.state.write().await = Dhcpv6State::Init;
                                } else {
                                    sleep(Duration::from_secs(self.config.timeout)).await;
                                }
                            } else {
                                *self.state.write().await = Dhcpv6State::Init;
                            }
                        }
                    }
                }
                Dhcpv6State::Confirm => {
                    // Confirm is used after link reconnection
                    // For now, just go to Bound
                    *self.state.write().await = Dhcpv6State::Bound;
                }
            }

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

        Ok(())
    }

    /// Send SOLICIT and wait for ADVERTISE
    async fn do_solicit(&self) -> Result<Option<Dhcpv6ServerInfo>> {
        self.security.check_rate_limit(&self.interface).await?;

        // Generate new transaction ID
        let xid: [u8; 3] = rand::random();
        *self.transaction_id.lock().await = xid;

        dhcpv6_info!("Sending DHCPv6 SOLICIT (xid: {:02x}{:02x}{:02x})", xid[0], xid[1], xid[2]);

        // Build SOLICIT message
        let solicit = self.build_solicit_message(&xid);

        // Create socket and send
        let socket = self.create_socket()?;

        let dest = SocketAddrV6::new(
            ALL_DHCP_RELAY_AGENTS_AND_SERVERS,
            DHCPV6_SERVER_PORT,
            0,
            self.get_interface_index()?,
        );

        socket.send_to(&solicit, dest)
            .map_err(|e| DhcpClientError::Network(e))?;

        info!("DHCPv6 SOLICIT sent on {}", self.interface);

        // Wait for ADVERTISE
        let mut buf = [0u8; 1500];
        let timeout = Duration::from_secs(self.config.timeout);
        let start = std::time::Instant::now();

        while start.elapsed() < timeout {
            match socket.recv_from(&mut buf) {
                Ok((size, _src)) => {
                    dhcpv6_debug!("Received {} bytes from {}", size, _src);

                    if let Some(server_info) = self.parse_advertise(&buf[..size], &xid) {
                        dhcpv6_info!("Received valid ADVERTISE");
                        return Ok(Some(server_info));
                    }
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
                    break;
                }
                Err(_e) => {
                    dhcpv6_debug!("Recv error: {}", _e);
                }
            }
        }

        Ok(None)
    }

    /// Send REQUEST and wait for REPLY
    async fn do_request(&self, server_info: &Dhcpv6ServerInfo) -> Result<bool> {
        self.security.check_rate_limit(&self.interface).await?;

        let xid: [u8; 3] = rand::random();
        *self.transaction_id.lock().await = xid;

        dhcpv6_info!("Sending DHCPv6 REQUEST");

        let request = self.build_request_message(&xid, server_info);

        let socket = self.create_socket()?;

        let dest = SocketAddrV6::new(
            ALL_DHCP_RELAY_AGENTS_AND_SERVERS,
            DHCPV6_SERVER_PORT,
            0,
            self.get_interface_index()?,
        );

        socket.send_to(&request, dest)
            .map_err(|e| DhcpClientError::Network(e))?;

        info!("DHCPv6 REQUEST sent on {}", self.interface);

        // Wait for REPLY
        let mut buf = [0u8; 1500];
        let timeout = Duration::from_secs(self.config.timeout);
        let start = std::time::Instant::now();

        while start.elapsed() < timeout {
            match socket.recv_from(&mut buf) {
                Ok((size, _src)) => {
                    if let Some((ia_na, ia_pd, dns, domains)) = self.parse_reply(&buf[..size], &xid) {
                        dhcpv6_info!("Received valid REPLY");

                        // Store lease information
                        if let Some(ia_na) = ia_na {
                            *self.ia_na.write().await = Some(ia_na);
                        }
                        if let Some(ia_pd) = ia_pd {
                            *self.ia_pd.write().await = Some(ia_pd);
                        }
                        *self.dns_servers.write().await = dns;
                        *self.domain_list.write().await = domains;

                        return Ok(true);
                    }
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
                Err(e) if e.kind() == std::io::ErrorKind::TimedOut => break,
                Err(_) => {}
            }
        }

        Ok(false)
    }

    /// Send RENEW message (unicast to server)
    async fn do_renew(&self) -> Result<bool> {
        self.security.check_rate_limit(&self.interface).await?;

        let xid: [u8; 3] = rand::random();
        *self.transaction_id.lock().await = xid;

        let server_duid = self.server_duid.read().await.clone()
            .ok_or_else(|| DhcpClientError::NoLease)?;

        dhcpv6_info!("Sending DHCPv6 RENEW");

        let renew = self.build_renew_message(&xid, &server_duid);

        let socket = self.create_socket()?;

        // RENEW is sent to multicast (could be unicast if server allows)
        let dest = SocketAddrV6::new(
            ALL_DHCP_RELAY_AGENTS_AND_SERVERS,
            DHCPV6_SERVER_PORT,
            0,
            self.get_interface_index()?,
        );

        socket.send_to(&renew, dest)
            .map_err(|e| DhcpClientError::Network(e))?;

        // Wait for REPLY
        let mut buf = [0u8; 1500];
        let timeout = Duration::from_secs(self.config.timeout);
        let start = std::time::Instant::now();

        while start.elapsed() < timeout {
            match socket.recv_from(&mut buf) {
                Ok((size, _)) => {
                    if let Some((ia_na, ia_pd, dns, domains)) = self.parse_reply(&buf[..size], &xid) {
                        if let Some(ia_na) = ia_na {
                            *self.ia_na.write().await = Some(ia_na);
                        }
                        if let Some(ia_pd) = ia_pd {
                            *self.ia_pd.write().await = Some(ia_pd);
                        }
                        *self.dns_servers.write().await = dns;
                        *self.domain_list.write().await = domains;
                        return Ok(true);
                    }
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
                Err(e) if e.kind() == std::io::ErrorKind::TimedOut => break,
                Err(_) => {}
            }
        }

        Ok(false)
    }

    /// Send REBIND message (multicast)
    async fn do_rebind(&self) -> Result<bool> {
        self.security.check_rate_limit(&self.interface).await?;

        let xid: [u8; 3] = rand::random();
        *self.transaction_id.lock().await = xid;

        dhcpv6_info!("Sending DHCPv6 REBIND");

        let rebind = self.build_rebind_message(&xid);

        let socket = self.create_socket()?;

        let dest = SocketAddrV6::new(
            ALL_DHCP_RELAY_AGENTS_AND_SERVERS,
            DHCPV6_SERVER_PORT,
            0,
            self.get_interface_index()?,
        );

        socket.send_to(&rebind, dest)
            .map_err(|e| DhcpClientError::Network(e))?;

        // Wait for REPLY
        let mut buf = [0u8; 1500];
        let timeout = Duration::from_secs(self.config.timeout);
        let start = std::time::Instant::now();

        while start.elapsed() < timeout {
            match socket.recv_from(&mut buf) {
                Ok((size, _)) => {
                    if let Some((ia_na, ia_pd, dns, domains)) = self.parse_reply(&buf[..size], &xid) {
                        if let Some(ia_na) = ia_na {
                            *self.ia_na.write().await = Some(ia_na);
                        }
                        if let Some(ia_pd) = ia_pd {
                            *self.ia_pd.write().await = Some(ia_pd);
                        }
                        *self.dns_servers.write().await = dns;
                        *self.domain_list.write().await = domains;
                        return Ok(true);
                    }
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
                Err(e) if e.kind() == std::io::ErrorKind::TimedOut => break,
                Err(_) => {}
            }
        }

        Ok(false)
    }

    /// Build SOLICIT message
    fn build_solicit_message(&self, xid: &[u8; 3]) -> Vec<u8> {
        let mut msg = Vec::new();

        // Message type (1 byte) + Transaction ID (3 bytes)
        msg.push(DHCPV6_SOLICIT);
        msg.extend_from_slice(xid);

        // Option: Client Identifier (DUID)
        self.add_option(&mut msg, OPTION_CLIENTID, &self.duid);

        // Option: Elapsed Time (initially 0)
        self.add_option(&mut msg, OPTION_ELAPSED_TIME, &[0, 0]);

        // Option: IA_NA (Identity Association for Non-temporary Addresses)
        let ia_na_data = self.build_ia_na_option(None);
        self.add_option(&mut msg, OPTION_IA_NA, &ia_na_data);

        // Option: IA_PD if prefix delegation enabled
        if self.config.prefix_delegation {
            let ia_pd_data = self.build_ia_pd_option(None);
            self.add_option(&mut msg, OPTION_IA_PD, &ia_pd_data);
        }

        // Option: Option Request (ORO)
        let mut oro_data = Vec::new();
        for opt in &self.config.request_options {
            oro_data.extend_from_slice(&opt.to_be_bytes());
        }
        // Always request DNS servers and domain list
        if !self.config.request_options.contains(&OPTION_DNS_SERVERS) {
            oro_data.extend_from_slice(&OPTION_DNS_SERVERS.to_be_bytes());
        }
        if !self.config.request_options.contains(&OPTION_DOMAIN_LIST) {
            oro_data.extend_from_slice(&OPTION_DOMAIN_LIST.to_be_bytes());
        }
        self.add_option(&mut msg, OPTION_ORO, &oro_data);

        // Option: Rapid Commit (if enabled)
        if self.config.rapid_commit {
            self.add_option(&mut msg, OPTION_RAPID_COMMIT, &[]);
        }

        // Add authentication option (must be last)
        self.add_auth_option_blocking(&mut msg);

        msg
    }

    /// Build REQUEST message
    fn build_request_message(&self, xid: &[u8; 3], server_info: &Dhcpv6ServerInfo) -> Vec<u8> {
        let mut msg = Vec::new();

        msg.push(DHCPV6_REQUEST);
        msg.extend_from_slice(xid);

        // Client ID
        self.add_option(&mut msg, OPTION_CLIENTID, &self.duid);

        // Server ID
        self.add_option(&mut msg, OPTION_SERVERID, &server_info.server_id);

        // Elapsed Time
        self.add_option(&mut msg, OPTION_ELAPSED_TIME, &[0, 0]);

        // IA_NA with addresses from ADVERTISE
        if let Some(ref ia_na) = server_info.ia_na {
            let ia_na_data = self.build_ia_na_option(Some(ia_na));
            self.add_option(&mut msg, OPTION_IA_NA, &ia_na_data);
        } else {
            let ia_na_data = self.build_ia_na_option(None);
            self.add_option(&mut msg, OPTION_IA_NA, &ia_na_data);
        }

        // IA_PD if enabled
        if self.config.prefix_delegation {
            if let Some(ref ia_pd) = server_info.ia_pd {
                let ia_pd_data = self.build_ia_pd_option(Some(ia_pd));
                self.add_option(&mut msg, OPTION_IA_PD, &ia_pd_data);
            } else {
                let ia_pd_data = self.build_ia_pd_option(None);
                self.add_option(&mut msg, OPTION_IA_PD, &ia_pd_data);
            }
        }

        // ORO
        let mut oro_data = Vec::new();
        oro_data.extend_from_slice(&OPTION_DNS_SERVERS.to_be_bytes());
        oro_data.extend_from_slice(&OPTION_DOMAIN_LIST.to_be_bytes());
        self.add_option(&mut msg, OPTION_ORO, &oro_data);

        // Add authentication option (must be last)
        self.add_auth_option_blocking(&mut msg);

        msg
    }

    /// Build RENEW message
    fn build_renew_message(&self, xid: &[u8; 3], server_duid: &[u8]) -> Vec<u8> {
        let mut msg = Vec::new();

        msg.push(DHCPV6_RENEW);
        msg.extend_from_slice(xid);

        // Client ID
        self.add_option(&mut msg, OPTION_CLIENTID, &self.duid);

        // Server ID
        self.add_option(&mut msg, OPTION_SERVERID, server_duid);

        // Elapsed Time
        self.add_option(&mut msg, OPTION_ELAPSED_TIME, &[0, 0]);

        // Include current IA_NA
        if let Some(ref ia_na) = *self.ia_na.blocking_read() {
            let ia_na_data = self.build_ia_na_option(Some(ia_na));
            self.add_option(&mut msg, OPTION_IA_NA, &ia_na_data);
        }

        // Include current IA_PD
        if self.config.prefix_delegation {
            if let Some(ref ia_pd) = *self.ia_pd.blocking_read() {
                let ia_pd_data = self.build_ia_pd_option(Some(ia_pd));
                self.add_option(&mut msg, OPTION_IA_PD, &ia_pd_data);
            }
        }

        // Add authentication option (must be last)
        self.add_auth_option_blocking(&mut msg);

        msg
    }

    /// Build REBIND message
    fn build_rebind_message(&self, xid: &[u8; 3]) -> Vec<u8> {
        let mut msg = Vec::new();

        msg.push(DHCPV6_REBIND);
        msg.extend_from_slice(xid);

        // Client ID
        self.add_option(&mut msg, OPTION_CLIENTID, &self.duid);

        // Elapsed Time
        self.add_option(&mut msg, OPTION_ELAPSED_TIME, &[0, 0]);

        // Include current IA_NA
        if let Some(ref ia_na) = *self.ia_na.blocking_read() {
            let ia_na_data = self.build_ia_na_option(Some(ia_na));
            self.add_option(&mut msg, OPTION_IA_NA, &ia_na_data);
        }

        // Include current IA_PD
        if self.config.prefix_delegation {
            if let Some(ref ia_pd) = *self.ia_pd.blocking_read() {
                let ia_pd_data = self.build_ia_pd_option(Some(ia_pd));
                self.add_option(&mut msg, OPTION_IA_PD, &ia_pd_data);
            }
        }

        // Add authentication option (must be last)
        self.add_auth_option_blocking(&mut msg);

        msg
    }

    /// Build RELEASE message
    fn build_release_message(&self, xid: &[u8; 3], server_duid: &[u8]) -> Vec<u8> {
        let mut msg = Vec::new();

        msg.push(DHCPV6_RELEASE);
        msg.extend_from_slice(xid);

        // Client ID
        self.add_option(&mut msg, OPTION_CLIENTID, &self.duid);

        // Server ID
        self.add_option(&mut msg, OPTION_SERVERID, server_duid);

        // Elapsed Time
        self.add_option(&mut msg, OPTION_ELAPSED_TIME, &[0, 0]);

        // Include IA_NA being released
        if let Some(ref ia_na) = *self.ia_na.blocking_read() {
            let ia_na_data = self.build_ia_na_option(Some(ia_na));
            self.add_option(&mut msg, OPTION_IA_NA, &ia_na_data);
        }

        // Include IA_PD being released
        if let Some(ref ia_pd) = *self.ia_pd.blocking_read() {
            let ia_pd_data = self.build_ia_pd_option(Some(ia_pd));
            self.add_option(&mut msg, OPTION_IA_PD, &ia_pd_data);
        }

        // Add authentication option (must be last)
        self.add_auth_option_blocking(&mut msg);

        msg
    }

    /// Build DECLINE message
    fn build_decline_message(&self, xid: &[u8; 3], server_duid: &[u8], addresses: &[Ipv6Addr]) -> Vec<u8> {
        let mut msg = Vec::new();

        msg.push(DHCPV6_DECLINE);
        msg.extend_from_slice(xid);

        // Client ID
        self.add_option(&mut msg, OPTION_CLIENTID, &self.duid);

        // Server ID
        self.add_option(&mut msg, OPTION_SERVERID, server_duid);

        // Elapsed Time
        self.add_option(&mut msg, OPTION_ELAPSED_TIME, &[0, 0]);

        // IA_NA with addresses being declined
        let mut ia_na_data = Vec::new();
        ia_na_data.extend_from_slice(&self.iaid.to_be_bytes());  // IAID
        ia_na_data.extend_from_slice(&0u32.to_be_bytes());  // T1
        ia_na_data.extend_from_slice(&0u32.to_be_bytes());  // T2

        for addr in addresses {
            let mut iaaddr = Vec::new();
            iaaddr.extend_from_slice(&addr.octets());  // Address
            iaaddr.extend_from_slice(&0u32.to_be_bytes());  // Preferred lifetime
            iaaddr.extend_from_slice(&0u32.to_be_bytes());  // Valid lifetime

            // Add IAADDR option to IA_NA
            ia_na_data.extend_from_slice(&OPTION_IAADDR.to_be_bytes());
            ia_na_data.extend_from_slice(&(iaaddr.len() as u16).to_be_bytes());
            ia_na_data.extend_from_slice(&iaaddr);
        }

        self.add_option(&mut msg, OPTION_IA_NA, &ia_na_data);

        // Add authentication option (must be last)
        self.add_auth_option_blocking(&mut msg);

        msg
    }

    /// Build IA_NA option data
    fn build_ia_na_option(&self, existing: Option<&Dhcpv6IaNa>) -> Vec<u8> {
        let mut data = Vec::new();

        // IAID (4 bytes)
        let iaid = existing.map(|i| i.iaid).unwrap_or(self.iaid);
        data.extend_from_slice(&iaid.to_be_bytes());

        // T1 (4 bytes)
        let t1 = existing.map(|i| i.t1.as_secs() as u32).unwrap_or(0);
        data.extend_from_slice(&t1.to_be_bytes());

        // T2 (4 bytes)
        let t2 = existing.map(|i| i.t2.as_secs() as u32).unwrap_or(0);
        data.extend_from_slice(&t2.to_be_bytes());

        // Include IAADDR options if we have addresses
        if let Some(ia_na) = existing {
            for addr in &ia_na.addresses {
                let mut iaaddr = Vec::new();
                iaaddr.extend_from_slice(&addr.octets());
                iaaddr.extend_from_slice(&(ia_na.preferred_lifetime.as_secs() as u32).to_be_bytes());
                iaaddr.extend_from_slice(&(ia_na.valid_lifetime.as_secs() as u32).to_be_bytes());

                data.extend_from_slice(&OPTION_IAADDR.to_be_bytes());
                data.extend_from_slice(&(iaaddr.len() as u16).to_be_bytes());
                data.extend_from_slice(&iaaddr);
            }
        }

        data
    }

    /// Build IA_PD option data
    fn build_ia_pd_option(&self, existing: Option<&Dhcpv6IaPd>) -> Vec<u8> {
        let mut data = Vec::new();

        // IAID (4 bytes) - use different IAID for PD
        let iaid = existing.map(|i| i.iaid).unwrap_or(self.iaid.wrapping_add(1));
        data.extend_from_slice(&iaid.to_be_bytes());

        // T1 (4 bytes)
        let t1 = existing.map(|i| i.t1.as_secs() as u32).unwrap_or(0);
        data.extend_from_slice(&t1.to_be_bytes());

        // T2 (4 bytes)
        let t2 = existing.map(|i| i.t2.as_secs() as u32).unwrap_or(0);
        data.extend_from_slice(&t2.to_be_bytes());

        // Include IAPREFIX option if we have a prefix
        if let Some(ia_pd) = existing {
            let mut iaprefix = Vec::new();
            iaprefix.extend_from_slice(&(ia_pd.preferred_lifetime.as_secs() as u32).to_be_bytes());
            iaprefix.extend_from_slice(&(ia_pd.valid_lifetime.as_secs() as u32).to_be_bytes());
            iaprefix.push(ia_pd.prefix_len);
            iaprefix.extend_from_slice(&ia_pd.prefix.octets());

            data.extend_from_slice(&OPTION_IAPREFIX.to_be_bytes());
            data.extend_from_slice(&(iaprefix.len() as u16).to_be_bytes());
            data.extend_from_slice(&iaprefix);
        }

        data
    }

    /// Add an option to the message
    fn add_option(&self, msg: &mut Vec<u8>, code: u16, data: &[u8]) {
        msg.extend_from_slice(&code.to_be_bytes());
        msg.extend_from_slice(&(data.len() as u16).to_be_bytes());
        msg.extend_from_slice(data);
    }

    /// Add authentication option to a message (async version)
    /// This must be called last, after all other options are added
    async fn add_auth_option(&self, msg: &mut Vec<u8>) {
        let mut auth_ctx = self.auth_context.lock().await;
        if !auth_ctx.enabled {
            return;
        }

        // Build authentication option with HMAC computed over the message
        if let Some(auth_data) = auth_ctx.build_auth_option(msg) {
            self.add_option(msg, OPTION_AUTH, &auth_data);
            dhcpv6_debug!("Added authentication option ({} bytes)", auth_data.len());
        }
    }

    /// Add authentication option to a message (blocking version for sync contexts)
    fn add_auth_option_blocking(&self, msg: &mut Vec<u8>) {
        let mut auth_ctx = self.auth_context.blocking_lock();
        if !auth_ctx.enabled {
            return;
        }

        // Build authentication option with HMAC computed over the message
        if let Some(auth_data) = auth_ctx.build_auth_option(msg) {
            self.add_option(msg, OPTION_AUTH, &auth_data);
            dhcpv6_debug!("Added authentication option ({} bytes)", auth_data.len());
        }
    }

    /// Verify authentication on a received message
    /// Returns Ok(true) if authentication verified, Ok(false) if no auth required/present,
    /// Err if authentication failed
    async fn verify_message_auth(&self, message: &[u8]) -> Result<bool> {
        let mut auth_ctx = self.auth_context.lock().await;

        if !auth_ctx.enabled {
            return Ok(false);
        }

        // Find authentication option in message
        if let Some(auth_opt_data) = self.extract_auth_option(message) {
            match auth_ctx.parse_and_verify_auth(message, &auth_opt_data) {
                Ok(true) => {
                    dhcpv6_debug!("Authentication verified successfully");
                    Ok(true)
                }
                Ok(false) => {
                    warn!("Authentication verification returned false");
                    if auth_ctx.require_server_auth {
                        Err(DhcpClientError::SecurityViolation(
                            "Server authentication failed".to_string()
                        ))
                    } else {
                        Ok(false)
                    }
                }
                Err(e) => {
                    warn!("Authentication verification error: {}", e);
                    if auth_ctx.require_server_auth {
                        Err(DhcpClientError::SecurityViolation(
                            format!("Server authentication error: {}", e)
                        ))
                    } else {
                        Ok(false)
                    }
                }
            }
        } else {
            // No authentication option in message
            if auth_ctx.require_server_auth && !auth_ctx.accept_unauthenticated {
                Err(DhcpClientError::SecurityViolation(
                    "Server message has no authentication".to_string()
                ))
            } else {
                dhcpv6_debug!("No authentication option in server message");
                Ok(false)
            }
        }
    }

    /// Extract authentication option data from message
    fn extract_auth_option(&self, message: &[u8]) -> Option<Vec<u8>> {
        if message.len() < 4 {
            return None;
        }

        let mut pos = 4; // Skip message type (1) + transaction ID (3)

        while pos + 4 <= message.len() {
            let opt_code = u16::from_be_bytes([message[pos], message[pos + 1]]);
            let opt_len = u16::from_be_bytes([message[pos + 2], message[pos + 3]]) as usize;

            if pos + 4 + opt_len > message.len() {
                break;
            }

            if opt_code == OPTION_AUTH {
                return Some(message[pos + 4..pos + 4 + opt_len].to_vec());
            }

            pos += 4 + opt_len;
        }

        None
    }

    /// Parse ADVERTISE message
    fn parse_advertise(&self, data: &[u8], expected_xid: &[u8; 3]) -> Option<Dhcpv6ServerInfo> {
        if data.len() < 4 {
            return None;
        }

        // Check message type
        if data[0] != DHCPV6_ADVERTISE {
            return None;
        }

        // Check transaction ID
        if &data[1..4] != expected_xid {
            dhcpv6_debug!("XID mismatch in ADVERTISE");
            return None;
        }

        // Parse options
        let mut server_id: Option<Vec<u8>> = None;
        let mut preference: u8 = 0;
        let mut ia_na: Option<Dhcpv6IaNa> = None;
        let mut ia_pd: Option<Dhcpv6IaPd> = None;
        let mut dns_servers: Vec<Ipv6Addr> = Vec::new();
        let mut domain_list: Vec<String> = Vec::new();

        let mut i = 4;
        while i + 4 <= data.len() {
            let opt_code = u16::from_be_bytes([data[i], data[i + 1]]);
            let opt_len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
            i += 4;

            if i + opt_len > data.len() {
                break;
            }

            let opt_data = &data[i..i + opt_len];

            match opt_code {
                OPTION_SERVERID => {
                    server_id = Some(opt_data.to_vec());
                }
                OPTION_PREFERENCE => {
                    if opt_len >= 1 {
                        preference = opt_data[0];
                    }
                }
                OPTION_IA_NA => {
                    ia_na = self.parse_ia_na(opt_data);
                }
                OPTION_IA_PD => {
                    ia_pd = self.parse_ia_pd(opt_data);
                }
                OPTION_DNS_SERVERS => {
                    dns_servers = self.parse_dns_servers(opt_data);
                }
                OPTION_DOMAIN_LIST => {
                    domain_list = self.parse_domain_list(opt_data);
                }
                OPTION_STATUS_CODE => {
                    if opt_len >= 2 {
                        let status = u16::from_be_bytes([opt_data[0], opt_data[1]]);
                        if status != STATUS_SUCCESS {
                            dhcpv6_debug!("ADVERTISE contains error status: {}", status);
                            return None;
                        }
                    }
                }
                _ => {
                    dhcpv6_debug!("Unknown option {} (len {})", opt_code, opt_len);
                }
            }

            i += opt_len;
        }

        let server_id = server_id?;

        Some(Dhcpv6ServerInfo {
            server_id,
            address: Ipv6Addr::UNSPECIFIED,  // Will be filled from socket
            preference,
            ia_na,
            ia_pd,
            dns_servers,
            domain_list,
        })
    }

    /// Parse REPLY message
    fn parse_reply(&self, data: &[u8], expected_xid: &[u8; 3]) -> Option<(Option<Dhcpv6IaNa>, Option<Dhcpv6IaPd>, Vec<Ipv6Addr>, Vec<String>)> {
        if data.len() < 4 {
            return None;
        }

        if data[0] != DHCPV6_REPLY {
            return None;
        }

        if &data[1..4] != expected_xid {
            dhcpv6_debug!("XID mismatch in REPLY");
            return None;
        }

        let mut ia_na: Option<Dhcpv6IaNa> = None;
        let mut ia_pd: Option<Dhcpv6IaPd> = None;
        let mut dns_servers: Vec<Ipv6Addr> = Vec::new();
        let mut domain_list: Vec<String> = Vec::new();
        let mut status_ok = true;

        let mut i = 4;
        while i + 4 <= data.len() {
            let opt_code = u16::from_be_bytes([data[i], data[i + 1]]);
            let opt_len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
            i += 4;

            if i + opt_len > data.len() {
                break;
            }

            let opt_data = &data[i..i + opt_len];

            match opt_code {
                OPTION_IA_NA => {
                    ia_na = self.parse_ia_na(opt_data);
                }
                OPTION_IA_PD => {
                    ia_pd = self.parse_ia_pd(opt_data);
                }
                OPTION_DNS_SERVERS => {
                    dns_servers = self.parse_dns_servers(opt_data);
                }
                OPTION_DOMAIN_LIST => {
                    domain_list = self.parse_domain_list(opt_data);
                }
                OPTION_STATUS_CODE => {
                    if opt_len >= 2 {
                        let status = u16::from_be_bytes([opt_data[0], opt_data[1]]);
                        if status != STATUS_SUCCESS {
                            warn!("REPLY contains error status: {}", status);
                            status_ok = false;
                        }
                    }
                }
                _ => {}
            }

            i += opt_len;
        }

        if !status_ok {
            return None;
        }

        Some((ia_na, ia_pd, dns_servers, domain_list))
    }

    /// Parse IA_NA option
    fn parse_ia_na(&self, data: &[u8]) -> Option<Dhcpv6IaNa> {
        if data.len() < 12 {
            return None;
        }

        let iaid = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
        let t1 = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
        let t2 = u32::from_be_bytes([data[8], data[9], data[10], data[11]]);

        let mut addresses = Vec::new();
        let mut preferred_lifetime = Duration::from_secs(0);
        let mut valid_lifetime = Duration::from_secs(0);

        // Parse sub-options (IAADDR)
        let mut i = 12;
        while i + 4 <= data.len() {
            let opt_code = u16::from_be_bytes([data[i], data[i + 1]]);
            let opt_len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
            i += 4;

            if i + opt_len > data.len() {
                break;
            }

            if opt_code == OPTION_IAADDR && opt_len >= 24 {
                let addr_bytes: [u8; 16] = data[i..i + 16].try_into().ok()?;
                let addr = Ipv6Addr::from(addr_bytes);
                preferred_lifetime = Duration::from_secs(
                    u32::from_be_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]) as u64
                );
                valid_lifetime = Duration::from_secs(
                    u32::from_be_bytes([data[i + 20], data[i + 21], data[i + 22], data[i + 23]]) as u64
                );
                addresses.push(addr);
            }

            i += opt_len;
        }

        if addresses.is_empty() {
            return None;
        }

        Some(Dhcpv6IaNa {
            iaid,
            addresses,
            t1: Duration::from_secs(t1 as u64),
            t2: Duration::from_secs(t2 as u64),
            preferred_lifetime,
            valid_lifetime,
            acquired_at: SystemTime::now(),
        })
    }

    /// Parse IA_PD option
    fn parse_ia_pd(&self, data: &[u8]) -> Option<Dhcpv6IaPd> {
        if data.len() < 12 {
            return None;
        }

        let iaid = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
        let t1 = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
        let t2 = u32::from_be_bytes([data[8], data[9], data[10], data[11]]);

        // Parse sub-options (IAPREFIX)
        let mut i = 12;
        while i + 4 <= data.len() {
            let opt_code = u16::from_be_bytes([data[i], data[i + 1]]);
            let opt_len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
            i += 4;

            if i + opt_len > data.len() {
                break;
            }

            if opt_code == OPTION_IAPREFIX && opt_len >= 25 {
                let preferred_lifetime = Duration::from_secs(
                    u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) as u64
                );
                let valid_lifetime = Duration::from_secs(
                    u32::from_be_bytes([data[i + 4], data[i + 5], data[i + 6], data[i + 7]]) as u64
                );
                let prefix_len = data[i + 8];
                let prefix_bytes: [u8; 16] = data[i + 9..i + 25].try_into().ok()?;
                let prefix = Ipv6Addr::from(prefix_bytes);

                return Some(Dhcpv6IaPd {
                    iaid,
                    prefix,
                    prefix_len,
                    t1: Duration::from_secs(t1 as u64),
                    t2: Duration::from_secs(t2 as u64),
                    preferred_lifetime,
                    valid_lifetime,
                    acquired_at: SystemTime::now(),
                });
            }

            i += opt_len;
        }

        None
    }

    /// Parse DNS servers option
    fn parse_dns_servers(&self, data: &[u8]) -> Vec<Ipv6Addr> {
        let mut servers = Vec::new();
        let mut i = 0;

        while i + 16 <= data.len() {
            let addr_bytes: [u8; 16] = data[i..i + 16].try_into().unwrap();
            servers.push(Ipv6Addr::from(addr_bytes));
            i += 16;
        }

        servers
    }

    /// Parse domain search list
    fn parse_domain_list(&self, data: &[u8]) -> Vec<String> {
        // Domain list uses DNS wire format (length-prefixed labels)
        let mut domains = Vec::new();
        let mut i = 0;

        while i < data.len() {
            let mut labels = Vec::new();

            loop {
                if i >= data.len() {
                    break;
                }

                let len = data[i] as usize;
                i += 1;

                if len == 0 {
                    break;
                }

                if i + len > data.len() {
                    break;
                }

                if let Ok(label) = std::str::from_utf8(&data[i..i + len]) {
                    labels.push(label.to_string());
                }
                i += len;
            }

            if !labels.is_empty() {
                domains.push(labels.join("."));
            }
        }

        domains
    }

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

        let ia_na = self.ia_na.read().await;
        let dns_servers = self.dns_servers.read().await;

        if let Some(ref ia_na) = *ia_na {
            for addr in &ia_na.addresses {
                info!("Configuring IPv6 address {} on {}", addr, self.interface);

                // Add IPv6 address
                let output = Command::new("ip")
                    .args(&["-6", "addr", "add", &format!("{}/128", addr), "dev", &self.interface])
                    .output()
                    .await
                    .map_err(|e| DhcpClientError::Network(e))?;

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    if !stderr.contains("File exists") {
                        warn!("Failed to add IPv6 address: {}", stderr);
                    }
                }
            }
        }

        // Update DNS configuration
        if !dns_servers.is_empty() {
            if let Err(e) = self.update_resolv_conf(&dns_servers).await {
                warn!("Failed to update resolv.conf: {}", e);
            }
        }

        info!("✓ DHCPv6 lease applied on {}", self.interface);
        Ok(())
    }

    /// Update /etc/resolv.conf with IPv6 DNS servers
    async fn update_resolv_conf(&self, dns_servers: &[Ipv6Addr]) -> Result<()> {
        use tokio::fs;

        // Read existing content
        let existing = fs::read_to_string("/etc/resolv.conf").await.unwrap_or_default();

        // Filter out old IPv6 nameservers (we'll add new ones)
        let lines: Vec<&str> = existing.lines()
            .filter(|line| {
                if line.starts_with("nameserver ") {
                    let addr = line.trim_start_matches("nameserver ").trim();
                    // Keep IPv4 nameservers
                    !addr.contains(':')
                } else {
                    true
                }
            })
            .collect();

        // Add new IPv6 nameservers
        let mut new_content = String::new();
        new_content.push_str(&format!("# DHCPv6 DNS servers for {}\n", self.interface));
        for dns in dns_servers {
            new_content.push_str(&format!("nameserver {}\n", dns));
        }
        for line in &lines {
            new_content.push_str(line);
            new_content.push('\n');
        }

        // Write atomically
        let temp_path = "/etc/resolv.conf.dhcpv6.tmp";
        fs::write(temp_path, &new_content).await
            .map_err(|e| DhcpClientError::Network(e))?;
        fs::rename(temp_path, "/etc/resolv.conf").await
            .map_err(|e| DhcpClientError::Network(e))?;

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

    /// Renew lease
    pub async fn renew(&self) -> Result<()> {
        info!("Renewing DHCPv6 lease on {}", self.interface);
        *self.state.write().await = Dhcpv6State::Renew;
        Ok(())
    }

    /// Release lease
    pub async fn release(&self) -> Result<()> {
        info!("Releasing DHCPv6 lease on {}", self.interface);

        // Send RELEASE message if we have a server DUID
        if let Some(ref server_duid) = *self.server_duid.read().await {
            let xid: [u8; 3] = rand::random();
            let release = self.build_release_message(&xid, server_duid);

            if let Ok(socket) = self.create_socket() {
                let dest = SocketAddrV6::new(
                    ALL_DHCP_RELAY_AGENTS_AND_SERVERS,
                    DHCPV6_SERVER_PORT,
                    0,
                    self.get_interface_index().unwrap_or(0),
                );

                let _ = socket.send_to(&release, dest);
                info!("DHCPv6 RELEASE sent on {}", self.interface);
            }
        }

        // Clear state
        *self.ia_na.write().await = None;
        *self.ia_pd.write().await = None;
        *self.server_duid.write().await = None;
        *self.dns_servers.write().await = Vec::new();
        *self.domain_list.write().await = Vec::new();
        *self.state.write().await = Dhcpv6State::Init;

        Ok(())
    }

    /// Decline addresses
    pub async fn decline(&self, addresses: &[Ipv6Addr]) -> Result<()> {
        info!("Declining DHCPv6 addresses on {}", self.interface);

        if let Some(ref server_duid) = *self.server_duid.read().await {
            let xid: [u8; 3] = rand::random();
            let decline = self.build_decline_message(&xid, server_duid, addresses);

            if let Ok(socket) = self.create_socket() {
                let dest = SocketAddrV6::new(
                    ALL_DHCP_RELAY_AGENTS_AND_SERVERS,
                    DHCPV6_SERVER_PORT,
                    0,
                    self.get_interface_index().unwrap_or(0),
                );

                let _ = socket.send_to(&decline, dest);
                info!("DHCPv6 DECLINE sent on {}", self.interface);
            }
        }

        // Return to INIT state
        *self.state.write().await = Dhcpv6State::Init;

        Ok(())
    }

    /// Shutdown the client
    pub async fn shutdown(&self) {
        *self.shutdown.lock().await = true;
    }

    /// Perform STARTTLS upgrade on a TCP connection (RFC 7653)
    /// This establishes a TLS-secured DHCPv6 connection
    pub async fn starttls(&self, server_addr: std::net::SocketAddrV6) -> Result<Dhcpv6TcpConnection> {
        let mut tls_ctx = self.tls_context.lock().await;

        if !tls_ctx.is_enabled() {
            return Err(DhcpClientError::InvalidConfig(
                "TLS is not enabled in configuration".to_string()
            ));
        }

        // Initialize TLS configuration if not already done
        tls_ctx.init_tls_config()?;

        info!("Initiating DHCPv6 STARTTLS to {}", server_addr);

        // Connect via TCP
        let mut conn = Dhcpv6TcpConnection::connect(server_addr).await?;

        // Generate transaction ID for STARTTLS
        let xid: [u8; 3] = rand::random();

        // Send STARTTLS message
        let starttls_msg = Dhcpv6TlsContext::build_starttls_message(&xid);
        conn.send(&starttls_msg).await?;

        dhcpv6_debug!("Sent STARTTLS message with XID {:02x}{:02x}{:02x}", xid[0], xid[1], xid[2]);

        // Wait for STARTTLS response
        let timeout = Duration::from_secs(self.config.timeout);
        let response = conn.recv(timeout).await?;

        // Verify STARTTLS response
        if !Dhcpv6TlsContext::parse_starttls_response(&response, &xid) {
            conn.close().await;
            return Err(DhcpClientError::ServerError(
                "Server rejected STARTTLS or invalid response".to_string()
            ));
        }

        dhcpv6_debug!("Server accepted STARTTLS, upgrading to TLS");

        // Get server name for TLS
        let server_name = tls_ctx.config.server_name
            .clone()
            .unwrap_or_else(|| server_addr.ip().to_string());

        // Get TLS config
        let tls_config = tls_ctx.get_tls_config()
            .ok_or_else(|| DhcpClientError::InvalidConfig(
                "TLS configuration not initialized".to_string()
            ))?;

        // Perform TLS handshake
        conn.starttls(tls_config, &server_name).await?;

        tls_ctx.set_tls_established(true);
        info!("DHCPv6 STARTTLS completed successfully");

        Ok(conn)
    }

    /// Check if TLS is enabled
    pub async fn is_tls_enabled(&self) -> bool {
        self.tls_context.lock().await.is_enabled()
    }

    /// Check if TLS has been established
    pub async fn is_tls_established(&self) -> bool {
        self.tls_context.lock().await.is_tls_established()
    }
}

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

    #[test]
    fn test_dhcpv6_state_display() {
        assert_eq!(Dhcpv6State::Init.to_string(), "INIT");
        assert_eq!(Dhcpv6State::Solicit.to_string(), "SOLICIT");
        assert_eq!(Dhcpv6State::Bound.to_string(), "BOUND");
    }

    #[test]
    fn test_generate_duid() {
        let mac = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
        let duid = Dhcpv6Client::generate_duid(&mac);

        // DUID-LLT: type(2) + hwtype(2) + time(4) + mac(6) = 14 bytes
        assert_eq!(duid.len(), 14);

        // Check type = 1 (DUID-LLT)
        assert_eq!(u16::from_be_bytes([duid[0], duid[1]]), 1);

        // Check hardware type = 1 (Ethernet)
        assert_eq!(u16::from_be_bytes([duid[2], duid[3]]), 1);

        // Check MAC at the end
        assert_eq!(&duid[8..14], &mac);
    }

    #[test]
    fn test_generate_iaid() {
        let iaid1 = Dhcpv6Client::generate_iaid("eth0");
        let iaid2 = Dhcpv6Client::generate_iaid("eth1");

        // Different interfaces should produce different IAIDs
        assert_ne!(iaid1, iaid2);

        // Same interface should produce same IAID
        let iaid1_again = Dhcpv6Client::generate_iaid("eth0");
        assert_eq!(iaid1, iaid1_again);
    }

    #[test]
    fn test_auth_context_creation() {
        use config::Dhcpv6AuthConfig;

        // Test default (disabled) config
        let config = Dhcpv6AuthConfig::default();
        let auth_ctx = Dhcpv6AuthContext::from_config(&config);
        assert!(!auth_ctx.enabled);
        assert!(auth_ctx.key.is_none());

        // Test enabled config with hex key
        let config = Dhcpv6AuthConfig {
            enabled: true,
            protocol: "delayed".to_string(),
            algorithm: "hmac-sha256".to_string(),
            key: Some("0102030405060708090a0b0c0d0e0f10".to_string()),
            key_id: Some(1),
            realm: Some("example.com".to_string()),
            require_server_auth: false,
            accept_unauthenticated: true,
        };
        let auth_ctx = Dhcpv6AuthContext::from_config(&config);
        assert!(auth_ctx.enabled);
        assert!(auth_ctx.key.is_some());
        assert_eq!(auth_ctx.key.as_ref().unwrap().len(), 16);
        assert_eq!(auth_ctx.protocol, AUTH_PROTOCOL_DELAYED);
        assert_eq!(auth_ctx.algorithm, AUTH_ALGORITHM_HMAC_SHA256);
    }

    #[test]
    fn test_auth_context_hmac() {
        use config::Dhcpv6AuthConfig;

        let config = Dhcpv6AuthConfig {
            enabled: true,
            protocol: "delayed".to_string(),
            algorithm: "hmac-sha256".to_string(),
            key: Some("secret_key_for_testing_12345678".to_string()),
            key_id: Some(1),
            realm: None,
            require_server_auth: false,
            accept_unauthenticated: true,
        };
        let auth_ctx = Dhcpv6AuthContext::from_config(&config);

        // Test HMAC computation
        let test_message = b"Test DHCPv6 message data";
        let hmac = auth_ctx.compute_hmac(test_message);
        assert!(hmac.is_some());
        let hmac = hmac.unwrap();
        assert_eq!(hmac.len(), 32); // SHA256 produces 32 bytes

        // Same message should produce same HMAC
        let hmac2 = auth_ctx.compute_hmac(test_message).unwrap();
        assert_eq!(hmac, hmac2);

        // Different message should produce different HMAC
        let hmac3 = auth_ctx.compute_hmac(b"Different message").unwrap();
        assert_ne!(hmac, hmac3);
    }

    #[test]
    fn test_auth_option_building() {
        use config::Dhcpv6AuthConfig;

        let config = Dhcpv6AuthConfig {
            enabled: true,
            protocol: "delayed".to_string(),
            algorithm: "hmac-sha256".to_string(),
            key: Some("test_key_123456789012345678901234".to_string()),
            key_id: Some(42),
            realm: Some("test.local".to_string()),
            require_server_auth: false,
            accept_unauthenticated: true,
        };
        let mut auth_ctx = Dhcpv6AuthContext::from_config(&config);

        // Build a test message (SOLICIT-like)
        let test_msg = vec![
            DHCPV6_SOLICIT, 0x01, 0x02, 0x03,  // Message type + XID
            0x00, 0x01, 0x00, 0x04, 0xde, 0xad, 0xbe, 0xef,  // Client ID option (fake)
        ];

        let auth_option = auth_ctx.build_auth_option(&test_msg);
        assert!(auth_option.is_some());

        let auth_data = auth_option.unwrap();
        // Check protocol
        assert_eq!(auth_data[0], AUTH_PROTOCOL_DELAYED);
        // Check algorithm
        assert_eq!(auth_data[1], AUTH_ALGORITHM_HMAC_SHA256);
        // Check RDM
        assert_eq!(auth_data[2], RDM_MONOTONIC_COUNTER);
        // Replay detection (8 bytes) starts at offset 3
        // Realm starts at offset 11, followed by null terminator
        // Key ID (4 bytes) follows
        // HMAC (32 bytes for SHA256) at the end
    }

    #[test]
    fn test_tls_context_creation() {
        use config::Dhcpv6TlsConfig;

        // Test default (disabled) config
        let config = Dhcpv6TlsConfig::default();
        let tls_ctx = Dhcpv6TlsContext::from_config(&config);
        assert!(!tls_ctx.is_enabled());
        assert!(!tls_ctx.use_tcp());
        assert!(!tls_ctx.is_tls_established());

        // Test enabled config
        let config = Dhcpv6TlsConfig {
            enabled: true,
            use_tcp: true,
            require_tls: true,
            verify_server: true,
            server_name: Some("dhcp.example.com".to_string()),
            ca_cert: None,
            client_cert: None,
            client_key: None,
            min_version: "1.3".to_string(),
            tcp_port: 547,
        };
        let tls_ctx = Dhcpv6TlsContext::from_config(&config);
        assert!(tls_ctx.is_enabled());
        assert!(tls_ctx.use_tcp());
    }

    #[test]
    fn test_starttls_message_building() {
        let xid = [0x12, 0x34, 0x56];

        let msg = Dhcpv6TlsContext::build_starttls_message(&xid);

        // STARTTLS message: type (1 byte) + XID (3 bytes) = 4 bytes
        assert_eq!(msg.len(), 4);

        // Check message type is STARTTLS (23)
        assert_eq!(msg[0], DHCPV6_STARTTLS);

        // Check XID
        assert_eq!(&msg[1..4], &xid);
    }

    #[test]
    fn test_starttls_response_parsing() {
        let xid = [0xAB, 0xCD, 0xEF];

        // Valid STARTTLS response
        let valid_response = vec![DHCPV6_STARTTLS, 0xAB, 0xCD, 0xEF];
        assert!(Dhcpv6TlsContext::parse_starttls_response(&valid_response, &xid));

        // Wrong message type
        let wrong_type = vec![DHCPV6_SOLICIT, 0xAB, 0xCD, 0xEF];
        assert!(!Dhcpv6TlsContext::parse_starttls_response(&wrong_type, &xid));

        // Wrong XID
        let wrong_xid = vec![DHCPV6_STARTTLS, 0x00, 0x00, 0x00];
        assert!(!Dhcpv6TlsContext::parse_starttls_response(&wrong_xid, &xid));

        // Too short
        let too_short = vec![DHCPV6_STARTTLS, 0xAB, 0xCD];
        assert!(!Dhcpv6TlsContext::parse_starttls_response(&too_short, &xid));

        // Empty
        let empty: Vec<u8> = vec![];
        assert!(!Dhcpv6TlsContext::parse_starttls_response(&empty, &xid));
    }
}