test_control.cc 76 KB

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