test_control.cc 80 KB

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