iface_mgr.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 "dhcp6/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. IfaceMgr::IfaceMgr()
  71. :control_buf_len_(CMSG_SPACE(sizeof(struct in6_pktinfo))),
  72. control_buf_(new char[control_buf_len_])
  73. {
  74. cout << "IfaceMgr initialization." << endl;
  75. try {
  76. // required for sending/receiving packets
  77. // let's keep it in front, just in case someone
  78. // wants to send anything during initialization
  79. // control_buf_ = boost::scoped_array<char>();
  80. detectIfaces();
  81. if (!openSockets()) {
  82. isc_throw(Unexpected, "Failed to open/bind sockets.");
  83. }
  84. } catch (const std::exception& ex) {
  85. cout << "IfaceMgr creation failed:" << ex.what() << endl;
  86. // TODO Uncomment this (or call LOG_FATAL) once
  87. // interface detection is implemented. Otherwise
  88. // it is not possible to run tests in a portable
  89. // way (see detectIfaces() method).
  90. // throw ex;
  91. }
  92. }
  93. IfaceMgr::~IfaceMgr() {
  94. // control_buf_ is deleted automatically (scoped_ptr)
  95. control_buf_len_ = 0;
  96. }
  97. void
  98. IfaceMgr::detectIfaces() {
  99. string ifaceName, linkLocal;
  100. // TODO do the actual detection. Currently interface detection is faked
  101. // by reading a text file.
  102. cout << "Interface detection is not implemented yet. "
  103. << "Reading interfaces.txt file instead." << endl;
  104. cout << "Please use format: interface-name link-local-address" << endl;
  105. try {
  106. ifstream interfaces("interfaces.txt");
  107. if (!interfaces.good()) {
  108. cout << "Failed to read interfaces.txt file." << endl;
  109. isc_throw(Unexpected, "Failed to read interfaces.txt");
  110. }
  111. interfaces >> ifaceName;
  112. interfaces >> linkLocal;
  113. cout << "Detected interface " << ifaceName << "/" << linkLocal << endl;
  114. Iface iface(ifaceName, if_nametoindex( ifaceName.c_str() ) );
  115. IOAddress addr(linkLocal);
  116. iface.addrs_.push_back(addr);
  117. ifaces_.push_back(iface);
  118. interfaces.close();
  119. } catch (const std::exception& ex) {
  120. // TODO: deallocate whatever memory we used
  121. // not that important, since this function is going to be
  122. // thrown away as soon as we get proper interface detection
  123. // implemented
  124. // TODO Do LOG_FATAL here
  125. std::cerr << "Interface detection failed." << std::endl;
  126. throw ex;
  127. }
  128. }
  129. bool
  130. IfaceMgr::openSockets() {
  131. int sock;
  132. for (IfaceLst::iterator iface=ifaces_.begin();
  133. iface!=ifaces_.end();
  134. ++iface) {
  135. for (Addr6Lst::iterator addr=iface->addrs_.begin();
  136. addr!=iface->addrs_.end();
  137. ++addr) {
  138. sock = openSocket(iface->name_, *addr,
  139. DHCP6_SERVER_PORT);
  140. if (sock<0) {
  141. cout << "Failed to open unicast socket." << endl;
  142. return (false);
  143. }
  144. sendsock_ = sock;
  145. sock = openSocket(iface->name_,
  146. IOAddress(ALL_DHCP_RELAY_AGENTS_AND_SERVERS),
  147. DHCP6_SERVER_PORT);
  148. if (sock<0) {
  149. cout << "Failed to open multicast socket." << endl;
  150. close(sendsock_);
  151. return (false);
  152. }
  153. recvsock_ = sock;
  154. }
  155. }
  156. return (true);
  157. }
  158. void
  159. IfaceMgr::printIfaces(std::ostream& out /*= std::cout*/) {
  160. for (IfaceLst::const_iterator iface=ifaces_.begin();
  161. iface!=ifaces_.end();
  162. ++iface) {
  163. out << "Detected interface " << iface->getFullName() << endl;
  164. out << " " << iface->addrs_.size() << " addr(s):" << endl;
  165. for (Addr6Lst::const_iterator addr=iface->addrs_.begin();
  166. addr != iface->addrs_.end();
  167. ++addr) {
  168. out << " " << addr->toText() << endl;
  169. }
  170. out << " mac: " << iface->getPlainMac() << endl;
  171. }
  172. }
  173. IfaceMgr::Iface*
  174. IfaceMgr::getIface(int ifindex) {
  175. for (IfaceLst::iterator iface=ifaces_.begin();
  176. iface!=ifaces_.end();
  177. ++iface) {
  178. if (iface->ifindex_ == ifindex)
  179. return (&(*iface));
  180. }
  181. return (NULL); // not found
  182. }
  183. IfaceMgr::Iface*
  184. IfaceMgr::getIface(const std::string& ifname) {
  185. for (IfaceLst::iterator iface=ifaces_.begin();
  186. iface!=ifaces_.end();
  187. ++iface) {
  188. if (iface->name_ == ifname)
  189. return (&(*iface));
  190. }
  191. return (NULL); // not found
  192. }
  193. int
  194. IfaceMgr::openSocket(const std::string& ifname,
  195. const IOAddress& addr,
  196. int port) {
  197. struct sockaddr_in6 addr6;
  198. cout << "Creating socket on " << ifname << "/" << addr.toText()
  199. << "/port=" << port << endl;
  200. memset(&addr6, 0, sizeof(addr6));
  201. addr6.sin6_family = AF_INET6;
  202. addr6.sin6_port = htons(port);
  203. addr6.sin6_scope_id = if_nametoindex(ifname.c_str());
  204. memcpy(&addr6.sin6_addr,
  205. addr.getAddress().to_v6().to_bytes().data(),
  206. sizeof(addr6.sin6_addr));
  207. #ifdef HAVE_SA_LEN
  208. addr6->sin6_len = sizeof(addr6);
  209. #endif
  210. // TODO: use sockcreator once it becomes available
  211. // make a socket
  212. int sock = socket(AF_INET6, SOCK_DGRAM, 0);
  213. if (sock < 0) {
  214. cout << "Failed to create UDP6 socket." << endl;
  215. return (-1);
  216. }
  217. /* Set the REUSEADDR option so that we don't fail to start if
  218. we're being restarted. */
  219. int flag = 1;
  220. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  221. (char *)&flag, sizeof(flag)) < 0) {
  222. cout << "Can't set SO_REUSEADDR option on dhcpv6 socket." << endl;
  223. close(sock);
  224. return (-1);
  225. }
  226. if (bind(sock, (struct sockaddr *)&addr6, sizeof(addr6)) < 0) {
  227. cout << "Failed to bind socket " << sock << " to " << addr.toText()
  228. << "/port=" << port << endl;
  229. close(sock);
  230. return (-1);
  231. }
  232. #ifdef IPV6_RECVPKTINFO
  233. /* RFC3542 - a new way */
  234. if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
  235. &flag, sizeof(flag)) != 0) {
  236. cout << "setsockopt: IPV6_RECVPKTINFO failed." << endl;
  237. close(sock);
  238. return (-1);
  239. }
  240. #else
  241. /* RFC2292 - an old way */
  242. if (setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO,
  243. &flag, sizeof(flag)) != 0) {
  244. cout << "setsockopt: IPV6_PKTINFO: failed." << endl;
  245. close(sock);
  246. return (-1);
  247. }
  248. #endif
  249. // multicast stuff
  250. if (addr.getAddress().to_v6().is_multicast()) {
  251. // both mcast (ALL_DHCP_RELAY_AGENTS_AND_SERVERS and ALL_DHCP_SERVERS)
  252. // are link and site-scoped, so there is no sense to join those groups
  253. // with global addresses.
  254. if ( !joinMcast( sock, ifname,
  255. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  256. close(sock);
  257. return (-1);
  258. }
  259. }
  260. cout << "Created socket " << sock << " on " << ifname << "/" <<
  261. addr.toText() << "/port=" << port << endl;
  262. return (sock);
  263. }
  264. bool
  265. IfaceMgr::joinMcast(int sock, const std::string& ifname,
  266. const std::string & mcast) {
  267. struct ipv6_mreq mreq;
  268. if (inet_pton(AF_INET6, mcast.c_str(),
  269. &mreq.ipv6mr_multiaddr) <= 0) {
  270. cout << "Failed to convert " << ifname
  271. << " to IPv6 multicast address." << endl;
  272. return (false);
  273. }
  274. mreq.ipv6mr_interface = if_nametoindex(ifname.c_str());
  275. if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
  276. &mreq, sizeof(mreq)) < 0) {
  277. cout << "Failed to join " << mcast << " multicast group." << endl;
  278. return (false);
  279. }
  280. cout << "Joined multicast " << mcast << " group." << endl;
  281. return (true);
  282. }
  283. bool
  284. IfaceMgr::send(boost::shared_ptr<Pkt6>& pkt) {
  285. struct msghdr m;
  286. struct iovec v;
  287. int result;
  288. struct in6_pktinfo *pktinfo;
  289. struct cmsghdr *cmsg;
  290. memset(&control_buf_[0], 0, control_buf_len_);
  291. /*
  292. * Initialize our message header structure.
  293. */
  294. memset(&m, 0, sizeof(m));
  295. /*
  296. * Set the target address we're sending to.
  297. */
  298. sockaddr_in6 to;
  299. memset(&to, 0, sizeof(to));
  300. to.sin6_family = AF_INET6;
  301. to.sin6_port = htons(pkt->remote_port_);
  302. memcpy(&to.sin6_addr,
  303. pkt->remote_addr_.getAddress().to_v6().to_bytes().data(),
  304. 16);
  305. to.sin6_scope_id = pkt->ifindex_;
  306. m.msg_name = &to;
  307. m.msg_namelen = sizeof(to);
  308. /*
  309. * Set the data buffer we're sending. (Using this wacky
  310. * "scatter-gather" stuff... we only have a single chunk
  311. * of data to send, so we declare a single vector entry.)
  312. */
  313. v.iov_base = (char *) &pkt->data_[0];
  314. v.iov_len = pkt->data_len_;
  315. m.msg_iov = &v;
  316. m.msg_iovlen = 1;
  317. /*
  318. * Setting the interface is a bit more involved.
  319. *
  320. * We have to create a "control message", and set that to
  321. * define the IPv6 packet information. We could set the
  322. * source address if we wanted, but we can safely let the
  323. * kernel decide what that should be.
  324. */
  325. m.msg_control = &control_buf_[0];
  326. m.msg_controllen = control_buf_len_;
  327. cmsg = CMSG_FIRSTHDR(&m);
  328. cmsg->cmsg_level = IPPROTO_IPV6;
  329. cmsg->cmsg_type = IPV6_PKTINFO;
  330. cmsg->cmsg_len = CMSG_LEN(sizeof(*pktinfo));
  331. pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
  332. memset(pktinfo, 0, sizeof(*pktinfo));
  333. pktinfo->ipi6_ifindex = pkt->ifindex_;
  334. m.msg_controllen = cmsg->cmsg_len;
  335. result = sendmsg(sendsock_, &m, 0);
  336. if (result < 0) {
  337. cout << "Send packet failed." << endl;
  338. }
  339. cout << "Sent " << result << " bytes." << endl;
  340. cout << "Sent " << pkt->data_len_ << " bytes over "
  341. << pkt->iface_ << "/" << pkt->ifindex_ << " interface: "
  342. << " dst=" << pkt->remote_addr_.toText()
  343. << ", src=" << pkt->local_addr_.toText()
  344. << endl;
  345. return (result);
  346. }
  347. boost::shared_ptr<Pkt6>
  348. IfaceMgr::receive() {
  349. struct msghdr m;
  350. struct iovec v;
  351. int result;
  352. struct cmsghdr* cmsg;
  353. struct in6_pktinfo* pktinfo;
  354. struct sockaddr_in6 from;
  355. struct in6_addr to_addr;
  356. boost::shared_ptr<Pkt6> pkt;
  357. char addr_str[INET6_ADDRSTRLEN];
  358. try {
  359. // RFC3315 states that server responses may be
  360. // fragmented if they are over MTU. There is no
  361. // text whether client's packets may be larger
  362. // than 1500. Nevertheless to be on the safe side
  363. // we use larger buffer. This buffer limit is checked
  364. // during reception (see iov_len below), so we are
  365. // safe
  366. pkt = boost::shared_ptr<Pkt6>(new Pkt6(65536));
  367. } catch (const std::exception& ex) {
  368. cout << "Failed to create new packet." << endl;
  369. return (boost::shared_ptr<Pkt6>()); // NULL
  370. }
  371. memset(&control_buf_[0], 0, control_buf_len_);
  372. memset(&from, 0, sizeof(from));
  373. memset(&to_addr, 0, sizeof(to_addr));
  374. /*
  375. * Initialize our message header structure.
  376. */
  377. memset(&m, 0, sizeof(m));
  378. /*
  379. * Point so we can get the from address.
  380. */
  381. m.msg_name = &from;
  382. m.msg_namelen = sizeof(from);
  383. /*
  384. * Set the data buffer we're receiving. (Using this wacky
  385. * "scatter-gather" stuff... but we that doesn't really make
  386. * sense for us, so we use a single vector entry.)
  387. */
  388. v.iov_base = (void*)&pkt->data_[0];
  389. v.iov_len = pkt->data_len_;
  390. m.msg_iov = &v;
  391. m.msg_iovlen = 1;
  392. /*
  393. * Getting the interface is a bit more involved.
  394. *
  395. * We set up some space for a "control message". We have
  396. * previously asked the kernel to give us packet
  397. * information (when we initialized the interface), so we
  398. * should get the destination address from that.
  399. */
  400. m.msg_control = &control_buf_[0];
  401. m.msg_controllen = control_buf_len_;
  402. result = recvmsg(recvsock_, &m, 0);
  403. if (result >= 0) {
  404. /*
  405. * If we did read successfully, then we need to loop
  406. * through the control messages we received and
  407. * find the one with our destination address.
  408. *
  409. * We also keep a flag to see if we found it. If we
  410. * didn't, then we consider this to be an error.
  411. */
  412. int found_pktinfo = 0;
  413. cmsg = CMSG_FIRSTHDR(&m);
  414. while (cmsg != NULL) {
  415. if ((cmsg->cmsg_level == IPPROTO_IPV6) &&
  416. (cmsg->cmsg_type == IPV6_PKTINFO)) {
  417. pktinfo = (struct in6_pktinfo*)CMSG_DATA(cmsg);
  418. to_addr = pktinfo->ipi6_addr;
  419. pkt->ifindex_ = pktinfo->ipi6_ifindex;
  420. found_pktinfo = 1;
  421. }
  422. cmsg = CMSG_NXTHDR(&m, cmsg);
  423. }
  424. if (!found_pktinfo) {
  425. cout << "Unable to find pktinfo" << endl;
  426. return (boost::shared_ptr<Pkt6>()); // NULL
  427. }
  428. } else {
  429. cout << "Failed to receive data." << endl;
  430. return (boost::shared_ptr<Pkt6>()); // NULL
  431. }
  432. // That's ugly.
  433. // TODO add IOAddress constructor that will take struct in6_addr*
  434. // TODO: there's from_bytes() method added in IOAddress. Use it!
  435. inet_ntop(AF_INET6, &to_addr, addr_str,INET6_ADDRSTRLEN);
  436. pkt->local_addr_ = IOAddress(string(addr_str));
  437. // TODO: there's from_bytes() method added in IOAddress. Use it!
  438. inet_ntop(AF_INET6, &from.sin6_addr, addr_str, INET6_ADDRSTRLEN);
  439. pkt->remote_addr_ = IOAddress(string(addr_str));
  440. pkt->remote_port_ = ntohs(from.sin6_port);
  441. Iface* received = getIface(pkt->ifindex_);
  442. if (received) {
  443. pkt->iface_ = received->name_;
  444. } else {
  445. cout << "Received packet over unknown interface (ifindex="
  446. << pkt->ifindex_ << ")." << endl;
  447. return (boost::shared_ptr<Pkt6>()); // NULL
  448. }
  449. pkt->data_len_ = result;
  450. // TODO Move this to LOG_DEBUG
  451. cout << "Received " << pkt->data_len_ << " bytes over "
  452. << pkt->iface_ << "/" << pkt->ifindex_ << " interface: "
  453. << " src=" << pkt->remote_addr_.toText()
  454. << ", dst=" << pkt->local_addr_.toText()
  455. << endl;
  456. return (pkt);
  457. }
  458. }