test_control.cc 79 KB

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