test_control.cc 71 KB

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