dhcp4_srv_unittest.cc 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  1. // Copyright (C) 2011-2013 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <sstream>
  16. #include <asiolink/io_address.h>
  17. #include <dhcp/dhcp4.h>
  18. #include <dhcp/iface_mgr.h>
  19. #include <dhcp/option.h>
  20. #include <dhcp/option4_addrlst.h>
  21. #include <dhcp/option_custom.h>
  22. #include <dhcp/option_int_array.h>
  23. #include <dhcp4/dhcp4_srv.h>
  24. #include <dhcp4/dhcp4_log.h>
  25. #include <dhcpsrv/cfgmgr.h>
  26. #include <dhcpsrv/lease_mgr.h>
  27. #include <dhcpsrv/lease_mgr_factory.h>
  28. #include <dhcpsrv/utils.h>
  29. #include <gtest/gtest.h>
  30. #include <fstream>
  31. #include <iostream>
  32. #include <arpa/inet.h>
  33. using namespace std;
  34. using namespace isc;
  35. using namespace isc::dhcp;
  36. using namespace isc::asiolink;
  37. namespace {
  38. class NakedDhcpv4Srv: public Dhcpv4Srv {
  39. // "Naked" DHCPv4 server, exposes internal fields
  40. public:
  41. /// @brief Constructor.
  42. ///
  43. /// It disables configuration of broadcast options on
  44. /// sockets that are opened by the Dhcpv4Srv constructor.
  45. /// Setting broadcast options requires root privileges
  46. /// which is not the case when running unit tests.
  47. NakedDhcpv4Srv(uint16_t port = 0)
  48. : Dhcpv4Srv(port, "type=memfile", false) {
  49. }
  50. using Dhcpv4Srv::processDiscover;
  51. using Dhcpv4Srv::processRequest;
  52. using Dhcpv4Srv::processRelease;
  53. using Dhcpv4Srv::processDecline;
  54. using Dhcpv4Srv::processInform;
  55. using Dhcpv4Srv::getServerID;
  56. using Dhcpv4Srv::loadServerID;
  57. using Dhcpv4Srv::generateServerID;
  58. using Dhcpv4Srv::writeServerID;
  59. using Dhcpv4Srv::sanityCheck;
  60. using Dhcpv4Srv::srvidToString;
  61. };
  62. static const char* SRVID_FILE = "server-id-test.txt";
  63. class Dhcpv4SrvTest : public ::testing::Test {
  64. public:
  65. /// @brief Constructor
  66. ///
  67. /// Initializes common objects used in many tests.
  68. /// Also sets up initial configuration in CfgMgr.
  69. Dhcpv4SrvTest() {
  70. subnet_ = Subnet4Ptr(new Subnet4(IOAddress("192.0.2.0"), 24, 1000,
  71. 2000, 3000));
  72. pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"), IOAddress("192.0.2.110")));
  73. subnet_->addPool(pool_);
  74. CfgMgr::instance().deleteSubnets4();
  75. CfgMgr::instance().addSubnet4(subnet_);
  76. // Add Router option.
  77. Option4AddrLstPtr opt_routers(new Option4AddrLst(DHO_ROUTERS));
  78. opt_routers->setAddress(IOAddress("192.0.2.2"));
  79. subnet_->addOption(opt_routers, false, "dhcp4");
  80. // it's ok if that fails. There should not be such a file anyway
  81. unlink(SRVID_FILE);
  82. }
  83. /// @brief Add 'Parameter Request List' option to the packet.
  84. ///
  85. /// This function PRL option comprising the following option codes:
  86. /// - 5 - Name Server
  87. /// - 15 - Domain Name
  88. /// - 7 - Log Server
  89. /// - 8 - Quotes Server
  90. /// - 9 - LPR Server
  91. ///
  92. /// @param pkt packet to add PRL option to.
  93. void addPrlOption(Pkt4Ptr& pkt) {
  94. OptionUint8ArrayPtr option_prl =
  95. OptionUint8ArrayPtr(new OptionUint8Array(Option::V4,
  96. DHO_DHCP_PARAMETER_REQUEST_LIST));
  97. // Let's request options that have been configured for the subnet.
  98. option_prl->addValue(DHO_DOMAIN_NAME_SERVERS);
  99. option_prl->addValue(DHO_DOMAIN_NAME);
  100. option_prl->addValue(DHO_LOG_SERVERS);
  101. option_prl->addValue(DHO_COOKIE_SERVERS);
  102. // Let's also request the option that hasn't been configured. In such
  103. // case server should ignore request for this particular option.
  104. option_prl->addValue(DHO_LPR_SERVERS);
  105. // And add 'Parameter Request List' option into the DISCOVER packet.
  106. pkt->addOption(option_prl);
  107. }
  108. /// @brief Configures options being requested in the PRL option.
  109. ///
  110. /// The lpr-servers option is NOT configured here although it is
  111. /// added to the 'Parameter Request List' option in the
  112. /// \ref addPrlOption. When requested option is not configured
  113. /// the server should not return it in its response. The goal
  114. /// of not configuring the requested option is to verify that
  115. /// the server will not return it.
  116. void configureRequestedOptions() {
  117. // dns-servers
  118. Option4AddrLstPtr
  119. option_dns_servers(new Option4AddrLst(DHO_DOMAIN_NAME_SERVERS));
  120. option_dns_servers->addAddress(IOAddress("192.0.2.1"));
  121. option_dns_servers->addAddress(IOAddress("192.0.2.100"));
  122. ASSERT_NO_THROW(subnet_->addOption(option_dns_servers, false, "dhcp4"));
  123. // domain-name
  124. OptionDefinition def("domain-name", DHO_DOMAIN_NAME, OPT_FQDN_TYPE);
  125. boost::shared_ptr<OptionCustom>
  126. option_domain_name(new OptionCustom(def, Option::V4));
  127. option_domain_name->writeFqdn("example.com");
  128. subnet_->addOption(option_domain_name, false, "dhcp4");
  129. // log-servers
  130. Option4AddrLstPtr option_log_servers(new Option4AddrLst(DHO_LOG_SERVERS));
  131. option_log_servers->addAddress(IOAddress("192.0.2.2"));
  132. option_log_servers->addAddress(IOAddress("192.0.2.10"));
  133. ASSERT_NO_THROW(subnet_->addOption(option_log_servers, false, "dhcp4"));
  134. // cookie-servers
  135. Option4AddrLstPtr option_cookie_servers(new Option4AddrLst(DHO_COOKIE_SERVERS));
  136. option_cookie_servers->addAddress(IOAddress("192.0.2.1"));
  137. ASSERT_NO_THROW(subnet_->addOption(option_cookie_servers, false, "dhcp4"));
  138. }
  139. /// @brief checks that the response matches request
  140. /// @param q query (client's message)
  141. /// @param a answer (server's message)
  142. void messageCheck(const boost::shared_ptr<Pkt4>& q,
  143. const boost::shared_ptr<Pkt4>& a) {
  144. ASSERT_TRUE(q);
  145. ASSERT_TRUE(a);
  146. EXPECT_EQ(q->getHops(), a->getHops());
  147. EXPECT_EQ(q->getIface(), a->getIface());
  148. EXPECT_EQ(q->getIndex(), a->getIndex());
  149. EXPECT_EQ(q->getGiaddr(), a->getGiaddr());
  150. // Check that bare minimum of required options are there.
  151. // We don't check options requested by a client. Those
  152. // are checked elsewhere.
  153. EXPECT_TRUE(a->getOption(DHO_SUBNET_MASK));
  154. EXPECT_TRUE(a->getOption(DHO_ROUTERS));
  155. EXPECT_TRUE(a->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  156. EXPECT_TRUE(a->getOption(DHO_DHCP_LEASE_TIME));
  157. EXPECT_TRUE(a->getOption(DHO_SUBNET_MASK));
  158. EXPECT_TRUE(a->getOption(DHO_DOMAIN_NAME));
  159. EXPECT_TRUE(a->getOption(DHO_DOMAIN_NAME_SERVERS));
  160. // Check that something is offered
  161. EXPECT_TRUE(a->getYiaddr().toText() != "0.0.0.0");
  162. }
  163. /// @brief Check that requested options are present.
  164. ///
  165. /// @param pkt packet to be checked.
  166. void optionsCheck(const Pkt4Ptr& pkt) {
  167. // Check that the requested and configured options are returned
  168. // in the ACK message.
  169. EXPECT_TRUE(pkt->getOption(DHO_DOMAIN_NAME))
  170. << "domain-name not present in the response";
  171. EXPECT_TRUE(pkt->getOption(DHO_DOMAIN_NAME_SERVERS))
  172. << "dns-servers not present in the response";
  173. EXPECT_TRUE(pkt->getOption(DHO_LOG_SERVERS))
  174. << "log-servers not present in the response";
  175. EXPECT_TRUE(pkt->getOption(DHO_COOKIE_SERVERS))
  176. << "cookie-servers not present in the response";
  177. // Check that the requested but not configured options are not
  178. // returned in the ACK message.
  179. EXPECT_FALSE(pkt->getOption(DHO_LPR_SERVERS))
  180. << "domain-name present in the response but it is"
  181. << " expected not to be present";
  182. }
  183. /// @brief generates client-id option
  184. ///
  185. /// Generate client-id option of specified length
  186. /// Ids with different lengths are sufficent to generate
  187. /// unique ids. If more fine grained control is required,
  188. /// tests generate client-ids on their own.
  189. /// Sets client_id_ field.
  190. /// @param size size of the client-id to be generated
  191. OptionPtr generateClientId(size_t size = 4) {
  192. OptionBuffer clnt_id(size);
  193. for (int i = 0; i < size; i++) {
  194. clnt_id[i] = 100 + i;
  195. }
  196. client_id_ = ClientIdPtr(new ClientId(clnt_id));
  197. return (OptionPtr(new Option(Option::V4, DHO_DHCP_CLIENT_IDENTIFIER,
  198. clnt_id.begin(),
  199. clnt_id.begin() + size)));
  200. }
  201. /// @brief generate hardware address
  202. ///
  203. /// @param size size of the generated MAC address
  204. /// @param pointer to Hardware Address object
  205. HWAddrPtr generateHWAddr(size_t size = 6) {
  206. const uint8_t hw_type = 123; // Just a fake number (typically 6=HTYPE_ETHER, see dhcp4.h)
  207. OptionBuffer mac(size);
  208. for (int i = 0; i < size; ++i) {
  209. mac[i] = 50 + i;
  210. }
  211. return (HWAddrPtr(new HWAddr(mac, hw_type)));
  212. }
  213. /// Check that address was returned from proper range, that its lease
  214. /// lifetime is correct, that T1 and T2 are returned properly
  215. /// @param rsp response to be checked
  216. /// @param subnet subnet that should be used to verify assigned address
  217. /// and options
  218. /// @param t1_mandatory is T1 mandatory?
  219. /// @param t2_mandatory is T2 mandatory?
  220. void checkAddressParams(const Pkt4Ptr& rsp, const SubnetPtr subnet,
  221. bool t1_mandatory = false,
  222. bool t2_mandatory = false) {
  223. // Technically inPool implies inRange, but let's be on the safe
  224. // side and check both.
  225. EXPECT_TRUE(subnet->inRange(rsp->getYiaddr()));
  226. EXPECT_TRUE(subnet->inPool(rsp->getYiaddr()));
  227. // Check lease time
  228. OptionPtr opt = rsp->getOption(DHO_DHCP_LEASE_TIME);
  229. if (!opt) {
  230. ADD_FAILURE() << "Lease time option missing in response";
  231. } else {
  232. EXPECT_EQ(opt->getUint32(), subnet->getValid());
  233. }
  234. // Check T1 timer
  235. opt = rsp->getOption(DHO_DHCP_RENEWAL_TIME);
  236. if (opt) {
  237. EXPECT_EQ(opt->getUint32(), subnet->getT1());
  238. } else {
  239. if (t1_mandatory) {
  240. ADD_FAILURE() << "Required T1 option missing";
  241. }
  242. }
  243. // Check T2 timer
  244. opt = rsp->getOption(DHO_DHCP_REBINDING_TIME);
  245. if (opt) {
  246. EXPECT_EQ(opt->getUint32(), subnet->getT2());
  247. } else {
  248. if (t2_mandatory) {
  249. ADD_FAILURE() << "Required T2 option missing";
  250. }
  251. }
  252. }
  253. /// @brief Basic checks for generated response (message type and trans-id).
  254. ///
  255. /// @param rsp response packet to be validated
  256. /// @param expected_message_type expected message type
  257. /// @param expected_transid expected transaction-id
  258. void checkResponse(const Pkt4Ptr& rsp, uint8_t expected_message_type,
  259. uint32_t expected_transid) {
  260. ASSERT_TRUE(rsp);
  261. EXPECT_EQ(expected_message_type, rsp->getType());
  262. EXPECT_EQ(expected_transid, rsp->getTransid());
  263. }
  264. /// @brief Checks if the lease sent to client is present in the database
  265. ///
  266. /// @param rsp response packet to be validated
  267. /// @param client_id expected client-identifier (or NULL)
  268. /// @param HWAddr expected hardware address (not used now)
  269. /// @param expected_addr expected address
  270. Lease4Ptr checkLease(const Pkt4Ptr& rsp, const OptionPtr& client_id,
  271. const HWAddrPtr&, const IOAddress& expected_addr) {
  272. ClientIdPtr id;
  273. if (client_id) {
  274. OptionBuffer data = client_id->getData();
  275. id.reset(new ClientId(data));
  276. }
  277. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(expected_addr);
  278. if (!lease) {
  279. cout << "Lease for " << expected_addr.toText()
  280. << " not found in the database backend.";
  281. return (Lease4Ptr());
  282. }
  283. EXPECT_EQ(rsp->getYiaddr().toText(), expected_addr.toText());
  284. EXPECT_EQ(expected_addr.toText(), lease->addr_.toText());
  285. if (client_id) {
  286. EXPECT_TRUE(*lease->client_id_ == *id);
  287. }
  288. EXPECT_EQ(subnet_->getID(), lease->subnet_id_);
  289. return (lease);
  290. }
  291. /// @brief Checks if server response (OFFER, ACK, NAK) includes proper server-id
  292. /// @param rsp response packet to be validated
  293. /// @param expected_srvid expected value of server-id
  294. void checkServerId(const Pkt4Ptr& rsp, const OptionPtr& expected_srvid) {
  295. // Check that server included its server-id
  296. OptionPtr opt = rsp->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  297. ASSERT_TRUE(opt);
  298. EXPECT_EQ(opt->getType(), expected_srvid->getType() );
  299. EXPECT_EQ(opt->len(), expected_srvid->len() );
  300. EXPECT_TRUE(opt->getData() == expected_srvid->getData());
  301. }
  302. /// @brief Checks if server response (OFFER, ACK, NAK) includes proper client-id
  303. /// @param rsp response packet to be validated
  304. /// @param expected_clientid expected value of client-id
  305. void checkClientId(const Pkt4Ptr& rsp, const OptionPtr& expected_clientid) {
  306. // check that server included our own client-id
  307. OptionPtr opt = rsp->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  308. ASSERT_TRUE(opt);
  309. EXPECT_EQ(expected_clientid->getType(), opt->getType());
  310. EXPECT_EQ(expected_clientid->len(), opt->len());
  311. EXPECT_TRUE(expected_clientid->getData() == opt->getData());
  312. }
  313. /// @brief Tests if Discover or Request message is processed correctly
  314. ///
  315. /// @param msg_type DHCPDISCOVER or DHCPREQUEST
  316. /// @param client_addr client address
  317. /// @param relay_addr relay address
  318. void testDiscoverRequest(const uint8_t msg_type,
  319. const IOAddress& client_addr,
  320. const IOAddress& relay_addr) {
  321. NakedDhcpv4Srv* srv = new NakedDhcpv4Srv(0);
  322. vector<uint8_t> mac(6);
  323. for (int i = 0; i < 6; i++) {
  324. mac[i] = i*10;
  325. }
  326. boost::shared_ptr<Pkt4> req(new Pkt4(msg_type, 1234));
  327. boost::shared_ptr<Pkt4> rsp;
  328. req->setIface("eth0");
  329. req->setIndex(17);
  330. req->setHWAddr(1, 6, mac);
  331. req->setRemoteAddr(IOAddress(client_addr));
  332. req->setGiaddr(relay_addr);
  333. // We are going to test that certain options are returned
  334. // in the response message when requested using 'Parameter
  335. // Request List' option. Let's configure those options that
  336. // are returned when requested.
  337. configureRequestedOptions();
  338. if (msg_type == DHCPDISCOVER) {
  339. ASSERT_NO_THROW(
  340. rsp = srv->processDiscover(req);
  341. );
  342. // Should return OFFER
  343. ASSERT_TRUE(rsp);
  344. EXPECT_EQ(DHCPOFFER, rsp->getType());
  345. } else {
  346. ASSERT_NO_THROW(
  347. rsp = srv->processRequest(req);
  348. );
  349. // Should return ACK
  350. ASSERT_TRUE(rsp);
  351. EXPECT_EQ(DHCPACK, rsp->getType());
  352. }
  353. if (relay_addr.toText() != "0.0.0.0") {
  354. // This is relayed message. It should be sent brsp to relay address.
  355. EXPECT_EQ(req->getGiaddr().toText(),
  356. rsp->getRemoteAddr().toText());
  357. } else if (client_addr.toText() != "0.0.0.0") {
  358. // This is a message from a client having an IP address.
  359. EXPECT_EQ(req->getRemoteAddr().toText(),
  360. rsp->getRemoteAddr().toText());
  361. } else {
  362. // This is a message from a client having no IP address yet.
  363. // If IfaceMgr supports direct traffic the response should
  364. // be sent to the new address assigned to the client.
  365. if (IfaceMgr::instance().isDirectResponseSupported()) {
  366. EXPECT_EQ(rsp->getYiaddr(),
  367. rsp->getRemoteAddr().toText());
  368. // If direct response to the client having no IP address is
  369. // not supported, response should go to broadcast.
  370. } else {
  371. EXPECT_EQ("255.255.255.255", rsp->getRemoteAddr().toText());
  372. }
  373. }
  374. messageCheck(req, rsp);
  375. // We did not request any options so these should not be present
  376. // in the RSP.
  377. EXPECT_FALSE(rsp->getOption(DHO_LOG_SERVERS));
  378. EXPECT_FALSE(rsp->getOption(DHO_COOKIE_SERVERS));
  379. EXPECT_FALSE(rsp->getOption(DHO_LPR_SERVERS));
  380. // Repeat the test but request some options.
  381. // Add 'Parameter Request List' option.
  382. addPrlOption(req);
  383. if (msg_type == DHCPDISCOVER) {
  384. ASSERT_NO_THROW(
  385. rsp = srv->processDiscover(req);
  386. );
  387. // Should return non-NULL packet.
  388. ASSERT_TRUE(rsp);
  389. EXPECT_EQ(DHCPOFFER, rsp->getType());
  390. } else {
  391. ASSERT_NO_THROW(
  392. rsp = srv->processRequest(req);
  393. );
  394. // Should return non-NULL packet.
  395. ASSERT_TRUE(rsp);
  396. EXPECT_EQ(DHCPACK, rsp->getType());
  397. }
  398. // Check that the requested options are returned.
  399. optionsCheck(rsp);
  400. }
  401. ~Dhcpv4SrvTest() {
  402. CfgMgr::instance().deleteSubnets4();
  403. // Let's clean up if there is such a file.
  404. unlink(SRVID_FILE);
  405. };
  406. /// @brief A subnet used in most tests
  407. Subnet4Ptr subnet_;
  408. /// @brief A pool used in most tests
  409. Pool4Ptr pool_;
  410. /// @brief A client-id used in most tests
  411. ClientIdPtr client_id_;
  412. };
  413. // Sanity check. Verifies that both Dhcpv4Srv and its derived
  414. // class NakedDhcpv4Srv can be instantiated and destroyed.
  415. TEST_F(Dhcpv4SrvTest, basic) {
  416. // Check that the base class can be instantiated
  417. Dhcpv4Srv* srv = NULL;
  418. ASSERT_NO_THROW({
  419. srv = new Dhcpv4Srv(DHCP4_SERVER_PORT + 10000);
  420. });
  421. delete srv;
  422. // Check that the derived class can be instantiated
  423. NakedDhcpv4Srv* naked_srv = NULL;
  424. ASSERT_NO_THROW({
  425. naked_srv = new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000);
  426. });
  427. EXPECT_TRUE(naked_srv->getServerID());
  428. delete naked_srv;
  429. ASSERT_NO_THROW({
  430. naked_srv = new NakedDhcpv4Srv(0);
  431. });
  432. EXPECT_TRUE(naked_srv->getServerID());
  433. delete naked_srv;
  434. }
  435. // Verifies that DISCOVER received via relay can be processed correctly,
  436. // that the OFFER message generated in response is valid and
  437. // contains necessary options.
  438. //
  439. // Note: this test focuses on the packet correctness. There
  440. // are other tests that verify correctness of the allocation
  441. // engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId
  442. // and DiscoverInvalidHint.
  443. TEST_F(Dhcpv4SrvTest, processDiscoverRelay) {
  444. testDiscoverRequest(DHCPDISCOVER,
  445. IOAddress("192.0.2.56"),
  446. IOAddress("192.0.2.67"));
  447. }
  448. // Verifies that the non-relayed DISCOVER is processed correctly when
  449. // client source address is specified.
  450. TEST_F(Dhcpv4SrvTest, processDiscoverNoRelay) {
  451. testDiscoverRequest(DHCPDISCOVER,
  452. IOAddress("0.0.0.0"),
  453. IOAddress("192.0.2.67"));
  454. }
  455. // Verified that the non-relayed DISCOVER is processed correctly when
  456. // client source address is not specified.
  457. TEST_F(Dhcpv4SrvTest, processDiscoverNoClientAddr) {
  458. testDiscoverRequest(DHCPDISCOVER,
  459. IOAddress("0.0.0.0"),
  460. IOAddress("0.0.0.0"));
  461. }
  462. // Verifies that REQUEST received via relay can be processed correctly,
  463. // that the OFFER message generated in response is valid and
  464. // contains necessary options.
  465. //
  466. // Note: this test focuses on the packet correctness. There
  467. // are other tests that verify correctness of the allocation
  468. // engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId
  469. // and DiscoverInvalidHint.
  470. TEST_F(Dhcpv4SrvTest, processRequestRelay) {
  471. testDiscoverRequest(DHCPREQUEST,
  472. IOAddress("192.0.2.56"),
  473. IOAddress("192.0.2.67"));
  474. }
  475. // Verifies that the non-relayed REQUEST is processed correctly when
  476. // client source address is specified.
  477. TEST_F(Dhcpv4SrvTest, processRequestNoRelay) {
  478. testDiscoverRequest(DHCPREQUEST,
  479. IOAddress("0.0.0.0"),
  480. IOAddress("192.0.2.67"));
  481. }
  482. // Verified that the non-relayed REQUEST is processed correctly when
  483. // client source address is not specified.
  484. TEST_F(Dhcpv4SrvTest, processRequestNoClientAddr) {
  485. testDiscoverRequest(DHCPREQUEST,
  486. IOAddress("0.0.0.0"),
  487. IOAddress("0.0.0.0"));
  488. }
  489. TEST_F(Dhcpv4SrvTest, processRelease) {
  490. NakedDhcpv4Srv* srv = new NakedDhcpv4Srv();
  491. boost::shared_ptr<Pkt4> pkt(new Pkt4(DHCPRELEASE, 1234));
  492. // Should not throw
  493. EXPECT_NO_THROW(
  494. srv->processRelease(pkt);
  495. );
  496. delete srv;
  497. }
  498. TEST_F(Dhcpv4SrvTest, processDecline) {
  499. NakedDhcpv4Srv* srv = new NakedDhcpv4Srv();
  500. boost::shared_ptr<Pkt4> pkt(new Pkt4(DHCPDECLINE, 1234));
  501. // Should not throw
  502. EXPECT_NO_THROW(
  503. srv->processDecline(pkt);
  504. );
  505. delete srv;
  506. }
  507. TEST_F(Dhcpv4SrvTest, processInform) {
  508. NakedDhcpv4Srv* srv = new NakedDhcpv4Srv();
  509. boost::shared_ptr<Pkt4> pkt(new Pkt4(DHCPINFORM, 1234));
  510. // Should not throw
  511. EXPECT_NO_THROW(
  512. srv->processInform(pkt);
  513. );
  514. // Should return something
  515. EXPECT_TRUE(srv->processInform(pkt));
  516. // @todo Implement more reasonable tests before starting
  517. // work on processSomething() method.
  518. delete srv;
  519. }
  520. TEST_F(Dhcpv4SrvTest, serverReceivedPacketName) {
  521. // Check all possible packet types
  522. for (int itype = 0; itype < 256; ++itype) {
  523. uint8_t type = itype;
  524. switch (type) {
  525. case DHCPDECLINE:
  526. EXPECT_STREQ("DECLINE", Dhcpv4Srv::serverReceivedPacketName(type));
  527. break;
  528. case DHCPDISCOVER:
  529. EXPECT_STREQ("DISCOVER", Dhcpv4Srv::serverReceivedPacketName(type));
  530. break;
  531. case DHCPINFORM:
  532. EXPECT_STREQ("INFORM", Dhcpv4Srv::serverReceivedPacketName(type));
  533. break;
  534. case DHCPRELEASE:
  535. EXPECT_STREQ("RELEASE", Dhcpv4Srv::serverReceivedPacketName(type));
  536. break;
  537. case DHCPREQUEST:
  538. EXPECT_STREQ("REQUEST", Dhcpv4Srv::serverReceivedPacketName(type));
  539. break;
  540. default:
  541. EXPECT_STREQ("UNKNOWN", Dhcpv4Srv::serverReceivedPacketName(type));
  542. }
  543. }
  544. }
  545. // This test verifies that incoming DISCOVER can be handled properly, that an
  546. // OFFER is generated, that the response has an address and that address
  547. // really belongs to the configured pool.
  548. //
  549. // constructed very simple DISCOVER message with:
  550. // - client-id option
  551. //
  552. // expected returned OFFER message:
  553. // - copy of client-id
  554. // - server-id
  555. // - offered address
  556. TEST_F(Dhcpv4SrvTest, DiscoverBasic) {
  557. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  558. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  559. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  560. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  561. OptionPtr clientid = generateClientId();
  562. dis->addOption(clientid);
  563. // Pass it to the server and get an offer
  564. Pkt4Ptr offer = srv->processDiscover(dis);
  565. // Check if we get response at all
  566. checkResponse(offer, DHCPOFFER, 1234);
  567. // Check that address was returned from proper range, that its lease
  568. // lifetime is correct, that T1 and T2 are returned properly
  569. checkAddressParams(offer, subnet_);
  570. // Check identifiers
  571. checkServerId(offer, srv->getServerID());
  572. checkClientId(offer, clientid);
  573. }
  574. // This test verifies that incoming DISCOVER can be handled properly, that an
  575. // OFFER is generated, that the response has an address and that address
  576. // really belongs to the configured pool.
  577. //
  578. // constructed very simple DISCOVER message with:
  579. // - client-id option
  580. // - address set to specific value as hint
  581. //
  582. // expected returned OFFER message:
  583. // - copy of client-id
  584. // - server-id
  585. // - offered address
  586. TEST_F(Dhcpv4SrvTest, DiscoverHint) {
  587. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  588. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  589. IOAddress hint("192.0.2.107");
  590. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  591. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  592. OptionPtr clientid = generateClientId();
  593. dis->addOption(clientid);
  594. dis->setYiaddr(hint);
  595. // Pass it to the server and get an offer
  596. Pkt4Ptr offer = srv->processDiscover(dis);
  597. // Check if we get response at all
  598. checkResponse(offer, DHCPOFFER, 1234);
  599. // Check that address was returned from proper range, that its lease
  600. // lifetime is correct, that T1 and T2 are returned properly
  601. checkAddressParams(offer, subnet_);
  602. EXPECT_EQ(offer->getYiaddr().toText(), hint.toText());
  603. // Check identifiers
  604. checkServerId(offer, srv->getServerID());
  605. checkClientId(offer, clientid);
  606. }
  607. // This test verifies that incoming DISCOVER can be handled properly, that an
  608. // OFFER is generated, that the response has an address and that address
  609. // really belongs to the configured pool.
  610. //
  611. // constructed very simple DISCOVER message with:
  612. // - address set to specific value as hint
  613. //
  614. // expected returned OFFER message:
  615. // - copy of client-id
  616. // - server-id
  617. // - offered address
  618. TEST_F(Dhcpv4SrvTest, DiscoverNoClientId) {
  619. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  620. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  621. IOAddress hint("192.0.2.107");
  622. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  623. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  624. dis->setYiaddr(hint);
  625. // Pass it to the server and get an offer
  626. Pkt4Ptr offer = srv->processDiscover(dis);
  627. // Check if we get response at all
  628. checkResponse(offer, DHCPOFFER, 1234);
  629. // Check that address was returned from proper range, that its lease
  630. // lifetime is correct, that T1 and T2 are returned properly
  631. checkAddressParams(offer, subnet_);
  632. EXPECT_EQ(offer->getYiaddr().toText(), hint.toText());
  633. // Check identifiers
  634. checkServerId(offer, srv->getServerID());
  635. }
  636. // This test verifies that incoming DISCOVER can be handled properly, that an
  637. // OFFER is generated, that the response has an address and that address
  638. // really belongs to the configured pool.
  639. //
  640. // constructed very simple DISCOVER message with:
  641. // - client-id option
  642. // - address set to specific value as hint, but that hint is invalid
  643. //
  644. // expected returned OFFER message:
  645. // - copy of client-id
  646. // - server-id
  647. // - offered address (!= hint)
  648. TEST_F(Dhcpv4SrvTest, DiscoverInvalidHint) {
  649. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  650. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  651. IOAddress hint("10.1.2.3");
  652. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  653. dis->setRemoteAddr(IOAddress("192.0.2.107"));
  654. OptionPtr clientid = generateClientId();
  655. dis->addOption(clientid);
  656. dis->setYiaddr(hint);
  657. // Pass it to the server and get an offer
  658. Pkt4Ptr offer = srv->processDiscover(dis);
  659. // Check if we get response at all
  660. checkResponse(offer, DHCPOFFER, 1234);
  661. // Check that address was returned from proper range, that its lease
  662. // lifetime is correct, that T1 and T2 are returned properly
  663. checkAddressParams(offer, subnet_);
  664. EXPECT_NE(offer->getYiaddr().toText(), hint.toText());
  665. // Check identifiers
  666. checkServerId(offer, srv->getServerID());
  667. checkClientId(offer, clientid);
  668. }
  669. /// @todo: Add a test that client sends hint that is in pool, but currently
  670. /// being used by a different client.
  671. // This test checks that the server is offering different addresses to different
  672. // clients in OFFERs. Please note that OFFER is not a guarantee that such
  673. // an address will be assigned. Had the pool was very small and contained only
  674. // 2 addresses, the third client would get the same offer as the first one
  675. // and this is a correct behavior. It is REQUEST that will fail for the third
  676. // client. OFFER is basically saying "if you send me a request, you will
  677. // probably get an address like this" (there are no guarantees).
  678. TEST_F(Dhcpv4SrvTest, ManyDiscovers) {
  679. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  680. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  681. Pkt4Ptr dis1 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  682. Pkt4Ptr dis2 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 2345));
  683. Pkt4Ptr dis3 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 3456));
  684. dis1->setRemoteAddr(IOAddress("192.0.2.1"));
  685. dis2->setRemoteAddr(IOAddress("192.0.2.2"));
  686. dis3->setRemoteAddr(IOAddress("192.0.2.3"));
  687. // Different client-id sizes
  688. OptionPtr clientid1 = generateClientId(4); // length 4
  689. OptionPtr clientid2 = generateClientId(5); // length 5
  690. OptionPtr clientid3 = generateClientId(6); // length 6
  691. dis1->addOption(clientid1);
  692. dis2->addOption(clientid2);
  693. dis3->addOption(clientid3);
  694. // Pass it to the server and get an offer
  695. Pkt4Ptr offer1 = srv->processDiscover(dis1);
  696. Pkt4Ptr offer2 = srv->processDiscover(dis2);
  697. Pkt4Ptr offer3 = srv->processDiscover(dis3);
  698. // Check if we get response at all
  699. checkResponse(offer1, DHCPOFFER, 1234);
  700. checkResponse(offer2, DHCPOFFER, 2345);
  701. checkResponse(offer3, DHCPOFFER, 3456);
  702. IOAddress addr1 = offer1->getYiaddr();
  703. IOAddress addr2 = offer2->getYiaddr();
  704. IOAddress addr3 = offer3->getYiaddr();
  705. // Check that the assigned address is indeed from the configured pool
  706. checkAddressParams(offer1, subnet_);
  707. checkAddressParams(offer2, subnet_);
  708. checkAddressParams(offer3, subnet_);
  709. // Check server-ids
  710. checkServerId(offer1, srv->getServerID());
  711. checkServerId(offer2, srv->getServerID());
  712. checkServerId(offer3, srv->getServerID());
  713. checkClientId(offer1, clientid1);
  714. checkClientId(offer2, clientid2);
  715. checkClientId(offer3, clientid3);
  716. // Finally check that the addresses offered are different
  717. EXPECT_NE(addr1.toText(), addr2.toText());
  718. EXPECT_NE(addr2.toText(), addr3.toText());
  719. EXPECT_NE(addr3.toText(), addr1.toText());
  720. cout << "Offered address to client1=" << addr1.toText() << endl;
  721. cout << "Offered address to client2=" << addr2.toText() << endl;
  722. cout << "Offered address to client3=" << addr3.toText() << endl;
  723. }
  724. // This test verifies that incoming REQUEST can be handled properly, that an
  725. // ACK is generated, that the response has an address and that address
  726. // really belongs to the configured pool.
  727. //
  728. // constructed a single REQUEST message with:
  729. // - client-id option
  730. // - hwaddr information
  731. // - requested address (that the client received in DISCOVER/OFFER exchange)
  732. //
  733. // expected returned ACK message:
  734. // - copy of client-id
  735. // - server-id
  736. // - assigned address
  737. //
  738. // Test verifies that the lease is actually in the database.
  739. TEST_F(Dhcpv4SrvTest, RequestBasic) {
  740. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  741. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  742. IOAddress hint("192.0.2.107");
  743. Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234));
  744. req->setRemoteAddr(IOAddress("192.0.2.1"));
  745. OptionPtr clientid = generateClientId();
  746. req->addOption(clientid);
  747. req->setYiaddr(hint);
  748. // Pass it to the server and get an advertise
  749. Pkt4Ptr ack = srv->processRequest(req);
  750. // Check if we get response at all
  751. checkResponse(ack, DHCPACK, 1234);
  752. EXPECT_EQ(hint.toText(), ack->getYiaddr().toText());
  753. // Check that address was returned from proper range, that its lease
  754. // lifetime is correct, that T1 and T2 are returned properly
  755. checkAddressParams(ack, subnet_);
  756. // Check identifiers
  757. checkServerId(ack, srv->getServerID());
  758. checkClientId(ack, clientid);
  759. // Check that the lease is really in the database
  760. Lease4Ptr l = checkLease(ack, clientid, req->getHWAddr(), hint);
  761. ASSERT_TRUE(l);
  762. LeaseMgrFactory::instance().deleteLease(l->addr_);
  763. }
  764. // This test verifies that incoming REQUEST can be handled properly, that an
  765. // ACK is generated, that the response has an address and that address
  766. // really belongs to the configured pool.
  767. //
  768. // constructed 3 REQUEST messages with:
  769. // - client-id option (differs between messages)
  770. // - hwaddr information (differs between messages)
  771. //
  772. // expected returned ACK message:
  773. // - copy of client-id
  774. // - server-id
  775. // - assigned address (different for each client)
  776. TEST_F(Dhcpv4SrvTest, ManyRequests) {
  777. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  778. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  779. const IOAddress req_addr1("192.0.2.105");
  780. const IOAddress req_addr2("192.0.2.101");
  781. const IOAddress req_addr3("192.0.2.109");
  782. const IOAddress relay("192.0.2.1");
  783. Pkt4Ptr req1 = Pkt4Ptr(new Pkt4(DHCPOFFER, 1234));
  784. Pkt4Ptr req2 = Pkt4Ptr(new Pkt4(DHCPOFFER, 2345));
  785. Pkt4Ptr req3 = Pkt4Ptr(new Pkt4(DHCPOFFER, 3456));
  786. req1->setRemoteAddr(relay);
  787. req2->setRemoteAddr(relay);
  788. req3->setRemoteAddr(relay);
  789. req1->setYiaddr(req_addr1);
  790. req2->setYiaddr(req_addr2);
  791. req3->setYiaddr(req_addr3);
  792. req1->setHWAddr(generateHWAddr(6));
  793. req2->setHWAddr(generateHWAddr(7));
  794. req3->setHWAddr(generateHWAddr(8));
  795. // Different client-id sizes
  796. OptionPtr clientid1 = generateClientId(4); // length 4
  797. OptionPtr clientid2 = generateClientId(5); // length 5
  798. OptionPtr clientid3 = generateClientId(6); // length 6
  799. req1->addOption(clientid1);
  800. req2->addOption(clientid2);
  801. req3->addOption(clientid3);
  802. // Pass it to the server and get an advertise
  803. Pkt4Ptr ack1 = srv->processRequest(req1);
  804. Pkt4Ptr ack2 = srv->processRequest(req2);
  805. Pkt4Ptr ack3 = srv->processRequest(req3);
  806. // Check if we get response at all
  807. checkResponse(ack1, DHCPACK, 1234);
  808. checkResponse(ack2, DHCPACK, 2345);
  809. checkResponse(ack3, DHCPACK, 3456);
  810. IOAddress addr1 = ack1->getYiaddr();
  811. IOAddress addr2 = ack2->getYiaddr();
  812. IOAddress addr3 = ack3->getYiaddr();
  813. // Check that every client received the address it requested
  814. EXPECT_EQ(req_addr1.toText(), addr1.toText());
  815. EXPECT_EQ(req_addr2.toText(), addr2.toText());
  816. EXPECT_EQ(req_addr3.toText(), addr3.toText());
  817. // Check that the assigned address is indeed from the configured pool
  818. checkAddressParams(ack1, subnet_);
  819. checkAddressParams(ack2, subnet_);
  820. checkAddressParams(ack3, subnet_);
  821. // Check DUIDs
  822. checkServerId(ack1, srv->getServerID());
  823. checkServerId(ack2, srv->getServerID());
  824. checkServerId(ack3, srv->getServerID());
  825. checkClientId(ack1, clientid1);
  826. checkClientId(ack2, clientid2);
  827. checkClientId(ack3, clientid3);
  828. // Check that leases are in the database
  829. Lease4Ptr l = checkLease(ack1, clientid1, req1->getHWAddr(), addr1);
  830. EXPECT_TRUE(l);
  831. l = checkLease(ack2, clientid2, req2->getHWAddr(), addr2);
  832. l = checkLease(ack3, clientid3, req3->getHWAddr(), addr3);
  833. // Finally check that the addresses offered are different
  834. EXPECT_NE(addr1.toText(), addr2.toText());
  835. EXPECT_NE(addr2.toText(), addr3.toText());
  836. EXPECT_NE(addr3.toText(), addr1.toText());
  837. cout << "Offered address to client1=" << addr1.toText() << endl;
  838. cout << "Offered address to client2=" << addr2.toText() << endl;
  839. cout << "Offered address to client3=" << addr3.toText() << endl;
  840. }
  841. // This test verifies that incoming (positive) REQUEST/Renewing can be handled properly, that a
  842. // REPLY is generated, that the response has an address and that address
  843. // really belongs to the configured pool and that lease is actually renewed.
  844. //
  845. // expected:
  846. // - returned REPLY message has copy of client-id
  847. // - returned REPLY message has server-id
  848. // - returned REPLY message has IA that includes IAADDR
  849. // - lease is actually renewed in LeaseMgr
  850. TEST_F(Dhcpv4SrvTest, RenewBasic) {
  851. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  852. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  853. const IOAddress addr("192.0.2.106");
  854. const uint32_t temp_t1 = 50;
  855. const uint32_t temp_t2 = 75;
  856. const uint32_t temp_valid = 100;
  857. const time_t temp_timestamp = time(NULL) - 10;
  858. // Generate client-id also sets client_id_ member
  859. OptionPtr clientid = generateClientId();
  860. // Check that the address we are about to use is indeed in pool
  861. ASSERT_TRUE(subnet_->inPool(addr));
  862. // let's create a lease and put it in the LeaseMgr
  863. uint8_t hwaddr2[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  864. Lease4Ptr used(new Lease4(IOAddress("192.0.2.106"), hwaddr2, sizeof(hwaddr2),
  865. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  866. temp_valid, temp_t1, temp_t2, temp_timestamp,
  867. subnet_->getID()));
  868. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  869. // Check that the lease is really in the database
  870. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  871. ASSERT_TRUE(l);
  872. // Check that T1, T2, preferred, valid and cltt really set.
  873. // Constructed lease looks as if it was assigned 10 seconds ago
  874. // EXPECT_EQ(l->t1_, temp_t1);
  875. // EXPECT_EQ(l->t2_, temp_t2);
  876. EXPECT_EQ(l->valid_lft_, temp_valid);
  877. EXPECT_EQ(l->cltt_, temp_timestamp);
  878. // Let's create a RENEW
  879. Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234));
  880. req->setRemoteAddr(IOAddress(addr));
  881. req->setYiaddr(addr);
  882. req->setCiaddr(addr); // client's address
  883. req->addOption(clientid);
  884. req->addOption(srv->getServerID());
  885. // Pass it to the server and hope for a REPLY
  886. Pkt4Ptr ack = srv->processRequest(req);
  887. // Check if we get response at all
  888. checkResponse(ack, DHCPACK, 1234);
  889. EXPECT_EQ(addr.toText(), ack->getYiaddr().toText());
  890. // Check that address was returned from proper range, that its lease
  891. // lifetime is correct, that T1 and T2 are returned properly
  892. checkAddressParams(ack, subnet_);
  893. // Check identifiers
  894. checkServerId(ack, srv->getServerID());
  895. checkClientId(ack, clientid);
  896. // Check that the lease is really in the database
  897. l = checkLease(ack, clientid, req->getHWAddr(), addr);
  898. ASSERT_TRUE(l);
  899. // Check that T1, T2, preferred, valid and cltt were really updated
  900. EXPECT_EQ(l->t1_, subnet_->getT1());
  901. EXPECT_EQ(l->t2_, subnet_->getT2());
  902. EXPECT_EQ(l->valid_lft_, subnet_->getValid());
  903. // Checking for CLTT is a bit tricky if we want to avoid off by 1 errors
  904. int32_t cltt = static_cast<int32_t>(l->cltt_);
  905. int32_t expected = static_cast<int32_t>(time(NULL));
  906. // Equality or difference by 1 between cltt and expected is ok.
  907. EXPECT_GE(1, abs(cltt - expected));
  908. EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(addr));
  909. }
  910. // @todo: Implement tests for rejecting renewals
  911. // This test verifies if the sanityCheck() really checks options presence.
  912. TEST_F(Dhcpv4SrvTest, sanityCheck) {
  913. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  914. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  915. Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  916. // Client-id is optional for information-request, so
  917. EXPECT_NO_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::OPTIONAL));
  918. // Empty packet, no server-id
  919. EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation);
  920. pkt->addOption(srv->getServerID());
  921. // Server-id is mandatory and present = no exception
  922. EXPECT_NO_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY));
  923. // Server-id is forbidden, but present => exception
  924. EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::FORBIDDEN),
  925. RFCViolation);
  926. }
  927. // This test verifies that incoming (positive) RELEASE can be handled properly.
  928. // As there is no REPLY in DHCPv4, the only thing to verify here is that
  929. // the lease is indeed removed from the database.
  930. TEST_F(Dhcpv4SrvTest, ReleaseBasic) {
  931. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  932. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  933. const IOAddress addr("192.0.2.106");
  934. const uint32_t temp_t1 = 50;
  935. const uint32_t temp_t2 = 75;
  936. const uint32_t temp_valid = 100;
  937. const time_t temp_timestamp = time(NULL) - 10;
  938. // Generate client-id also duid_
  939. OptionPtr clientid = generateClientId();
  940. // Check that the address we are about to use is indeed in pool
  941. ASSERT_TRUE(subnet_->inPool(addr));
  942. // Let's create a lease and put it in the LeaseMgr
  943. uint8_t mac_addr[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  944. HWAddrPtr hw(new HWAddr(mac_addr, sizeof(mac_addr), HTYPE_ETHER));
  945. Lease4Ptr used(new Lease4(addr, mac_addr, sizeof(mac_addr),
  946. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  947. temp_valid, temp_t1, temp_t2, temp_timestamp,
  948. subnet_->getID()));
  949. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  950. // Check that the lease is really in the database
  951. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  952. ASSERT_TRUE(l);
  953. // Let's create a RELEASE
  954. // Generate client-id also duid_
  955. Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
  956. rel->setRemoteAddr(addr);
  957. rel->setYiaddr(addr);
  958. rel->addOption(clientid);
  959. rel->addOption(srv->getServerID());
  960. rel->setHWAddr(hw);
  961. // Pass it to the server and hope for a REPLY
  962. // Note: this is no response to RELEASE in DHCPv4
  963. EXPECT_NO_THROW(srv->processRelease(rel));
  964. // The lease should be gone from LeaseMgr
  965. l = LeaseMgrFactory::instance().getLease4(addr);
  966. EXPECT_FALSE(l);
  967. // Try to get the lease by hardware address
  968. // @todo: Uncomment this once trac2592 is implemented
  969. // Lease4Collection leases = LeaseMgrFactory::instance().getLease4(hw->hwaddr_);
  970. // EXPECT_EQ(leases.size(), 0);
  971. // Try to get it by hw/subnet_id combination
  972. l = LeaseMgrFactory::instance().getLease4(hw->hwaddr_, subnet_->getID());
  973. EXPECT_FALSE(l);
  974. // Try by client-id
  975. // @todo: Uncomment this once trac2592 is implemented
  976. //Lease4Collection leases = LeaseMgrFactory::instance().getLease4(*client_id_);
  977. //EXPECT_EQ(leases.size(), 0);
  978. // Try by client-id/subnet-id
  979. l = LeaseMgrFactory::instance().getLease4(*client_id_, subnet_->getID());
  980. EXPECT_FALSE(l);
  981. // Ok, the lease is *really* not there.
  982. }
  983. // This test verifies that incoming (invalid) RELEASE can be handled properly.
  984. //
  985. // This test checks 3 scenarios:
  986. // 1. there is no such lease at all
  987. // 2. there is such a lease, but it is assigned to a different IAID
  988. // 3. there is such a lease, but it belongs to a different client
  989. TEST_F(Dhcpv4SrvTest, ReleaseReject) {
  990. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  991. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  992. const IOAddress addr("192.0.2.106");
  993. const uint32_t t1 = 50;
  994. const uint32_t t2 = 75;
  995. const uint32_t valid = 100;
  996. const time_t timestamp = time(NULL) - 10;
  997. // Let's create a lease and put it in the LeaseMgr
  998. uint8_t bogus_mac_addr[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  999. HWAddrPtr bogus_hw(new HWAddr(bogus_mac_addr, sizeof(bogus_mac_addr), HTYPE_ETHER));
  1000. OptionPtr bogus_clientid = generateClientId(7); // different length
  1001. // Generate client-id also duid_
  1002. OptionPtr clientid = generateClientId();
  1003. // Check that the address we are about to use is indeed in pool
  1004. ASSERT_TRUE(subnet_->inPool(addr));
  1005. // Let's create a RELEASE
  1006. // Generate client-id also duid_
  1007. Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
  1008. rel->setRemoteAddr(addr);
  1009. rel->setYiaddr(addr);
  1010. rel->addOption(clientid);
  1011. rel->addOption(srv->getServerID());
  1012. rel->setHWAddr(bogus_hw);
  1013. // Case 1: No lease known to server
  1014. SCOPED_TRACE("CASE 1: Lease is not known to the server");
  1015. // There is nothing to check here. The lease is not there and server does
  1016. // not send anything back. This case is enumerated here just for keeping
  1017. // parity with similar test in DHCPv6.
  1018. EXPECT_NO_THROW(srv->processRelease(rel));
  1019. // CASE 2: Lease is known and belongs to this client, but to a different hardware
  1020. SCOPED_TRACE("CASE 2: Lease is known and belongs to this client, but uses different HW addr");
  1021. // Let's create a lease and put it in the LeaseMgr
  1022. uint8_t mac_addr[] = { 0, 0x1, 0x2, 0x3, 0x4, 0x5};
  1023. HWAddrPtr hw(new HWAddr(mac_addr, sizeof(mac_addr), HTYPE_ETHER));
  1024. Lease4Ptr used(new Lease4(addr, mac_addr, sizeof(mac_addr),
  1025. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  1026. valid, t1, t2, timestamp, subnet_->getID()));
  1027. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  1028. // Check that the lease is really in the database
  1029. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  1030. ASSERT_TRUE(l);
  1031. rel->setHWAddr(bogus_hw);
  1032. EXPECT_NO_THROW(srv->processRelease(rel));
  1033. // Check that the lease was not removed (due to hardware address mis-match)
  1034. l = LeaseMgrFactory::instance().getLease4(addr);
  1035. ASSERT_TRUE(l);
  1036. // CASE 3: Lease belongs to a client with different client-id
  1037. SCOPED_TRACE("CASE 3: Lease belongs to a client with different client-id");
  1038. rel->setHWAddr(hw); // proper HW address this time
  1039. rel->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1040. rel->addOption(bogus_clientid); // but invalid client-id
  1041. OptionPtr x = rel->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1042. EXPECT_NO_THROW(srv->processRelease(rel));
  1043. // Check that the lease is still there
  1044. l = LeaseMgrFactory::instance().getLease4(addr);
  1045. ASSERT_TRUE(l);
  1046. // Final sanity check. Verify that with valid hw and client-id release is successful
  1047. rel->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1048. rel->addOption(clientid);
  1049. // It should work this time
  1050. EXPECT_NO_THROW(srv->processRelease(rel));
  1051. // Check that the lease is not there
  1052. l = LeaseMgrFactory::instance().getLease4(addr);
  1053. EXPECT_FALSE(l);
  1054. }
  1055. // This test verifies if the server-id disk operations (read, write) are
  1056. // working properly.
  1057. TEST_F(Dhcpv4SrvTest, ServerID) {
  1058. NakedDhcpv4Srv srv(0);
  1059. string srvid_text = "192.0.2.100";
  1060. IOAddress srvid(srvid_text);
  1061. fstream file1(SRVID_FILE, ios::out | ios::trunc);
  1062. file1 << srvid_text;
  1063. file1.close();
  1064. // Test reading from a file
  1065. EXPECT_TRUE(srv.loadServerID(SRVID_FILE));
  1066. ASSERT_TRUE(srv.getServerID());
  1067. EXPECT_EQ(srvid_text, srv.srvidToString(srv.getServerID()));
  1068. // Now test writing to a file
  1069. EXPECT_EQ(0, unlink(SRVID_FILE));
  1070. EXPECT_NO_THROW(srv.writeServerID(SRVID_FILE));
  1071. fstream file2(SRVID_FILE, ios::in);
  1072. ASSERT_TRUE(file2.good());
  1073. string text;
  1074. file2 >> text;
  1075. file2.close();
  1076. EXPECT_EQ(srvid_text, text);
  1077. }
  1078. } // end of anonymous namespace