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
// Copyright (C) 2018-2025 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 <asiolink/interval_timer.h>
#include <asiolink/io_service.h>
#include <asiolink/testutils/test_tls.h>
#include <cc/command_interpreter.h>
#include <config/command_mgr.h>
#include <config/http_command_mgr.h>
#include <config/timeouts.h>
#include <d2/d2_controller.h>
#include <d2/d2_process.h>
#include <d2/parser_context.h>
#include <http/response.h>
#include <http/response_parser.h>
#include <http/testutils/test_http_client.h>
#include <gtest/gtest.h>
#include <boost/pointer_cast.hpp>
#include <atomic>
#include <fstream>
#include <iostream>
#include <sstream>
#include <thread>

using namespace std;
using namespace isc;
using namespace isc::asiolink;
using namespace isc::asiolink::test;
using namespace isc::config;
using namespace isc::d2;
using namespace isc::data;
using namespace isc::http;
using namespace isc::process;
namespace ph = std::placeholders;

namespace isc {
namespace d2 {

// "Naked" D2 controller, exposes internal methods.
class NakedD2Controller;
typedef boost::shared_ptr<NakedD2Controller> NakedD2ControllerPtr;

class NakedD2Controller : public D2Controller {
public:
    static DControllerBasePtr& instance() {
        static DControllerBasePtr controller_ptr;
        if (!controller_ptr) {
            controller_ptr.reset(new NakedD2Controller());
        }

        return (controller_ptr);
    }

    virtual ~NakedD2Controller() {
        deregisterCommands();
    }

    using DControllerBase::getIOService;
    using DControllerBase::initProcess;

    D2ProcessPtr getProcess() {
        return (boost::dynamic_pointer_cast<D2Process>(DControllerBase::getProcess()));
    }

private:
    NakedD2Controller() { }
};

} // namespace isc::d2
} // namespace isc

namespace {

/// @brief IP address to which HTTP service is bound.
const std::string SERVER_ADDRESS = "127.0.0.1";

/// @brief Port number to which HTTP service is bound.
const unsigned short SERVER_PORT = 18125;

/// @brief Test timeout (ms).
const long TEST_TIMEOUT = 10000;

/// @brief Base fixture class intended for testing HTTP/HTTPS control channel
/// in D2.
class BaseCtrlChannelD2Test : public ::testing::Test {
public:
    /// @brief Reference to the base controller object.
    DControllerBasePtr& server_;

    /// @brief Cast controller object.
    NakedD2Controller* d2Controller() {
        return (dynamic_cast<NakedD2Controller*>(server_.get()));
    }

    /// @brief Configuration file.
    static const char* CFG_TEST_FILE;

    /// @brief Default constructor.
    ///
    /// Sets socket path to its default value.
    BaseCtrlChannelD2Test()
        : server_(NakedD2Controller::instance()) {
    }

    /// @brief Destructor.
    virtual ~BaseCtrlChannelD2Test() {
        // Deregister & co.
        server_.reset();

        // Remove files.
        ::remove(CFG_TEST_FILE);

        // Reset command manager.
        CommandMgr::instance().deregisterAll();
        HttpCommandMgr::instance().setConnectionTimeout(TIMEOUT_AGENT_RECEIVE_COMMAND);
    }

    /// @brief Returns pointer to the server's IO service.
    ///
    /// @return Pointer to the server's IO service or null pointer if the
    /// server hasn't been created.
    IOServicePtr getIOService() {
        return (server_ ? d2Controller()->getIOService() : IOServicePtr());
    }

    /// @brief Callback function invoke upon test timeout.
    ///
    /// It stops the IO service and reports test timeout.
    ///
    /// @param fail_on_timeout Specifies if test failure should be reported.
    void timeoutHandler(const bool fail_on_timeout) {
        if (fail_on_timeout) {
            ADD_FAILURE() << "Timeout occurred while running the test!";
        }
        getIOService()->stop();
    }

    /// @brief Runs IO service.
    void runIOService() {
        IOServicePtr io_service = getIOService();
        ASSERT_TRUE(io_service);
        IntervalTimer test_timer(io_service);
        test_timer.setup(std::bind(&BaseCtrlChannelD2Test::timeoutHandler,
                                   this, true),
                         TEST_TIMEOUT, IntervalTimer::ONE_SHOT);
        // Run until the client stops the service or an error occurs.
        io_service->run();
        test_timer.cancel();
        if (io_service->stopped()) {
            io_service->restart();
        }
        io_service->poll();
    }

    /// @brief Runs parser in DHCPDDNS mode
    ///
    /// @param config input configuration
    /// @param verbose display errors
    /// @return element pointer representing the configuration
    ElementPtr parseDHCPDDNS(const string& config, bool verbose = false) {
        try {
            D2ParserContext ctx;
            return (ctx.parseString(config,
                                    D2ParserContext::PARSER_SUB_DHCPDDNS));
        } catch (const std::exception& ex) {
            if (verbose) {
                cout << "EXCEPTION: " << ex.what() << endl;
            }
            throw;
        }
    }

    /// @brief Create a server with a HTTP command channel.
    virtual void createHttpChannelServer() = 0;

    /// @brief Constructs a complete HTTP POST given a request body.
    ///
    /// @param request_body string containing the desired request body.
    ///
    /// @return string containing the constructed POST.
    std::string buildPostStr(const std::string& request_body) {
        // Create the command string.
        std::stringstream ss;
        ss << "POST /foo/bar HTTP/1.1\r\n"
              "Content-Type: application/json\r\n"
              "Content-Length: "
              << request_body.size() << "\r\n\r\n"
              << request_body;
        return (ss.str());
    }

    /// @brief Create an HttpResponse from a response string.
    ///
    /// @param response_str a string containing the whole HTTP
    /// response received.
    ///
    /// @return An HttpResponse constructed by parsing the response string.
    HttpResponsePtr parseResponse(const std::string response_str) {
        HttpResponsePtr hr(new HttpResponse());
        HttpResponseParser parser(*hr);
        parser.initModel();
        parser.postBuffer(&response_str[0], response_str.size());
        parser.poll();
        if (!parser.httpParseOk()) {
            isc_throw(Unexpected, "response_str: '" << response_str
                      << "' failed to parse: " << parser.getErrorMessage());
        }

        return (hr);
    }

    /// @brief Conducts a command/response exchange via HttpCommandSocket.
    ///
    /// This method connects to the given server over the given address/port.
    /// If successful, it then sends the given command and retrieves the
    /// server's response.  Note that it polls the server's I/O service
    /// where needed to cause the server to process IO events on
    /// the control channel sockets.
    ///
    /// @param command the command text to execute in JSON form.
    /// @param response variable into which the received response should be
    /// placed.
    /// @param address The server address to connect to.
    /// @param port The server port to connect to.
    virtual void sendHttpCommand(const string& command,
                                 string& response,
                                 std::string address = std::string(),
                                 int port = 0) = 0;

    /// @brief Parse list answer.
    ///
    /// Clone of parseAnswer but taking the answer as a list and
    /// decapsulating it.
    ///
    /// @param rcode Return code.
    /// @param msg_list The message to parse.
    /// @return The optional argument in the message after decapsulation.
    ConstElementPtr parseListAnswer(int &rcode,
                                    const ConstElementPtr& msg_list) {
        if (!msg_list) {
            isc_throw(CtrlChannelError, "invalid answer: no answer specified");
        }
        if (msg_list->getType() != Element::list) {
            isc_throw(CtrlChannelError, "invalid answer: expected toplevel "
                      << "entry to be a list, got "
                      << Element::typeToName(msg_list->getType())
                      << " instead");
        }
        if (msg_list->size() != 1) {
            isc_throw(CtrlChannelError, "invalid answer: expected toplevel "
                      << "entry to be an one element list, got "
                      << msg_list->size() << " long list instead");
        }
        ConstElementPtr msg = msg_list->get(0);
        if (!msg) {
            isc_throw(CtrlChannelError, "invalid answer: null element");
        }
        if (msg->getType() != Element::map) {
            isc_throw(CtrlChannelError, "invalid answer: expected list of "
                      << "one map, got list of one "
                      << Element::typeToName(msg->getType())
                      << " instead");
        }
        if (!msg->contains(CONTROL_RESULT)) {
            isc_throw(CtrlChannelError, "invalid answer: does not contain "
                      << "mandatory '" << CONTROL_RESULT << "'");
        }

        ConstElementPtr result = msg->get(CONTROL_RESULT);
        if (result->getType() != Element::integer) {
            isc_throw(CtrlChannelError, "invalid answer: expected '"
                      << CONTROL_RESULT << "' to be an integer, got "
                      << Element::typeToName(result->getType())
                      << " instead");
        }

        rcode = result->intValue();

        // If there are arguments, return them.
        ConstElementPtr args = msg->get(CONTROL_ARGUMENTS);
        if (args) {
            return (args);
        }

        // There are no arguments, let's try to return just the text status.
        return (msg->get(CONTROL_TEXT));
    }

