test_control.cc 78 KB

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