test_control.cc 73 KB

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