test_control.cc 80 KB

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