test_control.cc 64 KB

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