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
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
// Copyright (C) 2011-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>
#include <kea_version.h>

#include <asiolink/io_address.h>
#include <asiolink/io_service.h>
#include <asiolink/io_service_mgr.h>
#include <cc/data.h>
#include <config/http_command_mgr.h>
#include <cryptolink/cryptolink.h>
#include <dhcp/classify.h>
#include <dhcp/dhcp6.h>
#include <dhcp/docsis3_option_defs.h>
#include <dhcp/duid.h>
#include <dhcp/duid_factory.h>
#include <dhcp/hwaddr.h>
#include <dhcp/iface_mgr.h>
#include <dhcp/libdhcp++.h>
#include <dhcp/opaque_data_tuple.h>
#include <dhcp/option.h>
#include <dhcp/option6_client_fqdn.h>
#include <dhcp/option6_ia.h>
#include <dhcp/option6_iaaddr.h>
#include <dhcp/option6_iaprefix.h>
#include <dhcp/option6_status_code.h>
#include <dhcp/option_int_array.h>
#include <dhcp/option_vendor.h>
#include <dhcp/option_vendor_class.h>
#include <dhcp/pkt.h>
#include <dhcp/pkt6.h>
#include <dhcp/std_option_defs.h>
#include <dhcp6/client_handler.h>
#include <dhcp6/dhcp6_log.h>
#include <dhcp6/dhcp6_srv.h>
#include <dhcp6/dhcp6to4_ipc.h>
#include <dhcp_ddns/ncr_io.h>
#include <dhcp_ddns/ncr_msg.h>
#include <dhcpsrv/alloc_engine.h>
#include <dhcpsrv/callout_handle_store.h>
#include <dhcpsrv/cb_ctl_dhcp6.h>
#include <dhcpsrv/cfg_expiration.h>
#include <dhcpsrv/cfg_globals.h>
#include <dhcpsrv/cfg_host_operations.h>
#include <dhcpsrv/cfg_mac_source.h>
#include <dhcpsrv/cfg_option.h>
#include <dhcpsrv/cfg_shared_networks.h>
#include <dhcpsrv/cfg_rsoo.h>
#include <dhcpsrv/cfg_subnets6.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/client_class_def.h>
#include <dhcpsrv/d2_client_cfg.h>
#include <dhcpsrv/d2_client_mgr.h>
#include <dhcpsrv/host.h>
#include <dhcpsrv/host_data_source_factory.h>
#include <dhcpsrv/host_mgr.h>
#include <dhcpsrv/lease.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcpsrv/ncr_generator.h>
#include <dhcpsrv/network_state.h>
#include <dhcpsrv/packet_fuzzer.h>
#include <dhcpsrv/pool.h>
#include <dhcpsrv/resource_handler.h>
#include <dhcpsrv/shared_network.h>
#include <dhcpsrv/srv_config.h>
#include <dhcpsrv/subnet.h>
#include <dhcpsrv/subnet_id.h>
#include <dhcpsrv/subnet_selector.h>
#include <dhcpsrv/utils.h>
#include <eval/evaluate.h>
#include <eval/token.h>
#include <exceptions/exceptions.h>
#include <hooks/callout_handle.h>
#include <hooks/hooks_log.h>
#include <hooks/hooks_manager.h>
#include <hooks/parking_lots.h>
#include <hooks/server_hooks.h>
#include <log/interprocess/interprocess_sync_file.h>
#include <log/log_dbglevels.h>
#include <log/log_formatter.h>
#include <log/logger.h>
#include <log/macros.h>
#include <stats/stats_mgr.h>
#include <util/buffer.h>
#include <util/multi_threading_mgr.h>
#include <util/optional.h>
#include <util/pointer_util.h>
#include <util/readwrite_mutex.h>
#include <util/thread_pool.h>
#include <util/triplet.h>

#include <algorithm><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <cmath><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <cstdint><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <cstdlib><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <exception><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <functional><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <iomanip><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <limits><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <list><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <map><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <memory><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <set><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sstream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <string><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <tuple><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <utility><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <vector><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

#include <boost/algorithm/string/erase.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/algorithm/string/join.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/algorithm/string/split.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/foreach.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/tokenizer.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

using namespace isc;
using namespace isc::asiolink;
using namespace isc::cryptolink;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::dhcp_ddns;
using namespace isc::hooks;
using namespace isc::log;
using namespace isc::log::interprocess;
using namespace isc::stats;
using namespace isc::util;
using namespace std;
namespace ph = std::placeholders;

namespace {

/// Structure that holds registered hook indexes
struct Dhcp6Hooks {
    int hook_index_buffer6_receive_;  ///< index for "buffer6_receive" hook point
    int hook_index_pkt6_receive_;     ///< index for "pkt6_receive" hook point
    int hook_index_subnet6_select_;   ///< index for "subnet6_select" hook point
    int hook_index_leases6_committed_;///< index for "leases6_committed" hook point
    int hook_index_lease6_release_;   ///< index for "lease6_release" hook point
    int hook_index_pkt6_send_;        ///< index for "pkt6_send" hook point
    int hook_index_buffer6_send_;     ///< index for "buffer6_send" hook point
    int hook_index_lease6_decline_;   ///< index for "lease6_decline" hook point
    int hook_index_host6_identifier_; ///< index for "host6_identifier" hook point
    int hook_index_ddns6_update_;     ///< index for "ddns6_update" hook point

    /// Constructor that registers hook points for DHCPv6 engine
    Dhcp6Hooks() {
        hook_index_buffer6_receive_   = HooksManager::registerHook("buffer6_receive");
        hook_index_pkt6_receive_      = HooksManager::registerHook("pkt6_receive");
        hook_index_subnet6_select_    = HooksManager::registerHook("subnet6_select");
        hook_index_leases6_committed_ = HooksManager::registerHook("leases6_committed");
        hook_index_lease6_release_    = HooksManager::registerHook("lease6_release");
        hook_index_pkt6_send_         = HooksManager::registerHook("pkt6_send");
        hook_index_buffer6_send_      = HooksManager::registerHook("buffer6_send");
        hook_index_lease6_decline_    = HooksManager::registerHook("lease6_decline");
        hook_index_host6_identifier_  = HooksManager::registerHook("host6_identifier");
        hook_index_ddns6_update_      = HooksManager::registerHook("ddns6_update");
    }
};

// Declare a Hooks object. As this is outside any function or method, it
// will be instantiated (and the constructor run) when the module is loaded.
// As a result, the hook indexes will be defined before any method in this
// module is called.
Dhcp6Hooks Hooks;

/// @brief Creates instance of the Status Code option.
///
/// This variant of the function is used when the Status Code option
/// is added as a top-level option. It logs the debug message and
/// includes the information about the client and transaction.
///
/// @param pkt Reference to the client's message.
/// @param status_code Numeric status code.
/// @param status_message Status message.
///
/// @return Pointer to the Status Code option.
OptionPtr
createStatusCode(const Pkt6& pkt, const uint16_t status_code,
                 const std::string& status_message) {
    Option6StatusCodePtr option_status(new Option6StatusCode(status_code,
                                                             status_message));
    LOG_DEBUG(options6_logger, DBG_DHCP6_DETAIL, DHCP6_ADD_GLOBAL_STATUS_CODE)
        .arg(pkt.getLabel())
        .arg(option_status->dataToText());
    return (option_status);
}

/// @brief Creates instance of the Status Code option.
///
/// This variant of the function is used when the Status Code option
/// is added to one of the IA options. It logs the debug message and
/// includes the information about the client and transaction as well
/// as IAID of the IA option.
///
/// @param pkt Reference to the client's message.
/// param ia Reference to the IA option to which the Status Code is
/// being added.
/// @param status_code Numeric status code.
/// @param status_message Status message.
///
/// @return Pointer to the Status Code option.
OptionPtr
createStatusCode(const Pkt6& pkt, const Option6IA& ia, const uint16_t status_code,
                 const std::string& status_message) {
    Option6StatusCodePtr option_status(new Option6StatusCode(status_code,
                                                             status_message));
    LOG_DEBUG(options6_logger, DBG_DHCP6_DETAIL, DHCP6_ADD_STATUS_CODE_FOR_IA)
        .arg(pkt.getLabel())
        .arg(ia.getIAID())
        .arg(option_status->dataToText());
    return (option_status);
}

/// List of statistics which is initialized to 0 during the DHCPv6
/// server startup.
std::set<std::string> dhcp6_statistics = {
    "pkt6-received",
    "pkt6-solicit-received",
    "pkt6-advertise-received",
    "pkt6-request-received",
    "pkt6-reply-received",
    "pkt6-renew-received",
    "pkt6-rebind-received",
    "pkt6-decline-received",
    "pkt6-release-received",
    "pkt6-infrequest-received",
    "pkt6-dhcpv4-query-received",
    "pkt6-dhcpv4-response-received",
    "pkt6-unknown-received",
    "pkt6-sent",
    "pkt6-advertise-sent",
    "pkt6-reply-sent",
    "pkt6-dhcpv4-response-sent",
    "pkt6-parse-failed",
    "pkt6-receive-drop",
    "v6-allocation-fail",
    "v6-allocation-fail-shared-network",
    "v6-allocation-fail-subnet",
    "v6-allocation-fail-no-pools",
    "v6-allocation-fail-classes",
    "v6-ia-na-lease-reuses",
    "v6-ia-pd-lease-reuses",
};

}  // namespace

namespace isc {
namespace dhcp {

const std::string Dhcpv6Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");

Dhcpv6Srv::Dhcpv6Srv(uint16_t server_port, uint16_t client_port)
    : io_service_(new IOService()), server_port_(server_port),
      client_port_(client_port), serverid_(), shutdown_(true),
      alloc_engine_(), name_change_reqs_(),
      network_state_(new NetworkState()),
      cb_control_(new CBControlDHCPv6()) {
    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_START, DHCP6_OPEN_SOCKET)
        .arg(server_port);

    Dhcp6to4Ipc::instance().client_port = client_port;

    // Initialize objects required for DHCP server operation.
    try {
        // Port 0 is used for testing purposes where in most cases we don't
        // rely on the physical interfaces. Therefore, it should be possible
        // to create an object even when there are no usable interfaces.
        if ((server_port > 0) && (IfaceMgr::instance().countIfaces() == 0)) {
            LOG_ERROR(dhcp6_logger, DHCP6_NO_INTERFACES);
            return;
        }

        // Create a DUID instance but do not store it into a file.
        DUIDFactory duid_factory;
        DuidPtr duid = duid_factory.get();
        serverid_.reset(new Option(Option::V6, D6O_SERVERID, duid->getDuid()));

        // Instantiate allocation engine. The number of allocation attempts equal
        // to zero indicates that the allocation engine will use the number of
        // attempts depending on the pool size.
        alloc_engine_.reset(new AllocEngine(0));

        /// @todo call loadLibraries() when handling configuration changes

    } catch (const std::exception &e) {
        LOG_ERROR(dhcp6_logger, DHCP6_SRV_CONSTRUCT_ERROR).arg(e.what());
        return;
    }

    // Initializing all observations with default value
    setPacketStatisticsDefaults();

    // All done, so can proceed
    shutdown_ = false;
}

void Dhcpv6Srv::setPacketStatisticsDefaults() {
    isc::stats::StatsMgr& stats_mgr = isc::stats::StatsMgr::instance();

    // Iterate over set of observed statistics
    for (auto const& it : dhcp6_statistics) {
        // Initialize them with default value 0
        stats_mgr.setValue(it, static_cast<int64_t>(0));
    }
}

Dhcpv6Srv::~Dhcpv6Srv() {
    // Discard any parked packets
    discardPackets();

    try {
        stopD2();
    } catch (const std::exception& ex) {
        // Highly unlikely, but lets Report it but go on
        LOG_ERROR(dhcp6_logger, DHCP6_SRV_D2STOP_ERROR).arg(ex.what());<--- Exception thrown in function declared not to throw exceptions.
    }

    try {
        Dhcp6to4Ipc::instance().close();
    } catch (const std::exception& ex) {
        // Highly unlikely, but lets Report it but go on
        // LOG_ERROR(dhcp6_logger, DHCP6_SRV_DHCP4O6_ERROR).arg(ex.what());
    }

    IfaceMgr::instance().closeSockets();

    // The lease manager was instantiated during DHCPv6Srv configuration,
    // so we should clean up after ourselves.
    LeaseMgrFactory::destroy();

    // Destroy the host manager before hooks unload.
    HostMgr::create();

    // Explicitly unload hooks
    HooksManager::prepareUnloadLibraries();
    if (!HooksManager::unloadLibraries()) {
        auto names = HooksManager::getLibraryNames();
        std::string msg;
        if (!names.empty()) {
            msg = names[0];
            for (size_t i = 1; i < names.size(); ++i) {
                msg += std::string(", ") + names[i];
            }
        }
        LOG_ERROR(dhcp6_logger, DHCP6_SRV_UNLOAD_LIBRARIES_ERROR).arg(msg);
    }
    IOServiceMgr::instance().clearIOServices();
    io_service_->stopAndPoll();
}

void Dhcpv6Srv::shutdown() {
    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_SHUTDOWN_REQUEST);
    shutdown_ = true;
}

Pkt6Ptr Dhcpv6Srv::receivePacket(int timeout) {
    return (IfaceMgr::instance().receive6(timeout));
}

void Dhcpv6Srv::sendPacket(const Pkt6Ptr& packet) {
    IfaceMgr::instance().send(packet);
}

bool
Dhcpv6Srv::testServerID(const Pkt6Ptr& pkt) {
    /// @todo Currently we always check server identifier regardless if
    /// it is allowed in the received message or not (per RFC 8415).
    /// If the server identifier is not allowed in the message, the
    /// sanityCheck function should deal with it.
    OptionPtr server_id = pkt->getOption(D6O_SERVERID);
    if (server_id){
        // Let us test received ServerID if it is same as ServerID
        // which is being used by server
        if (getServerID()->getData() != server_id->getData()){
            LOG_DEBUG(bad_packet6_logger, DBGLVL_PKT_HANDLING, DHCP6_PACKET_DROP_SERVERID_MISMATCH)
                .arg(pkt->getLabel())
                .arg(duidToString(server_id))
                .arg(duidToString(getServerID()));
            return (false);
        }
    }
    // return True if: no serverid received or ServerIDs matching
    return (true);
}

bool
Dhcpv6Srv::testUnicast(const Pkt6Ptr& pkt) const {
    switch (pkt->getType()) {
    case DHCPV6_SOLICIT:
    case DHCPV6_CONFIRM:
    case DHCPV6_REBIND:
    case DHCPV6_INFORMATION_REQUEST:
        if (pkt->relay_info_.empty() && !pkt->getLocalAddr().isV6Multicast()) {
            LOG_DEBUG(bad_packet6_logger, DBGLVL_PKT_HANDLING, DHCP6_PACKET_DROP_UNICAST)
                .arg(pkt->getLabel())
                .arg(pkt->getName());
            return (false);
        }
        break;
    default:
        // do nothing
        ;
    }
    return (true);
}

void
Dhcpv6Srv::setHostIdentifiers(AllocEngine::ClientContext6& ctx) {
    const ConstCfgHostOperationsPtr cfg =
        CfgMgr::instance().getCurrentCfg()->getCfgHostOperations6();
    for (auto const& id_type : cfg->getIdentifierTypes()) {
        switch (id_type) {
        case Host::IDENT_DUID:
            if (ctx.duid_) {
                ctx.addHostIdentifier(id_type, ctx.duid_->getDuid());
            }
            break;

        case Host::IDENT_HWADDR:
            if (ctx.hwaddr_) {
                ctx.addHostIdentifier(id_type, ctx.hwaddr_->hwaddr_);
            }
            break;
        case Host::IDENT_FLEX:
            // At this point the information in the packet has been unpacked into
            // the various packet fields and option objects has been created.
            // Execute callouts registered for host6_identifier.
            if (HooksManager::calloutsPresent(Hooks.hook_index_host6_identifier_)) {
                CalloutHandlePtr callout_handle = getCalloutHandle(ctx.query_);

                Host::IdentifierType type = Host::IDENT_FLEX;
                std::vector<uint8_t> id;

                // Use the RAII wrapper to make sure that the callout handle state is
                // reset when this object goes out of scope. All hook points must do
                // it to prevent possible circular dependency between the callout
                // handle and its arguments.
                ScopedCalloutHandleState callout_handle_state(callout_handle);

                // Pass incoming packet as argument
                callout_handle->setArgument("query6", ctx.query_);
                callout_handle->setArgument("id_type", type);
                callout_handle->setArgument("id_value", id);

                // Call callouts
                HooksManager::callCallouts(Hooks.hook_index_host6_identifier_,
                                           *callout_handle);

                callout_handle->getArgument("id_type", type);
                callout_handle->getArgument("id_value", id);

                if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_CONTINUE) &&
                    !id.empty()) {

                    LOG_DEBUG(packet6_logger, DBGLVL_TRACE_BASIC, DHCP6_FLEX_ID)
                        .arg(ctx.query_->getLabel())
                        .arg(Host::getIdentifierAsText(type, &id[0], id.size()));

                    ctx.addHostIdentifier(type, id);
                }
            }
            break;
        default:
            ;
        }
    }
}

void
Dhcpv6Srv::initContext0(const Pkt6Ptr& query,
                        AllocEngine::ClientContext6& ctx) {
    // Pointer to client's query.
    ctx.query_ = query;

    // DUID.
    ctx.duid_ = query->getClientId();

    // Hardware address.
    ctx.hwaddr_ = getMAC(query);
}

bool
Dhcpv6Srv::earlyGHRLookup(const Pkt6Ptr& query,
                          AllocEngine::ClientContext6& ctx) {
    // First part of context initialization.
    initContext0(query, ctx);

    // Get the early-global-reservations-lookup flag value.
    data::ConstElementPtr egrl = CfgMgr::instance().getCurrentCfg()->
         getConfiguredGlobal(CfgGlobals::EARLY_GLOBAL_RESERVATIONS_LOOKUP);
    if (egrl) {
        ctx.early_global_reservations_lookup_ = egrl->boolValue();
    }

    // Perform early global reservations lookup when wanted.
    if (ctx.early_global_reservations_lookup_) {
        // Get the host identifiers.
        setHostIdentifiers(ctx);

        // Check for global host reservations.
        ConstHostPtr global_host = alloc_engine_->findGlobalReservation(ctx);

        if (global_host && !global_host->getClientClasses6().empty()) {
            // Remove dependent evaluated classes.
            removeDependentEvaluatedClasses(query);

            // Add classes from the global reservations.
            const ClientClasses& classes = global_host->getClientClasses6();
            for (auto const& cclass : classes) {
                query->addClass(cclass);
            }

            // Evaluate classes before KNOWN.
            evaluateClasses(query, false);
        }

        if (global_host) {
            // Add the KNOWN class;
            query->addClass("KNOWN");
            LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASS_ASSIGNED)
                .arg(query->getLabel())
                .arg("KNOWN");

            // Evaluate classes after KNOWN.
            evaluateClasses(query, true);

            // Check the DROP special class.
            if (query->inClass("DROP")) {
                LOG_DEBUG(packet6_logger, DBGLVL_PKT_HANDLING,
                          DHCP6_PACKET_DROP_DROP_CLASS_EARLY)
                    .arg(query->makeLabel(query->getClientId(), nullptr))
                    .arg(query->toText());
                StatsMgr::instance().addValue("pkt6-receive-drop",
                                              static_cast<int64_t>(1));
                return (false);
            }

            // Store the reservation.
            ctx.hosts_[SUBNET_ID_GLOBAL] = global_host;
        }
    }

    return (true);
}

void
Dhcpv6Srv::initContext(AllocEngine::ClientContext6& ctx, bool& drop) {
    // Sanity check.
    if (!ctx.query_) {
        drop = true;
        return;
    }
    ctx.fwd_dns_update_ = false;
    ctx.rev_dns_update_ = false;
    ctx.hostname_ = "";
    ctx.callout_handle_ = getCalloutHandle(ctx.query_);

    // Collect host identifiers if host reservations enabled. The identifiers
    // are stored in order of preference. The server will use them in that
    // order to search for host reservations.
    SharedNetwork6Ptr sn;
    if (ctx.subnet_) {
        // Before we can check for static reservations, we need to prepare
        // a set of identifiers to be used for this.
        if (!ctx.early_global_reservations_lookup_) {
            setHostIdentifiers(ctx);
        }

        // Find host reservations using specified identifiers.
        alloc_engine_->findReservation(ctx);

        // Get shared network to see if it is set for a subnet.
        ctx.subnet_->getSharedNetwork(sn);
    }

    // Global host reservations are independent of a selected subnet. If the
    // global reservations contain client classes we should use them in case
    // they are meant to affect pool selection. Also, if the subnet does not
    // belong to a shared network we can use the reserved client classes
    // because there is no way our subnet could change. Such classes may
    // affect selection of a pool within the selected subnet.
    auto global_host = ctx.globalHost();
    auto current_host = ctx.currentHost();
    if ((!ctx.early_global_reservations_lookup_ &&
         global_host && !global_host->getClientClasses6().empty()) ||
        (!sn && current_host && !current_host->getClientClasses6().empty())) {
        // We have already evaluated client classes and some of them may
        // be in conflict with the reserved classes. Suppose there are
        // two classes defined in the server configuration: first_class
        // and second_class and the test for the second_class it looks
        // like this: "not member('first_class')". If the first_class
        // initially evaluates to false, the second_class evaluates to
        // true. If the first_class is now set within the hosts reservations
        // and we don't remove the previously evaluated second_class we'd
        // end up with both first_class and second_class evaluated to
        // true. In order to avoid that, we have to remove the classes
        // evaluated in the first pass and evaluate them again. As
        // a result, the first_class set via the host reservation will
        // replace the second_class because the second_class will this
        // time evaluate to false as desired.
        removeDependentEvaluatedClasses(ctx.query_);
        setReservedClientClasses(ctx.query_, ctx);
        evaluateClasses(ctx.query_, false);
    }

    // Set KNOWN builtin class if something was found, UNKNOWN if not.
    if (!ctx.hosts_.empty()) {
        ctx.query_->addClass("KNOWN");
        LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASS_ASSIGNED)
          .arg(ctx.query_->getLabel())
          .arg("KNOWN");
    } else {
        ctx.query_->addClass("UNKNOWN");
        LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASS_ASSIGNED)
          .arg(ctx.query_->getLabel())
          .arg("UNKNOWN");
    }

    // Perform second pass of classification.
    evaluateClasses(ctx.query_, true);

    const ClientClasses& classes = ctx.query_->getClasses();
    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED_AFTER_SUBNET_SELECTION)
        .arg(ctx.query_->getLabel())
        .arg(classes.toText());

    // Check the DROP special class.
    if (ctx.query_->inClass("DROP")) {
        LOG_DEBUG(packet6_logger, DBGLVL_PKT_HANDLING, DHCP6_PACKET_DROP_DROP_CLASS2)
            .arg(ctx.query_->makeLabel(ctx.query_->getClientId(), 0))
            .arg(ctx.query_->toText());
        StatsMgr::instance().addValue("pkt6-receive-drop",
                                      static_cast<int64_t>(1));
        drop = true;
    }
}

