test_control.cc 83 KB

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