test_control.cc 80 KB

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