test_control.cc 80 KB

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