iface_mgr.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. // Copyright (C) 2011 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 <sstream>
  15. #include <fstream>
  16. #include <string.h>
  17. #include <netinet/in.h>
  18. #include <arpa/inet.h>
  19. #include <dhcp/dhcp6.h>
  20. #include <dhcp/iface_mgr.h>
  21. #include <exceptions/exceptions.h>
  22. using namespace std;
  23. using namespace isc;
  24. using namespace isc::asiolink;
  25. using namespace isc::dhcp;
  26. namespace isc {
  27. /// IfaceMgr is a singleton implementation
  28. IfaceMgr* IfaceMgr::instance_ = 0;
  29. void
  30. IfaceMgr::instanceCreate() {
  31. if (instance_) {
  32. // no need to do anything. Instance is already created.
  33. // Who called it again anyway? Uh oh. Had to be us, as
  34. // this is private method.
  35. return;
  36. }
  37. instance_ = new IfaceMgr();
  38. }
  39. IfaceMgr&
  40. IfaceMgr::instance() {
  41. if (instance_ == 0) {
  42. instanceCreate();
  43. }
  44. return (*instance_);
  45. }
  46. IfaceMgr::Iface::Iface(const std::string& name, int ifindex)
  47. :name_(name), ifindex_(ifindex), mac_len_(0) {
  48. memset(mac_, 0, sizeof(mac_));
  49. }
  50. std::string
  51. IfaceMgr::Iface::getFullName() const {
  52. ostringstream tmp;
  53. tmp << name_ << "/" << ifindex_;
  54. return (tmp.str());
  55. }
  56. std::string
  57. IfaceMgr::Iface::getPlainMac() const {
  58. ostringstream tmp;
  59. tmp.fill('0');
  60. tmp << hex;
  61. for (int i = 0; i < mac_len_; i++) {
  62. tmp.width(2);
  63. tmp << mac_[i];
  64. if (i < mac_len_-1) {
  65. tmp << ":";
  66. }
  67. }
  68. return (tmp.str());
  69. }
  70. bool IfaceMgr::Iface::delAddress(const isc::asiolink::IOAddress& addr) {
  71. // Let's delete all addresses that match. It really shouldn't matter
  72. // if we delete first or all, as the OS should allow to add a single
  73. // address to an interface only once. If OS allows multiple instances
  74. // of the same address added, we are in deep problems anyway.
  75. size_t size = addrs_.size();
  76. addrs_.erase(remove(addrs_.begin(), addrs_.end(), addr), addrs_.end());
  77. return (addrs_.size() < size);
  78. }
  79. bool IfaceMgr::Iface::delSocket(uint16_t sockfd) {
  80. list<SocketInfo>::iterator sock = sockets_.begin();
  81. while (sock!=sockets_.end()) {
  82. if (sock->sockfd_ == sockfd) {
  83. close(sockfd);
  84. sockets_.erase(sock);
  85. return (true); //socket found
  86. }
  87. ++sock;
  88. }
  89. return (false); // socket not found
  90. }
  91. IfaceMgr::IfaceMgr()
  92. :control_buf_len_(CMSG_SPACE(sizeof(struct in6_pktinfo))),
  93. control_buf_(new char[control_buf_len_])
  94. {
  95. cout << "IfaceMgr initialization." << endl;
  96. try {
  97. // required for sending/receiving packets
  98. // let's keep it in front, just in case someone
  99. // wants to send anything during initialization
  100. // control_buf_ = boost::scoped_array<char>();
  101. detectIfaces();
  102. } catch (const std::exception& ex) {
  103. cout << "IfaceMgr creation failed:" << ex.what() << endl;
  104. // TODO Uncomment this (or call LOG_FATAL) once
  105. // interface detection is implemented. Otherwise
  106. // it is not possible to run tests in a portable
  107. // way (see detectIfaces() method).
  108. // throw ex;
  109. }
  110. }
  111. void IfaceMgr::closeSockets() {
  112. for (IfaceCollection::iterator iface = ifaces_.begin();
  113. iface != ifaces_.end(); ++iface) {
  114. for (SocketCollection::iterator sock = iface->sockets_.begin();
  115. sock != iface->sockets_.end(); ++sock) {
  116. cout << "Closing socket " << sock->sockfd_ << endl;
  117. close(sock->sockfd_);
  118. }
  119. iface->sockets_.clear();
  120. }
  121. }
  122. IfaceMgr::~IfaceMgr() {
  123. closeSockets();
  124. // control_buf_ is deleted automatically (scoped_ptr)
  125. control_buf_len_ = 0;
  126. }
  127. void
  128. IfaceMgr::detectIfaces() {
  129. string ifaceName, linkLocal;
  130. // TODO do the actual detection. Currently interface detection is faked
  131. // by reading a text file.
  132. cout << "Interface detection is not implemented yet. "
  133. << "Reading interfaces.txt file instead." << endl;
  134. cout << "Please use format: interface-name link-local-address" << endl;
  135. try {
  136. ifstream interfaces("interfaces.txt");
  137. if (!interfaces.good()) {
  138. cout << "Failed to read interfaces.txt file." << endl;
  139. isc_throw(Unexpected, "Failed to read interfaces.txt");
  140. }
  141. interfaces >> ifaceName;
  142. interfaces >> linkLocal;
  143. cout << "Detected interface " << ifaceName << "/" << linkLocal << endl;
  144. Iface iface(ifaceName, if_nametoindex( ifaceName.c_str() ) );
  145. IOAddress addr(linkLocal);
  146. iface.addAddress(addr);
  147. addInterface(iface);
  148. interfaces.close();
  149. } catch (const std::exception& ex) {
  150. // TODO: deallocate whatever memory we used
  151. // not that important, since this function is going to be
  152. // thrown away as soon as we get proper interface detection
  153. // implemented
  154. // TODO Do LOG_FATAL here
  155. std::cerr << "Interface detection failed." << std::endl;
  156. throw ex;
  157. }
  158. }
  159. void
  160. IfaceMgr::openSockets(uint16_t port) {
  161. int sock1, sock2;
  162. for (IfaceCollection::iterator iface = ifaces_.begin();
  163. iface != ifaces_.end(); ++iface) {
  164. AddressCollection addrs = iface->getAddresses();
  165. for (AddressCollection::iterator addr = addrs.begin();
  166. addr != addrs.end();
  167. ++addr) {
  168. sock1 = openSocket(iface->getName(), *addr, port);
  169. if (sock1 < 0) {
  170. isc_throw(Unexpected, "Failed to open unicast socket on "
  171. << " interface " << iface->getFullName());
  172. }
  173. if ( !joinMcast(sock1, iface->getName(),
  174. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  175. close(sock1);
  176. isc_throw(Unexpected, "Failed to join " << ALL_DHCP_RELAY_AGENTS_AND_SERVERS
  177. << " multicast group.");
  178. }
  179. // this doesn't work too well on NetBSD
  180. sock2 = openSocket(iface->getName(),
  181. IOAddress(ALL_DHCP_RELAY_AGENTS_AND_SERVERS),
  182. port);
  183. if (sock2 < 0) {
  184. isc_throw(Unexpected, "Failed to open multicast socket on "
  185. << " interface " << iface->getFullName());
  186. iface->delSocket(sock1); // delete previously opened socket
  187. }
  188. }
  189. }
  190. }
  191. void
  192. IfaceMgr::printIfaces(std::ostream& out /*= std::cout*/) {
  193. for (IfaceCollection::const_iterator iface = ifaces_.begin();
  194. iface != ifaces_.end(); ++iface) {
  195. out << "Detected interface " << iface->getFullName() << endl;
  196. out << " " << iface->getAddresses().size() << " addr(s):" << endl;
  197. const AddressCollection addrs = iface->getAddresses();
  198. for (AddressCollection::const_iterator addr = addrs.begin();
  199. addr != addrs.end(); ++addr) {
  200. out << " " << addr->toText() << endl;
  201. }
  202. out << " mac: " << iface->getPlainMac() << endl;
  203. }
  204. }
  205. IfaceMgr::Iface*
  206. IfaceMgr::getIface(int ifindex) {
  207. for (IfaceCollection::iterator iface = ifaces_.begin();
  208. iface != ifaces_.end(); ++iface) {
  209. if (iface->getIndex() == ifindex) {
  210. return (&(*iface));
  211. }
  212. }
  213. return (NULL); // not found
  214. }
  215. IfaceMgr::Iface*
  216. IfaceMgr::getIface(const std::string& ifname) {
  217. for (IfaceCollection::iterator iface = ifaces_.begin();
  218. iface != ifaces_.end(); ++iface) {
  219. if (iface->getName() == ifname) {
  220. return (&(*iface));
  221. }
  222. }
  223. return (NULL); // not found
  224. }
  225. int
  226. IfaceMgr::openSocket(const std::string& ifname, const IOAddress& addr,
  227. int port) {
  228. Iface* iface = getIface(ifname);
  229. if (!iface) {
  230. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  231. }
  232. switch (addr.getFamily()) {
  233. case AF_INET:
  234. return openSocket4(*iface, addr, port);
  235. case AF_INET6:
  236. return openSocket6(*iface, addr, port);
  237. default:
  238. isc_throw(BadValue, "Failed to detect family of address: "
  239. << addr.toText());
  240. }
  241. }
  242. int
  243. IfaceMgr::openSocket4(Iface& iface, const IOAddress& addr, int port) {
  244. cout << "Creating UDP4 socket on " << iface.getFullName()
  245. << " " << addr.toText() << "/port=" << port << endl;
  246. struct sockaddr_in addr4;
  247. memset(&addr4, 0, sizeof(sockaddr));
  248. addr4.sin_family = AF_INET;
  249. addr4.sin_port = htons(port);
  250. memcpy(&addr4.sin_addr, addr.getAddress().to_v4().to_bytes().data(),
  251. sizeof(addr4.sin_addr));
  252. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  253. if (sock < 0) {
  254. isc_throw(Unexpected, "Failed to create UDP6 socket.");
  255. }
  256. if (bind(sock, (struct sockaddr *)&addr4, sizeof(addr4)) < 0) {
  257. close(sock);
  258. isc_throw(Unexpected, "Failed to bind socket " << sock << " to " << addr.toText()
  259. << "/port=" << port);
  260. }
  261. // If there is no support for IP_PKTINFO, we are really out of luck.
  262. // It will be difficult to understand, where this packet came from.
  263. #if defined(IP_PKTINFO)
  264. int flag = 1;
  265. if (setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &flag, sizeof(flag)) != 0) {
  266. close(sock);
  267. isc_throw(Unexpected, "setsockopt: IP_PKTINFO: failed.");
  268. }
  269. #endif
  270. cout << "Created socket " << sock << " on " << iface.getName() << "/" <<
  271. addr.toText() << "/port=" << port << endl;
  272. iface.addSocket(SocketInfo(sock, addr, port));
  273. return (sock);
  274. }
  275. int
  276. IfaceMgr::openSocket6(Iface& iface, const IOAddress& addr, int port) {
  277. cout << "Creating UDP6 socket on " << iface.getFullName()
  278. << " " << addr.toText() << "/port=" << port << endl;
  279. struct sockaddr_in6 addr6;
  280. memset(&addr6, 0, sizeof(addr6));
  281. addr6.sin6_family = AF_INET6;
  282. addr6.sin6_port = htons(port);
  283. if (addr.toText() != "::1")
  284. addr6.sin6_scope_id = if_nametoindex(iface.getName().c_str());
  285. memcpy(&addr6.sin6_addr,
  286. addr.getAddress().to_v6().to_bytes().data(),
  287. sizeof(addr6.sin6_addr));
  288. #ifdef HAVE_SA_LEN
  289. addr6->sin6_len = sizeof(addr6);
  290. #endif
  291. // TODO: use sockcreator once it becomes available
  292. // make a socket
  293. int sock = socket(AF_INET6, SOCK_DGRAM, 0);
  294. if (sock < 0) {
  295. isc_throw(Unexpected, "Failed to create UDP6 socket.");
  296. }
  297. // Set the REUSEADDR option so that we don't fail to start if
  298. // we're being restarted.
  299. int flag = 1;
  300. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  301. (char *)&flag, sizeof(flag)) < 0) {
  302. close(sock);
  303. isc_throw(Unexpected, "Can't set SO_REUSEADDR option on dhcpv6 socket.");
  304. }
  305. if (bind(sock, (struct sockaddr *)&addr6, sizeof(addr6)) < 0) {
  306. close(sock);
  307. isc_throw(Unexpected, "Failed to bind socket " << sock << " to " << addr.toText()
  308. << "/port=" << port);
  309. }
  310. #ifdef IPV6_RECVPKTINFO
  311. // RFC3542 - a new way
  312. if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
  313. &flag, sizeof(flag)) != 0) {
  314. close(sock);
  315. isc_throw(Unexpected, "setsockopt: IPV6_RECVPKTINFO failed.");
  316. }
  317. #else
  318. // RFC2292 - an old way
  319. if (setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO,
  320. &flag, sizeof(flag)) != 0) {
  321. close(sock);
  322. isc_throw(Unexpected, "setsockopt: IPV6_PKTINFO: failed.");
  323. }
  324. #endif
  325. // multicast stuff
  326. if (addr.getAddress().to_v6().is_multicast()) {
  327. // both mcast (ALL_DHCP_RELAY_AGENTS_AND_SERVERS and ALL_DHCP_SERVERS)
  328. // are link and site-scoped, so there is no sense to join those groups
  329. // with global addresses.
  330. if ( !joinMcast( sock, iface.getName(),
  331. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  332. close(sock);
  333. isc_throw(Unexpected, "Failed to join " << ALL_DHCP_RELAY_AGENTS_AND_SERVERS
  334. << " multicast group.");
  335. }
  336. }
  337. cout << "Created socket " << sock << " on " << iface.getName() << "/" <<
  338. addr.toText() << "/port=" << port << endl;
  339. iface.addSocket(SocketInfo(sock, addr, port));
  340. return (sock);
  341. }
  342. bool
  343. IfaceMgr::joinMcast(int sock, const std::string& ifname,
  344. const std::string & mcast) {
  345. struct ipv6_mreq mreq;
  346. if (inet_pton(AF_INET6, mcast.c_str(),
  347. &mreq.ipv6mr_multiaddr) <= 0) {
  348. cout << "Failed to convert " << ifname
  349. << " to IPv6 multicast address." << endl;
  350. return (false);
  351. }
  352. mreq.ipv6mr_interface = if_nametoindex(ifname.c_str());
  353. if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
  354. &mreq, sizeof(mreq)) < 0) {
  355. cout << "Failed to join " << mcast << " multicast group." << endl;
  356. return (false);
  357. }
  358. cout << "Joined multicast " << mcast << " group." << endl;
  359. return (true);
  360. }
  361. bool
  362. IfaceMgr::send(boost::shared_ptr<Pkt6>& pkt) {
  363. struct msghdr m;
  364. struct iovec v;
  365. int result;
  366. struct in6_pktinfo *pktinfo;
  367. struct cmsghdr *cmsg;
  368. Iface* iface = getIface(pkt->iface_);
  369. if (!iface) {
  370. isc_throw(BadValue, "Unable to send Pkt6. Invalid interface ("
  371. << pkt->iface_ << ") specified.");
  372. }
  373. memset(&control_buf_[0], 0, control_buf_len_);
  374. // Initialize our message header structure.
  375. memset(&m, 0, sizeof(m));
  376. // Set the target address we're sending to.
  377. sockaddr_in6 to;
  378. memset(&to, 0, sizeof(to));
  379. to.sin6_family = AF_INET6;
  380. to.sin6_port = htons(pkt->remote_port_);
  381. memcpy(&to.sin6_addr,
  382. pkt->remote_addr_.getAddress().to_v6().to_bytes().data(),
  383. 16);
  384. to.sin6_scope_id = pkt->ifindex_;
  385. m.msg_name = &to;
  386. m.msg_namelen = sizeof(to);
  387. // Set the data buffer we're sending. (Using this wacky
  388. // "scatter-gather" stuff... we only have a single chunk
  389. // of data to send, so we declare a single vector entry.)
  390. v.iov_base = (char *) &pkt->data_[0];
  391. v.iov_len = pkt->data_len_;
  392. m.msg_iov = &v;
  393. m.msg_iovlen = 1;
  394. // Setting the interface is a bit more involved.
  395. //
  396. // We have to create a "control message", and set that to
  397. // define the IPv6 packet information. We could set the
  398. // source address if we wanted, but we can safely let the
  399. // kernel decide what that should be.
  400. m.msg_control = &control_buf_[0];
  401. m.msg_controllen = control_buf_len_;
  402. cmsg = CMSG_FIRSTHDR(&m);
  403. cmsg->cmsg_level = IPPROTO_IPV6;
  404. cmsg->cmsg_type = IPV6_PKTINFO;
  405. cmsg->cmsg_len = CMSG_LEN(sizeof(*pktinfo));
  406. pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
  407. memset(pktinfo, 0, sizeof(*pktinfo));
  408. pktinfo->ipi6_ifindex = pkt->ifindex_;
  409. m.msg_controllen = cmsg->cmsg_len;
  410. result = sendmsg(getSocket(*pkt), &m, 0);
  411. if (result < 0) {
  412. cout << "Send packet failed." << endl;
  413. }
  414. cout << "Sent " << pkt->data_len_ << " bytes over socket " << getSocket(*pkt)
  415. << " on " << iface->getFullName() << " interface: "
  416. << " dst=" << pkt->remote_addr_.toText()
  417. << ", src=" << pkt->local_addr_.toText()
  418. << endl;
  419. return (result);
  420. }
  421. bool
  422. IfaceMgr::send(boost::shared_ptr<Pkt4>& )
  423. {
  424. /// TODO: Implement this (ticket #1240)
  425. isc_throw(NotImplemented, "Pkt4 send not implemented yet.");
  426. }
  427. boost::shared_ptr<Pkt4>
  428. IfaceMgr::receive4() {
  429. isc_throw(NotImplemented, "Pkt4 reception not implemented yet.");
  430. // TODO: To be implemented (ticket #1239)
  431. return (boost::shared_ptr<Pkt4>()); // NULL
  432. }
  433. boost::shared_ptr<Pkt6>
  434. IfaceMgr::receive6() {
  435. struct msghdr m;
  436. struct iovec v;
  437. int result;
  438. struct cmsghdr* cmsg;
  439. struct in6_pktinfo* pktinfo;
  440. struct sockaddr_in6 from;
  441. struct in6_addr to_addr;
  442. boost::shared_ptr<Pkt6> pkt;
  443. char addr_str[INET6_ADDRSTRLEN];
  444. try {
  445. // RFC3315 states that server responses may be
  446. // fragmented if they are over MTU. There is no
  447. // text whether client's packets may be larger
  448. // than 1500. Nevertheless to be on the safe side
  449. // we use larger buffer. This buffer limit is checked
  450. // during reception (see iov_len below), so we are
  451. // safe
  452. pkt = boost::shared_ptr<Pkt6>(new Pkt6(65536));
  453. } catch (const std::exception& ex) {
  454. cout << "Failed to create new packet." << endl;
  455. return (boost::shared_ptr<Pkt6>()); // NULL
  456. }
  457. memset(&control_buf_[0], 0, control_buf_len_);
  458. memset(&from, 0, sizeof(from));
  459. memset(&to_addr, 0, sizeof(to_addr));
  460. // Initialize our message header structure.
  461. memset(&m, 0, sizeof(m));
  462. // Point so we can get the from address.
  463. m.msg_name = &from;
  464. m.msg_namelen = sizeof(from);
  465. // Set the data buffer we're receiving. (Using this wacky
  466. // "scatter-gather" stuff... but we that doesn't really make
  467. // sense for us, so we use a single vector entry.)
  468. v.iov_base = (void*)&pkt->data_[0];
  469. v.iov_len = pkt->data_len_;
  470. m.msg_iov = &v;
  471. m.msg_iovlen = 1;
  472. // Getting the interface is a bit more involved.
  473. //
  474. // We set up some space for a "control message". We have
  475. // previously asked the kernel to give us packet
  476. // information (when we initialized the interface), so we
  477. // should get the destination address from that.
  478. m.msg_control = &control_buf_[0];
  479. m.msg_controllen = control_buf_len_;
  480. /// TODO: Need to move to select() and pool over
  481. /// all available sockets. For now, we just take the
  482. /// first interface and use first socket from it.
  483. IfaceCollection::const_iterator iface = ifaces_.begin();
  484. if (iface == ifaces_.end()) {
  485. isc_throw(Unexpected, "No interfaces detected. Can't receive anything.");
  486. }
  487. SocketCollection::const_iterator s = iface->sockets_.begin();
  488. const SocketInfo* candidate = 0;
  489. while (s != iface->sockets_.end()) {
  490. if (s->addr_.getAddress().to_v6().is_multicast()) {
  491. candidate = &(*s);
  492. break;
  493. }
  494. if (!candidate) {
  495. candidate = &(*s); // it's not multicast, but it's better than none
  496. }
  497. ++s;
  498. }
  499. if (!candidate) {
  500. isc_throw(Unexpected, "Interface " << iface->getFullName()
  501. << " does not have any sockets open.");
  502. }
  503. cout << "Trying to receive over socket " << candidate->sockfd_ << " bound to "
  504. << candidate->addr_.toText() << "/port=" << candidate->port_ << " on "
  505. << iface->getFullName() << endl;
  506. result = recvmsg(candidate->sockfd_, &m, 0);
  507. if (result >= 0) {
  508. // If we did read successfully, then we need to loop
  509. // through the control messages we received and
  510. // find the one with our destination address.
  511. //
  512. // We also keep a flag to see if we found it. If we
  513. // didn't, then we consider this to be an error.
  514. int found_pktinfo = 0;
  515. cmsg = CMSG_FIRSTHDR(&m);
  516. while (cmsg != NULL) {
  517. if ((cmsg->cmsg_level == IPPROTO_IPV6) &&
  518. (cmsg->cmsg_type == IPV6_PKTINFO)) {
  519. pktinfo = (struct in6_pktinfo*)CMSG_DATA(cmsg);
  520. to_addr = pktinfo->ipi6_addr;
  521. pkt->ifindex_ = pktinfo->ipi6_ifindex;
  522. found_pktinfo = 1;
  523. }
  524. cmsg = CMSG_NXTHDR(&m, cmsg);
  525. }
  526. if (!found_pktinfo) {
  527. cout << "Unable to find pktinfo" << endl;
  528. return (boost::shared_ptr<Pkt6>()); // NULL
  529. }
  530. } else {
  531. cout << "Failed to receive data." << endl;
  532. return (boost::shared_ptr<Pkt6>()); // NULL
  533. }
  534. // That's ugly.
  535. // TODO add IOAddress constructor that will take struct in6_addr*
  536. // TODO: there's from_bytes() method added in IOAddress. Use it!
  537. inet_ntop(AF_INET6, &to_addr, addr_str,INET6_ADDRSTRLEN);
  538. pkt->local_addr_ = IOAddress(string(addr_str));
  539. // TODO: there's from_bytes() method added in IOAddress. Use it!
  540. inet_ntop(AF_INET6, &from.sin6_addr, addr_str, INET6_ADDRSTRLEN);
  541. pkt->remote_addr_ = IOAddress(string(addr_str));
  542. pkt->remote_port_ = ntohs(from.sin6_port);
  543. Iface* received = getIface(pkt->ifindex_);
  544. if (received) {
  545. pkt->iface_ = received->getName();
  546. } else {
  547. cout << "Received packet over unknown interface (ifindex="
  548. << pkt->ifindex_ << ")." << endl;
  549. return (boost::shared_ptr<Pkt6>()); // NULL
  550. }
  551. pkt->data_len_ = result;
  552. // TODO Move this to LOG_DEBUG
  553. cout << "Received " << pkt->data_len_ << " bytes over "
  554. << pkt->iface_ << "/" << pkt->ifindex_ << " interface: "
  555. << " src=" << pkt->remote_addr_.toText()
  556. << ", dst=" << pkt->local_addr_.toText()
  557. << endl;
  558. return (pkt);
  559. }
  560. uint16_t
  561. IfaceMgr::getSocket(isc::dhcp::Pkt6 const& pkt) {
  562. Iface* iface = getIface(pkt.iface_);
  563. if (!iface) {
  564. isc_throw(BadValue, "Tried to find socket for non-existent interface "
  565. << pkt.iface_);
  566. }
  567. SocketCollection::const_iterator s;
  568. for (s = iface->sockets_.begin(); s != iface->sockets_.end(); ++s) {
  569. if (s->family_ != AF_INET6) {
  570. // don't use IPv4 sockets
  571. continue;
  572. }
  573. if (s->addr_.getAddress().to_v6().is_multicast()) {
  574. // don't use IPv6 sockets bound to multicast address
  575. continue;
  576. }
  577. /// TODO: Add more checks here later. If remote address is
  578. /// not link-local, we can't use link local bound socket
  579. /// to send data.
  580. return (s->sockfd_);
  581. }
  582. isc_throw(Unexpected, "Interface " << iface->getFullName()
  583. << " does not have any suitable IPv6 sockets open.");
  584. }
  585. uint16_t
  586. IfaceMgr::getSocket(isc::dhcp::Pkt4 const& pkt) {
  587. Iface* iface = getIface(pkt.getIface());
  588. if (!iface) {
  589. isc_throw(BadValue, "Tried to find socket for non-existent interface "
  590. << pkt.getIface());
  591. }
  592. SocketCollection::const_iterator s;
  593. for (s = iface->sockets_.begin(); s != iface->sockets_.end(); ++s) {
  594. if (s->family_ != AF_INET) {
  595. // don't use IPv4 sockets
  596. continue;
  597. }
  598. /// TODO: Add more checks here later. If remote address is
  599. /// not link-local, we can't use link local bound socket
  600. /// to send data.
  601. return (s->sockfd_);
  602. }
  603. isc_throw(Unexpected, "Interface " << iface->getFullName()
  604. << " does not have any suitable IPv4 sockets open.");
  605. }
  606. }