iface_mgr.cc 17 KB

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