test_control.cc 80 KB

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