    /// @brief Checks response for list-commands.
    ///
    /// This method checks if the list-commands response is generally sane
    /// and whether specified command is mentioned in the response.
    ///
    /// @param rsp response sent back by the server.
    /// @param command command expected to be on the list.
    void checkListCommands(const ConstElementPtr& rsp, const string command) {
        ConstElementPtr params;
        int status_code = -1;
        EXPECT_NO_THROW(params = parseListAnswer(status_code, rsp));
        EXPECT_EQ(CONTROL_RESULT_SUCCESS, status_code);
        ASSERT_TRUE(params);
        ASSERT_EQ(Element::list, params->getType());

        int cnt = 0;
        for (size_t i = 0; i < params->size(); ++i) {
            string tmp = params->get(i)->stringValue();
            if (tmp == command) {
                // Command found, but that's not enough.
                // Need to continue working through the list to see
                // if there are no duplicates.
                cnt++;
            }
        }

        // Exactly one command on the list is expected.
        EXPECT_EQ(1, cnt) << "Command " << command << " not found";
    }

    /// @brief Check if the answer for config-write command is correct.
    ///
    /// @param response_txt response in text form (as read from
    /// the control socket).
    /// @param exp_status expected status (0 success, 1 failure).
    /// @param exp_txt for success cases this defines the expected filename,
    /// for failure cases this defines the expected error message.
    void checkConfigWrite(const string& response_txt, int exp_status,
                          const string& exp_txt = "") {

        ConstElementPtr rsp;
        EXPECT_NO_THROW(rsp = Element::fromJSON(response_txt));
        ASSERT_TRUE(rsp);

        int status;
        ConstElementPtr params = parseListAnswer(status, rsp);
        EXPECT_EQ(exp_status, status);

        if (exp_status == CONTROL_RESULT_SUCCESS) {
            // Let's check couple things...

            // The parameters must include filename.
            ASSERT_TRUE(params);
            ASSERT_TRUE(params->get("filename"));
            ASSERT_EQ(Element::string, params->get("filename")->getType());
            EXPECT_EQ(exp_txt, params->get("filename")->stringValue());

            // The parameters must include size. And the size
            // must indicate some content.
            ASSERT_TRUE(params->get("size"));
            ASSERT_EQ(Element::integer, params->get("size")->getType());
            int64_t size = params->get("size")->intValue();
            EXPECT_LE(1, size);

            // Now check if the file is really there and suitable for
            // opening.
            ifstream f(exp_txt, ios::binary | ios::ate);
            ASSERT_TRUE(f.good());

            // Now check that it is the correct size as reported.
            EXPECT_EQ(size, static_cast<int64_t>(f.tellg()));

            // Finally, check that it's really a JSON.
            ElementPtr from_file = Element::fromJSONFile(exp_txt);
            ASSERT_TRUE(from_file);
        } else if (exp_status == CONTROL_RESULT_ERROR) {

            // Let's check if the reason for failure was given.
            ConstElementPtr text = rsp->get("text");
            ASSERT_TRUE(text);
            ASSERT_EQ(Element::string, text->getType());
            EXPECT_EQ(exp_txt, text->stringValue());
        } else {
            ADD_FAILURE() << "Invalid expected status: " << exp_status;
        }
    }

    /// @brief Handler for long command.
    ///
    /// It checks whether the received command is equal to the one specified
    /// as an argument.
    ///
    /// @param expected_command String representing an expected command.
    /// @param command_name Command name received by the handler.
    /// @param arguments Command arguments received by the handler.
    ///
    /// @returns Success answer.
    static ConstElementPtr
    longCommandHandler(const string& expected_command,
                       const string& command_name,
                       const ConstElementPtr& arguments) {
        // The handler is called with a command name and the structure holding
        // command arguments. We have to rebuild the command from those
        // two arguments so as it can be compared against expected_command.
        ElementPtr entire_command = Element::createMap();
        entire_command->set("command", Element::create(command_name));
        entire_command->set("arguments", (arguments));

        // The rebuilt command will have a different order of parameters so
        // let's parse expected_command back to JSON to guarantee that
        // both structures are built using the same order.
        EXPECT_EQ(Element::fromJSON(expected_command)->str(),
                  entire_command->str());
        return (createAnswer(CONTROL_RESULT_SUCCESS, "long command received ok"));
    }

    /// @brief Command handler which generates long response.
    ///
    /// This handler generates a large response (over 400kB). It includes
    /// a list of randomly generated strings to make sure that the test
    /// can catch out of order delivery.
    static ConstElementPtr
    longResponseHandler(const string&, const ConstElementPtr&) {
        ElementPtr arguments = Element::createList();
        for (unsigned i = 0; i < 80000; ++i) {
            std::ostringstream s;
            s << std::setw(5) << i;
            arguments->add(Element::create(s.str()));
        }
        return (createAnswer(CONTROL_RESULT_SUCCESS, arguments));
    }

    // Tests that the server properly responds to invalid commands.
    void testInvalid();

    // Tests that the server properly responds to shutdown command.
    void testShutdown();

    // Tests that the server sets exit value supplied as argument
    // to shutdown command.
    void testShutdownExitValue();

    // This test verifies that the D2 server handles version-get commands.
    void testGetVersion();

    // Tests that the server properly responds to list-commands command.
    void testListCommands();

    // This test verifies that the D2 server handles status-get commands.
    void testStatusGet();

    // Tests if the server returns its configuration using config-get.
    void testConfigGet();

    // Tests if the server returns the hash of its configuration using
    // config-hash-get.
    void testConfigHashGet();

    // Tests if config-write can be called without any parameters.
    void testWriteConfigNoFilename();

    // Tests if config-write can be called with a valid filename as parameter.
    void testWriteConfigFilename();

    // Tests if config-reload attempts to reload a file and reports that the
    // file is missing.
    void testConfigReloadMissingFile();

    // Tests if config-reload attempts to reload a file and reports that the
    // file is not a valid JSON.
    void testConfigReloadBrokenFile();

    // Tests if config-reload attempts to reload a file and reports that the
    // file is loaded correctly.
    void testConfigReloadFileValid();

    // This test verifies that the server can receive and process a
    // large command.
    void testLongCommand();

    // This test verifies that the server can send long response to the client.
    void testLongResponse();

    // This test verifies that the server signals timeout if the transmission
    // takes too long, having received no data from the client.
    void testConnectionTimeoutNoData();
};

const char* BaseCtrlChannelD2Test::CFG_TEST_FILE = "d2-http-test-config.json";

/// @brief Fixture class intended for testing HTTP control channel in D2.
class HttpCtrlChannelD2Test : public BaseCtrlChannelD2Test {
public:

    /// @brief Create a server with a HTTP command channel.
    virtual void createHttpChannelServer() override {
        // Just a simple config. The important part here is the socket
        // location information.
        string config_txt =
            "{"
            "    \"ip-address\": \"192.168.77.1\","
            "    \"port\": 777,"
            "    \"control-socket\": {"
            "        \"socket-type\": \"http\","
            "        \"socket-address\": \"127.0.0.1\","
            "        \"socket-port\": 18125"
            "    },"
            "    \"tsig-keys\": [],"
            "    \"forward-ddns\" : {},"
            "    \"reverse-ddns\" : {}"
            "}";

        ASSERT_TRUE(server_);

        ConstElementPtr config;
        ASSERT_NO_THROW(config = parseDHCPDDNS(config_txt, true));
        ASSERT_NO_THROW(d2Controller()->initProcess());
        D2ProcessPtr proc = d2Controller()->getProcess();
        ASSERT_TRUE(proc);
        ConstElementPtr answer = proc->configure(config, false);
        ASSERT_TRUE(answer);
        ASSERT_NO_THROW(d2Controller()->registerCommands());

        int status = 0;
        ConstElementPtr txt = parseAnswer(status, answer);
        // This should succeed. If not, print the error message.
        ASSERT_EQ(0, status) << txt->str();

        // Now check that the socket was indeed open.
        ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    }

    /// @brief Conducts a command/response exchange via HttpCommandSocket.
    ///
    /// This method connects to the given server over the given address/port.
    /// If successful, it then sends the given command and retrieves the
    /// server's response.  Note that it polls the server's I/O service
    /// where needed to cause the server to process IO events on
    /// the control channel sockets.
    ///
    /// @param command the command text to execute in JSON form.
    /// @param response variable into which the received response should be
    /// placed.
    /// @param address The server address to connect to.
    /// @param port The server port to connect to.
    virtual void sendHttpCommand(const string& command,
                                 string& response,
                                 std::string address = std::string(),
                                 int port = 0) override {
        response = "";
        IOServicePtr io_service = getIOService();
        ASSERT_TRUE(io_service);
        if (address.empty()) {
            address = SERVER_ADDRESS;
        }
        if (!port) {
            port = SERVER_PORT;
        }
        TestHttpClientPtr client(new TestHttpClient(io_service, address,
                                                    port));
        ASSERT_TRUE(client);

        // Send the command. This will trigger server's handler which
        // receives data over the HTTP socket. The server will start
        // sending response to the client.
        ASSERT_NO_THROW(client->startRequest(buildPostStr(command)));
        runIOService();
        ASSERT_TRUE(client->receiveDone());

        // Read the response generated by the server.
        HttpResponsePtr hr;
        ASSERT_NO_THROW(hr = parseResponse(client->getResponse()));
        response = hr->getBody();

        // Now close client.
        client->close();

        ASSERT_NO_THROW(io_service->poll());
    }
};

/// @brief Fixture class intended for testing HTTPS control channel in D2.
class HttpsCtrlChannelD2Test : public BaseCtrlChannelD2Test {
public:

