test_control.cc 70 KB

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