test_control.cc 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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 <fstream>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <stdint.h>
  18. #include <unistd.h>
  19. #include <signal.h>
  20. #include <boost/date_time/posix_time/posix_time.hpp>
  21. #include <exceptions/exceptions.h>
  22. #include <asiolink/io_address.h>
  23. #include <dhcp/libdhcp++.h>
  24. #include <dhcp/iface_mgr.h>
  25. #include <dhcp/dhcp4.h>
  26. #include <dhcp/option6_ia.h>
  27. #include "test_control.h"
  28. #include "command_options.h"
  29. #include "perf_pkt4.h"
  30. #include "perf_pkt6.h"
  31. using namespace std;
  32. using namespace boost;
  33. using namespace boost::posix_time;
  34. using namespace isc;
  35. using namespace isc::dhcp;
  36. using namespace isc::asiolink;
  37. namespace isc {
  38. namespace perfdhcp {
  39. bool TestControl::interrupted_ = false;
  40. TestControl::TestControlSocket::TestControlSocket(const int socket) :
  41. SocketInfo(socket, asiolink::IOAddress("127.0.0.1"), 0),
  42. ifindex_(0), valid_(true) {
  43. try {
  44. initSocketData();
  45. } catch (const Exception&) {
  46. valid_ = false;
  47. }
  48. }
  49. TestControl::TestControlSocket::~TestControlSocket() {
  50. IfaceMgr::Iface* iface = IfaceMgr::instance().getIface(ifindex_);
  51. if (iface) {
  52. iface->delSocket(sockfd_);
  53. }
  54. }
  55. void
  56. TestControl::TestControlSocket::initSocketData() {
  57. const IfaceMgr::IfaceCollection& ifaces =
  58. IfaceMgr::instance().getIfaces();
  59. for (IfaceMgr::IfaceCollection::const_iterator it = ifaces.begin();
  60. it != ifaces.end();
  61. ++it) {
  62. const IfaceMgr::SocketCollection& socket_collection =
  63. it->getSockets();
  64. for (IfaceMgr::SocketCollection::const_iterator s =
  65. socket_collection.begin();
  66. s != socket_collection.end();
  67. ++s) {
  68. if (s->sockfd_ == sockfd_) {
  69. ifindex_ = it->getIndex();
  70. addr_ = s->addr_;
  71. return;
  72. }
  73. }
  74. }
  75. isc_throw(BadValue, "interface for for specified socket "
  76. "descriptor not found");
  77. }
  78. TestControl&
  79. TestControl::instance() {
  80. static TestControl test_control;
  81. return (test_control);
  82. }
  83. TestControl::TestControl() {
  84. reset();
  85. }
  86. std::string
  87. TestControl::byte2Hex(const uint8_t b) const {
  88. const int b1 = b / 16;
  89. const int b0 = b % 16;
  90. ostringstream stream;
  91. stream << std::hex << b1 << b0 << std::dec;
  92. return (stream.str());
  93. }
  94. bool
  95. TestControl::checkExitConditions() const {
  96. if (interrupted_) {
  97. return (true);
  98. }
  99. CommandOptions& options = CommandOptions::instance();
  100. bool test_period_reached = false;
  101. // Check if test period passed.
  102. if (options.getPeriod() != 0) {
  103. if (options.getIpVersion() == 4) {
  104. time_period period(stats_mgr4_->getTestPeriod());
  105. if (period.length().total_seconds() >= options.getPeriod()) {
  106. test_period_reached = true;
  107. }
  108. } else if (options.getIpVersion() == 6) {
  109. time_period period = stats_mgr6_->getTestPeriod();
  110. if (period.length().total_seconds() >= options.getPeriod()) {
  111. test_period_reached = true;
  112. }
  113. }
  114. }
  115. if (test_period_reached) {
  116. if (testDiags('e')) {
  117. std::cout << "reached test-period." << std::endl;
  118. }
  119. return (true);
  120. }
  121. bool max_requests = false;
  122. // Check if we reached maximum number of DISCOVER/SOLICIT sent.
  123. if (options.getNumRequests().size() > 0) {
  124. if (options.getIpVersion() == 4) {
  125. if (getSentPacketsNum(StatsMgr4::XCHG_DO) >=
  126. options.getNumRequests()[0]) {
  127. max_requests = true;
  128. }
  129. } else if (options.getIpVersion() == 6) {
  130. if (stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_SA) >=
  131. options.getNumRequests()[0]) {
  132. max_requests = true;
  133. }
  134. }
  135. }
  136. // Check if we reached maximum number REQUEST packets.
  137. if (options.getNumRequests().size() == 2) {
  138. if (options.getIpVersion() == 4) {
  139. if (stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_RA) >=
  140. options.getNumRequests()[1]) {
  141. max_requests = true;
  142. }
  143. } else if (options.getIpVersion() == 6) {
  144. if (stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_RR) >=
  145. options.getNumRequests()[1]) {
  146. max_requests = true;
  147. }
  148. }
  149. }
  150. if (max_requests) {
  151. if (testDiags('e')) {
  152. std::cout << "Reached max requests limit." << std::endl;
  153. }
  154. return (true);
  155. }
  156. // Check if we reached maximum number of drops of OFFER/ADVERTISE packets.
  157. bool max_drops = false;
  158. if (options.getMaxDrop().size() > 0) {
  159. if (options.getIpVersion() == 4) {
  160. if (stats_mgr4_->getDroppedPacketsNum(StatsMgr4::XCHG_DO) >=
  161. options.getMaxDrop()[0]) {
  162. max_drops = true;
  163. }
  164. } else if (options.getIpVersion() == 6) {
  165. if (stats_mgr6_->getDroppedPacketsNum(StatsMgr6::XCHG_SA) >=
  166. options.getMaxDrop()[0]) {
  167. max_drops = true;
  168. }
  169. }
  170. }
  171. // Check if we reached maximum number of drops of ACK/REPLY packets.
  172. if (options.getMaxDrop().size() == 2) {
  173. if (options.getIpVersion() == 4) {
  174. if (stats_mgr4_->getDroppedPacketsNum(StatsMgr4::XCHG_RA) >=
  175. options.getMaxDrop()[1]) {
  176. max_drops = true;
  177. }
  178. } else if (options.getIpVersion() == 6) {
  179. if (stats_mgr6_->getDroppedPacketsNum(StatsMgr6::XCHG_RR) >=
  180. options.getMaxDrop()[1]) {
  181. max_drops = true;
  182. }
  183. }
  184. }
  185. if (max_drops) {
  186. if (testDiags('e')) {
  187. std::cout << "Reached maximum drops number." << std::endl;
  188. }
  189. return (true);
  190. }
  191. // Check if we reached maximum drops percentage of OFFER/ADVERTISE packets.
  192. bool max_pdrops = false;
  193. if (options.getMaxDropPercentage().size() > 0) {
  194. if (options.getIpVersion() == 4) {
  195. if ((stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_DO) > 10) &&
  196. ((100. * stats_mgr4_->getDroppedPacketsNum(StatsMgr4::XCHG_DO) /
  197. stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_DO)) >=
  198. options.getMaxDropPercentage()[0])) {
  199. max_pdrops = true;
  200. }
  201. } else if (options.getIpVersion() == 6) {
  202. if ((stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_SA) > 10) &&
  203. ((100. * stats_mgr6_->getDroppedPacketsNum(StatsMgr6::XCHG_SA) /
  204. stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_SA)) >=
  205. options.getMaxDropPercentage()[0])) {
  206. max_pdrops = true;
  207. }
  208. }
  209. }
  210. // Check if we reached maximum drops percentage of ACK/REPLY packets.
  211. if (options.getMaxDropPercentage().size() == 2) {
  212. if (options.getIpVersion() == 4) {
  213. if ((stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_RA) > 10) &&
  214. ((100. * stats_mgr4_->getDroppedPacketsNum(StatsMgr4::XCHG_RA) /
  215. stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_RA)) >=
  216. options.getMaxDropPercentage()[1])) {
  217. max_pdrops = true;
  218. }
  219. } else if (options.getIpVersion() == 6) {
  220. if ((stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_RR) > 10) &&
  221. ((100. * stats_mgr6_->getDroppedPacketsNum(StatsMgr6::XCHG_RR) /
  222. stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_RR)) >=
  223. options.getMaxDropPercentage()[1])) {
  224. max_pdrops = true;
  225. }
  226. }
  227. }
  228. if (max_pdrops) {
  229. if (testDiags('e')) {
  230. std::cout << "Reached maximum percentage of drops." << std::endl;
  231. }
  232. return (true);
  233. }
  234. return (false);
  235. }
  236. OptionPtr
  237. TestControl::factoryElapsedTime6(Option::Universe, uint16_t,
  238. const OptionBuffer& buf) {
  239. if (buf.size() == 2) {
  240. return (OptionPtr(new Option(Option::V6, D6O_ELAPSED_TIME, buf)));
  241. } else if (buf.size() == 0) {
  242. return (OptionPtr(new Option(Option::V6, D6O_ELAPSED_TIME,
  243. OptionBuffer(2, 0))));
  244. }
  245. isc_throw(isc::BadValue,
  246. "elapsed time option buffer size has to be 0 or 2");
  247. }
  248. OptionPtr
  249. TestControl::factoryGeneric(Option::Universe u, uint16_t type,
  250. const OptionBuffer& buf) {
  251. OptionPtr opt(new Option(u, type, buf));
  252. return (opt);
  253. }
  254. OptionPtr
  255. TestControl::factoryIana6(Option::Universe, uint16_t,
  256. const OptionBuffer& buf) {
  257. // @todo allow different values of T1, T2 and IAID.
  258. const uint8_t buf_array[] = {
  259. 0, 0, 0, 1, // IAID = 1
  260. 0, 0, 3600 >> 8, 3600 && 0xff, // T1 = 3600
  261. 0, 0, 5400 >> 8, 5400 & 0xff, // T2 = 5400
  262. };
  263. OptionBuffer buf_ia_na(buf_array, buf_array + sizeof(buf_array));
  264. for (int i = 0; i < buf.size(); ++i) {
  265. buf_ia_na.push_back(buf[i]);
  266. }
  267. return (OptionPtr(new Option(Option::V6, D6O_IA_NA, buf_ia_na)));
  268. }
  269. OptionPtr
  270. TestControl::factoryRapidCommit6(Option::Universe, uint16_t,
  271. const OptionBuffer&) {
  272. return (OptionPtr(new Option(Option::V6, D6O_RAPID_COMMIT, OptionBuffer())));
  273. }
  274. OptionPtr
  275. TestControl::factoryOptionRequestOption6(Option::Universe,
  276. uint16_t,
  277. const OptionBuffer&) {
  278. const uint8_t buf_array[] = {
  279. 0, D6O_NAME_SERVERS,
  280. 0, D6O_DOMAIN_SEARCH
  281. };
  282. OptionBuffer buf_with_options(buf_array, buf_array + sizeof(buf_array));
  283. return (OptionPtr(new Option(Option::V6, D6O_ORO, buf_with_options)));
  284. }
  285. OptionPtr
  286. TestControl::factoryRequestList4(Option::Universe u,
  287. uint16_t type,
  288. const OptionBuffer& buf) {
  289. const uint8_t buf_array[] = {
  290. DHO_SUBNET_MASK,
  291. DHO_BROADCAST_ADDRESS,
  292. DHO_TIME_OFFSET,
  293. DHO_ROUTERS,
  294. DHO_DOMAIN_NAME,
  295. DHO_DOMAIN_NAME_SERVERS,
  296. DHO_HOST_NAME
  297. };
  298. OptionBuffer buf_with_options(buf_array, buf_array + sizeof(buf_array));
  299. OptionPtr opt(new Option(u, type, buf));
  300. opt->setData(buf_with_options.begin(), buf_with_options.end());
  301. return (opt);
  302. }
  303. std::vector<uint8_t>
  304. TestControl::generateMacAddress(uint8_t& randomized) const {
  305. CommandOptions& options = CommandOptions::instance();
  306. uint32_t clients_num = options.getClientsNum();
  307. if ((clients_num == 0) || (clients_num == 1)) {
  308. return (options.getMacTemplate());
  309. }
  310. // Get the base MAC address. We are going to randomize part of it.
  311. std::vector<uint8_t> mac_addr(options.getMacTemplate());
  312. if (mac_addr.size() != HW_ETHER_LEN) {
  313. isc_throw(BadValue, "invalid MAC address template specified");
  314. }
  315. uint32_t r = random();
  316. // The random number must be in the range 0..clients_num-1. This
  317. // will guarantee that every client has exactly one random MAC
  318. // address assigned.
  319. r %= clients_num;
  320. randomized = 0;
  321. // Randomize MAC address octets.
  322. for (std::vector<uint8_t>::iterator it = mac_addr.end() - 1;
  323. it >= mac_addr.begin();
  324. --it) {
  325. // Add the random value to the current octet.
  326. (*it) += r;
  327. ++randomized;
  328. if (r < 256) {
  329. // If we are here it means that there is no sense
  330. // to randomize the remaining octets of MAC address
  331. // because the following bytes of random value
  332. // are zero and it will have no effect.
  333. break;
  334. }
  335. // Randomize the next octet with the following
  336. // byte of random value.
  337. r >>= 8;
  338. }
  339. return (mac_addr);
  340. }
  341. std::vector<uint8_t>
  342. TestControl::generateDuid(uint8_t& randomized) const {
  343. CommandOptions& options = CommandOptions::instance();
  344. uint32_t clients_num = options.getClientsNum();
  345. if ((clients_num == 0) || (clients_num == 1)) {
  346. return (options.getDuidTemplate());
  347. }
  348. // Get the base DUID. We are going to randomize part of it.
  349. std::vector<uint8_t> duid(options.getDuidTemplate());
  350. // @todo: add support for DUIDs of different sizes.
  351. std::vector<uint8_t> mac_addr(generateMacAddress(randomized));
  352. duid.resize(duid.size());
  353. std::copy(mac_addr.begin(), mac_addr.end(),
  354. duid.begin() + duid.size() - mac_addr.size());
  355. return (duid);
  356. }
  357. template<class T>
  358. uint32_t
  359. TestControl::getElapsedTime(const T& pkt1, const T& pkt2) {
  360. using namespace boost::posix_time;
  361. ptime pkt1_time = pkt1->getTimestamp();
  362. ptime pkt2_time = pkt2->getTimestamp();
  363. if (pkt1_time.is_not_a_date_time() ||
  364. pkt2_time.is_not_a_date_time()) {
  365. isc_throw(InvalidOperation, "packet timestamp not set");;
  366. }
  367. time_period elapsed_period(pkt1_time, pkt2_time);
  368. if (elapsed_period.is_null()) {
  369. isc_throw(InvalidOperation, "unable to calculate time elapsed"
  370. " between packets");
  371. }
  372. return(elapsed_period.length().total_milliseconds());
  373. }
  374. uint64_t
  375. TestControl::getNextExchangesNum() const {
  376. CommandOptions& options = CommandOptions::instance();
  377. // Reset number of exchanges.
  378. uint64_t due_exchanges = 0;
  379. // Get current time.
  380. ptime now(microsec_clock::universal_time());
  381. if (now >= send_due_) {
  382. // If rate is specified from the command line we have to
  383. // synchornize with it.
  384. if (options.getRate() != 0) {
  385. time_period period(send_due_, now);
  386. time_duration duration = period.length();
  387. // due_factor indicates the number of seconds that
  388. // sending next chunk of packets will take.
  389. double due_factor = duration.fractional_seconds() /
  390. time_duration::ticks_per_second();
  391. due_factor += duration.total_seconds();
  392. // Multiplying due_factor by expected rate gives the number
  393. // of exchanges to be initiated.
  394. due_exchanges = static_cast<uint64_t>(due_factor * options.getRate());
  395. // We want to make sure that at least one packet goes out.
  396. if (due_exchanges == 0) {
  397. due_exchanges = 1;
  398. }
  399. // We should not exceed aggressivity as it could have been
  400. // restricted from command line.
  401. if (due_exchanges > options.getAggressivity()) {
  402. due_exchanges = options.getAggressivity();
  403. }
  404. } else {
  405. // Rate is not specified so we rely on aggressivity
  406. // which is the number of packets to be sent in
  407. // one chunk.
  408. due_exchanges = options.getAggressivity();
  409. }
  410. return (due_exchanges);
  411. }
  412. return (0);
  413. }
  414. uint64_t
  415. TestControl::getRcvdPacketsNum(const ExchangeType xchg_type) const {
  416. uint8_t ip_version = CommandOptions::instance().getIpVersion();
  417. if (ip_version == 4) {
  418. return (stats_mgr4_->getRcvdPacketsNum(xchg_type));
  419. }
  420. return (stats_mgr6_->
  421. getRcvdPacketsNum(static_cast<StatsMgr6::ExchangeType>(xchg_type)));
  422. }
  423. uint64_t
  424. TestControl::getSentPacketsNum(const ExchangeType xchg_type) const {
  425. uint8_t ip_version = CommandOptions::instance().getIpVersion();
  426. if (ip_version == 4) {
  427. return (stats_mgr4_->getSentPacketsNum(xchg_type));
  428. }
  429. return (stats_mgr6_->
  430. getSentPacketsNum(static_cast<StatsMgr6::ExchangeType>(xchg_type)));
  431. }
  432. TestControl::TemplateBuffer
  433. TestControl::getTemplateBuffer(const size_t idx) const {
  434. if (template_buffers_.size() > idx) {
  435. return (template_buffers_[idx]);
  436. }
  437. isc_throw(OutOfRange, "invalid buffer index");
  438. }
  439. void
  440. TestControl::handleInterrupt(int) {
  441. interrupted_ = true;
  442. }
  443. void
  444. TestControl::initPacketTemplates() {
  445. template_buffers_.clear();
  446. CommandOptions& options = CommandOptions::instance();
  447. std::vector<std::string> template_files = options.getTemplateFiles();
  448. for (std::vector<std::string>::const_iterator it = template_files.begin();
  449. it != template_files.end(); ++it) {
  450. readPacketTemplate(*it);
  451. }
  452. }
  453. void
  454. TestControl::initializeStatsMgr() {
  455. CommandOptions& options = CommandOptions::instance();
  456. if (options.getIpVersion() == 4) {
  457. stats_mgr4_.reset();
  458. stats_mgr4_ = StatsMgr4Ptr(new StatsMgr4());
  459. stats_mgr4_->addExchangeStats(StatsMgr4::XCHG_DO);
  460. if (options.getExchangeMode() == CommandOptions::DORA_SARR) {
  461. stats_mgr4_->addExchangeStats(StatsMgr4::XCHG_RA);
  462. }
  463. } else if (options.getIpVersion() == 6) {
  464. stats_mgr6_.reset();
  465. stats_mgr6_ = StatsMgr6Ptr(new StatsMgr6());
  466. stats_mgr6_->addExchangeStats(StatsMgr6::XCHG_SA);
  467. if (options.getExchangeMode() == CommandOptions::DORA_SARR) {
  468. stats_mgr6_->addExchangeStats(StatsMgr6::XCHG_RR);
  469. }
  470. }
  471. if (testDiags('i')) {
  472. if (options.getIpVersion() == 4) {
  473. stats_mgr4_->addCustomCounter("latesend", "Late sent packets");
  474. stats_mgr4_->addCustomCounter("shortwait", "Short waits for packets");
  475. stats_mgr4_->addCustomCounter("multircvd", "Multiple packets receives");
  476. // stats_mgr4_->addCustomCounter("latercvd", "Late received packets");
  477. } else if (options.getIpVersion() == 6) {
  478. stats_mgr6_->addCustomCounter("latesend", "Late sent packets");
  479. stats_mgr6_->addCustomCounter("shortwait", "Short waits for packets");
  480. stats_mgr6_->addCustomCounter("multircvd", "Multiple packets receives");
  481. // stats_mgr6_->addCustomCounter("latercvd", "Late received packets");
  482. }
  483. }
  484. }
  485. int
  486. TestControl::openSocket() const {
  487. CommandOptions& options = CommandOptions::instance();
  488. std::string localname = options.getLocalName();
  489. std::string servername = options.getServerName();
  490. uint16_t port = options.getLocalPort();
  491. uint8_t family = AF_INET;
  492. int sock = 0;
  493. IOAddress remoteaddr(servername);
  494. if (port == 0) {
  495. if (options.getIpVersion() == 6) {
  496. port = DHCP6_CLIENT_PORT;
  497. } else if (options.getIpVersion() == 4) {
  498. port = 67; // TODO: find out why port 68 is wrong here.
  499. }
  500. }
  501. if (options.getIpVersion() == 6) {
  502. family = AF_INET6;
  503. }
  504. // Local name is specified along with '-l' option.
  505. // It may point to interface name or local address.
  506. if (!localname.empty()) {
  507. // CommandOptions should be already aware wether local name
  508. // is interface name or address because it uses IfaceMgr to
  509. // scan interfaces and get's their names.
  510. if (options.isInterface()) {
  511. sock = IfaceMgr::instance().openSocketFromIface(localname,
  512. port,
  513. family);
  514. } else {
  515. IOAddress localaddr(localname);
  516. sock = IfaceMgr::instance().openSocketFromAddress(localaddr,
  517. port);
  518. }
  519. } else if (!servername.empty()) {
  520. // If only server name is given we will need to try to resolve
  521. // the local address to bind socket to based on remote address.
  522. sock = IfaceMgr::instance().openSocketFromRemoteAddress(remoteaddr,
  523. port);
  524. }
  525. if (sock <= 0) {
  526. isc_throw(BadValue, "unable to open socket to communicate with "
  527. "DHCP server");
  528. }
  529. // IfaceMgr does not set broadcast option on the socket. We rely
  530. // on CommandOptions object to find out if socket has to have
  531. // broadcast enabled.
  532. if ((options.getIpVersion() == 4) && options.isBroadcast()) {
  533. int broadcast_enable = 1;
  534. int ret = setsockopt(sock, SOL_SOCKET, SO_BROADCAST,
  535. &broadcast_enable, sizeof(broadcast_enable));
  536. if (ret < 0) {
  537. isc_throw(InvalidOperation,
  538. "unable to set broadcast option on the socket");
  539. }
  540. } else if (options.getIpVersion() == 6) {
  541. // If remote address is multicast we need to enable it on
  542. // the socket that has been created.
  543. asio::ip::address_v6 remote_v6 = remoteaddr.getAddress().to_v6();
  544. if (remote_v6.is_multicast()) {
  545. int hops = 1;
  546. int ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
  547. &hops, sizeof(hops));
  548. // If user specified interface name with '-l' the
  549. // IPV6_MULTICAST_IF has to be set.
  550. if ((ret >= 0) && options.isInterface()) {
  551. IfaceMgr::Iface* iface =
  552. IfaceMgr::instance().getIface(options.getLocalName());
  553. if (iface == NULL) {
  554. isc_throw(Unexpected, "unknown interface "
  555. << options.getLocalName());
  556. }
  557. int idx = iface->getIndex();
  558. ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
  559. &idx, sizeof(idx));
  560. }
  561. if (ret < 0) {
  562. isc_throw(InvalidOperation,
  563. "unable to enable multicast on socket " << sock
  564. << ". errno = " << errno);
  565. }
  566. }
  567. }
  568. return (sock);
  569. }
  570. void
  571. TestControl::printDiagnostics() const {
  572. CommandOptions& options = CommandOptions::instance();
  573. if (testDiags('a')) {
  574. // Print all command line parameters.
  575. options.printCommandLine();
  576. // Print MAC and DUID.
  577. std::cout << "Set MAC to " << vector2Hex(options.getMacTemplate(), "::")
  578. << std::endl;
  579. if (options.getDuidTemplate().size() > 0) {
  580. std::cout << "Set DUID to " << vector2Hex(options.getDuidTemplate()) << std::endl;
  581. }
  582. }
  583. }
  584. void
  585. TestControl::printRate() const {
  586. double rate = 0;
  587. CommandOptions& options = CommandOptions::instance();
  588. if (options.getIpVersion() == 4) {
  589. double duration =
  590. stats_mgr4_->getTestPeriod().length().total_nanoseconds() / 1e9;
  591. rate = stats_mgr4_->getRcvdPacketsNum(StatsMgr4::XCHG_DO) / duration;
  592. } else if (options.getIpVersion() == 6) {
  593. double duration =
  594. stats_mgr6_->getTestPeriod().length().total_nanoseconds() / 1e9;
  595. rate = stats_mgr6_->getRcvdPacketsNum(StatsMgr6::XCHG_SA) / duration;
  596. }
  597. std::cout << "***Rate statistics***" << std::endl;
  598. if (options.getRate() > 0) {
  599. std::cout << "Rate: " << rate << ", expected rate: "
  600. << options.getRate() << std::endl << std::endl;
  601. } else {
  602. std::cout << "Rate: " << rate << std::endl << std::endl;
  603. }
  604. }
  605. void
  606. TestControl::printIntermediateStats() {
  607. CommandOptions& options = CommandOptions::instance();
  608. int delay = options.getReportDelay();
  609. ptime now = microsec_clock::universal_time();
  610. time_period time_since_report(last_report_, now);
  611. if (time_since_report.length().total_seconds() >= delay) {
  612. if (options.getIpVersion() == 4) {
  613. stats_mgr4_->printIntermediateStats();
  614. } else if (options.getIpVersion() == 6) {
  615. stats_mgr6_->printIntermediateStats();
  616. }
  617. last_report_ = now;
  618. }
  619. }
  620. void
  621. TestControl::printStats() const {
  622. printRate();
  623. CommandOptions& options = CommandOptions::instance();
  624. if (options.getIpVersion() == 4) {
  625. if (!stats_mgr4_) {
  626. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  627. "hasn't been initialized");
  628. }
  629. stats_mgr4_->printStats();
  630. if (testDiags('i')) {
  631. stats_mgr4_->printCustomCounters();
  632. }
  633. } else if (options.getIpVersion() == 6) {
  634. if (!stats_mgr6_) {
  635. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  636. "hasn't been initialized");
  637. }
  638. stats_mgr6_->printStats();
  639. if (testDiags('i')) {
  640. stats_mgr6_->printCustomCounters();
  641. }
  642. }
  643. }
  644. std::string
  645. TestControl::vector2Hex(const std::vector<uint8_t>& vec,
  646. const std::string& separator /* ="" */) const {
  647. std::ostringstream stream;
  648. for (std::vector<uint8_t>::const_iterator it = vec.begin();
  649. it != vec.end();
  650. ++it) {
  651. if (it == vec.begin()) {
  652. stream << byte2Hex(*it);
  653. } else {
  654. stream << separator << byte2Hex(*it);
  655. }
  656. }
  657. return (stream.str());
  658. }
  659. void
  660. TestControl::readPacketTemplate(const std::string& file_name) {
  661. std::ifstream temp_file;
  662. temp_file.open(file_name.c_str(), ios::in | ios::binary | ios::ate);
  663. if (!temp_file.is_open()) {
  664. isc_throw(BadValue, "unable to open template file " << file_name);
  665. }
  666. std::ifstream::pos_type temp_size = temp_file.tellg();
  667. if (temp_size % 2 != 0) {
  668. temp_file.close();
  669. isc_throw(BadValue, "odd number of digits in template file");
  670. }
  671. temp_file.seekg(0, ios::beg);
  672. std::vector<char> hex_digits(temp_size);
  673. std::vector<uint8_t> binary_stream;
  674. temp_file.read(&hex_digits[0], temp_size);
  675. temp_file.close();
  676. for (int i = 0; i < hex_digits.size(); i += 2) {
  677. if (!isxdigit(hex_digits[i]) || !isxdigit(hex_digits[i+1])) {
  678. isc_throw(BadValue, "the '" << hex_digits[i] << hex_digits[i+1]
  679. << "' is not hexadecimal digit");
  680. }
  681. stringstream s;
  682. s << "0x" << hex_digits[i] << hex_digits[i+1];
  683. int b;
  684. s >> std::hex >> b;
  685. binary_stream.push_back(static_cast<uint8_t>(b));
  686. }
  687. template_buffers_.push_back(binary_stream);
  688. }
  689. void
  690. TestControl::receivePacket4(const TestControlSocket& socket,
  691. const Pkt4Ptr& pkt4) {
  692. if (pkt4->getType() == DHCPOFFER) {
  693. Pkt4Ptr discover_pkt4(stats_mgr4_->passRcvdPacket(StatsMgr4::XCHG_DO,
  694. pkt4));
  695. CommandOptions::ExchangeMode xchg_mode =
  696. CommandOptions::instance().getExchangeMode();
  697. if ((xchg_mode == CommandOptions::DORA_SARR) && discover_pkt4) {
  698. if (template_buffers_.size() < 2) {
  699. sendRequest4(socket, discover_pkt4, pkt4);
  700. } else {
  701. sendRequest4(socket, template_buffers_[1], discover_pkt4, pkt4);
  702. }
  703. }
  704. } else if (pkt4->getType() == DHCPACK) {
  705. stats_mgr4_->passRcvdPacket(StatsMgr4::XCHG_RA, pkt4);
  706. }
  707. }
  708. void
  709. TestControl::receivePacket6(const TestControlSocket& socket,
  710. const Pkt6Ptr& pkt6) {
  711. uint8_t packet_type = pkt6->getType();
  712. if (packet_type == DHCPV6_ADVERTISE) {
  713. Pkt6Ptr solicit_pkt6(stats_mgr6_->passRcvdPacket(StatsMgr6::XCHG_SA,
  714. pkt6));
  715. CommandOptions::ExchangeMode xchg_mode =
  716. CommandOptions::instance().getExchangeMode();
  717. if ((xchg_mode == CommandOptions::DORA_SARR) && solicit_pkt6) {
  718. // \todo check whether received ADVERTISE packet is sane.
  719. // We might want to check if STATUS_CODE option is non-zero
  720. // and if there is IAADR option in IA_NA.
  721. if (template_buffers_.size() < 2) {
  722. sendRequest6(socket, pkt6);
  723. } else {
  724. sendRequest6(socket, template_buffers_[1], pkt6);
  725. }
  726. }
  727. } else if (packet_type == DHCPV6_REPLY) {
  728. stats_mgr6_->passRcvdPacket(StatsMgr6::XCHG_RR, pkt6);
  729. }
  730. }
  731. void
  732. TestControl::receivePackets(const TestControlSocket& socket) {
  733. int timeout = 0;
  734. bool receiving = true;
  735. uint64_t received = 0;
  736. while (receiving) {
  737. if (CommandOptions::instance().getIpVersion() == 4) {
  738. Pkt4Ptr pkt4 = IfaceMgr::instance().receive4(timeout);
  739. if (!pkt4) {
  740. receiving = false;
  741. } else {
  742. ++received;
  743. if ((received > 1) && testDiags('i')) {
  744. stats_mgr4_->incrementCounter("multircvd");
  745. }
  746. pkt4->unpack();
  747. receivePacket4(socket, pkt4);
  748. }
  749. } else if (CommandOptions::instance().getIpVersion() == 6) {
  750. Pkt6Ptr pkt6 = IfaceMgr::instance().receive6(timeout);
  751. if (!pkt6) {
  752. receiving = false;
  753. } else {
  754. ++received;
  755. if ((received > 1) && testDiags('i')) {
  756. stats_mgr6_->incrementCounter("multircvd");
  757. }
  758. if (pkt6->unpack()) {
  759. receivePacket6(socket, pkt6);
  760. }
  761. }
  762. }
  763. }
  764. }
  765. void
  766. TestControl::registerOptionFactories4() const {
  767. static bool factories_registered = false;
  768. if (!factories_registered) {
  769. // DHCP_MESSAGE_TYPE option factory.
  770. LibDHCP::OptionFactoryRegister(Option::V4,
  771. DHO_DHCP_MESSAGE_TYPE,
  772. &TestControl::factoryGeneric);
  773. // DHCP_SERVER_IDENTIFIER option factory.
  774. LibDHCP::OptionFactoryRegister(Option::V4,
  775. DHO_DHCP_SERVER_IDENTIFIER,
  776. &TestControl::factoryGeneric);
  777. // DHCP_PARAMETER_REQUEST_LIST option factory.
  778. LibDHCP::OptionFactoryRegister(Option::V4,
  779. DHO_DHCP_PARAMETER_REQUEST_LIST,
  780. &TestControl::factoryRequestList4);
  781. }
  782. factories_registered = true;
  783. }
  784. void
  785. TestControl::registerOptionFactories6() const {
  786. static bool factories_registered = false;
  787. if (!factories_registered) {
  788. // D60_ELAPSED_TIME
  789. LibDHCP::OptionFactoryRegister(Option::V6,
  790. D6O_ELAPSED_TIME,
  791. &TestControl::factoryElapsedTime6);
  792. // D6O_RAPID_COMMIT
  793. LibDHCP::OptionFactoryRegister(Option::V6,
  794. D6O_RAPID_COMMIT,
  795. &TestControl::factoryRapidCommit6);
  796. // D6O_ORO (option request option) factory.
  797. LibDHCP::OptionFactoryRegister(Option::V6,
  798. D6O_ORO,
  799. &TestControl::factoryOptionRequestOption6);
  800. // D6O_CLIENTID option factory.
  801. LibDHCP::OptionFactoryRegister(Option::V6,
  802. D6O_CLIENTID,
  803. &TestControl::factoryGeneric);
  804. // D6O_SERVERID option factory.
  805. LibDHCP::OptionFactoryRegister(Option::V6,
  806. D6O_SERVERID,
  807. &TestControl::factoryGeneric);
  808. // D6O_IA_NA option factory.
  809. LibDHCP::OptionFactoryRegister(Option::V6,
  810. D6O_IA_NA,
  811. &TestControl::factoryIana6);
  812. }
  813. factories_registered = true;
  814. }
  815. void
  816. TestControl::registerOptionFactories() const {
  817. CommandOptions& options = CommandOptions::instance();
  818. switch(options.getIpVersion()) {
  819. case 4:
  820. registerOptionFactories4();
  821. break;
  822. case 6:
  823. registerOptionFactories6();
  824. break;
  825. default:
  826. isc_throw(InvalidOperation, "command line options have to be parsed "
  827. "before DHCP option factories can be registered");
  828. }
  829. }
  830. void
  831. TestControl::reset() {
  832. send_due_ = microsec_clock::universal_time();
  833. last_sent_ = send_due_;
  834. last_report_ = send_due_;
  835. transid_gen_.reset();
  836. transid_gen_ = TransidGeneratorPtr(new TransidGenerator());
  837. first_packet_serverid_.clear();
  838. interrupted_ = false;
  839. }
  840. void
  841. TestControl::run() {
  842. // Reset singleton state before test starts.
  843. reset();
  844. CommandOptions& options = CommandOptions::instance();
  845. // Ip version is not set ONLY in case the command options
  846. // were not parsed. This surely means that parse() function
  847. // was not called prior to starting the test. This is fatal
  848. // error.
  849. if (options.getIpVersion() == 0) {
  850. isc_throw(InvalidOperation,
  851. "command options must be parsed before running a test");
  852. }
  853. // Diagnostics are command line options mainly.
  854. printDiagnostics();
  855. // Option factories have to be registered.
  856. registerOptionFactories();
  857. TestControlSocket socket(openSocket());
  858. if (!socket.valid_) {
  859. isc_throw(Unexpected, "invalid socket descriptor");
  860. }
  861. // Initialize packet templates.
  862. initPacketTemplates();
  863. // Initialize randomization seed.
  864. if (options.isSeeded()) {
  865. srandom(options.getSeed());
  866. } else {
  867. // Seed with current time.
  868. time_period duration(from_iso_string("20111231T235959"),
  869. microsec_clock::universal_time());
  870. srandom(duration.length().total_seconds()
  871. + duration.length().fractional_seconds());
  872. }
  873. // If user interrupts the program we will exit gracefully.
  874. signal(SIGINT, TestControl::handleInterrupt);
  875. // Preload server with number of packets.
  876. const bool do_preload = true;
  877. for (int i = 0; i < options.getPreload(); ++i) {
  878. if (options.getIpVersion() == 4) {
  879. // No template buffer means no -T option specified.
  880. // We will build packet ourselves.
  881. if (template_buffers_.size() == 0) {
  882. sendDiscover4(socket, do_preload);
  883. } else {
  884. // Pick template #0 if Discover is being sent.
  885. // For Request it would be #1.
  886. const uint8_t template_idx = 0;
  887. sendDiscover4(socket, template_buffers_[template_idx],
  888. do_preload);
  889. }
  890. } else if (options.getIpVersion() == 6) {
  891. // No template buffer means no -T option specified.
  892. // We will build packet ourselfs.
  893. if (template_buffers_.size() == 0) {
  894. sendSolicit6(socket, do_preload);
  895. } else {
  896. // Pick template #0 if Solicit is being sent.
  897. // For Request it would be #1.
  898. const uint8_t template_idx = 0;
  899. sendSolicit6(socket, template_buffers_[template_idx],
  900. do_preload);
  901. }
  902. }
  903. }
  904. // Initialize Statistics Manager. Release previous if any.
  905. initializeStatsMgr();
  906. for (;;) {
  907. // Calculate send due based on when last exchange was initiated.
  908. updateSendDue();
  909. // If test period finished, maximum number of packet drops
  910. // has been reached or test has been interrupted we have to
  911. // finish the test.
  912. if (checkExitConditions()) {
  913. break;
  914. }
  915. // Calculate number of packets to be sent to stay
  916. // catch up with rate.
  917. uint64_t packets_due = getNextExchangesNum();
  918. if ((packets_due == 0) && testDiags('i')) {
  919. if (options.getIpVersion() == 4) {
  920. stats_mgr4_->incrementCounter("shortwait");
  921. } else if (options.getIpVersion() == 6) {
  922. stats_mgr6_->incrementCounter("shortwait");
  923. }
  924. }
  925. // @todo: set non-zero timeout for packets once we implement
  926. // microseconds timeout in IfaceMgr.
  927. receivePackets(socket);
  928. // Send packets.
  929. for (uint64_t i = packets_due; i > 0; --i) {
  930. if (options.getIpVersion() == 4) {
  931. // No template packets means that no -T option was specified.
  932. // We have to build packets ourselfs.
  933. if (template_buffers_.size() == 0) {
  934. sendDiscover4(socket);
  935. } else {
  936. const uint8_t template_idx = 0;
  937. sendDiscover4(socket, template_buffers_[template_idx]);
  938. }
  939. } else {
  940. // No template packets means that no -T option was specified.
  941. // We have to build packets ourselfs.
  942. if (template_buffers_.size() == 0) {
  943. sendSolicit6(socket);
  944. } else {
  945. const uint8_t template_idx = 0;
  946. sendSolicit6(socket, template_buffers_[template_idx]);
  947. }
  948. }
  949. }
  950. // Report delay means that user requested printing number
  951. // of sent/received/dropped packets repeatedly.
  952. if (options.getReportDelay() > 0) {
  953. printIntermediateStats();
  954. }
  955. }
  956. printStats();
  957. // Print server id.
  958. if (testDiags('s') && (first_packet_serverid_.size() > 0)) {
  959. std::cout << "Server id: " << vector2Hex(first_packet_serverid_) << std::endl;
  960. }
  961. // Diagnostics flag 'e' means show exit reason.
  962. if (testDiags('e')) {
  963. std::cout << "Interrupted" << std::endl;
  964. }
  965. }
  966. void
  967. TestControl::sendDiscover4(const TestControlSocket& socket,
  968. const bool preload /*= false*/) {
  969. last_sent_ = microsec_clock::universal_time();
  970. // Generate the MAC address to be passed in the packet.
  971. uint8_t randomized = 0;
  972. std::vector<uint8_t> mac_address = generateMacAddress(randomized);
  973. // Generate trasnaction id to be set for the new exchange.
  974. const uint32_t transid = generateTransid();
  975. Pkt4Ptr pkt4(new Pkt4(DHCPDISCOVER, transid));
  976. if (!pkt4) {
  977. isc_throw(Unexpected, "failed to create DISCOVER packet");
  978. }
  979. // Set options: DHCP_MESSAGE_TYPE and DHCP_PARAMETER_REQUEST_LIST
  980. OptionBuffer buf_msg_type;
  981. buf_msg_type.push_back(DHCPDISCOVER);
  982. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  983. buf_msg_type));
  984. pkt4->addOption(Option::factory(Option::V4,
  985. DHO_DHCP_PARAMETER_REQUEST_LIST));
  986. // Set client's and server's ports as well as server's address,
  987. // and local (relay) address.
  988. setDefaults4(socket, pkt4);
  989. // Set hardware address
  990. pkt4->setHWAddr(HTYPE_ETHER, mac_address.size(), mac_address);
  991. pkt4->pack();
  992. IfaceMgr::instance().send(pkt4);
  993. if (!preload) {
  994. if (!stats_mgr4_) {
  995. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  996. "hasn't been initialized");
  997. }
  998. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_DO, pkt4);
  999. }
  1000. }
  1001. void
  1002. TestControl::sendDiscover4(const TestControlSocket& socket,
  1003. const std::vector<uint8_t>& template_buf,
  1004. const bool preload /* = false */) {
  1005. // last_sent_ has to be updated for each function that initiates
  1006. // new transaction. The packet exchange synchronization relies on this.
  1007. last_sent_ = microsec_clock::universal_time();
  1008. CommandOptions& options = CommandOptions::instance();
  1009. // Get the first argument if mulitple the same arguments specified
  1010. // in the command line. First one refers to DISCOVER packets.
  1011. const uint8_t arg_idx = 0;
  1012. // Generate the MAC address to be passed in the packet.
  1013. uint8_t randomized = 0;
  1014. std::vector<uint8_t> mac_address = generateMacAddress(randomized);
  1015. // Generate trasnaction id to be set for the new exchange.
  1016. const uint32_t transid = generateTransid();
  1017. // Get transaction id offset.
  1018. size_t transid_offset = DHCPV4_TRANSID_OFFSET;
  1019. if (options.getTransactionIdOffset().size() > arg_idx) {
  1020. transid_offset = options.getTransactionIdOffset()[arg_idx];
  1021. }
  1022. // Calculate randomization offset.
  1023. size_t rand_offset = DHCPV4_RANDOMIZATION_OFFSET;
  1024. if (options.getRandomOffset().size() > arg_idx) {
  1025. rand_offset = options.getRandomOffset()[arg_idx];
  1026. }
  1027. // We need to go back by HW_ETHER_LEN (MAC address length)
  1028. // because this offset points to last octet of MAC address.
  1029. rand_offset -= HW_ETHER_LEN + 1;
  1030. // Create temporary buffer with template contents. We will
  1031. // modify this temporary buffer but we don't want to modify
  1032. // the original template.
  1033. std::vector<uint8_t> in_buf(template_buf.begin(),
  1034. template_buf.end());
  1035. // Check if we are not going out of bounds.
  1036. if (rand_offset + HW_ETHER_LEN > in_buf.size()) {
  1037. isc_throw(OutOfRange, "randomization offset is out of bounds");
  1038. }
  1039. PerfPkt4Ptr pkt4(new PerfPkt4(&in_buf[0], in_buf.size(),
  1040. transid_offset,
  1041. transid));
  1042. // Replace MAC address in the template with actual MAC address.
  1043. pkt4->writeAt(rand_offset, mac_address.begin(), mac_address.end());
  1044. // Create a packet from the temporary buffer.
  1045. setDefaults4(socket, static_pointer_cast<Pkt4>(pkt4));
  1046. // Pack the input packet buffer to output buffer so as it can
  1047. // be sent to server.
  1048. pkt4->rawPack();
  1049. IfaceMgr::instance().send(static_pointer_cast<Pkt4>(pkt4));
  1050. if (!preload) {
  1051. if (!stats_mgr4_) {
  1052. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  1053. "hasn't been initialized");
  1054. }
  1055. // Update packet stats.
  1056. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_DO,
  1057. static_pointer_cast<Pkt4>(pkt4));
  1058. }
  1059. }
  1060. void
  1061. TestControl::sendRequest4(const TestControlSocket& socket,
  1062. const dhcp::Pkt4Ptr& discover_pkt4,
  1063. const dhcp::Pkt4Ptr& offer_pkt4) {
  1064. const uint32_t transid = generateTransid();
  1065. Pkt4Ptr pkt4(new Pkt4(DHCPREQUEST, transid));
  1066. OptionBuffer buf_msg_type;
  1067. buf_msg_type.push_back(DHCPREQUEST);
  1068. OptionPtr opt_msg_type = Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  1069. buf_msg_type);
  1070. pkt4->addOption(opt_msg_type);
  1071. if (CommandOptions::instance().isUseFirst() &&
  1072. (first_packet_serverid_.size() > 0)) {
  1073. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_SERVER_IDENTIFIER,
  1074. first_packet_serverid_));
  1075. } else {
  1076. OptionPtr opt_serverid =
  1077. offer_pkt4->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1078. if (!opt_serverid) {
  1079. isc_throw(BadValue, "there is no SERVER_IDENTIFIER option "
  1080. << "in OFFER message");
  1081. }
  1082. if (stats_mgr4_->getRcvdPacketsNum(StatsMgr4::XCHG_DO) == 1) {
  1083. first_packet_serverid_ = opt_serverid->getData();
  1084. }
  1085. pkt4->addOption(opt_serverid);
  1086. }
  1087. /// Set client address.
  1088. asiolink::IOAddress yiaddr = offer_pkt4->getYiaddr();
  1089. if (!yiaddr.getAddress().is_v4()) {
  1090. isc_throw(BadValue, "the YIADDR returned in OFFER packet is not "
  1091. " IPv4 address");
  1092. }
  1093. OptionPtr opt_requested_address =
  1094. OptionPtr(new Option(Option::V4, DHO_DHCP_REQUESTED_ADDRESS,
  1095. OptionBuffer()));
  1096. opt_requested_address->setUint32(static_cast<uint32_t>(yiaddr));
  1097. pkt4->addOption(opt_requested_address);
  1098. OptionPtr opt_parameter_list =
  1099. Option::factory(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST);
  1100. pkt4->addOption(opt_parameter_list);
  1101. // Set client's and server's ports as well as server's address,
  1102. // and local (relay) address.
  1103. setDefaults4(socket, pkt4);
  1104. // Set hardware address
  1105. const uint8_t* chaddr = offer_pkt4->getChaddr();
  1106. std::vector<uint8_t> mac_address(chaddr, chaddr + HW_ETHER_LEN);
  1107. pkt4->setHWAddr(HTYPE_ETHER, mac_address.size(), mac_address);
  1108. // Set elapsed time.
  1109. uint32_t elapsed_time = getElapsedTime<Pkt4Ptr>(discover_pkt4, offer_pkt4);
  1110. pkt4->setSecs(static_cast<uint16_t>(elapsed_time / 1000));
  1111. // Prepare on wire data to send.
  1112. pkt4->pack();
  1113. IfaceMgr::instance().send(pkt4);
  1114. if (!stats_mgr4_) {
  1115. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  1116. "hasn't been initialized");
  1117. }
  1118. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_RA, pkt4);
  1119. }
  1120. void
  1121. TestControl::sendRequest4(const TestControlSocket& socket,
  1122. const std::vector<uint8_t>& template_buf,
  1123. const dhcp::Pkt4Ptr& discover_pkt4,
  1124. const dhcp::Pkt4Ptr& offer_pkt4) {
  1125. CommandOptions& options = CommandOptions::instance();
  1126. // Get the second argument if multiple the same arguments specified
  1127. // in the command line. Second one refers to REQUEST packets.
  1128. const uint8_t arg_idx = 1;
  1129. // Generate new transaction id.
  1130. const uint32_t transid = generateTransid();
  1131. // Get transaction id offset.
  1132. size_t transid_offset = DHCPV4_TRANSID_OFFSET;
  1133. if (options.getTransactionIdOffset().size() > arg_idx) {
  1134. transid_offset = options.getTransactionIdOffset()[arg_idx];
  1135. }
  1136. // Get the offset of MAC's last octet.
  1137. size_t rand_offset = DHCPV4_RANDOMIZATION_OFFSET;
  1138. if (options.getRandomOffset().size() > arg_idx) {
  1139. rand_offset = options.getRandomOffset()[arg_idx];
  1140. }
  1141. // We need to go back by HW_ETHER_LEN (MAC address length)
  1142. // because this offset points to last octet of MAC address.
  1143. rand_offset -= HW_ETHER_LEN + 1;
  1144. // Create temporaru buffer from the template.
  1145. std::vector<uint8_t> in_buf(template_buf.begin(),
  1146. template_buf.end());
  1147. // Check if given randomization offset is not out of bounds.
  1148. if (rand_offset + HW_ETHER_LEN > in_buf.size()) {
  1149. isc_throw(OutOfRange, "randomization offset is out of bounds");
  1150. }
  1151. // Create packet from the temporary buffer.
  1152. PerfPkt4Ptr pkt4(new PerfPkt4(&in_buf[0], in_buf.size(),
  1153. transid_offset,
  1154. transid));
  1155. // Set hardware address from OFFER packet received.
  1156. const uint8_t* chaddr = offer_pkt4->getChaddr();
  1157. std::vector<uint8_t> mac_address(chaddr, chaddr + HW_ETHER_LEN);
  1158. pkt4->writeAt(rand_offset, mac_address.begin(), mac_address.end());
  1159. // Set elapsed time.
  1160. size_t elp_offset = 0;
  1161. if (options.getElapsedTimeOffset() > 0) {
  1162. elp_offset = options.getElapsedTimeOffset();
  1163. }
  1164. uint32_t elapsed_time = getElapsedTime<Pkt4Ptr>(discover_pkt4, offer_pkt4);
  1165. pkt4->writeValueAt<uint16_t>(elp_offset,
  1166. static_cast<uint16_t>(elapsed_time / 1000));
  1167. // Get the actual server id offset.
  1168. size_t sid_offset = DHCPV4_SERVERID_OFFSET;
  1169. if (options.getServerIdOffset() > 0) {
  1170. sid_offset = options.getServerIdOffset();
  1171. }
  1172. if (CommandOptions::instance().isUseFirst() &&
  1173. (first_packet_serverid_.size() > 0)) {
  1174. boost::shared_ptr<LocalizedOption>
  1175. opt_serverid(new LocalizedOption(Option::V4,
  1176. DHO_DHCP_SERVER_IDENTIFIER,
  1177. first_packet_serverid_,
  1178. sid_offset));
  1179. pkt4->addOption(opt_serverid);
  1180. } else {
  1181. // Copy the contents of server identifier received in
  1182. // OFFER packet to put this into REQUEST.
  1183. OptionPtr opt_serverid_offer =
  1184. offer_pkt4->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1185. if (!opt_serverid_offer) {
  1186. isc_throw(BadValue, "there is no SERVER_IDENTIFIER option "
  1187. << "in OFFER message");
  1188. }
  1189. boost::shared_ptr<LocalizedOption>
  1190. opt_serverid(new LocalizedOption(Option::V4,
  1191. DHO_DHCP_SERVER_IDENTIFIER,
  1192. opt_serverid_offer->getData(),
  1193. sid_offset));
  1194. pkt4->addOption(opt_serverid);
  1195. if (stats_mgr4_->getRcvdPacketsNum(StatsMgr4::XCHG_DO) == 1) {
  1196. first_packet_serverid_ = opt_serverid_offer->getData();
  1197. }
  1198. }
  1199. /// Set client address.
  1200. asiolink::IOAddress yiaddr = offer_pkt4->getYiaddr();
  1201. if (!yiaddr.getAddress().is_v4()) {
  1202. isc_throw(BadValue, "the YIADDR returned in OFFER packet is not "
  1203. " IPv4 address");
  1204. }
  1205. // Get the actual offset of requested ip.
  1206. size_t rip_offset = DHCPV4_REQUESTED_IP_OFFSET;
  1207. if (options.getRequestedIpOffset() > 0) {
  1208. rip_offset = options.getRequestedIpOffset();
  1209. }
  1210. // Place requested IP option at specified position (rip_offset).
  1211. boost::shared_ptr<LocalizedOption>
  1212. opt_requested_ip(new LocalizedOption(Option::V4,
  1213. DHO_DHCP_REQUESTED_ADDRESS,
  1214. OptionBuffer(),
  1215. rip_offset));
  1216. // The IOAddress is castable to uint32_t and returns exactly what we need.
  1217. opt_requested_ip->setUint32(static_cast<uint32_t>(yiaddr));
  1218. pkt4->addOption(opt_requested_ip);
  1219. setDefaults4(socket, static_pointer_cast<Pkt4>(pkt4));
  1220. // Prepare on-wire data.
  1221. pkt4->rawPack();
  1222. IfaceMgr::instance().send(static_pointer_cast<Pkt4>(pkt4));
  1223. if (!stats_mgr4_) {
  1224. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  1225. "hasn't been initialized");
  1226. }
  1227. // Update packet stats.
  1228. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_RA,
  1229. static_pointer_cast<Pkt4>(pkt4));
  1230. }
  1231. void
  1232. TestControl::sendRequest6(const TestControlSocket& socket,
  1233. const Pkt6Ptr& advertise_pkt6) {
  1234. const uint32_t transid = generateTransid();
  1235. Pkt6Ptr pkt6(new Pkt6(DHCPV6_REQUEST, transid));
  1236. // Set elapsed time.
  1237. OptionPtr opt_elapsed_time =
  1238. Option::factory(Option::V6, D6O_ELAPSED_TIME);
  1239. pkt6->addOption(opt_elapsed_time);
  1240. // Set client id.
  1241. OptionPtr opt_clientid = advertise_pkt6->getOption(D6O_CLIENTID);
  1242. if (!opt_clientid) {
  1243. isc_throw(Unexpected, "client id not found in received packet");
  1244. }
  1245. pkt6->addOption(opt_clientid);
  1246. // Use first flags indicates that we want to use the server
  1247. // id captured in fisrt packet.
  1248. if (CommandOptions::instance().isUseFirst() &&
  1249. (first_packet_serverid_.size() > 0)) {
  1250. pkt6->addOption(Option::factory(Option::V6, D6O_SERVERID,
  1251. first_packet_serverid_));
  1252. } else {
  1253. OptionPtr opt_serverid = advertise_pkt6->getOption(D6O_SERVERID);
  1254. if (!opt_serverid) {
  1255. isc_throw(Unexpected, "server id not found in received packet");
  1256. }
  1257. if (stats_mgr6_->getRcvdPacketsNum(StatsMgr6::XCHG_SA) == 1) {
  1258. first_packet_serverid_ = opt_serverid->getData();
  1259. }
  1260. pkt6->addOption(opt_serverid);
  1261. }
  1262. // Set IA_NA option.
  1263. OptionPtr opt_ia_na = advertise_pkt6->getOption(D6O_IA_NA);
  1264. if (!opt_ia_na) {
  1265. isc_throw(Unexpected, "DHCPv6 IA_NA option not found in received "
  1266. "packet");
  1267. }
  1268. pkt6->addOption(opt_ia_na);
  1269. // Set default packet data.
  1270. setDefaults6(socket, pkt6);
  1271. // Prepare on-wire data.
  1272. pkt6->pack();
  1273. IfaceMgr::instance().send(pkt6);
  1274. if (!stats_mgr6_) {
  1275. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  1276. "hasn't been initialized");
  1277. }
  1278. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_RR, pkt6);
  1279. }
  1280. void
  1281. TestControl::sendRequest6(const TestControlSocket& socket,
  1282. const std::vector<uint8_t>& template_buf,
  1283. const Pkt6Ptr& advertise_pkt6) {
  1284. CommandOptions& options = CommandOptions::instance();
  1285. // Get the second argument if multiple the same arguments specified
  1286. // in the command line. Second one refers to REQUEST packets.
  1287. const uint8_t arg_idx = 1;
  1288. // Generate transaction id.
  1289. const uint32_t transid = generateTransid();
  1290. // Get transaction id offset.
  1291. size_t transid_offset = DHCPV6_TRANSID_OFFSET;
  1292. if (options.getTransactionIdOffset().size() > arg_idx) {
  1293. transid_offset = options.getTransactionIdOffset()[arg_idx];
  1294. }
  1295. PerfPkt6Ptr pkt6(new PerfPkt6(&template_buf[0], template_buf.size(),
  1296. transid_offset, transid));
  1297. // Set elapsed time.
  1298. size_t elp_offset = DHCPV6_ELAPSED_TIME_OFFSET;
  1299. if (options.getElapsedTimeOffset() > 0) {
  1300. elp_offset = options.getElapsedTimeOffset();
  1301. }
  1302. boost::shared_ptr<LocalizedOption>
  1303. opt_elapsed_time(new LocalizedOption(Option::V6, D6O_ELAPSED_TIME,
  1304. OptionBuffer(), elp_offset));
  1305. pkt6->addOption(opt_elapsed_time);
  1306. // Get the actual server id offset.
  1307. size_t sid_offset = DHCPV6_SERVERID_OFFSET;
  1308. if (options.getServerIdOffset() > 0) {
  1309. sid_offset = options.getServerIdOffset();
  1310. }
  1311. if (CommandOptions::instance().isUseFirst() &&
  1312. (first_packet_serverid_.size() > 0)) {
  1313. boost::shared_ptr<LocalizedOption>
  1314. opt_serverid(new LocalizedOption(Option::V6,
  1315. D6O_SERVERID,
  1316. first_packet_serverid_,
  1317. sid_offset));
  1318. pkt6->addOption(opt_serverid);
  1319. } else {
  1320. // Copy the contents of server identifier received in
  1321. // ADVERTISE packet to put this into REQUEST.
  1322. OptionPtr opt_serverid_advertise =
  1323. advertise_pkt6->getOption(D6O_SERVERID);
  1324. if (!opt_serverid_advertise) {
  1325. isc_throw(BadValue, "there is no SERVERID option "
  1326. << "in ADVERTISE message");
  1327. }
  1328. boost::shared_ptr<LocalizedOption>
  1329. opt_serverid(new LocalizedOption(Option::V6,
  1330. D6O_SERVERID,
  1331. opt_serverid_advertise->getData(),
  1332. sid_offset));
  1333. pkt6->addOption(opt_serverid);
  1334. if (stats_mgr6_->getRcvdPacketsNum(StatsMgr6::XCHG_SA) == 1) {
  1335. first_packet_serverid_ = opt_serverid_advertise->getData();
  1336. }
  1337. }
  1338. // Set IA_NA
  1339. boost::shared_ptr<Option6IA> opt_ia_na_advertise =
  1340. static_pointer_cast<Option6IA>(advertise_pkt6->getOption(D6O_IA_NA));
  1341. if (!opt_ia_na_advertise) {
  1342. isc_throw(Unexpected, "DHCPv6 IA_NA option not found in received "
  1343. "packet");
  1344. }
  1345. size_t addr_offset = DHCPV6_IA_NA_OFFSET;
  1346. if (options.getRequestedIpOffset() > 0) {
  1347. addr_offset = options.getRequestedIpOffset();
  1348. }
  1349. boost::shared_ptr<LocalizedOption>
  1350. opt_ia_na(new LocalizedOption(opt_ia_na_advertise, addr_offset));
  1351. if (!opt_ia_na->valid()) {
  1352. isc_throw(BadValue, "Option IA_NA in advertise packet is invalid");
  1353. }
  1354. pkt6->addOption(opt_ia_na);
  1355. // Set server id.
  1356. OptionPtr opt_serverid_advertise = advertise_pkt6->getOption(D6O_SERVERID);
  1357. if (!opt_serverid_advertise) {
  1358. isc_throw(Unexpected, "DHCPV6 SERVERID option not found in received "
  1359. "packet");
  1360. }
  1361. size_t srvid_offset = DHCPV6_SERVERID_OFFSET;
  1362. if (options.getServerIdOffset() > 0) {
  1363. srvid_offset = options.getServerIdOffset();
  1364. }
  1365. boost::shared_ptr<LocalizedOption>
  1366. opt_serverid(new LocalizedOption(Option::V6, D6O_SERVERID,
  1367. opt_serverid_advertise->getData(),
  1368. srvid_offset));
  1369. pkt6->addOption(opt_serverid);
  1370. // Get randomization offset.
  1371. size_t rand_offset = DHCPV6_RANDOMIZATION_OFFSET;
  1372. if (options.getRandomOffset().size() > arg_idx) {
  1373. rand_offset = options.getRandomOffset()[arg_idx];
  1374. }
  1375. OptionPtr opt_clientid_advertise = advertise_pkt6->getOption(D6O_CLIENTID);
  1376. if (!opt_clientid_advertise) {
  1377. isc_throw(Unexpected, "DHCPV6 CLIENTID option not found in received packet");
  1378. }
  1379. rand_offset -= (opt_clientid_advertise->len() - 1);
  1380. // Set client id.
  1381. boost::shared_ptr<LocalizedOption>
  1382. opt_clientid(new LocalizedOption(Option::V6, D6O_CLIENTID,
  1383. opt_clientid_advertise->getData(),
  1384. rand_offset));
  1385. pkt6->addOption(opt_clientid);
  1386. // Set default packet data.
  1387. setDefaults6(socket, pkt6);
  1388. // Prepare on wire data.
  1389. pkt6->rawPack();
  1390. // Send packet.
  1391. IfaceMgr::instance().send(pkt6);
  1392. if (!stats_mgr6_) {
  1393. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  1394. "hasn't been initialized");
  1395. }
  1396. // Update packet stats.
  1397. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_RR, pkt6);
  1398. }
  1399. void
  1400. TestControl::sendSolicit6(const TestControlSocket& socket,
  1401. const bool preload /*= false*/) {
  1402. last_sent_ = microsec_clock::universal_time();
  1403. // Generate DUID to be passed to the packet
  1404. uint8_t randomized = 0;
  1405. std::vector<uint8_t> duid = generateDuid(randomized);
  1406. // Generate trasnaction id to be set for the new exchange.
  1407. const uint32_t transid = generateTransid();
  1408. Pkt6Ptr pkt6(new Pkt6(DHCPV6_SOLICIT, transid));
  1409. if (!pkt6) {
  1410. isc_throw(Unexpected, "failed to create SOLICIT packet");
  1411. }
  1412. pkt6->addOption(Option::factory(Option::V6, D6O_ELAPSED_TIME));
  1413. if (CommandOptions::instance().isRapidCommit()) {
  1414. pkt6->addOption(Option::factory(Option::V6, D6O_RAPID_COMMIT));
  1415. }
  1416. pkt6->addOption(Option::factory(Option::V6, D6O_CLIENTID, duid));
  1417. pkt6->addOption(Option::factory(Option::V6, D6O_ORO));
  1418. pkt6->addOption(Option::factory(Option::V6, D6O_IA_NA));
  1419. setDefaults6(socket, pkt6);
  1420. pkt6->pack();
  1421. IfaceMgr::instance().send(pkt6);
  1422. if (!preload) {
  1423. if (!stats_mgr6_) {
  1424. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  1425. "hasn't been initialized");
  1426. }
  1427. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_SA, pkt6);
  1428. }
  1429. }
  1430. void
  1431. TestControl::sendSolicit6(const TestControlSocket& socket,
  1432. const std::vector<uint8_t>& template_buf,
  1433. const bool preload /*= false*/) {
  1434. last_sent_ = microsec_clock::universal_time();
  1435. CommandOptions& options = CommandOptions::instance();
  1436. const int arg_idx = 0;
  1437. // Get transaction id offset.
  1438. size_t transid_offset = DHCPV6_TRANSID_OFFSET;
  1439. if (options.getTransactionIdOffset().size() > arg_idx) {
  1440. transid_offset = options.getTransactionIdOffset()[arg_idx];
  1441. }
  1442. // Generate trasnaction id to be set for the new exchange.
  1443. const uint32_t transid = generateTransid();
  1444. // Create packet.
  1445. PerfPkt6Ptr pkt6(new PerfPkt6(&template_buf[0], template_buf.size(),
  1446. transid_offset, transid));
  1447. if (!pkt6) {
  1448. isc_throw(Unexpected, "failed to create SOLICIT packet");
  1449. }
  1450. size_t rand_offset = DHCPV6_RANDOMIZATION_OFFSET;
  1451. if (options.getRandomOffset().size() > arg_idx) {
  1452. rand_offset = options.getRandomOffset()[arg_idx];
  1453. }
  1454. // randomized will pick number of bytes randomized so we can
  1455. // just use part of the generated duid and substitude a few bytes
  1456. /// in template.
  1457. uint8_t randomized = 0;
  1458. std::vector<uint8_t> duid = generateDuid(randomized);
  1459. if (rand_offset > template_buf.size()) {
  1460. isc_throw(OutOfRange, "randomization offset is out of bounds");
  1461. }
  1462. // Store random part of the DUID into the packet.
  1463. pkt6->writeAt(rand_offset - randomized + 1,
  1464. duid.end() - randomized, duid.end());
  1465. // Prepare on-wire data.
  1466. pkt6->rawPack();
  1467. setDefaults6(socket, pkt6);
  1468. // Send solicit packet.
  1469. IfaceMgr::instance().send(pkt6);
  1470. if (!preload) {
  1471. if (!stats_mgr6_) {
  1472. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  1473. "hasn't been initialized");
  1474. }
  1475. // Update packet stats.
  1476. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_SA, pkt6);
  1477. }
  1478. }
  1479. void
  1480. TestControl::setDefaults4(const TestControlSocket& socket,
  1481. const Pkt4Ptr& pkt) {
  1482. CommandOptions& options = CommandOptions::instance();
  1483. // Interface name.
  1484. IfaceMgr::Iface* iface = IfaceMgr::instance().getIface(socket.ifindex_);
  1485. if (iface == NULL) {
  1486. isc_throw(BadValue, "unable to find interface with given index");
  1487. }
  1488. pkt->setIface(iface->getName());
  1489. // Interface index.
  1490. pkt->setIndex(socket.ifindex_);
  1491. // Local client's port (68)
  1492. pkt->setLocalPort(DHCP4_CLIENT_PORT);
  1493. // Server's port (67)
  1494. pkt->setRemotePort(DHCP4_SERVER_PORT);
  1495. // The remote server's name or IP.
  1496. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  1497. // Set local addresss.
  1498. pkt->setLocalAddr(IOAddress(socket.addr_));
  1499. // Set relay (GIADDR) address to local address.
  1500. pkt->setGiaddr(IOAddress(socket.addr_));
  1501. // Pretend that we have one relay (which is us).
  1502. pkt->setHops(1);
  1503. }
  1504. void
  1505. TestControl::setDefaults6(const TestControlSocket& socket,
  1506. const Pkt6Ptr& pkt) {
  1507. CommandOptions& options = CommandOptions::instance();
  1508. // Interface name.
  1509. IfaceMgr::Iface* iface = IfaceMgr::instance().getIface(socket.ifindex_);
  1510. if (iface == NULL) {
  1511. isc_throw(BadValue, "unable to find interface with given index");
  1512. }
  1513. pkt->setIface(iface->getName());
  1514. // Interface index.
  1515. pkt->setIndex(socket.ifindex_);
  1516. // Local client's port (547)
  1517. pkt->setLocalPort(DHCP6_CLIENT_PORT);
  1518. // Server's port (548)
  1519. pkt->setRemotePort(DHCP6_SERVER_PORT);
  1520. // Set local address.
  1521. pkt->setLocalAddr(socket.addr_);
  1522. // The remote server's name or IP.
  1523. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  1524. }
  1525. bool
  1526. TestControl::testDiags(const char diag) const {
  1527. std::string diags(CommandOptions::instance().getDiags());
  1528. if (diags.find(diag) != std::string::npos) {
  1529. return (true);
  1530. }
  1531. return (false);
  1532. }
  1533. void
  1534. TestControl::updateSendDue() {
  1535. // If default constructor was called, this should not happen but
  1536. // if somebody has changed default constructor it is better to
  1537. // keep this check.
  1538. if (last_sent_.is_not_a_date_time()) {
  1539. isc_throw(Unexpected, "time of last sent packet not initialized");
  1540. }
  1541. // Get the expected exchange rate.
  1542. CommandOptions& options = CommandOptions::instance();
  1543. int rate = options.getRate();
  1544. // If rate was not specified we will wait just one clock tick to
  1545. // send next packet. This simulates best effort conditions.
  1546. long duration = 1;
  1547. if (rate != 0) {
  1548. // We use number of ticks instead of nanoseconds because
  1549. // nanosecond resolution may not be available on some
  1550. // machines. Number of ticks guarantees the highest possible
  1551. // timer resolution.
  1552. duration = time_duration::ticks_per_second() / rate;
  1553. }
  1554. // Calculate due time to initate next chunk of exchanges.
  1555. send_due_ = last_sent_ + time_duration(0, 0, 0, duration);
  1556. // Check if it is already due.
  1557. ptime now(microsec_clock::universal_time());
  1558. // \todo verify if this condition is not too tight. In other words
  1559. // verify if this will not produce too many late sends.
  1560. // We might want to look at this once we are done implementing
  1561. // microsecond timeouts in IfaceMgr.
  1562. if (now > send_due_) {
  1563. if (testDiags('i')) {
  1564. if (options.getIpVersion() == 4) {
  1565. stats_mgr4_->incrementCounter("latesend");
  1566. } else if (options.getIpVersion() == 6) {
  1567. stats_mgr6_->incrementCounter("latesend");
  1568. }
  1569. }
  1570. }
  1571. }
  1572. } // namespace perfdhcp
  1573. } // namespace isc