int
Dhcpv6Srv::run() {
#ifdef HAVE_AFL
    // Get the values of the environment variables used to control the
    // fuzzing.

    // Specfies the interface to be used to pass packets from AFL to Kea.
    const char* interface = getenv("KEA_AFL_INTERFACE");
    if (!interface) {
        isc_throw(FuzzInitFail, "no fuzzing interface has been set");
    }

    // The address on the interface to be used.
    const char* address = getenv("KEA_AFL_ADDRESS");
    if (!address) {
        isc_throw(FuzzInitFail, "no fuzzing address has been set");
    }

    // Set up structures needed for fuzzing.
    PacketFuzzer fuzzer(server_port_, interface, address);

    // The next line is needed as a signature for AFL to recognize that we are
    // running persistent fuzzing.  This has to be in the main image file.
    while (__AFL_LOOP(fuzzer.maxLoopCount())) {
        // Read from stdin and put the data read into an address/port on which
        // Kea is listening, read for Kea to read it via asynchronous I/O.
        fuzzer.transfer();
#else
    while (!shutdown_) {
#endif // HAVE_AFL
        try {
            runOne();
            // Handle events registered by hooks using external IOService objects.
            IOServiceMgr::instance().pollIOServices();
            getIOService()->poll();
            config::HttpCommandMgr::instance().garbageCollectListeners();
        } catch (const std::exception& e) {
            // General catch-all standard exceptions that are not caught by more
            // specific catches.
            LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_STD_EXCEPTION_MAIN)
                .arg(e.what());

        } catch (...) {
            // General catch-all non-standard exception that are not caught
            // by more specific catches.
            LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_EXCEPTION_MAIN);
        }
    }

    // Stop everything before we change into single-threaded mode.
    MultiThreadingCriticalSection cs;

    // destroying the thread pool
    MultiThreadingMgr::instance().apply(false, 0, 0);

    return (getExitValue());
}

void
Dhcpv6Srv::runOne() {
    // client's message and server's response
    Pkt6Ptr query;

    try {
        // Set select() timeout to 1s. This value should not be modified
        // because it is important that the select() returns control
        // frequently so as the IOService can be polled for ready handlers.
        uint32_t timeout = 1;
        query = receivePacket(timeout);

        // Log if packet has arrived. We can't log the detailed information
        // about the DHCP message because it hasn't been unpacked/parsed
        // yet, and it can't be parsed at this point because hooks will
        // have to process it first. The only information available at this
        // point are: the interface, source address and destination addresses
        // and ports.
        if (query) {
            LOG_DEBUG(packet6_logger, DBG_DHCP6_BASIC, DHCP6_BUFFER_RECEIVED)
                .arg(query->getRemoteAddr().toText())
                .arg(query->getRemotePort())
                .arg(query->getLocalAddr().toText())
                .arg(query->getLocalPort())
                .arg(query->getIface());

            // Log reception of the packet. We need to increase it early, as
            // any failures in unpacking will cause the packet to be dropped.
            // we will increase type specific packets further down the road.
            // See processStatsReceived().
            StatsMgr::instance().addValue("pkt6-received", static_cast<int64_t>(1));
        }

        // We used to log that the wait was interrupted, but this is no longer
        // the case. Our wait time is 1s now, so the lack of query packet more
        // likely means that nothing new appeared within a second, rather than
        // we were interrupted. And we don't want to print a message every
        // second.

    } catch (const SignalInterruptOnSelect&) {
        // Packet reception interrupted because a signal has been received.
        // This is not an error because we might have received a SIGTERM,
        // SIGINT, SIGHUP or SIGCHLD which are handled by the server. For
        // signals that are not handled by the server we rely on the default
        // behavior of the system.
        LOG_DEBUG(packet6_logger, DBG_DHCP6_DETAIL, DHCP6_BUFFER_WAIT_SIGNAL);
    } catch (const std::exception& e) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_RECEIVE_FAIL)
            .arg(e.what());
    }

    // Timeout may be reached or signal received, which breaks select()
    // with no packet received
    if (!query) {
        return;
    }

    // If the DHCP service has been globally disabled, drop the packet.
    if (!network_state_->isServiceEnabled()) {
        LOG_DEBUG(bad_packet6_logger, DBGLVL_PKT_HANDLING, DHCP6_PACKET_DROP_DHCP_DISABLED)
            .arg(query->getLabel());
        return;
    } else {
        if (MultiThreadingMgr::instance().getMode()) {
            query->addPktEvent("mt_queued");
            typedef function<void()> CallBack;
            boost::shared_ptr<CallBack> call_back =
                boost::make_shared<CallBack>(std::bind(&Dhcpv6Srv::processPacketAndSendResponseNoThrow,
                                                       this, query));
            if (!MultiThreadingMgr::instance().getThreadPool().add(call_back)) {
                LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_PACKET_QUEUE_FULL);
            }
        } else {
            processPacketAndSendResponse(query);
        }
    }
}

void
Dhcpv6Srv::processPacketAndSendResponseNoThrow(Pkt6Ptr query) {
    try {
        processPacketAndSendResponse(query);
    } catch (const std::exception& e) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_STD_EXCEPTION)
            .arg(query->getLabel())
            .arg(e.what());
    } catch (...) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_EXCEPTION)
            .arg(query->getLabel());
    }
}

void
Dhcpv6Srv::processPacketAndSendResponse(Pkt6Ptr query) {
    Pkt6Ptr rsp = processPacket(query);
    if (!rsp) {
        return;
    }

    CalloutHandlePtr callout_handle = getCalloutHandle(query);
    processPacketBufferSend(callout_handle, rsp);
}

Pkt6Ptr
Dhcpv6Srv::processPacket(Pkt6Ptr query) {
    query->addPktEvent("process_started");

    // All packets belong to ALL.
    query->addClass("ALL");

    bool skip_unpack = false;

    // The packet has just been received so contains the uninterpreted wire
    // data; execute callouts registered for buffer6_receive.
    if (HooksManager::calloutsPresent(Hooks.hook_index_buffer6_receive_)) {
        CalloutHandlePtr callout_handle = getCalloutHandle(query);

        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        ScopedCalloutHandleState callout_handle_state(callout_handle);

        // Enable copying options from the packet within hook library.
        ScopedEnableOptionsCopy<Pkt6> query6_options_copy(query);

        // Pass incoming packet as argument
        callout_handle->setArgument("query6", query);

        // Call callouts
        HooksManager::callCallouts(Hooks.hook_index_buffer6_receive_, *callout_handle);

        // Callouts decided to skip the next processing step. The next
        // processing step would be to parse the packet, so skip at this
        // stage means that callouts did the parsing already, so server
        // should skip parsing.
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
            LOG_DEBUG(hooks_logger, DBG_DHCP6_DETAIL, DHCP6_HOOK_BUFFER_RCVD_SKIP)
                .arg(query->getRemoteAddr().toText())
                .arg(query->getLocalAddr().toText())
                .arg(query->getIface());
            skip_unpack = true;
        }

        // Callouts decided to drop the received packet
        // The response (rsp) is null so the caller (runOne) will
        // immediately return too.
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
            LOG_DEBUG(hooks_logger, DBGLVL_PKT_HANDLING, DHCP6_HOOK_BUFFER_RCVD_DROP)
                .arg(query->getRemoteAddr().toText())
                .arg(query->getLocalAddr().toText())
                .arg(query->getIface());

            // Not increasing the statistics of the dropped packets because it
            // is the callouts' responsibility to increase it. There are some
            // cases when the callouts may elect to not increase the statistics.
            // For example, packets dropped by the load-balancing algorithm must
            // not increase the statistics.
            return (Pkt6Ptr());
        }

        callout_handle->getArgument("query6", query);
        if (!query) {
            // Please use the status instead of resetting query!
            return (Pkt6Ptr());
        }
    }

    // Unpack the packet information unless the buffer6_receive callouts
    // indicated they did it
    if (!skip_unpack) {
        try {
            LOG_DEBUG(options6_logger, DBG_DHCP6_DETAIL, DHCP6_BUFFER_UNPACK)
                .arg(query->getRemoteAddr().toText())
                .arg(query->getLocalAddr().toText())
                .arg(query->getIface());
            query->unpack();
        } catch (const SkipRemainingOptionsError& e) {
            // An option failed to unpack but we are to attempt to process it
            // anyway.  Log it and let's hope for the best.
            LOG_DEBUG(options6_logger, DBG_DHCP6_DETAIL,
                      DHCP6_PACKET_OPTIONS_SKIPPED)
                .arg(query->getLabel())
                .arg(e.what());
        } catch (const std::exception &e) {
            // Failed to parse the packet.
            LOG_DEBUG(bad_packet6_logger, DBGLVL_PKT_HANDLING, DHCP6_PACKET_DROP_PARSE_FAIL)
                .arg(query->getLabel())
                .arg(query->getRemoteAddr().toText())
                .arg(query->getLocalAddr().toText())
                .arg(query->getIface())
                .arg(e.what())
                .arg(query->makeLabel(query->getClientId(), nullptr));

            // Increase the statistics of parse failures and dropped packets.
            StatsMgr::instance().addValue("pkt6-parse-failed",
                                          static_cast<int64_t>(1));
            StatsMgr::instance().addValue("pkt6-receive-drop",
                                          static_cast<int64_t>(1));
            return (Pkt6Ptr());
        }
    }

    // Classify can emit INFO logs so help to track the query.
    LOG_INFO(dhcp6_logger, DHCP6_QUERY_LABEL)
        .arg(query->getLabel());

    // Update statistics accordingly for received packet.
    processStatsReceived(query);

    // Check if received query carries server identifier matching
    // server identifier being used by the server.
    if (!testServerID(query)) {

        // Increase the statistic of dropped packets.
        StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));
        return (Pkt6Ptr());
    }

    // Check if the received query has been sent to unicast or multicast.
    // The Solicit, Confirm, Rebind and Information Request will be
    // discarded if sent to unicast address.
    if (!testUnicast(query)) {

        // Increase the statistic of dropped packets.
        StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));
        return (Pkt6Ptr());
    }

    // Assign this packet to a class, if possible
    classifyPacket(query);

    LOG_INFO(packet6_logger, DHCP6_PACKET_RECEIVED)
        .arg(query->getLabel())
        .arg(query->getName())
        .arg(static_cast<int>(query->getType()))
        .arg(query->getRemoteAddr())
        .arg(query->getLocalAddr())
        .arg(query->getIface());
    LOG_DEBUG(packet6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_QUERY_DATA)
        .arg(query->getLabel())
        .arg(query->toText());

    // At this point the information in the packet has been unpacked into
    // the various packet fields and option objects has been created.
    // Execute callouts registered for packet6_receive.
    if (HooksManager::calloutsPresent(Hooks.hook_index_pkt6_receive_)) {
        CalloutHandlePtr callout_handle = getCalloutHandle(query);

        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        ScopedCalloutHandleState callout_handle_state(callout_handle);

        // Enable copying options from the packet within hook library.
        ScopedEnableOptionsCopy<Pkt6> query6_options_copy(query);

        // Pass incoming packet as argument
        callout_handle->setArgument("query6", query);

        // Call callouts
        HooksManager::callCallouts(Hooks.hook_index_pkt6_receive_, *callout_handle);

        // Callouts decided to skip the next processing step. The next
        // processing step would be to process the packet, so skip at this
        // stage means drop.
        if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
            (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
            LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_PACKET_RCVD_SKIP)
                .arg(query->getLabel());
            // Not increasing the statistics of the dropped packets because it
            // is the callouts' responsibility to increase it. There are some
            // cases when the callouts may elect to not increase the statistics.
            // For example, packets dropped by the load-balancing algorithm must
            // not increase the statistics.
            return (Pkt6Ptr());
        }

        callout_handle->getArgument("query6", query);
        if (!query) {
            // Please use the status instead of resetting query!
            return (Pkt6Ptr());
        }
    }

    // Reject the message if it doesn't pass the sanity check.
    if (!sanityCheck(query)) {
        return (Pkt6Ptr());
    }

    // Check the DROP special class.
    if (query->inClass("DROP")) {
        LOG_DEBUG(packet6_logger, DBGLVL_PKT_HANDLING, DHCP6_PACKET_DROP_DROP_CLASS)
            .arg(query->makeLabel(query->getClientId(), nullptr))
            .arg(query->toText());
        StatsMgr::instance().addValue("pkt6-receive-drop",
                                      static_cast<int64_t>(1));
        return (Pkt6Ptr());
    }

    return (processDhcp6Query(query));
}

void
Dhcpv6Srv::processDhcp6QueryAndSendResponse(Pkt6Ptr query) {
    try {
        Pkt6Ptr rsp = processDhcp6Query(query);
        if (!rsp) {
            return;
        }

        CalloutHandlePtr callout_handle = getCalloutHandle(query);
        processPacketBufferSend(callout_handle, rsp);
    } catch (const std::exception& e) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_STD_EXCEPTION)
            .arg(query->getLabel())
            .arg(e.what());
    } catch (...) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_EXCEPTION)
            .arg(query->getLabel());
    }
}

Pkt6Ptr
Dhcpv6Srv::processDhcp6Query(Pkt6Ptr query) {
    // Create a client race avoidance RAII handler.
    ClientHandler client_handler;

    // Check for lease modifier queries from the same client being processed.
    if (MultiThreadingMgr::instance().getMode() &&
        ((query->getType() == DHCPV6_SOLICIT) ||
         (query->getType() == DHCPV6_REQUEST) ||
         (query->getType() == DHCPV6_RENEW) ||
         (query->getType() == DHCPV6_REBIND) ||
         (query->getType() == DHCPV6_RELEASE) ||
         (query->getType() == DHCPV6_DECLINE))) {
        ContinuationPtr cont =
            makeContinuation(std::bind(&Dhcpv6Srv::processDhcp6QueryAndSendResponse,
                                       this, query));
        if (!client_handler.tryLock(query, cont)) {
            return (Pkt6Ptr());
        }
    }

    // Let's create a simplified client context here.
    AllocEngine::ClientContext6 ctx;
    if (!earlyGHRLookup(query, ctx)) {
        return (Pkt6Ptr());
    }

    if (query->getType() == DHCPV6_DHCPV4_QUERY) {
        // This call never throws. Should this change, this section must be
        // enclosed in try-catch.
        processDhcp4Query(query);
        return (Pkt6Ptr());
    }

    // Complete the client context initialization.
    bool drop = false;
    ctx.subnet_ = selectSubnet(query, drop);
    if (drop) {
        // Caller will immediately drop the packet so simply return now.
        return (Pkt6Ptr());
    }

    return (processLocalizedQuery6(ctx));
}


void
Dhcpv6Srv::processLocalizedQuery6AndSendResponse(Pkt6Ptr query,
                                                 AllocEngine::ClientContext6& ctx) {
    try {
        Pkt6Ptr rsp = processLocalizedQuery6(ctx);
        if (!rsp) {
            return;
        }

        CalloutHandlePtr callout_handle = getCalloutHandle(query);
        processPacketBufferSend(callout_handle, rsp);
    } catch (const std::exception& e) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_STD_EXCEPTION)
            .arg(query->getLabel())
            .arg(e.what());
    } catch (...) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_EXCEPTION)
            .arg(query->getLabel());
    }
}

void
Dhcpv6Srv::processLocalizedQuery6AndSendResponse(Pkt6Ptr query) {
    // Initialize context.
    AllocEngine::ClientContext6 ctx;
    initContext0(query, ctx);

    // Subnet is cached in the callout context associated to the query.
    try {
        CalloutHandlePtr callout_handle = getCalloutHandle(query);
        callout_handle->getContext("subnet6", ctx.subnet_);
    } catch (const Exception&) {
        // No subnet, leave it to null...
    }

    processLocalizedQuery6AndSendResponse(query, ctx);
}

Pkt6Ptr
Dhcpv6Srv::processLocalizedQuery6(AllocEngine::ClientContext6& ctx) {
    Pkt6Ptr query = ctx.query_;
    bool drop  = false;
    initContext(ctx, drop);
    // Stop here if initContext decided to drop the packet.
    if (drop) {
        return (Pkt6Ptr());
    }

    Pkt6Ptr rsp;
    try {
        switch (query->getType()) {
        case DHCPV6_SOLICIT:
            rsp = processSolicit(ctx);
            break;

        case DHCPV6_REQUEST:
            rsp = processRequest(ctx);
            break;

        case DHCPV6_RENEW:
            rsp = processRenew(ctx);
            break;

        case DHCPV6_REBIND:
            rsp = processRebind(ctx);
            break;

        case DHCPV6_CONFIRM:
            rsp = processConfirm(ctx);
            break;

        case DHCPV6_RELEASE:
            rsp = processRelease(ctx);
            break;

        case DHCPV6_DECLINE:
            rsp = processDecline(ctx);
            break;

        case DHCPV6_INFORMATION_REQUEST:
            rsp = processInfRequest(ctx);
            break;

        default:
            return (rsp);
        }

    } catch (const std::exception& e) {

        // Catch-all exception (at least for ones based on the isc Exception
        // class, which covers more or less all that are explicitly raised
        // in the Kea code), but also the standard one, which may possibly be
        // thrown from boost code.  Just log the problem and ignore the packet.
        // (The problem is logged as a debug message because debug is
        // disabled by default - it prevents a DDOS attack based on the
        // sending of problem packets.)
        LOG_DEBUG(bad_packet6_logger, DBG_DHCP6_BASIC, DHCP6_PACKET_PROCESS_FAIL)
            .arg(query->getLabel())
            .arg(query->getName())
            .arg(query->getRemoteAddr().toText())
            .arg(e.what());

        // Increase the statistic of dropped packets.
        StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));
    }

    if (!rsp) {
        return (rsp);
    }

    // Process relay-supplied options. It is important to call this very
    // late in the process, because we now have all the options the
    // server wanted to send already set. This is important, because
    // RFC6422, section 6 states:
    //
    //   The server SHOULD discard any options that appear in the RSOO
    //   for which it already has one or more candidates.
    //
    // So we ignore any RSOO options if there's an option with the same
    // code already present.
    processRSOO(query, rsp);

    rsp->setRemoteAddr(query->getRemoteAddr());
    rsp->setLocalAddr(query->getLocalAddr());

    if (client_port_) {
        // A command line option enforces a specific client port
        rsp->setRemotePort(client_port_);
    } else if (rsp->relay_info_.empty()) {
        // Direct traffic, send back to the client directly
        rsp->setRemotePort(DHCP6_CLIENT_PORT);
    } else {
        // Relayed traffic, send back to the relay agent
        uint16_t relay_port = checkRelaySourcePort(query);
        rsp->setRemotePort(relay_port ? relay_port : DHCP6_SERVER_PORT);
    }

    if (server_port_) {
        rsp->setLocalPort(server_port_);
    } else {
        rsp->setLocalPort(DHCP6_SERVER_PORT);
    }
    rsp->setIndex(query->getIndex());
    rsp->setIface(query->getIface());

    CalloutHandlePtr callout_handle = getCalloutHandle(query);
    if (!ctx.fake_allocation_ && (ctx.query_->getType() != DHCPV6_CONFIRM) &&
        (ctx.query_->getType() != DHCPV6_INFORMATION_REQUEST) &&
        HooksManager::calloutsPresent(Hooks.hook_index_leases6_committed_)) {
        // The ScopedCalloutHandleState class which guarantees that the task
        // is added to the thread pool after the response is reset (if needed)
        // and CalloutHandle state is reset. In ST it does nothing.
        // A smart pointer is used to store the ScopedCalloutHandleState so that
        // a copy of the pointer is created by the lambda and only on the
        // destruction of the last reference the task is added.
        // In MT there are 2 cases:
        // 1. packet is unparked before current thread smart pointer to
        //    ScopedCalloutHandleState is destroyed:
        //  - the lambda uses the smart pointer to set the callout which adds the
        //    task, but the task is added after ScopedCalloutHandleState is
        //    destroyed, on the destruction of the last reference which is held
        //    by the current thread.
        // 2. packet is unparked after the current thread smart pointer to
        //    ScopedCalloutHandleState is destroyed:
        //  - the current thread reference to ScopedCalloutHandleState is
        //    destroyed, but the reference in the lambda keeps it alive until
        //    the lambda is called and the last reference is released, at which
        //    time the task is actually added.
        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        std::shared_ptr<ScopedCalloutHandleState> callout_handle_state =
                std::make_shared<ScopedCalloutHandleState>(callout_handle);

        ScopedEnableOptionsCopy<Pkt6> query6_options_copy(query);

        // Also pass the corresponding query packet as argument
        callout_handle->setArgument("query6", query);

        Lease6CollectionPtr new_leases(new Lease6Collection());
        if (!ctx.new_leases_.empty()) {
            // Filter out reused leases as they were not committed.
            for (auto const& new_lease : ctx.new_leases_) {
                if (new_lease->reuseable_valid_lft_ == 0) {
                    new_leases->push_back(new_lease);<--- Consider using std::copy_if algorithm instead of a raw loop.
                }
            }
        }
        callout_handle->setArgument("leases6", new_leases);

        Lease6CollectionPtr deleted_leases(new Lease6Collection());

        // Do per IA lists
        for (auto const& iac : ctx.ias_) {
            if (!iac.old_leases_.empty()) {
                for (auto const& old_lease : iac.old_leases_) {
                    if (ctx.new_leases_.empty()) {
                        deleted_leases->push_back(old_lease);
                        continue;
                    }
                    bool in_new = false;
                    for (auto const& new_lease : ctx.new_leases_) {
                        if ((new_lease->addr_ == old_lease->addr_) &&
                            ((new_lease->type_ != Lease::TYPE_PD) ||
                             (new_lease->prefixlen_ == old_lease->prefixlen_))) {<--- Consider using std::any_of algorithm instead of a raw loop.
                            in_new = true;
                            break;
                        }
                    }
                    if (!in_new) {
                        deleted_leases->push_back(old_lease);
                    }
                }
            }
        }
        callout_handle->setArgument("deleted_leases6", deleted_leases);

        // Get the parking limit. Parsing should ensure the value is present.
        uint32_t parked_packet_limit = 0;
        data::ConstElementPtr ppl = CfgMgr::instance().getCurrentCfg()->
            getConfiguredGlobal(CfgGlobals::PARKED_PACKET_LIMIT);
        if (ppl) {
            parked_packet_limit = ppl->intValue();
        }

        if (parked_packet_limit) {
            auto const& parking_lot = ServerHooks::getServerHooks().
                getParkingLotPtr("leases6_committed");
            if (parking_lot && (parking_lot->size() >= parked_packet_limit)) {
                // We can't park it so we're going to throw it on the floor.
                LOG_DEBUG(packet6_logger, DBGLVL_PKT_HANDLING,
                          DHCP6_HOOK_LEASES6_PARKING_LOT_FULL)
                          .arg(parked_packet_limit)
                          .arg(query->getLabel());
                isc::stats::StatsMgr::instance().addValue("pkt6-receive-drop",
                                                          static_cast<int64_t>(1));
                rsp.reset();
                return (rsp);
            }
        }

        // We proactively park the packet. We'll unpark it without invoking
        // the callback (i.e. drop) unless the callout status is set to
        // NEXT_STEP_PARK.  Otherwise the callback we bind here will be
        // executed when the hook library unparks the packet.
        ConstSubnet6Ptr subnet = ctx.subnet_;
        HooksManager::park("leases6_committed", query,
        [this, callout_handle, query, rsp, callout_handle_state, subnet]() mutable {
            if (MultiThreadingMgr::instance().getMode()) {
                typedef function<void()> CallBack;
                boost::shared_ptr<CallBack> call_back =
                    boost::make_shared<CallBack>(std::bind(&Dhcpv6Srv::sendResponseNoThrow,
                                                           this, callout_handle, query, rsp, subnet));
                callout_handle_state->on_completion_ = [call_back]() {
                    MultiThreadingMgr::instance().getThreadPool().add(call_back);
                };
            } else {
                processPacketPktSend(callout_handle, query, rsp, subnet);
                processPacketBufferSend(callout_handle, rsp);
            }
        });

        try {
            // Call all installed callouts
            HooksManager::callCallouts(Hooks.hook_index_leases6_committed_,
                                       *callout_handle);
        } catch (...) {
            // Make sure we don't orphan a parked packet.
            HooksManager::drop("leases6_committed", query);
            throw;
        }

        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK) {
            LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASES6_COMMITTED_PARK)
                      .arg(query->getLabel());
            // Since the hook library(ies) are going to do the unparking, then
            // reset the pointer to the response to indicate to the caller that
            // it should return, as the packet processing will continue via
            // the callback.
            rsp.reset();
        } else {
            // Drop the park job on the packet, it isn't needed.
            HooksManager::drop("leases6_committed", query);
            if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
                LOG_DEBUG(hooks_logger, DBGLVL_PKT_HANDLING, DHCP6_HOOK_LEASES6_COMMITTED_DROP)
                          .arg(query->getLabel());
                rsp.reset();
            }
        }
    }

    // If we have a response prep it for shipment.
    if (rsp) {
        processPacketPktSend(callout_handle, query, rsp, ctx.subnet_);
    }

    return (rsp);
}

