test_control.cc 73 KB

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