test_control.cc 82 KB

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