void
Dhcpv6Srv::sendResponseNoThrow(hooks::CalloutHandlePtr& callout_handle,
                               Pkt6Ptr query, Pkt6Ptr& rsp,
                               ConstSubnet6Ptr& subnet) {
    try {
            processPacketPktSend(callout_handle, query, rsp, subnet);
            processPacketBufferSend(callout_handle, rsp);
        } catch (const std::exception& e) {
            LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_STD_EXCEPTION)
                .arg(query->getLabel())
                .arg(e.what());
    } catch (...) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_PROCESS_EXCEPTION)
            .arg(query->getLabel());
    }
}

void
Dhcpv6Srv::processPacketPktSend(hooks::CalloutHandlePtr& callout_handle,
                                Pkt6Ptr& query, Pkt6Ptr& rsp,
                                ConstSubnet6Ptr& subnet) {
    query->addPktEvent("process_completed");
    if (!rsp) {
        return;
    }

    // Specifies if server should do the packing
    bool skip_pack = false;

    // Server's reply packet now has all options and fields set.
    // Options are represented by individual objects, but the
    // output wire data has not been prepared yet.
    // Execute all callouts registered for packet6_send
    if (HooksManager::calloutsPresent(Hooks.hook_index_pkt6_send_)) {

        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        ScopedCalloutHandleState callout_handle_state(callout_handle);

        // Enable copying options from the packets within hook library.
        ScopedEnableOptionsCopy<Pkt6> query_resp_options_copy(query, rsp);

        // Pass incoming packet as argument
        callout_handle->setArgument("query6", query);

        // Set our response
        callout_handle->setArgument("response6", rsp);

        // Pass the selected subnet as an argument.
        callout_handle->setArgument("subnet6", subnet);

        // Call all installed callouts
        HooksManager::callCallouts(Hooks.hook_index_pkt6_send_, *callout_handle);

        // Callouts decided to skip the next processing step. The next
        // processing step would be to pack the packet (create wire data).
        // That step will be skipped if any callout sets skip flag.
        // It essentially means that the callout already did packing,
        // so the server does not have to do it again.
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
            LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_PACKET_SEND_SKIP)
                .arg(rsp->getLabel());
            skip_pack = true;
        }

        /// Callouts decided to drop the packet.
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
            LOG_DEBUG(hooks_logger, DBGLVL_PKT_HANDLING, DHCP6_HOOK_PACKET_SEND_DROP)
                .arg(rsp->getLabel());
            rsp.reset();
            return;
        }
    }

    if (!skip_pack) {
        try {
            LibDHCP::splitNtpServerOptions6(rsp->options_);
            rsp->pack();
        } catch (const std::exception& e) {
            LOG_ERROR(options6_logger, DHCP6_PACK_FAIL)
                .arg(query->getLabel())
                .arg(e.what());
            return;
        }

    }
}

void
Dhcpv6Srv::processPacketBufferSend(CalloutHandlePtr& callout_handle,
                                   Pkt6Ptr& rsp) {
    if (!rsp) {
        return;
    }

    try {
        // Now all fields and options are constructed into output wire buffer.
        // Option objects modification does not make sense anymore. Hooks
        // can only manipulate wire buffer at this stage.
        // Let's execute all callouts registered for buffer6_send
        if (HooksManager::calloutsPresent(Hooks.hook_index_buffer6_send_)) {

            // Use the RAII wrapper to make sure that the callout handle state is
            // reset when this object goes out of scope. All hook points must do
            // it to prevent possible circular dependency between the callout
            // handle and its arguments.
            ScopedCalloutHandleState callout_handle_state(callout_handle);

            // Enable copying options from the packet within hook library.
            ScopedEnableOptionsCopy<Pkt6> response6_options_copy(rsp);

            // Pass incoming packet as argument
            callout_handle->setArgument("response6", rsp);

            // Call callouts
            HooksManager::callCallouts(Hooks.hook_index_buffer6_send_,
                                       *callout_handle);

            // Callouts decided to skip the next processing step. The next
            // processing step would be to parse the packet, so skip at this
            // stage means drop.
            if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
                (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
                LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS,
                          DHCP6_HOOK_BUFFER_SEND_SKIP)
                    .arg(rsp->getLabel());
                return;
            }

            callout_handle->getArgument("response6", rsp);
        }

        LOG_INFO(packet6_logger, DHCP6_PACKET_SEND)
            .arg(rsp->getLabel())
            .arg(rsp->getName())
            .arg(static_cast<int>(rsp->getType()))
            .arg(rsp->getLocalAddr().isV6Zero() ? "*" : rsp->getLocalAddr().toText())
            .arg(rsp->getLocalPort())
            .arg(rsp->getRemoteAddr())
            .arg(rsp->getRemotePort())
            .arg(rsp->getIface());

        LOG_DEBUG(packet6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_RESPONSE_DATA)
            .arg(rsp->getLabel())
            .arg(rsp->getName())
            .arg(static_cast<int>(rsp->getType()))
            .arg(rsp->toText());
        sendPacket(rsp);

        // Update statistics accordingly for sent packet.
        processStatsSent(rsp);

    } catch (const std::exception& e) {
        LOG_ERROR(packet6_logger, DHCP6_PACKET_SEND_FAIL)
            .arg(rsp->getLabel())
            .arg(e.what());
    }
}

std::string
Dhcpv6Srv::duidToString(const OptionPtr& opt) {
    stringstream tmp;

    OptionBuffer data = opt->getData();

    bool colon = false;
    for (auto const& it : data) {
        if (colon) {
            tmp << ":";
        }
        tmp << hex << setw(2) << setfill('0') << static_cast<uint16_t>(it);
        if (!colon) {<--- Condition '!colon' is redundant
            colon = true;<--- Assignment 'colon=true'
        }
    }

    return tmp.str();
}

void
Dhcpv6Srv::copyClientOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
    // Add client-id.
    OptionPtr clientid = question->getOption(D6O_CLIENTID);
    if (clientid) {
        answer->addOption(clientid);
    }
    /// @todo: Should throw if there is no client-id (except anonymous INF-REQUEST)

    // If this is a relayed message, we need to copy relay information
    if (!question->relay_info_.empty()) {
        answer->copyRelayInfo(question);
    }

}

void
Dhcpv6Srv::appendDefaultOptions(const Pkt6Ptr&, Pkt6Ptr& answer,
                                const CfgOptionList&) {
    // add server-id
    answer->addOption(getServerID());
}

void
Dhcpv6Srv::buildCfgOptionList(const Pkt6Ptr& question,
                              AllocEngine::ClientContext6& ctx,
                              CfgOptionList& co_list) {
    // Firstly, host specific options.
    if (ctx.currentHost() && !ctx.currentHost()->getCfgOption6()->empty()) {
        co_list.push_back(ctx.currentHost()->getCfgOption6());
    }

    // Secondly, pool specific options. Pools are defined within a subnet, so
    // if there is no subnet, there is nothing to do.
    if (ctx.subnet_) {
        for (auto const& resource : ctx.allocated_resources_) {
            PoolPtr pool =
                ctx.subnet_->getPool(resource.getPrefixLength() == 128 ?
                                     Lease::TYPE_NA : Lease::TYPE_PD,
                                     resource.getAddress(),
                                     false);
            if (pool && !pool->getCfgOption()->empty()) {
                co_list.push_back(pool->getCfgOption());
            }
        }

        // Thirdly, subnet configured options.
        if (!ctx.subnet_->getCfgOption()->empty()) {
            co_list.push_back(ctx.subnet_->getCfgOption());
        }

        // Fourthly, shared network specific options.
        SharedNetwork6Ptr network;
        ctx.subnet_->getSharedNetwork(network);
        if (network && !network->getCfgOption()->empty()) {
            co_list.push_back(network->getCfgOption());
        }
    }

    // Each class in the incoming packet
    const ClientClasses& classes = question->getClasses();
    for (auto const& cclass : classes) {
        // Find the client class definition for this class
        const ClientClassDefPtr& ccdef = CfgMgr::instance().getCurrentCfg()->
            getClientClassDictionary()->findClass(cclass);
        if (!ccdef) {
            // Not found: the class is built-in or not configured
            if (!isClientClassBuiltIn(cclass)) {
                LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASS_UNCONFIGURED)
                    .arg(question->getLabel())
                    .arg(cclass);
            }
            // Skip it
            continue;
        }

        if (ccdef->getCfgOption()->empty()) {
            // Skip classes which don't configure options
            continue;
        }

        co_list.push_back(ccdef->getCfgOption());
    }

    // Last global options
    if (!CfgMgr::instance().getCurrentCfg()->getCfgOption()->empty()) {
        co_list.push_back(CfgMgr::instance().getCurrentCfg()->getCfgOption());
    }
}

void
Dhcpv6Srv::appendRequestedOptions(const Pkt6Ptr& question, Pkt6Ptr& answer,
                                  const CfgOptionList& co_list) {
    // Unlikely short cut
    if (co_list.empty()) {
        return;
    }

    set<uint16_t> requested_opts;

    // Client requests some options using ORO option. Try to
    // get this option from client's message.
    OptionUint16ArrayPtr option_oro = boost::dynamic_pointer_cast<
        OptionUint16Array>(question->getOption(D6O_ORO));

    // Get the list of options that client requested.
    if (option_oro) {
        for (uint16_t code : option_oro->getValues()) {
            static_cast<void>(requested_opts.insert(code));
        }
    }

    set<uint16_t> cancelled_opts;

    // Iterate on the configured option list to add persistent and
    // cancelled options.
    for (auto const& copts : co_list) {
        const OptionContainerPtr& opts = copts->getAll(DHCP6_OPTION_SPACE);
        if (!opts) {
            continue;
        }
        // Get persistent options.
        const OptionContainerPersistIndex& pidx = opts->get<2>();
        const OptionContainerPersistRange& prange = pidx.equal_range(true);
        BOOST_FOREACH(auto const& desc, prange) {
            // Add the persistent option code to requested options.
            if (desc.option_) {
                uint16_t code = desc.option_->getType();
                static_cast<void>(requested_opts.insert(code));
            }
        }
        // Get cancelled options.
        const OptionContainerCancelIndex& cidx = opts->get<5>();
        const OptionContainerCancelRange& crange = cidx.equal_range(true);
        BOOST_FOREACH(auto const& desc, crange) {
            // Add the cancelled option code to the cancelled options.
            if (desc.option_) {
                uint16_t code = desc.option_->getType();
                static_cast<void>(cancelled_opts.insert(code));
            }
        }
    }

    const auto& cclasses = question->getClasses();
    // For each requested option code get the first instance of the option
    // to be returned to the client.
    for (uint16_t opt : requested_opts) {
        // Skip if cancelled.
        if (cancelled_opts.count(opt) > 0) {
            continue;
        }
        // Add nothing when it is already there.
        // Skip special cases: D6O_VENDOR_OPTS
        if (opt == D6O_VENDOR_OPTS) {
            continue;
        }
        if (!answer->getOption(opt)) {
            // Iterate on the configured option list
            for (auto const& copts : co_list) {
                OptionDescriptor desc = copts->get(DHCP6_OPTION_SPACE, opt);
                // Got it: if allowed add it and jump to the outer loop.
                if (desc.option_ && desc.allowedForClientClasses(cclasses)) {
                    answer->addOption(desc.option_);
                    break;
                }
            }
        }
    }

    // Special cases for vendor class and options which are identified
    // by the code/type and the vendor/enterprise id vs. the code/type only.
    if ((requested_opts.count(D6O_VENDOR_CLASS) > 0) &&
        (cancelled_opts.count(D6O_VENDOR_CLASS) == 0)) {
        // Keep vendor ids which are already in the response to insert
        // D6O_VENDOR_CLASS options at most once per vendor.
        set<uint32_t> vendor_ids;
        // Get what already exists in the response.
        for (auto const& opt : answer->getOptions(D6O_VENDOR_CLASS)) {
            OptionVendorClassPtr vendor_class;
            vendor_class = boost::dynamic_pointer_cast<OptionVendorClass>(opt.second);
            if (vendor_class) {
                uint32_t vendor_id = vendor_class->getVendorId();
                static_cast<void>(vendor_ids.insert(vendor_id));
            }
        }
        // Iterate on the configured option list.
        for (auto const& copts : co_list) {
            for (auto const& desc : copts->getList(DHCP6_OPTION_SPACE, D6O_VENDOR_CLASS)) {
                // Empty or not allowed, skip i.
                if (!desc.option_ || !desc.allowedForClientClasses(cclasses)) {
                    continue;
                }
                OptionVendorClassPtr vendor_class =
                    boost::dynamic_pointer_cast<OptionVendorClass>(desc.option_);
                if (!vendor_class) {
                    continue;
                }
                // Is the vendor id already in the response?
                uint32_t vendor_id = vendor_class->getVendorId();
                if (vendor_ids.count(vendor_id) > 0) {
                    continue;
                }
                // Got it: add it.
                answer->addOption(desc.option_);
                static_cast<void>(vendor_ids.insert(vendor_id));
            }
        }
    }

    if ((requested_opts.count(D6O_VENDOR_OPTS) > 0) &&
        (cancelled_opts.count(D6O_VENDOR_OPTS) == 0)) {
        // Keep vendor ids which are already in the response to insert
        // D6O_VENDOR_OPTS options at most once per vendor.
        set<uint32_t> vendor_ids;
        // Get what already exists in the response.
        for (auto const& opt : answer->getOptions(D6O_VENDOR_OPTS)) {
            OptionVendorPtr vendor_opts;
            vendor_opts = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
            if (vendor_opts) {
                uint32_t vendor_id = vendor_opts->getVendorId();
                static_cast<void>(vendor_ids.insert(vendor_id));
            }
        }
        // Iterate on the configured option list
        for (auto const& copts : co_list) {
            for (auto const& desc : copts->getList(DHCP6_OPTION_SPACE, D6O_VENDOR_OPTS)) {
                // Empty or not allowed, skip i.
                if (!desc.option_ || !desc.allowedForClientClasses(cclasses)) {
                    continue;
                }
                OptionVendorPtr vendor_opts =
                    boost::dynamic_pointer_cast<OptionVendor>(desc.option_);
                if (!vendor_opts) {
                    continue;
                }
                // Is the vendor id already in the response?
                uint32_t vendor_id = vendor_opts->getVendorId();
                if (vendor_ids.count(vendor_id) > 0) {
                    continue;
                }
                // Append a fresh vendor option as the next method should
                // add suboptions to it.
                vendor_opts.reset(new OptionVendor(Option::V6, vendor_id));
                answer->addOption(vendor_opts);
                static_cast<void>(vendor_ids.insert(vendor_id));
            }
        }
    }
}

void
Dhcpv6Srv::appendRequestedVendorOptions(const Pkt6Ptr& question,
                                        Pkt6Ptr& answer,
                                        AllocEngine::ClientContext6& ctx,<--- Parameter 'ctx' can be declared as reference to const
                                        const CfgOptionList& co_list) {

    // Leave if there is no subnet matching the incoming packet.
    // There is no need to log the error message here because
    // it will be logged in the assignLease() when it fails to
    // pick the suitable subnet. We don't want to duplicate
    // error messages in such case.
    //
    // Also, if there's no options to possibly assign, give up.
    if (!ctx.subnet_ || co_list.empty()) {
        return;
    }

    set<uint32_t> vendor_ids;

    // The server could have provided the option using client classification or
    // hooks. If there're vendor info options in the response already, use them.
    map<uint32_t, OptionVendorPtr> vendor_rsps;
    for (auto const& opt : answer->getOptions(D6O_VENDOR_OPTS)) {
        OptionVendorPtr vendor_rsp;
        vendor_rsp = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
        if (vendor_rsp) {
            uint32_t vendor_id = vendor_rsp->getVendorId();
            vendor_rsps[vendor_id] = vendor_rsp;
            static_cast<void>(vendor_ids.insert(vendor_id));
        }
    }

    // Next, try to get the vendor-id from the client packet's
    // vendor-specific information option (17).
    map<uint32_t, OptionVendorPtr> vendor_reqs;
    for (auto const& opt : question->getOptions(D6O_VENDOR_OPTS)) {
        OptionVendorPtr vendor_req;
        vendor_req = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
        if (vendor_req) {
            uint32_t vendor_id = vendor_req->getVendorId();
            vendor_reqs[vendor_id] = vendor_req;
            static_cast<void>(vendor_ids.insert(vendor_id));
        }
    }

    // Finally, try to get the vendor-id from the client packet's vendor-class
    // option (16).
    for (auto const& opt : question->getOptions(D6O_VENDOR_CLASS)) {
        OptionVendorClassPtr vendor_class;
        vendor_class = boost::dynamic_pointer_cast<OptionVendorClass>(opt.second);
        if (vendor_class) {
            uint32_t vendor_id = vendor_class->getVendorId();
            static_cast<void>(vendor_ids.insert(vendor_id));
        }
    }

    // If there's no vendor option in either request or response, then there's no way
    // to figure out what the vendor-id values are and we give up.
    if (vendor_ids.empty()) {
        return;
    }

    map<uint32_t, set<uint16_t> > requested_opts;

    // Let's try to get ORO within that vendor-option.
    // This is specific to vendor-id=4491 (Cable Labs). Other vendors may have
    // different policies.
    OptionUint16ArrayPtr oro;
    if (vendor_reqs.count(VENDOR_ID_CABLE_LABS) > 0) {
        OptionVendorPtr vendor_req = vendor_reqs[VENDOR_ID_CABLE_LABS];
        OptionPtr oro_generic = vendor_req->getOption(DOCSIS3_V6_ORO);
        if (oro_generic) {
            // Vendor ID 4491 makes Kea look at DOCSIS3_V6_OPTION_DEFINITIONS
            // when parsing options. Based on that, oro_generic will have been
            // created as an OptionUint16Array, but might not be for other
            // vendor IDs.
            oro = boost::dynamic_pointer_cast<OptionUint16Array>(oro_generic);
        }
        if (oro) {
            set<uint16_t> oro_req_opts;
            for (uint16_t code : oro->getValues()) {
                static_cast<void>(oro_req_opts.insert(code));
            }
            requested_opts[VENDOR_ID_CABLE_LABS] = oro_req_opts;
        }
    }

    map<uint32_t, set<uint16_t> > cancelled_opts;
    const auto& cclasses = question->getClasses();

    // Iterate on the configured option list to add persistent and
    // cancelled options.
    for (uint32_t vendor_id : vendor_ids) {
        for (auto const& copts : co_list) {
            const OptionContainerPtr& opts = copts->getAll(vendor_id);
            if (!opts) {
                continue;
            }
            // Get persistent options.
            const OptionContainerPersistIndex& pidx = opts->get<2>();
            const OptionContainerPersistRange& prange = pidx.equal_range(true);
            BOOST_FOREACH(auto const& desc, prange) {
                if (!desc.option_) {
                    continue;
                }
                // Add the persistent option code to requested options
                uint16_t code = desc.option_->getType();
                static_cast<void>(requested_opts[vendor_id].insert(code));
            }
            // Get cancelled options.
            const OptionContainerCancelIndex& cidx = opts->get<5>();
            const OptionContainerCancelRange& crange = cidx.equal_range(true);
            BOOST_FOREACH(auto const& desc, crange) {
                if (!desc.option_) {
                    continue;
                }
                // Add the cancelled option code to cancelled options
                uint16_t code = desc.option_->getType();
                static_cast<void>(cancelled_opts[vendor_id].insert(code));
            }
        }

        // If there is nothing to add don't do anything with this vendor.
        // This will explicitly not echo back vendor options from the request
        // that either correspond to a vendor not known to Kea even if the
        // option encapsulates data or there are no persistent options
        // configured for this vendor so Kea does not send any option back.
        if (requested_opts[vendor_id].empty()) {
            continue;
        }

        // It's possible that the vendor opts option was inserted already
        // by client class or a hook. If that is so, let's use it.
        OptionVendorPtr vendor_rsp;
        if (vendor_rsps.count(vendor_id) > 0) {
            vendor_rsp = vendor_rsps[vendor_id];
        } else {
            vendor_rsp.reset(new OptionVendor(Option::V6, vendor_id));
        }

        // Get the list of options that client requested.
        bool added = false;

        for (uint16_t opt : requested_opts[vendor_id]) {
            if (cancelled_opts[vendor_id].count(opt) > 0) {
                continue;
            }
            if (!vendor_rsp->getOption(opt)) {
                for (auto const& copts : co_list) {
                    OptionDescriptor desc = copts->get(vendor_id, opt);
                    // Got it: if allowed add it and jump to outer loop.
                    if (desc.option_ && desc.allowedForClientClasses(cclasses)) {
                        vendor_rsp->addOption(desc.option_);
                        added = true;
                        break;
                    }
                }
            }
        }

        // If we added some sub-options and the vendor opts option is not in
        // the response already, then add it.
        if (added && (vendor_rsps.count(vendor_id) == 0)) {
            answer->addOption(vendor_rsp);
        }
    }
}

