test_control.cc 71 KB

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