test_control.cc 70 KB

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