    /// @brief Create a server with a HTTP command channel.
    virtual void createHttpChannelServer() override {
        // Just a simple config. The important part here is the socket
        // location information.
        string ca_dir(string(TEST_CA_DIR));
        ostringstream cf_st;
        cf_st << "{"
              << "    \"ip-address\": \"192.168.77.1\","
              << "    \"port\": 777,"
              << "    \"control-socket\": {"
              << "        \"socket-type\": \"https\","
              << "        \"socket-address\": \"127.0.0.1\","
              << "        \"socket-port\": 18125,"
              << "        \"trust-anchor\": \"" << ca_dir << "/kea-ca.crt\","
              << "        \"cert-file\": \"" << ca_dir << "/kea-server.crt\","
              << "        \"key-file\": \"" << ca_dir << "/kea-server.key\""
              << "    },"
              << "    \"tsig-keys\": [],"
              << "    \"forward-ddns\" : {},"
              << "    \"reverse-ddns\" : {}"
              << "}";

        ASSERT_TRUE(server_);

        ConstElementPtr config;
        ASSERT_NO_THROW(config = parseDHCPDDNS(cf_st.str(), true));
        ASSERT_NO_THROW(d2Controller()->initProcess());
        D2ProcessPtr proc = d2Controller()->getProcess();
        ASSERT_TRUE(proc);
        ConstElementPtr answer = proc->configure(config, false);
        ASSERT_TRUE(answer);
        ASSERT_NO_THROW(d2Controller()->registerCommands());

        int status = 0;
        ConstElementPtr txt = parseAnswer(status, answer);
        // This should succeed. If not, print the error message.
        ASSERT_EQ(0, status) << txt->str();

        // Now check that the socket was indeed open.
        ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    }

    /// @brief Conducts a command/response exchange via HttpCommandSocket.
    ///
    /// This method connects to the given server over the given address/port.
    /// If successful, it then sends the given command and retrieves the
    /// server's response.  Note that it polls the server's I/O service
    /// where needed to cause the server to process IO events on
    /// the control channel sockets.
    ///
    /// @param command the command text to execute in JSON form.
    /// @param response variable into which the received response should be
    /// placed.
    /// @param address The server address to connect to.
    /// @param port The server port to connect to.
    virtual void sendHttpCommand(const string& command,
                                 string& response,
                                 std::string address = std::string(),
                                 int port = 0) override {
        response = "";
        IOServicePtr io_service = getIOService();
        ASSERT_TRUE(io_service);

        TlsContextPtr client_tls_context;
        configClient(client_tls_context);
        if (address.empty()) {
            address = SERVER_ADDRESS;
        }
        if (!port) {
            port = SERVER_PORT;
        }
        TestHttpsClientPtr client(new TestHttpsClient(io_service, client_tls_context,
                                                      address, port));
        ASSERT_TRUE(client);

        // Send the command. This will trigger server's handler which
        // receives data over the HTTP socket. The server will start
        // sending response to the client.
        ASSERT_NO_THROW(client->startRequest(buildPostStr(command)));
        runIOService();
        ASSERT_TRUE(client->receiveDone());

        // Read the response generated by the server.
        HttpResponsePtr hr;
        ASSERT_NO_THROW(hr = parseResponse(client->getResponse()));
        response = hr->getBody();

        // Now close client.
        client->close();

        ASSERT_NO_THROW(io_service->poll());
    }
};

// Tests that the server properly responds to invalid commands.
void
BaseCtrlChannelD2Test::testInvalid() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    sendHttpCommand("{ \"command\": \"bogus\" }", response);
    EXPECT_EQ("[ { \"result\": 2, \"text\": \"'bogus' command not supported.\" } ]",
              response);

    sendHttpCommand("utter nonsense", response);
    EXPECT_EQ("{ \"result\": 400, \"text\": \"Bad Request\" }", response);
}

TEST_F(HttpCtrlChannelD2Test, invalid) {
    testInvalid();
}

TEST_F(HttpsCtrlChannelD2Test, invalid) {
    testInvalid();
}

// Tests that the server properly responds to shutdown command.
void
BaseCtrlChannelD2Test::testShutdown() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    sendHttpCommand("{ \"command\": \"shutdown\" }", response);
    EXPECT_EQ("[ { \"result\": 0, \"text\": \"Shutdown initiated, type is: normal\" } ]",
              response);
    EXPECT_EQ(EXIT_SUCCESS, server_->getExitValue());
}

TEST_F(HttpCtrlChannelD2Test, shutdown) {
    testShutdown();
}

TEST_F(HttpsCtrlChannelD2Test, shutdown) {
    testShutdown();
}

// Tests that the server sets exit value supplied as argument
// to shutdown command.
void
BaseCtrlChannelD2Test::testShutdownExitValue() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    sendHttpCommand("{ \"command\": \"shutdown\", "
                    "\"arguments\": { \"exit-value\": 77 }}",
                    response);

    EXPECT_EQ("[ { \"result\": 0, \"text\": \"Shutdown initiated, type is: normal\" } ]",
              response);

    EXPECT_EQ(77, server_->getExitValue());
}

TEST_F(HttpCtrlChannelD2Test, shutdownExitValue) {
    testShutdownExitValue();
}

TEST_F(HttpsCtrlChannelD2Test, shutdownExitValue) {
    testShutdownExitValue();
}

// This test verifies that the D2 server handles version-get commands.
void
BaseCtrlChannelD2Test::testGetVersion() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    // Send the version-get command.
    sendHttpCommand("{ \"command\": \"version-get\" }", response);
    EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
    EXPECT_TRUE(response.find("log4cplus") != string::npos);
    EXPECT_FALSE(response.find("Hooks directory: ") != string::npos);

    // Send the build-report command.
    sendHttpCommand("{ \"command\": \"build-report\" }", response);
    EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
    EXPECT_TRUE(response.find("Hooks directory: ") != string::npos);
}

TEST_F(HttpCtrlChannelD2Test, getVersion) {
    testGetVersion();
}

TEST_F(HttpsCtrlChannelD2Test, getVersion) {
    testGetVersion();
}

// Tests that the server properly responds to list-commands command.
void
BaseCtrlChannelD2Test::testListCommands() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    sendHttpCommand("{ \"command\": \"list-commands\" }", response);

    ConstElementPtr rsp;
    EXPECT_NO_THROW(rsp = Element::fromJSON(response));

    // We expect the server to report at least the following commands:
    checkListCommands(rsp, "build-report");
    checkListCommands(rsp, "config-get");
    checkListCommands(rsp, "config-hash-get");
    checkListCommands(rsp, "config-reload");
    checkListCommands(rsp, "config-set");
    checkListCommands(rsp, "config-test");
    checkListCommands(rsp, "config-write");
    checkListCommands(rsp, "list-commands");
    checkListCommands(rsp, "statistic-get");
    checkListCommands(rsp, "statistic-get-all");
    checkListCommands(rsp, "statistic-reset");
    checkListCommands(rsp, "statistic-reset-all");
    checkListCommands(rsp, "status-get");
    checkListCommands(rsp, "shutdown");
    checkListCommands(rsp, "version-get");
}

TEST_F(HttpCtrlChannelD2Test, listCommands) {
    testListCommands();
}

TEST_F(HttpsCtrlChannelD2Test, listCommands) {
    testListCommands();
}

