test_control.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. // Copyright (C) 2012 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 <stdio.h>
  15. #include <stdlib.h>
  16. #include <stdint.h>
  17. #include <unistd.h>
  18. #include <boost/date_time/posix_time/posix_time.hpp>
  19. #include <exceptions/exceptions.h>
  20. #include <asiolink/io_address.h>
  21. #include <dhcp/libdhcp++.h>
  22. #include <dhcp/iface_mgr.h>
  23. #include <dhcp/dhcp4.h>
  24. #include "test_control.h"
  25. #include "command_options.h"
  26. using namespace std;
  27. using namespace boost;
  28. using namespace boost::posix_time;
  29. using namespace isc;
  30. using namespace isc::dhcp;
  31. using namespace isc::asiolink;
  32. namespace isc {
  33. namespace perfdhcp {
  34. TestControl::TestControlSocket::TestControlSocket(int socket) :
  35. socket_(socket),
  36. addr_("127.0.0.1") {
  37. initSocketData();
  38. }
  39. TestControl::TestControlSocket::~TestControlSocket() {
  40. IfaceMgr::instance().closeSockets();
  41. }
  42. void
  43. TestControl::TestControlSocket::initSocketData() {
  44. const IfaceMgr::IfaceCollection& ifaces =
  45. IfaceMgr::instance().getIfaces();
  46. for (IfaceMgr::IfaceCollection::const_iterator it = ifaces.begin();
  47. it != ifaces.end();
  48. ++it) {
  49. const IfaceMgr::SocketCollection& socket_collection =
  50. it->getSockets();
  51. for (IfaceMgr::SocketCollection::const_iterator s =
  52. socket_collection.begin();
  53. s != socket_collection.end();
  54. ++s) {
  55. if (s->sockfd_ == socket_) {
  56. iface_ = it->getName();
  57. ifindex_ = it->getIndex();
  58. addr_ = s->addr_;
  59. return;
  60. }
  61. }
  62. }
  63. isc_throw(BadValue, "interface for for specified socket "
  64. "descriptor not found");
  65. }
  66. TestControl&
  67. TestControl::instance() {
  68. static TestControl test_control;
  69. return (test_control);
  70. }
  71. TestControl::TestControl() :
  72. send_due_(microsec_clock::universal_time()),
  73. last_sent_(send_due_) {
  74. }
  75. bool
  76. TestControl::checkExitConditions() const {
  77. CommandOptions& options = CommandOptions::instance();
  78. if ((options.getNumRequests().size() > 0) &&
  79. (sent_packets_0_ >= options.getNumRequests()[0])) {
  80. return(true);
  81. } else if ((options.getNumRequests().size() == 2) &&
  82. (sent_packets_1_ >= options.getNumRequests()[1])) {
  83. return(true);
  84. }
  85. return(false);
  86. }
  87. OptionPtr
  88. TestControl::factoryElapsedTimeSolicit6(Option::Universe, uint16_t,
  89. const OptionBuffer&) {
  90. return OptionPtr(new Option(Option::V6, D6O_ELAPSED_TIME,
  91. OptionBuffer(2, 0)));
  92. }
  93. OptionPtr
  94. TestControl::factoryGeneric(Option::Universe u, uint16_t type,
  95. const OptionBuffer& buf) {
  96. OptionPtr opt(new Option(u, type, buf));
  97. return opt;
  98. }
  99. OptionPtr
  100. TestControl::factoryIana6(Option::Universe, uint16_t,
  101. const OptionBuffer&) {
  102. const uint8_t buf_array[] = {
  103. 0, 0, 0, 1, // IAID = 1
  104. 0, 0, 3600 >> 8, 3600 && 0xff, // T1 = 3600
  105. 0, 0, 5400 >> 8, 5400 & 0xff, // T2 = 5400
  106. };
  107. OptionBuffer buf(buf_array, buf_array + sizeof(buf_array));
  108. return OptionPtr(new Option(Option::V6, D6O_IA_NA, buf));
  109. }
  110. OptionPtr
  111. TestControl::factoryRapidCommit6(Option::Universe, uint16_t,
  112. const OptionBuffer&) {
  113. return OptionPtr(new Option(Option::V6, D6O_RAPID_COMMIT, OptionBuffer()));
  114. }
  115. OptionPtr
  116. TestControl::factoryOptionRequestOption6(Option::Universe,
  117. uint16_t,
  118. const OptionBuffer&) {
  119. const uint8_t buf_array[] = {
  120. D6O_NAME_SERVERS,
  121. D6O_DOMAIN_SEARCH
  122. };
  123. OptionBuffer buf_with_options(buf_array, buf_array + sizeof(buf_array));
  124. return OptionPtr(new Option(Option::V6, D6O_ORO, buf_with_options));
  125. }
  126. OptionPtr
  127. TestControl::factoryRequestList4(Option::Universe u,
  128. uint16_t type,
  129. const OptionBuffer& buf) {
  130. const uint8_t buf_array[] = {
  131. DHO_SUBNET_MASK,
  132. DHO_BROADCAST_ADDRESS,
  133. DHO_TIME_OFFSET,
  134. DHO_ROUTERS,
  135. DHO_DOMAIN_NAME,
  136. DHO_DOMAIN_NAME_SERVERS,
  137. DHO_HOST_NAME
  138. };
  139. OptionBuffer buf_with_options(buf_array, buf_array + sizeof(buf_array));
  140. OptionPtr opt(new Option(u, type, buf));
  141. opt->setData(buf_with_options.begin(), buf_with_options.end());
  142. return opt;
  143. }
  144. std::vector<uint8_t>
  145. TestControl::generateMacAddress() const {
  146. CommandOptions& options = CommandOptions::instance();
  147. uint32_t clients_num = options.getClientsNum();
  148. if ((clients_num == 0) || (clients_num == 1)) {
  149. return options.getMacPrefix();
  150. }
  151. // Get the base MAC address. We are going to randomize part of it.
  152. std::vector<uint8_t> mac_addr(options.getMacPrefix());
  153. if (mac_addr.size() != HW_ETHER_LEN) {
  154. isc_throw(BadValue, "invalid MAC address prefix specified");
  155. }
  156. uint32_t r = random();
  157. // The random number must be in the range 0..clients_num. This
  158. // will guarantee that every client has exactly one random MAC
  159. // address assigned.
  160. r %= clients_num;
  161. // Randomize MAC address octets.
  162. for (std::vector<uint8_t>::iterator it = mac_addr.end() - 1;
  163. it >= mac_addr.begin();
  164. --it) {
  165. // Add the random value to the current octet.
  166. (*it) += r;
  167. if (r < 256) {
  168. // If we are here it means that there is no sense
  169. // to randomize the remaining octets of MAC address
  170. // because the following bytes of random value
  171. // are zero and it will have no effect.
  172. break;
  173. }
  174. // Randomize the next octet with the following
  175. // byte of random value.
  176. r >>= 8;
  177. }
  178. return mac_addr;
  179. }
  180. std::vector<uint8_t>
  181. TestControl::generateDuid() const {
  182. CommandOptions& options = CommandOptions::instance();
  183. uint32_t clients_num = options.getClientsNum();
  184. if ((clients_num == 0) || (clients_num == 1)) {
  185. return options.getDuidPrefix();
  186. }
  187. // Get the base MAC address. We are going to randomize part of it.
  188. std::vector<uint8_t> duid(options.getDuidPrefix());
  189. return duid;
  190. }
  191. uint64_t
  192. TestControl::getNextExchangesNum() const {
  193. CommandOptions& options = CommandOptions::instance();
  194. // Reset number of exchanges.
  195. uint64_t due_exchanges = 0;
  196. // Get current time.
  197. ptime now(microsec_clock::universal_time());
  198. // The due time indicates when we should start sending next chunk
  199. // of packets. If it is already due time, we should calculate
  200. // how many packets to send.
  201. if (now >= send_due_) {
  202. // If rate is specified from the command line we have to
  203. // synchornize with it.
  204. if (options.getRate() != 0) {
  205. time_period period(send_due_, now);
  206. // Null condition should not occur because we
  207. // have checked it in the first if statement but
  208. // let's keep this check just in case.
  209. if (period.is_null()) {
  210. return (0);
  211. }
  212. time_duration duration = period.length();
  213. // due_factor indicates the number of seconds that
  214. // sending next chunk of packets will take.
  215. double due_factor = duration.fractional_seconds() /
  216. time_duration::ticks_per_second();
  217. due_factor += duration.total_seconds();
  218. // Multiplying due_factor by expected rate gives the number
  219. // of exchanges to be initiated.
  220. due_exchanges = static_cast<uint64_t>(due_factor * options.getRate());
  221. // We want to make sure that at least one packet goes out.
  222. due_exchanges += 1;
  223. // We should not exceed aggressivity as it could have been
  224. // restricted from command line.
  225. if (due_exchanges > options.getAggressivity()) {
  226. due_exchanges = options.getAggressivity();
  227. }
  228. } else {
  229. // Rate is not specified so we rely on aggressivity
  230. // which is the number of packets to be sent in
  231. // one chunk.
  232. due_exchanges = options.getAggressivity();
  233. }
  234. return (due_exchanges);
  235. }
  236. return (0);
  237. }
  238. int
  239. TestControl::openSocket() const {
  240. CommandOptions& options = CommandOptions::instance();
  241. std::string localname = options.getLocalName();
  242. std::string servername = options.getServerName();
  243. uint8_t family = AF_INET;
  244. uint16_t port = 67;
  245. int sock = 0;
  246. IOAddress remoteaddr(servername);
  247. if (options.getIpVersion() == 6) {
  248. family = AF_INET6;
  249. port = 547;
  250. }
  251. // Local name is specified along with '-l' option.
  252. // It may point to interface name or local address.
  253. if (!localname.empty()) {
  254. // CommandOptions should be already aware wether local name
  255. // is interface name or address because it uses IfaceMgr to
  256. // scan interfaces and get's their names.
  257. if (options.isInterface()) {
  258. sock = IfaceMgr::instance().openSocketFromIface(localname,
  259. port,
  260. family);
  261. } else {
  262. IOAddress localaddr(localname);
  263. sock = IfaceMgr::instance().openSocketFromAddress(localaddr,
  264. port);
  265. }
  266. } else if (!servername.empty()) {
  267. // If only server name is given we will need to try to resolve
  268. // the local address to bind socket to based on remote address.
  269. sock = IfaceMgr::instance().openSocketFromRemoteAddress(remoteaddr,
  270. port);
  271. }
  272. if (sock <= 0) {
  273. isc_throw(BadValue, "unable to open socket to communicate with "
  274. "DHCP server");
  275. }
  276. // IfaceMgr does not set broadcast option on the socket. We rely
  277. // on CommandOptions object to find out if socket has to have
  278. // broadcast enabled.
  279. if ((options.getIpVersion() == 4) && options.isBroadcast()) {
  280. int broadcast_enable = 1;
  281. int ret = setsockopt(sock, SOL_SOCKET, SO_BROADCAST,
  282. &broadcast_enable, sizeof(broadcast_enable));
  283. if (ret < 0) {
  284. isc_throw(InvalidOperation,
  285. "unable to set broadcast option on the socket");
  286. }
  287. } else if (options.getIpVersion() == 6) {
  288. // If remote address is multicast we need to enable it on
  289. // the socket that has been created.
  290. asio::ip::address_v6 remote_v6 = remoteaddr.getAddress().to_v6();
  291. if (remote_v6.is_multicast()) {
  292. int hops = 1;
  293. int ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
  294. &hops, sizeof(hops));
  295. // If user specified interface name with '-l' the
  296. // IPV6_MULTICAST_IF has to be set.
  297. if ((ret >= 0) && options.isInterface()) {
  298. IfaceMgr::Iface* iface =
  299. IfaceMgr::instance().getIface(options.getLocalName());
  300. if (iface == NULL) {
  301. isc_throw(Unexpected, "unknown interface "
  302. << options.getLocalName());
  303. }
  304. int idx = iface->getIndex();
  305. ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
  306. &idx, sizeof(idx));
  307. }
  308. if (ret < 0) {
  309. isc_throw(InvalidOperation,
  310. "unable to enable multicast on socket " << sock
  311. << ". errno = " << errno);
  312. }
  313. }
  314. }
  315. return(sock);
  316. }
  317. void
  318. TestControl::receivePackets() {
  319. int timeout = 0;
  320. bool receiving = true;
  321. while (receiving) {
  322. if (CommandOptions::instance().getIpVersion() == 4) {
  323. Pkt4Ptr pkt4 = IfaceMgr::instance().receive4(timeout);
  324. if (!pkt4) {
  325. receiving = false;
  326. } else {
  327. // TODO: replace this with use of StatsMgr to increase
  328. // number of received packets. This can be done once
  329. // the 1958 ticket is reviewed and checked-in.
  330. std::cout << "Received packet" << std::endl;
  331. }
  332. } else if (CommandOptions::instance().getIpVersion() == 6) {
  333. Pkt6Ptr pkt6 = IfaceMgr::instance().receive6();
  334. if (!pkt6) {
  335. receiving = false;
  336. } else {
  337. std::cout << "Received DHCPv6 packet" << std::endl;
  338. }
  339. }
  340. }
  341. }
  342. void
  343. TestControl::registerOptionFactories4() const {
  344. static bool factories_registered = false;
  345. if (!factories_registered) {
  346. // DHCP_MESSAGE_TYPE option factory.
  347. LibDHCP::OptionFactoryRegister(Option::V4,
  348. DHO_DHCP_MESSAGE_TYPE,
  349. &TestControl::factoryGeneric);
  350. // DHCP_PARAMETER_REQUEST_LIST option factory.
  351. LibDHCP::OptionFactoryRegister(Option::V4,
  352. DHO_DHCP_PARAMETER_REQUEST_LIST,
  353. &TestControl::factoryRequestList4);
  354. }
  355. factories_registered = true;
  356. }
  357. void
  358. TestControl::registerOptionFactories6() const {
  359. static bool factories_registered = false;
  360. if (!factories_registered) {
  361. LibDHCP::OptionFactoryRegister(Option::V6,
  362. D6O_ELAPSED_TIME,
  363. &TestControl::factoryElapsedTimeSolicit6);
  364. LibDHCP::OptionFactoryRegister(Option::V6,
  365. D6O_RAPID_COMMIT,
  366. &TestControl::factoryRapidCommit6);
  367. LibDHCP::OptionFactoryRegister(Option::V6,
  368. D6O_ORO,
  369. &TestControl::factoryOptionRequestOption6);
  370. LibDHCP::OptionFactoryRegister(Option::V6,
  371. D6O_CLIENTID,
  372. &TestControl::factoryGeneric);
  373. LibDHCP::OptionFactoryRegister(Option::V6,
  374. D6O_IA_NA,
  375. &TestControl::factoryIana6);
  376. }
  377. factories_registered = true;
  378. }
  379. void
  380. TestControl::registerOptionFactories() const {
  381. CommandOptions& options = CommandOptions::instance();
  382. switch(options.getIpVersion()) {
  383. case 4:
  384. registerOptionFactories4();
  385. break;
  386. case 6:
  387. registerOptionFactories6();
  388. break;
  389. default:
  390. isc_throw(InvalidOperation, "command line options have to be parsed "
  391. "before DHCP option factories can be registered");
  392. }
  393. }
  394. void
  395. TestControl::run() {
  396. sent_packets_0_ = 0;
  397. sent_packets_1_ = 0;
  398. CommandOptions& options = CommandOptions::instance();
  399. // Ip version is not set ONLY in case the command options
  400. // were not parsed. This surely means that parse() function
  401. // was not called prior to starting the test. This is fatal
  402. // error.
  403. if (options.getIpVersion() == 0) {
  404. isc_throw(InvalidOperation,
  405. "command options must be parsed before running a test");
  406. }
  407. registerOptionFactories();
  408. TestControlSocket socket(openSocket());
  409. uint64_t packets_sent = 0;
  410. for (;;) {
  411. updateSendDue();
  412. if (checkExitConditions()) {
  413. break;
  414. }
  415. uint64_t packets_due = getNextExchangesNum();
  416. receivePackets();
  417. for (uint64_t i = packets_due; i > 0; --i) {
  418. if (options.getIpVersion() == 4) {
  419. sendDiscover4(socket);
  420. } else {
  421. sendSolicit6(socket);
  422. }
  423. ++packets_sent;
  424. cout << "Packets sent " << packets_sent << endl;
  425. }
  426. }
  427. }
  428. void
  429. TestControl::sendDiscover4(const TestControlSocket& socket) {
  430. ++sent_packets_0_;
  431. last_sent_ = microsec_clock::universal_time();
  432. // Generate the MAC address to be passed in the packet.
  433. std::vector<uint8_t> mac_address = generateMacAddress();
  434. // Generate trasnaction id to be set for the new exchange.
  435. const uint32_t transid = static_cast<uint32_t>(random());
  436. boost::shared_ptr<Pkt4> pkt4(new Pkt4(DHCPDISCOVER, transid));
  437. if (!pkt4) {
  438. isc_throw(Unexpected, "failed to create DISCOVER packet");
  439. }
  440. // Set options: DHCP_MESSAGE_TYPE and DHCP_PARAMETER_REQUEST_LIST
  441. OptionBuffer buf_msg_type;
  442. buf_msg_type.push_back(DHCPDISCOVER);
  443. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  444. buf_msg_type));
  445. pkt4->addOption(Option::factory(Option::V4,
  446. DHO_DHCP_PARAMETER_REQUEST_LIST));
  447. // Set client's and server's ports as well as server's address,
  448. // and local (relay) address.
  449. setDefaults4(socket, pkt4);
  450. pkt4->pack();
  451. IfaceMgr::instance().send(pkt4);
  452. }
  453. void
  454. TestControl::sendSolicit6(const TestControlSocket& socket) {
  455. ++sent_packets_0_;
  456. last_sent_ = microsec_clock::universal_time();
  457. // Generate the MAC address to be passed in the packet.
  458. std::vector<uint8_t> mac_address = generateMacAddress();
  459. // Generate DUID to be passed to the packet
  460. std::vector<uint8_t> duid = generateDuid();
  461. // Generate trasnaction id to be set for the new exchange.
  462. const uint32_t transid = static_cast<uint32_t>(random());
  463. boost::shared_ptr<Pkt6> pkt6(new Pkt6(DHCPV6_SOLICIT, transid));
  464. if (!pkt6) {
  465. isc_throw(Unexpected, "failed to create SOLICIT packet");
  466. }
  467. pkt6->addOption(Option::factory(Option::V6, D6O_ELAPSED_TIME));
  468. pkt6->addOption(Option::factory(Option::V6, D6O_RAPID_COMMIT));
  469. pkt6->addOption(Option::factory(Option::V6, D6O_CLIENTID, duid));
  470. pkt6->addOption(Option::factory(Option::V6, D6O_ORO));
  471. pkt6->addOption(Option::factory(Option::V6, D6O_IA_NA));
  472. setDefaults6(socket, pkt6);
  473. pkt6->pack();
  474. IfaceMgr::instance().send(pkt6);
  475. }
  476. void
  477. TestControl::setDefaults4(const TestControlSocket& socket,
  478. const boost::shared_ptr<Pkt4>& pkt) {
  479. CommandOptions& options = CommandOptions::instance();
  480. // Interface name.
  481. pkt->setIface(socket.getIface());
  482. // Interface index.
  483. pkt->setIndex(socket.getIfIndex());
  484. // Local client's port (68)
  485. pkt->setLocalPort(DHCP4_CLIENT_PORT);
  486. // Server's port (67)
  487. pkt->setRemotePort(DHCP4_SERVER_PORT);
  488. // The remote server's name or IP.
  489. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  490. // Set relay (GIADDR) address to local address.
  491. pkt->setGiaddr(IOAddress(socket.getAddress()));
  492. // Pretend that we have one relay (which is us).
  493. pkt->setHops(1);
  494. }
  495. void
  496. TestControl::setDefaults6(const TestControlSocket& socket,
  497. const boost::shared_ptr<Pkt6>& pkt) {
  498. CommandOptions& options = CommandOptions::instance();
  499. // Interface name.
  500. pkt->setIface(socket.getIface());
  501. // Interface index.
  502. pkt->setIndex(socket.getIfIndex());
  503. // Local client's port (547)
  504. pkt->setLocalPort(DHCP6_CLIENT_PORT);
  505. // Server's port (548)
  506. pkt->setRemotePort(DHCP6_SERVER_PORT);
  507. // The remote server's name or IP.
  508. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  509. }
  510. void
  511. TestControl::updateSendDue() {
  512. // If default constructor was called, this should not happen but
  513. // if somebody has changed default constructor it is better to
  514. // keep this check.
  515. if (last_sent_.is_not_a_date_time()) {
  516. isc_throw(Unexpected, "time of last sent packet not initialized");
  517. }
  518. // Get the expected exchange rate.
  519. CommandOptions& options = CommandOptions::instance();
  520. int rate = options.getRate();
  521. // If rate was not specified we will wait just one clock tick to
  522. // send next packet. This simulates best effort conditions.
  523. long duration = 1;
  524. if (rate != 0) {
  525. // We use number of ticks instead of nanoseconds because
  526. // nanosecond resolution may not be available on some
  527. // machines. Number of ticks guarantees the highest possible
  528. // timer resolution.
  529. duration = time_duration::ticks_per_second() / rate;
  530. }
  531. // Calculate due time to initate next chunk of exchanges.
  532. send_due_ = last_sent_ + time_duration(0, 0, 0, duration);
  533. }
  534. } // namespace perfdhcp
  535. } // namespace isc