option_definition.cc 19 KB

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