// This test verifies that the D2 server handles status-get commands.
void
BaseCtrlChannelD2Test::testStatusGet() {
    EXPECT_NO_THROW(createHttpChannelServer());

    std::string response_txt;

    // Send the status-get command.
    sendHttpCommand("{ \"command\": \"status-get\" }", response_txt);
    ConstElementPtr response_list;
    ASSERT_NO_THROW(response_list = Element::fromJSON(response_txt));
    ASSERT_TRUE(response_list);
    ASSERT_EQ(Element::list, response_list->getType());
    EXPECT_EQ(1, response_list->size());
    ConstElementPtr response = response_list->get(0);
    ASSERT_TRUE(response);
    ASSERT_EQ(Element::map, response->getType());
    EXPECT_EQ(2, response->size());
    ConstElementPtr result = response->get("result");
    ASSERT_TRUE(result);
    ASSERT_EQ(Element::integer, result->getType());
    EXPECT_EQ(0, result->intValue());
    ConstElementPtr arguments = response->get("arguments");
    ASSERT_EQ(Element::map, arguments->getType());

    // The returned pid should be the pid of our process.
    auto found_pid = arguments->get("pid");
    ASSERT_TRUE(found_pid);
    EXPECT_EQ(static_cast<int64_t>(getpid()), found_pid->intValue());

    // It is hard to check the actual reload time as it is based
    // on current time. Let's just make sure it is within a reasonable
    // range.
    auto found_reload = arguments->get("reload");
    ASSERT_TRUE(found_reload);
    EXPECT_LE(found_reload->intValue(), 5);
    EXPECT_GE(found_reload->intValue(), 0);

    /// @todo uptime is not available in this test, because the launch()
    /// function is not called. This is not critical to test here,
    /// because the same logic is tested for CA and in that case the
    /// uptime is tested.
}

TEST_F(HttpCtrlChannelD2Test, statusGet) {
    testStatusGet();
}

TEST_F(HttpsCtrlChannelD2Test, statusGet) {
    testStatusGet();
}

// Tests if the server returns its configuration using config-get.
// Note there are separate tests that verify if toElement() called by the
// config-get handler are actually converting the configuration correctly.
void
BaseCtrlChannelD2Test::testConfigGet() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    sendHttpCommand("{ \"command\": \"config-get\" }", response);
    ConstElementPtr rsp;

    // The response should be a valid JSON.
    EXPECT_NO_THROW(rsp = Element::fromJSON(response));
    ASSERT_TRUE(rsp);

    int status;
    ConstElementPtr cfg = parseListAnswer(status, rsp);
    EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);

    // Ok, now roughly check if the response seems legit.
    ASSERT_TRUE(cfg);
    ASSERT_EQ(Element::map, cfg->getType());
    EXPECT_TRUE(cfg->get("DhcpDdns"));
}

TEST_F(HttpCtrlChannelD2Test, configGet) {
    testConfigGet();
}

TEST_F(HttpsCtrlChannelD2Test, configGet) {
    testConfigGet();
}

// Tests if the server returns the hash of its configuration using
// config-hash-get.
void
BaseCtrlChannelD2Test::testConfigHashGet() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    sendHttpCommand("{ \"command\": \"config-hash-get\" }", response);
    ConstElementPtr rsp;

    // The response should be a valid JSON.
    EXPECT_NO_THROW(rsp = Element::fromJSON(response));
    ASSERT_TRUE(rsp);

    int status;
    ConstElementPtr args = parseListAnswer(status, rsp);
    EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
    // The parseListAnswer is trying to be smart with ignoring hash.
    // But this time we really want to see the hash, so we'll retrieve
    // the arguments manually.
    ASSERT_NO_THROW(args = rsp->get(0)->get(CONTROL_ARGUMENTS));

    // Ok, now roughly check if the response seems legit.
    ASSERT_TRUE(args);
    ASSERT_EQ(Element::map, args->getType());
    ConstElementPtr hash = args->get("hash");
    ASSERT_TRUE(hash);
    ASSERT_EQ(Element::string, hash->getType());
    // SHA-256 -> 64 hex digits.
    EXPECT_EQ(64, hash->stringValue().size());
}

TEST_F(HttpCtrlChannelD2Test, configHashGet) {
    testConfigHashGet();
}

TEST_F(HttpsCtrlChannelD2Test, configHashGet) {
    testConfigHashGet();
}

// Verify that the "config-test" command will do what we expect.
TEST_F(HttpCtrlChannelD2Test, configTest) {

    string d2_cfg_txt =
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_cfg_txt, true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    EXPECT_EQ("{ \"arguments\": { \"hash\": \"029AE1208415D6911B5651A6F82D054F55B7877D2589CFD1DCEB5BFFCD3B13A3\" }, \"result\": 0, \"text\": \"Configuration applied successfully.\" }",
              answer->str());
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    // Check that the config was indeed applied.
    D2CfgMgrPtr cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(cfg_mgr);
    D2CfgContextPtr d2_context = cfg_mgr->getD2CfgContext();
    ASSERT_TRUE(d2_context);
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());

    // Create a config with invalid content that should fail to parse.
    string config_test_txt =
        "{ \"command\": \"config-test\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n"
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"BOGUS\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n"
        "}} \n";

    // Send the config-test command.
    string response;
    sendHttpCommand(config_test_txt, response);

    // Should fail with a syntax error.
    EXPECT_EQ("[ { \"result\": 1, \"text\": \"missing parameter 'name' (<string>:10:14)\" } ]",
              response);

    // Check that the config was not lost (fix: reacquire the context).
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    // Create a valid config with two keys and no command channel.
    config_test_txt =
        "{ \"command\": \"config-test\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n"
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"}, \n"
        "           {\"name\": \"d2_key.billcat.net\", \n"
        "            \"algorithm\": \"hmac-md5\", \n"
        "            \"digest-bits\": 120, \n"
        "            \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ] \n"
        "    } \n"
        "}} \n";

    // Send the config-test command.
    sendHttpCommand(config_test_txt, response);

    // Verify the configuration was successful.
    EXPECT_EQ("[ { \"result\": 0, \"text\": \"Configuration check successful\" } ]",
              response);

    // Check that the config was not applied.
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());
}

// Verify that the "config-test" command will do what we expect.
TEST_F(HttpsCtrlChannelD2Test, configTest) {

    string ca_dir(string(TEST_CA_DIR));
    ostringstream d2_st;
    d2_st << "    { \n"
          << "        \"ip-address\": \"192.168.77.1\", \n"
          << "        \"port\": 777, \n"
          << "        \"forward-ddns\" : {}, \n"
          << "        \"reverse-ddns\" : {}, \n"
          << "        \"tsig-keys\": [ \n"
          << "            {\"name\": \"d2_key.example.com\", \n"
          << "             \"algorithm\": \"hmac-md5\", \n"
          << "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
          << "          ], \n"
          << "        \"control-socket\": { \n"
          << "           \"socket-type\": \"https\", \n"
          << "           \"socket-address\": \"127.0.0.1\", \n"
          << "           \"socket-port\": 18125, \n"
          << "        \"trust-anchor\": \"" << ca_dir << "/kea-ca.crt\", \n"
          << "        \"cert-file\": \"" << ca_dir << "/kea-server.crt\", \n"
          << "        \"key-file\": \"" << ca_dir << "/kea-server.key\" \n"
          << "        } \n"
          << "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_st.str(), true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    // Verify the configuration was successful. The config contains random
    // file paths (CA directory), so the hash will be different each time.
    // As such, we can do simplified checks:
    // - verify the "result": 0 is there
    // - verify the "text": "Configuration applied successfully." is there
    string answer_txt = answer->str();
    EXPECT_NE(answer_txt.find("\"result\": 0"), std::string::npos);
    EXPECT_NE(answer_txt.find("\"text\": \"Configuration applied successfully.\""),
              std::string::npos);
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    // Check that the config was indeed applied.
    D2CfgMgrPtr cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(cfg_mgr);
    D2CfgContextPtr d2_context = cfg_mgr->getD2CfgContext();
    ASSERT_TRUE(d2_context);
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());

    // Create a config with invalid content that should fail to parse.
    string config_test_txt =
        "{ \"command\": \"config-test\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n"
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"BOGUS\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n"
        "}} \n";

    // Send the config-test command.
    string response;
    sendHttpCommand(config_test_txt, response);

    // Should fail with a syntax error.
    EXPECT_EQ("[ { \"result\": 1, \"text\": \"missing parameter 'name' (<string>:10:14)\" } ]",
              response);

    // Check that the config was not lost (fix: reacquire the context).
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    // Create a valid config with two keys and no command channel.
    config_test_txt =
        "{ \"command\": \"config-test\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n"
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"}, \n"
        "           {\"name\": \"d2_key.billcat.net\", \n"
        "            \"algorithm\": \"hmac-md5\", \n"
        "            \"digest-bits\": 120, \n"
        "            \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ] \n"
        "    } \n"
        "}} \n";

    // Send the config-test command.
    sendHttpCommand(config_test_txt, response);

    // Verify the configuration was successful.
    EXPECT_EQ("[ { \"result\": 0, \"text\": \"Configuration check successful\" } ]",
              response);

    // Check that the config was not applied.
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());
}

