command_options.cc 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. // Copyright (C) 2012-2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include "command_options.h"
  8. #include <exceptions/exceptions.h>
  9. #include <dhcp/iface_mgr.h>
  10. #include <dhcp/duid.h>
  11. #include <cfgrpt/config_report.h>
  12. #include <boost/lexical_cast.hpp>
  13. #include <boost/date_time/posix_time/posix_time.hpp>
  14. #include <sstream>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <stdint.h>
  18. #include <unistd.h>
  19. using namespace std;
  20. using namespace isc;
  21. namespace isc {
  22. namespace perfdhcp {
  23. // Refer to config_report so it will be embedded in the binary
  24. const char* const* perfdhcp_config_report = isc::detail::config_report;
  25. CommandOptions::LeaseType::LeaseType()
  26. : type_(ADDRESS) {
  27. }
  28. CommandOptions::LeaseType::LeaseType(const Type lease_type)
  29. : type_(lease_type) {
  30. }
  31. bool
  32. CommandOptions::LeaseType::is(const Type lease_type) const {
  33. return (lease_type == type_);
  34. }
  35. bool
  36. CommandOptions::LeaseType::includes(const Type lease_type) const {
  37. return (is(ADDRESS_AND_PREFIX) || (lease_type == type_));
  38. }
  39. void
  40. CommandOptions::LeaseType::set(const Type lease_type) {
  41. type_ = lease_type;
  42. }
  43. void
  44. CommandOptions::LeaseType::fromCommandLine(const std::string& cmd_line_arg) {
  45. if (cmd_line_arg == "address-only") {
  46. type_ = ADDRESS;
  47. } else if (cmd_line_arg == "prefix-only") {
  48. type_ = PREFIX;
  49. } else if (cmd_line_arg == "address-and-prefix") {
  50. type_ = ADDRESS_AND_PREFIX;
  51. } else {
  52. isc_throw(isc::InvalidParameter, "value of lease-type: -e<lease-type>,"
  53. " must be one of the following: 'address-only' or"
  54. " 'prefix-only'");
  55. }
  56. }
  57. std::string
  58. CommandOptions::LeaseType::toText() const {
  59. switch (type_) {
  60. case ADDRESS:
  61. return ("address-only (IA_NA option added to the client's request)");
  62. case PREFIX:
  63. return ("prefix-only (IA_PD option added to the client's request)");
  64. case ADDRESS_AND_PREFIX:
  65. return ("address-and-prefix (Both IA_NA and IA_PD options added to the"
  66. " client's request)");
  67. default:
  68. isc_throw(Unexpected, "internal error: undefined lease type code when"
  69. " returning textual representation of the lease type");
  70. }
  71. }
  72. CommandOptions&
  73. CommandOptions::instance() {
  74. static CommandOptions options;
  75. return (options);
  76. }
  77. void
  78. CommandOptions::reset() {
  79. // Default mac address used in DHCP messages
  80. // if -b mac=<mac-address> was not specified
  81. uint8_t mac[6] = { 0x0, 0xC, 0x1, 0x2, 0x3, 0x4 };
  82. // Default packet drop time if -D<drop-time> parameter
  83. // was not specified
  84. double dt[2] = { 1., 1. };
  85. // We don't use constructor initialization list because we
  86. // will need to reset all members many times to perform unit tests
  87. ipversion_ = 0;
  88. exchange_mode_ = DORA_SARR;
  89. lease_type_.set(LeaseType::ADDRESS);
  90. rate_ = 0;
  91. renew_rate_ = 0;
  92. release_rate_ = 0;
  93. report_delay_ = 0;
  94. clients_num_ = 0;
  95. mac_template_.assign(mac, mac + 6);
  96. duid_template_.clear();
  97. base_.clear();
  98. num_request_.clear();
  99. period_ = 0;
  100. drop_time_set_ = 0;
  101. drop_time_.assign(dt, dt + 2);
  102. max_drop_.clear();
  103. max_pdrop_.clear();
  104. localname_.clear();
  105. is_interface_ = false;
  106. preload_ = 0;
  107. aggressivity_ = 1;
  108. local_port_ = 0;
  109. seeded_ = false;
  110. seed_ = 0;
  111. broadcast_ = false;
  112. rapid_commit_ = false;
  113. use_first_ = false;
  114. template_file_.clear();
  115. rnd_offset_.clear();
  116. xid_offset_.clear();
  117. elp_offset_ = -1;
  118. sid_offset_ = -1;
  119. rip_offset_ = -1;
  120. diags_.clear();
  121. wrapped_.clear();
  122. server_name_.clear();
  123. generateDuidTemplate();
  124. }
  125. bool
  126. CommandOptions::parse(int argc, char** const argv, bool print_cmd_line) {
  127. // Reset internal variables used by getopt
  128. // to eliminate undefined behavior when
  129. // parsing different command lines multiple times
  130. #ifdef __GLIBC__
  131. // Warning: non-portable code. This is due to a bug in glibc's
  132. // getopt() which keeps internal state about an old argument vector
  133. // (argc, argv) from last call and tries to scan them when a new
  134. // argument vector (argc, argv) is passed. As the old vector may not
  135. // be main()'s arguments, but heap allocated and may have been freed
  136. // since, this becomes a use after free and results in random
  137. // behavior. According to the NOTES section in glibc getopt()'s
  138. // manpage, setting optind=0 resets getopt()'s state. Though this is
  139. // not required in our usage of getopt(), the bug still happens
  140. // unless we set optind=0.
  141. //
  142. // Setting optind=0 is non-portable code.
  143. optind = 0;
  144. #else
  145. optind = 1;
  146. #endif
  147. // optreset is declared on BSD systems and is used to reset internal
  148. // state of getopt(). When parsing command line arguments multiple
  149. // times with getopt() the optreset must be set to 1 every time before
  150. // parsing starts. Failing to do so will result in random behavior of
  151. // getopt().
  152. #ifdef HAVE_OPTRESET
  153. optreset = 1;
  154. #endif
  155. opterr = 0;
  156. // Reset values of class members
  157. reset();
  158. // Informs if program has been run with 'h' or 'v' option.
  159. bool help_or_version_mode = initialize(argc, argv, print_cmd_line);
  160. if (!help_or_version_mode) {
  161. validate();
  162. }
  163. return (help_or_version_mode);
  164. }
  165. bool
  166. CommandOptions::initialize(int argc, char** argv, bool print_cmd_line) {
  167. int opt = 0; // Subsequent options returned by getopt()
  168. std::string drop_arg; // Value of -D<value>argument
  169. size_t percent_loc = 0; // Location of % sign in -D<value>
  170. double drop_percent = 0; // % value (1..100) in -D<value%>
  171. int num_drops = 0; // Max number of drops specified in -D<value>
  172. int num_req = 0; // Max number of dropped
  173. // requests in -n<max-drops>
  174. int offset_arg = 0; // Temporary variable holding offset arguments
  175. std::string sarg; // Temporary variable for string args
  176. std::ostringstream stream;
  177. stream << "perfdhcp";
  178. // In this section we collect argument values from command line
  179. // they will be tuned and validated elsewhere
  180. while((opt = getopt(argc, argv, "hv46r:t:R:b:n:p:d:D:l:P:a:L:"
  181. "s:iBc1T:X:O:E:S:I:x:w:e:f:F:")) != -1) {
  182. stream << " -" << static_cast<char>(opt);
  183. if (optarg) {
  184. stream << " " << optarg;
  185. }
  186. switch (opt) {
  187. case '1':
  188. use_first_ = true;
  189. break;
  190. case '4':
  191. check(ipversion_ == 6, "IP version already set to 6");
  192. ipversion_ = 4;
  193. break;
  194. case '6':
  195. check(ipversion_ == 4, "IP version already set to 4");
  196. ipversion_ = 6;
  197. break;
  198. case 'a':
  199. aggressivity_ = positiveInteger("value of aggressivity: -a<value>"
  200. " must be a positive integer");
  201. break;
  202. case 'b':
  203. check(base_.size() > 3, "-b<value> already specified,"
  204. " unexpected occurrence of 5th -b<value>");
  205. base_.push_back(optarg);
  206. decodeBase(base_.back());
  207. break;
  208. case 'B':
  209. broadcast_ = true;
  210. break;
  211. case 'c':
  212. rapid_commit_ = true;
  213. break;
  214. case 'd':
  215. check(drop_time_set_ > 1,
  216. "maximum number of drops already specified, "
  217. "unexpected 3rd occurrence of -d<value>");
  218. try {
  219. drop_time_[drop_time_set_] =
  220. boost::lexical_cast<double>(optarg);
  221. } catch (boost::bad_lexical_cast&) {
  222. isc_throw(isc::InvalidParameter,
  223. "value of drop time: -d<value>"
  224. " must be positive number");
  225. }
  226. check(drop_time_[drop_time_set_] <= 0.,
  227. "drop-time must be a positive number");
  228. drop_time_set_ = true;
  229. break;
  230. case 'D':
  231. drop_arg = std::string(optarg);
  232. percent_loc = drop_arg.find('%');
  233. check(max_pdrop_.size() > 1 || max_drop_.size() > 1,
  234. "values of maximum drops: -D<value> already "
  235. "specified, unexpected 3rd occurrence of -D<value>");
  236. if ((percent_loc) != std::string::npos) {
  237. try {
  238. drop_percent =
  239. boost::lexical_cast<double>(drop_arg.substr(0, percent_loc));
  240. } catch (boost::bad_lexical_cast&) {
  241. isc_throw(isc::InvalidParameter,
  242. "value of drop percentage: -D<value%>"
  243. " must be 0..100");
  244. }
  245. check((drop_percent <= 0) || (drop_percent >= 100),
  246. "value of drop percentage: -D<value%> must be 0..100");
  247. max_pdrop_.push_back(drop_percent);
  248. } else {
  249. num_drops = positiveInteger("value of max drops number:"
  250. " -d<value> must be a positive integer");
  251. max_drop_.push_back(num_drops);
  252. }
  253. break;
  254. case 'e':
  255. initLeaseType();
  256. break;
  257. case 'E':
  258. elp_offset_ = nonNegativeInteger("value of time-offset: -E<value>"
  259. " must not be a negative integer");
  260. break;
  261. case 'f':
  262. renew_rate_ = positiveInteger("value of the renew rate: -f<renew-rate>"
  263. " must be a positive integer");
  264. break;
  265. case 'F':
  266. release_rate_ = positiveInteger("value of the release rate:"
  267. " -F<release-rate> must be a"
  268. " positive integer");
  269. break;
  270. case 'h':
  271. usage();
  272. return (true);
  273. case 'i':
  274. exchange_mode_ = DO_SA;
  275. break;
  276. case 'I':
  277. rip_offset_ = positiveInteger("value of ip address offset:"
  278. " -I<value> must be a"
  279. " positive integer");
  280. break;
  281. case 'l':
  282. localname_ = std::string(optarg);
  283. initIsInterface();
  284. break;
  285. case 'L':
  286. local_port_ = nonNegativeInteger("value of local port:"
  287. " -L<value> must not be a"
  288. " negative integer");
  289. check(local_port_ >
  290. static_cast<int>(std::numeric_limits<uint16_t>::max()),
  291. "local-port must be lower than " +
  292. boost::lexical_cast<std::string>(std::numeric_limits<uint16_t>::max()));
  293. break;
  294. case 'n':
  295. num_req = positiveInteger("value of num-request:"
  296. " -n<value> must be a positive integer");
  297. if (num_request_.size() >= 2) {
  298. isc_throw(isc::InvalidParameter,
  299. "value of maximum number of requests: -n<value> "
  300. "already specified, unexpected 3rd occurrence"
  301. " of -n<value>");
  302. }
  303. num_request_.push_back(num_req);
  304. break;
  305. case 'O':
  306. if (rnd_offset_.size() < 2) {
  307. offset_arg = positiveInteger("value of random offset: "
  308. "-O<value> must be greater than 3");
  309. } else {
  310. isc_throw(isc::InvalidParameter,
  311. "random offsets already specified,"
  312. " unexpected 3rd occurrence of -O<value>");
  313. }
  314. check(offset_arg < 3, "value of random random-offset:"
  315. " -O<value> must be greater than 3 ");
  316. rnd_offset_.push_back(offset_arg);
  317. break;
  318. case 'p':
  319. period_ = positiveInteger("value of test period:"
  320. " -p<value> must be a positive integer");
  321. break;
  322. case 'P':
  323. preload_ = nonNegativeInteger("number of preload packets:"
  324. " -P<value> must not be "
  325. "a negative integer");
  326. break;
  327. case 'r':
  328. rate_ = positiveInteger("value of rate:"
  329. " -r<value> must be a positive integer");
  330. break;
  331. case 'R':
  332. initClientsNum();
  333. break;
  334. case 's':
  335. seed_ = static_cast<unsigned int>
  336. (nonNegativeInteger("value of seed:"
  337. " -s <seed> must be non-negative integer"));
  338. seeded_ = seed_ > 0 ? true : false;
  339. break;
  340. case 'S':
  341. sid_offset_ = positiveInteger("value of server id offset:"
  342. " -S<value> must be a"
  343. " positive integer");
  344. break;
  345. case 't':
  346. report_delay_ = positiveInteger("value of report delay:"
  347. " -t<value> must be a"
  348. " positive integer");
  349. break;
  350. case 'T':
  351. if (template_file_.size() < 2) {
  352. sarg = nonEmptyString("template file name not specified,"
  353. " expected -T<filename>");
  354. template_file_.push_back(sarg);
  355. } else {
  356. isc_throw(isc::InvalidParameter,
  357. "template files are already specified,"
  358. " unexpected 3rd -T<filename> occurrence");
  359. }
  360. break;
  361. case 'v':
  362. version();
  363. return (true);
  364. case 'w':
  365. wrapped_ = nonEmptyString("command for wrapped mode:"
  366. " -w<command> must be specified");
  367. break;
  368. case 'x':
  369. diags_ = nonEmptyString("value of diagnostics selectors:"
  370. " -x<value> must be specified");
  371. break;
  372. case 'X':
  373. if (xid_offset_.size() < 2) {
  374. offset_arg = positiveInteger("value of transaction id:"
  375. " -X<value> must be a"
  376. " positive integer");
  377. } else {
  378. isc_throw(isc::InvalidParameter,
  379. "transaction ids already specified,"
  380. " unexpected 3rd -X<value> occurrence");
  381. }
  382. xid_offset_.push_back(offset_arg);
  383. break;
  384. default:
  385. isc_throw(isc::InvalidParameter, "unknown command line option");
  386. }
  387. }
  388. // If the IP version was not specified in the
  389. // command line, assume IPv4.
  390. if (ipversion_ == 0) {
  391. ipversion_ = 4;
  392. }
  393. // If template packet files specified for both DISCOVER/SOLICIT
  394. // and REQUEST/REPLY exchanges make sure we have transaction id
  395. // and random duid offsets for both exchanges. We will duplicate
  396. // value specified as -X<value> and -R<value> for second
  397. // exchange if user did not specified otherwise.
  398. if (template_file_.size() > 1) {
  399. if (xid_offset_.size() == 1) {
  400. xid_offset_.push_back(xid_offset_[0]);
  401. }
  402. if (rnd_offset_.size() == 1) {
  403. rnd_offset_.push_back(rnd_offset_[0]);
  404. }
  405. }
  406. // Get server argument
  407. // NoteFF02::1:2 and FF02::1:3 are defined in RFC3315 as
  408. // All_DHCP_Relay_Agents_and_Servers and All_DHCP_Servers
  409. // addresses
  410. check(optind < argc -1, "extra arguments?");
  411. if (optind == argc - 1) {
  412. server_name_ = argv[optind];
  413. stream << " " << server_name_;
  414. // Decode special cases
  415. if ((ipversion_ == 4) && (server_name_.compare("all") == 0)) {
  416. broadcast_ = true;
  417. // Use broadcast address as server name.
  418. server_name_ = DHCP_IPV4_BROADCAST_ADDRESS;
  419. } else if ((ipversion_ == 6) && (server_name_.compare("all") == 0)) {
  420. server_name_ = ALL_DHCP_RELAY_AGENTS_AND_SERVERS;
  421. } else if ((ipversion_ == 6) &&
  422. (server_name_.compare("servers") == 0)) {
  423. server_name_ = ALL_DHCP_SERVERS;
  424. }
  425. }
  426. if (print_cmd_line) {
  427. std::cout << "Running: " << stream.str() << std::endl;
  428. }
  429. // Handle the local '-l' address/interface
  430. if (!localname_.empty()) {
  431. if (server_name_.empty()) {
  432. if (is_interface_ && (ipversion_ == 4)) {
  433. broadcast_ = true;
  434. server_name_ = DHCP_IPV4_BROADCAST_ADDRESS;
  435. } else if (is_interface_ && (ipversion_ == 6)) {
  436. server_name_ = ALL_DHCP_RELAY_AGENTS_AND_SERVERS;
  437. }
  438. }
  439. }
  440. if (server_name_.empty()) {
  441. isc_throw(InvalidParameter,
  442. "without an interface, server is required");
  443. }
  444. // If DUID is not specified from command line we need to
  445. // generate one.
  446. if (duid_template_.empty()) {
  447. generateDuidTemplate();
  448. }
  449. return (false);
  450. }
  451. void
  452. CommandOptions::initClientsNum() {
  453. const std::string errmsg =
  454. "value of -R <value> must be non-negative integer";
  455. try {
  456. // Declare clients_num as as 64-bit signed value to
  457. // be able to detect negative values provided
  458. // by user. We would not detect negative values
  459. // if we casted directly to unsigned value.
  460. long long clients_num = boost::lexical_cast<long long>(optarg);
  461. check(clients_num < 0, errmsg);
  462. clients_num_ = boost::lexical_cast<uint32_t>(optarg);
  463. } catch (boost::bad_lexical_cast&) {
  464. isc_throw(isc::InvalidParameter, errmsg);
  465. }
  466. }
  467. void
  468. CommandOptions::initIsInterface() {
  469. is_interface_ = false;
  470. if (!localname_.empty()) {
  471. dhcp::IfaceMgr& iface_mgr = dhcp::IfaceMgr::instance();
  472. if (iface_mgr.getIface(localname_) != NULL) {
  473. is_interface_ = true;
  474. }
  475. }
  476. }
  477. void
  478. CommandOptions::decodeBase(const std::string& base) {
  479. std::string b(base);
  480. boost::algorithm::to_lower(b);
  481. // Currently we only support mac and duid
  482. if ((b.substr(0, 4) == "mac=") || (b.substr(0, 6) == "ether=")) {
  483. decodeMac(b);
  484. } else if (b.substr(0, 5) == "duid=") {
  485. decodeDuid(b);
  486. } else {
  487. isc_throw(isc::InvalidParameter,
  488. "base value not provided as -b<value>,"
  489. " expected -b mac=<mac> or -b duid=<duid>");
  490. }
  491. }
  492. void
  493. CommandOptions::decodeMac(const std::string& base) {
  494. // Strip string from mac=
  495. size_t found = base.find('=');
  496. static const char* errmsg = "expected -b<base> format for"
  497. " mac address is -b mac=00::0C::01::02::03::04 or"
  498. " -b mac=00:0C:01:02:03:04";
  499. check(found == std::string::npos, errmsg);
  500. // Decode mac address to vector of uint8_t
  501. std::istringstream s1(base.substr(found + 1));
  502. std::string token;
  503. mac_template_.clear();
  504. // Get pieces of MAC address separated with : (or even ::)
  505. while (std::getline(s1, token, ':')) {
  506. // Convert token to byte value using std::istringstream
  507. if (token.length() > 0) {
  508. unsigned int ui = 0;
  509. try {
  510. // Do actual conversion
  511. ui = convertHexString(token);
  512. } catch (isc::InvalidParameter&) {
  513. isc_throw(isc::InvalidParameter,
  514. "invalid characters in MAC provided");
  515. }
  516. // If conversion succeeded store byte value
  517. mac_template_.push_back(ui);
  518. }
  519. }
  520. // MAC address must consist of 6 octets, otherwise it is invalid
  521. check(mac_template_.size() != 6, errmsg);
  522. }
  523. void
  524. CommandOptions::decodeDuid(const std::string& base) {
  525. // Strip argument from duid=
  526. std::vector<uint8_t> duid_template;
  527. size_t found = base.find('=');
  528. check(found == std::string::npos, "expected -b<base>"
  529. " format for duid is -b duid=<duid>");
  530. std::string b = base.substr(found + 1);
  531. // DUID must have even number of digits and must not be longer than 64 bytes
  532. check(b.length() & 1, "odd number of hexadecimal digits in duid");
  533. check(b.length() > 128, "duid too large");
  534. check(b.length() == 0, "no duid specified");
  535. // Turn pairs of hexadecimal digits into vector of octets
  536. for (size_t i = 0; i < b.length(); i += 2) {
  537. unsigned int ui = 0;
  538. try {
  539. // Do actual conversion
  540. ui = convertHexString(b.substr(i, 2));
  541. } catch (isc::InvalidParameter&) {
  542. isc_throw(isc::InvalidParameter,
  543. "invalid characters in DUID provided,"
  544. " expected hex digits");
  545. }
  546. duid_template.push_back(static_cast<uint8_t>(ui));
  547. }
  548. // @todo Get rid of this limitation when we manage add support
  549. // for DUIDs other than LLT. Shorter DUIDs may be useful for
  550. // server testing purposes.
  551. check(duid_template.size() < 6, "DUID must be at least 6 octets long");
  552. // Assign the new duid only if successfully generated.
  553. std::swap(duid_template, duid_template_);
  554. }
  555. void
  556. CommandOptions::generateDuidTemplate() {
  557. using namespace boost::posix_time;
  558. // Duid template will be most likely generated only once but
  559. // it is ok if it is called more then once so we simply
  560. // regenerate it and discard previous value.
  561. duid_template_.clear();
  562. const uint8_t duid_template_len = 14;
  563. duid_template_.resize(duid_template_len);
  564. // The first four octets consist of DUID LLT and hardware type.
  565. duid_template_[0] = static_cast<uint8_t>(static_cast<uint16_t>(isc::dhcp::DUID::DUID_LLT) >> 8);
  566. duid_template_[1] = static_cast<uint8_t>(static_cast<uint16_t>(isc::dhcp::DUID::DUID_LLT) & 0xff);
  567. duid_template_[2] = HWTYPE_ETHERNET >> 8;
  568. duid_template_[3] = HWTYPE_ETHERNET & 0xff;
  569. // As described in RFC3315: 'the time value is the time
  570. // that the DUID is generated represented in seconds
  571. // since midnight (UTC), January 1, 2000, modulo 2^32.'
  572. ptime now = microsec_clock::universal_time();
  573. ptime duid_epoch(from_iso_string("20000101T000000"));
  574. time_period period(duid_epoch, now);
  575. uint32_t duration_sec = htonl(period.length().total_seconds());
  576. memcpy(&duid_template_[4], &duration_sec, 4);
  577. // Set link layer address (6 octets). This value may be
  578. // randomized before sending a packet to simulate different
  579. // clients.
  580. memcpy(&duid_template_[8], &mac_template_[0], 6);
  581. }
  582. uint8_t
  583. CommandOptions::convertHexString(const std::string& text) const {
  584. unsigned int ui = 0;
  585. // First, check if we are dealing with hexadecimal digits only
  586. for (size_t i = 0; i < text.length(); ++i) {
  587. if (!std::isxdigit(text[i])) {
  588. isc_throw(isc::InvalidParameter,
  589. "The following digit: " << text[i] << " in "
  590. << text << "is not hexadecimal");
  591. }
  592. }
  593. // If we are here, we have valid string to convert to octet
  594. std::istringstream text_stream(text);
  595. text_stream >> std::hex >> ui >> std::dec;
  596. // Check if for some reason we have overflow - this should never happen!
  597. if (ui > 0xFF) {
  598. isc_throw(isc::InvalidParameter, "Can't convert more than"
  599. " two hex digits to byte");
  600. }
  601. return ui;
  602. }
  603. void
  604. CommandOptions::validate() const {
  605. check((getIpVersion() != 4) && (isBroadcast() != 0),
  606. "-B is not compatible with IPv6 (-6)");
  607. check((getIpVersion() != 6) && (isRapidCommit() != 0),
  608. "-6 (IPv6) must be set to use -c");
  609. check((getIpVersion() != 6) && (getReleaseRate() != 0),
  610. "-F<release-rate> may be used with -6 (IPv6) only");
  611. check((getExchangeMode() == DO_SA) && (getNumRequests().size() > 1),
  612. "second -n<num-request> is not compatible with -i");
  613. check((getIpVersion() == 4) && !getLeaseType().is(LeaseType::ADDRESS),
  614. "-6 option must be used if lease type other than '-e address-only'"
  615. " is specified");
  616. check(!getTemplateFiles().empty() &&
  617. !getLeaseType().is(LeaseType::ADDRESS),
  618. "template files may be only used with '-e address-only'");
  619. check((getExchangeMode() == DO_SA) && (getDropTime()[1] != 1.),
  620. "second -d<drop-time> is not compatible with -i");
  621. check((getExchangeMode() == DO_SA) &&
  622. ((getMaxDrop().size() > 1) || (getMaxDropPercentage().size() > 1)),
  623. "second -D<max-drop> is not compatible with -i");
  624. check((getExchangeMode() == DO_SA) && (isUseFirst()),
  625. "-1 is not compatible with -i");
  626. check((getExchangeMode() == DO_SA) && (getTemplateFiles().size() > 1),
  627. "second -T<template-file> is not compatible with -i");
  628. check((getExchangeMode() == DO_SA) && (getTransactionIdOffset().size() > 1),
  629. "second -X<xid-offset> is not compatible with -i");
  630. check((getExchangeMode() == DO_SA) && (getRandomOffset().size() > 1),
  631. "second -O<random-offset is not compatible with -i");
  632. check((getExchangeMode() == DO_SA) && (getElapsedTimeOffset() >= 0),
  633. "-E<time-offset> is not compatible with -i");
  634. check((getExchangeMode() == DO_SA) && (getServerIdOffset() >= 0),
  635. "-S<srvid-offset> is not compatible with -i");
  636. check((getExchangeMode() == DO_SA) && (getRequestedIpOffset() >= 0),
  637. "-I<ip-offset> is not compatible with -i");
  638. check((getExchangeMode() == DO_SA) && (getRenewRate() != 0),
  639. "-f<renew-rate> is not compatible with -i");
  640. check((getExchangeMode() == DO_SA) && (getReleaseRate() != 0),
  641. "-F<release-rate> is not compatible with -i");
  642. check((getExchangeMode() != DO_SA) && (isRapidCommit() != 0),
  643. "-i must be set to use -c");
  644. check((getRate() == 0) && (getReportDelay() != 0),
  645. "-r<rate> must be set to use -t<report>");
  646. check((getRate() == 0) && (getNumRequests().size() > 0),
  647. "-r<rate> must be set to use -n<num-request>");
  648. check((getRate() == 0) && (getPeriod() != 0),
  649. "-r<rate> must be set to use -p<test-period>");
  650. check((getRate() == 0) &&
  651. ((getMaxDrop().size() > 0) || getMaxDropPercentage().size() > 0),
  652. "-r<rate> must be set to use -D<max-drop>");
  653. check((getRate() != 0) && (getRenewRate() + getReleaseRate() > getRate()),
  654. "The sum of Renew rate (-f<renew-rate>) and Release rate"
  655. " (-F<release-rate>) must not be greater than the exchange"
  656. " rate specified as -r<rate>");
  657. check((getRate() == 0) && (getRenewRate() != 0),
  658. "Renew rate specified as -f<renew-rate> must not be specified"
  659. " when -r<rate> parameter is not specified");
  660. check((getRate() == 0) && (getReleaseRate() != 0),
  661. "Release rate specified as -F<release-rate> must not be specified"
  662. " when -r<rate> parameter is not specified");
  663. check((getTemplateFiles().size() < getTransactionIdOffset().size()),
  664. "-T<template-file> must be set to use -X<xid-offset>");
  665. check((getTemplateFiles().size() < getRandomOffset().size()),
  666. "-T<template-file> must be set to use -O<random-offset>");
  667. check((getTemplateFiles().size() < 2) && (getElapsedTimeOffset() >= 0),
  668. "second/request -T<template-file> must be set to use -E<time-offset>");
  669. check((getTemplateFiles().size() < 2) && (getServerIdOffset() >= 0),
  670. "second/request -T<template-file> must be set to "
  671. "use -S<srvid-offset>");
  672. check((getTemplateFiles().size() < 2) && (getRequestedIpOffset() >= 0),
  673. "second/request -T<template-file> must be set to "
  674. "use -I<ip-offset>");
  675. }
  676. void
  677. CommandOptions::check(bool condition, const std::string& errmsg) const {
  678. // The same could have been done with macro or just if statement but
  679. // we prefer functions to macros here
  680. std::ostringstream stream;
  681. stream << errmsg << "\n";
  682. if (condition) {
  683. isc_throw(isc::InvalidParameter, errmsg);
  684. }
  685. }
  686. int
  687. CommandOptions::positiveInteger(const std::string& errmsg) const {
  688. try {
  689. int value = boost::lexical_cast<int>(optarg);
  690. check(value <= 0, errmsg);
  691. return (value);
  692. } catch (boost::bad_lexical_cast&) {
  693. isc_throw(InvalidParameter, errmsg);
  694. }
  695. }
  696. int
  697. CommandOptions::nonNegativeInteger(const std::string& errmsg) const {
  698. try {
  699. int value = boost::lexical_cast<int>(optarg);
  700. check(value < 0, errmsg);
  701. return (value);
  702. } catch (boost::bad_lexical_cast&) {
  703. isc_throw(InvalidParameter, errmsg);
  704. }
  705. }
  706. std::string
  707. CommandOptions::nonEmptyString(const std::string& errmsg) const {
  708. std::string sarg = optarg;
  709. if (sarg.length() == 0) {
  710. isc_throw(isc::InvalidParameter, errmsg);
  711. }
  712. return sarg;
  713. }
  714. void
  715. CommandOptions::initLeaseType() {
  716. std::string lease_type_arg = optarg;
  717. lease_type_.fromCommandLine(lease_type_arg);
  718. }
  719. void
  720. CommandOptions::printCommandLine() const {
  721. std::cout << "IPv" << static_cast<int>(ipversion_) << std::endl;
  722. if (exchange_mode_ == DO_SA) {
  723. if (ipversion_ == 4) {
  724. std::cout << "DISCOVER-OFFER only" << std::endl;
  725. } else {
  726. std::cout << "SOLICIT-ADVERTISE only" << std::endl;
  727. }
  728. }
  729. std::cout << "lease-type=" << getLeaseType().toText() << std::endl;
  730. if (rate_ != 0) {
  731. std::cout << "rate[1/s]=" << rate_ << std::endl;
  732. }
  733. if (getRenewRate() != 0) {
  734. std::cout << "renew-rate[1/s]=" << getRenewRate() << std::endl;
  735. }
  736. if (getReleaseRate() != 0) {
  737. std::cout << "release-rate[1/s]=" << getReleaseRate() << std::endl;
  738. }
  739. if (report_delay_ != 0) {
  740. std::cout << "report[s]=" << report_delay_ << std::endl;
  741. }
  742. if (clients_num_ != 0) {
  743. std::cout << "clients=" << clients_num_ << std::endl;
  744. }
  745. for (size_t i = 0; i < base_.size(); ++i) {
  746. std::cout << "base[" << i << "]=" << base_[i] << std::endl;
  747. }
  748. for (size_t i = 0; i < num_request_.size(); ++i) {
  749. std::cout << "num-request[" << i << "]=" << num_request_[i] << std::endl;
  750. }
  751. if (period_ != 0) {
  752. std::cout << "test-period=" << period_ << std::endl;
  753. }
  754. for (size_t i = 0; i < drop_time_.size(); ++i) {
  755. std::cout << "drop-time[" << i << "]=" << drop_time_[i] << std::endl;
  756. }
  757. for (size_t i = 0; i < max_drop_.size(); ++i) {
  758. std::cout << "max-drop{" << i << "]=" << max_drop_[i] << std::endl;
  759. }
  760. for (size_t i = 0; i < max_pdrop_.size(); ++i) {
  761. std::cout << "max-pdrop{" << i << "]=" << max_pdrop_[i] << std::endl;
  762. }
  763. if (preload_ != 0) {
  764. std::cout << "preload=" << preload_ << std::endl;
  765. }
  766. std::cout << "aggressivity=" << aggressivity_ << std::endl;
  767. if (getLocalPort() != 0) {
  768. std::cout << "local-port=" << local_port_ << std::endl;
  769. }
  770. if (seeded_) {
  771. std::cout << "seed=" << seed_ << std::endl;
  772. }
  773. if (broadcast_) {
  774. std::cout << "broadcast" << std::endl;
  775. }
  776. if (rapid_commit_) {
  777. std::cout << "rapid-commit" << std::endl;
  778. }
  779. if (use_first_) {
  780. std::cout << "use-first" << std::endl;
  781. }
  782. for (size_t i = 0; i < template_file_.size(); ++i) {
  783. std::cout << "template-file[" << i << "]=" << template_file_[i] << std::endl;
  784. }
  785. for (size_t i = 0; i < xid_offset_.size(); ++i) {
  786. std::cout << "xid-offset[" << i << "]=" << xid_offset_[i] << std::endl;
  787. }
  788. if (elp_offset_ != 0) {
  789. std::cout << "elp-offset=" << elp_offset_ << std::endl;
  790. }
  791. for (size_t i = 0; i < rnd_offset_.size(); ++i) {
  792. std::cout << "rnd-offset[" << i << "]=" << rnd_offset_[i] << std::endl;
  793. }
  794. if (sid_offset_ != 0) {
  795. std::cout << "sid-offset=" << sid_offset_ << std::endl;
  796. }
  797. if (rip_offset_ != 0) {
  798. std::cout << "rip-offset=" << rip_offset_ << std::endl;
  799. }
  800. if (!diags_.empty()) {
  801. std::cout << "diagnostic-selectors=" << diags_ << std::endl;
  802. }
  803. if (!wrapped_.empty()) {
  804. std::cout << "wrapped=" << wrapped_ << std::endl;
  805. }
  806. if (!localname_.empty()) {
  807. if (is_interface_) {
  808. std::cout << "interface=" << localname_ << std::endl;
  809. } else {
  810. std::cout << "local-addr=" << localname_ << std::endl;
  811. }
  812. }
  813. if (!server_name_.empty()) {
  814. std::cout << "server=" << server_name_ << std::endl;
  815. }
  816. }
  817. void
  818. CommandOptions::usage() const {
  819. std::cout <<
  820. "perfdhcp [-hv] [-4|-6] [-e<lease-type>] [-r<rate>] [-f<renew-rate>]\n"
  821. " [-F<release-rate>] [-t<report>] [-R<range>] [-b<base>]\n"
  822. " [-n<num-request>] [-p<test-period>] [-d<drop-time>]\n"
  823. " [-D<max-drop>] [-l<local-addr|interface>] [-P<preload>]\n"
  824. " [-a<aggressivity>] [-L<local-port>] [-s<seed>] [-i] [-B]\n"
  825. " [-c] [-1] [-T<template-file>] [-X<xid-offset>]\n"
  826. " [-O<random-offset] [-E<time-offset>] [-S<srvid-offset>]\n"
  827. " [-I<ip-offset>] [-x<diagnostic-selector>] [-w<wrapped>]\n"
  828. " [server]\n"
  829. "\n"
  830. "The [server] argument is the name/address of the DHCP server to\n"
  831. "contact. For DHCPv4 operation, exchanges are initiated by\n"
  832. "transmitting a DHCP DISCOVER to this address.\n"
  833. "\n"
  834. "For DHCPv6 operation, exchanges are initiated by transmitting a DHCP\n"
  835. "SOLICIT to this address. In the DHCPv6 case, the special name 'all'\n"
  836. "can be used to refer to All_DHCP_Relay_Agents_and_Servers (the\n"
  837. "multicast address FF02::1:2), or the special name 'servers' to refer\n"
  838. "to All_DHCP_Servers (the multicast address FF05::1:3). The [server]\n"
  839. "argument is optional only in the case that -l is used to specify an\n"
  840. "interface, in which case [server] defaults to 'all'.\n"
  841. "\n"
  842. "The default is to perform a single 4-way exchange, effectively pinging\n"
  843. "the server.\n"
  844. "The -r option is used to set up a performance test, without\n"
  845. "it exchanges are initiated as fast as possible.\n"
  846. "\n"
  847. "Options:\n"
  848. "-1: Take the server-ID option from the first received message.\n"
  849. "-4: DHCPv4 operation (default). This is incompatible with the -6 option.\n"
  850. "-6: DHCPv6 operation. This is incompatible with the -4 option.\n"
  851. "-a<aggressivity>: When the target sending rate is not yet reached,\n"
  852. " control how many exchanges are initiated before the next pause.\n"
  853. "-b<base>: The base mac, duid, IP, etc, used to simulate different\n"
  854. " clients. This can be specified multiple times, each instance is\n"
  855. " in the <type>=<value> form, for instance:\n"
  856. " (and default) mac=00:0c:01:02:03:04.\n"
  857. "-d<drop-time>: Specify the time after which a request is treated as\n"
  858. " having been lost. The value is given in seconds and may contain a\n"
  859. " fractional component. The default is 1 second.\n"
  860. "-e<lease-type>: A type of lease being requested from the server. It\n"
  861. " may be one of the following: address-only, prefix-only or\n"
  862. " address-and-prefix. The address-only indicates that the regular\n"
  863. " address (v4 or v6) will be requested. The prefix-only indicates\n"
  864. " that the IPv6 prefix will be requested. The address-and-prefix\n"
  865. " indicates that both IPv6 address and prefix will be requested.\n"
  866. " The '-e prefix-only' and -'e address-and-prefix' must not be\n"
  867. " used with -4.\n"
  868. "-E<time-offset>: Offset of the (DHCPv4) secs field / (DHCPv6)\n"
  869. " elapsed-time option in the (second/request) template.\n"
  870. " The value 0 disables it.\n"
  871. "-h: Print this help.\n"
  872. "-i: Do only the initial part of an exchange: DO or SA, depending on\n"
  873. " whether -6 is given.\n"
  874. "-I<ip-offset>: Offset of the (DHCPv4) IP address in the requested-IP\n"
  875. " option / (DHCPv6) IA_NA option in the (second/request) template.\n"
  876. "-l<local-addr|interface>: For DHCPv4 operation, specify the local\n"
  877. " hostname/address to use when communicating with the server. By\n"
  878. " default, the interface address through which traffic would\n"
  879. " normally be routed to the server is used.\n"
  880. " For DHCPv6 operation, specify the name of the network interface\n"
  881. " via which exchanges are initiated.\n"
  882. "-L<local-port>: Specify the local port to use\n"
  883. " (the value 0 means to use the default).\n"
  884. "-O<random-offset>: Offset of the last octet to randomize in the template.\n"
  885. "-P<preload>: Initiate first <preload> exchanges back to back at startup.\n"
  886. "-r<rate>: Initiate <rate> DORA/SARR (or if -i is given, DO/SA)\n"
  887. " exchanges per second. A periodic report is generated showing the\n"
  888. " number of exchanges which were not completed, as well as the\n"
  889. " average response latency. The program continues until\n"
  890. " interrupted, at which point a final report is generated.\n"
  891. "-R<range>: Specify how many different clients are used. With 1\n"
  892. " (the default), all requests seem to come from the same client.\n"
  893. "-s<seed>: Specify the seed for randomization, making it repeatable.\n"
  894. "-S<srvid-offset>: Offset of the server-ID option in the\n"
  895. " (second/request) template.\n"
  896. "-T<template-file>: The name of a file containing the template to use\n"
  897. " as a stream of hexadecimal digits.\n"
  898. "-v: Report the version number of this program.\n"
  899. "-w<wrapped>: Command to call with start/stop at the beginning/end of\n"
  900. " the program.\n"
  901. "-x<diagnostic-selector>: Include extended diagnostics in the output.\n"
  902. " <diagnostic-selector> is a string of single-keywords specifying\n"
  903. " the operations for which verbose output is desired. The selector\n"
  904. " keyletters are:\n"
  905. " * 'a': print the decoded command line arguments\n"
  906. " * 'e': print the exit reason\n"
  907. " * 'i': print rate processing details\n"
  908. " * 's': print first server-id\n"
  909. " * 't': when finished, print timers of all successful exchanges\n"
  910. " * 'T': when finished, print templates\n"
  911. "-X<xid-offset>: Transaction ID (aka. xid) offset in the template.\n"
  912. "\n"
  913. "DHCPv4 only options:\n"
  914. "-B: Force broadcast handling.\n"
  915. "\n"
  916. "DHCPv6 only options:\n"
  917. "-c: Add a rapid commit option (exchanges will be SA).\n"
  918. "-f<renew-rate>: Rate at which DHCPv4 or DHCPv6 renew requests are sent\n"
  919. " to a server. This value is only valid when used in conjunction\n"
  920. " with the exchange rate (given by -r<rate>). Furthermore the sum of\n"
  921. " this value and the release-rate (given by -F<rate) must be equal\n"
  922. " to or less than the exchange rate.\n"
  923. "-F<release-rate>: Rate at which IPv6 Release requests are sent to\n"
  924. " a server. This value is only valid when used in conjunction with\n"
  925. " the exchange rate (given by -r<rate>). Furthermore the sum of\n"
  926. " this value and the renew-rate (given by -f<rate) must be equal\n"
  927. " to or less than the exchange rate.\n"
  928. "\n"
  929. "The remaining options are used only in conjunction with -r:\n"
  930. "\n"
  931. "-D<max-drop>: Abort the test if more than <max-drop> requests have\n"
  932. " been dropped. Use -D0 to abort if even a single request has been\n"
  933. " dropped. If <max-drop> includes the suffix '%', it specifies a\n"
  934. " maximum percentage of requests that may be dropped before abort.\n"
  935. " In this case, testing of the threshold begins after 10 requests\n"
  936. " have been expected to be received.\n"
  937. "-n<num-request>: Initiate <num-request> transactions. No report is\n"
  938. " generated until all transactions have been initiated/waited-for,\n"
  939. " after which a report is generated and the program terminates.\n"
  940. "-p<test-period>: Send requests for the given test period, which is\n"
  941. " specified in the same manner as -d. This can be used as an\n"
  942. " alternative to -n, or both options can be given, in which case the\n"
  943. " testing is completed when either limit is reached.\n"
  944. "-t<report>: Delay in seconds between two periodic reports.\n"
  945. "\n"
  946. "Errors:\n"
  947. "- tooshort: received a too short message\n"
  948. "- orphans: received a message which doesn't match an exchange\n"
  949. " (duplicate, late or not related)\n"
  950. "- locallimit: reached to local system limits when sending a message.\n"
  951. "\n"
  952. "Exit status:\n"
  953. "The exit status is:\n"
  954. "0 on complete success.\n"
  955. "1 for a general error.\n"
  956. "2 if an error is found in the command line arguments.\n"
  957. "3 if there are no general failures in operation, but one or more\n"
  958. " exchanges are not successfully completed.\n";
  959. }
  960. void
  961. CommandOptions::version() const {
  962. std::cout << "VERSION: " << VERSION << std::endl;
  963. }
  964. } // namespace perfdhcp
  965. } // namespace isc