test_control.cc 71 KB

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