// Verify that the "config-set" command will do what we expect.
TEST_F(HttpCtrlChannelD2Test, configSet) {

    string d2_cfg_txt =
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_cfg_txt, true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    EXPECT_EQ("{ \"arguments\": { \"hash\": \"029AE1208415D6911B5651A6F82D054F55B7877D2589CFD1DCEB5BFFCD3B13A3\" }, \"result\": 0, \"text\": \"Configuration applied successfully.\" }",
              answer->str());
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    // Check that the config was indeed applied.
    D2CfgMgrPtr cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(cfg_mgr);
    D2CfgContextPtr d2_context = cfg_mgr->getD2CfgContext();
    ASSERT_TRUE(d2_context);
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());

    // Create a config with invalid content that should fail to parse.
    string config_set_txt =
        "{ \"command\": \"config-set\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n"
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"BOGUS\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n"
        "}} \n";

    // Send the config-set command.
    string response;
    sendHttpCommand(config_set_txt, response);

    // Should fail with a syntax error.
    EXPECT_EQ("[ { \"result\": 1, \"text\": \"missing parameter 'name' (<string>:10:14)\" } ]",
              response);

    // Check that the config was not lost (fix: reacquire the context).
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    // Create a valid config with two keys and no command channel.
    config_set_txt =
        "{ \"command\": \"config-set\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n"
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"}, \n"
        "           {\"name\": \"d2_key.billcat.net\", \n"
        "            \"algorithm\": \"hmac-md5\", \n"
        "            \"digest-bits\": 120, \n"
        "            \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ] \n"
        "    } \n"
        "}} \n";

    // Verify the HTTP control channel socket exists.
    EXPECT_TRUE(HttpCommandMgr::instance().getHttpListener());

    // Send the config-set command.
    sendHttpCommand(config_set_txt, response);

    // Verify the HTTP control channel socket no longer exists.
    ASSERT_NO_THROW(HttpCommandMgr::instance().closeCommandSockets());
    EXPECT_FALSE(HttpCommandMgr::instance().getHttpListener());

    // Verify the configuration was successful.
    EXPECT_EQ("[ { \"arguments\": { \"hash\": \"5206A1BEC7E3C6ADD5E97C5983861F97739EA05CFEAD823CBBC4"
              "524095AAA10A\" }, \"result\": 0, \"text\": \"Configuration applied successfully.\" } ]",
              response);

    // Check that the config was applied.
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(2, keys->size());
}

// Verify that the "config-set" command will do what we expect.
TEST_F(HttpsCtrlChannelD2Test, configSet) {

    string ca_dir(string(TEST_CA_DIR));
    ostringstream d2_st;
    d2_st << "    { \n"
          << "        \"ip-address\": \"192.168.77.1\", \n"
          << "        \"port\": 777, \n"
          << "        \"forward-ddns\" : {}, \n"
          << "        \"reverse-ddns\" : {}, \n"
          << "        \"tsig-keys\": [ \n"
          << "            {\"name\": \"d2_key.example.com\", \n"
          << "             \"algorithm\": \"hmac-md5\", \n"
          << "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
          << "          ], \n"
          << "        \"control-socket\": { \n"
          << "           \"socket-type\": \"https\", \n"
          << "           \"socket-address\": \"127.0.0.1\", \n"
          << "           \"socket-port\": 18125, \n"
          << "        \"trust-anchor\": \"" << ca_dir << "/kea-ca.crt\", \n"
          << "        \"cert-file\": \"" << ca_dir << "/kea-server.crt\", \n"
          << "        \"key-file\": \"" << ca_dir << "/kea-server.key\" \n"
          << "        } \n"
          << "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_st.str(), true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    // Verify the configuration was successful. The config contains random
    // file paths (CA directory), so the hash will be different each time.
    // As such, we can do simplified checks:
    // - verify the "result": 0 is there
    // - verify the "text": "Configuration applied successfully." is there
    string answer_txt = answer->str();
    EXPECT_NE(answer_txt.find("\"result\": 0"), std::string::npos);
    EXPECT_NE(answer_txt.find("\"text\": \"Configuration applied successfully.\""),
              std::string::npos);
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    // Check that the config was indeed applied.
    D2CfgMgrPtr cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(cfg_mgr);
    D2CfgContextPtr d2_context = cfg_mgr->getD2CfgContext();
    ASSERT_TRUE(d2_context);
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());

    // Create a config with invalid content that should fail to parse.
    string config_set_txt =
        "{ \"command\": \"config-set\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n"
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"BOGUS\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n"
        "}} \n";

    // Send the config-set command.
    string response;
    sendHttpCommand(config_set_txt, response);

    // Should fail with a syntax error.
    EXPECT_EQ("[ { \"result\": 1, \"text\": \"missing parameter 'name' (<string>:10:14)\" } ]",
              response);

    // Check that the config was not lost (fix: reacquire the context).
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    // Create a valid config with two keys and no command channel.
    config_set_txt =
        "{ \"command\": \"config-set\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n"
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"}, \n"
        "           {\"name\": \"d2_key.billcat.net\", \n"
        "            \"algorithm\": \"hmac-md5\", \n"
        "            \"digest-bits\": 120, \n"
        "            \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ] \n"
        "    } \n"
        "}} \n";

    // Verify the HTTP control channel socket exists.
    EXPECT_TRUE(HttpCommandMgr::instance().getHttpListener());

    // Send the config-set command.
    sendHttpCommand(config_set_txt, response);

    // Verify the HTTP control channel socket no longer exists.
    ASSERT_NO_THROW(HttpCommandMgr::instance().closeCommandSockets());
    EXPECT_FALSE(HttpCommandMgr::instance().getHttpListener());

    // Verify the configuration was successful.
    EXPECT_EQ("[ { \"arguments\": { \"hash\": \"5206A1BEC7E3C6ADD5E97C5983861F97739EA05CFEAD823CBBC4"
              "524095AAA10A\" }, \"result\": 0, \"text\": \"Configuration applied successfully.\" } ]",
              response);

    // Check that the config was applied.
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(2, keys->size());
}

// Tests if config-write can be called without any parameters.
void
BaseCtrlChannelD2Test::testWriteConfigNoFilename() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    // This is normally set by the command line -c parameter.
    server_->setConfigFile("test1.json");

    // If the filename is not explicitly specified, the name used
    // in -c command line switch is used.
    sendHttpCommand("{ \"command\": \"config-write\" }", response);

    checkConfigWrite(response, CONTROL_RESULT_SUCCESS, "test1.json");
    ::remove("test1.json");
}

TEST_F(HttpCtrlChannelD2Test, writeConfigNoFilename) {
    testWriteConfigNoFilename();
}

TEST_F(HttpsCtrlChannelD2Test, writeConfigNoFilename) {
    testWriteConfigNoFilename();
}

// Tests if config-write can be called with a valid filename as parameter.
void
BaseCtrlChannelD2Test::testWriteConfigFilename() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    sendHttpCommand("{ \"command\": \"config-write\", "
                    "\"arguments\": { \"filename\": \"test2.json\" } }",
                    response);

    checkConfigWrite(response, CONTROL_RESULT_SUCCESS, "test2.json");
    ::remove("test2.json");
}

TEST_F(HttpCtrlChannelD2Test, writeConfigFilename) {
    testWriteConfigFilename();
}

TEST_F(HttpsCtrlChannelD2Test, writeConfigFilename) {
    testWriteConfigFilename();
}

// Tests if config-reload attempts to reload a file and reports that the
// file is missing.
void
BaseCtrlChannelD2Test::testConfigReloadMissingFile() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    // This is normally set to whatever value is passed to -c when the server is
    // started, but we're not starting it that way, so need to set it by hand.
    server_->setConfigFile("does-not-exist.json");

    // Tell the server to reload its configuration. It should attempt to load
    // does-not-exist.json (and fail, because the file is not there).
    sendHttpCommand("{ \"command\": \"config-reload\" }", response);

    // Verify the reload was rejected.
    string expected = "[ { \"result\": 1, \"text\": "
        "\"Configuration parsing failed: "
        "Unable to open file does-not-exist.json\" } ]";
    EXPECT_EQ(expected, response);
}

TEST_F(HttpCtrlChannelD2Test, configReloadMissingFile) {
    testConfigReloadMissingFile();
}

TEST_F(HttpsCtrlChannelD2Test, configReloadMissingFile) {
    testConfigReloadMissingFile();
}

// Tests if config-reload attempts to reload a file and reports that the
// file is not a valid JSON.
void
BaseCtrlChannelD2Test::testConfigReloadBrokenFile() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    // This is normally set to whatever value is passed to -c when the server is
    // started, but we're not starting it that way, so need to set it by hand.
    server_->setConfigFile("testbad.json");

    // Although Kea is smart, its AI routines are not smart enough to handle
    // this one... at least not yet.
    ofstream f("testbad.json", ios::trunc);
    f << "bla bla bla...";
    f.close();

    // Tell the server to reload its configuration. It should attempt to load
    // testbad.json (and fail, because the file is not valid JSON).
    sendHttpCommand("{ \"command\": \"config-reload\" }", response);

    // Verify the reload was rejected.
    string expected = "[ { \"result\": 1, \"text\": "
        "\"Configuration parsing failed: "
        "testbad.json:1.1: Invalid character: b\" } ]";
    EXPECT_EQ(expected, response);

    // Remove the file.
    ::remove("testbad.json");
}

TEST_F(HttpCtrlChannelD2Test, configReloadBrokenFile) {
    testConfigReloadBrokenFile();
}

