option_definition.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 <dhcp/dhcp6.h>
  15. #include <dhcp/option4_addrlst.h>
  16. #include <dhcp/option6_addrlst.h>
  17. #include <dhcp/option6_ia.h>
  18. #include <dhcp/option6_iaaddr.h>
  19. #include <dhcp/option_custom.h>
  20. #include <dhcp/option_definition.h>
  21. #include <dhcp/option_int.h>
  22. #include <dhcp/option_int_array.h>
  23. #include <dhcp/option_space.h>
  24. #include <util/encode/hex.h>
  25. #include <util/strutil.h>
  26. #include <boost/algorithm/string/classification.hpp>
  27. #include <boost/algorithm/string/predicate.hpp>
  28. using namespace std;
  29. using namespace isc::util;
  30. namespace isc {
  31. namespace dhcp {
  32. OptionDefinition::OptionDefinition(const std::string& name,
  33. const uint16_t code,
  34. const std::string& type,
  35. const bool array_type /* = false */)
  36. : name_(name),
  37. code_(code),
  38. type_(OPT_UNKNOWN_TYPE),
  39. array_type_(array_type),
  40. encapsulated_space_("") {
  41. // Data type is held as enum value by this class.
  42. // Use the provided option type string to get the
  43. // corresponding enum value.
  44. type_ = OptionDataTypeUtil::getDataType(type);
  45. }
  46. OptionDefinition::OptionDefinition(const std::string& name,
  47. const uint16_t code,
  48. const OptionDataType type,
  49. const bool array_type /* = false */)
  50. : name_(name),
  51. code_(code),
  52. type_(type),
  53. array_type_(array_type),
  54. encapsulated_space_("") {
  55. }
  56. OptionDefinition::OptionDefinition(const std::string& name,
  57. const uint16_t code,
  58. const std::string& type,
  59. const char* encapsulated_space)
  60. : name_(name),
  61. code_(code),
  62. // Data type is held as enum value by this class.
  63. // Use the provided option type string to get the
  64. // corresponding enum value.
  65. type_(OptionDataTypeUtil::getDataType(type)),
  66. array_type_(false),
  67. encapsulated_space_(encapsulated_space) {
  68. }
  69. OptionDefinition::OptionDefinition(const std::string& name,
  70. const uint16_t code,
  71. const OptionDataType type,
  72. const char* encapsulated_space)
  73. : name_(name),
  74. code_(code),
  75. type_(type),
  76. array_type_(false),
  77. encapsulated_space_(encapsulated_space) {
  78. }
  79. void
  80. OptionDefinition::addRecordField(const std::string& data_type_name) {
  81. OptionDataType data_type = OptionDataTypeUtil::getDataType(data_type_name);
  82. addRecordField(data_type);
  83. }
  84. void
  85. OptionDefinition::addRecordField(const OptionDataType data_type) {
  86. if (type_ != OPT_RECORD_TYPE) {
  87. isc_throw(isc::InvalidOperation, "'record' option type must be used"
  88. " to add data fields to the record");
  89. }
  90. if (data_type >= OPT_RECORD_TYPE ||
  91. data_type == OPT_ANY_ADDRESS_TYPE ||
  92. data_type == OPT_EMPTY_TYPE) {
  93. isc_throw(isc::BadValue, "attempted to add invalid data type to the record.");
  94. }
  95. record_fields_.push_back(data_type);
  96. }
  97. OptionPtr
  98. OptionDefinition::optionFactory(Option::Universe u, uint16_t type,
  99. OptionBufferConstIter begin,
  100. OptionBufferConstIter end) const {
  101. validate();
  102. try {
  103. switch(type_) {
  104. case OPT_EMPTY_TYPE:
  105. return (factoryEmpty(u, type));
  106. case OPT_BINARY_TYPE:
  107. return (factoryGeneric(u, type, begin, end));
  108. case OPT_UINT8_TYPE:
  109. return (array_type_ ? factoryGeneric(u, type, begin, end) :
  110. factoryInteger<uint8_t>(u, type, begin, end));
  111. case OPT_INT8_TYPE:
  112. return (array_type_ ? factoryGeneric(u, type, begin, end) :
  113. factoryInteger<int8_t>(u, type, begin, end));
  114. case OPT_UINT16_TYPE:
  115. return (array_type_ ? factoryIntegerArray<uint16_t>(u, type, begin, end) :
  116. factoryInteger<uint16_t>(u, type, begin, end));
  117. case OPT_INT16_TYPE:
  118. return (array_type_ ? factoryIntegerArray<uint16_t>(u, type, begin, end) :
  119. factoryInteger<int16_t>(u, type, begin, end));
  120. case OPT_UINT32_TYPE:
  121. return (array_type_ ? factoryIntegerArray<uint32_t>(u, type, begin, end) :
  122. factoryInteger<uint32_t>(u, type, begin, end));
  123. case OPT_INT32_TYPE:
  124. return (array_type_ ? factoryIntegerArray<uint32_t>(u, type, begin, end) :
  125. factoryInteger<int32_t>(u, type, begin, end));
  126. case OPT_IPV4_ADDRESS_TYPE:
  127. // If definition specifies that an option is an array
  128. // of IPv4 addresses we return an instance of specialized
  129. // class (OptionAddrLst4). For non-array types there is no
  130. // specialized class yet implemented so we drop through
  131. // to return an instance of OptionCustom.
  132. if (array_type_) {
  133. return (factoryAddrList4(type, begin, end));
  134. }
  135. break;
  136. case OPT_IPV6_ADDRESS_TYPE:
  137. // Handle array type only here (see comments for
  138. // OPT_IPV4_ADDRESS_TYPE case).
  139. if (array_type_) {
  140. return (factoryAddrList6(type, begin, end));
  141. }
  142. break;
  143. default:
  144. if (u == Option::V6) {
  145. if ((code_ == D6O_IA_NA || code_ == D6O_IA_PD) &&
  146. haveIA6Format()) {
  147. // Return Option6IA instance for IA_PD and IA_NA option
  148. // types only. We don't want to return Option6IA for other
  149. // options that comprise 3 UINT32 data fields because
  150. // Option6IA accessors' and modifiers' names are derived
  151. // from the IA_NA and IA_PD options' field names: IAID,
  152. // T1, T2. Using functions such as getIAID, getT1 etc. for
  153. // options other than IA_NA and IA_PD would be bad practice
  154. // and cause confusion.
  155. return (factoryIA6(type, begin, end));
  156. } else if (code_ == D6O_IAADDR && haveIAAddr6Format()) {
  157. // Rerurn Option6IAAddr option instance for the IAADDR
  158. // option only for the same reasons as described in
  159. // for IA_NA and IA_PD above.
  160. return (factoryIAAddr6(type, begin, end));
  161. }
  162. }
  163. }
  164. return (OptionPtr(new OptionCustom(*this, u, OptionBuffer(begin, end))));
  165. } catch (const Exception& ex) {
  166. isc_throw(InvalidOptionValue, ex.what());
  167. }
  168. }
  169. OptionPtr
  170. OptionDefinition::optionFactory(Option::Universe u, uint16_t type,
  171. const OptionBuffer& buf) const {
  172. return (optionFactory(u, type, buf.begin(), buf.end()));
  173. }
  174. OptionPtr
  175. OptionDefinition::optionFactory(Option::Universe u, uint16_t type,
  176. const std::vector<std::string>& values) const {
  177. validate();
  178. OptionBuffer buf;
  179. if (!array_type_ && type_ != OPT_RECORD_TYPE) {
  180. if (values.empty()) {
  181. isc_throw(InvalidOptionValue, "no option value specified");
  182. }
  183. writeToBuffer(util::str::trim(values[0]), type_, buf);
  184. } else if (array_type_ && type_ != OPT_RECORD_TYPE) {
  185. for (size_t i = 0; i < values.size(); ++i) {
  186. writeToBuffer(util::str::trim(values[i]), type_, buf);
  187. }
  188. } else if (type_ == OPT_RECORD_TYPE) {
  189. const RecordFieldsCollection& records = getRecordFields();
  190. if (records.size() > values.size()) {
  191. isc_throw(InvalidOptionValue, "number of data fields for the option"
  192. << " type '" << getCode() << "' is greater than number"
  193. << " of values provided.");
  194. }
  195. for (size_t i = 0; i < records.size(); ++i) {
  196. writeToBuffer(util::str::trim(values[i]),
  197. records[i], buf);
  198. }
  199. }
  200. return (optionFactory(u, type, buf.begin(), buf.end()));
  201. }
  202. void
  203. OptionDefinition::sanityCheckUniverse(const Option::Universe expected_universe,
  204. const Option::Universe actual_universe) {
  205. if (expected_universe != actual_universe) {
  206. isc_throw(isc::BadValue, "invalid universe specified for the option");
  207. }
  208. }
  209. void
  210. OptionDefinition::validate() const {
  211. using namespace boost::algorithm;
  212. std::ostringstream err_str;
  213. // Allowed characters in the option name are: lower or
  214. // upper case letters, digits, underscores and hyphens.
  215. // Empty option spaces are not allowed.
  216. if (!all(name_, boost::is_from_range('a', 'z') ||
  217. boost::is_from_range('A', 'Z') ||
  218. boost::is_digit() ||
  219. boost::is_any_of(std::string("-_"))) ||
  220. name_.empty() ||
  221. // Hyphens and underscores are not allowed at the beginning
  222. // and at the end of the option name.
  223. all(find_head(name_, 1), boost::is_any_of(std::string("-_"))) ||
  224. all(find_tail(name_, 1), boost::is_any_of(std::string("-_")))) {
  225. err_str << "invalid option name '" << name_ << "'";
  226. } else if (!encapsulated_space_.empty() &&
  227. !OptionSpace::validateName(encapsulated_space_)) {
  228. err_str << "invalid encapsulated option space name: '"
  229. << encapsulated_space_ << "'";
  230. } else if (type_ >= OPT_UNKNOWN_TYPE) {
  231. // Option definition must be of a known type.
  232. err_str << "option type value " << type_ << " is out of range.";
  233. } else if (array_type_) {
  234. if (type_ == OPT_STRING_TYPE) {
  235. // Array of strings is not allowed because there is no way
  236. // to determine the size of a particular string and thus there
  237. // it no way to tell when other data fields begin.
  238. err_str << "array of strings is not a valid option definition.";
  239. } else if (type_ == OPT_BINARY_TYPE) {
  240. err_str << "array of binary values is not a valid option definition.";
  241. } else if (type_ == OPT_EMPTY_TYPE) {
  242. err_str << "array of empty value is not a valid option definition.";
  243. }
  244. } else if (type_ == OPT_RECORD_TYPE) {
  245. // At least two data fields should be added to the record. Otherwise
  246. // non-record option definition could be used.
  247. if (getRecordFields().size() < 2) {
  248. err_str << "invalid number of data fields: " << getRecordFields().size()
  249. << " specified for the option of type 'record'. Expected at"
  250. << " least 2 fields.";
  251. } else {
  252. // If the number of fields is valid we have to check if their order
  253. // is valid too. We check that string or binary data fields are not
  254. // laid before other fields. But we allow that they are laid at the end of
  255. // an option.
  256. const RecordFieldsCollection& fields = getRecordFields();
  257. for (RecordFieldsConstIter it = fields.begin();
  258. it != fields.end(); ++it) {
  259. if (*it == OPT_STRING_TYPE &&
  260. it < fields.end() - 1) {
  261. err_str << "string data field can't be laid before data fields"
  262. << " of other types.";
  263. break;
  264. }
  265. if (*it == OPT_BINARY_TYPE &&
  266. it < fields.end() - 1) {
  267. err_str << "binary data field can't be laid before data fields"
  268. << " of other types.";
  269. }
  270. /// Empty type is not allowed within a record.
  271. if (*it == OPT_EMPTY_TYPE) {
  272. err_str << "empty data type can't be stored as a field in an"
  273. << " option record.";
  274. break;
  275. }
  276. }
  277. }
  278. }
  279. // Non-empty error string means that we have hit the error. We throw
  280. // exception and include error string.
  281. if (!err_str.str().empty()) {
  282. isc_throw(MalformedOptionDefinition, err_str.str());
  283. }
  284. }
  285. bool
  286. OptionDefinition::haveIAx6Format(OptionDataType first_type) const {
  287. return (haveType(OPT_RECORD_TYPE) &&
  288. record_fields_.size() == 3 &&
  289. record_fields_[0] == first_type &&
  290. record_fields_[1] == OPT_UINT32_TYPE &&
  291. record_fields_[2] == OPT_UINT32_TYPE);
  292. }
  293. bool
  294. OptionDefinition::haveIA6Format() const {
  295. // Expect that IA_NA option format is defined as record.
  296. // Although it consists of 3 elements of the same (uint32)
  297. // type it can't be defined as array of uint32 elements because
  298. // arrays do not impose limitations on number of elements in
  299. // the array while this limitation is needed for IA_NA - need
  300. // exactly 3 elements.
  301. return (haveIAx6Format(OPT_UINT32_TYPE));
  302. }
  303. bool
  304. OptionDefinition::haveIAAddr6Format() const {
  305. return (haveIAx6Format(OPT_IPV6_ADDRESS_TYPE));
  306. }
  307. template<typename T>
  308. T OptionDefinition::lexicalCastWithRangeCheck(const std::string& value_str) const {
  309. // Lexical cast in case of our data types make sense only
  310. // for uintX_t, intX_t and bool type.
  311. if (!OptionDataTypeTraits<T>::integer_type &&
  312. OptionDataTypeTraits<T>::type != OPT_BOOLEAN_TYPE) {
  313. isc_throw(BadDataTypeCast, "unable to do lexical cast to non-integer and"
  314. << " non-boolean data type");
  315. }
  316. // We use the 64-bit value here because it has wider range than
  317. // any other type we use here and it allows to detect out of
  318. // bounds conditions e.g. negative value specified for uintX_t
  319. // data type. Obviously if the value exceeds the limits of int64
  320. // this function will not handle that properly.
  321. int64_t result = 0;
  322. try {
  323. result = boost::lexical_cast<int64_t>(value_str);
  324. } catch (const boost::bad_lexical_cast& ex) {
  325. // Prepare error message here.
  326. std::string data_type_str = "boolean";
  327. if (OptionDataTypeTraits<T>::integer_type) {
  328. data_type_str = "integer";
  329. }
  330. isc_throw(BadDataTypeCast, "unable to do lexical cast to " << data_type_str
  331. << " data type for value " << value_str << ": " << ex.what());
  332. }
  333. // Perform range checks for integer values only (exclude bool values).
  334. if (OptionDataTypeTraits<T>::integer_type) {
  335. if (result > numeric_limits<T>::max() ||
  336. result < numeric_limits<T>::min()) {
  337. isc_throw(BadDataTypeCast, "unable to do lexical cast for value "
  338. << value_str << ". This value is expected to be in the range of "
  339. << numeric_limits<T>::min() << ".." << numeric_limits<T>::max());
  340. }
  341. }
  342. return (static_cast<T>(result));
  343. }
  344. void
  345. OptionDefinition::writeToBuffer(const std::string& value,
  346. const OptionDataType type,
  347. OptionBuffer& buf) const {
  348. // We are going to write value given by value argument to the buffer.
  349. // The actual type of the value is given by second argument. Check
  350. // this argument to determine how to write this value to the buffer.
  351. switch (type) {
  352. case OPT_BINARY_TYPE:
  353. OptionDataTypeUtil::writeBinary(value, buf);
  354. return;
  355. case OPT_BOOLEAN_TYPE:
  356. // We encode the true value as 1 and false as 0 on 8 bits.
  357. // That way we actually waste 7 bits but it seems to be the
  358. // simpler way to encode boolean.
  359. // @todo Consider if any other encode methods can be used.
  360. OptionDataTypeUtil::writeBool(lexicalCastWithRangeCheck<bool>(value), buf);
  361. return;
  362. case OPT_INT8_TYPE:
  363. OptionDataTypeUtil::writeInt<uint8_t>(lexicalCastWithRangeCheck<int8_t>(value),
  364. buf);
  365. return;
  366. case OPT_INT16_TYPE:
  367. OptionDataTypeUtil::writeInt<uint16_t>(lexicalCastWithRangeCheck<int16_t>(value),
  368. buf);
  369. return;
  370. case OPT_INT32_TYPE:
  371. OptionDataTypeUtil::writeInt<uint32_t>(lexicalCastWithRangeCheck<int32_t>(value),
  372. buf);
  373. return;
  374. case OPT_UINT8_TYPE:
  375. OptionDataTypeUtil::writeInt<uint8_t>(lexicalCastWithRangeCheck<uint8_t>(value),
  376. buf);
  377. return;
  378. case OPT_UINT16_TYPE:
  379. OptionDataTypeUtil::writeInt<uint16_t>(lexicalCastWithRangeCheck<uint16_t>(value),
  380. buf);
  381. return;
  382. case OPT_UINT32_TYPE:
  383. OptionDataTypeUtil::writeInt<uint32_t>(lexicalCastWithRangeCheck<uint32_t>(value),
  384. buf);
  385. return;
  386. case OPT_IPV4_ADDRESS_TYPE:
  387. case OPT_IPV6_ADDRESS_TYPE:
  388. {
  389. asiolink::IOAddress address(value);
  390. if (!address.isV4() && !address.isV6()) {
  391. isc_throw(BadDataTypeCast, "provided address " << address.toText()
  392. << " is not a valid IPv4 or IPv6 address.");
  393. }
  394. OptionDataTypeUtil::writeAddress(address, buf);
  395. return;
  396. }
  397. case OPT_STRING_TYPE:
  398. OptionDataTypeUtil::writeString(value, buf);
  399. return;
  400. case OPT_FQDN_TYPE:
  401. OptionDataTypeUtil::writeFqdn(value, buf);
  402. return;
  403. default:
  404. // We hit this point because invalid option data type has been specified
  405. // This may be the case because 'empty' or 'record' data type has been
  406. // specified. We don't throw exception here because it will be thrown
  407. // at the exit point from this function.
  408. ;
  409. }
  410. isc_throw(isc::BadValue, "attempt to write invalid option data field type"
  411. " into the option buffer: " << type);
  412. }
  413. OptionPtr
  414. OptionDefinition::factoryAddrList4(uint16_t type,
  415. OptionBufferConstIter begin,
  416. OptionBufferConstIter end) {
  417. boost::shared_ptr<Option4AddrLst> option(new Option4AddrLst(type, begin, end));
  418. return (option);
  419. }
  420. OptionPtr
  421. OptionDefinition::factoryAddrList6(uint16_t type,
  422. OptionBufferConstIter begin,
  423. OptionBufferConstIter end) {
  424. boost::shared_ptr<Option6AddrLst> option(new Option6AddrLst(type, begin, end));
  425. return (option);
  426. }
  427. OptionPtr
  428. OptionDefinition::factoryEmpty(Option::Universe u, uint16_t type) {
  429. OptionPtr option(new Option(u, type));
  430. return (option);
  431. }
  432. OptionPtr
  433. OptionDefinition::factoryGeneric(Option::Universe u, uint16_t type,
  434. OptionBufferConstIter begin,
  435. OptionBufferConstIter end) {
  436. OptionPtr option(new Option(u, type, begin, end));
  437. return (option);
  438. }
  439. OptionPtr
  440. OptionDefinition::factoryIA6(uint16_t type,
  441. OptionBufferConstIter begin,
  442. OptionBufferConstIter end) {
  443. if (std::distance(begin, end) < Option6IA::OPTION6_IA_LEN) {
  444. isc_throw(isc::OutOfRange, "input option buffer has invalid size, expected "
  445. "at least " << Option6IA::OPTION6_IA_LEN << " bytes");
  446. }
  447. boost::shared_ptr<Option6IA> option(new Option6IA(type, begin, end));
  448. return (option);
  449. }
  450. OptionPtr
  451. OptionDefinition::factoryIAAddr6(uint16_t type,
  452. OptionBufferConstIter begin,
  453. OptionBufferConstIter end) {
  454. if (std::distance(begin, end) < Option6IAAddr::OPTION6_IAADDR_LEN) {
  455. isc_throw(isc::OutOfRange, "input option buffer has invalid size, expected "
  456. " at least " << Option6IAAddr::OPTION6_IAADDR_LEN << " bytes");
  457. }
  458. boost::shared_ptr<Option6IAAddr> option(new Option6IAAddr(type, begin, end));
  459. return (option);
  460. }
  461. } // end of isc::dhcp namespace
  462. } // end of isc namespace