test_control.cc 70 KB

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