dhcp4_test_utils.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. // Copyright (C) 2013-2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include <asiolink/io_address.h>
  8. #include <cc/data.h>
  9. #include <cc/command_interpreter.h>
  10. #include <dhcp4/json_config_parser.h>
  11. #include <dhcp4/tests/dhcp4_test_utils.h>
  12. #include <dhcp/option4_addrlst.h>
  13. #include <dhcp/option_int.h>
  14. #include <dhcp/option_int_array.h>
  15. #include <dhcp/option_custom.h>
  16. #include <dhcp/iface_mgr.h>
  17. #include <dhcp/tests/iface_mgr_test_config.h>
  18. #include <dhcp/tests/pkt_captures.h>
  19. #include <dhcpsrv/cfgmgr.h>
  20. #include <dhcpsrv/lease.h>
  21. #include <dhcpsrv/lease_mgr.h>
  22. #include <dhcpsrv/lease_mgr_factory.h>
  23. #include <stats/stats_mgr.h>
  24. using namespace std;
  25. using namespace isc::asiolink;
  26. using namespace isc::data;
  27. namespace isc {
  28. namespace dhcp {
  29. namespace test {
  30. BaseServerTest::BaseServerTest()
  31. : original_datadir_(CfgMgr::instance().getDataDir()) {
  32. CfgMgr::instance().setDataDir(TEST_DATA_BUILDDIR);
  33. }
  34. BaseServerTest::~BaseServerTest() {
  35. // Remove default lease file.
  36. std::ostringstream s2;
  37. s2 << CfgMgr::instance().getDataDir() << "/" << "kea-leases4.csv";
  38. static_cast<void>(::remove(s2.str().c_str()));
  39. // Revert to original data directory.
  40. CfgMgr::instance().setDataDir(original_datadir_);
  41. }
  42. Dhcpv4SrvTest::Dhcpv4SrvTest()
  43. :rcode_(-1), srv_(0) {
  44. // Wipe any existing statistics
  45. isc::stats::StatsMgr::instance().removeAll();
  46. subnet_ = Subnet4Ptr(new Subnet4(IOAddress("192.0.2.0"), 24, 1000,
  47. 2000, 3000));
  48. pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"), IOAddress("192.0.2.110")));
  49. subnet_->addPool(pool_);
  50. // Add Router option.
  51. Option4AddrLstPtr opt_routers(new Option4AddrLst(DHO_ROUTERS));
  52. opt_routers->setAddress(IOAddress("192.0.2.2"));
  53. subnet_->getCfgOption()->add(opt_routers, false, "dhcp4");
  54. CfgMgr::instance().clear();
  55. CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_);
  56. CfgMgr::instance().commit();
  57. // Let's wipe all existing statistics.
  58. isc::stats::StatsMgr::instance().removeAll();
  59. }
  60. Dhcpv4SrvTest::~Dhcpv4SrvTest() {
  61. // Make sure that we revert to default value
  62. CfgMgr::instance().clear();
  63. CfgMgr::instance().echoClientId(true);
  64. // Let's wipe all existing statistics.
  65. isc::stats::StatsMgr::instance().removeAll();
  66. }
  67. void Dhcpv4SrvTest::addPrlOption(Pkt4Ptr& pkt) {
  68. OptionUint8ArrayPtr option_prl =
  69. OptionUint8ArrayPtr(new OptionUint8Array(Option::V4,
  70. DHO_DHCP_PARAMETER_REQUEST_LIST));
  71. // Let's request options that have been configured for the subnet.
  72. option_prl->addValue(DHO_DOMAIN_NAME_SERVERS);
  73. option_prl->addValue(DHO_DOMAIN_NAME);
  74. option_prl->addValue(DHO_LOG_SERVERS);
  75. option_prl->addValue(DHO_COOKIE_SERVERS);
  76. // Let's also request the option that hasn't been configured. In such
  77. // case server should ignore request for this particular option.
  78. option_prl->addValue(DHO_LPR_SERVERS);
  79. // And add 'Parameter Request List' option into the DISCOVER packet.
  80. pkt->addOption(option_prl);
  81. }
  82. void Dhcpv4SrvTest::configureRequestedOptions() {
  83. // dns-servers
  84. Option4AddrLstPtr
  85. option_dns_servers(new Option4AddrLst(DHO_DOMAIN_NAME_SERVERS));
  86. option_dns_servers->addAddress(IOAddress("192.0.2.1"));
  87. option_dns_servers->addAddress(IOAddress("192.0.2.100"));
  88. ASSERT_NO_THROW(subnet_->getCfgOption()->add(option_dns_servers, false, "dhcp4"));
  89. // domain-name
  90. OptionDefinition def("domain-name", DHO_DOMAIN_NAME, OPT_FQDN_TYPE);
  91. OptionCustomPtr option_domain_name(new OptionCustom(def, Option::V4));
  92. option_domain_name->writeFqdn("example.com");
  93. subnet_->getCfgOption()->add(option_domain_name, false, "dhcp4");
  94. // log-servers
  95. Option4AddrLstPtr option_log_servers(new Option4AddrLst(DHO_LOG_SERVERS));
  96. option_log_servers->addAddress(IOAddress("192.0.2.2"));
  97. option_log_servers->addAddress(IOAddress("192.0.2.10"));
  98. ASSERT_NO_THROW(subnet_->getCfgOption()->add(option_log_servers, false, "dhcp4"));
  99. // cookie-servers
  100. Option4AddrLstPtr option_cookie_servers(new Option4AddrLst(DHO_COOKIE_SERVERS));
  101. option_cookie_servers->addAddress(IOAddress("192.0.2.1"));
  102. ASSERT_NO_THROW(subnet_->getCfgOption()->add(option_cookie_servers, false, "dhcp4"));
  103. }
  104. void Dhcpv4SrvTest::messageCheck(const Pkt4Ptr& q, const Pkt4Ptr& a) {
  105. ASSERT_TRUE(q);
  106. ASSERT_TRUE(a);
  107. EXPECT_EQ(q->getHops(), a->getHops());
  108. EXPECT_EQ(q->getIface(), a->getIface());
  109. EXPECT_EQ(q->getIndex(), a->getIndex());
  110. EXPECT_EQ(q->getGiaddr(), a->getGiaddr());
  111. // When processing an incoming packet the remote address
  112. // is copied as a src address, and the source address is
  113. // copied as a remote address to the response.
  114. EXPECT_TRUE(q->getLocalHWAddr() == a->getLocalHWAddr());
  115. EXPECT_TRUE(q->getRemoteHWAddr() == a->getRemoteHWAddr());
  116. // Check that the server identifier is present in the response.
  117. // Presence (or absence) of other options is checked elsewhere.
  118. EXPECT_TRUE(a->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  119. // Check that something is offered
  120. EXPECT_NE("0.0.0.0", a->getYiaddr().toText());
  121. }
  122. ::testing::AssertionResult
  123. Dhcpv4SrvTest::basicOptionsPresent(const Pkt4Ptr& pkt) {
  124. std::ostringstream errmsg;
  125. errmsg << "option missing in the response";
  126. if (!pkt->getOption(DHO_DOMAIN_NAME)) {
  127. return (::testing::AssertionFailure(::testing::Message()
  128. << "domain-name " << errmsg.str()));
  129. } else if (!pkt->getOption(DHO_DOMAIN_NAME_SERVERS)) {
  130. return (::testing::AssertionFailure(::testing::Message()
  131. << "dns-servers " << errmsg.str()));
  132. } else if (!pkt->getOption(DHO_SUBNET_MASK)) {
  133. return (::testing::AssertionFailure(::testing::Message()
  134. << "subnet-mask " << errmsg.str()));
  135. } else if (!pkt->getOption(DHO_ROUTERS)) {
  136. return (::testing::AssertionFailure(::testing::Message() << "routers "
  137. << errmsg.str()));
  138. } else if (!pkt->getOption(DHO_DHCP_LEASE_TIME)) {
  139. return (::testing::AssertionFailure(::testing::Message() <<
  140. "dhcp-lease-time " << errmsg.str()));
  141. }
  142. return (::testing::AssertionSuccess());
  143. }
  144. ::testing::AssertionResult
  145. Dhcpv4SrvTest::noBasicOptions(const Pkt4Ptr& pkt) {
  146. std::ostringstream errmsg;
  147. errmsg << "option present in the response";
  148. if (pkt->getOption(DHO_DOMAIN_NAME)) {
  149. return (::testing::AssertionFailure(::testing::Message()
  150. << "domain-name " << errmsg.str()));
  151. } else if (pkt->getOption(DHO_DOMAIN_NAME_SERVERS)) {
  152. return (::testing::AssertionFailure(::testing::Message()
  153. << "dns-servers " << errmsg.str()));
  154. } else if (pkt->getOption(DHO_SUBNET_MASK)) {
  155. return (::testing::AssertionFailure(::testing::Message()
  156. << "subnet-mask " << errmsg.str()));
  157. } else if (pkt->getOption(DHO_ROUTERS)) {
  158. return (::testing::AssertionFailure(::testing::Message() << "routers "
  159. << errmsg.str()));
  160. } else if (pkt->getOption(DHO_DHCP_LEASE_TIME)) {
  161. return (::testing::AssertionFailure(::testing::Message()
  162. << "dhcp-lease-time " << errmsg.str()));
  163. }
  164. return (::testing::AssertionSuccess());
  165. }
  166. ::testing::AssertionResult
  167. Dhcpv4SrvTest::requestedOptionsPresent(const Pkt4Ptr& pkt) {
  168. std::ostringstream errmsg;
  169. errmsg << "option missing in the response";
  170. if (!pkt->getOption(DHO_LOG_SERVERS)) {
  171. return (::testing::AssertionFailure(::testing::Message()
  172. << "log-servers " << errmsg.str()));
  173. } else if (!pkt->getOption(DHO_COOKIE_SERVERS)) {
  174. return (::testing::AssertionFailure(::testing::Message()
  175. << "cookie-servers " << errmsg.str()));
  176. }
  177. return (::testing::AssertionSuccess());
  178. }
  179. ::testing::AssertionResult
  180. Dhcpv4SrvTest::noRequestedOptions(const Pkt4Ptr& pkt) {
  181. std::ostringstream errmsg;
  182. errmsg << "option present in the response";
  183. if (pkt->getOption(DHO_LOG_SERVERS)) {
  184. return (::testing::AssertionFailure(::testing::Message()
  185. << "log-servers " << errmsg.str()));
  186. } else if (pkt->getOption(DHO_COOKIE_SERVERS)) {
  187. return (::testing::AssertionFailure(::testing::Message()
  188. << "cookie-servers " << errmsg.str()));
  189. }
  190. return (::testing::AssertionSuccess());
  191. }
  192. OptionPtr Dhcpv4SrvTest::generateClientId(size_t size /*= 4*/) {
  193. OptionBuffer clnt_id(size);
  194. for (size_t i = 0; i < size; i++) {
  195. clnt_id[i] = 100 + i;
  196. }
  197. client_id_ = ClientIdPtr(new ClientId(clnt_id));
  198. return (OptionPtr(new Option(Option::V4, DHO_DHCP_CLIENT_IDENTIFIER,
  199. clnt_id.begin(),
  200. clnt_id.begin() + size)));
  201. }
  202. HWAddrPtr Dhcpv4SrvTest::generateHWAddr(size_t size /*= 6*/) {
  203. const uint8_t hw_type = 123; // Just a fake number (typically 6=HTYPE_ETHER, see dhcp4.h)
  204. OptionBuffer mac(size);
  205. for (size_t i = 0; i < size; ++i) {
  206. mac[i] = 50 + i;
  207. }
  208. return (HWAddrPtr(new HWAddr(mac, hw_type)));
  209. }
  210. void Dhcpv4SrvTest::checkAddressParams(const Pkt4Ptr& rsp,
  211. const SubnetPtr subnet,
  212. bool t1_present,
  213. bool t2_present) {
  214. // Technically inPool implies inRange, but let's be on the safe
  215. // side and check both.
  216. EXPECT_TRUE(subnet->inRange(rsp->getYiaddr()));
  217. EXPECT_TRUE(subnet->inPool(Lease::TYPE_V4, rsp->getYiaddr()));
  218. // Check lease time
  219. OptionUint32Ptr opt = boost::dynamic_pointer_cast<
  220. OptionUint32>(rsp->getOption(DHO_DHCP_LEASE_TIME));
  221. if (!opt) {
  222. ADD_FAILURE() << "Lease time option missing in response or the"
  223. " option has unexpected type";
  224. } else {
  225. EXPECT_EQ(opt->getValue(), subnet->getValid());
  226. }
  227. // Check T1 timer
  228. opt = boost::dynamic_pointer_cast<
  229. OptionUint32>(rsp->getOption(DHO_DHCP_RENEWAL_TIME));
  230. if (t1_present) {
  231. ASSERT_TRUE(opt) << "Required T1 option missing or it has"
  232. " an unexpected type";
  233. EXPECT_EQ(opt->getValue(), subnet->getT1());
  234. } else {
  235. EXPECT_FALSE(opt);
  236. }
  237. // Check T2 timer
  238. opt = boost::dynamic_pointer_cast<
  239. OptionUint32>(rsp->getOption(DHO_DHCP_REBINDING_TIME));
  240. if (t2_present) {
  241. ASSERT_TRUE(opt) << "Required T2 option missing or it has"
  242. " an unexpected type";
  243. EXPECT_EQ(opt->getValue(), subnet->getT2());
  244. } else {
  245. EXPECT_FALSE(opt);
  246. }
  247. }
  248. void Dhcpv4SrvTest::checkResponse(const Pkt4Ptr& rsp, int expected_message_type,
  249. uint32_t expected_transid) {
  250. ASSERT_TRUE(rsp);
  251. EXPECT_EQ(expected_message_type,
  252. static_cast<int>(rsp->getType()));
  253. EXPECT_EQ(expected_transid, rsp->getTransid());
  254. }
  255. Lease4Ptr Dhcpv4SrvTest::checkLease(const Pkt4Ptr& rsp,
  256. const OptionPtr& client_id,
  257. const HWAddrPtr&,
  258. const IOAddress& expected_addr) {
  259. ClientIdPtr id;
  260. if (client_id) {
  261. OptionBuffer data = client_id->getData();
  262. id.reset(new ClientId(data));
  263. }
  264. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(expected_addr);
  265. if (!lease) {
  266. cout << "Lease for " << expected_addr
  267. << " not found in the database backend.";
  268. return (Lease4Ptr());
  269. }
  270. EXPECT_EQ(rsp->getYiaddr(), expected_addr);
  271. EXPECT_EQ(expected_addr, lease->addr_);
  272. if (client_id) {
  273. EXPECT_TRUE(*lease->client_id_ == *id);
  274. }
  275. EXPECT_EQ(subnet_->getID(), lease->subnet_id_);
  276. return (lease);
  277. }
  278. void Dhcpv4SrvTest::checkServerId(const Pkt4Ptr& rsp, const OptionPtr& expected_srvid) {
  279. // Check that server included its server-id
  280. OptionPtr opt = rsp->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  281. ASSERT_TRUE(opt);
  282. EXPECT_EQ(opt->getType(), expected_srvid->getType() );
  283. EXPECT_EQ(opt->len(), expected_srvid->len() );
  284. EXPECT_TRUE(opt->getData() == expected_srvid->getData());
  285. }
  286. void Dhcpv4SrvTest::checkClientId(const Pkt4Ptr& rsp, const OptionPtr& expected_clientid) {
  287. bool include_clientid = CfgMgr::instance().echoClientId();
  288. // check that server included our own client-id
  289. OptionPtr opt = rsp->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  290. if (include_clientid) {
  291. // Normal mode: echo back (see RFC6842)
  292. ASSERT_TRUE(opt);
  293. EXPECT_EQ(expected_clientid->getType(), opt->getType());
  294. EXPECT_EQ(expected_clientid->len(), opt->len());
  295. EXPECT_TRUE(expected_clientid->getData() == opt->getData());
  296. } else {
  297. // Backward compatibility mode for pre-RFC6842 devices
  298. ASSERT_FALSE(opt);
  299. }
  300. }
  301. ::testing::AssertionResult
  302. Dhcpv4SrvTest::createPacketFromBuffer(const Pkt4Ptr& src_pkt,
  303. Pkt4Ptr& dst_pkt) {
  304. // Create on-wire format of the packet. If pack() has been called
  305. // on this instance of the packet already, the next call to pack()
  306. // should remove all contents of the output buffer.
  307. try {
  308. src_pkt->pack();
  309. } catch (const Exception& ex) {
  310. return (::testing::AssertionFailure(::testing::Message()
  311. << "Failed to parse source packet: "
  312. << ex.what()));
  313. }
  314. // Get the output buffer from the source packet.
  315. const util::OutputBuffer& buf = src_pkt->getBuffer();
  316. // Create a copy of the packet using the output buffer from the source
  317. // packet.
  318. try {
  319. dst_pkt.reset(new Pkt4(static_cast<const uint8_t*>(buf.getData()),
  320. buf.getLength()));
  321. } catch (const Exception& ex) {
  322. return (::testing::AssertionFailure(::testing::Message()
  323. << "Failed to create a"
  324. " destination packet from"
  325. " the buffer: "
  326. << ex.what()));
  327. }
  328. try {
  329. // Parse the new packet and return to the caller.
  330. dst_pkt->unpack();
  331. } catch (const Exception& ex) {
  332. return (::testing::AssertionFailure(::testing::Message()
  333. << "Failed to parse a"
  334. << " destination packet: "
  335. << ex.what()));
  336. }
  337. return (::testing::AssertionSuccess());
  338. }
  339. void
  340. // cppcheck-suppress unusedFunction
  341. Dhcpv4SrvTest::TearDown() {
  342. CfgMgr::instance().clear();
  343. // Close all open sockets.
  344. IfaceMgr::instance().closeSockets();
  345. // Some unit tests override the default packet filtering class, used
  346. // by the IfaceMgr. The dummy class, called PktFilterTest, reports the
  347. // capability to directly respond to the clients without IP address
  348. // assigned. This capability is not supported by the default packet
  349. // filtering class: PktFilterInet. Therefore setting the dummy class
  350. // allows to test scenarios, when server responds to the broadcast address
  351. // on client's request, despite having support for direct response.
  352. // The following call restores the use of original packet filtering class
  353. // after the test.
  354. try {
  355. IfaceMgr::instance().setPacketFilter(PktFilterPtr(new PktFilterInet()));
  356. } catch (const Exception& ex) {
  357. FAIL() << "Failed to restore the default (PktFilterInet) packet filtering"
  358. << " class after the test. Exception has been caught: "
  359. << ex.what();
  360. }
  361. }
  362. void
  363. Dhcpv4SrvTest::testDiscoverRequest(const uint8_t msg_type) {
  364. IfaceMgrTestConfig test_config(true);
  365. IfaceMgr::instance().openSockets4();
  366. // Create an instance of the tested class.
  367. boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));
  368. // Initialize the source HW address.
  369. vector<uint8_t> mac(6);
  370. for (uint8_t i = 0; i < 6; ++i) {
  371. mac[i] = i * 10;
  372. }
  373. // Initialized the destination HW address.
  374. vector<uint8_t> dst_mac(6);
  375. for (uint8_t i = 0; i < 6; ++i) {
  376. dst_mac[i] = i * 20;
  377. }
  378. // Create a DHCP message. It will be used to simulate the
  379. // incoming message.
  380. boost::shared_ptr<Pkt4> req(new Pkt4(msg_type, 1234));
  381. // Create a response message. It will hold a response packet.
  382. // Initially, set it to NULL.
  383. boost::shared_ptr<Pkt4> rsp;
  384. // Set the name of the interface on which packet is received.
  385. req->setIface("eth0");
  386. // Set the interface index. It is just a dummy value and will
  387. // not be interpreted.
  388. req->setIndex(17);
  389. // Set the target HW address. This value is normally used to
  390. // construct the data link layer header.
  391. req->setRemoteHWAddr(1, 6, dst_mac);
  392. // Set the HW address. This value is set on DHCP level (in chaddr).
  393. req->setHWAddr(1, 6, mac);
  394. // Set local HW address. It is used to construct the data link layer
  395. // header.
  396. req->setLocalHWAddr(1, 6, mac);
  397. // Set target IP address.
  398. req->setRemoteAddr(IOAddress("192.0.2.55"));
  399. // Set relay address and hops.
  400. req->setGiaddr(IOAddress("192.0.2.10"));
  401. req->setHops(1);
  402. // We are going to test that certain options are returned
  403. // in the response message when requested using 'Parameter
  404. // Request List' option. Let's configure those options that
  405. // are returned when requested.
  406. configureRequestedOptions();
  407. // Create a copy of the original packet by parsing its wire format.
  408. // This simulates the real life scenario when we process the packet
  409. // which was parsed from its wire format.
  410. Pkt4Ptr received;
  411. ASSERT_TRUE(createPacketFromBuffer(req, received));
  412. // Set interface. It is required for the server to generate server id.
  413. received->setIface("eth0");
  414. if (msg_type == DHCPDISCOVER) {
  415. ASSERT_NO_THROW(
  416. rsp = srv->processDiscover(received);
  417. );
  418. // Should return OFFER
  419. ASSERT_TRUE(rsp);
  420. EXPECT_EQ(DHCPOFFER, rsp->getType());
  421. } else {
  422. ASSERT_NO_THROW(rsp = srv->processRequest(received));
  423. // Should return ACK
  424. ASSERT_TRUE(rsp);
  425. EXPECT_EQ(DHCPACK, rsp->getType());
  426. }
  427. messageCheck(received, rsp);
  428. // Basic options should be present when we got the lease.
  429. EXPECT_TRUE(basicOptionsPresent(rsp));
  430. // We did not request any options so these should not be present
  431. // in the RSP.
  432. EXPECT_TRUE(noRequestedOptions(rsp));
  433. // Repeat the test but request some options.
  434. // Add 'Parameter Request List' option.
  435. addPrlOption(req);
  436. ASSERT_TRUE(createPacketFromBuffer(req, received));
  437. ASSERT_TRUE(received->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  438. // Set interface. It is required for the server to generate server id.
  439. received->setIface("eth0");
  440. if (msg_type == DHCPDISCOVER) {
  441. ASSERT_NO_THROW(rsp = srv->processDiscover(received));
  442. // Should return non-NULL packet.
  443. ASSERT_TRUE(rsp);
  444. EXPECT_EQ(DHCPOFFER, rsp->getType());
  445. } else {
  446. ASSERT_NO_THROW(rsp = srv->processRequest(received));
  447. // Should return non-NULL packet.
  448. ASSERT_TRUE(rsp);
  449. EXPECT_EQ(DHCPACK, rsp->getType());
  450. }
  451. // Check that the requested options are returned.
  452. EXPECT_TRUE(basicOptionsPresent(rsp));
  453. EXPECT_TRUE(requestedOptionsPresent(rsp));
  454. // The following part of the test will test that the NAK is sent when
  455. // there is no address pool configured. In the same time, we expect
  456. // that the requested options are not included in NAK message, but that
  457. // they are only included when yiaddr is set to non-zero value.
  458. ASSERT_NO_THROW(subnet_->delPools(Lease::TYPE_V4));
  459. // There has been a lease allocated for the particular client. So,
  460. // even though we deleted the subnet, the client would get the
  461. // existing lease (not a NAK). Therefore, we have to change the chaddr
  462. // in the packet so as the existing lease is not returned.
  463. req->setHWAddr(1, 6, std::vector<uint8_t>(2, 6));
  464. ASSERT_TRUE(createPacketFromBuffer(req, received));
  465. ASSERT_TRUE(received->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  466. // Set interface. It is required for the server to generate server id.
  467. received->setIface("eth0");
  468. if (msg_type == DHCPDISCOVER) {
  469. ASSERT_NO_THROW(rsp = srv->processDiscover(received));
  470. // Should return NULL packet.
  471. ASSERT_FALSE(rsp);
  472. } else {
  473. ASSERT_NO_THROW(rsp = srv->processRequest(received));
  474. // Should return non-NULL packet.
  475. ASSERT_TRUE(rsp);
  476. // We should get the NAK packet with yiaddr set to 0.
  477. EXPECT_EQ(DHCPNAK, rsp->getType());
  478. ASSERT_EQ("0.0.0.0", rsp->getYiaddr().toText());
  479. // Make sure that none of the requested options is returned in NAK.
  480. // Also options such as Routers or Subnet Mask should not be there,
  481. // because lease hasn't been acquired.
  482. EXPECT_TRUE(noRequestedOptions(rsp));
  483. EXPECT_TRUE(noBasicOptions(rsp));
  484. }
  485. }
  486. void
  487. Dhcpv4SrvTest::configure(const std::string& config, const bool commit) {
  488. configure(config, srv_, commit);
  489. }
  490. void
  491. Dhcpv4SrvTest::configure(const std::string& config, NakedDhcpv4Srv& srv,
  492. const bool commit) {
  493. ElementPtr json = Element::fromJSON(config);
  494. ConstElementPtr status;
  495. // Configure the server and make sure the config is accepted
  496. EXPECT_NO_THROW(status = configureDhcp4Server(srv, json));
  497. ASSERT_TRUE(status);
  498. int rcode;
  499. ConstElementPtr comment = config::parseAnswer(rcode, status);
  500. ASSERT_EQ(0, rcode);
  501. if (commit) {
  502. CfgMgr::instance().commit();
  503. }
  504. }
  505. Dhcpv4Exchange
  506. Dhcpv4SrvTest::createExchange(const Pkt4Ptr& query) {
  507. return (Dhcpv4Exchange(srv_.alloc_engine_, query, srv_.selectSubnet(query)));
  508. }
  509. void
  510. Dhcpv4SrvTest::pretendReceivingPkt(NakedDhcpv4Srv& srv, const std::string& config,
  511. uint8_t pkt_type, const std::string& stat_name) {
  512. IfaceMgrTestConfig test_config(true);
  513. IfaceMgr::instance().openSockets4();
  514. // Apply the configuration we just received.
  515. configure(config);
  516. // Let's just use one of the actual captured packets that we have.
  517. Pkt4Ptr pkt = PktCaptures::captureRelayedDiscover();
  518. // We just need to tweak it a it, to pretend that it's type is as desired.
  519. // Note that when receiving a packet, its on-wire form is stored in data_
  520. // field. Most methods (including setType()) operates on option objects
  521. // (objects stored in options_ after unpack() is called). Finally, outgoing
  522. // packets are stored in out_buffer_. So we need to go through the full
  523. // unpack/tweak/pack cycle and do repack, i.e. move the output buffer back
  524. // to incoming buffer.
  525. pkt->unpack();
  526. pkt->setType(pkt_type); // Set message type.
  527. pkt->pack();
  528. pkt->data_.resize(pkt->getBuffer().getLength());
  529. // Copy out_buffer_ to data_ to pretend that it's what was just received.
  530. memcpy(&pkt->data_[0], pkt->getBuffer().getData(), pkt->getBuffer().getLength());
  531. // Simulate that we have received that traffic
  532. srv.fakeReceive(pkt);
  533. srv.run();
  534. using namespace isc::stats;
  535. StatsMgr& mgr = StatsMgr::instance();
  536. ObservationPtr pkt4_rcvd = mgr.getObservation("pkt4-received");
  537. ObservationPtr tested_stat = mgr.getObservation(stat_name);
  538. // All expected statstics must be present.
  539. ASSERT_TRUE(pkt4_rcvd);
  540. ASSERT_TRUE(tested_stat);
  541. // They also must have expected values.
  542. EXPECT_EQ(1, pkt4_rcvd->getInteger().first);
  543. EXPECT_EQ(1, tested_stat->getInteger().first);
  544. }
  545. }; // end of isc::dhcp::test namespace
  546. }; // end of isc::dhcp namespace
  547. }; // end of isc namespace