test_control.cc 83 KB

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