test_control.cc 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  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. transid_gen_.reset();
  1206. // Actual generators will have to be set later on because we need to
  1207. // get command line parameters first.
  1208. setTransidGenerator(NumberGeneratorPtr());
  1209. setMacAddrGenerator(NumberGeneratorPtr());
  1210. first_packet_serverid_.clear();
  1211. interrupted_ = false;
  1212. }
  1213. int
  1214. TestControl::run() {
  1215. // Reset singleton state before test starts.
  1216. reset();
  1217. CommandOptions& options = CommandOptions::instance();
  1218. // Ip version is not set ONLY in case the command options
  1219. // were not parsed. This surely means that parse() function
  1220. // was not called prior to starting the test. This is fatal
  1221. // error.
  1222. if (options.getIpVersion() == 0) {
  1223. isc_throw(InvalidOperation,
  1224. "command options must be parsed before running a test");
  1225. } else if (options.getIpVersion() == 4) {
  1226. setTransidGenerator(NumberGeneratorPtr(new SequentialGenerator()));
  1227. } else {
  1228. setTransidGenerator(NumberGeneratorPtr(new SequentialGenerator(0x00FFFFFF)));
  1229. }
  1230. uint32_t clients_num = options.getClientsNum() == 0 ?
  1231. 1 : options.getClientsNum();
  1232. setMacAddrGenerator(NumberGeneratorPtr(new SequentialGenerator(clients_num)));
  1233. // Diagnostics are command line options mainly.
  1234. printDiagnostics();
  1235. // Option factories have to be registered.
  1236. registerOptionFactories();
  1237. TestControlSocket socket(openSocket());
  1238. if (!socket.valid_) {
  1239. isc_throw(Unexpected, "invalid socket descriptor");
  1240. }
  1241. // Initialize packet templates.
  1242. initPacketTemplates();
  1243. // Initialize randomization seed.
  1244. if (options.isSeeded()) {
  1245. srandom(options.getSeed());
  1246. } else {
  1247. // Seed with current time.
  1248. time_period duration(from_iso_string("20111231T235959"),
  1249. microsec_clock::universal_time());
  1250. srandom(duration.length().total_seconds()
  1251. + duration.length().fractional_seconds());
  1252. }
  1253. // If user interrupts the program we will exit gracefully.
  1254. signal(SIGINT, TestControl::handleInterrupt);
  1255. // Preload server with the number of packets.
  1256. sendPackets(socket, options.getPreload(), true);
  1257. // Fork and run command specified with -w<wrapped-command>
  1258. if (!options.getWrapped().empty()) {
  1259. runWrapped();
  1260. }
  1261. // Initialize Statistics Manager. Release previous if any.
  1262. initializeStatsMgr();
  1263. for (;;) {
  1264. // Calculate send due based on when last exchange was initiated.
  1265. updateSendDue(last_sent_, options.getRate(), send_due_);
  1266. // Calculate number of packets to be sent to stay
  1267. // catch up with rate.
  1268. uint64_t packets_due = getNextExchangesNum(send_due_, options.getRate());
  1269. if ((packets_due == 0) && testDiags('i')) {
  1270. if (options.getIpVersion() == 4) {
  1271. stats_mgr4_->incrementCounter("shortwait");
  1272. } else if (options.getIpVersion() == 6) {
  1273. stats_mgr6_->incrementCounter("shortwait");
  1274. }
  1275. }
  1276. // @todo: set non-zero timeout for packets once we implement
  1277. // microseconds timeout in IfaceMgr.
  1278. receivePackets(socket);
  1279. // If test period finished, maximum number of packet drops
  1280. // has been reached or test has been interrupted we have to
  1281. // finish the test.
  1282. if (checkExitConditions()) {
  1283. break;
  1284. }
  1285. // Initiate new DHCP packet exchanges.
  1286. sendPackets(socket, packets_due);
  1287. // If -f<renew-rate> option was specified we have to check how many
  1288. // Renew packets should be sent to catch up with a desired rate.
  1289. if ((options.getIpVersion() == 6) && (options.getRenewRate() != 0)) {
  1290. updateSendDue(last_renew_, options.getRenewRate(), renew_due_);
  1291. uint64_t renew_packets_due =
  1292. getNextExchangesNum(renew_due_, options.getRenewRate());
  1293. // Send Renew messages.
  1294. sendMultipleMessages6(socket, DHCPV6_RENEW, renew_packets_due);
  1295. }
  1296. // If -F<release-rate> option was specified we have to check how many
  1297. // Release messages should be sent to catch up with a desired rate.
  1298. if ((options.getIpVersion() == 6) && (options.getReleaseRate() != 0)) {
  1299. updateSendDue(last_release_, options.getReleaseRate(),
  1300. release_due_);
  1301. uint64_t release_packets_due =
  1302. getNextExchangesNum(release_due_, options.getReleaseRate());
  1303. // Send Release messages.
  1304. sendMultipleMessages6(socket, DHCPV6_RELEASE, release_packets_due);
  1305. }
  1306. // Report delay means that user requested printing number
  1307. // of sent/received/dropped packets repeatedly.
  1308. if (options.getReportDelay() > 0) {
  1309. printIntermediateStats();
  1310. }
  1311. // If we are sending Renews to the server, the Reply packets are cached
  1312. // so as leases for which we send Renews can be idenitfied. The major
  1313. // issue with this approach is that most of the time we are caching
  1314. // more packets than we actually need. This function removes excessive
  1315. // Reply messages to reduce the memory and CPU utilization. Note that
  1316. // searches in the long list of Reply packets increases CPU utilization.
  1317. cleanCachedPackets();
  1318. }
  1319. printStats();
  1320. if (!options.getWrapped().empty()) {
  1321. // true means that we execute wrapped command with 'stop' argument.
  1322. runWrapped(true);
  1323. }
  1324. // Print packet timestamps
  1325. if (testDiags('t')) {
  1326. if (options.getIpVersion() == 4) {
  1327. stats_mgr4_->printTimestamps();
  1328. } else if (options.getIpVersion() == 6) {
  1329. stats_mgr6_->printTimestamps();
  1330. }
  1331. }
  1332. // Print server id.
  1333. if (testDiags('s') && (first_packet_serverid_.size() > 0)) {
  1334. std::cout << "Server id: " << vector2Hex(first_packet_serverid_) << std::endl;
  1335. }
  1336. // Diagnostics flag 'e' means show exit reason.
  1337. if (testDiags('e')) {
  1338. std::cout << "Interrupted" << std::endl;
  1339. }
  1340. // Print packet templates. Even if -T options have not been specified the
  1341. // dynamically build packet will be printed if at least one has been sent.
  1342. if (testDiags('T')) {
  1343. printTemplates();
  1344. }
  1345. int ret_code = 0;
  1346. // Check if any packet drops occured.
  1347. if (options.getIpVersion() == 4) {
  1348. ret_code = stats_mgr4_->droppedPackets() ? 3 : 0;
  1349. } else if (options.getIpVersion() == 6) {
  1350. ret_code = stats_mgr6_->droppedPackets() ? 3 : 0;
  1351. }
  1352. return (ret_code);
  1353. }
  1354. void
  1355. TestControl::runWrapped(bool do_stop /*= false */) const {
  1356. CommandOptions& options = CommandOptions::instance();
  1357. if (!options.getWrapped().empty()) {
  1358. pid_t pid = 0;
  1359. signal(SIGCHLD, handleChild);
  1360. pid = fork();
  1361. if (pid < 0) {
  1362. isc_throw(Unexpected, "unable to fork");
  1363. } else if (pid == 0) {
  1364. execlp(options.getWrapped().c_str(),
  1365. do_stop ? "stop" : "start",
  1366. NULL);
  1367. }
  1368. }
  1369. }
  1370. void
  1371. TestControl::saveFirstPacket(const Pkt4Ptr& pkt) {
  1372. if (testDiags('T')) {
  1373. if (template_packets_v4_.find(pkt->getType()) == template_packets_v4_.end()) {
  1374. template_packets_v4_[pkt->getType()] = pkt;
  1375. }
  1376. }
  1377. }
  1378. void
  1379. TestControl::saveFirstPacket(const Pkt6Ptr& pkt) {
  1380. if (testDiags('T')) {
  1381. if (template_packets_v6_.find(pkt->getType()) == template_packets_v6_.end()) {
  1382. template_packets_v6_[pkt->getType()] = pkt;
  1383. }
  1384. }
  1385. }
  1386. void
  1387. TestControl::sendDiscover4(const TestControlSocket& socket,
  1388. const bool preload /*= false*/) {
  1389. last_sent_ = microsec_clock::universal_time();
  1390. // Generate the MAC address to be passed in the packet.
  1391. uint8_t randomized = 0;
  1392. std::vector<uint8_t> mac_address = generateMacAddress(randomized);
  1393. // Generate trasnaction id to be set for the new exchange.
  1394. const uint32_t transid = generateTransid();
  1395. Pkt4Ptr pkt4(new Pkt4(DHCPDISCOVER, transid));
  1396. if (!pkt4) {
  1397. isc_throw(Unexpected, "failed to create DISCOVER packet");
  1398. }
  1399. // Delete the default Message Type option set by Pkt4
  1400. pkt4->delOption(DHO_DHCP_MESSAGE_TYPE);
  1401. // Set options: DHCP_MESSAGE_TYPE and DHCP_PARAMETER_REQUEST_LIST
  1402. OptionBuffer buf_msg_type;
  1403. buf_msg_type.push_back(DHCPDISCOVER);
  1404. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  1405. buf_msg_type));
  1406. pkt4->addOption(Option::factory(Option::V4,
  1407. DHO_DHCP_PARAMETER_REQUEST_LIST));
  1408. // Set client's and server's ports as well as server's address,
  1409. // and local (relay) address.
  1410. setDefaults4(socket, pkt4);
  1411. // Set hardware address
  1412. pkt4->setHWAddr(HTYPE_ETHER, mac_address.size(), mac_address);
  1413. pkt4->pack();
  1414. IfaceMgr::instance().send(pkt4);
  1415. if (!preload) {
  1416. if (!stats_mgr4_) {
  1417. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  1418. "hasn't been initialized");
  1419. }
  1420. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_DO, pkt4);
  1421. }
  1422. saveFirstPacket(pkt4);
  1423. }
  1424. void
  1425. TestControl::sendDiscover4(const TestControlSocket& socket,
  1426. const std::vector<uint8_t>& template_buf,
  1427. const bool preload /* = false */) {
  1428. // last_sent_ has to be updated for each function that initiates
  1429. // new transaction. The packet exchange synchronization relies on this.
  1430. last_sent_ = microsec_clock::universal_time();
  1431. // Get the first argument if mulitple the same arguments specified
  1432. // in the command line. First one refers to DISCOVER packets.
  1433. const uint8_t arg_idx = 0;
  1434. // Generate the MAC address to be passed in the packet.
  1435. uint8_t randomized = 0;
  1436. std::vector<uint8_t> mac_address = generateMacAddress(randomized);
  1437. // Generate trasnaction id to be set for the new exchange.
  1438. const uint32_t transid = generateTransid();
  1439. // Get transaction id offset.
  1440. size_t transid_offset = getTransactionIdOffset(arg_idx);
  1441. // Get randomization offset.
  1442. // We need to go back by HW_ETHER_LEN (MAC address length)
  1443. // because this offset points to last octet of MAC address.
  1444. size_t rand_offset = getRandomOffset(arg_idx) - HW_ETHER_LEN + 1;
  1445. // Create temporary buffer with template contents. We will
  1446. // modify this temporary buffer but we don't want to modify
  1447. // the original template.
  1448. std::vector<uint8_t> in_buf(template_buf.begin(),
  1449. template_buf.end());
  1450. // Check if we are not going out of bounds.
  1451. if (rand_offset + HW_ETHER_LEN > in_buf.size()) {
  1452. isc_throw(OutOfRange, "randomization offset is out of bounds");
  1453. }
  1454. PerfPkt4Ptr pkt4(new PerfPkt4(&in_buf[0], in_buf.size(),
  1455. transid_offset,
  1456. transid));
  1457. // Replace MAC address in the template with actual MAC address.
  1458. pkt4->writeAt(rand_offset, mac_address.begin(), mac_address.end());
  1459. // Create a packet from the temporary buffer.
  1460. setDefaults4(socket, boost::static_pointer_cast<Pkt4>(pkt4));
  1461. // Pack the input packet buffer to output buffer so as it can
  1462. // be sent to server.
  1463. pkt4->rawPack();
  1464. IfaceMgr::instance().send(boost::static_pointer_cast<Pkt4>(pkt4));
  1465. if (!preload) {
  1466. if (!stats_mgr4_) {
  1467. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  1468. "hasn't been initialized");
  1469. }
  1470. // Update packet stats.
  1471. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_DO,
  1472. boost::static_pointer_cast<Pkt4>(pkt4));
  1473. }
  1474. saveFirstPacket(pkt4);
  1475. }
  1476. bool
  1477. TestControl::sendMessageFromReply(const uint16_t msg_type,
  1478. const TestControlSocket& socket) {
  1479. // We only permit Release or Renew messages to be sent using this function.
  1480. if (msg_type != DHCPV6_RENEW && msg_type != DHCPV6_RELEASE) {
  1481. isc_throw(isc::BadValue, "invalid message type " << msg_type
  1482. << " to be sent, expected DHCPV6_RENEW or DHCPV6_RELEASE");
  1483. }
  1484. // We track the timestamp of last Release and Renew in different variables.
  1485. if (msg_type == DHCPV6_RENEW) {
  1486. last_renew_ = microsec_clock::universal_time();
  1487. } else {
  1488. last_release_ = microsec_clock::universal_time();
  1489. }
  1490. Pkt6Ptr reply = reply_storage_.getRandom();
  1491. if (!reply) {
  1492. return (false);
  1493. }
  1494. // Prepare the message of the specified type.
  1495. Pkt6Ptr msg = createMessageFromReply(msg_type, reply);
  1496. setDefaults6(socket, msg);
  1497. msg->pack();
  1498. // And send it.
  1499. IfaceMgr::instance().send(msg);
  1500. if (!stats_mgr6_) {
  1501. isc_throw(Unexpected, "Statistics Manager for DHCPv6 "
  1502. "hasn't been initialized");
  1503. }
  1504. stats_mgr6_->passSentPacket((msg_type == DHCPV6_RENEW ? StatsMgr6::XCHG_RN
  1505. : StatsMgr6::XCHG_RL), msg);
  1506. return (true);
  1507. }
  1508. void
  1509. TestControl::sendRequest4(const TestControlSocket& socket,
  1510. const dhcp::Pkt4Ptr& discover_pkt4,
  1511. const dhcp::Pkt4Ptr& offer_pkt4) {
  1512. const uint32_t transid = generateTransid();
  1513. Pkt4Ptr pkt4(new Pkt4(DHCPREQUEST, transid));
  1514. // Use first flags indicates that we want to use the server
  1515. // id captured in first packet.
  1516. if (CommandOptions::instance().isUseFirst() &&
  1517. (first_packet_serverid_.size() > 0)) {
  1518. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_SERVER_IDENTIFIER,
  1519. first_packet_serverid_));
  1520. } else {
  1521. OptionPtr opt_serverid =
  1522. offer_pkt4->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1523. if (!opt_serverid) {
  1524. isc_throw(BadValue, "there is no SERVER_IDENTIFIER option "
  1525. << "in OFFER message");
  1526. }
  1527. if (stats_mgr4_->getRcvdPacketsNum(StatsMgr4::XCHG_DO) == 1) {
  1528. first_packet_serverid_ = opt_serverid->getData();
  1529. }
  1530. pkt4->addOption(opt_serverid);
  1531. }
  1532. /// Set client address.
  1533. asiolink::IOAddress yiaddr = offer_pkt4->getYiaddr();
  1534. if (!yiaddr.getAddress().is_v4()) {
  1535. isc_throw(BadValue, "the YIADDR returned in OFFER packet is not "
  1536. " IPv4 address");
  1537. }
  1538. OptionPtr opt_requested_address =
  1539. OptionPtr(new Option(Option::V4, DHO_DHCP_REQUESTED_ADDRESS,
  1540. OptionBuffer()));
  1541. opt_requested_address->setUint32(static_cast<uint32_t>(yiaddr));
  1542. pkt4->addOption(opt_requested_address);
  1543. OptionPtr opt_parameter_list =
  1544. Option::factory(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST);
  1545. pkt4->addOption(opt_parameter_list);
  1546. // Set client's and server's ports as well as server's address,
  1547. // and local (relay) address.
  1548. setDefaults4(socket, pkt4);
  1549. // Set hardware address
  1550. pkt4->setHWAddr(offer_pkt4->getHWAddr());
  1551. // Set elapsed time.
  1552. uint32_t elapsed_time = getElapsedTime<Pkt4Ptr>(discover_pkt4, offer_pkt4);
  1553. pkt4->setSecs(static_cast<uint16_t>(elapsed_time / 1000));
  1554. // Prepare on wire data to send.
  1555. pkt4->pack();
  1556. IfaceMgr::instance().send(pkt4);
  1557. if (!stats_mgr4_) {
  1558. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  1559. "hasn't been initialized");
  1560. }
  1561. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_RA, pkt4);
  1562. saveFirstPacket(pkt4);
  1563. }
  1564. void
  1565. TestControl::sendRequest4(const TestControlSocket& socket,
  1566. const std::vector<uint8_t>& template_buf,
  1567. const dhcp::Pkt4Ptr& discover_pkt4,
  1568. const dhcp::Pkt4Ptr& offer_pkt4) {
  1569. // Get the second argument if multiple the same arguments specified
  1570. // in the command line. Second one refers to REQUEST packets.
  1571. const uint8_t arg_idx = 1;
  1572. // Generate new transaction id.
  1573. const uint32_t transid = generateTransid();
  1574. // Get transaction id offset.
  1575. size_t transid_offset = getTransactionIdOffset(arg_idx);
  1576. // Get the offset of MAC's last octet.
  1577. // We need to go back by HW_ETHER_LEN (MAC address length)
  1578. // because this offset points to last octet of MAC address.
  1579. size_t rand_offset = getRandomOffset(arg_idx) - HW_ETHER_LEN + 1;
  1580. // Create temporaru buffer from the template.
  1581. std::vector<uint8_t> in_buf(template_buf.begin(),
  1582. template_buf.end());
  1583. // Check if given randomization offset is not out of bounds.
  1584. if (rand_offset + HW_ETHER_LEN > in_buf.size()) {
  1585. isc_throw(OutOfRange, "randomization offset is out of bounds");
  1586. }
  1587. // Create packet from the temporary buffer.
  1588. PerfPkt4Ptr pkt4(new PerfPkt4(&in_buf[0], in_buf.size(),
  1589. transid_offset,
  1590. transid));
  1591. // Set hardware address from OFFER packet received.
  1592. HWAddrPtr hwaddr = offer_pkt4->getHWAddr();
  1593. std::vector<uint8_t> mac_address(HW_ETHER_LEN, 0);
  1594. uint8_t hw_len = hwaddr->hwaddr_.size();
  1595. memcpy(&mac_address[0], &hwaddr->hwaddr_[0], hw_len > 16 ? 16 : hw_len);
  1596. pkt4->writeAt(rand_offset, mac_address.begin(), mac_address.end());
  1597. // Set elapsed time.
  1598. size_t elp_offset = getElapsedTimeOffset();
  1599. uint32_t elapsed_time = getElapsedTime<Pkt4Ptr>(discover_pkt4, offer_pkt4);
  1600. pkt4->writeValueAt<uint16_t>(elp_offset,
  1601. static_cast<uint16_t>(elapsed_time / 1000));
  1602. // Get the actual server id offset.
  1603. size_t sid_offset = getServerIdOffset();
  1604. // Use first flags indicates that we want to use the server
  1605. // id captured in first packet.
  1606. if (CommandOptions::instance().isUseFirst() &&
  1607. (first_packet_serverid_.size() > 0)) {
  1608. boost::shared_ptr<LocalizedOption>
  1609. opt_serverid(new LocalizedOption(Option::V4,
  1610. DHO_DHCP_SERVER_IDENTIFIER,
  1611. first_packet_serverid_,
  1612. sid_offset));
  1613. pkt4->addOption(opt_serverid);
  1614. } else {
  1615. // Copy the contents of server identifier received in
  1616. // OFFER packet to put this into REQUEST.
  1617. OptionPtr opt_serverid_offer =
  1618. offer_pkt4->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1619. if (!opt_serverid_offer) {
  1620. isc_throw(BadValue, "there is no SERVER_IDENTIFIER option "
  1621. << "in OFFER message");
  1622. }
  1623. boost::shared_ptr<LocalizedOption>
  1624. opt_serverid(new LocalizedOption(Option::V4,
  1625. DHO_DHCP_SERVER_IDENTIFIER,
  1626. opt_serverid_offer->getData(),
  1627. sid_offset));
  1628. pkt4->addOption(opt_serverid);
  1629. if (stats_mgr4_->getRcvdPacketsNum(StatsMgr4::XCHG_DO) == 1) {
  1630. first_packet_serverid_ = opt_serverid_offer->getData();
  1631. }
  1632. }
  1633. /// Set client address.
  1634. asiolink::IOAddress yiaddr = offer_pkt4->getYiaddr();
  1635. if (!yiaddr.getAddress().is_v4()) {
  1636. isc_throw(BadValue, "the YIADDR returned in OFFER packet is not "
  1637. " IPv4 address");
  1638. }
  1639. // Get the actual offset of requested ip.
  1640. size_t rip_offset = getRequestedIpOffset();
  1641. // Place requested IP option at specified position (rip_offset).
  1642. boost::shared_ptr<LocalizedOption>
  1643. opt_requested_ip(new LocalizedOption(Option::V4,
  1644. DHO_DHCP_REQUESTED_ADDRESS,
  1645. OptionBuffer(),
  1646. rip_offset));
  1647. // The IOAddress is castable to uint32_t and returns exactly what we need.
  1648. opt_requested_ip->setUint32(static_cast<uint32_t>(yiaddr));
  1649. pkt4->addOption(opt_requested_ip);
  1650. setDefaults4(socket, boost::static_pointer_cast<Pkt4>(pkt4));
  1651. // Prepare on-wire data.
  1652. pkt4->rawPack();
  1653. IfaceMgr::instance().send(boost::static_pointer_cast<Pkt4>(pkt4));
  1654. if (!stats_mgr4_) {
  1655. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  1656. "hasn't been initialized");
  1657. }
  1658. // Update packet stats.
  1659. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_RA,
  1660. boost::static_pointer_cast<Pkt4>(pkt4));
  1661. saveFirstPacket(pkt4);
  1662. }
  1663. void
  1664. TestControl::sendRequest6(const TestControlSocket& socket,
  1665. const Pkt6Ptr& advertise_pkt6) {
  1666. const uint32_t transid = generateTransid();
  1667. Pkt6Ptr pkt6(new Pkt6(DHCPV6_REQUEST, transid));
  1668. // Set elapsed time.
  1669. OptionPtr opt_elapsed_time =
  1670. Option::factory(Option::V6, D6O_ELAPSED_TIME);
  1671. pkt6->addOption(opt_elapsed_time);
  1672. // Set client id.
  1673. OptionPtr opt_clientid = advertise_pkt6->getOption(D6O_CLIENTID);
  1674. if (!opt_clientid) {
  1675. isc_throw(Unexpected, "client id not found in received packet");
  1676. }
  1677. pkt6->addOption(opt_clientid);
  1678. // Use first flags indicates that we want to use the server
  1679. // id captured in first packet.
  1680. if (CommandOptions::instance().isUseFirst() &&
  1681. (first_packet_serverid_.size() > 0)) {
  1682. pkt6->addOption(Option::factory(Option::V6, D6O_SERVERID,
  1683. first_packet_serverid_));
  1684. } else {
  1685. OptionPtr opt_serverid = advertise_pkt6->getOption(D6O_SERVERID);
  1686. if (!opt_serverid) {
  1687. isc_throw(Unexpected, "server id not found in received packet");
  1688. }
  1689. if (stats_mgr6_->getRcvdPacketsNum(StatsMgr6::XCHG_SA) == 1) {
  1690. first_packet_serverid_ = opt_serverid->getData();
  1691. }
  1692. pkt6->addOption(opt_serverid);
  1693. }
  1694. // Copy IA_NA or IA_PD option from the Advertise message to the Request
  1695. // message being sent to the server. This will throw exception if the
  1696. // option to be copied is not found. Note that this function will copy
  1697. // one of IA_NA or IA_PD options, depending on the lease-type value
  1698. // specified in the command line.
  1699. copyIaOptions(advertise_pkt6, pkt6);
  1700. // Set default packet data.
  1701. setDefaults6(socket, pkt6);
  1702. // Prepare on-wire data.
  1703. pkt6->pack();
  1704. IfaceMgr::instance().send(pkt6);
  1705. if (!stats_mgr6_) {
  1706. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  1707. "hasn't been initialized");
  1708. }
  1709. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_RR, pkt6);
  1710. saveFirstPacket(pkt6);
  1711. }
  1712. void
  1713. TestControl::sendRequest6(const TestControlSocket& socket,
  1714. const std::vector<uint8_t>& template_buf,
  1715. const Pkt6Ptr& advertise_pkt6) {
  1716. // Get the second argument if multiple the same arguments specified
  1717. // in the command line. Second one refers to REQUEST packets.
  1718. const uint8_t arg_idx = 1;
  1719. // Generate transaction id.
  1720. const uint32_t transid = generateTransid();
  1721. // Get transaction id offset.
  1722. size_t transid_offset = getTransactionIdOffset(arg_idx);
  1723. PerfPkt6Ptr pkt6(new PerfPkt6(&template_buf[0], template_buf.size(),
  1724. transid_offset, transid));
  1725. // Set elapsed time.
  1726. size_t elp_offset = getElapsedTimeOffset();
  1727. boost::shared_ptr<LocalizedOption>
  1728. opt_elapsed_time(new LocalizedOption(Option::V6, D6O_ELAPSED_TIME,
  1729. OptionBuffer(), elp_offset));
  1730. pkt6->addOption(opt_elapsed_time);
  1731. // Get the actual server id offset.
  1732. size_t sid_offset = getServerIdOffset();
  1733. // Use first flags indicates that we want to use the server
  1734. // id captured in first packet.
  1735. if (CommandOptions::instance().isUseFirst() &&
  1736. (first_packet_serverid_.size() > 0)) {
  1737. boost::shared_ptr<LocalizedOption>
  1738. opt_serverid(new LocalizedOption(Option::V6,
  1739. D6O_SERVERID,
  1740. first_packet_serverid_,
  1741. sid_offset));
  1742. pkt6->addOption(opt_serverid);
  1743. } else {
  1744. // Copy the contents of server identifier received in
  1745. // ADVERTISE packet to put this into REQUEST.
  1746. OptionPtr opt_serverid_advertise =
  1747. advertise_pkt6->getOption(D6O_SERVERID);
  1748. if (!opt_serverid_advertise) {
  1749. isc_throw(BadValue, "there is no SERVERID option "
  1750. << "in ADVERTISE message");
  1751. }
  1752. boost::shared_ptr<LocalizedOption>
  1753. opt_serverid(new LocalizedOption(Option::V6,
  1754. D6O_SERVERID,
  1755. opt_serverid_advertise->getData(),
  1756. sid_offset));
  1757. pkt6->addOption(opt_serverid);
  1758. if (stats_mgr6_->getRcvdPacketsNum(StatsMgr6::XCHG_SA) == 1) {
  1759. first_packet_serverid_ = opt_serverid_advertise->getData();
  1760. }
  1761. }
  1762. // Set IA_NA
  1763. boost::shared_ptr<Option6IA> opt_ia_na_advertise =
  1764. boost::static_pointer_cast<Option6IA>(advertise_pkt6->getOption(D6O_IA_NA));
  1765. if (!opt_ia_na_advertise) {
  1766. isc_throw(Unexpected, "DHCPv6 IA_NA option not found in received "
  1767. "packet");
  1768. }
  1769. size_t addr_offset = getRequestedIpOffset();
  1770. boost::shared_ptr<LocalizedOption>
  1771. opt_ia_na(new LocalizedOption(opt_ia_na_advertise, addr_offset));
  1772. if (!opt_ia_na->valid()) {
  1773. isc_throw(BadValue, "Option IA_NA in advertise packet is invalid");
  1774. }
  1775. pkt6->addOption(opt_ia_na);
  1776. // Set server id.
  1777. OptionPtr opt_serverid_advertise = advertise_pkt6->getOption(D6O_SERVERID);
  1778. if (!opt_serverid_advertise) {
  1779. isc_throw(Unexpected, "DHCPV6 SERVERID option not found in received "
  1780. "packet");
  1781. }
  1782. size_t srvid_offset = getServerIdOffset();
  1783. boost::shared_ptr<LocalizedOption>
  1784. opt_serverid(new LocalizedOption(Option::V6, D6O_SERVERID,
  1785. opt_serverid_advertise->getData(),
  1786. srvid_offset));
  1787. pkt6->addOption(opt_serverid);
  1788. // Get randomization offset.
  1789. size_t rand_offset = getRandomOffset(arg_idx);
  1790. OptionPtr opt_clientid_advertise = advertise_pkt6->getOption(D6O_CLIENTID);
  1791. if (!opt_clientid_advertise) {
  1792. isc_throw(Unexpected, "DHCPV6 CLIENTID option not found in received packet");
  1793. }
  1794. rand_offset -= (opt_clientid_advertise->len() - 1);
  1795. // Set client id.
  1796. boost::shared_ptr<LocalizedOption>
  1797. opt_clientid(new LocalizedOption(Option::V6, D6O_CLIENTID,
  1798. opt_clientid_advertise->getData(),
  1799. rand_offset));
  1800. pkt6->addOption(opt_clientid);
  1801. // Set default packet data.
  1802. setDefaults6(socket, pkt6);
  1803. // Prepare on wire data.
  1804. pkt6->rawPack();
  1805. // Send packet.
  1806. IfaceMgr::instance().send(pkt6);
  1807. if (!stats_mgr6_) {
  1808. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  1809. "hasn't been initialized");
  1810. }
  1811. // Update packet stats.
  1812. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_RR, pkt6);
  1813. // When 'T' diagnostics flag is specified it means that user requested
  1814. // printing packet contents. It will be just one (first) packet which
  1815. // contents will be printed. Here we check if this packet has been already
  1816. // collected. If it hasn't we save this packet so as we can print its
  1817. // contents when test is finished.
  1818. if (testDiags('T') &&
  1819. (template_packets_v6_.find(DHCPV6_REQUEST) == template_packets_v6_.end())) {
  1820. template_packets_v6_[DHCPV6_REQUEST] = pkt6;
  1821. }
  1822. }
  1823. void
  1824. TestControl::sendSolicit6(const TestControlSocket& socket,
  1825. const bool preload /*= false*/) {
  1826. last_sent_ = microsec_clock::universal_time();
  1827. // Generate DUID to be passed to the packet
  1828. uint8_t randomized = 0;
  1829. std::vector<uint8_t> duid = generateDuid(randomized);
  1830. // Generate trasnaction id to be set for the new exchange.
  1831. const uint32_t transid = generateTransid();
  1832. Pkt6Ptr pkt6(new Pkt6(DHCPV6_SOLICIT, transid));
  1833. if (!pkt6) {
  1834. isc_throw(Unexpected, "failed to create SOLICIT packet");
  1835. }
  1836. pkt6->addOption(Option::factory(Option::V6, D6O_ELAPSED_TIME));
  1837. if (CommandOptions::instance().isRapidCommit()) {
  1838. pkt6->addOption(Option::factory(Option::V6, D6O_RAPID_COMMIT));
  1839. }
  1840. pkt6->addOption(Option::factory(Option::V6, D6O_CLIENTID, duid));
  1841. pkt6->addOption(Option::factory(Option::V6, D6O_ORO));
  1842. // Depending on the lease-type option specified, we should request
  1843. // IPv6 address (with IA_NA) or IPv6 prefix (IA_PD) or both.
  1844. // IA_NA
  1845. if (CommandOptions::instance().getLeaseType()
  1846. .includes(CommandOptions::LeaseType::ADDRESS)) {
  1847. pkt6->addOption(Option::factory(Option::V6, D6O_IA_NA));
  1848. }
  1849. // IA_PD
  1850. if (CommandOptions::instance().getLeaseType()
  1851. .includes(CommandOptions::LeaseType::PREFIX)) {
  1852. pkt6->addOption(Option::factory(Option::V6, D6O_IA_PD));
  1853. }
  1854. setDefaults6(socket, pkt6);
  1855. pkt6->pack();
  1856. IfaceMgr::instance().send(pkt6);
  1857. if (!preload) {
  1858. if (!stats_mgr6_) {
  1859. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  1860. "hasn't been initialized");
  1861. }
  1862. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_SA, pkt6);
  1863. }
  1864. saveFirstPacket(pkt6);
  1865. }
  1866. void
  1867. TestControl::sendSolicit6(const TestControlSocket& socket,
  1868. const std::vector<uint8_t>& template_buf,
  1869. const bool preload /*= false*/) {
  1870. last_sent_ = microsec_clock::universal_time();
  1871. const int arg_idx = 0;
  1872. // Get transaction id offset.
  1873. size_t transid_offset = getTransactionIdOffset(arg_idx);
  1874. // Generate trasnaction id to be set for the new exchange.
  1875. const uint32_t transid = generateTransid();
  1876. // Create packet.
  1877. PerfPkt6Ptr pkt6(new PerfPkt6(&template_buf[0], template_buf.size(),
  1878. transid_offset, transid));
  1879. if (!pkt6) {
  1880. isc_throw(Unexpected, "failed to create SOLICIT packet");
  1881. }
  1882. size_t rand_offset = getRandomOffset(arg_idx);
  1883. // randomized will pick number of bytes randomized so we can
  1884. // just use part of the generated duid and substitude a few bytes
  1885. /// in template.
  1886. uint8_t randomized = 0;
  1887. std::vector<uint8_t> duid = generateDuid(randomized);
  1888. if (rand_offset > template_buf.size()) {
  1889. isc_throw(OutOfRange, "randomization offset is out of bounds");
  1890. }
  1891. // Store random part of the DUID into the packet.
  1892. pkt6->writeAt(rand_offset - randomized + 1,
  1893. duid.end() - randomized, duid.end());
  1894. // Prepare on-wire data.
  1895. pkt6->rawPack();
  1896. setDefaults6(socket, pkt6);
  1897. // Send solicit packet.
  1898. IfaceMgr::instance().send(pkt6);
  1899. if (!preload) {
  1900. if (!stats_mgr6_) {
  1901. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  1902. "hasn't been initialized");
  1903. }
  1904. // Update packet stats.
  1905. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_SA, pkt6);
  1906. }
  1907. saveFirstPacket(pkt6);
  1908. }
  1909. void
  1910. TestControl::setDefaults4(const TestControlSocket& socket,
  1911. const Pkt4Ptr& pkt) {
  1912. CommandOptions& options = CommandOptions::instance();
  1913. // Interface name.
  1914. Iface* iface = IfaceMgr::instance().getIface(socket.ifindex_);
  1915. if (iface == NULL) {
  1916. isc_throw(BadValue, "unable to find interface with given index");
  1917. }
  1918. pkt->setIface(iface->getName());
  1919. // Interface index.
  1920. pkt->setIndex(socket.ifindex_);
  1921. // Local client's port (68)
  1922. pkt->setLocalPort(DHCP4_CLIENT_PORT);
  1923. // Server's port (67)
  1924. pkt->setRemotePort(DHCP4_SERVER_PORT);
  1925. // The remote server's name or IP.
  1926. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  1927. // Set local address.
  1928. pkt->setLocalAddr(IOAddress(socket.addr_));
  1929. // Set relay (GIADDR) address to local address.
  1930. pkt->setGiaddr(IOAddress(socket.addr_));
  1931. // Pretend that we have one relay (which is us).
  1932. pkt->setHops(1);
  1933. }
  1934. void
  1935. TestControl::setDefaults6(const TestControlSocket& socket,
  1936. const Pkt6Ptr& pkt) {
  1937. CommandOptions& options = CommandOptions::instance();
  1938. // Interface name.
  1939. Iface* iface = IfaceMgr::instance().getIface(socket.ifindex_);
  1940. if (iface == NULL) {
  1941. isc_throw(BadValue, "unable to find interface with given index");
  1942. }
  1943. pkt->setIface(iface->getName());
  1944. // Interface index.
  1945. pkt->setIndex(socket.ifindex_);
  1946. // Local client's port (547)
  1947. pkt->setLocalPort(DHCP6_CLIENT_PORT);
  1948. // Server's port (548)
  1949. pkt->setRemotePort(DHCP6_SERVER_PORT);
  1950. // Set local address.
  1951. pkt->setLocalAddr(socket.addr_);
  1952. // The remote server's name or IP.
  1953. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  1954. }
  1955. bool
  1956. TestControl::testDiags(const char diag) const {
  1957. std::string diags(CommandOptions::instance().getDiags());
  1958. if (diags.find(diag) != std::string::npos) {
  1959. return (true);
  1960. }
  1961. return (false);
  1962. }
  1963. void
  1964. TestControl::updateSendDue(const boost::posix_time::ptime& last_sent,
  1965. const int rate,
  1966. boost::posix_time::ptime& send_due) {
  1967. // If default constructor was called, this should not happen but
  1968. // if somebody has changed default constructor it is better to
  1969. // keep this check.
  1970. if (last_sent.is_not_a_date_time()) {
  1971. isc_throw(Unexpected, "time of last sent packet not initialized");
  1972. }
  1973. // Get the expected exchange rate.
  1974. CommandOptions& options = CommandOptions::instance();
  1975. // If rate was not specified we will wait just one clock tick to
  1976. // send next packet. This simulates best effort conditions.
  1977. long duration = 1;
  1978. if (rate != 0) {
  1979. // We use number of ticks instead of nanoseconds because
  1980. // nanosecond resolution may not be available on some
  1981. // machines. Number of ticks guarantees the highest possible
  1982. // timer resolution.
  1983. duration = time_duration::ticks_per_second() / rate;
  1984. }
  1985. // Calculate due time to initiate next chunk of exchanges.
  1986. send_due = last_sent + time_duration(0, 0, 0, duration);
  1987. // Check if it is already due.
  1988. ptime now(microsec_clock::universal_time());
  1989. // \todo verify if this condition is not too tight. In other words
  1990. // verify if this will not produce too many late sends.
  1991. // We might want to look at this once we are done implementing
  1992. // microsecond timeouts in IfaceMgr.
  1993. if (now > send_due) {
  1994. if (testDiags('i')) {
  1995. if (options.getIpVersion() == 4) {
  1996. stats_mgr4_->incrementCounter("latesend");
  1997. } else if (options.getIpVersion() == 6) {
  1998. stats_mgr6_->incrementCounter("latesend");
  1999. }
  2000. }
  2001. }
  2002. }
  2003. } // namespace perfdhcp
  2004. } // namespace isc