iface_mgr.cc 17 KB

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