test_control.cc 71 KB

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