bool
Dhcpv6Srv::sanityCheck(const Pkt6Ptr& pkt) {
    try {
        switch (pkt->getType()) {
        case DHCPV6_SOLICIT:
        case DHCPV6_REBIND:
        case DHCPV6_CONFIRM:
            sanityCheck(pkt, MANDATORY, FORBIDDEN);
            return (true);

        case DHCPV6_REQUEST:
        case DHCPV6_RENEW:
        case DHCPV6_RELEASE:
        case DHCPV6_DECLINE:
            sanityCheck(pkt, MANDATORY, MANDATORY);
            return (true);

        case DHCPV6_INFORMATION_REQUEST:
        case DHCPV6_DHCPV4_QUERY:
            sanityCheck(pkt, OPTIONAL, OPTIONAL);
            return (true);

        default:
            LOG_DEBUG(bad_packet6_logger, DBG_DHCP6_BASIC,
                      DHCP6_UNKNOWN_MSG_RECEIVED)
                .arg(pkt->getLabel())
                .arg(static_cast<int>(pkt->getType()))
                .arg(pkt->getIface());
        }

    } catch (const RFCViolation& e) {
        LOG_DEBUG(bad_packet6_logger, DBG_DHCP6_BASIC, DHCP6_REQUIRED_OPTIONS_CHECK_FAIL)
            .arg(pkt->getLabel())
            .arg(pkt->getName())
            .arg(pkt->getRemoteAddr().toText())
            .arg(e.what());
    }

    // Increase the statistic of dropped packets.
    StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));
    return (false);
}

void
Dhcpv6Srv::sanityCheck(const Pkt6Ptr& pkt, RequirementLevel clientid,
                       RequirementLevel serverid) {
    OptionCollection client_ids = pkt->getOptions(D6O_CLIENTID);
    switch (clientid) {
    case MANDATORY: {
        if (client_ids.size() != 1) {
            isc_throw(RFCViolation, "Exactly 1 client-id option expected in "
                      << pkt->getName() << ", but " << client_ids.size()
                      << " received");
        }
        sanityCheckDUID(client_ids.begin()->second, "client-id");
        break;
    }
    case OPTIONAL:
        if (client_ids.size() > 1) {
            isc_throw(RFCViolation, "Too many (" << client_ids.size()
                      << ") client-id options received in " << pkt->getName());
        }
        if (!client_ids.empty()) {
            sanityCheckDUID(client_ids.begin()->second, "client-id");
        }
        break;

    case FORBIDDEN:
        // doesn't make sense - client-id is always allowed
        break;
    }

    OptionCollection server_ids = pkt->getOptions(D6O_SERVERID);
    switch (serverid) {
    case FORBIDDEN:
        if (!server_ids.empty()) {
            isc_throw(RFCViolation, "Server-id option was not expected, but "
                      << server_ids.size() << " received in " << pkt->getName());
        }
        break;

    case MANDATORY:
        if (server_ids.size() != 1) {
            isc_throw(RFCViolation, "Invalid number of server-id options received ("
                      << server_ids.size() << "), exactly 1 expected in message "
                      << pkt->getName());
        }
        sanityCheckDUID(server_ids.begin()->second, "server-id");
        break;

    case OPTIONAL:
        if (server_ids.size() > 1) {
            isc_throw(RFCViolation, "Too many (" << server_ids.size()
                      << ") server-id options received in " << pkt->getName());
        }
        if (!server_ids.empty()) {
            sanityCheckDUID(server_ids.begin()->second, "server-id");
        }
    }
}

void Dhcpv6Srv::sanityCheckDUID(const OptionPtr& opt, const std::string& opt_name) {
    if (!opt) {
        isc_throw(RFCViolation, "Unable to find expected option " << opt_name);
    }

    // The client-id or server-id has to have at least 3 bytes of useful data:
    // two for duid type and one more for actual duid value.
    uint16_t len = opt->len() - opt->getHeaderLen();
    if (len < DUID::MIN_DUID_LEN || len > DUID::MAX_DUID_LEN) {
        isc_throw(RFCViolation, "Received invalid DUID for " << opt_name << ", received "
                  << len << " byte(s). It must be at least " << DUID::MIN_DUID_LEN
                  << " and no more than " << DUID::MAX_DUID_LEN);
    }
}

ConstSubnet6Ptr
Dhcpv6Srv::selectSubnet(const Pkt6Ptr& question, bool& drop) {
    const SubnetSelector& selector = CfgSubnets6::initSelector(question);

    ConstSubnet6Ptr subnet = CfgMgr::instance().getCurrentCfg()->
        getCfgSubnets6()->selectSubnet(selector);

    // Let's execute all callouts registered for subnet6_receive
    if (HooksManager::calloutsPresent(Hooks.hook_index_subnet6_select_)) {
        CalloutHandlePtr callout_handle = getCalloutHandle(question);

        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        shared_ptr<ScopedCalloutHandleState> callout_handle_state(
            std::make_shared<ScopedCalloutHandleState>(callout_handle));

        // Enable copying options from the packet within hook library.
        ScopedEnableOptionsCopy<Pkt6> query6_options_copy(question);

        // Set new arguments
        callout_handle->setArgument("query6", question);
        callout_handle->setArgument("subnet6", subnet);

        // We pass pointer to const collection for performance reasons.
        // Otherwise we would get a non-trivial performance penalty each
        // time subnet6_select is called.
        callout_handle->setArgument("subnet6collection",
                                    CfgMgr::instance().getCurrentCfg()->
                                    getCfgSubnets6()->getAll());

        auto const tpl(parkingLimitExceeded("subnet6_select"));
        bool const exceeded(get<0>(tpl));
        if (exceeded) {
            uint32_t const limit(get<1>(tpl));
            // We can't park it so we're going to throw it on the floor.
            LOG_DEBUG(packet6_logger, DBGLVL_PKT_HANDLING,
                      DHCP4_HOOK_SUBNET6_SELECT_PARKING_LOT_FULL)
                .arg(limit)
                .arg(question->getLabel());
            return (ConstSubnet6Ptr());
        }

        // We proactively park the packet.
        // Not MT compatible because the unparking callback can be called
        // before the current thread exists from this block.
        HooksManager::park("subnet6_select", question, [this, question, callout_handle_state]() {
            if (MultiThreadingMgr::instance().getMode()) {
                boost::shared_ptr<function<void()>> callback(
                    boost::make_shared<function<void()>>([this, question]() mutable {
                        processLocalizedQuery6AndSendResponse(question);
                    }));
                callout_handle_state->on_completion_ = [callback]() {
                    MultiThreadingMgr::instance().getThreadPool().add(callback);
                };
            } else {
                processLocalizedQuery6AndSendResponse(question);
            }
        });

        // Call user (and server-side) callouts
        try {
            HooksManager::callCallouts(Hooks.hook_index_subnet6_select_,
                                       *callout_handle);
        } catch (...) {
            // Make sure we don't orphan a parked packet.
            HooksManager::drop("subnet6_select", question);
            throw;
        }

        // Callouts parked the packet. Same as drop but callouts will resume
        // processing or drop the packet later.
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK) {
            LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_SUBNET6_SELECT_PARK)
                .arg(question->getLabel());
            drop = true;
            return (ConstSubnet6Ptr());
        } else {
            HooksManager::drop("subnet6_select", question);
        }

        // Callouts decided to skip this step. This means that no
        // subnet will be selected. Packet processing will continue,
        // but it will be severely limited (i.e. only global options
        // will be assigned)
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
            LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_SUBNET6_SELECT_SKIP)
                .arg(question->getLabel());
            return (ConstSubnet6Ptr());
        }

        // Callouts decided to drop the packet. It is a superset of the
        // skip case so no subnet will be selected.
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
            LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_SUBNET6_SELECT_DROP)
                .arg(question->getLabel());
            drop = true;
            return (ConstSubnet6Ptr());
        }

        // Use whatever subnet was specified by the callout
        callout_handle->getArgument("subnet6", subnet);
    }

    if (subnet) {
        // Log at higher debug level that subnet has been found.
        LOG_DEBUG(packet6_logger, DBG_DHCP6_BASIC_DATA, DHCP6_SUBNET_SELECTED)
            .arg(question->getLabel())
            .arg(subnet->getID());
        // Log detailed information about the selected subnet at the
        // lower debug level.
        LOG_DEBUG(packet6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_DATA)
            .arg(question->getLabel())
            .arg(subnet->toText());

    } else {
        LOG_DEBUG(packet6_logger, DBG_DHCP6_DETAIL, DHCP6_SUBNET_SELECTION_FAILED)
            .arg(question->getLabel());
    }

    return (subnet);
}

void
Dhcpv6Srv::assignLeases(const Pkt6Ptr& question, Pkt6Ptr& answer,
                        AllocEngine::ClientContext6& ctx) {
    // Save the originally selected subnet.
    ConstSubnet6Ptr orig_subnet = ctx.subnet_;

    // We need to allocate addresses for all IA_NA options in the client's
    // question (i.e. SOLICIT or REQUEST) message.
    // @todo add support for IA_TA

    // For the lease allocation it is critical that the client has sent
    // DUID. There is no need to check for the presence of the DUID here
    // because we have already checked it in the sanityCheck().

    // Now that we have all information about the client, let's iterate over all
    // received options and handle IA_NA options one by one and store our
    // responses in answer message (ADVERTISE or REPLY).
    //
    // @todo: IA_TA once we implement support for temporary addresses.
    for (auto const& opt : question->options_) {
        switch (opt.second->getType()) {
        case D6O_IA_NA: {
            OptionPtr answer_opt = assignIA_NA(question, ctx,
                                               boost::dynamic_pointer_cast<
                                               Option6IA>(opt.second));
            if (answer_opt) {
                answer->addOption(answer_opt);
            }
            break;
        }
        case D6O_IA_PD: {
            OptionPtr answer_opt = assignIA_PD(question, ctx,
                                               boost::dynamic_pointer_cast<
                                               Option6IA>(opt.second));
            if (answer_opt) {
                answer->addOption(answer_opt);
            }
            break;
        }
        default:
            break;
        }
    }

    // Subnet may be modified by the allocation engine, there are things
    // we need to do when that happens.
    checkDynamicSubnetChange(question, answer, ctx, orig_subnet);
}

void
Dhcpv6Srv::processClientFqdn(const Pkt6Ptr& question, const Pkt6Ptr& answer,
                             AllocEngine::ClientContext6& ctx) {
    D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
    DdnsParamsPtr ddns_params = ctx.getDdnsParams();

    // Get Client FQDN Option from the client's message. If this option hasn't
    // been included, do nothing.
    Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
        Option6ClientFqdn>(question->getOption(D6O_CLIENT_FQDN));
    if (!fqdn) {
        if (ddns_params->getEnableUpdates() &&
            (ddns_params->getReplaceClientNameMode() == D2ClientConfig::RCM_ALWAYS ||
             ddns_params->getReplaceClientNameMode() == D2ClientConfig::RCM_WHEN_NOT_PRESENT)) {
            // Fabricate an empty "client" FQDN with flags requesting
            // the server do all the updates.  The flags will get modified
            // below according the configuration options, the name will
            // be supplied later on.
            fqdn.reset(new Option6ClientFqdn(Option6ClientFqdn::FLAG_S, "",
                                             Option6ClientFqdn::PARTIAL));
            LOG_DEBUG(ddns6_logger, DBG_DHCP6_DETAIL, DHCP6_DDNS_GENERATE_FQDN)
                .arg(question->getLabel());
        } else {
            // No FQDN so get the lease hostname from the host reservation if
            // there is one.
            if (ctx.currentHost()) {
                ctx.hostname_ = ctx.currentHost()->getHostname();
            }

            return;
        }
    }

    LOG_DEBUG(ddns6_logger, DBG_DHCP6_DETAIL, DHCP6_DDNS_RECEIVE_FQDN)
        .arg(question->getLabel())
        .arg(fqdn->toText());

    // Create the DHCPv6 Client FQDN Option to be included in the server's
    // response to a client.
    Option6ClientFqdnPtr fqdn_resp(new Option6ClientFqdn(*fqdn));

    // Set the server S, N, and O flags based on client's flags and
    // current configuration.
    d2_mgr.adjustFqdnFlags<Option6ClientFqdn>(*fqdn, *fqdn_resp, *ddns_params);

    // Get DDNS update direction flags
    CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn_resp, ctx.fwd_dns_update_,
                                                            ctx.rev_dns_update_);

    // If there's a reservation and it has a hostname specified, use it!
    if (ctx.currentHost() && !ctx.currentHost()->getHostname().empty()) {
        // Add the qualifying suffix.
        // After #3765, this will only occur if the suffix is not empty.
        fqdn_resp->setDomainName(d2_mgr.qualifyName(ctx.currentHost()->getHostname(),
                                                    *ddns_params, true),
                                                    Option6ClientFqdn::FULL);
    } else {
        // Adjust the domain name based on domain name value and type sent by
        // the client and current configuration.
        d2_mgr.adjustDomainName<Option6ClientFqdn>(*fqdn, *fqdn_resp, *ddns_params);
    }

    // Once we have the FQDN setup to use it for the lease hostname.  This
    // only gets replaced later if the FQDN is to be generated from the address.
    ctx.hostname_ = fqdn_resp->getDomainName();

    // The FQDN has been processed successfully. Let's append it to the
    // response to be sent to a client. Note that the Client FQDN option is
    // always sent back to the client if Client FQDN was included in the
    // client's message.
    LOG_DEBUG(ddns6_logger, DBG_DHCP6_DETAIL, DHCP6_DDNS_RESPONSE_FQDN_DATA)
        .arg(question->getLabel())
        .arg(fqdn_resp->toText());
    answer->addOption(fqdn_resp);

    // Optionally, call a hook that may override the decisions made
    // earlier.
    if (HooksManager::calloutsPresent(Hooks.hook_index_ddns6_update_)) {
        CalloutHandlePtr callout_handle = getCalloutHandle(question);

        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        ScopedCalloutHandleState callout_handle_state(callout_handle);

        // Setup the callout arguments.
        ConstSubnet6Ptr subnet = ctx.subnet_;
        callout_handle->setArgument("query6", question);
        callout_handle->setArgument("response6", answer);
        callout_handle->setArgument("subnet6", subnet);
        callout_handle->setArgument("hostname", ctx.hostname_);
        callout_handle->setArgument("fwd-update", ctx.fwd_dns_update_);
        callout_handle->setArgument("rev-update", ctx.rev_dns_update_);
        callout_handle->setArgument("ddns-params", ddns_params);

        // Call callouts
        HooksManager::callCallouts(Hooks.hook_index_ddns6_update_, *callout_handle);

        // Let's get the parameters returned by hook.
        string hook_hostname;
        bool hook_fwd_dns_update;
        bool hook_rev_dns_update;
        callout_handle->getArgument("hostname", hook_hostname);
        callout_handle->getArgument("fwd-update", hook_fwd_dns_update);
        callout_handle->getArgument("rev-update", hook_rev_dns_update);

        // If there's anything changed by the hook, log it and then update the parameters
        if ((ctx.hostname_ != hook_hostname) || (ctx.fwd_dns_update_!= hook_fwd_dns_update) ||
            (ctx.rev_dns_update_ != hook_rev_dns_update)) {
            LOG_DEBUG(hooks_logger, DBGLVL_PKT_HANDLING, DHCP6_HOOK_DDNS_UPDATE)
                      .arg(ctx.hostname_).arg(hook_hostname)
                      .arg(ctx.fwd_dns_update_).arg(hook_fwd_dns_update)
                      .arg(ctx.rev_dns_update_).arg(hook_rev_dns_update);

            // Update the FQDN option in the response.
            fqdn_resp = boost::dynamic_pointer_cast<Option6ClientFqdn>(answer->getOption(D6O_CLIENT_FQDN));
            if (fqdn) {
                fqdn_resp->setDomainName(hook_hostname, Option6ClientFqdn::FULL);
                if (!(hook_fwd_dns_update || hook_rev_dns_update)) {
                    // Hook disabled updates, Set flags back to client accordingly.
                    fqdn_resp->setFlag(Option6ClientFqdn::FLAG_S, 0);
                    fqdn_resp->setFlag(Option6ClientFqdn::FLAG_N, 1);
                }
            }

            ctx.hostname_ = hook_hostname;
            ctx.fwd_dns_update_ = hook_fwd_dns_update;
            ctx.rev_dns_update_ = hook_rev_dns_update;
        }
    }
}

void
Dhcpv6Srv::createNameChangeRequests(const Pkt6Ptr& answer,
                                    AllocEngine::ClientContext6& ctx) {
    // Don't create NameChangeRequests if DNS updates are disabled.
    if (!(ctx.getDdnsParams()->getEnableUpdates())) {
        return;
    }

    // The response message instance is always required. For instance it
    // holds the Client Identifier. It is a programming error if supplied
    // message is NULL.
    if (!answer) {
        isc_throw(isc::Unexpected, "an instance of the object"
                  << " encapsulating server's message must not be"
                  << " NULL when creating DNS NameChangeRequest");
    }

    // It is likely that client haven't included the FQDN option. In such case,
    // FQDN option will be NULL. This is valid state, so we simply return.
    Option6ClientFqdnPtr opt_fqdn = boost::dynamic_pointer_cast<
        Option6ClientFqdn>(answer->getOption(D6O_CLIENT_FQDN));
    if (!opt_fqdn) {
        return;
    }

    // Get the update directions that should be performed based on our
    // response FQDN flags.
    bool do_fwd = false;
    bool do_rev = false;
    CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*opt_fqdn,
                                                             do_fwd, do_rev);

    // Get the Client Id. It is mandatory and a function creating a response
    // would have thrown an exception if it was missing. Thus throwing
    // Unexpected if it is missing as it is a programming error.
    OptionPtr opt_duid = answer->getOption(D6O_CLIENTID);
    if (!opt_duid) {
        isc_throw(isc::Unexpected,
                  "client identifier is required when creating a new"
                  " DNS NameChangeRequest");
    }
    DuidPtr duid = DuidPtr(new DUID(opt_duid->getData()));

    // Get the FQDN in the on-wire format. It will be needed to compute
    // DHCID.
    OutputBuffer name_buf(1);
    opt_fqdn->packDomainName(name_buf);
    const std::vector<uint8_t>& buf_vec = name_buf.getVector();
    // Compute DHCID from Client Identifier and FQDN.
    isc::dhcp_ddns::D2Dhcid dhcid(*duid, buf_vec);

    // Iterate over the IAContexts (there should be one per client IA processed).
    // For the first address in each IA_NA, create the appropriate NCR(s).
    for (auto& ia_ctx : ctx.getIAContexts()) {
        if ((ia_ctx.type_ != Lease::TYPE_NA) || !ia_ctx.ia_rsp_) {
            continue;
        }

        /// @todo IA_NA may contain multiple addresses. We should process
        /// each address individually. Currently we only process the first one.
        Option6IAAddrPtr iaaddr = boost::static_pointer_cast<
            Option6IAAddr>(ia_ctx.ia_rsp_->getOption(D6O_IAADDR));

        // We need an address to create a name-to-address mapping.
        // If address is missing for any reason, go to the next IA.
        if (!iaaddr) {
            continue;
        }

        bool extended_only = false;
        // If the lease is being reused (i.e. lease caching in effect) skip it.
        IOAddress ia_address = iaaddr->getAddress();
        for (auto const& l : ia_ctx.reused_leases_) {
            if (l->addr_ == ia_address) {<--- Consider using std::any_of algorithm instead of a raw loop.
                extended_only = true;
                break;
            }
        }

        if (extended_only) {
            continue;
        }

        // If the lease for iaaddr is in the list of changed leases, we need
        // to determine if the changes included changes to the FQDN. If so
        // then we may need to do a CHG_REMOVE.
        for (auto const& l : ia_ctx.changed_leases_) {

            if (l->addr_ == ia_address) {<--- Consider using std::find_if algorithm instead of a raw loop.
                // The address is the same so this must be renewal. If we're not
                // always updating on renew, then we only renew if DNS info has
                // changed.
                if ((l->reuseable_valid_lft_ > 0) ||
                    (!ctx.getDdnsParams()->getUpdateOnRenew() &&
                    (l->hostname_ == opt_fqdn->getDomainName() &&
                     l->fqdn_fwd_ == do_fwd && l->fqdn_rev_ == do_rev))) {
                    extended_only = true;
                } else {
                    // Queue a CHG_REMOVE of the old data.
                    // NCR will only be created if the lease hostname is not
                    // empty and at least one of the direction flags is true
                    queueNCR(CHG_REMOVE, l);
                }

                break;
            }
        }

        if (!(do_fwd || do_rev) || (extended_only)) {
            // Flags indicate no updates needed  or it was an extension of
            // an existing lease with no FQDN changes.  In the case of the
            // former, the most likely scenario is that we are honoring the
            // client's request that no updates be done.
            continue;
        }

        // Create new NameChangeRequest. Use the domain name from the FQDN.
        // This is an FQDN included in the response to the client, so it
        // holds a fully qualified domain-name already (not partial).
        // Get the IP address from the lease.
        NameChangeRequestPtr ncr;
        auto cr_mode = StringToConflictResolutionMode(ctx.getDdnsParams()->getConflictResolutionMode());
        ncr.reset(new NameChangeRequest(isc::dhcp_ddns::CHG_ADD,
                                        do_fwd, do_rev,
                                        opt_fqdn->getDomainName(),
                                        iaaddr->getAddress().toText(),
                                        dhcid, 0,
                                        calculateDdnsTtl(iaaddr->getValid(),
                                                         ctx.getDdnsParams()->getTtlPercent(),
                                                         ctx.getDdnsParams()->getTtl(),
                                                         ctx.getDdnsParams()->getTtlMin(),
                                                         ctx.getDdnsParams()->getTtlMax()),
                                        cr_mode));
        LOG_DEBUG(ddns6_logger, DBG_DHCP6_DETAIL, DHCP6_DDNS_CREATE_ADD_NAME_CHANGE_REQUEST)
            .arg(answer->getLabel())
            .arg(ncr->toText());

        // Post the NCR to the D2ClientMgr.
        CfgMgr::instance().getD2ClientMgr().sendRequest(ncr);

        /// @todo Currently we create NCR with the first IPv6 address that
        /// is carried in one of the IA_NAs. In the future, the NCR API should
        /// be extended to map multiple IPv6 addresses to a single FQDN.
        /// In such case, this return statement will be removed.
        return;
    }
}

