test_control.cc 64 KB

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