pkt6.cc 18 KB

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