HWAddrPtr
Dhcpv6Srv::getMAC(const Pkt6Ptr& pkt) {
    CfgMACSources mac_sources = CfgMgr::instance().getCurrentCfg()->
        getMACSources().get();
    HWAddrPtr hwaddr;
    for (auto const& it : mac_sources) {
        hwaddr = pkt->getMAC(it);
        if (hwaddr) {
            return (hwaddr);
        }
    }
    return (hwaddr);
}

OptionPtr
Dhcpv6Srv::getPDExclude(const AllocEngine::ClientContext6& ctx,
                        const Lease6Ptr& lease) {

    // Search the reservation the prefix is from.
    ConstHostPtr host = ctx.currentHost();
    if (host) {
        IPv6ResrvRange resvs = host->getIPv6Reservations(IPv6Resrv::TYPE_PD);
        BOOST_FOREACH(auto const& resv, resvs) {
            if ((resv.second.getPrefix() == lease->addr_) &&
                (resv.second.getPrefixLen() == lease->prefixlen_)) {
                return (resv.second.getPDExclude());
            }
        }
    }

    // Search the pool the address is from.
    const ConstSubnet6Ptr& subnet = ctx.subnet_;
    Pool6Ptr pool = boost::dynamic_pointer_cast<Pool6>(
        subnet->getPool(Lease::TYPE_PD, lease->addr_));
    if (pool) {
        return (pool->getPrefixExcludeOption());
    }
    return (OptionPtr());
}

OptionPtr
Dhcpv6Srv::assignIA_NA(const Pkt6Ptr& query,
                       AllocEngine::ClientContext6& ctx,
                       boost::shared_ptr<Option6IA> ia) {

    // Check if the client sent us a hint in his IA_NA. Clients may send an
    // address in their IA_NA options as a suggestion (e.g. the last address
    // they used before).
    Option6IAAddrPtr hint_opt =
        boost::dynamic_pointer_cast<Option6IAAddr>(ia->getOption(D6O_IAADDR));
    IOAddress hint = IOAddress::IPV6_ZERO_ADDRESS();
    if (hint_opt) {
        hint = hint_opt->getAddress();
    }

    if (ctx.fake_allocation_) {
        LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_NA_SOLICIT)
            .arg(query->getLabel())
            .arg(ia->getIAID())
            .arg(hint_opt ? hint.toText() : "(no hint)");
    } else {
        LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_NA_REQUEST)
            .arg(query->getLabel())
            .arg(ia->getIAID())
            .arg(hint_opt ? hint.toText() : "(no hint)");
    }

    // convenience values
    const ConstSubnet6Ptr& subnet = ctx.subnet_;

    // If there is no subnet selected for handling this IA_NA, the only thing left to do is
    // to say that we are sorry, but the user won't get an address. As a convenience, we
    // use a different status text to indicate that (compare to the same status code,
    // but different wording below)
    if (!subnet) {
        // Create an empty IA_NA option with IAID matching the request.
        // Note that we don't use OptionDefinition class to create this option.
        // This is because we prefer using a constructor of Option6IA that
        // initializes IAID. Otherwise we would have to use setIAID() after
        // creation of the option which has some performance implications.
        boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));

        // Insert status code NoAddrsAvail.
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoAddrsAvail,
                                           "Server could not select subnet for"
                                           " this client"));
        return (ia_rsp);
    }

    // Set per-IA context values.
    ctx.createIAContext();
    ctx.currentIA().iaid_ = ia->getIAID();
    if (hint_opt) {
        ctx.currentIA().addHint(hint_opt);
    } else {
        ctx.currentIA().addHint(hint);
    }
    ctx.currentIA().type_ = Lease::TYPE_NA;

    // Use allocation engine to pick a lease for this client. Allocation engine
    // will try to honor the hint, but it is just a hint - some other address
    // may be used instead. If fake_allocation is set to false, the lease will
    // be inserted into the LeaseMgr as well.
    Lease6Collection leases = alloc_engine_->allocateLeases6(ctx);

    /// @todo: Handle more than one lease
    Lease6Ptr lease;
    if (!leases.empty()) {
        lease = *leases.begin();
    }

    // Create IA_NA that we will put in the response.
    // Do not use OptionDefinition to create option's instance so
    // as we can initialize IAID using a constructor.
    Option6IAPtr ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
    ctx.currentIA().ia_rsp_ = ia_rsp;

    if (lease) {
        // We have a lease! Let's wrap its content into IA_NA option
        // with IAADDR suboption.
        if (ctx.fake_allocation_) {
            LOG_INFO(lease6_logger, DHCP6_LEASE_ADVERT)
                .arg(query->getLabel())
                .arg(lease->addr_.toText())
                .arg(ia->getIAID());
        } else if (lease->reuseable_valid_lft_ == 0) {
            LOG_INFO(lease6_logger, DHCP6_LEASE_ALLOC)
                .arg(query->getLabel())
                .arg(lease->addr_.toText())
                .arg(ia->getIAID())
                .arg(Lease::lifetimeToText(lease->valid_lft_));
        } else {
            lease->valid_lft_ = lease->reuseable_valid_lft_;
            lease->preferred_lft_ = lease->reuseable_preferred_lft_;
            ctx.currentIA().reused_leases_.push_back(lease);
            LOG_INFO(lease6_logger, DHCP6_LEASE_REUSE)
                .arg(query->getLabel())
                .arg(lease->addr_.toText())
                .arg(ia->getIAID())
                .arg(Lease::lifetimeToText(lease->valid_lft_));

            // Increment the reuse statistics.
            StatsMgr::instance().addValue("v6-ia-na-lease-reuses", int64_t(1));
            StatsMgr::instance().addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
                                                                 "v6-ia-na-lease-reuses"),
                                          int64_t(1));
        }
        LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_LEASE_DATA)
            .arg(query->getLabel())
            .arg(ia->getIAID())
            .arg(lease->toText());

        // Set the values for T1 and T2.
        setTeeTimes(lease->preferred_lft_, subnet, ia_rsp);

        Option6IAAddrPtr addr(new Option6IAAddr(D6O_IAADDR, lease->addr_,
                                                lease->preferred_lft_,
                                                lease->valid_lft_));
        ia_rsp->addOption(addr);

        // It would be possible to insert status code=0(success) as well,
        // but this is considered waste of bandwidth as absence of status
        // code is considered a success.

    } else {
        // Allocation engine did not allocate a lease. The engine logged
        // cause of that failure. The only thing left is to insert
        // status code to pass the sad news to the client.

        LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, ctx.fake_allocation_ ?
                  DHCP6_LEASE_ADVERT_FAIL : DHCP6_LEASE_ALLOC_FAIL)
            .arg(query->getLabel())
            .arg(ia->getIAID());

        ia_rsp->addOption(createStatusCode(*query, *ia_rsp,
                                           STATUS_NoAddrsAvail,
                                           "Sorry, no address could be"
                                           " allocated."));
    }
    return (ia_rsp);
}

OptionPtr
Dhcpv6Srv::assignIA_PD(const Pkt6Ptr& query,
                       AllocEngine::ClientContext6& ctx,
                       boost::shared_ptr<Option6IA> ia) {

    // Check if the client sent us a hint in his IA_PD. Clients may send an
    // address in their IA_PD options as a suggestion (e.g. the last address
    // they used before). While the hint consists of a full prefix (prefix +
    // length), getting just the prefix is sufficient to identify a lease.
    Option6IAPrefixPtr hint_opt =
        boost::dynamic_pointer_cast<Option6IAPrefix>(ia->getOption(D6O_IAPREFIX));
    IOAddress hint = IOAddress::IPV6_ZERO_ADDRESS();
    if (hint_opt) {
        hint = hint_opt->getAddress();
    }

    if (ctx.fake_allocation_) {
        LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_PD_SOLICIT)
            .arg(query->getLabel())
            .arg(ia->getIAID())
            .arg(hint_opt ? hint.toText() : "(no hint)");
    } else {
        LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_PD_REQUEST)
            .arg(query->getLabel())
            .arg(ia->getIAID())
            .arg(hint_opt ? hint.toText() : "(no hint)");
    }

    const ConstSubnet6Ptr& subnet = ctx.subnet_;

    // Create IA_PD that we will put in the response.
    // Do not use OptionDefinition to create option's instance so
    // as we can initialize IAID using a constructor.
    boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));

    // If there is no subnet selected for handling this IA_PD, the only thing
    // left to do is to say that we are sorry, but the user won't get an address.
    // As a convenience, we use a different status text to indicate that
    // (compare to the same status code, but different wording below)
    if (!subnet) {

        // Insert status code NoAddrsAvail.
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoPrefixAvail,
                                           "Sorry, no subnet available."));
        return (ia_rsp);
    }

    // Set per-IA context values.
    ctx.createIAContext();
    ctx.currentIA().iaid_ = ia->getIAID();
    if (hint_opt) {
        ctx.currentIA().addHint(hint_opt);
    } else {
        ctx.currentIA().addHint(hint, 0);
    }
    ctx.currentIA().type_ = Lease::TYPE_PD;
    ctx.currentIA().ia_rsp_ = ia_rsp;

    // Use allocation engine to pick a lease for this client. Allocation engine
    // will try to honor the hint, but it is just a hint - some other address
    // may be used instead. If fake_allocation is set to false, the lease will
    // be inserted into the LeaseMgr as well.
    Lease6Collection leases = alloc_engine_->allocateLeases6(ctx);

    if (!leases.empty()) {

        // Need to retain the shortest preferred lease time to use
        // for calculating T1 and T2.
        uint32_t min_preferred_lft = (*leases.begin())->preferred_lft_;

        const bool pd_exclude_requested = requestedInORO(query, D6O_PD_EXCLUDE);
        for (auto const& l : leases) {

            // We have a lease! Let's wrap its content into IA_PD option
            // with IAADDR suboption.
            if (ctx.fake_allocation_) {
                LOG_INFO(lease6_logger, DHCP6_PD_LEASE_ADVERT)
                    .arg(query->getLabel())
                    .arg(l->addr_.toText())
                    .arg(static_cast<int>(l->prefixlen_))
                    .arg(ia->getIAID());
            } else if (l->reuseable_valid_lft_ == 0) {
                LOG_INFO(lease6_logger, DHCP6_PD_LEASE_ALLOC)
                    .arg(query->getLabel())
                    .arg(l->addr_.toText())
                    .arg(static_cast<int>(l->prefixlen_))
                    .arg(ia->getIAID())
                    .arg(Lease::lifetimeToText(l->valid_lft_));
            } else {
                l->valid_lft_ = l->reuseable_valid_lft_;
                l->preferred_lft_ = l->reuseable_preferred_lft_;
                LOG_INFO(lease6_logger, DHCP6_PD_LEASE_REUSE)
                    .arg(query->getLabel())
                    .arg(l->addr_.toText())
                    .arg(static_cast<int>(l->prefixlen_))
                    .arg(ia->getIAID())
                    .arg(Lease::lifetimeToText(l->valid_lft_));

                // Increment the reuse statistics.
                StatsMgr::instance().addValue("v6-ia-pd-lease-reuses", int64_t(1));
                StatsMgr::instance().addValue(StatsMgr::generateName("subnet", l->subnet_id_,
                                                                    "v6-ia-pd-lease-reuses"),
                                            int64_t(1));
            }

            // Check for new minimum lease time
            if ((l->preferred_lft_ > 0) && (min_preferred_lft > l->preferred_lft_)) {
                min_preferred_lft = l->preferred_lft_;
            }

            boost::shared_ptr<Option6IAPrefix>
                addr(new Option6IAPrefix(D6O_IAPREFIX, l->addr_,
                                         l->prefixlen_, l->preferred_lft_,
                                         l->valid_lft_));
            ia_rsp->addOption(addr);

            if (pd_exclude_requested) {
                OptionPtr pd_exclude_option = getPDExclude(ctx, l);
                if (pd_exclude_option) {
                    addr->addOption(pd_exclude_option);
                }
            }
        }

        // Set T1 and T2, using the shortest preferred lifetime among the leases.
        setTeeTimes(min_preferred_lft, subnet, ia_rsp);

        // It would be possible to insert status code=0(success) as well,
        // but this is considered waste of bandwidth as absence of status
        // code is considered a success.

    } else {
        // Allocation engine did not allocate a lease. The engine logged
        // cause of that failure. The only thing left is to insert
        // status code to pass the sad news to the client.

        LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, ctx.fake_allocation_ ?
                  DHCP6_PD_LEASE_ADVERT_FAIL : DHCP6_PD_LEASE_ALLOC_FAIL)
            .arg(query->getLabel())
            .arg(ia->getIAID());

        ia_rsp->addOption(createStatusCode(*query, *ia_rsp,
                                           STATUS_NoPrefixAvail,
                                           "Sorry, no prefixes could"
                                           " be allocated."));
    }
    return (ia_rsp);
}

OptionPtr
Dhcpv6Srv::extendIA_NA(const Pkt6Ptr& query,
                       AllocEngine::ClientContext6& ctx,
                       boost::shared_ptr<Option6IA> ia) {

    LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_NA_EXTEND)
        .arg(query->getLabel())
        .arg(ia->getIAID());

    // convenience values
    const ConstSubnet6Ptr& subnet = ctx.subnet_;

    // Create empty IA_NA option with IAID matching the request.
    Option6IAPtr ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));

    if (!subnet) {
        /// @todo For simplicity and due to limitations of LeaseMgr we don't
        /// get the binding for the client for which we don't get subnet id.
        /// Subnet id is a required value when searching for the bindings.
        /// The fact that we can't identify the subnet for the returning client
        /// doesn't really mean that the client has no binding. It is possible
        /// that due to server's reconfiguration the subnet has been removed
        /// or modified since the client has got his lease. We may need to
        /// rethink whether it is appropriate to send no binding if the subnet
        /// hasn't been found for the client.
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                          "Sorry, no known leases for this duid/iaid."));
        return (ia_rsp);
    }

    // Set per-IA context values.
    ctx.createIAContext();
    ctx.currentIA().iaid_ = ia->getIAID();
    ctx.currentIA().type_ = Lease::TYPE_NA;
    ctx.currentIA().ia_rsp_ = ia_rsp;

    // Extract the addresses that the client is trying to obtain.
    OptionCollection addrs = ia->getOptions();
    for (auto const& it : addrs) {
        if (it.second->getType() != D6O_IAADDR) {
            continue;
        }
        Option6IAAddrPtr iaaddr = boost::dynamic_pointer_cast<Option6IAAddr>(it.second);
        if (!iaaddr) {
            // That's weird. Option code was ok, but the object type was not.
            // This should never happen. The only case would be with badly
            // mis-implemented hook libraries that insert invalid option objects.
            // There's no way to protect against this.
            continue;
        }
        ctx.currentIA().addHint(iaaddr);
    }

    Lease6Collection leases = alloc_engine_->renewLeases6(ctx);

    // Ok, now we have the leases extended. We have:
    // - what the client tried to renew in ctx.hints_
    // - what we actually assigned in leases
    // - old leases that are no longer valid in ctx.old_leases_

    // For each IA inserted by the client we have to determine what to do
    // about included addresses and notify the client. We will iterate over
    // those prefixes and remove those that we have already processed. We
    // don't want to remove them from the context, so we need to copy them
    // into temporary container.
    AllocEngine::HintContainer hints = ctx.currentIA().hints_;

    // Retains the shortest valid lease time to use
    // for calculating T1 and T2.
    uint32_t min_preferred_lft = std::numeric_limits<uint32_t>::max();

    // For all leases we have now, add the IAADDR with non-zero lifetimes.
    for (auto const& l : leases) {
        if (l->reuseable_valid_lft_ == 0) {
            LOG_INFO(lease6_logger, DHCP6_LEASE_RENEW)
                .arg(query->getLabel())
                .arg(l->addr_.toText())
                .arg(ia->getIAID());
        } else {
            l->valid_lft_ = l->reuseable_valid_lft_;
            l->preferred_lft_ = l->reuseable_preferred_lft_;
            LOG_INFO(lease6_logger, DHCP6_LEASE_REUSE)
                .arg(query->getLabel())
                .arg(l->addr_.toText())
                .arg(ia->getIAID())
                .arg(Lease::lifetimeToText(l->valid_lft_));

            // Increment the reuse statistics.
            StatsMgr::instance().addValue("v6-ia-na-lease-reuses", int64_t(1));
            StatsMgr::instance().addValue(StatsMgr::generateName("subnet", l->subnet_id_,
                                                                 "v6-ia-na-lease-reuses"),
                                          int64_t(1));
        }

        Option6IAAddrPtr iaaddr(new Option6IAAddr(D6O_IAADDR,
                                l->addr_, l->preferred_lft_, l->valid_lft_));
        ia_rsp->addOption(iaaddr);

        // Check for new minimum lease time
        if ((l->preferred_lft_ > 0) && (min_preferred_lft > l->preferred_lft_)) {
            min_preferred_lft = l->preferred_lft_;
        }

        // Now remove this address from the hints list.
        AllocEngine::Resource hint_type(l->addr_);
        hints.erase(std::remove(hints.begin(), hints.end(), hint_type),
                    hints.end());
    }

    // For the leases that we just retired, send the addresses with 0 lifetimes.
    for (auto const& l : ctx.currentIA().old_leases_) {

        // Send an address with zero lifetimes only when this lease belonged to
        // this client. Do not send it when we're reusing an old lease that belonged
        // to someone else.
        if (equalValues(query->getClientId(), l->duid_)) {
            Option6IAAddrPtr iaaddr(new Option6IAAddr(D6O_IAADDR,
                                                      l->addr_, 0, 0));
            ia_rsp->addOption(iaaddr);
        }

        // Now remove this address from the hints list.
        AllocEngine::Resource hint_type(l->addr_);
        hints.erase(std::remove(hints.begin(), hints.end(), hint_type), hints.end());

        // If the new FQDN settings have changed for the lease, we need to
        // delete any existing FQDN records for this lease.
        if ((l->hostname_ != ctx.hostname_) || (l->fqdn_fwd_ != ctx.fwd_dns_update_) ||
            (l->fqdn_rev_ != ctx.rev_dns_update_)) {
            LOG_DEBUG(ddns6_logger, DBG_DHCP6_DETAIL,
                      DHCP6_DDNS_REMOVE_OLD_LEASE_FQDN)
                .arg(query->getLabel())
                .arg(l->toText())
                .arg(ctx.hostname_)
                .arg(ctx.rev_dns_update_ ? "true" : "false")
                .arg(ctx.fwd_dns_update_ ? "true" : "false");

            queueNCR(CHG_REMOVE, l);
        }
    }

    // Finally, if there are any addresses requested that we haven't dealt with
    // already, inform the client that he can't have them.
    for (auto const& hint : hints) {
        Option6IAAddrPtr iaaddr(new Option6IAAddr(D6O_IAADDR,
                                                  hint.getAddress(), 0, 0));
        ia_rsp->addOption(iaaddr);
    }

    if (!leases.empty()) {
        // We allocated leases so we need to update T1 and T2.
        setTeeTimes(min_preferred_lft, subnet, ia_rsp);
    } else {
        // The server wasn't able allocate new lease and renew an existing
        // lease. In that case, the server sends NoAddrsAvail per RFC 8415.
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp,
                                           STATUS_NoAddrsAvail,
                                           "Sorry, no addresses could be"
                                           " assigned at this time."));
    }

    return (ia_rsp);
}

