test_control_unittest.cc 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. // Copyright (C) 2012-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 <cstddef>
  15. #include <stdint.h>
  16. #include <string>
  17. #include <fstream>
  18. #include <gtest/gtest.h>
  19. #include <boost/date_time/posix_time/posix_time.hpp>
  20. #include <exceptions/exceptions.h>
  21. #include <asiolink/io_address.h>
  22. #include <dhcp/dhcp4.h>
  23. #include <dhcp/iface_mgr.h>
  24. #include "command_options_helper.h"
  25. #include "../test_control.h"
  26. using namespace std;
  27. using namespace boost::posix_time;
  28. using namespace isc;
  29. using namespace isc::dhcp;
  30. using namespace isc::perfdhcp;
  31. /// \brief Test Control class with protected members made public.
  32. ///
  33. /// This class makes protected TestControl class'es member public
  34. /// to allow unit testing.
  35. class NakedTestControl: public TestControl {
  36. public:
  37. /// \brief Incremental transaction id generaator.
  38. ///
  39. /// This is incremental transaction id generator. It overrides
  40. /// the default transaction id generator that generates transaction
  41. /// ids using random function. This generator will generate values
  42. /// like: 1,2,3 etc.
  43. class IncrementalGenerator : public TestControl::NumberGenerator {
  44. public:
  45. /// \brief Default constructor.
  46. IncrementalGenerator() :
  47. NumberGenerator(),
  48. transid_(0) {
  49. }
  50. /// \brief Generate unique transaction id.
  51. ///
  52. /// Generate unique transaction ids incrementally:
  53. /// 1,2,3,4 etc.
  54. ///
  55. /// \return generated transaction id.
  56. virtual uint32_t generate() {
  57. return (++transid_);
  58. }
  59. private:
  60. uint32_t transid_; ///< Last generated transaction id.
  61. };
  62. using TestControl::checkExitConditions;
  63. using TestControl::factoryElapsedTime6;
  64. using TestControl::factoryGeneric;
  65. using TestControl::factoryIana6;
  66. using TestControl::factoryOptionRequestOption6;
  67. using TestControl::factoryRapidCommit6;
  68. using TestControl::factoryRequestList4;
  69. using TestControl::generateDuid;
  70. using TestControl::generateMacAddress;
  71. using TestControl::getNextExchangesNum;
  72. using TestControl::getTemplateBuffer;
  73. using TestControl::initPacketTemplates;
  74. using TestControl::initializeStatsMgr;
  75. using TestControl::openSocket;
  76. using TestControl::processReceivedPacket4;
  77. using TestControl::processReceivedPacket6;
  78. using TestControl::registerOptionFactories;
  79. using TestControl::sendDiscover4;
  80. using TestControl::sendSolicit6;
  81. using TestControl::setDefaults4;
  82. using TestControl::setDefaults6;
  83. NakedTestControl() : TestControl() {
  84. uint32_t clients_num = CommandOptions::instance().getClientsNum() == 0 ?
  85. 1 : CommandOptions::instance().getClientsNum();
  86. setMacAddrGenerator(NumberGeneratorPtr(new TestControl::SequentialGenerator(clients_num)));
  87. };
  88. };
  89. /// \brief Test Fixture Class
  90. ///
  91. /// This test fixture class is used to perform
  92. /// unit tests on perfdhcp TestControl class.
  93. class TestControlTest : public virtual ::testing::Test
  94. {
  95. public:
  96. typedef std::vector<uint8_t> MacAddress;
  97. typedef MacAddress::iterator MacAddressIterator;
  98. typedef std::vector<uint8_t> Duid;
  99. typedef Duid::iterator DuidIterator;
  100. /// \brief Default Constructor
  101. TestControlTest() { }
  102. /// \brief Create packet template file from binary data.
  103. ///
  104. /// Function creates file containing data from the provided buffer
  105. /// in hexadecimal format. The size parameter specifies the maximum
  106. /// size of the file. If total number of hexadecimal digits resulting
  107. /// from buffer size is greater than maximum file size the file is
  108. /// truncated.
  109. ///
  110. /// \param filename template file to be created.
  111. /// \param buffer with binary datato be stored in file.
  112. /// \param size target size of the file.
  113. /// \param invalid_chars inject invalid chars to the template file.
  114. /// \return true if file creation successful.
  115. bool createTemplateFile(const std::string& filename,
  116. const std::vector<uint8_t>& buf,
  117. const size_t size,
  118. const bool invalid_chars = false) const {
  119. std::ofstream temp_file;
  120. temp_file.open(filename.c_str(), ios::out | ios::trunc);
  121. if (!temp_file.is_open()) {
  122. return (false);
  123. }
  124. for (int i = 0; i < buf.size(); ++i) {
  125. int first_digit = buf[i] / 16;
  126. int second_digit = buf[i] % 16;
  127. // Insert two spaces between two hexadecimal digits.
  128. // Spaces are allowed in template files.
  129. temp_file << std::string(2, ' ');
  130. if (2 * i + 1 < size) {
  131. if (!invalid_chars) {
  132. temp_file << std::hex << first_digit << second_digit << std::dec;
  133. } else {
  134. temp_file << "XY";
  135. }
  136. } else if (2 * i < size) {
  137. if (!invalid_chars) {
  138. temp_file << std::hex << first_digit;
  139. } else {
  140. temp_file << "X";
  141. }
  142. } else {
  143. break;
  144. }
  145. }
  146. temp_file.close();
  147. return (true);
  148. }
  149. /// \brief Get local loopback interface name.
  150. ///
  151. /// Scan available network interfaces for local loopback
  152. /// interface and get its name. On Linux this interface is
  153. /// usually called 'lo' but on other systems, e.g. BSD
  154. /// it will have slightly different name. Local loopback
  155. /// interface is required for unit tests that require
  156. /// socket creation.
  157. ///
  158. /// \return local loopback interface name.
  159. std::string getLocalLoopback() const {
  160. const IfaceMgr::IfaceCollection& ifaces =
  161. IfaceMgr::instance().getIfaces();
  162. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  163. iface != ifaces.end();
  164. ++iface) {
  165. if (iface->flag_loopback_) {
  166. return (iface->getName());
  167. }
  168. }
  169. return ("");
  170. }
  171. /// \brief Get full path to a file in testdata directory.
  172. ///
  173. /// \param filename filename being appended to absolute
  174. /// path to testdata directory
  175. ///
  176. /// \return full path to a file in testdata directory.
  177. std::string getFullPath(const std::string& filename) const {
  178. std::ostringstream stream;
  179. stream << TEST_DATA_DIR << "/" << filename;
  180. return (stream.str());
  181. }
  182. /// \brief Match requested options in the buffer with given list.
  183. ///
  184. /// This method iterates through options provided in the buffer
  185. /// and matches them with the options specified with first parameter.
  186. /// Options in both vectors may be laid in different order.
  187. ///
  188. /// \param requested_options reference buffer with options.
  189. /// \param buf test buffer with options that will be matched.
  190. /// \return number of options from the buffer matched with options
  191. /// in the reference buffer.
  192. int matchRequestedOptions(const dhcp::OptionBuffer& requested_options,
  193. const dhcp::OptionBuffer& buf) const {
  194. size_t matched_num = 0;
  195. for (size_t i = 0; i < buf.size(); ++i) {
  196. for (int j = 0; j < requested_options.size(); ++j) {
  197. if (requested_options[j] == buf[i]) {
  198. // Requested option has been found.
  199. ++matched_num;
  200. }
  201. }
  202. }
  203. return (matched_num);
  204. }
  205. /// \brief Match requested DHCPv6 options in the buffer with given list.
  206. ///
  207. /// This method iterates through options provided in the buffer and
  208. /// matches them with the options specified with first parameter.
  209. /// Options in both vectors ma be laid in different order.
  210. ///
  211. /// \param requested_options reference buffer with options.
  212. /// \param buf test buffer with options that will be matched.
  213. /// \return number of options from the buffer matched with options in
  214. /// the reference buffer or -1 if error occured.
  215. int matchRequestedOptions6(const dhcp::OptionBuffer& requested_options,
  216. const dhcp::OptionBuffer& buf) const {
  217. // Sanity check.
  218. if ((requested_options.size() % 2 != 0) ||
  219. (buf.size() % 2 != 0)) {
  220. return -1;
  221. }
  222. size_t matched_num = 0;
  223. for (size_t i = 0; i < buf.size(); i += 2) {
  224. for (int j = 0; j < requested_options.size(); j += 2) {
  225. uint16_t opt_i = (buf[i + 1] << 8) + (buf[i] & 0xFF);
  226. uint16_t opt_j = (requested_options[j + 1] << 8)
  227. + (requested_options[j] & 0xFF);
  228. if (opt_i == opt_j) {
  229. // Requested option has been found.
  230. ++matched_num;
  231. }
  232. }
  233. }
  234. return (matched_num);
  235. }
  236. /// \brief Calculate the maximum vectors' mismatch position.
  237. ///
  238. /// This helper function calculates the maximum mismatch position
  239. /// between two vectors (two different DUIDs or MAC addresses).
  240. /// Calculated position is counted from the end of vectors.
  241. /// Calculation is based on number of simulated clients. When number
  242. /// of clients is less than 256 different DUIDs or MAC addresses can
  243. /// can be coded in such a way that they differ on last vector element.
  244. /// If number of clients is between 257 and 65536 they can differ
  245. /// on two last positions so the returned value will be 2 and so on.
  246. ///
  247. /// \param clients_num number of simulated clients
  248. /// \return maximum mismatch position
  249. int unequalOctetPosition(int clients_num) const {
  250. if (!clients_num) {
  251. return (0);
  252. }
  253. clients_num--;
  254. int cnt = 0;
  255. while (clients_num) {
  256. clients_num >>= 8;
  257. ++cnt;
  258. }
  259. return (cnt);
  260. }
  261. /// brief Test generation of mulitple DUIDs
  262. ///
  263. /// Thie method checks the generation of multiple DUIDs. Number
  264. /// of iterations depends on the number of simulated clients.
  265. /// It is expected that DUID's size is 14 (consists of DUID-LLT
  266. /// HW type field, 4 octets of time value and MAC address). The
  267. /// MAC address can be randomized depending on the number of
  268. /// simulated clients. The DUID-LLT and HW type are expected to
  269. /// be constant. The time value has to be properly calculated
  270. /// as the number of seconds since DUID time epoch. The parts
  271. /// of MAC address has to change if multiple clients are simulated
  272. /// and do not change if single client is simulated.
  273. void testDuid() const {
  274. int clients_num = CommandOptions::instance().getClientsNum();
  275. // Initialize Test Control class.
  276. NakedTestControl tc;
  277. // The old duid will be holding the previously generated DUID.
  278. // It will be used to compare against the new one. If we have
  279. // multiple clients we want to make sure that duids differ.
  280. uint8_t randomized = 0;
  281. Duid old_duid(tc.generateDuid(randomized));
  282. Duid new_duid(0);
  283. // total_dist shows the total difference between generated duid.
  284. // It has to be greater than zero if multiple clients are simulated.
  285. size_t total_dist = 0;
  286. // Number of unique DUIDs.
  287. size_t unique_duids = 0;
  288. // Holds the position if the octet on which two DUIDS can be different.
  289. // If number of clients is 256 or less it is last DUID octet (except for
  290. // single client when subsequent DUIDs have to be equal). If number of
  291. // clients is between 257 and 65536 the last two octets can differ etc.
  292. int unequal_pos = unequalOctetPosition(clients_num);
  293. // Keep generated DUIDs in this container.
  294. std::list<std::vector<uint8_t> > duids;
  295. // Perform number of iterations to generate number of DUIDs.
  296. for (int i = 0; i < 10 * clients_num; ++i) {
  297. if (new_duid.empty()) {
  298. new_duid = old_duid;
  299. } else {
  300. std::swap(old_duid, new_duid);
  301. new_duid = tc.generateDuid(randomized);
  302. }
  303. // The DUID-LLT is expected to start with DUID_LLT value
  304. // of 1 and hardware ethernet type equal to 1 (HWETHER_TYPE).
  305. const uint8_t duid_llt_and_hw[4] = { 0x0, 0x1, 0x0, 0x1 };
  306. // We assume DUID-LLT length 14. This includes 4 octets of
  307. // DUID_LLT value, two octets of hardware type, 4 octets
  308. // of time value and 6 octets of variable link layer (MAC)
  309. // address.
  310. const int duid_llt_size = 14;
  311. ASSERT_EQ(duid_llt_size, new_duid.size());
  312. // The first four octets do not change.
  313. EXPECT_TRUE(std::equal(new_duid.begin(), new_duid.begin() + 4,
  314. duid_llt_and_hw));
  315. // As described in RFC3315: 'the time value is the time
  316. // that the DUID is generated represented in seconds
  317. // since midnight (UTC), January 1, 2000, modulo 2^32.'
  318. uint32_t duid_time = 0;
  319. // Pick 4 bytes of the time from generated DUID and put them
  320. // in reverse order (in DUID they are stored in network order).
  321. for (int j = 4; j < 8; ++j) {
  322. duid_time |= new_duid[j] << (j - 4);
  323. }
  324. // Calculate the duration since epoch time.
  325. ptime now = microsec_clock::universal_time();
  326. ptime duid_epoch(from_iso_string("20000101T000000"));
  327. time_period period(duid_epoch, now);
  328. // Current time is the same or later than time from the DUID because
  329. // DUID had been generated before reference duration was calculated.
  330. EXPECT_GE(period.length().total_seconds(), duid_time);
  331. // Get the mismatch position (counting from the end) of
  332. // mismatched octet between previously generated DUID
  333. // and current.
  334. std::pair<DuidIterator, DuidIterator> mismatch_pos =
  335. std::mismatch(old_duid.begin(), old_duid.end(),
  336. new_duid.begin());
  337. size_t mismatch_dist =
  338. std::distance(mismatch_pos.first, old_duid.end());
  339. // For single client total_dist is expected to be 0 because
  340. // old_duid and new_duid should always match. If we have
  341. // more clients then duids have to differ except the case
  342. // if randomization algorithm generates the same values but
  343. // this would be an error in randomization algorithm.
  344. total_dist += mismatch_dist;
  345. // Mismatch may have occured on the DUID octet position
  346. // up to calculated earlier unequal_pos.
  347. ASSERT_LE(mismatch_dist, unequal_pos);
  348. // unique will inform if tested DUID is unique.
  349. bool unique = true;
  350. for (std::list<std::vector<uint8_t> >::const_iterator it =
  351. duids.begin();
  352. it != duids.end(); ++it) {
  353. // DUIDs should be of the same size if we want to compare them.
  354. ASSERT_EQ(new_duid.size(), it->size());
  355. // Check if DUID is unique.
  356. if (std::equal(new_duid.begin(), new_duid.end(), it->begin())) {
  357. unique = false;
  358. }
  359. }
  360. // Expecting that DUIDs will be unique only when
  361. // first clients-num iterations is performed.
  362. // After that, DUIDs become non unique.
  363. if (unique) {
  364. ++unique_duids;
  365. }
  366. // For number of iterations equal to clients_num,2*clients_num
  367. // 3*clients_num ... we have to have number of unique duids
  368. // equal to clients_num.
  369. if ((i != 0) && (i % clients_num == 0)) {
  370. ASSERT_EQ(clients_num, unique_duids);
  371. }
  372. // Remember generated DUID.
  373. duids.push_back(new_duid);
  374. }
  375. // If we have more than one client at least one mismatch occured.
  376. if (clients_num < 2) {
  377. EXPECT_EQ(0, total_dist);
  378. }
  379. }
  380. /// \brief Test DHCPv4 exchanges.
  381. ///
  382. /// Function simulates DHCPv4 exchanges. Function caller specifies
  383. /// number of exchanges to be simulated and number of simulated
  384. /// responses. When number of responses is lower than number of
  385. /// iterations than the difference between them is the number
  386. /// of simulated packet drops. This is useful to test if program
  387. /// exit conditions are handled properly (maximum number of packet
  388. /// drops specified as -D<max-drops> is taken into account).
  389. ///
  390. /// \param iterations_num number of exchanges to simulate.
  391. /// \param receive_num number of received OFFER packets.
  392. /// \param iterations_performed actual number of iterations.
  393. void testPkt4Exchange(int iterations_num,
  394. int receive_num,
  395. bool use_templates,
  396. int& iterations_performed) const {
  397. int sock_handle = 0;
  398. NakedTestControl tc;
  399. tc.initializeStatsMgr();
  400. // Use templates files to crate packets.
  401. if (use_templates) {
  402. tc.initPacketTemplates();
  403. ASSERT_NO_THROW(tc.getTemplateBuffer(0));
  404. ASSERT_NO_THROW(tc.getTemplateBuffer(1));
  405. }
  406. // Incremental transaction id generator will generate
  407. // predictable values of transaction id for each iteration.
  408. // This is important because we need to simulate responses
  409. // from the server and use the same transaction ids as in
  410. // packets sent by client.
  411. TestControl::NumberGeneratorPtr
  412. generator(new NakedTestControl::IncrementalGenerator());
  413. tc.setTransidGenerator(generator);
  414. // Socket is needed to send packets through the interface.
  415. ASSERT_NO_THROW(sock_handle = tc.openSocket());
  416. TestControl::TestControlSocket sock(sock_handle);
  417. uint32_t transid = 0;
  418. for (int i = 0; i < iterations_num; ++i) {
  419. if (use_templates) {
  420. ASSERT_NO_THROW(tc.sendDiscover4(sock, tc.getTemplateBuffer(0)));
  421. } else {
  422. ASSERT_NO_THROW(tc.sendDiscover4(sock));
  423. }
  424. ++transid;
  425. // Do not simulate responses for packets later
  426. // that specified as receive_num. This simulates
  427. // packet drops.
  428. if (i < receive_num) {
  429. boost::shared_ptr<Pkt4> offer_pkt4(createOfferPkt4(transid));
  430. ASSERT_NO_THROW(tc.processReceivedPacket4(sock, offer_pkt4));
  431. ++transid;
  432. }
  433. if (tc.checkExitConditions()) {
  434. iterations_performed = i + 1;
  435. break;
  436. }
  437. iterations_performed = i + 1;
  438. }
  439. }
  440. /// \brief Test DHCPv6 exchanges.
  441. ///
  442. /// Function simulates DHCPv6 exchanges. Function caller specifies
  443. /// number of exchanges to be simulated and number of simulated
  444. /// responses. When number of responses is lower than number of
  445. /// iterations than the difference between them is the number
  446. /// of simulated packet drops. This is useful to test if program
  447. /// exit conditions are handled properly (maximum number of packet
  448. /// drops specified as -D<max-drops> is taken into account).
  449. ///
  450. /// \param iterations_num number of exchanges to simulate.
  451. /// \param receive_num number of received OFFER packets.
  452. /// \param iterations_performed actual number of iterations.
  453. void testPkt6Exchange(int iterations_num,
  454. int receive_num,
  455. bool use_templates,
  456. int& iterations_performed) const {
  457. int sock_handle = 0;
  458. NakedTestControl tc;
  459. tc.initializeStatsMgr();
  460. // Use templates files to crate packets.
  461. if (use_templates) {
  462. tc.initPacketTemplates();
  463. ASSERT_NO_THROW(tc.getTemplateBuffer(0));
  464. ASSERT_NO_THROW(tc.getTemplateBuffer(1));
  465. }
  466. // Incremental transaction id generator will generate
  467. // predictable values of transaction id for each iteration.
  468. // This is important because we need to simulate reponses
  469. // from the server and use the same transaction ids as in
  470. // packets sent by client.
  471. TestControl::NumberGeneratorPtr
  472. generator(new NakedTestControl::IncrementalGenerator());
  473. tc.setTransidGenerator(generator);
  474. // Socket is needed to send packets through the interface.
  475. ASSERT_NO_THROW(sock_handle = tc.openSocket());
  476. TestControl::TestControlSocket sock(sock_handle);
  477. uint32_t transid = 0;
  478. for (int i = 0; i < iterations_num; ++i) {
  479. // Do not simulate responses for packets later
  480. // that specified as receive_num. This simulates
  481. // packet drops.
  482. if (use_templates) {
  483. ASSERT_NO_THROW(tc.sendSolicit6(sock, tc.getTemplateBuffer(0)));
  484. } else {
  485. ASSERT_NO_THROW(tc.sendSolicit6(sock));
  486. }
  487. ++transid;
  488. if (i < receive_num) {
  489. boost::shared_ptr<Pkt6>
  490. advertise_pkt6(createAdvertisePkt6(transid));
  491. // Receive ADVERTISE and send REQUEST.
  492. /* ASSERT_NO_THROW(tc.processReceivedPacket6(sock,
  493. advertise_pkt6)); */
  494. try {
  495. tc.processReceivedPacket6(sock,
  496. advertise_pkt6);
  497. } catch (const Exception& ex) {
  498. std::cout << ex.what() << std::endl;
  499. }
  500. ++transid;
  501. }
  502. if (tc.checkExitConditions()) {
  503. iterations_performed = i + 1;
  504. break;
  505. }
  506. iterations_performed = i + 1;
  507. }
  508. }
  509. /// \brief Test generation of multiple MAC addresses.
  510. ///
  511. /// This method validates generation of multiple MAC addresses.
  512. /// The MAC address can be randomized depending on the number
  513. /// of simulated clients. This test checks if different MAC
  514. /// addresses are generated if number of simulated clients is
  515. /// greater than 1. It also checks if the same MAC addresses is
  516. /// generated if only 1 client is simulated.
  517. void testMacAddress() const {
  518. int clients_num = CommandOptions::instance().getClientsNum();
  519. // The old_mac will be holding the value of previously generated
  520. // MAC address. We will be comparing the newly generated one with it
  521. // to see if it changes when mulitple clients are simulated or if it
  522. // does not change when single client is simulated.
  523. MacAddress old_mac(CommandOptions::instance().getMacTemplate());
  524. // Holds the position if the octet on which two MAC addresses can
  525. // be different. If number of clients is 256 or less it is last MAC
  526. // octet (except for single client when subsequent MAC addresses
  527. // have to be equal). If number of clients is between 257 and 65536
  528. // the last two octets can differ etc.
  529. int unequal_pos = unequalOctetPosition(clients_num);
  530. // Number of unique MACs.
  531. size_t unique_macs = 0;
  532. // Initialize Test Controller.
  533. NakedTestControl tc;
  534. size_t total_dist = 0;
  535. // Keep generated MACs in this container.
  536. std::list<std::vector<uint8_t> > macs;
  537. // Do many iterations to generate and test MAC address values.
  538. for (int i = 0; i < clients_num * 10; ++i) {
  539. // Generate new MAC address.
  540. uint8_t randomized = 0;
  541. MacAddress new_mac(tc.generateMacAddress(randomized));
  542. // Get the mismatch position (counting from the end) of
  543. // mismatched octet between previously generated MAC address
  544. // and current.
  545. std::pair<MacAddressIterator, MacAddressIterator> mismatch_pos =
  546. std::mismatch(old_mac.begin(), old_mac.end(), new_mac.begin());
  547. size_t mismatch_dist =
  548. std::distance(mismatch_pos.first, old_mac.end());
  549. // For single client total_dist is expected to be 0 because
  550. // old_mac and new_mac should always match. If we have
  551. // more clients then MAC addresses have to differ except
  552. // the case if randomization algorithm generates the same
  553. // values but this would be an error in randomization algorithm.
  554. total_dist += mismatch_dist;
  555. // Mismatch may have occured on the MAC address'es octet position
  556. // up to calculated earlier unequal_pos.
  557. ASSERT_LE(mismatch_dist, unequal_pos);
  558. // unique will inform if tested DUID is unique.
  559. bool unique = true;
  560. for (std::list<std::vector<uint8_t> >::const_iterator it =
  561. macs.begin();
  562. it != macs.end(); ++it) {
  563. // MACs should be of the same size if we want to compare them.
  564. ASSERT_EQ(new_mac.size(), it->size());
  565. // Check if MAC is unique.
  566. if (std::equal(new_mac.begin(), new_mac.end(), it->begin())) {
  567. unique = false;
  568. }
  569. }
  570. // Expecting that MACs will be unique only when
  571. // first clients-num iterations is performed.
  572. // After that, MACs become non unique.
  573. if (unique) {
  574. ++unique_macs;
  575. }
  576. // For number of iterations equal to clients_num,2*clients_num
  577. // 3*clients_num ... we have to have number of unique MACs
  578. // equal to clients_num.
  579. if ((i != 0) && (i % clients_num == 0)) {
  580. ASSERT_EQ(clients_num, unique_macs);
  581. }
  582. // Remember generated MAC.
  583. macs.push_back(new_mac);
  584. }
  585. if (clients_num < 2) {
  586. EXPECT_EQ(total_dist, 0);
  587. }
  588. }
  589. /// \brief Parse command line string with CommandOptions.
  590. ///
  591. /// \param cmdline command line string to be parsed.
  592. /// \throw isc::Unexpected if unexpected error occured.
  593. /// \throw isc::InvalidParameter if command line is invalid.
  594. void processCmdLine(const std::string& cmdline) const {
  595. CommandOptionsHelper::process(cmdline);
  596. }
  597. private:
  598. /// \brief Create DHCPv4 OFFER packet.
  599. ///
  600. /// \param transid transaction id.
  601. /// \return instance of the packet.
  602. boost::shared_ptr<Pkt4>
  603. createOfferPkt4(uint32_t transid) const {
  604. boost::shared_ptr<Pkt4> offer(new Pkt4(DHCPOFFER, transid));
  605. OptionPtr opt_serverid = Option::factory(Option::V4,
  606. DHO_DHCP_SERVER_IDENTIFIER,
  607. OptionBuffer(4, 1));
  608. offer->setYiaddr(asiolink::IOAddress("127.0.0.1"));
  609. offer->addOption(opt_serverid);
  610. offer->updateTimestamp();
  611. return (offer);
  612. }
  613. /// \brief Create DHCPv6 ADVERTISE packet.
  614. ///
  615. /// \param transid transaction id.
  616. /// \return instance of the packet.
  617. boost::shared_ptr<Pkt6>
  618. createAdvertisePkt6(uint32_t transid) const {
  619. boost::shared_ptr<Pkt6> advertise(new Pkt6(DHCPV6_ADVERTISE, transid));
  620. // Add IA_NA if requested by the client.
  621. if (CommandOptions::instance().getLeaseType()
  622. .includes(CommandOptions::LeaseType::ADDRESS)) {
  623. OptionPtr opt_ia_na = Option::factory(Option::V6, D6O_IA_NA);
  624. advertise->addOption(opt_ia_na);
  625. }
  626. // Add IA_PD if requested by the client.
  627. if (CommandOptions::instance().getLeaseType()
  628. .includes(CommandOptions::LeaseType::PREFIX)) {
  629. OptionPtr opt_ia_pd = Option::factory(Option::V6, D6O_IA_PD);
  630. advertise->addOption(opt_ia_pd);
  631. }
  632. OptionPtr opt_serverid(new Option(Option::V6, D6O_SERVERID));
  633. NakedTestControl tc;
  634. uint8_t randomized = 0;
  635. std::vector<uint8_t> duid(tc.generateDuid(randomized));
  636. OptionPtr opt_clientid(Option::factory(Option::V6, D6O_CLIENTID, duid));
  637. advertise->addOption(opt_serverid);
  638. advertise->addOption(opt_clientid);
  639. advertise->updateTimestamp();
  640. return (advertise);
  641. }
  642. };
  643. TEST_F(TestControlTest, GenerateDuid) {
  644. // Simple command line that simulates one client only. Always the
  645. // same DUID will be generated.
  646. ASSERT_NO_THROW(processCmdLine("perfdhcp -l 127.0.0.1 all"));
  647. testDuid();
  648. // Simulate 50 clients. Different DUID will be generated.
  649. ASSERT_NO_THROW(processCmdLine("perfdhcp -l 127.0.0.1 -R 50 all"));
  650. testDuid();
  651. }
  652. TEST_F(TestControlTest, MisMatchVerionServer) {
  653. NakedTestControl tc;
  654. // make sure we catch -6 paired with v4 address
  655. ASSERT_NO_THROW(processCmdLine("perfdhcp -l 127.0.0.1 -6 192.168.1.1"));
  656. EXPECT_THROW(tc.openSocket(), isc::InvalidParameter);
  657. // make sure we catch -4 paired with v6 address
  658. ASSERT_NO_THROW(processCmdLine("perfdhcp -l 127.0.0.1 -4 ff02::1:2"));
  659. EXPECT_THROW(tc.openSocket(), isc::InvalidParameter);
  660. }
  661. TEST_F(TestControlTest, GenerateMacAddress) {
  662. // Simulate one client only. Always the same MAC address will be
  663. // generated.
  664. ASSERT_NO_THROW(processCmdLine("perfdhcp -l 127.0.0.1 all"));
  665. testMacAddress();
  666. // Simulate 50 clients. Different MAC addresses will be generated.
  667. ASSERT_NO_THROW(processCmdLine("perfdhcp -l 127.0.0.1 -R 50 all"));
  668. testMacAddress();
  669. }
  670. TEST_F(TestControlTest, Options4) {
  671. using namespace isc::dhcp;
  672. NakedTestControl tc;
  673. // By default the IP version mode is V4 so there is no need to
  674. // parse command line to override the IP version. Note that
  675. // registerOptionFactories is used for both V4 and V6.
  676. tc.registerOptionFactories();
  677. // Create option with buffer size equal to 1 and holding DHCPDISCOVER
  678. // message type.
  679. OptionPtr opt_msg_type(Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  680. OptionBuffer(1, DHCPDISCOVER)));
  681. // Validate the option type and universe.
  682. EXPECT_EQ(Option::V4, opt_msg_type->getUniverse());
  683. EXPECT_EQ(DHO_DHCP_MESSAGE_TYPE, opt_msg_type->getType());
  684. // Validate the message type from the option we have now created.
  685. uint8_t msg_type = 0;
  686. ASSERT_NO_THROW(msg_type = opt_msg_type->getUint8());
  687. EXPECT_EQ(DHCPDISCOVER, msg_type);
  688. // Create another option: DHCP_PARAMETER_REQUEST_LIST
  689. OptionPtr
  690. opt_requested_options(Option::factory(Option::V4,
  691. DHO_DHCP_PARAMETER_REQUEST_LIST));
  692. // Here is a list of options that we are requesting in the
  693. // server's response.
  694. const uint8_t requested_options[] = {
  695. DHO_SUBNET_MASK,
  696. DHO_BROADCAST_ADDRESS,
  697. DHO_TIME_OFFSET,
  698. DHO_ROUTERS,
  699. DHO_DOMAIN_NAME,
  700. DHO_DOMAIN_NAME_SERVERS,
  701. DHO_HOST_NAME
  702. };
  703. OptionBuffer
  704. requested_options_ref(requested_options,
  705. requested_options + sizeof(requested_options));
  706. // Get the option buffer. It should hold the combination of values
  707. // listed in requested_options array. However their order can be
  708. // different in general so we need to search each value separatelly.
  709. const OptionBuffer& requested_options_buf =
  710. opt_requested_options->getData();
  711. EXPECT_EQ(requested_options_ref.size(), requested_options_buf.size());
  712. size_t matched_num = matchRequestedOptions(requested_options_ref,
  713. requested_options_buf);
  714. // We want exactly the same requested options as listed in
  715. // requested_options array - nothing more or less.
  716. EXPECT_EQ(requested_options_ref.size(), matched_num);
  717. }
  718. TEST_F(TestControlTest, Options6) {
  719. using namespace isc::dhcp;
  720. // Lets override the IP version to test V6 options (-6 parameter)
  721. ASSERT_NO_THROW(processCmdLine("perfdhcp -l 127.0.0.1 -6 all"));
  722. NakedTestControl tc;
  723. tc.registerOptionFactories();
  724. // Validate the D6O_ELAPSED_TIME option.
  725. OptionPtr opt_elapsed_time(Option::factory(Option::V6, D6O_ELAPSED_TIME));
  726. // Validate the option type and universe.
  727. EXPECT_EQ(Option::V6, opt_elapsed_time->getUniverse());
  728. EXPECT_EQ(D6O_ELAPSED_TIME, opt_elapsed_time->getType());
  729. // The default value of elapsed time is zero.
  730. uint16_t elapsed_time;
  731. ASSERT_NO_THROW(elapsed_time = opt_elapsed_time->getUint16());
  732. EXPECT_EQ(0, elapsed_time);
  733. // With the factory function we may also specify the actual
  734. // value of elapsed time. Let's make use of std::vector
  735. // constructor to create the option buffer, 2 octets long
  736. // with each octet initialized to 0x1.
  737. size_t elapsed_time_buf_size = 2;
  738. uint8_t elapsed_time_pattern = 0x1;
  739. OptionPtr
  740. opt_elapsed_time2(Option::factory(Option::V6, D6O_ELAPSED_TIME,
  741. OptionBuffer(elapsed_time_buf_size,
  742. elapsed_time_pattern)));
  743. // Any buffer that has size neither equal to 0 nor 2 is considered invalid.
  744. elapsed_time_buf_size = 1;
  745. EXPECT_THROW(
  746. Option::factory(Option::V6, D6O_ELAPSED_TIME,
  747. OptionBuffer(elapsed_time_buf_size, elapsed_time_pattern)),
  748. isc::BadValue
  749. );
  750. // Validate the option type and universe.
  751. EXPECT_EQ(Option::V6, opt_elapsed_time2->getUniverse());
  752. EXPECT_EQ(D6O_ELAPSED_TIME, opt_elapsed_time2->getType());
  753. // Make sure the getUint16 does not throw exception. It wile throw
  754. // buffer is shorter than 2 octets.
  755. ASSERT_NO_THROW(elapsed_time = opt_elapsed_time2->getUint16());
  756. // Check the expected value of elapsed time.
  757. EXPECT_EQ(0x0101, elapsed_time);
  758. // Validate the D6O_RAPID_COMMIT option.
  759. OptionPtr opt_rapid_commit(Option::factory(Option::V6, D6O_RAPID_COMMIT));
  760. // Validate the option type and universe.
  761. EXPECT_EQ(Option::V6, opt_rapid_commit->getUniverse());
  762. EXPECT_EQ(D6O_RAPID_COMMIT, opt_rapid_commit->getType());
  763. // Rapid commit has no data payload.
  764. EXPECT_THROW(opt_rapid_commit->getUint8(), isc::OutOfRange);
  765. // Validate the D6O_CLIENTID option.
  766. OptionBuffer duid(CommandOptions::instance().getDuidTemplate());
  767. OptionPtr opt_clientid(Option::factory(Option::V6, D6O_CLIENTID, duid));
  768. EXPECT_EQ(Option::V6, opt_clientid->getUniverse());
  769. EXPECT_EQ(D6O_CLIENTID, opt_clientid->getType());
  770. const OptionBuffer& duid2 = opt_clientid->getData();
  771. ASSERT_EQ(duid.size(), duid2.size());
  772. // The Duid we set for option is the same we get.
  773. EXPECT_TRUE(std::equal(duid.begin(), duid.end(), duid2.begin()));
  774. // Validate the D6O_ORO (Option Request Option).
  775. OptionPtr opt_oro(Option::factory(Option::V6, D6O_ORO));
  776. // Prepare the reference buffer with requested options.
  777. const uint8_t requested_options[] = {
  778. 0, D6O_NAME_SERVERS,
  779. 0, D6O_DOMAIN_SEARCH
  780. };
  781. // Each option code in ORO is 2 bytes long. We calculate the number of
  782. // requested options by dividing the size of the buffer holding options
  783. // by the size of each individual option.
  784. int requested_options_num = sizeof(requested_options) / sizeof(uint16_t);
  785. OptionBuffer
  786. requested_options_ref(requested_options,
  787. requested_options + sizeof(requested_options));
  788. // Get the buffer from option.
  789. const OptionBuffer& requested_options_buf = opt_oro->getData();
  790. // Size of reference buffer and option buffer have to be
  791. // the same for comparison.
  792. EXPECT_EQ(requested_options_ref.size(), requested_options_buf.size());
  793. // Check if all options in the buffer are matched with reference buffer.
  794. size_t matched_num = matchRequestedOptions6(requested_options_ref,
  795. requested_options_buf);
  796. EXPECT_EQ(requested_options_num, matched_num);
  797. // Validate the D6O_IA_NA option.
  798. OptionPtr opt_ia_na(Option::factory(Option::V6, D6O_IA_NA));
  799. EXPECT_EQ(Option::V6, opt_ia_na->getUniverse());
  800. EXPECT_EQ(D6O_IA_NA, opt_ia_na->getType());
  801. // Every IA_NA option is expected to start with this sequence.
  802. const uint8_t opt_ia_na_array[] = {
  803. 0, 0, 0, 1, // IAID = 1
  804. 0, 0, 3600 >> 8, 3600 & 0xff, // T1 = 3600
  805. 0, 0, 5400 >> 8, 5400 & 0xff, // T2 = 5400
  806. };
  807. OptionBuffer opt_ia_na_ref(opt_ia_na_array,
  808. opt_ia_na_array + sizeof(opt_ia_na_array));
  809. const OptionBuffer& opt_ia_na_buf = opt_ia_na->getData();
  810. ASSERT_EQ(opt_ia_na_buf.size(), opt_ia_na_ref.size());
  811. EXPECT_TRUE(std::equal(opt_ia_na_ref.begin(), opt_ia_na_ref.end(),
  812. opt_ia_na_buf.begin()));
  813. // @todo Add more tests for IA address options.
  814. }
  815. TEST_F(TestControlTest, Packet4) {
  816. // Use Interface Manager to get the local loopback interface.
  817. // If interface can't be found we don't want to fail test.
  818. std::string loopback_iface(getLocalLoopback());
  819. if (!loopback_iface.empty()) {
  820. ASSERT_NO_THROW(processCmdLine("perfdhcp -l " + loopback_iface +
  821. " -L 10547 all"));
  822. NakedTestControl tc;
  823. int sock_handle = 0;
  824. // We have to create the socket to setup some parameters of
  825. // outgoing packet.
  826. ASSERT_NO_THROW(sock_handle = tc.openSocket());
  827. TestControl::TestControlSocket sock(sock_handle);
  828. uint32_t transid = 123;
  829. boost::shared_ptr<Pkt4> pkt4(new Pkt4(DHCPDISCOVER, transid));
  830. // Set parameters on outgoing packet.
  831. ASSERT_NO_THROW(tc.setDefaults4(sock, pkt4));
  832. // Validate that packet has been setup correctly.
  833. EXPECT_EQ(loopback_iface, pkt4->getIface());
  834. EXPECT_EQ(sock.ifindex_, pkt4->getIndex());
  835. EXPECT_EQ(DHCP4_CLIENT_PORT, pkt4->getLocalPort());
  836. EXPECT_EQ(DHCP4_SERVER_PORT, pkt4->getRemotePort());
  837. EXPECT_EQ(1, pkt4->getHops());
  838. EXPECT_EQ(asiolink::IOAddress("255.255.255.255"),
  839. pkt4->getRemoteAddr());
  840. EXPECT_EQ(asiolink::IOAddress(sock.addr_), pkt4->getLocalAddr());
  841. EXPECT_EQ(asiolink::IOAddress(sock.addr_), pkt4->getGiaddr());
  842. } else {
  843. std::cout << "Unable to find the loopback interface. Skip test. "
  844. << std::endl;
  845. }
  846. }
  847. TEST_F(TestControlTest, Packet6) {
  848. // Use Interface Manager to get the local loopback interface.
  849. // If the interface can't be found we don't want to fail test.
  850. std::string loopback_iface(getLocalLoopback());
  851. if (!loopback_iface.empty()) {
  852. ASSERT_NO_THROW(processCmdLine("perfdhcp -6 -l " + loopback_iface +
  853. " -L 10547 servers"));
  854. NakedTestControl tc;
  855. int sock_handle = 0;
  856. // Create the socket. It will be needed to set packet's
  857. // parameters.
  858. ASSERT_NO_THROW(sock_handle = tc.openSocket());
  859. TestControl::TestControlSocket sock(sock_handle);
  860. uint32_t transid = 123;
  861. boost::shared_ptr<Pkt6> pkt6(new Pkt6(DHCPV6_SOLICIT, transid));
  862. // Set packet's parameters.
  863. ASSERT_NO_THROW(tc.setDefaults6(sock, pkt6));
  864. // Validate if parameters have been set correctly.
  865. EXPECT_EQ(loopback_iface, pkt6->getIface());
  866. EXPECT_EQ(sock.ifindex_, pkt6->getIndex());
  867. EXPECT_EQ(DHCP6_CLIENT_PORT, pkt6->getLocalPort());
  868. EXPECT_EQ(DHCP6_SERVER_PORT, pkt6->getRemotePort());
  869. EXPECT_EQ(sock.addr_, pkt6->getLocalAddr());
  870. EXPECT_EQ(asiolink::IOAddress("FF05::1:3"), pkt6->getRemoteAddr());
  871. } else {
  872. std::cout << "Unable to find the loopback interface. Skip test. "
  873. << std::endl;
  874. }
  875. }
  876. TEST_F(TestControlTest, Packet4Exchange) {
  877. // Get the local loopback interface to open socket on
  878. // it and test packets exchanges. We don't want to fail
  879. // the test if interface is not available.
  880. std::string loopback_iface(getLocalLoopback());
  881. if (loopback_iface.empty()) {
  882. std::cout << "Unable to find the loopback interface. Skip test."
  883. << std::endl;
  884. return;
  885. }
  886. // Set number of iterations to some high value.
  887. const int iterations_num = 100;
  888. processCmdLine("perfdhcp -l " + loopback_iface
  889. + " -r 100 -n 10 -R 20 -L 10547 127.0.0.1");
  890. // The actual number of iterations will be stored in the
  891. // following variable.
  892. int iterations_performed = 0;
  893. bool use_templates = false;
  894. testPkt4Exchange(iterations_num, iterations_num, use_templates, iterations_performed);
  895. // The command line restricts the number of iterations to 10
  896. // with -n 10 parameter.
  897. EXPECT_EQ(10, iterations_performed);
  898. // With the following command line we restrict the maximum
  899. // number of dropped packets to 20% of all.
  900. // Use templates for this test.
  901. processCmdLine("perfdhcp -l " + loopback_iface
  902. + " -r 100 -R 20 -n 20 -D 10% -L 10547"
  903. + " -T " + getFullPath("discover-example.hex")
  904. + " -T " + getFullPath("request4-example.hex")
  905. + " 127.0.0.1");
  906. // The number iterations is restricted by the percentage of
  907. // dropped packets (-D 10%). We also have to bump up the number
  908. // of iterations because the percentage limitation checks starts
  909. // at packet #10. We expect that at packet #12 the 10% threshold
  910. // will be reached.
  911. const int received_num = 10;
  912. use_templates = true;
  913. testPkt4Exchange(iterations_num, received_num, use_templates, iterations_performed);
  914. EXPECT_EQ(12, iterations_performed);
  915. }
  916. TEST_F(TestControlTest, Packet6Exchange) {
  917. // Get the local loopback interface to open socket on
  918. // it and test packets exchanges. We don't want to fail
  919. // the test if interface is not available.
  920. std::string loopback_iface(getLocalLoopback());
  921. if (loopback_iface.empty()) {
  922. std::cout << "Unable to find the loopback interface. Skip test."
  923. << std::endl;
  924. return;
  925. }
  926. const int iterations_num = 100;
  927. // Set number of iterations to 10.
  928. processCmdLine("perfdhcp -l " + loopback_iface
  929. + " -6 -r 100 -n 10 -R 20 -L 10547 ::1");
  930. int iterations_performed = 0;
  931. // Set number of received packets equal to number of iterations.
  932. // This simulates no packet drops.
  933. bool use_templates = false;
  934. testPkt6Exchange(iterations_num, iterations_num, use_templates,
  935. iterations_performed);
  936. // Actual number of iterations should be 10.
  937. EXPECT_EQ(10, iterations_performed);
  938. // The maximum number of dropped packets is 3 (because of -D 3).
  939. use_templates = true;
  940. processCmdLine("perfdhcp -l " + loopback_iface
  941. + " -6 -r 100 -n 10 -R 20 -D 3 -L 10547"
  942. + " -T " + getFullPath("solicit-example.hex")
  943. + " -T " + getFullPath("request6-example.hex ::1"));
  944. // For the first 3 packets we are simulating responses from server.
  945. // For other packets we don't so packet as 4,5,6 will be dropped and
  946. // then test should be interrupted and actual number of iterations will
  947. // be 6.
  948. const int received_num = 3;
  949. testPkt6Exchange(iterations_num, received_num, use_templates,
  950. iterations_performed);
  951. EXPECT_EQ(6, iterations_performed);
  952. }
  953. TEST_F(TestControlTest, Packet6ExchangePrefixDelegation) {
  954. // Get the local loopback interface to open socket on
  955. // it and test packets exchanges. We don't want to fail
  956. // the test if interface is not available.
  957. std::string loopback_iface(getLocalLoopback());
  958. if (loopback_iface.empty()) {
  959. std::cout << "Unable to find the loopback interface. Skip test."
  960. << std::endl;
  961. return;
  962. }
  963. const int iterations_num = 100;
  964. // Set number of iterations to 10.
  965. processCmdLine("perfdhcp -l " + loopback_iface
  966. + " -e prefix-only"
  967. + " -6 -r 100 -n 10 -R 20 -L 10547 ::1");
  968. int iterations_performed = 0;
  969. // Set number of received packets equal to number of iterations.
  970. // This simulates no packet drops.
  971. bool use_templates = false;
  972. testPkt6Exchange(iterations_num, iterations_num, use_templates,
  973. iterations_performed);
  974. // Actual number of iterations should be 10.
  975. EXPECT_EQ(10, iterations_performed);
  976. }
  977. TEST_F(TestControlTest, Packet6ExchangeAddressAndPrefix) {
  978. // Get the local loopback interface to open socket on
  979. // it and test packets exchanges. We don't want to fail
  980. // the test if interface is not available.
  981. std::string loopback_iface(getLocalLoopback());
  982. if (loopback_iface.empty()) {
  983. std::cout << "Unable to find the loopback interface. Skip test."
  984. << std::endl;
  985. return;
  986. }
  987. const int iterations_num = 100;
  988. // Set number of iterations to 10.
  989. processCmdLine("perfdhcp -l " + loopback_iface
  990. + " -e address-and-prefix"
  991. + " -6 -r 100 -n 10 -R 20 -L 10547 ::1");
  992. int iterations_performed = 0;
  993. // Set number of received packets equal to number of iterations.
  994. // This simulates no packet drops.
  995. bool use_templates = false;
  996. testPkt6Exchange(iterations_num, iterations_num, use_templates,
  997. iterations_performed);
  998. // Actual number of iterations should be 10.
  999. EXPECT_EQ(10, iterations_performed);
  1000. }
  1001. TEST_F(TestControlTest, PacketTemplates) {
  1002. std::vector<uint8_t> template1(256);
  1003. std::string file1("test1.hex");
  1004. std::vector<uint8_t> template2(233);
  1005. std::string file2("test2.hex");
  1006. for (int i = 0; i < template1.size(); ++i) {
  1007. template1[i] = static_cast<uint8_t>(random() % 256);
  1008. }
  1009. for (int i = 0; i < template2.size(); ++i) {
  1010. template2[i] = static_cast<uint8_t>(random() % 256);
  1011. }
  1012. // Size of the file is 2 times larger than binary data size.
  1013. ASSERT_TRUE(createTemplateFile(file1, template1, template1.size() * 2));
  1014. ASSERT_TRUE(createTemplateFile(file2, template2, template2.size() * 2));
  1015. CommandOptions& options = CommandOptions::instance();
  1016. NakedTestControl tc;
  1017. ASSERT_NO_THROW(
  1018. processCmdLine("perfdhcp -l 127.0.0.1"
  1019. " -T " + file1 + " -T " + file2 + " all")
  1020. );
  1021. ASSERT_NO_THROW(tc.initPacketTemplates());
  1022. TestControl::TemplateBuffer buf1;
  1023. TestControl::TemplateBuffer buf2;
  1024. ASSERT_NO_THROW(buf1 = tc.getTemplateBuffer(0));
  1025. ASSERT_NO_THROW(buf2 = tc.getTemplateBuffer(1));
  1026. ASSERT_EQ(template1.size(), buf1.size());
  1027. ASSERT_EQ(template2.size(), buf2.size());
  1028. EXPECT_TRUE(std::equal(template1.begin(), template1.end(), buf1.begin()));
  1029. EXPECT_TRUE(std::equal(template2.begin(), template2.end(), buf2.begin()));
  1030. // Try to read template file with odd number of digits.
  1031. std::string file3("test3.hex");
  1032. // Size of the file is 2 times larger than binary data size and it is always
  1033. // even number. Substracting 1 makes file size odd.
  1034. ASSERT_TRUE(createTemplateFile(file3, template1, template1.size() * 2 - 1));
  1035. ASSERT_NO_THROW(
  1036. processCmdLine("perfdhcp -l 127.0.0.1 -T " + file3 + " all")
  1037. );
  1038. EXPECT_THROW(tc.initPacketTemplates(), isc::OutOfRange);
  1039. // Try to read empty file.
  1040. std::string file4("test4.hex");
  1041. ASSERT_TRUE(createTemplateFile(file4, template2, 0));
  1042. ASSERT_NO_THROW(
  1043. processCmdLine("perfdhcp -l 127.0.0.1 -T " + file4 + " all")
  1044. );
  1045. EXPECT_THROW(tc.initPacketTemplates(), isc::OutOfRange);
  1046. // Try reading file with non hexadecimal characters.
  1047. std::string file5("test5.hex");
  1048. ASSERT_TRUE(createTemplateFile(file5, template1, template1.size() * 2, true));
  1049. ASSERT_NO_THROW(
  1050. processCmdLine("perfdhcp -l 127.0.0.1 -T " + file5 + " all")
  1051. );
  1052. EXPECT_THROW(tc.initPacketTemplates(), isc::BadValue);
  1053. }
  1054. TEST_F(TestControlTest, RateControl) {
  1055. // We don't specify the exchange rate here so the aggressivity
  1056. // value will determine how many packets are to be send each
  1057. // time we query the getNextExchangesNum.
  1058. ASSERT_NO_THROW(processCmdLine("perfdhcp -l 127.0.0.1 all"));
  1059. CommandOptions& options = CommandOptions::instance();
  1060. NakedTestControl tc1;
  1061. uint64_t xchgs_num = tc1.getNextExchangesNum();
  1062. EXPECT_EQ(options.getAggressivity(), xchgs_num);
  1063. // The exchange rate is now 1 per second. We don't know how many
  1064. // exchanges have to initiated exactly but for sure it has to be
  1065. // non-zero value. Also, since aggressivity is very high we expect
  1066. // that it will not be restricted by aggressivity.
  1067. ASSERT_NO_THROW(
  1068. processCmdLine("perfdhcp -l 127.0.0.1 -a 1000000 -r 1 all")
  1069. );
  1070. NakedTestControl tc2;
  1071. xchgs_num = tc2.getNextExchangesNum();
  1072. EXPECT_GT(xchgs_num, 0);
  1073. EXPECT_LT(xchgs_num, options.getAggressivity());
  1074. // @todo add more thorough checks for rate values.
  1075. }