TEST_F(HttpsCtrlChannelD2Test, configReloadBrokenFile) {
    testConfigReloadBrokenFile();
}

// Tests if config-reload attempts to reload a file and reports that the
// file is loaded correctly.
void
BaseCtrlChannelD2Test::testConfigReloadFileValid() {
    EXPECT_NO_THROW(createHttpChannelServer());
    string response;

    // This is normally set to whatever value is passed to -c when the server is
    // started, but we're not starting it that way, so need to set it by hand.
    server_->setConfigFile("testvalid.json");

    // Ok, enough fooling around. Let's create a valid config.
    ofstream f("testvalid.json", ios::trunc);
    f << "{ \"DhcpDdns\": "
      << "{"
      << " \"ip-address\": \"192.168.77.1\" , "
      << " \"port\": 777 , "
      << "\"tsig-keys\": [], "
      << "\"forward-ddns\" : {}, "
      << "\"reverse-ddns\" : {} "
      << "}"
      << " }" << endl;
    f.close();

    // Tell the server to reload its configuration. It should attempt to load
    // testvalid.json (and succeed).
    sendHttpCommand("{ \"command\": \"config-reload\" }", response);

    // Verify the reload was successful.
    string expected = "[ { \"arguments\": { \"hash\": \"DC1235F1948D68E06F1425FC28BE326EF01DC4856C3"
                      "833673B9CC8732409B04D\" }, \"result\": 0, \"text\": "
                      "\"Configuration applied successfully.\" } ]";
    EXPECT_EQ(expected, response);

    // Check that the config was indeed applied.
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    D2CfgMgrPtr d2_cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(d2_cfg_mgr);
    D2ParamsPtr d2_params = d2_cfg_mgr->getD2Params();
    ASSERT_TRUE(d2_params);

    EXPECT_EQ("192.168.77.1", d2_params->getIpAddress().toText());
    EXPECT_EQ(777, d2_params->getPort());
    EXPECT_FALSE(d2_cfg_mgr->forwardUpdatesEnabled());
    EXPECT_FALSE(d2_cfg_mgr->reverseUpdatesEnabled());

    // Remove the file.
    ::remove("testvalid.json");
}

TEST_F(HttpCtrlChannelD2Test, configReloadFileValid) {
    testConfigReloadFileValid();
}

TEST_F(HttpsCtrlChannelD2Test, configReloadFileValid) {
    testConfigReloadFileValid();
}

/// Verify that concurrent connections over the HTTP control channel can be
/// established.
TEST_F(HttpCtrlChannelD2Test, concurrentConnections) {
    EXPECT_NO_THROW(createHttpChannelServer());

    const size_t NB = 5;
    vector<IOServicePtr> io_services;
    vector<TestHttpClientPtr> clients;

    // Create clients.
    for (size_t i = 0; i < NB; ++i) {
        IOServicePtr io_service(new IOService());
        io_services.push_back(io_service);
        TestHttpClientPtr client(new TestHttpClient(io_service, SERVER_ADDRESS,
                                                    SERVER_PORT));
        clients.push_back(client);
    }
    ASSERT_EQ(NB, io_services.size());
    ASSERT_EQ(NB, clients.size());

    // Send requests and receive responses.
    atomic<size_t> terminated;
    terminated = 0;
    vector<thread> threads;
    const string command = "{ \"command\": \"list-commands\" }";
    for (size_t i = 0; i < NB; ++i) {
        threads.push_back(thread([&, i] () {
            TestHttpClientPtr client = clients[i];
            ASSERT_TRUE(client);
            client->startRequest(buildPostStr(command));
            IOServicePtr io_service = io_services[i];
            ASSERT_TRUE(io_service);
            io_service->run();
            ASSERT_TRUE(client->receiveDone());
            HttpResponsePtr hr;
            ASSERT_NO_THROW(hr = parseResponse(client->getResponse()));
            string response = hr->getBody();
            EXPECT_TRUE(response.find("\"result\": 0") != std::string::npos);
            client->close();
            ++terminated;
        }));
    }
    ASSERT_EQ(NB, threads.size());

    // Run the service IO services with a timeout.
    IntervalTimer test_timer(getIOService());
    bool timeout = false;
    test_timer.setup([&timeout] () { timeout = true; },
                     TEST_TIMEOUT, IntervalTimer::ONE_SHOT);
    while (!timeout && (terminated < NB)) {
        getIOService()->poll();
    }
    test_timer.cancel();
    EXPECT_FALSE(timeout);

    // Cleanup clients.
    for (IOServicePtr io_service : io_services) {
        io_service->stopAndPoll();
    }
    for (auto th = threads.begin(); th != threads.end(); ++th) {
        th->join();
    }
}

/// Verify that concurrent connections over the HTTPS control channel can be
/// established.
TEST_F(HttpsCtrlChannelD2Test, concurrentConnections) {
    EXPECT_NO_THROW(createHttpChannelServer());

    const size_t NB = 5;
    vector<IOServicePtr> io_services;
    vector<TestHttpsClientPtr> clients;
    vector<TlsContextPtr> tls_contexts;

    // Create clients.
    for (size_t i = 0; i < NB; ++i) {
        IOServicePtr io_service(new IOService());
        io_services.push_back(io_service);
        TlsContextPtr tls_context;
        configClient(tls_context);
        tls_contexts.push_back(tls_context);
        TestHttpsClientPtr client(new TestHttpsClient(io_service,
                                                      tls_context,
                                                      SERVER_ADDRESS,
                                                      SERVER_PORT));
        clients.push_back(client);
    }
    ASSERT_EQ(NB, io_services.size());
    ASSERT_EQ(NB, clients.size());

    // Send requests and receive responses.
    atomic<size_t> terminated;
    terminated = 0;
    vector<thread> threads;
    const string command = "{ \"command\": \"list-commands\" }";
    for (size_t i = 0; i < NB; ++i) {
        threads.push_back(thread([&, i] () {
            TestHttpsClientPtr client = clients[i];
            ASSERT_TRUE(client);
            client->startRequest(buildPostStr(command));
            IOServicePtr io_service = io_services[i];
            ASSERT_TRUE(io_service);
            io_service->run();
            ASSERT_TRUE(client->receiveDone());
            HttpResponsePtr hr;
            ASSERT_NO_THROW(hr = parseResponse(client->getResponse()));
            string response = hr->getBody();
            EXPECT_TRUE(response.find("\"result\": 0") != std::string::npos);
            client->close();
            ++terminated;
        }));
    }
    ASSERT_EQ(NB, threads.size());

    // Run the service IO services with a timeout.
    IntervalTimer test_timer(getIOService());
    bool timeout = false;
    test_timer.setup([&timeout] () { timeout = true; },
                     TEST_TIMEOUT, IntervalTimer::ONE_SHOT);
    while (!timeout && (terminated < NB)) {
        getIOService()->poll();
    }
    test_timer.cancel();
    EXPECT_FALSE(timeout);

    // Cleanup clients.
    for (IOServicePtr io_service : io_services) {
        io_service->stopAndPoll();
    }
    for (auto th = threads.begin(); th != threads.end(); ++th) {
        th->join();
    }
}

// This test verifies that the server can receive and process a large command.
void
BaseCtrlChannelD2Test::testLongCommand() {

    ostringstream command;

    // This is the desired size of the command sent to the server (1MB).
    // The actual size sent will be slightly greater than that.
    const size_t command_size = 1024 * 1000;

    while (command.tellp() < static_cast<std::streampos>(command_size)) {

        // We're sending command 'foo' with arguments being a list of
        // strings. If this is the first transmission, send command name
        // and open the arguments list. Also insert the first argument
        // so as all subsequent arguments can be prefixed with a comma.
        if (command.tellp() == 0) {
            command << "{ \"command\": \"foo\", \"arguments\": [ \"begin\"";

        } else {
            // Generate a random number and insert it into the stream as
            // 10 digits long string.
            ostringstream arg;
            arg << setw(10) << std::rand();
            // Append the argument in the command.
            command << ", \"" << arg.str() << "\"\n";

            // If we have hit the limit of the command size, close braces to
            // get appropriate JSON.
            if (command.tellp() > static_cast<std::streampos>(command_size)) {
                command << "] }";
            }
        }
    }

    ASSERT_NO_THROW(
        CommandMgr::instance().registerCommand("foo",
            std::bind(&HttpCtrlChannelD2Test::longCommandHandler,
                      command.str(), ph::_1, ph::_2));
    );

    createHttpChannelServer();

    string response;
    ASSERT_NO_THROW(sendHttpCommand(command.str(), response));

    EXPECT_EQ("[ { \"result\": 0, \"text\": \"long command received ok\" } ]",
              response);
}

TEST_F(HttpCtrlChannelD2Test, longCommand) {
    testLongCommand();
}

TEST_F(HttpsCtrlChannelD2Test, longCommand) {
    testLongCommand();
}