OptionPtr
Dhcpv6Srv::extendIA_PD(const Pkt6Ptr& query,
                       AllocEngine::ClientContext6& ctx,
                       boost::shared_ptr<Option6IA> ia) {

    LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_PD_EXTEND)
        .arg(query->getLabel())
        .arg(ia->getIAID());

    const ConstSubnet6Ptr& subnet = ctx.subnet_;
    const DuidPtr& duid = ctx.duid_;

    // Let's create a IA_PD response and fill it in later
    Option6IAPtr ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));

    // If there is no subnet for the particular client, we can't retrieve
    // information about client's leases from lease database. We treat this
    // as no binding for the client.
    if (!subnet) {
        // Per RFC 8415, section 18.3.4, if there is no binding and we are
        // processing a Renew, the NoBinding status code should be returned.
        if (query->getType() == DHCPV6_RENEW) {
            // Insert status code NoBinding
            ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                                               "Sorry, no known PD leases"
                                               " for this duid/iaid."));
            return (ia_rsp);

        // Per RFC 8415, section 18.3.5, if there is no binding and we are
        // processing Rebind, the message has to be discarded (assuming that
        // the server doesn't know if the prefix in the IA_PD option is
        // appropriate for the client's link). The exception being thrown
        // here should propagate to the main loop and cause the message to
        // be discarded.
        } else {

            /// @todo: We may consider in which cases we could determine
            /// whether the delegated prefixes are appropriate for the
            /// link to which the client's interface is attached. Just not
            /// being able to select the subnet may not be enough, because
            /// there might be other DHCP servers around that are configured
            /// to handle that subnet. Therefore we don't fully follow all
            /// the paths in section 18.3.5 of RFC 8415 to respond with
            /// zero lifetimes for the prefixes being rebound.
            isc_throw(DHCPv6DiscardMessageError, "no subnet found for the"
                      " client sending Rebind to extend lifetime of the"
                      " prefix (DUID=" << duid->toText() << ", IAID="
                      << ia->getIAID() << ")");
        }
    }

    // Set per-IA context values.
    ctx.createIAContext();
    ctx.currentIA().iaid_ = ia->getIAID();
    ctx.currentIA().type_ = Lease::TYPE_PD;
    ctx.currentIA().ia_rsp_ = ia_rsp;

    // Extract prefixes that the client is trying to renew.
    OptionCollection addrs = ia->getOptions();
    for (auto const& it : addrs) {
        if (it.second->getType() != D6O_IAPREFIX) {
            continue;
        }
        Option6IAPrefixPtr prf = boost::dynamic_pointer_cast<Option6IAPrefix>(it.second);
        if (!prf) {
            // That's weird. Option code was ok, but the object type was not.
            // This should never happen. The only case would be with badly
            // mis-implemented hook libraries that insert invalid option objects.
            // There's no way to protect against this.
            continue;
        }

        // Put the client's prefix into the hints list.
        ctx.currentIA().addHint(prf);
    }

    // Call Allocation Engine and attempt to renew leases. Number of things
    // may happen. Leases may be extended, revoked (if the lease is no longer
    // valid or reserved for someone else), or new leases may be added.
    // Important parameters are:
    // - returned container - current valid leases
    // - old_leases - leases that used to be, but are no longer valid
    // - changed_leases - leases that have FQDN changed (not really important
    //                    in PD context)
    Lease6Collection leases = alloc_engine_->renewLeases6(ctx);

    // For each IA inserted by the client we have to determine what to do
    // about included prefixes and notify the client. We will iterate over
    // those prefixes and remove those that we have already processed. We
    // don't want to remove them from the context, so we need to copy them
    // into temporary container.
    AllocEngine::HintContainer hints = ctx.currentIA().hints_;

    const bool pd_exclude_requested = requestedInORO(query, D6O_PD_EXCLUDE);

    // Retains the shortest valid lease time to use
    // for calculating T1 and T2.
    uint32_t min_preferred_lft = std::numeric_limits<uint32_t>::max();

    for (auto const& l : leases) {
        if (l->reuseable_valid_lft_ == 0) {
            LOG_INFO(lease6_logger, DHCP6_PD_LEASE_RENEW)
                .arg(query->getLabel())
                .arg(l->addr_.toText())
                .arg(static_cast<int>(l->prefixlen_))
                .arg(ia->getIAID());
        } else {
            l->valid_lft_ = l->reuseable_valid_lft_;
            l->preferred_lft_ = l->reuseable_preferred_lft_;
            LOG_INFO(lease6_logger, DHCP6_PD_LEASE_REUSE)
                .arg(query->getLabel())
                .arg(l->addr_.toText())
                .arg(static_cast<int>(l->prefixlen_))
                .arg(ia->getIAID())
                .arg(Lease::lifetimeToText(l->valid_lft_));

            // Increment the reuse statistics.
            StatsMgr::instance().addValue("v6-ia-pd-lease-reuses", int64_t(1));
            StatsMgr::instance().addValue(StatsMgr::generateName("subnet", l->subnet_id_,
                                                                 "v6-ia-pd-lease-reuses"),
                                          int64_t(1));
        }

        Option6IAPrefixPtr prf(new Option6IAPrefix(D6O_IAPREFIX,
                               l->addr_, l->prefixlen_,
                               l->preferred_lft_, l->valid_lft_));
        ia_rsp->addOption(prf);

        if (pd_exclude_requested) {
            OptionPtr pd_exclude_option = getPDExclude(ctx, l);
            if (pd_exclude_option) {
                prf->addOption(pd_exclude_option);
            }
        }

        // Check for new minimum lease time
        if ((l->preferred_lft_ > 0) && (l->preferred_lft_ < min_preferred_lft)) {
            min_preferred_lft = l->preferred_lft_;
        }

        // Now remove this prefix from the hints list.
        AllocEngine::Resource hint_type(l->addr_, l->prefixlen_);
        hints.erase(std::remove(hints.begin(), hints.end(), hint_type),
                    hints.end());
    }

    /// For the leases that we just retired, send the prefixes with 0 lifetimes.
    for (auto const& l : ctx.currentIA().old_leases_) {

        // Send a prefix with zero lifetimes only when this lease belonged to
        // this client. Do not send it when we're reusing an old lease that belonged
        // to someone else.
        if (equalValues(query->getClientId(), l->duid_)) {
            Option6IAPrefixPtr prefix(new Option6IAPrefix(D6O_IAPREFIX, l->addr_,
                                                          l->prefixlen_, 0, 0));
            ia_rsp->addOption(prefix);
        }

        // Now remove this prefix from the hints list.
        AllocEngine::Resource hint_type(l->addr_, l->prefixlen_);
        hints.erase(std::remove(hints.begin(), hints.end(), hint_type), hints.end());
    }

    // Finally, if there are any prefixes requested that we haven't dealt with
    // already, inform the client that he can't have them.
    for (auto const& prefix : hints) {

        // Send the prefix with the zero lifetimes only if the prefix
        // contains non-zero value. A zero value indicates that the hint was
        // for the prefix length.
        if (!prefix.getAddress().isV6Zero()) {
            OptionPtr prefix_opt(new Option6IAPrefix(D6O_IAPREFIX,
                                                     prefix.getAddress(),
                                                     prefix.getPrefixLength(),
                                                     0, 0));
            ia_rsp->addOption(prefix_opt);
        }
    }

    if (!leases.empty()) {
        // We allocated leases so we need to update T1 and T2.
        setTeeTimes(min_preferred_lft, subnet, ia_rsp);
    } else {
        // All is left is to insert the status code.
        // The server wasn't able allocate new lease and renew an existing
        // lease. In that case, the server sends NoPrefixAvail per RFC 8415.
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp,
                                           STATUS_NoPrefixAvail,
                                           "Sorry, no prefixes could be"
                                           " assigned at this time."));
    }

    return (ia_rsp);
}

void
Dhcpv6Srv::extendLeases(const Pkt6Ptr& query, Pkt6Ptr& reply,
                       AllocEngine::ClientContext6& ctx) {

    // We will try to extend lease lifetime for all IA options in the client's
    // Renew or Rebind message.
    /// @todo add support for IA_TA

    // For the lease extension it is critical that the client has sent
    // DUID. There is no need to check for the presence of the DUID here
    // because we have already checked it in the sanityCheck().

    // Save the originally selected subnet.
    ConstSubnet6Ptr orig_subnet = ctx.subnet_;

    for (auto const& opt : query->options_) {
        switch (opt.second->getType()) {
        case D6O_IA_NA: {
            OptionPtr answer_opt = extendIA_NA(query, ctx,
                                               boost::dynamic_pointer_cast<
                                                   Option6IA>(opt.second));
            if (answer_opt) {
                reply->addOption(answer_opt);
            }
            break;
        }

        case D6O_IA_PD: {
            OptionPtr answer_opt = extendIA_PD(query, ctx,
                                               boost::dynamic_pointer_cast<
                                                   Option6IA>(opt.second));
            if (answer_opt) {
                reply->addOption(answer_opt);
            }
            break;
        }

        default:
            break;
        }
    }

    // Subnet may be modified by the allocation engine, there are things
    // we need to do when that happens.
    checkDynamicSubnetChange(query, reply, ctx, orig_subnet);
}

void
Dhcpv6Srv::releaseLeases(const Pkt6Ptr& release, Pkt6Ptr& reply,
                         AllocEngine::ClientContext6& ctx) {

    // We need to release addresses for all IA options in the client's
    // RELEASE message.

    /// @todo Add support for IA_TA
    /// @todo Consider supporting more than one address in a single IA.
    /// It is allowed by RFC 8415, but it is not widely implemented. The only
    /// software that supports that is Dibbler, but its author seriously doubts
    /// if anyone is really using it. Clients that want more than one address
    /// or prefix just include more instances of IA options.

    // Let's set the status to be success by default. We can override it with
    // error status if needed. The important thing to understand here is that
    // the global status code may be set to success only if all IA options were
    // handled properly. Therefore the releaseIA_NA and releaseIA_PD options
    // may turn the status code to some error, but can't turn it back to success.
    int general_status = STATUS_Success;
    for (auto const& opt : release->options_) {
        Lease6Ptr old_lease;
        switch (opt.second->getType()) {
        case D6O_IA_NA: {
            OptionPtr answer_opt = releaseIA_NA(ctx.duid_, release, general_status,
                                                boost::dynamic_pointer_cast<Option6IA>(opt.second),
                                                old_lease);
            if (answer_opt) {
                reply->addOption(answer_opt);
            }
            break;
        }
        case D6O_IA_PD: {
            OptionPtr answer_opt = releaseIA_PD(ctx.duid_, release, general_status,
                                                boost::dynamic_pointer_cast<Option6IA>(opt.second),
                                                old_lease);
            if (answer_opt) {
                reply->addOption(answer_opt);
            }
            break;
        }
        // @todo: add support for IA_TA
        default:
            // remaining options are stateless and thus ignored in this context
            ;
        }

        // Store the old lease.
        if (old_lease) {
            ctx.currentIA().old_leases_.push_back(old_lease);
        }
    }

    // Include top-level status code as well.
    reply->addOption(createStatusCode(*release, general_status,
                     "Summary status for all processed IA_NAs"));
}

OptionPtr
Dhcpv6Srv::releaseIA_NA(const DuidPtr& duid, const Pkt6Ptr& query,
                        int& general_status, boost::shared_ptr<Option6IA> ia,
                        Lease6Ptr& old_lease) {

    LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_NA_RELEASE)
        .arg(query->getLabel())
        .arg(ia->getIAID());

    // Release can be done in one of two ways:
    // Approach 1: extract address from client's IA_NA and see if it belongs
    // to this particular client.
    // Approach 2: find a subnet for this client, get a lease for
    // this subnet/duid/iaid and check if its content matches to what the
    // client is asking us to release.
    //
    // This method implements approach 1.

    // That's our response
    boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));

    Option6IAAddrPtr release_addr = boost::dynamic_pointer_cast<Option6IAAddr>
        (ia->getOption(D6O_IAADDR));
    if (!release_addr) {
        ia_rsp->addOption(createStatusCode(*query, STATUS_NoBinding,
                                           "You did not include an address in your RELEASE"));
        general_status = STATUS_NoBinding;
        return (ia_rsp);
    }

    Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA,
                                                            release_addr->getAddress());

    if (!lease) {
        // client releasing a lease that we don't know about.

        // Insert status code NoBinding.
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                          "Sorry, no known leases for this duid/iaid, can't release."));
        general_status = STATUS_NoBinding;

        return (ia_rsp);
    }

    if (!lease->duid_) {
        // Something is gravely wrong here. We do have a lease, but it does not
        // have mandatory DUID information attached. Someone was messing with our
        // database.

        LOG_ERROR(lease6_logger, DHCP6_LEASE_NA_WITHOUT_DUID)
            .arg(query->getLabel())
            .arg(release_addr->getAddress().toText());

        general_status = STATUS_UnspecFail;
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_UnspecFail,
                          "Database consistency check failed when trying to RELEASE"));
        return (ia_rsp);
    }

    if (*duid != *(lease->duid_)) {

        // Sorry, it's not your address. You can't release it.
        LOG_INFO(lease6_logger, DHCP6_RELEASE_NA_FAIL_WRONG_DUID)
            .arg(query->getLabel())
            .arg(release_addr->getAddress().toText())
            .arg(lease->duid_->toText());

        general_status = STATUS_NoBinding;
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                          "This address does not belong to you, you can't release it"));
        return (ia_rsp);
    }

    if (ia->getIAID() != lease->iaid_) {
        // This address belongs to this client, but to a different IA
        LOG_WARN(lease6_logger, DHCP6_RELEASE_NA_FAIL_WRONG_IAID)
            .arg(query->getLabel())
            .arg(release_addr->getAddress().toText())
            .arg(lease->iaid_)
            .arg(ia->getIAID());
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                          "This is your address, but you used wrong IAID"));
        general_status = STATUS_NoBinding;
        return (ia_rsp);
    }

    // It is not necessary to check if the address matches as we used
    // getLease6(addr) method that is supposed to return a proper lease.

    bool skip = false;
    // Execute all callouts registered for packet6_send
    if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_release_)) {
        CalloutHandlePtr callout_handle = getCalloutHandle(query);

        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        ScopedCalloutHandleState callout_handle_state(callout_handle);

        // Enable copying options from the packet within hook library.
        ScopedEnableOptionsCopy<Pkt6> query6_options_copy(query);

        // Delete all previous arguments
        callout_handle->deleteAllArguments();

        // Pass the original packet
        callout_handle->setArgument("query6", query);

        // Pass the lease to be updated
        callout_handle->setArgument("lease6", lease);

        // Call all installed callouts
        HooksManager::callCallouts(Hooks.hook_index_lease6_release_, *callout_handle);

        // Callouts decided to skip the next processing step. The next
        // processing step would be to send the packet, so skip at this
        // stage means "drop response".
        if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
            (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
            skip = true;
            LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RELEASE_NA_SKIP)
                .arg(query->getLabel());
        }
    }

    // Ok, we've passed all checks. Let's release this address.
    bool success = false; // was the removal operation successful?
    bool expired = false; // explicitly expired instead of removed?
    auto expiration_cfg = CfgMgr::instance().getCurrentCfg()->getCfgExpiration();

    // Callout didn't indicate to skip the release process. Let's release
    // the lease.
    if (!skip) {
        // Delete lease only if affinity is disabled.
        if (expiration_cfg->getFlushReclaimedTimerWaitTime() &&
            expiration_cfg->getHoldReclaimedTime() &&
            lease->valid_lft_ != Lease::INFINITY_LFT) {
            // Expire the lease.
            lease->valid_lft_ = 0;
            lease->preferred_lft_ = 0;
            // Set the lease state to released to indicate that this lease
            // must be preserved in the database. It is particularly useful
            // in HA to differentiate between the leases that should be
            // updated in the partner's database and deleted from the partner's
            // database.
            lease->state_ = Lease6::STATE_RELEASED;
            LeaseMgrFactory::instance().updateLease6(lease);
            expired = true;
            success = true;
        } else {
            success = LeaseMgrFactory::instance().deleteLease(lease);
        }
    }

    // Here the success should be true if we removed lease successfully
    // and false if skip flag was set or the removal failed for whatever reason

    if (!success) {
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_UnspecFail,
                          "Server failed to release a lease"));

        LOG_ERROR(lease6_logger, DHCP6_RELEASE_NA_FAIL)
            .arg(query->getLabel())
            .arg(lease->addr_.toText())
            .arg(lease->iaid_);
        general_status = STATUS_UnspecFail;

        return (ia_rsp);
    } else {
        old_lease = lease;

        LOG_INFO(lease6_logger, DHCP6_RELEASE_NA)
            .arg(query->getLabel())
            .arg(lease->addr_.toText())
            .arg(lease->iaid_);

        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_Success,
                          "Lease released. Thank you, please come again."));

        if (expired) {
            LOG_INFO(lease6_logger, DHCP6_RELEASE_NA_EXPIRED)
                .arg(query->getLabel())
                .arg(lease->addr_.toText())
                .arg(lease->iaid_);
        } else {
            LOG_INFO(lease6_logger, DHCP6_RELEASE_NA_DELETED)
                .arg(query->getLabel())
                .arg(lease->addr_.toText())
                .arg(lease->iaid_);

            // Check if a lease has flags indicating that the FQDN update has
            // been performed. If so, create NameChangeRequest which removes
            // the entries.
            queueNCR(CHG_REMOVE, lease);
        }

        // Need to decrease statistic for assigned addresses.
        StatsMgr::instance().addValue(
            StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-nas"),
            static_cast<int64_t>(-1));

        auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId(lease->subnet_id_);
        if (subnet) {
            auto const& pool = subnet->getPool(Lease::TYPE_NA, lease->addr_, false);
            if (pool) {
                StatsMgr::instance().addValue(
                    StatsMgr::generateName("subnet", subnet->getID(),
                                           StatsMgr::generateName("pool", pool->getID(), "assigned-nas")),
                    static_cast<int64_t>(-1));
            }
        }

        return (ia_rsp);
    }
}

OptionPtr
Dhcpv6Srv::releaseIA_PD(const DuidPtr& duid, const Pkt6Ptr& query,
                        int& general_status, boost::shared_ptr<Option6IA> ia,
                        Lease6Ptr& old_lease) {
    // Release can be done in one of two ways:
    // Approach 1: extract address from client's IA_NA and see if it belongs
    // to this particular client.
    // Approach 2: find a subnet for this client, get a lease for
    // this subnet/duid/iaid and check if its content matches to what the
    // client is asking us to release.
    //
    // This method implements approach 1.

    // That's our response. We will fill it in as we check the lease to be
    // released.
    boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));

    boost::shared_ptr<Option6IAPrefix> release_prefix =
        boost::dynamic_pointer_cast<Option6IAPrefix>(ia->getOption(D6O_IAPREFIX));
    if (!release_prefix) {
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                          "You did not include a prefix in your RELEASE"));
        general_status = STATUS_NoBinding;
        return (ia_rsp);
    }

    Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_PD,
                                                            release_prefix->getAddress());

    if (!lease) {
        // Client releasing a lease that we don't know about.

        // Insert status code NoBinding.
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                          "Sorry, no known leases for this duid/iaid, can't release."));
        general_status = STATUS_NoBinding;

        return (ia_rsp);
    }

    if (!lease->duid_) {
        // Something is gravely wrong here. We do have a lease, but it does not
        // have mandatory DUID information attached. Someone was messing with our
        // database.
        LOG_ERROR(lease6_logger, DHCP6_LEASE_PD_WITHOUT_DUID)
            .arg(query->getLabel())
            .arg(release_prefix->getAddress().toText())
            .arg(static_cast<int>(release_prefix->getLength()));

        general_status = STATUS_UnspecFail;
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_UnspecFail,
                          "Database consistency check failed when trying to RELEASE"));
        return (ia_rsp);
    }

    if (*duid != *(lease->duid_)) {
        // Sorry, it's not your address. You can't release it.
        LOG_INFO(lease6_logger, DHCP6_RELEASE_PD_FAIL_WRONG_DUID)
            .arg(query->getLabel())
            .arg(release_prefix->getAddress().toText())
            .arg(static_cast<int>(release_prefix->getLength()))
            .arg(lease->duid_->toText());

        general_status = STATUS_NoBinding;
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                          "This address does not belong to you, you can't release it"));
        return (ia_rsp);
    }

    if (ia->getIAID() != lease->iaid_) {
        // This address belongs to this client, but to a different IA
        LOG_WARN(lease6_logger, DHCP6_RELEASE_PD_FAIL_WRONG_IAID)
            .arg(query->getLabel())
            .arg(release_prefix->getAddress().toText())
            .arg(static_cast<int>(release_prefix->getLength()))
            .arg(lease->iaid_)
            .arg(ia->getIAID());
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_NoBinding,
                          "This is your address, but you used wrong IAID"));
        general_status = STATUS_NoBinding;
        return (ia_rsp);
    }

    // It is not necessary to check if the address matches as we used
    // getLease6(addr) method that is supposed to return a proper lease.

    bool skip = false;
    // Execute all callouts registered for packet6_send
    if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_release_)) {
        CalloutHandlePtr callout_handle = getCalloutHandle(query);

        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        ScopedCalloutHandleState callout_handle_state(callout_handle);

        // Enable copying options from the packet within hook library.
        ScopedEnableOptionsCopy<Pkt6> query6_options_copy(query);

        // Pass the original packet
        callout_handle->setArgument("query6", query);

        // Pass the lease to be updated
        callout_handle->setArgument("lease6", lease);

        // Call all installed callouts
        HooksManager::callCallouts(Hooks.hook_index_lease6_release_, *callout_handle);

        // Callouts decided to skip the next processing step. The next
        // processing step would be to send the packet, so skip at this
        // stage means "drop response".
        if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
            (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
            skip = true;
            LOG_DEBUG(hooks_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RELEASE_PD_SKIP)
                .arg(query->getLabel());
        }
    }

    // Ok, we've passed all checks. Let's release this prefix.
    bool success = false; // was the removal operation successful?
    bool expired = false; // explicitly expired instead of removed?
    auto expiration_cfg = CfgMgr::instance().getCurrentCfg()->getCfgExpiration();

    // Callout didn't indicate to skip the release process. Let's release
    // the lease.
    if (!skip) {
        // Delete lease only if affinity is disabled.
        if (expiration_cfg->getFlushReclaimedTimerWaitTime() &&
            expiration_cfg->getHoldReclaimedTime() &&
            lease->valid_lft_ != Lease::INFINITY_LFT) {
            // Expire the lease.
            lease->valid_lft_ = 0;
            lease->preferred_lft_ = 0;
            // Set the lease state to released to indicate that this lease
            // must be preserved in the database. It is particularly useful
            // in HA to differentiate between the leases that should be
            // updated in the partner's database and deleted from the partner's
            // database.
            lease->state_ = Lease6::STATE_RELEASED;
            LeaseMgrFactory::instance().updateLease6(lease);
            expired = true;
            success = true;
        } else {
            success = LeaseMgrFactory::instance().deleteLease(lease);
        }
    }

    // Here the success should be true if we removed lease successfully
    // and false if skip flag was set or the removal failed for whatever reason

    if (!success) {
        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_UnspecFail,
                          "Server failed to release a lease"));

        LOG_ERROR(lease6_logger, DHCP6_RELEASE_PD_FAIL)
            .arg(query->getLabel())
            .arg(lease->addr_.toText())
            .arg(static_cast<int>(lease->prefixlen_))
            .arg(lease->iaid_);
        general_status = STATUS_UnspecFail;

    } else {
        old_lease = lease;

        LOG_INFO(lease6_logger, DHCP6_RELEASE_PD)
            .arg(query->getLabel())
            .arg(lease->addr_.toText())
            .arg(static_cast<int>(lease->prefixlen_))
            .arg(lease->iaid_);

        ia_rsp->addOption(createStatusCode(*query, *ia_rsp, STATUS_Success,
                          "Lease released. Thank you, please come again."));

        if (expired) {
            LOG_INFO(lease6_logger, DHCP6_RELEASE_PD_EXPIRED)
                .arg(query->getLabel())
                .arg(lease->addr_.toText())
                .arg(static_cast<int>(lease->prefixlen_))
                .arg(lease->iaid_);
        } else {
            LOG_INFO(lease6_logger, DHCP6_RELEASE_PD_DELETED)
                .arg(query->getLabel())
                .arg(lease->addr_.toText())
                .arg(static_cast<int>(lease->prefixlen_))
                .arg(lease->iaid_);
        }

        // Need to decrease statistic for assigned prefixes.
        StatsMgr::instance().addValue(
            StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-pds"),
            static_cast<int64_t>(-1));

        auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId(lease->subnet_id_);
        if (subnet) {
            auto const& pool = subnet->getPool(Lease::TYPE_PD, lease->addr_, false);
            if (pool) {
                StatsMgr::instance().addValue(
                    StatsMgr::generateName("subnet", subnet->getID(),
                                           StatsMgr::generateName("pd-pool", pool->getID(), "assigned-pds")),
                    static_cast<int64_t>(-1));
            }
        }
    }

    return (ia_rsp);
}

