test_control.cc 80 KB

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