dhcp4_test_utils.cc 24 KB

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