// This test verifies that the server can send long response to the client.
void
BaseCtrlChannelD2Test::testLongResponse() {
    // We need to generate large response. The simplest way is to create
    // a command and a handler which will generate some static response
    // of a desired size.
    ASSERT_NO_THROW(
        CommandMgr::instance().registerCommand("foo",
            std::bind(&HttpCtrlChannelD2Test::longResponseHandler,
                      ph::_1, ph::_2));
    );

    createHttpChannelServer();

    // The entire response should be received but anyway check it.
    ConstElementPtr raw_response =
        longResponseHandler("foo", ConstElementPtr());
    ElementPtr json_response = Element::createList();
    json_response->add(isc::data::copy(raw_response));
    string reference_response = json_response->str();

    string response;
    string command = "{ \"command\": \"foo\", \"arguments\": { }  }";
    ASSERT_NO_THROW(sendHttpCommand(command, response));

    // Make sure we have received correct response.
    EXPECT_EQ(reference_response, response);
}

TEST_F(HttpCtrlChannelD2Test, longResponse) {
    testLongResponse();
}

TEST_F(HttpsCtrlChannelD2Test, longResponse) {
    testLongResponse();
}

// Verify that the dual stack scenario works as expect.
TEST_F(HttpCtrlChannelD2Test, dualStack) {

    string d2_cfg_txt =
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-sockets\": [ { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        }, { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"::1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } ] \n"
        "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_cfg_txt, true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    EXPECT_EQ("{ \"arguments\": { \"hash\": \"948CDC181979EBB24333894B477C6A29FF158800A11E8AF7C7BA9981F15FC62D\" }, \"result\": 0, \"text\": \"Configuration applied successfully.\" }",
              answer->str());
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    string response;

    // Send the version-get command
    sendHttpCommand("{ \"command\": \"version-get\" }", response);
    EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
    EXPECT_TRUE(response.find("log4cplus") != string::npos);
    EXPECT_FALSE(response.find("Hooks directory: ") != string::npos);

    // Send the version-get command
    sendHttpCommand("{ \"command\": \"version-get\" }", response, "::1");
    EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
    EXPECT_TRUE(response.find("log4cplus") != string::npos);
    EXPECT_FALSE(response.find("Hooks directory: ") != string::npos);
}

// Verify that the dual stack scenario works as expect.
TEST_F(HttpsCtrlChannelD2Test, dualStack) {

    string ca_dir(string(TEST_CA_DIR));
    ostringstream d2_st;
    d2_st << "    { \n"
          << "        \"ip-address\": \"192.168.77.1\", \n"
          << "        \"port\": 777, \n"
          << "        \"forward-ddns\" : {}, \n"
          << "        \"reverse-ddns\" : {}, \n"
          << "        \"tsig-keys\": [ \n"
          << "            {\"name\": \"d2_key.example.com\", \n"
          << "             \"algorithm\": \"hmac-md5\", \n"
          << "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
          << "          ], \n"
          << "        \"control-sockets\": [ { \n"
          << "           \"socket-type\": \"https\", \n"
          << "           \"socket-address\": \"127.0.0.1\", \n"
          << "           \"socket-port\": 18125, \n"
          << "           \"trust-anchor\": \"" << ca_dir << "/kea-ca.crt\", \n"
          << "           \"cert-file\": \"" << ca_dir << "/kea-server.crt\", \n"
          << "           \"key-file\": \"" << ca_dir << "/kea-server.key\" \n"
          << "        }, { \n"
          << "           \"socket-type\": \"https\", \n"
          << "           \"socket-address\": \"::1\", \n"
          << "           \"socket-port\": 18125, \n"
          << "           \"trust-anchor\": \"" << ca_dir << "/kea-ca.crt\", \n"
          << "           \"cert-file\": \"" << ca_dir << "/kea-server.crt\", \n"
          << "           \"key-file\": \"" << ca_dir << "/kea-server.key\" \n"
          << "        } ] \n"
          << "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_st.str(), true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    // Verify the configuration was successful. The config contains random
    // file paths (CA directory), so the hash will be different each time.
    // As such, we can do simplified checks:
    // - verify the "result": 0 is there
    // - verify the "text": "Configuration applied successfully." is there
    string answer_txt = answer->str();
    EXPECT_NE(answer_txt.find("\"result\": 0"), std::string::npos);
    EXPECT_NE(answer_txt.find("\"text\": \"Configuration applied successfully.\""),
              std::string::npos);
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    string response;

    // Send the version-get command
    sendHttpCommand("{ \"command\": \"version-get\" }", response);
    EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
    EXPECT_TRUE(response.find("log4cplus") != string::npos);
    EXPECT_FALSE(response.find("Hooks directory: ") != string::npos);

    // Send the version-get command
    sendHttpCommand("{ \"command\": \"version-get\" }", response, "::1");
    EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
    EXPECT_TRUE(response.find("log4cplus") != string::npos);
    EXPECT_FALSE(response.find("Hooks directory: ") != string::npos);
}

// This test verifies that the server signals timeout if the transmission
// takes too long, having received no data from the client.
void
BaseCtrlChannelD2Test::testConnectionTimeoutNoData() {
    // Set connection timeout to 2s to prevent long waiting time for the
    // timeout during this test.
    const unsigned short timeout = 2000;
    HttpCommandMgr::instance().setConnectionTimeout(timeout);

    createHttpChannelServer();

    string response;
    ASSERT_NO_THROW(sendHttpCommand("{ \"command\": ", response));

    EXPECT_EQ("{ \"result\": 400, \"text\": \"Bad Request\" }", response);
}

TEST_F(HttpCtrlChannelD2Test, connectionTimeoutNoData) {
    testConnectionTimeoutNoData();
}

TEST_F(HttpsCtrlChannelD2Test, connectionTimeoutNoData) {
    testConnectionTimeoutNoData();
}

// Verify that the "config-set" command will reuse listener
TEST_F(HttpCtrlChannelD2Test, noListenerChange) {

    string d2_cfg_txt =
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_cfg_txt, true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    EXPECT_EQ("{ \"arguments\": { \"hash\": \"029AE1208415D6911B5651A6F82D054F55B7877D2589CFD1DCEB5BFFCD3B13A3\" }, \"result\": 0, \"text\": \"Configuration applied successfully.\" }",
              answer->str());
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    // Check that the config was indeed applied.
    D2CfgMgrPtr cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(cfg_mgr);
    D2CfgContextPtr d2_context = cfg_mgr->getD2CfgContext();
    ASSERT_TRUE(d2_context);
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    auto const listener = HttpCommandMgr::instance().getHttpListener().get();
    ASSERT_FALSE(HttpCommandMgr::instance().getHttpListener()->getTlsContext());

    // Create a config with same content that should not recreate listener.
    string config_set_txt =
        "{ \"command\": \"config-set\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n";

    config_set_txt += d2_cfg_txt;
    config_set_txt += "}} \n";

    // Send the config-set command.
    string response;
    sendHttpCommand(config_set_txt, response);

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    EXPECT_EQ(listener, HttpCommandMgr::instance().getHttpListener().get());
    ASSERT_FALSE(HttpCommandMgr::instance().getHttpListener()->getTlsContext());

    // Verify the configuration was successful.
    EXPECT_EQ("[ { \"arguments\": { \"hash\": \"029AE1208415D6911B5651A6F82D054F55B7877D2589CFD1DCEB5BFFCD3B13A3\" }, \"result\": 0, \"text\": \"Configuration applied successfully.\" } ]",
              response);

    // Check that the config was applied.
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());
}