Pkt6Ptr
Dhcpv6Srv::processSolicit(AllocEngine::ClientContext6& ctx) {

    Pkt6Ptr solicit = ctx.query_;
    Pkt6Ptr response(new Pkt6(DHCPV6_ADVERTISE, solicit->getTransid()));

    // Handle Rapid Commit option, if present.
    if (ctx.subnet_ && ctx.subnet_->getRapidCommit()) {
        OptionPtr opt_rapid_commit = solicit->getOption(D6O_RAPID_COMMIT);
        if (opt_rapid_commit) {

            LOG_DEBUG(options6_logger, DBG_DHCP6_DETAIL, DHCP6_RAPID_COMMIT)
                .arg(solicit->getLabel());

            // If Rapid Commit has been sent by the client, change the
            // response type to Reply and include Rapid Commit option.
            response->setType(DHCPV6_REPLY);
            response->addOption(opt_rapid_commit);
        }
    }

    // "Fake" allocation is the case when the server is processing the Solicit
    // message without the Rapid Commit option and advertises a lease to
    // the client, but doesn't commit this lease to the lease database. If
    // the Solicit contains the Rapid Commit option and the server is
    // configured to honor the Rapid Commit option, or the client has sent
    // the Request message, the lease will be committed to the lease
    // database. The type of the server's response may be used to determine
    // if this is the fake allocation case or not. When the server sends
    // Reply message it means that it is committing leases. Other message
    // type (Advertise) means that server is not committing leases (fake
    // allocation).
    ctx.fake_allocation_ = (response->getType() != DHCPV6_REPLY);

    processClientFqdn(solicit, response, ctx);

    if (MultiThreadingMgr::instance().getMode()) {
        // The lease reclamation cannot run at the same time.
        ReadLockGuard share(alloc_engine_->getReadWriteMutex());

        assignLeases(solicit, response, ctx);
    } else {
        assignLeases(solicit, response, ctx);
    }

    conditionallySetReservedClientClasses(solicit, ctx);
    // Evaluate additional classes.
    evaluateAdditionalClasses(solicit, ctx);

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED)
        .arg(solicit->getLabel())
        .arg(solicit->getName())
        .arg(solicit->getClasses().toText());

    copyClientOptions(solicit, response);
    CfgOptionList co_list;
    buildCfgOptionList(solicit, ctx, co_list);
    appendDefaultOptions(solicit, response, co_list);
    appendRequestedOptions(solicit, response, co_list);
    appendRequestedVendorOptions(solicit, response, ctx, co_list);

    updateReservedFqdn(ctx, response);

    // Only generate name change requests if sending a Reply as a result
    // of receiving Rapid Commit option.
    if (response->getType() == DHCPV6_REPLY) {
        createNameChangeRequests(response, ctx);
    }

    return (response);
}

Pkt6Ptr
Dhcpv6Srv::processRequest(AllocEngine::ClientContext6& ctx) {

    Pkt6Ptr request = ctx.query_;
    Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, request->getTransid()));

    processClientFqdn(request, reply, ctx);

    if (MultiThreadingMgr::instance().getMode()) {
        // The lease reclamation cannot run at the same time.
        ReadLockGuard share(alloc_engine_->getReadWriteMutex());

        assignLeases(request, reply, ctx);
    } else {
        assignLeases(request, reply, ctx);
    }

    conditionallySetReservedClientClasses(request, ctx);
    // Evaluate additional classes.
    evaluateAdditionalClasses(request, ctx);

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED)
        .arg(request->getLabel())
        .arg(request->getName())
        .arg(request->getClasses().toText());

    copyClientOptions(request, reply);
    CfgOptionList co_list;
    buildCfgOptionList(request, ctx, co_list);
    appendDefaultOptions(request, reply, co_list);
    appendRequestedOptions(request, reply, co_list);
    appendRequestedVendorOptions(request, reply, ctx, co_list);

    updateReservedFqdn(ctx, reply);
    generateFqdn(reply, ctx);
    createNameChangeRequests(reply, ctx);

    return (reply);
}

Pkt6Ptr
Dhcpv6Srv::processRenew(AllocEngine::ClientContext6& ctx) {

    Pkt6Ptr renew = ctx.query_;
    Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, renew->getTransid()));

    processClientFqdn(renew, reply, ctx);

    if (MultiThreadingMgr::instance().getMode()) {
        // The lease reclamation cannot run at the same time.
        ReadLockGuard share(alloc_engine_->getReadWriteMutex());

        extendLeases(renew, reply, ctx);
    } else {
        extendLeases(renew, reply, ctx);
    }

    conditionallySetReservedClientClasses(renew, ctx);
    // Evaluate additional classes.
    evaluateAdditionalClasses(renew, ctx);

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED)
        .arg(renew->getLabel())
        .arg(renew->getName())
        .arg(renew->getClasses().toText());

    copyClientOptions(renew, reply);
    CfgOptionList co_list;
    buildCfgOptionList(renew, ctx, co_list);
    appendDefaultOptions(renew, reply, co_list);
    appendRequestedOptions(renew, reply, co_list);
    appendRequestedVendorOptions(renew, reply, ctx, co_list);

    updateReservedFqdn(ctx, reply);
    generateFqdn(reply, ctx);
    createNameChangeRequests(reply, ctx);

    return (reply);
}

Pkt6Ptr
Dhcpv6Srv::processRebind(AllocEngine::ClientContext6& ctx) {

    Pkt6Ptr rebind = ctx.query_;
    Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, rebind->getTransid()));

    processClientFqdn(rebind, reply, ctx);

    if (MultiThreadingMgr::instance().getMode()) {
        // The lease reclamation cannot run at the same time.
        ReadLockGuard share(alloc_engine_->getReadWriteMutex());

        extendLeases(rebind, reply, ctx);
    } else {
        extendLeases(rebind, reply, ctx);
    }

    conditionallySetReservedClientClasses(rebind, ctx);
    // Evaluate additional classes.
    evaluateAdditionalClasses(rebind, ctx);

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED)
        .arg(rebind->getLabel())
        .arg(rebind->getName())
        .arg(rebind->getClasses().toText());

    copyClientOptions(rebind, reply);
    CfgOptionList co_list;
    buildCfgOptionList(rebind, ctx, co_list);
    appendDefaultOptions(rebind, reply, co_list);
    appendRequestedOptions(rebind, reply, co_list);
    appendRequestedVendorOptions(rebind, reply, ctx, co_list);

    updateReservedFqdn(ctx, reply);
    generateFqdn(reply, ctx);
    createNameChangeRequests(reply, ctx);

    return (reply);
}

Pkt6Ptr
Dhcpv6Srv::processConfirm(AllocEngine::ClientContext6& ctx) {

    Pkt6Ptr confirm = ctx.query_;
    conditionallySetReservedClientClasses(confirm, ctx);
    // Evaluate additional classes.
    evaluateAdditionalClasses(confirm, ctx);

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED)
        .arg(confirm->getLabel())
        .arg(confirm->getName())
        .arg(confirm->getClasses().toText());

    // Get IA_NAs from the Confirm. If there are none, the message is
    // invalid and must be discarded. There is nothing more to do.
    OptionCollection ias = confirm->getOptions(D6O_IA_NA);
    if (ias.empty()) {
        return (Pkt6Ptr());
    }

    // The server sends Reply message in response to Confirm.
    Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, confirm->getTransid()));
    // Make sure that the necessary options are included.
    copyClientOptions(confirm, reply);
    CfgOptionList co_list;
    buildCfgOptionList(confirm, ctx, co_list);
    appendDefaultOptions(confirm, reply, co_list);
    appendRequestedOptions(confirm, reply, co_list);
    appendRequestedVendorOptions(confirm, reply, ctx, co_list);
    // Indicates if at least one address has been verified. If no addresses
    // are verified it means that the client has sent no IA_NA options
    // or no IAAddr options and that client's message has to be discarded.
    bool verified = false;
    // Check if subnet was selected for the message. If no subnet
    // has been selected, the client is not on link.
    ConstSubnetPtr subnet = ctx.subnet_;

    // Regardless if the subnet has been selected or not, we will iterate
    // over the IA_NA options to check if they hold any addresses. If there
    // are no, the Confirm is discarded.
    // Check addresses in IA_NA options and make sure they are appropriate.
    for (auto const& ia : ias) {
        const OptionCollection& opts = ia.second->getOptions();
        for (auto const& opt : opts) {
            // Ignore options other than IAAddr.
            if (opt.second->getType() == D6O_IAADDR) {
                // Check that the address is in range in the subnet selected.
                Option6IAAddrPtr iaaddr = boost::dynamic_pointer_cast<
                    Option6IAAddr>(opt.second);
                // If there is subnet selected and the address has been included
                // in IA_NA, mark it verified and verify that it belongs to the
                // subnet.
                if (iaaddr) {
                    // If at least one address is not in range, then return
                    // the NotOnLink status code.
                    if (subnet && !subnet->inRange(iaaddr->getAddress())) {
                        std::ostringstream status_msg;
                        status_msg << "Address " << iaaddr->getAddress()
                                   << " is not on link.";
                        reply->addOption(createStatusCode(*confirm,
                                                          STATUS_NotOnLink,
                                                          status_msg.str()));
                        return (reply);
                    }
                    verified = true;
                } else {
                    isc_throw(Unexpected, "failed to cast the IA Address option"
                              " to the Option6IAAddrPtr. This is programming"
                              " error and should be reported");
                }
            }
        }
    }

    // It seems that the client hasn't included any addresses in which case
    // the Confirm must be discarded.
    if (!verified) {
        return (Pkt6Ptr());
    }

    // If there is a subnet, there were addresses in IA_NA options and the
    // addresses where consistent with the subnet then the client is on link.
    if (subnet) {
        // All addresses in range, so return success.
        reply->addOption(createStatusCode(*confirm, STATUS_Success,
                                          "All addresses are on-link"));
    } else {
        reply->addOption(createStatusCode(*confirm, STATUS_NotOnLink,
                                          "No subnet selected"));
    }

    return (reply);
}

Pkt6Ptr
Dhcpv6Srv::processRelease(AllocEngine::ClientContext6& ctx) {

    Pkt6Ptr release = ctx.query_;
    conditionallySetReservedClientClasses(release, ctx);
    // Evaluate additional classes.
    evaluateAdditionalClasses(release, ctx);

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED)
        .arg(release->getLabel())
        .arg(release->getName())
        .arg(release->getClasses().toText());

    // Create an empty Reply message.
    Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, release->getTransid()));

    // Copy client options (client-id, also relay information if present)
    copyClientOptions(release, reply);

    // Get the configured option list
    CfgOptionList co_list;
    // buildCfgOptionList(release, ctx, co_list);
    appendDefaultOptions(release, reply, co_list);

    releaseLeases(release, reply, ctx);

    /// @todo If client sent a release and we should remove outstanding
    /// DNS records.

    return (reply);
}

Pkt6Ptr
Dhcpv6Srv::processDecline(AllocEngine::ClientContext6& ctx) {

    Pkt6Ptr decline = ctx.query_;
    conditionallySetReservedClientClasses(decline, ctx);
    // Evaluate additional classes.
    evaluateAdditionalClasses(decline, ctx);

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED)
        .arg(decline->getLabel())
        .arg(decline->getName())
        .arg(decline->getClasses().toText());

    // Create an empty Reply message.
    Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, decline->getTransid()));

    // Copy client options (client-id, also relay information if present)
    copyClientOptions(decline, reply);

    // Get the configured option list
    CfgOptionList co_list;
    buildCfgOptionList(decline, ctx, co_list);

    // Include server-id
    appendDefaultOptions(decline, reply, co_list);

    if (declineLeases(decline, reply, ctx)) {
        return (reply);
    } else {

        // declineLeases returns false only if the hooks set the next step
        // status to DROP. We'll just doing as requested.
        return (Pkt6Ptr());
    }
}

bool
Dhcpv6Srv::declineLeases(const Pkt6Ptr& decline, Pkt6Ptr& reply,
                         AllocEngine::ClientContext6& ctx) {

    // We need to decline addresses for all IA_NA options in the client's
    // DECLINE message.

    // Let's set the status to be success by default. We can override it with
    // error status if needed. The important thing to understand here is that
    // the global status code may be set to success only if all IA options were
    // handled properly. Therefore the declineIA  options
    // may turn the status code to some error, but can't turn it back to success.
    int general_status = STATUS_Success;

    for (auto const& opt : decline->options_) {
        switch (opt.second->getType()) {
        case D6O_IA_NA: {
            OptionPtr answer_opt = declineIA(decline, ctx.duid_, general_status,
                                             boost::dynamic_pointer_cast<Option6IA>(opt.second),
                                             ctx.new_leases_);
            if (answer_opt) {

                // We have an answer, let's use it.
                reply->addOption(answer_opt);
            } else {

                // The only case when declineIA could return NULL is if one of the
                // hook callouts set next step status to DROP. We just need to drop
                // this packet.
                return (false);
            }
            break;
        }
        default:
            // We don't care for the remaining options
            ;
        }
    }

    return (true);
}

OptionPtr
Dhcpv6Srv::declineIA(const Pkt6Ptr& decline, const DuidPtr& duid,
                     int& general_status, boost::shared_ptr<Option6IA> ia,
                     Lease6Collection& new_leases) {

    LOG_DEBUG(lease6_logger, DBG_DHCP6_DETAIL, DHCP6_DECLINE_PROCESS_IA)
        .arg(decline->getLabel())
        .arg(ia->getIAID());

    // Decline can be done in one of two ways:
    // Approach 1: extract address from client's IA_NA and see if it belongs
    // to this particular client.
    // Approach 2: find a subnet for this client, get a lease for
    // this subnet/duid/iaid and check if its content matches to what the
    // client is asking us to decline.
    //
    // This method implements approach 1.

    // That's our response
    boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));

    const OptionCollection& opts = ia->getOptions();
    int total_addrs = 0; // Let's count the total number of addresses.
    for (auto const& opt : opts) {

        // Let's ignore nested options other than IAADDR (there shouldn't be anything
        // else in IA_NA in Decline message, but let's be on the safe side).
        if (opt.second->getType() != D6O_IAADDR) {
            continue;
        }
        Option6IAAddrPtr decline_addr = boost::dynamic_pointer_cast<Option6IAAddr>
            (opt.second);
        if (!decline_addr) {
            continue;
        }

        total_addrs++;

        Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA,
                                                                decline_addr->getAddress());

        if (!lease || lease->expired() || lease->state_ != Lease::STATE_DEFAULT) {
            // Client trying to decline a lease that we don't know about.
            LOG_INFO(lease6_logger, DHCP6_DECLINE_FAIL_NO_LEASE)
                .arg(decline->getLabel()).arg(decline_addr->getAddress().toText());

            // According to RFC 8415, section 18.3.8:
            // "For each IA in the Decline message for which the server has no
            // binding information, the server adds an IA option using the IAID
            // from the Decline message and includes a Status Code option with
            // the value NoBinding in the IA option".
            setStatusCode(ia_rsp, createStatusCode(*decline, *ia_rsp, STATUS_NoBinding,
                                  "Server does not know about such an address."));

            // In the same section of RFC 8415:
            // "The server ignores addresses not assigned to the IAs (though it may"
            // choose to log an error if it finds such addresses)."
            continue; // There may be other addresses.
        }

        if (!lease->duid_) {
            // Something is gravely wrong here. We do have a lease, but it does not
            // have mandatory DUID information attached. Someone was messing with our
            // database.

            LOG_ERROR(lease6_logger, DHCP6_DECLINE_FAIL_LEASE_WITHOUT_DUID)
                .arg(decline->getLabel())
                .arg(decline_addr->getAddress().toText());

            ia_rsp->addOption(createStatusCode(*decline, *ia_rsp, STATUS_UnspecFail,
                    "Database consistency check failed when attempting Decline."));

            continue;
        }

        // Ok, there's a sane lease with an address. Let's check if DUID matches first.
        if (*duid != *(lease->duid_)) {

            // Sorry, it's not your address. You can't release it.
            LOG_INFO(lease6_logger, DHCP6_DECLINE_FAIL_DUID_MISMATCH)
                .arg(decline->getLabel())
                .arg(decline_addr->getAddress().toText())
                .arg(lease->duid_->toText());

            ia_rsp->addOption(createStatusCode(*decline, *ia_rsp, STATUS_NoBinding,
                     "This address does not belong to you, you can't decline it"));

            continue;
        }

        // Let's check if IAID matches.
        if (ia->getIAID() != lease->iaid_) {
            // This address belongs to this client, but to a different IA
            LOG_INFO(lease6_logger, DHCP6_DECLINE_FAIL_IAID_MISMATCH)
                .arg(decline->getLabel())
                .arg(lease->addr_.toText())
                .arg(ia->getIAID())
                .arg(lease->iaid_);
            setStatusCode(ia_rsp, createStatusCode(*decline, *ia_rsp, STATUS_NoBinding,
                              "This is your address, but you used wrong IAID"));

            continue;
        }

        // Ok, all is good. Decline this lease.
        if (!declineLease(decline, lease, ia_rsp)) {
            // declineLease returns false only when hook callouts set the next
            // step status to drop. We just propagate the bad news here.
            return (OptionPtr());

        } else {
            new_leases.push_back(lease);
        }
    }

    if (total_addrs == 0) {
        setStatusCode(ia_rsp, createStatusCode(*decline, *ia_rsp, STATUS_NoBinding,
                                               "No addresses sent in IA_NA"));
        general_status = STATUS_NoBinding;
    }

    return (ia_rsp);
}

void
Dhcpv6Srv::setStatusCode(boost::shared_ptr<isc::dhcp::Option6IA>& container,
                         const OptionPtr& status) {
    // Let's delete any old status code we may have.
    container->delOption(D6O_STATUS_CODE);

    container->addOption(status);
}

bool
Dhcpv6Srv::declineLease(const Pkt6Ptr& decline, const Lease6Ptr lease,
                        boost::shared_ptr<Option6IA> ia_rsp) {
    // We do not want to decrease the assigned-nas at this time. While
    // technically a declined address is no longer allocated, the
    // primary usage of the assigned-nas statistic is to monitor pool
    // utilization. Most people would forget to include declined-addresses
    // in the calculation, and simply do assigned-nas/total-nas. This
    // would have a bias towards under-representing pool utilization,
    // if we decreased allocated immediately after receiving DHCPDECLINE,
    // rather than later when we recover the address.

    // Let's call lease6_decline hooks if necessary.
    if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_decline_)) {
        CalloutHandlePtr callout_handle = getCalloutHandle(decline);

        // Use the RAII wrapper to make sure that the callout handle state is
        // reset when this object goes out of scope. All hook points must do
        // it to prevent possible circular dependency between the callout
        // handle and its arguments.
        ScopedCalloutHandleState callout_handle_state(callout_handle);

        // Enable copying options from the packet within hook library.
        ScopedEnableOptionsCopy<Pkt6> query6_options_copy(decline);

        // Pass the original packet
        callout_handle->setArgument("query6", decline);

        // Pass the lease to be updated
        callout_handle->setArgument("lease6", lease);

        // Call callouts
        HooksManager::callCallouts(Hooks.hook_index_lease6_decline_,
                                   *callout_handle);

        // Callouts decided to SKIP the next processing step. The next
        // processing step would be to actually decline the lease, so we'll
        // keep the lease as is.
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
            LOG_DEBUG(hooks_logger, DBG_DHCP6_DETAIL, DHCP6_HOOK_DECLINE_SKIP)
                .arg(decline->getLabel())
                .arg(decline->getIface())
                .arg(lease->addr_.toText());
            return (true);
        }

        // Callouts decided to DROP the packet. Let's simply log it and
        // return false, so callers will act accordingly.
        if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
            LOG_DEBUG(hooks_logger, DBGLVL_PKT_HANDLING, DHCP6_HOOK_DECLINE_DROP)
                .arg(decline->getLabel())
                .arg(decline->getIface())
                .arg(lease->addr_.toText());
            return (false);
        }
    }

    Lease6Ptr old_values = boost::make_shared<Lease6>(*lease);

    // @todo: Call hooks.

    // We need to disassociate the lease from the client. Once we move a lease
    // to declined state, it is no longer associated with the client in any
    // way.
    lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());

    try {
        LeaseMgrFactory::instance().updateLease6(lease);
    } catch (const Exception& ex) {
        // Update failed.
        LOG_ERROR(lease6_logger, DHCP6_DECLINE_FAIL)
            .arg(decline->getLabel())
            .arg(lease->addr_.toText())
            .arg(ex.what());
        return (false);
    }

    // Check if a lease has flags indicating that the FQDN update has
    // been performed. If so, create NameChangeRequest which removes
    // the entries. This method does all necessary checks.
    queueNCR(CHG_REMOVE, old_values);

    // Bump up the subnet-specific statistic.
    StatsMgr::instance().addValue(
        StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
        static_cast<int64_t>(1));

    auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId(lease->subnet_id_);
    if (subnet) {
        auto const& pool = subnet->getPool(Lease::TYPE_NA, lease->addr_, false);
        if (pool) {
            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", subnet->getID(),
                                       StatsMgr::generateName("pool", pool->getID(), "declined-addresses")),
                static_cast<int64_t>(1));
        }
    }

    // Global declined addresses counter.
    StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));

    LOG_INFO(lease6_logger, DHCP6_DECLINE_LEASE).arg(decline->getLabel())
        .arg(lease->addr_.toText()).arg(lease->valid_lft_);

    ia_rsp->addOption(createStatusCode(*decline, *ia_rsp, STATUS_Success,
                      "Lease declined. Hopefully the next one will be better."));

    return (true);
}

Pkt6Ptr
Dhcpv6Srv::processInfRequest(AllocEngine::ClientContext6& ctx) {

    Pkt6Ptr inf_request = ctx.query_;
    conditionallySetReservedClientClasses(inf_request, ctx);
    // Evaluate additional classes.
    evaluateAdditionalClasses(inf_request, ctx);

    LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLASSES_ASSIGNED)
        .arg(inf_request->getLabel())
        .arg(inf_request->getName())
        .arg(inf_request->getClasses().toText());

    // Create a Reply packet, with the same trans-id as the client's.
    Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, inf_request->getTransid()));

    // Copy client options (client-id, also relay information if present)
    copyClientOptions(inf_request, reply);

    // Build the configured option list for append methods
    CfgOptionList co_list;
    buildCfgOptionList(inf_request, ctx, co_list);

    // Append default options, i.e. options that the server is supposed
    // to put in all messages it sends (server-id for now, but possibly other
    // options once we start supporting authentication)
    appendDefaultOptions(inf_request, reply, co_list);

    // Try to assign options that were requested by the client.
    appendRequestedOptions(inf_request, reply, co_list);

    // Try to assign vendor options that were requested by the client.
    appendRequestedVendorOptions(inf_request, reply, ctx, co_list);

    return (reply);
}

void
Dhcpv6Srv::processDhcp4Query(const Pkt6Ptr& dhcp4_query) {

    // flags are in transid
    // uint32_t flags = dhcp4_query->getTransid();
    // do nothing with DHCPV4_QUERY_FLAGS_UNICAST

    // Get the DHCPv4 message option
    OptionPtr dhcp4_msg = dhcp4_query->getOption(D6O_DHCPV4_MSG);
    if (dhcp4_msg) {
        try {
            // Forward the whole message to the DHCPv4 server via IPC
            Dhcp6to4Ipc::instance().send(dhcp4_query);
        } catch (...) {
            // Assume the error was already logged
            return;
        }
    }

    // This method does not return anything as we always sent back
    // the response via Dhcp6To4Ipc.
}

void Dhcpv6Srv::classifyByVendor(const Pkt6Ptr& pkt) {
    OptionVendorClassPtr vclass;
    for (auto const& opt : pkt->getOptions(D6O_VENDOR_CLASS)) {
        vclass = boost::dynamic_pointer_cast<OptionVendorClass>(opt.second);
        if (!vclass || vclass->getTuplesNum() == 0) {
            continue;
        }

        if (vclass->hasTuple(DOCSIS3_CLASS_MODEM)) {
            pkt->addClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM);

        } else if (vclass->hasTuple(DOCSIS3_CLASS_EROUTER)) {
            pkt->addClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER);

        } else {
            pkt->addClass(VENDOR_CLASS_PREFIX + vclass->getTuple(0).getText());
        }
    }
}

