test_control.cc 65 KB

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