// Verify that the "config-set" command will reuse listener
TEST_F(HttpsCtrlChannelD2Test, noListenerChange) {

    string ca_dir(string(TEST_CA_DIR));
    ostringstream d2_st;
    d2_st << "    { \n"
          << "        \"ip-address\": \"192.168.77.1\", \n"
          << "        \"port\": 777, \n"
          << "        \"forward-ddns\" : {}, \n"
          << "        \"reverse-ddns\" : {}, \n"
          << "        \"tsig-keys\": [ \n"
          << "            {\"name\": \"d2_key.example.com\", \n"
          << "             \"algorithm\": \"hmac-md5\", \n"
          << "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
          << "          ], \n"
          << "        \"control-socket\": { \n"
          << "           \"socket-type\": \"https\", \n"
          << "           \"socket-address\": \"127.0.0.1\", \n"
          << "           \"socket-port\": 18125, \n"
          << "        \"trust-anchor\": \"" << ca_dir << "/kea-ca.crt\", \n"
          << "        \"cert-file\": \"" << ca_dir << "/kea-server.crt\", \n"
          << "        \"key-file\": \"" << ca_dir << "/kea-server.key\" \n"
          << "        } \n"
          << "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_st.str(), true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    // Verify the configuration was successful. The config contains random
    // file paths (CA directory), so the hash will be different each time.
    // As such, we can do simplified checks:
    // - verify the "result": 0 is there
    // - verify the "text": "Configuration applied successfully." is there
    string answer_txt = answer->str();
    EXPECT_NE(answer_txt.find("\"result\": 0"), std::string::npos);
    EXPECT_NE(answer_txt.find("\"text\": \"Configuration applied successfully.\""),
              std::string::npos);
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    // Check that the config was indeed applied.
    D2CfgMgrPtr cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(cfg_mgr);
    D2CfgContextPtr d2_context = cfg_mgr->getD2CfgContext();
    ASSERT_TRUE(d2_context);
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    auto const listener = HttpCommandMgr::instance().getHttpListener().get();
    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener()->getTlsContext());
    auto const context = HttpCommandMgr::instance().getHttpListener()->getTlsContext().get();

    // Create a config with same content that should not recreate listener.
    string config_set_txt =
        "{ \"command\": \"config-set\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n";

    config_set_txt += d2_st.str();
    config_set_txt += "}} \n";

    // Send the config-set command.
    string response;
    sendHttpCommand(config_set_txt, response);

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    EXPECT_EQ(listener, HttpCommandMgr::instance().getHttpListener().get());
    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener()->getTlsContext());
    // The TLS settings have been applied
    EXPECT_NE(context, HttpCommandMgr::instance().getHttpListener()->getTlsContext().get());

    // Verify the configuration was successful.
    EXPECT_NE(response.find("\"result\": 0"), std::string::npos);
    EXPECT_NE(response.find("\"text\": \"Configuration applied successfully.\""),
              std::string::npos);

    // Check that the config was applied.
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());
}

// Verify that the "config-set" command will exit with an error
TEST_F(HttpCtrlChannelD2Test, handleHttpToHttpsSwitch) {

    string d2_cfg_txt =
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_cfg_txt, true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    EXPECT_EQ("{ \"arguments\": { \"hash\": \"029AE1208415D6911B5651A6F82D054F55B7877D2589CFD1DCEB5BFFCD3B13A3\" }, \"result\": 0, \"text\": \"Configuration applied successfully.\" }",
              answer->str());
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    // Check that the config was indeed applied.
    D2CfgMgrPtr cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(cfg_mgr);
    D2CfgContextPtr d2_context = cfg_mgr->getD2CfgContext();
    ASSERT_TRUE(d2_context);
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    auto const listener = HttpCommandMgr::instance().getHttpListener().get();
    ASSERT_FALSE(HttpCommandMgr::instance().getHttpListener()->getTlsContext());

    string ca_dir(string(TEST_CA_DIR));
    ostringstream d2_st;
    d2_st << "    { \n"
          << "        \"ip-address\": \"192.168.77.1\", \n"
          << "        \"port\": 777, \n"
          << "        \"forward-ddns\" : {}, \n"
          << "        \"reverse-ddns\" : {}, \n"
          << "        \"tsig-keys\": [ \n"
          << "            {\"name\": \"d2_key.example.com\", \n"
          << "             \"algorithm\": \"hmac-md5\", \n"
          << "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
          << "          ], \n"
          << "        \"control-socket\": { \n"
          << "           \"socket-type\": \"https\", \n"
          << "           \"socket-address\": \"127.0.0.1\", \n"
          << "           \"socket-port\": 18125, \n"
          << "        \"trust-anchor\": \"" << ca_dir << "/kea-ca.crt\", \n"
          << "        \"cert-file\": \"" << ca_dir << "/kea-server.crt\", \n"
          << "        \"key-file\": \"" << ca_dir << "/kea-server.key\" \n"
          << "        } \n"
          << "    } \n";

    // Create a config with HTTPS and same content that should not recreate listener.
    string config_set_txt =
        "{ \"command\": \"config-set\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n";

    config_set_txt += d2_st.str();
    config_set_txt += "}} \n";

    // Send the config-set command.
    string response;
    sendHttpCommand(config_set_txt, response);

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    EXPECT_EQ(listener, HttpCommandMgr::instance().getHttpListener().get());
    ASSERT_FALSE(HttpCommandMgr::instance().getHttpListener()->getTlsContext());

    // Verify the configuration was rejected.
    EXPECT_NE(response.find("\"result\": 1"), std::string::npos);
    EXPECT_NE(response.find("\"text\": \"Can not switch from HTTP to HTTPS sockets using the same address and port.\""),
              std::string::npos);

    // Check that the config was not applied.
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());
}

// Verify that the "config-set" command will exit with an error
TEST_F(HttpsCtrlChannelD2Test, handleHttpsToHttpSwitch) {

    string ca_dir(string(TEST_CA_DIR));
    ostringstream d2_st;
    d2_st << "    { \n"
          << "        \"ip-address\": \"192.168.77.1\", \n"
          << "        \"port\": 777, \n"
          << "        \"forward-ddns\" : {}, \n"
          << "        \"reverse-ddns\" : {}, \n"
          << "        \"tsig-keys\": [ \n"
          << "            {\"name\": \"d2_key.example.com\", \n"
          << "             \"algorithm\": \"hmac-md5\", \n"
          << "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
          << "          ], \n"
          << "        \"control-socket\": { \n"
          << "           \"socket-type\": \"https\", \n"
          << "           \"socket-address\": \"127.0.0.1\", \n"
          << "           \"socket-port\": 18125, \n"
          << "        \"trust-anchor\": \"" << ca_dir << "/kea-ca.crt\", \n"
          << "        \"cert-file\": \"" << ca_dir << "/kea-server.crt\", \n"
          << "        \"key-file\": \"" << ca_dir << "/kea-server.key\" \n"
          << "        } \n"
          << "    } \n";

    ASSERT_TRUE(server_);

    ConstElementPtr config;
    ASSERT_NO_THROW(config = parseDHCPDDNS(d2_st.str(), true));
    ASSERT_NO_THROW(d2Controller()->initProcess());
    D2ProcessPtr proc = d2Controller()->getProcess();
    ASSERT_TRUE(proc);
    ConstElementPtr answer = proc->configure(config, false);
    ASSERT_TRUE(answer);
    // Verify the configuration was successful. The config contains random
    // file paths (CA directory), so the hash will be different each time.
    // As such, we can do simplified checks:
    // - verify the "result": 0 is there
    // - verify the "text": "Configuration applied successfully." is there
    string answer_txt = answer->str();
    EXPECT_NE(answer_txt.find("\"result\": 0"), std::string::npos);
    EXPECT_NE(answer_txt.find("\"text\": \"Configuration applied successfully.\""),
              std::string::npos);
    ASSERT_NO_THROW(d2Controller()->registerCommands());

    // Check that the config was indeed applied.
    D2CfgMgrPtr cfg_mgr = proc->getD2CfgMgr();
    ASSERT_TRUE(cfg_mgr);
    D2CfgContextPtr d2_context = cfg_mgr->getD2CfgContext();
    ASSERT_TRUE(d2_context);
    TSIGKeyInfoMapPtr keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    auto const listener = HttpCommandMgr::instance().getHttpListener().get();
    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener()->getTlsContext());
    auto const context = HttpCommandMgr::instance().getHttpListener()->getTlsContext().get();

    string d2_cfg_txt =
        "    { \n"
        "        \"ip-address\": \"192.168.77.1\", \n"
        "        \"port\": 777, \n"
        "        \"forward-ddns\" : {}, \n"
        "        \"reverse-ddns\" : {}, \n"
        "        \"tsig-keys\": [ \n"
        "            {\"name\": \"d2_key.example.com\", \n"
        "             \"algorithm\": \"hmac-md5\", \n"
        "             \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\"} \n"
        "          ], \n"
        "        \"control-socket\": { \n"
        "           \"socket-type\": \"http\", \n"
        "           \"socket-address\": \"127.0.0.1\", \n"
        "           \"socket-port\": 18125 \n"
        "        } \n"
        "    } \n";

    // Create a config with HTTP and same content that should not recreate listener.
    string config_set_txt =
        "{ \"command\": \"config-set\", \n"
        "  \"arguments\": { \n"
        "    \"DhcpDdns\": \n";

    config_set_txt += d2_cfg_txt;
    config_set_txt += "}} \n";

    // Send the config-set command.
    string response;
    sendHttpCommand(config_set_txt, response);

    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener());
    EXPECT_EQ(listener, HttpCommandMgr::instance().getHttpListener().get());
    ASSERT_TRUE(HttpCommandMgr::instance().getHttpListener()->getTlsContext());
    // The TLS settings have not changed
    EXPECT_EQ(context, HttpCommandMgr::instance().getHttpListener()->getTlsContext().get());

    // Verify the configuration was rejected.
    EXPECT_EQ("[ { \"result\": 1, \"text\": \"Can not switch from HTTPS to HTTP sockets using the same address and port.\" } ]",
              response);

    // Check that the config was not applied.
    d2_context = cfg_mgr->getD2CfgContext();
    keys = d2_context->getKeys();
    ASSERT_TRUE(keys);
    EXPECT_EQ(1, keys->size());
}

} // end of anonymous namespace