void Dhcpv6Srv::classifyPacket(const Pkt6Ptr& pkt) {
    // All packets belong to ALL.
    pkt->addClass("ALL");

    // First: built-in vendor class processing
    classifyByVendor(pkt);

    // Run match expressions on classes not depending on KNOWN/UNKNOWN.
    evaluateClasses(pkt, false);
}

void Dhcpv6Srv::evaluateClasses(const Pkt6Ptr& pkt, bool depend_on_known) {
    // Note getClientClassDictionary() cannot be null
    const ClientClassDictionaryPtr& dict =
        CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
    const ClientClassDefListPtr& defs_ptr = dict->getClasses();
    for (auto const& it : *defs_ptr) {
        // Note second cannot be null
        const ExpressionPtr& expr_ptr = it->getMatchExpr();
        // Nothing to do without an expression to evaluate
        if (!expr_ptr) {
            continue;
        }
        // Not the right time if only when required
        if (it->getAdditional()) {
            continue;
        }
        // Not the right pass.
        if (it->getDependOnKnown() != depend_on_known) {
            continue;
        }
        it->test(pkt, expr_ptr);
    }
}

void
Dhcpv6Srv::removeDependentEvaluatedClasses(const Pkt6Ptr& pkt) {
    const ClientClassDictionaryPtr& dict =
        CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
    const ClientClassDefListPtr& defs_ptr = dict->getClasses();
    for (auto const& def : *defs_ptr) {
        // Only remove evaluated classes. Other classes can be
        // assigned via hooks libraries and we should not remove
        // them because there is no way they can be added back.
        if (def->getMatchExpr()) {
            pkt->classes_.erase(def->getName());
        }
    }
}

void
Dhcpv6Srv::setReservedClientClasses(const Pkt6Ptr& pkt,
                                    const AllocEngine::ClientContext6& ctx) {
    if (ctx.currentHost() && pkt) {
        const ClientClasses& classes = ctx.currentHost()->getClientClasses6();
        for (auto const& cclass : classes) {
            pkt->addClass(cclass);
        }
    }
}

void
Dhcpv6Srv::conditionallySetReservedClientClasses(const Pkt6Ptr& pkt,
                                                 const AllocEngine::ClientContext6& ctx) {
    if (ctx.subnet_) {
        SharedNetwork6Ptr shared_network;
        ctx.subnet_->getSharedNetwork(shared_network);
        if (shared_network) {
            ConstHostPtr host = ctx.currentHost();
            if (host && (host->getIPv6SubnetID() != SUBNET_ID_GLOBAL)) {
                setReservedClientClasses(pkt, ctx);
            }
        }
    }
}

void
Dhcpv6Srv::evaluateAdditionalClasses(const Pkt6Ptr& pkt, AllocEngine::ClientContext6& ctx) {
    // Get additional classes to evaluate added elsewhere, posssibly by hooks.
    ClientClasses classes = pkt->getAdditionalClasses();
    ConstSubnet6Ptr subnet = ctx.subnet_;

    if (subnet) {
        // host reservation???

        // Begin by pools
        for (auto const& resource : ctx.allocated_resources_) {
            PoolPtr pool =
                ctx.subnet_->getPool(resource.getPrefixLength() == 128 ?
                                     Lease::TYPE_NA : Lease::TYPE_PD,
                                     resource.getAddress(),
                                     false);
            if (pool) {
                const ClientClasses& pool_to_add = pool->getAdditionalClasses();
                for (auto const& cclass : pool_to_add) {
                    classes.insert(cclass);
                }
            }
        }

        // Followed by the subnet
        const ClientClasses& to_add = subnet->getAdditionalClasses();
        for (auto const& cclass : to_add) {
            classes.insert(cclass);
        }

        // And finish by the shared-network
        SharedNetwork6Ptr network;
        subnet->getSharedNetwork(network);
        if (network) {
            const ClientClasses& net_to_add = network->getAdditionalClasses();
            for (auto const& cclass : net_to_add) {
                classes.insert(cclass);
            }
        }
    }

    // Run match expressions
    // Note getClientClassDictionary() cannot be null
    const ClientClassDictionaryPtr& dict =
        CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
    for (auto const& cclass : classes) {
        const ClientClassDefPtr class_def = dict->findClass(cclass);
        if (!class_def) {
            LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC,
                      DHCP6_ADDITIONAL_CLASS_UNDEFINED)
                .arg(cclass);
            // Ignore it as it can't have an attached action
            continue;
        }
        const ExpressionPtr& expr_ptr = class_def->getMatchExpr();
        // Add a class without an expression to evaluate
        if (!expr_ptr) {
            LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC,
                      DHCP6_ADDITIONAL_CLASS_NO_TEST)
                .arg(cclass);
            pkt->addClass(cclass);
            continue;
        }
        // Evaluate the expression which can return false (no match),
        // true (match) or raise an exception (error)
        try {
            bool status = evaluateBool(*expr_ptr, *pkt);
            LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_ADDITIONAL_CLASS_EVAL_RESULT)
                .arg(pkt->getLabel())
                .arg(cclass)
                .arg(status ? "true" : "false");
            if (status) {
                // Matching: add the class
                pkt->addClass(cclass);
            }
        } catch (const Exception& ex) {
            LOG_ERROR(dhcp6_logger, DHCP6_ADDITIONAL_CLASS_EVAL_ERROR)
                .arg(pkt->getLabel())
                .arg(cclass)
                .arg(ex.what());
        }
    }
}

void
Dhcpv6Srv::updateReservedFqdn(AllocEngine::ClientContext6& ctx,
                              const Pkt6Ptr& answer) {
    if (!answer) {
        isc_throw(isc::Unexpected, "an instance of the object encapsulating"
                  " a message must not be NULL when updating reserved FQDN");
    }

    Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option6ClientFqdn>
        (answer->getOption(D6O_CLIENT_FQDN));

   // If Client FQDN option is not included, there is nothing to do.
   if (!fqdn) {
       return;
   }

   std::string name = fqdn->getDomainName();

   // If there is a host reservation for this client we have to check whether
   // this reservation has the same hostname as the hostname currently
   // present in the FQDN option. If not, it indicates that the allocation
   // engine picked a different subnet (from within a shared network) for
   // reservations and we have to send this new value to the client.
   if (ctx.currentHost() &&
       !ctx.currentHost()->getHostname().empty()) {
       std::string new_name = CfgMgr::instance().getD2ClientMgr().
           qualifyName(ctx.currentHost()->getHostname(), *ctx.getDdnsParams(), true);

       if (new_name != name) {
           fqdn->setDomainName(new_name, Option6ClientFqdn::FULL);

           // Replace previous instance of Client FQDN option.
           answer->delOption(D6O_CLIENT_FQDN);
           answer->addOption(fqdn);
       }
   }
}

void
Dhcpv6Srv::generateFqdn(const Pkt6Ptr& answer,
                        AllocEngine::ClientContext6& ctx) {
    if (!answer) {
        isc_throw(isc::Unexpected, "an instance of the object encapsulating"
                  " a message must not be NULL when generating FQDN");
    }

    /// @todo Add proper logging for cases when we can't generate FQDN.
    /// See #3885 for details.

    // It is likely that client hasn't included the FQDN option. In such case,
    // FQDN option will be NULL. Also, there is nothing to do if the option
    // is present and conveys the non-empty FQDN.
    Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
        Option6ClientFqdn>(answer->getOption(D6O_CLIENT_FQDN));
    if (!fqdn || !fqdn->getDomainName().empty()) {
        return;
    }

    // Get the first IA_NA acquired for the client.
    OptionPtr ia = answer->getOption(D6O_IA_NA);
    if (!ia) {
        return;
    }

    // If it has any IAAddr with a valid lifetime > 0, use it to
    // generate unique FQDN.
    Option6IAAddrPtr iaaddr = boost::dynamic_pointer_cast<
        Option6IAAddr>(ia->getOption(D6O_IAADDR));
    if (!iaaddr || iaaddr->getValid() == 0) {
        return;
    }

    // Get the IPv6 address acquired by the client.
    IOAddress addr = iaaddr->getAddress();
    std::string generated_name =
        CfgMgr::instance().getD2ClientMgr().generateFqdn(addr, *ctx.getDdnsParams());

    LOG_DEBUG(ddns6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_DDNS_FQDN_GENERATED)
        .arg(answer->getLabel())
        .arg(generated_name);

    try {
        // The lease has been acquired but the FQDN for this lease hasn't
        // been updated in the lease database. We now have new FQDN
        // generated, so the lease database has to be updated here.
        // However, never update lease database for Advertise, just send
        // our notion of client's FQDN in the Client FQDN option.
        if (answer->getType() != DHCPV6_ADVERTISE) {
            Lease6Ptr lease;
            for (auto const& l : ctx.new_leases_) {
                if ((l->type_ == Lease::TYPE_NA) && (l->addr_ == addr)) {<--- Consider using std::find_if algorithm instead of a raw loop.
                    lease = l;
                    break;
                }
            }
            if (lease) {
                lease->hostname_ = generated_name;
                lease->reuseable_valid_lft_ = 0;
                LeaseMgrFactory::instance().updateLease6(lease);

            } else {
                isc_throw(isc::Unexpected, "there is no lease in the database "
                          " for address " << addr << ", so as it is impossible"
                          " to update FQDN data. This is a programmatic error"
                          " as the given address is now being handed to the"
                          " client");
            }
        }
        // Set the generated FQDN in the Client FQDN option.
        fqdn->setDomainName(generated_name, Option6ClientFqdn::FULL);

        answer->delOption(D6O_CLIENT_FQDN);
        answer->addOption(fqdn);
        ctx.hostname_ = generated_name;
    } catch (const Exception& ex) {
        LOG_ERROR(ddns6_logger, DHCP6_DDNS_GENERATED_FQDN_UPDATE_FAIL)
            .arg(answer->getLabel())
            .arg(addr.toText())
            .arg(ex.what());
    }
}

void
Dhcpv6Srv::startD2() {
    D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
    if (d2_mgr.ddnsEnabled()) {
        // Updates are enabled, so lets start the sender, passing in
        // our error handler.
        // This may throw so wherever this is called needs to ready.
        d2_mgr.startSender(std::bind(&Dhcpv6Srv::d2ClientErrorHandler,
                                     this, ph::_1, ph::_2));
    }
}

void
Dhcpv6Srv::stopD2() {
    D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
    if (d2_mgr.ddnsEnabled()) {
        // Updates are enabled, so lets stop the sender
        d2_mgr.stop();
        d2_mgr.stopSender();
    }
}

void
Dhcpv6Srv::d2ClientErrorHandler(const
                                dhcp_ddns::NameChangeSender::Result result,
                                dhcp_ddns::NameChangeRequestPtr& ncr) {
    LOG_ERROR(ddns6_logger, DHCP6_DDNS_REQUEST_SEND_FAILED).
              arg(result).arg((ncr ? ncr->toText() : " NULL "));
    // We cannot communicate with kea-dhcp-ddns, suspend further updates.
    /// @todo We may wish to revisit this, but for now we will simply turn
    /// them off.
    CfgMgr::instance().getD2ClientMgr().suspendUpdates();
}

std::string
Dhcpv6Srv::getVersion(bool extended) {<--- Derived function 'Dhcpv6Srv::getVersion'
    std::stringstream tmp;

    tmp << VERSION;
    if (extended) {
        tmp << " (" << EXTENDED_VERSION << ")" << endl;
        tmp << "premium: " << PREMIUM_EXTENDED_VERSION << endl;
        tmp << "linked with:" << endl;
        tmp << "- " << Logger::getVersion() << endl;
        tmp << "- " << CryptoLink::getVersion();
        auto info = LeaseMgrFactory::getDBVersions();
        if (info.size()) {
            tmp << endl << "lease backends:";
            for (auto const& version : info) {
                tmp << endl << "- " << version;
            }
        }
        info = HostDataSourceFactory::getDBVersions();
        if (info.size()) {
            tmp << endl << "host backends:";
            for (auto const& version : info) {
                tmp << endl << "- " << version;
            }
        }
        // @todo: more details about database runtime
    }

    return (tmp.str());
}

void Dhcpv6Srv::processRSOO(const Pkt6Ptr& query, const Pkt6Ptr& rsp) {

    if (query->relay_info_.empty()) {
        // RSOO is inserted by relay agents, nothing to do here if it's
        // a direct message.
        return;
    }

    // Get RSOO configuration.
    ConstCfgRSOOPtr cfg_rsoo  = CfgMgr::instance().getCurrentCfg()->getCfgRSOO();

    // Let's get over all relays (encapsulation levels). We need to do
    // it in the same order as the client packet traversed the relays.
    for (int i = query->relay_info_.size(); i > 0 ; --i) {
        OptionPtr rsoo_container = query->getRelayOption(D6O_RSOO, i - 1);
        if (rsoo_container) {
            // There are RSOO options. Let's get through them one by one
            // and if it's RSOO-enabled and there's no such option provided yet,
            // copy it to the server's response
            const OptionCollection& rsoo = rsoo_container->getOptions();
            for (auto const& opt : rsoo) {

                // Echo option if it is RSOO enabled option and there is no such
                // option added yet.
                if (cfg_rsoo->enabled(opt.second->getType()) &&
                    !rsp->getOption(opt.second->getType())) {
                    rsp->addOption(opt.second);
                }
            }
        }
    }
}

uint16_t Dhcpv6Srv::checkRelaySourcePort(const Pkt6Ptr& query) {

    if (query->relay_info_.empty()) {
        // No relay agent
        return (0);
    }

    // Did the last relay agent add a relay-source-port?
    if (query->getRelayOption(D6O_RELAY_SOURCE_PORT, 0)) {
        // RFC 8357 section 5.2
        return (query->getRemotePort());
    }

    return (0);
}

void Dhcpv6Srv::processStatsReceived(const Pkt6Ptr& query) {
    // Note that we're not bumping pkt6-received statistic as it was
    // increased early in the packet reception code.

    string stat_name = "pkt6-unknown-received";
    switch (query->getType()) {
    case DHCPV6_SOLICIT:
        stat_name = "pkt6-solicit-received";
        break;
    case DHCPV6_ADVERTISE:
        // Should not happen, but let's keep a counter for it
        stat_name = "pkt6-advertise-received";
        break;
    case DHCPV6_REQUEST:
        stat_name = "pkt6-request-received";
        break;
    case DHCPV6_CONFIRM:
        stat_name = "pkt6-confirm-received";
        break;
    case DHCPV6_RENEW:
        stat_name = "pkt6-renew-received";
        break;
    case DHCPV6_REBIND:
        stat_name = "pkt6-rebind-received";
        break;
    case DHCPV6_REPLY:
        // Should not happen, but let's keep a counter for it
        stat_name = "pkt6-reply-received";
        break;
    case DHCPV6_RELEASE:
        stat_name = "pkt6-release-received";
        break;
    case DHCPV6_DECLINE:
        stat_name = "pkt6-decline-received";
        break;
    case DHCPV6_RECONFIGURE:
        stat_name = "pkt6-reconfigure-received";
        break;
    case DHCPV6_INFORMATION_REQUEST:
        stat_name = "pkt6-infrequest-received";
        break;
    case DHCPV6_DHCPV4_QUERY:
        stat_name = "pkt6-dhcpv4-query-received";
        break;
    case DHCPV6_DHCPV4_RESPONSE:
        // Should not happen, but let's keep a counter for it
        stat_name = "pkt6-dhcpv4-response-received";
        break;
    default:
            ; // do nothing
    }

    StatsMgr::instance().addValue(stat_name, static_cast<int64_t>(1));
}

void Dhcpv6Srv::processStatsSent(const Pkt6Ptr& response) {
    // Increase generic counter for sent packets.
    StatsMgr::instance().addValue("pkt6-sent", static_cast<int64_t>(1));

    // Increase packet type specific counter for packets sent.
    string stat_name;
    switch (response->getType()) {
    case DHCPV6_ADVERTISE:
        stat_name = "pkt6-advertise-sent";
        break;
    case DHCPV6_REPLY:
        stat_name = "pkt6-reply-sent";
        break;
    case DHCPV6_DHCPV4_RESPONSE:
        stat_name = "pkt6-dhcpv4-response-sent";
        break;
    default:
        // That should never happen
        return;
    }

    StatsMgr::instance().addValue(stat_name, static_cast<int64_t>(1));
}

int Dhcpv6Srv::getHookIndexBuffer6Send() {
    return (Hooks.hook_index_buffer6_send_);
}

bool
Dhcpv6Srv::requestedInORO(const Pkt6Ptr& query, const uint16_t code) const {
    OptionUint16ArrayPtr oro =
        boost::dynamic_pointer_cast<OptionUint16Array>(query->getOption(D6O_ORO));

    if (oro) {
        const std::vector<uint16_t>& codes = oro->getValues();
        return (std::find(codes.begin(), codes.end(), code) != codes.end());
    }

    return (false);
}

tuple<bool, uint32_t>
Dhcpv6Srv::parkingLimitExceeded(string const& hook_label) {
    // Get the parking limit. Parsing should ensure the value is present.
    uint32_t parked_packet_limit(0);
    ConstElementPtr const& ppl(
        CfgMgr::instance().getCurrentCfg()->getConfiguredGlobal(CfgGlobals::PARKED_PACKET_LIMIT));
    if (ppl) {
        parked_packet_limit = ppl->intValue();
    }

    if (parked_packet_limit) {
        ParkingLotPtr const& parking_lot(
            ServerHooks::getServerHooks().getParkingLotPtr(hook_label));

        if (parking_lot && parked_packet_limit <= parking_lot->size()) {
            return make_tuple(true, parked_packet_limit);
        }
    }
    return make_tuple(false, parked_packet_limit);
}


void Dhcpv6Srv::discardPackets() {
    // Dump all of our current packets, anything that is mid-stream
    HooksManager::clearParkingLots();
}

uint16_t Dhcpv6Srv::getServerPort() const {
#ifdef FUZZING
    char const* const rotate(getenv("KEA_DHCP6_FUZZING_ROTATE_PORT"));
    if (rotate) {
        InterprocessSyncFile file("kea-dhcp6-fuzzing-rotate-port");
        InterprocessSyncLocker locker(file);
        while (!locker.lock()) {
            this_thread::sleep_for(1s);
        }
        fstream port_file;
        port_file.open("/tmp/port6.txt", ios::in);
        string line;
        int port;
        getline(port_file, line);
        port_file.close();
        if (line.empty()) {
            port = 2000;
        } else {
            port = stoi(line);
            if (port < 3000) {
                ++port;
            } else {
                port = 2000;
            }
        }
        port_file.open("/tmp/port6.txt", ios::out | ios::trunc);
        port_file << to_string(port) << endl;
        port_file.close();
        locker.unlock();
        return port;
    }
#endif  // FUZZING
    return server_port_;
}

/// @todo This logic to be modified if we decide to support infinite lease times.
void
Dhcpv6Srv::setTeeTimes(uint32_t preferred_lft,
                       const ConstSubnet6Ptr& subnet,
                       Option6IAPtr& resp) {
    // Default T2 time to zero.
    uint32_t t2_time = 0;

    // If T2 is explicitly configured we'll use that value.
    if (!subnet->getT2().unspecified()) {
        t2_time = subnet->getT2();
    } else if (subnet->getCalculateTeeTimes()) {
        // Calculating tee times is enabled, so calculate it.
        t2_time = static_cast<uint32_t>(round(subnet->getT2Percent() * preferred_lft));
    }

    // We allow T2 to be any value.
    resp->setT2(t2_time);

    // Default T1 time to zero.
    uint32_t t1_time = 0;

    // If T1 is explicitly configured we'll use try value.
    if (!subnet->getT1().unspecified()) {
        t1_time = subnet->getT1();
    } else if (subnet->getCalculateTeeTimes()) {
        // Calculating tee times is enabled, so calculate it.
        t1_time = static_cast<uint32_t>(round(subnet->getT1Percent() * preferred_lft));
    }

    // T1 is sane if it is less than or equal to T2.
    if (t1_time < t2_time) {
        resp->setT1(t1_time);
    } else {
        // It's either explicitly 0 or insane, leave it to the client
        resp->setT1(0);
    }
}

void
Dhcpv6Srv::checkDynamicSubnetChange(const Pkt6Ptr& question, Pkt6Ptr& answer,
                                    AllocEngine::ClientContext6& ctx,
                                    const ConstSubnet6Ptr orig_subnet) {
    // If the subnet's are the same there's nothing to do.
    if ((!ctx.subnet_) || (!orig_subnet) || (orig_subnet->getID() == ctx.subnet_->getID())) {
        return;
    }

    // We get the network for logging only. It should always be set as this a dynamic
    // change should only happen within shared-networks.  Not having one might not be
    // an error if a hook changed the subnet?
    SharedNetwork6Ptr network;
    orig_subnet->getSharedNetwork(network);
    LOG_DEBUG(packet6_logger, DBG_DHCP6_BASIC_DATA, DHCP6_SUBNET_DYNAMICALLY_CHANGED)
             .arg(question->getLabel())
             .arg(orig_subnet->toText())
             .arg(ctx.subnet_->toText())
             .arg(network ? network->getName() : "<no network?>");

    // The DDNS parameters may have changed with the subnet, so we need to
    // recalculate the client name.

    // Save the current DNS values on the context.
    std::string prev_hostname = ctx.hostname_;
    bool prev_fwd_dns_update = ctx.fwd_dns_update_;
    bool prev_rev_dns_update = ctx.rev_dns_update_;

    // Remove the current FQDN option from the answer.
    answer->delOption(D6O_CLIENT_FQDN);

    // Recalculate the client's FQDN.  This will replace the FQDN option and
    // update the context values for hostname_ and DNS directions.
    processClientFqdn(question, answer, ctx);

    // If this is a real allocation and the DNS values changed we need to
    // update the leases.
    if (!ctx.fake_allocation_ &&
        ((prev_hostname != ctx.hostname_) ||
        (prev_fwd_dns_update != ctx.fwd_dns_update_) ||
        (prev_rev_dns_update != ctx.rev_dns_update_))) {
        for (auto const& l : ctx.new_leases_) {
            l->hostname_ = ctx.hostname_;
            l->fqdn_fwd_ = ctx.fwd_dns_update_;
            l->fqdn_rev_ = ctx.rev_dns_update_;
            l->reuseable_valid_lft_ = 0;
            LeaseMgrFactory::instance().updateLease6(l);
        }
    }
}

std::list<std::list<std::string>> Dhcpv6Srv::jsonPathsToRedact()  const{
    static std::list<std::list<std::string>> const list({
        {"config-control", "config-databases", "[]"},
        {"hooks-libraries", "[]", "parameters", "*"},
        {"hosts-database"},
        {"hosts-databases", "[]"},
        {"lease-database"},
    });
    return list;
}

}  // namespace dhcp
}  // namespace isc