pkt6.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. // Copyright (C) 2011-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/libdhcp++.h>
  16. #include <dhcp/pkt6.h>
  17. #include <exceptions/exceptions.h>
  18. #include <iostream>
  19. #include <sstream>
  20. using namespace std;
  21. using namespace isc::asiolink;
  22. namespace isc {
  23. namespace dhcp {
  24. Pkt6::RelayInfo::RelayInfo()
  25. :msg_type_(0), hop_count_(0), linkaddr_("::"), peeraddr_("::"), relay_msg_len_(0) {
  26. // interface_id_, subscriber_id_, remote_id_ initialized to NULL
  27. // echo_options_ initialized to empty collection
  28. }
  29. Pkt6::Pkt6(const uint8_t* buf, uint32_t buf_len, DHCPv6Proto proto /* = UDP */) :
  30. proto_(proto),
  31. msg_type_(0),
  32. transid_(rand()%0xffffff),
  33. iface_(""),
  34. ifindex_(-1),
  35. local_addr_("::"),
  36. remote_addr_("::"),
  37. local_port_(0),
  38. remote_port_(0),
  39. bufferOut_(0) {
  40. data_.resize(buf_len);
  41. memcpy(&data_[0], buf, buf_len);
  42. }
  43. Pkt6::Pkt6(uint8_t msg_type, uint32_t transid, DHCPv6Proto proto /*= UDP*/) :
  44. proto_(proto),
  45. msg_type_(msg_type),
  46. transid_(transid),
  47. iface_(""),
  48. ifindex_(-1),
  49. local_addr_("::"),
  50. remote_addr_("::"),
  51. local_port_(0),
  52. remote_port_(0),
  53. bufferOut_(0) {
  54. }
  55. uint16_t Pkt6::len() {
  56. if (relay_info_.empty()) {
  57. return (directLen());
  58. } else {
  59. // Unfortunately we need to re-calculate relay size every time, because
  60. // we need to make sure that once a new option is added, its extra size
  61. // is reflected in Pkt6::len().
  62. calculateRelaySizes();
  63. return (relay_info_[0].relay_msg_len_ + getRelayOverhead(relay_info_[0]));
  64. }
  65. }
  66. OptionPtr Pkt6::getAnyRelayOption(uint16_t opt_type, RelaySearchOrder order) {
  67. if (relay_info_.empty()) {
  68. // There's no relay info, this is a direct message
  69. return (OptionPtr());
  70. }
  71. int start = 0; // First relay to check
  72. int end = 0; // Last relay to check
  73. int direction = 0; // How we going to iterate: forward or backward?
  74. switch (order) {
  75. case RELAY_SEARCH_FROM_CLIENT:
  76. // Search backwards
  77. start = relay_info_.size() - 1;
  78. end = 0;
  79. direction = -1;
  80. break;
  81. case RELAY_SEARCH_FROM_SERVER:
  82. // Search forward
  83. start = 0;
  84. end = relay_info_.size() - 1;
  85. direction = 1;
  86. break;
  87. case RELAY_GET_FIRST:
  88. // Look at the innermost relay only
  89. start = relay_info_.size() - 1;
  90. end = start;
  91. direction = 1;
  92. break;
  93. case RELAY_GET_LAST:
  94. // Look at the outermost relay only
  95. start = 0;
  96. end = 0;
  97. direction = 1;
  98. }
  99. // This is a tricky loop. It must go from start to end, but it must work in
  100. // both directions (start > end; or start < end). We can't use regular
  101. // exit condition, because we don't know whether to use i <= end or i >= end.
  102. // That's why we check if in the next iteration we would go past the
  103. // list (end + direction). It is similar to STL concept of end pointing
  104. // to a place after the last element
  105. for (int i = start; i != end + direction; i += direction) {
  106. OptionPtr opt = getRelayOption(opt_type, i);
  107. if (opt) {
  108. return (opt);
  109. }
  110. }
  111. // We iterated over specified relays and haven't found what we were
  112. // looking for
  113. return (OptionPtr());
  114. }
  115. OptionPtr Pkt6::getRelayOption(uint16_t opt_type, uint8_t relay_level) {
  116. if (relay_level >= relay_info_.size()) {
  117. isc_throw(OutOfRange, "This message was relayed " << relay_info_.size() << " time(s)."
  118. << " There is no info about " << relay_level + 1 << " relay.");
  119. }
  120. for (Option::OptionCollection::iterator it = relay_info_[relay_level].options_.begin();
  121. it != relay_info_[relay_level].options_.end(); ++it) {
  122. if ((*it).second->getType() == opt_type) {
  123. return (it->second);
  124. }
  125. }
  126. return (OptionPtr());
  127. }
  128. uint16_t Pkt6::getRelayOverhead(const RelayInfo& relay) const {
  129. uint16_t len = DHCPV6_RELAY_HDR_LEN // fixed header
  130. + Option::OPTION6_HDR_LEN; // header of the relay-msg option
  131. for (Option::OptionCollection::const_iterator opt = relay.options_.begin();
  132. opt != relay.options_.end(); ++opt) {
  133. len += (opt->second)->len();
  134. }
  135. return (len);
  136. }
  137. uint16_t Pkt6::calculateRelaySizes() {
  138. uint16_t len = directLen(); // start with length of all options
  139. for (int relay_index = relay_info_.size(); relay_index > 0; --relay_index) {
  140. relay_info_[relay_index - 1].relay_msg_len_ = len;
  141. len += getRelayOverhead(relay_info_[relay_index - 1]);
  142. }
  143. return (len);
  144. }
  145. uint16_t Pkt6::directLen() const {
  146. uint16_t length = DHCPV6_PKT_HDR_LEN; // DHCPv6 header
  147. for (Option::OptionCollection::const_iterator it = options_.begin();
  148. it != options_.end();
  149. ++it) {
  150. length += (*it).second->len();
  151. }
  152. return (length);
  153. }
  154. void
  155. Pkt6::pack() {
  156. switch (proto_) {
  157. case UDP:
  158. packUDP();
  159. break;
  160. case TCP:
  161. packTCP();
  162. break;
  163. default:
  164. isc_throw(BadValue, "Invalid protocol specified (non-TCP, non-UDP)");
  165. }
  166. }
  167. void
  168. Pkt6::packUDP() {
  169. try {
  170. // is this a relayed packet?
  171. if (!relay_info_.empty()) {
  172. // calculate size needed for each relay (if there is only one relay,
  173. // then it will be equal to "regular" length + relay-forw header +
  174. // size of relay-msg option header + possibly size of interface-id
  175. // option (if present). If there is more than one relay, the whole
  176. // process is called iteratively for each relay.
  177. calculateRelaySizes();
  178. // Now for each relay, we need to...
  179. for (vector<RelayInfo>::iterator relay = relay_info_.begin();
  180. relay != relay_info_.end(); ++relay) {
  181. // build relay-forw/relay-repl header (see RFC3315, section 7)
  182. bufferOut_.writeUint8(relay->msg_type_);
  183. bufferOut_.writeUint8(relay->hop_count_);
  184. bufferOut_.writeData(&(relay->linkaddr_.toBytes()[0]),
  185. isc::asiolink::V6ADDRESS_LEN);
  186. bufferOut_.writeData(&relay->peeraddr_.toBytes()[0],
  187. isc::asiolink::V6ADDRESS_LEN);
  188. // store every option in this relay scope. Usually that will be
  189. // only interface-id, but occasionally other options may be
  190. // present here as well (vendor-opts for Cable modems,
  191. // subscriber-id, remote-id, options echoed back from Echo
  192. // Request Option, etc.)
  193. for (Option::OptionCollection::const_iterator opt =
  194. relay->options_.begin();
  195. opt != relay->options_.end(); ++opt) {
  196. (opt->second)->pack(bufferOut_);
  197. }
  198. // and include header relay-msg option. Its payload will be
  199. // generated in the next iteration (if there are more relays)
  200. // or outside the loop (if there are no more relays and the
  201. // payload is a direct message)
  202. bufferOut_.writeUint16(D6O_RELAY_MSG);
  203. bufferOut_.writeUint16(relay->relay_msg_len_);
  204. }
  205. }
  206. // DHCPv6 header: message-type (1 octect) + transaction id (3 octets)
  207. bufferOut_.writeUint8(msg_type_);
  208. // store 3-octet transaction-id
  209. bufferOut_.writeUint8( (transid_ >> 16) & 0xff );
  210. bufferOut_.writeUint8( (transid_ >> 8) & 0xff );
  211. bufferOut_.writeUint8( (transid_) & 0xff );
  212. // the rest are options
  213. LibDHCP::packOptions(bufferOut_, options_);
  214. }
  215. catch (const Exception& e) {
  216. // An exception is thrown and message will be written to Logger
  217. isc_throw(InvalidOperation, e.what());
  218. }
  219. }
  220. void
  221. Pkt6::packTCP() {
  222. /// TODO Implement this function.
  223. isc_throw(NotImplemented, "DHCPv6 over TCP (bulk leasequery and failover)"
  224. "not implemented yet.");
  225. }
  226. bool
  227. Pkt6::unpack() {
  228. switch (proto_) {
  229. case UDP:
  230. return unpackUDP();
  231. case TCP:
  232. return unpackTCP();
  233. default:
  234. isc_throw(BadValue, "Invalid protocol specified (non-TCP, non-UDP)");
  235. }
  236. return (false); // never happens
  237. }
  238. bool
  239. Pkt6::unpackUDP() {
  240. if (data_.size() < 4) {
  241. // @todo: throw exception here informing that packet is truncated
  242. // once we turn this function to void.
  243. return (false);
  244. }
  245. msg_type_ = data_[0];
  246. switch (msg_type_) {
  247. case DHCPV6_SOLICIT:
  248. case DHCPV6_ADVERTISE:
  249. case DHCPV6_REQUEST:
  250. case DHCPV6_CONFIRM:
  251. case DHCPV6_RENEW:
  252. case DHCPV6_REBIND:
  253. case DHCPV6_REPLY:
  254. case DHCPV6_DECLINE:
  255. case DHCPV6_RECONFIGURE:
  256. case DHCPV6_INFORMATION_REQUEST:
  257. default: // assume that uknown messages are not using relay format
  258. {
  259. return (unpackMsg(data_.begin(), data_.end()));
  260. }
  261. case DHCPV6_RELAY_FORW:
  262. case DHCPV6_RELAY_REPL:
  263. return (unpackRelayMsg());
  264. }
  265. }
  266. bool
  267. Pkt6::unpackMsg(OptionBuffer::const_iterator begin,
  268. OptionBuffer::const_iterator end) {
  269. if (std::distance(begin, end) < 4) {
  270. // truncated message (less than 4 bytes)
  271. return (false);
  272. }
  273. msg_type_ = *begin++;
  274. transid_ = ( (*begin++) << 16 ) +
  275. ((*begin++) << 8) + (*begin++);
  276. transid_ = transid_ & 0xffffff;
  277. try {
  278. OptionBuffer opt_buffer(begin, end);
  279. LibDHCP::unpackOptions6(opt_buffer, options_);
  280. } catch (const Exception& e) {
  281. // @todo: throw exception here once we turn this function to void.
  282. return (false);
  283. }
  284. return (true);
  285. }
  286. bool
  287. Pkt6::unpackRelayMsg() {
  288. // we use offset + bufsize, because we want to avoid creating unnecessary
  289. // copies. There may be up to 32 relays. While using InputBuffer would
  290. // be probably a bit cleaner, copying data up to 32 times is unacceptable
  291. // price here. Hence a single buffer with offets and lengths.
  292. size_t bufsize = data_.size();
  293. size_t offset = 0;
  294. while (bufsize >= DHCPV6_RELAY_HDR_LEN) {
  295. RelayInfo relay;
  296. size_t relay_msg_offset = 0;
  297. size_t relay_msg_len = 0;
  298. // parse fixed header first (first 34 bytes)
  299. relay.msg_type_ = data_[offset++];
  300. relay.hop_count_ = data_[offset++];
  301. relay.linkaddr_ = IOAddress::fromBytes(AF_INET6, &data_[offset]);
  302. offset += isc::asiolink::V6ADDRESS_LEN;
  303. relay.peeraddr_ = IOAddress::fromBytes(AF_INET6, &data_[offset]);
  304. offset += isc::asiolink::V6ADDRESS_LEN;
  305. bufsize -= DHCPV6_RELAY_HDR_LEN; // 34 bytes (1+1+16+16)
  306. try {
  307. // parse the rest as options
  308. OptionBuffer opt_buffer(&data_[offset], &data_[offset+bufsize]);
  309. LibDHCP::unpackOptions6(opt_buffer, relay.options_, &relay_msg_offset,
  310. &relay_msg_len);
  311. /// @todo: check that each option appears at most once
  312. //relay.interface_id_ = options->getOption(D6O_INTERFACE_ID);
  313. //relay.subscriber_id_ = options->getOption(D6O_SUBSCRIBER_ID);
  314. //relay.remote_id_ = options->getOption(D6O_REMOTE_ID);
  315. if (relay_msg_offset == 0 || relay_msg_len == 0) {
  316. isc_throw(BadValue, "Mandatory relay-msg option missing");
  317. }
  318. // store relay information parsed so far
  319. addRelayInfo(relay);
  320. /// @todo: implement ERO here
  321. if (relay_msg_len >= bufsize) {
  322. // length of the relay_msg option extends beyond end of the message
  323. isc_throw(Unexpected, "Relay-msg option is truncated.");
  324. return false;
  325. }
  326. uint8_t inner_type = data_[offset + relay_msg_offset];
  327. offset += relay_msg_offset; // offset is relative
  328. bufsize = relay_msg_len; // length is absolute
  329. if ( (inner_type != DHCPV6_RELAY_FORW) &&
  330. (inner_type != DHCPV6_RELAY_REPL)) {
  331. // Ok, the inner message is not encapsulated, let's decode it
  332. // directly
  333. return (unpackMsg(data_.begin() + offset, data_.begin() + offset
  334. + relay_msg_len));
  335. }
  336. // Oh well, there's inner relay-forw or relay-repl inside. Let's
  337. // unpack it as well. The next loop iteration will take care
  338. // of that.
  339. } catch (const Exception& e) {
  340. /// @todo: throw exception here once we turn this function to void.
  341. return (false);
  342. }
  343. }
  344. if ( (offset == data_.size()) && (bufsize == 0) ) {
  345. // message has been parsed completely
  346. return (true);
  347. }
  348. /// @todo: log here that there are additional unparsed bytes
  349. return (true);
  350. }
  351. void
  352. Pkt6::addRelayInfo(const RelayInfo& relay) {
  353. if (relay_info_.size() > 32) {
  354. isc_throw(BadValue, "Massage cannot be encapsulated more than 32 times");
  355. }
  356. /// @todo: Implement type checks here (e.g. we could receive relay-forw in relay-repl)
  357. relay_info_.push_back(relay);
  358. }
  359. bool
  360. Pkt6::unpackTCP() {
  361. isc_throw(Unexpected, "DHCPv6 over TCP (bulk leasequery and failover) "
  362. "not implemented yet.");
  363. }
  364. std::string
  365. Pkt6::toText() {
  366. stringstream tmp;
  367. tmp << "localAddr=[" << local_addr_.toText() << "]:" << local_port_
  368. << " remoteAddr=[" << remote_addr_.toText()
  369. << "]:" << remote_port_ << endl;
  370. tmp << "msgtype=" << static_cast<int>(msg_type_) << ", transid=0x" <<
  371. hex << transid_ << dec << endl;
  372. for (isc::dhcp::Option::OptionCollection::iterator opt=options_.begin();
  373. opt != options_.end();
  374. ++opt) {
  375. tmp << opt->second->toText() << std::endl;
  376. }
  377. return tmp.str();
  378. }
  379. OptionPtr
  380. Pkt6::getOption(uint16_t opt_type) {
  381. isc::dhcp::Option::OptionCollection::const_iterator x = options_.find(opt_type);
  382. if (x!=options_.end()) {
  383. return (*x).second;
  384. }
  385. return OptionPtr(); // NULL
  386. }
  387. isc::dhcp::Option::OptionCollection
  388. Pkt6::getOptions(uint16_t opt_type) {
  389. isc::dhcp::Option::OptionCollection found;
  390. for (Option::OptionCollection::const_iterator x = options_.begin();
  391. x != options_.end(); ++x) {
  392. if (x->first == opt_type) {
  393. found.insert(make_pair(opt_type, x->second));
  394. }
  395. }
  396. return (found);
  397. }
  398. void
  399. Pkt6::addOption(const OptionPtr& opt) {
  400. options_.insert(pair<int, boost::shared_ptr<Option> >(opt->getType(), opt));
  401. }
  402. bool
  403. Pkt6::delOption(uint16_t type) {
  404. isc::dhcp::Option::OptionCollection::iterator x = options_.find(type);
  405. if (x!=options_.end()) {
  406. options_.erase(x);
  407. return (true); // delete successful
  408. }
  409. return (false); // can't find option to be deleted
  410. }
  411. void Pkt6::repack() {
  412. bufferOut_.writeData(&data_[0], data_.size());
  413. }
  414. void
  415. Pkt6::updateTimestamp() {
  416. timestamp_ = boost::posix_time::microsec_clock::universal_time();
  417. }
  418. const char*
  419. Pkt6::getName(uint8_t type) {
  420. static const char* CONFIRM = "CONFIRM";
  421. static const char* DECLINE = "DECLINE";
  422. static const char* INFORMATION_REQUEST = "INFORMATION_REQUEST";
  423. static const char* REBIND = "REBIND";
  424. static const char* RELEASE = "RELEASE";
  425. static const char* RENEW = "RENEW";
  426. static const char* REQUEST = "REQUEST";
  427. static const char* SOLICIT = "SOLICIT";
  428. static const char* UNKNOWN = "UNKNOWN";
  429. switch (type) {
  430. case DHCPV6_CONFIRM:
  431. return (CONFIRM);
  432. case DHCPV6_DECLINE:
  433. return (DECLINE);
  434. case DHCPV6_INFORMATION_REQUEST:
  435. return (INFORMATION_REQUEST);
  436. case DHCPV6_REBIND:
  437. return (REBIND);
  438. case DHCPV6_RELEASE:
  439. return (RELEASE);
  440. case DHCPV6_RENEW:
  441. return (RENEW);
  442. case DHCPV6_REQUEST:
  443. return (REQUEST);
  444. case DHCPV6_SOLICIT:
  445. return (SOLICIT);
  446. default:
  447. ;
  448. }
  449. return (UNKNOWN);
  450. }
  451. const char* Pkt6::getName() const {
  452. return (getName(getType()));
  453. }
  454. void Pkt6::copyRelayInfo(const Pkt6Ptr& question) {
  455. // We use index rather than iterator, because we need that as a parameter
  456. // passed to getRelayOption()
  457. for (int i = 0; i < question->relay_info_.size(); ++i) {
  458. RelayInfo info;
  459. info.msg_type_ = DHCPV6_RELAY_REPL;
  460. info.hop_count_ = question->relay_info_[i].hop_count_;
  461. info.linkaddr_ = question->relay_info_[i].linkaddr_;
  462. info.peeraddr_ = question->relay_info_[i].peeraddr_;
  463. // Is there an interface-id option in this nesting level?
  464. // If there is, we need to echo it back
  465. OptionPtr opt = question->getRelayOption(D6O_INTERFACE_ID, i);
  466. // taken from question->RelayInfo_[i].options_
  467. if (opt) {
  468. info.options_.insert(make_pair(opt->getType(), opt));
  469. }
  470. /// @todo: Implement support for ERO (Echo Request Option, RFC4994)
  471. // Add this relay-forw info (client's message) to our relay-repl
  472. // message (server's response)
  473. relay_info_.push_back(info);
  474. }
  475. }
  476. } // end of isc::dhcp namespace
  477. } // end of isc namespace