iface_mgr.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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), flag_loopback_(false),
  48. flag_up_(false), flag_running_(false), flag_multicast_(false),
  49. flag_broadcast_(false), flags_(0), hardware_type_(0)
  50. {
  51. memset(mac_, 0, sizeof(mac_));
  52. }
  53. std::string
  54. IfaceMgr::Iface::getFullName() const {
  55. ostringstream tmp;
  56. tmp << name_ << "/" << ifindex_;
  57. return (tmp.str());
  58. }
  59. std::string
  60. IfaceMgr::Iface::getPlainMac() const {
  61. ostringstream tmp;
  62. tmp.fill('0');
  63. tmp << hex;
  64. for (int i = 0; i < mac_len_; i++) {
  65. tmp.width(2);
  66. tmp << int(mac_[i]);
  67. if (i < mac_len_-1) {
  68. tmp << ":";
  69. }
  70. }
  71. return (tmp.str());
  72. }
  73. IfaceMgr::IfaceMgr()
  74. :control_buf_len_(CMSG_SPACE(sizeof(struct in6_pktinfo))),
  75. control_buf_(new char[control_buf_len_])
  76. {
  77. cout << "IfaceMgr initialization." << endl;
  78. try {
  79. // required for sending/receiving packets
  80. // let's keep it in front, just in case someone
  81. // wants to send anything during initialization
  82. // control_buf_ = boost::scoped_array<char>();
  83. detectIfaces();
  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::stubDetectIfaces() {
  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. #if !defined(OS_LINUX) && !defined(OS_BSD)
  130. void IfaceMgr::detectIfaces() {
  131. stubDetectIfaces();
  132. }
  133. #endif
  134. bool IfaceMgr::openSockets6() {
  135. int sock;
  136. for (IfaceLst::iterator iface=ifaces_.begin();
  137. iface!=ifaces_.end();
  138. ++iface) {
  139. for (Addr6Lst::iterator addr=iface->addrs_.begin();
  140. addr!=iface->addrs_.end();
  141. ++addr) {
  142. // skip IPv4 addresses
  143. if (addr->getFamily() != AF_INET6) {
  144. continue;
  145. }
  146. sock = openSocket(iface->name_, *addr,
  147. DHCP6_SERVER_PORT);
  148. if (sock<0) {
  149. cout << "Failed to open unicast socket." << endl;
  150. return (false);
  151. }
  152. sendsock_ = sock;
  153. sock = openSocket(iface->name_,
  154. IOAddress(ALL_DHCP_RELAY_AGENTS_AND_SERVERS),
  155. DHCP6_SERVER_PORT);
  156. if (sock<0) {
  157. cout << "Failed to open multicast socket." << endl;
  158. close(sendsock_);
  159. return (false);
  160. }
  161. recvsock_ = sock;
  162. }
  163. }
  164. return (true);
  165. }
  166. void
  167. IfaceMgr::printIfaces(std::ostream& out /*= std::cout*/) {
  168. for (IfaceLst::const_iterator iface=ifaces_.begin();
  169. iface!=ifaces_.end();
  170. ++iface) {
  171. out << "Detected interface " << iface->getFullName()
  172. << ", hwtype=" << iface->hardware_type_ << ", maclen=" << iface->mac_len_
  173. << ", mac=" << iface->getPlainMac();
  174. out << ", flags=" << hex << iface->flags_ << dec << "("
  175. << (iface->flag_loopback_?"LOOPBACK ":"")
  176. << (iface->flag_up_?"UP ":"")
  177. << (iface->flag_running_?"RUNNING ":"")
  178. << (iface->flag_multicast_?"MULTICAST ":"")
  179. << (iface->flag_broadcast_?"BROADCAST ":"")
  180. << ")" << endl;
  181. out << " " << iface->addrs_.size() << " addr(s):";
  182. for (Addr6Lst::const_iterator addr=iface->addrs_.begin();
  183. addr != iface->addrs_.end();
  184. ++addr) {
  185. out << " " << addr->toText();
  186. }
  187. out << endl;
  188. }
  189. }
  190. IfaceMgr::Iface*
  191. IfaceMgr::getIface(int ifindex) {
  192. for (IfaceLst::iterator iface=ifaces_.begin();
  193. iface!=ifaces_.end();
  194. ++iface) {
  195. if (iface->ifindex_ == ifindex)
  196. return (&(*iface));
  197. }
  198. return (NULL); // not found
  199. }
  200. IfaceMgr::Iface*
  201. IfaceMgr::getIface(const std::string& ifname) {
  202. for (IfaceLst::iterator iface=ifaces_.begin();
  203. iface!=ifaces_.end();
  204. ++iface) {
  205. if (iface->name_ == ifname)
  206. return (&(*iface));
  207. }
  208. return (NULL); // not found
  209. }
  210. int
  211. IfaceMgr::openSocket(const std::string& ifname,
  212. const IOAddress& addr,
  213. int port) {
  214. struct sockaddr_in6 addr6;
  215. cout << "Creating socket on " << ifname << "/" << addr.toText()
  216. << "/port=" << port << endl;
  217. memset(&addr6, 0, sizeof(addr6));
  218. addr6.sin6_family = AF_INET6;
  219. addr6.sin6_port = htons(port);
  220. addr6.sin6_scope_id = if_nametoindex(ifname.c_str());
  221. memcpy(&addr6.sin6_addr,
  222. addr.getAddress().to_v6().to_bytes().data(),
  223. sizeof(addr6.sin6_addr));
  224. #ifdef HAVE_SA_LEN
  225. addr6->sin6_len = sizeof(addr6);
  226. #endif
  227. // TODO: use sockcreator once it becomes available
  228. // make a socket
  229. int sock = socket(AF_INET6, SOCK_DGRAM, 0);
  230. if (sock < 0) {
  231. cout << "Failed to create UDP6 socket." << endl;
  232. return (-1);
  233. }
  234. /* Set the REUSEADDR option so that we don't fail to start if
  235. we're being restarted. */
  236. int flag = 1;
  237. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  238. (char *)&flag, sizeof(flag)) < 0) {
  239. cout << "Can't set SO_REUSEADDR option on dhcpv6 socket." << endl;
  240. close(sock);
  241. return (-1);
  242. }
  243. if (bind(sock, (struct sockaddr *)&addr6, sizeof(addr6)) < 0) {
  244. cout << "Failed to bind socket " << sock << " to " << addr.toText()
  245. << "/port=" << port << endl;
  246. close(sock);
  247. return (-1);
  248. }
  249. #ifdef IPV6_RECVPKTINFO
  250. /* RFC3542 - a new way */
  251. if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
  252. &flag, sizeof(flag)) != 0) {
  253. cout << "setsockopt: IPV6_RECVPKTINFO failed." << endl;
  254. close(sock);
  255. return (-1);
  256. }
  257. #else
  258. /* RFC2292 - an old way */
  259. if (setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO,
  260. &flag, sizeof(flag)) != 0) {
  261. cout << "setsockopt: IPV6_PKTINFO: failed." << endl;
  262. close(sock);
  263. return (-1);
  264. }
  265. #endif
  266. // multicast stuff
  267. if (addr.getAddress().to_v6().is_multicast()) {
  268. // both mcast (ALL_DHCP_RELAY_AGENTS_AND_SERVERS and ALL_DHCP_SERVERS)
  269. // are link and site-scoped, so there is no sense to join those groups
  270. // with global addresses.
  271. if ( !joinMcast( sock, ifname,
  272. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  273. close(sock);
  274. return (-1);
  275. }
  276. }
  277. cout << "Created socket " << sock << " on " << ifname << "/" <<
  278. addr.toText() << "/port=" << port << endl;
  279. return (sock);
  280. }
  281. bool
  282. IfaceMgr::joinMcast(int sock, const std::string& ifname,
  283. const std::string & mcast) {
  284. struct ipv6_mreq mreq;
  285. if (inet_pton(AF_INET6, mcast.c_str(),
  286. &mreq.ipv6mr_multiaddr) <= 0) {
  287. cout << "Failed to convert " << ifname
  288. << " to IPv6 multicast address." << endl;
  289. return (false);
  290. }
  291. mreq.ipv6mr_interface = if_nametoindex(ifname.c_str());
  292. if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
  293. &mreq, sizeof(mreq)) < 0) {
  294. cout << "Failed to join " << mcast << " multicast group." << endl;
  295. return (false);
  296. }
  297. cout << "Joined multicast " << mcast << " group." << endl;
  298. return (true);
  299. }
  300. bool
  301. IfaceMgr::send(boost::shared_ptr<Pkt6>& pkt) {
  302. struct msghdr m;
  303. struct iovec v;
  304. int result;
  305. struct in6_pktinfo *pktinfo;
  306. struct cmsghdr *cmsg;
  307. memset(&control_buf_[0], 0, control_buf_len_);
  308. /*
  309. * Initialize our message header structure.
  310. */
  311. memset(&m, 0, sizeof(m));
  312. /*
  313. * Set the target address we're sending to.
  314. */
  315. sockaddr_in6 to;
  316. memset(&to, 0, sizeof(to));
  317. to.sin6_family = AF_INET6;
  318. to.sin6_port = htons(pkt->remote_port_);
  319. memcpy(&to.sin6_addr,
  320. pkt->remote_addr_.getAddress().to_v6().to_bytes().data(),
  321. 16);
  322. to.sin6_scope_id = pkt->ifindex_;
  323. m.msg_name = &to;
  324. m.msg_namelen = sizeof(to);
  325. /*
  326. * Set the data buffer we're sending. (Using this wacky
  327. * "scatter-gather" stuff... we only have a single chunk
  328. * of data to send, so we declare a single vector entry.)
  329. */
  330. v.iov_base = (char *) &pkt->data_[0];
  331. v.iov_len = pkt->data_len_;
  332. m.msg_iov = &v;
  333. m.msg_iovlen = 1;
  334. /*
  335. * Setting the interface is a bit more involved.
  336. *
  337. * We have to create a "control message", and set that to
  338. * define the IPv6 packet information. We could set the
  339. * source address if we wanted, but we can safely let the
  340. * kernel decide what that should be.
  341. */
  342. m.msg_control = &control_buf_[0];
  343. m.msg_controllen = control_buf_len_;
  344. cmsg = CMSG_FIRSTHDR(&m);
  345. cmsg->cmsg_level = IPPROTO_IPV6;
  346. cmsg->cmsg_type = IPV6_PKTINFO;
  347. cmsg->cmsg_len = CMSG_LEN(sizeof(*pktinfo));
  348. pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
  349. memset(pktinfo, 0, sizeof(*pktinfo));
  350. pktinfo->ipi6_ifindex = pkt->ifindex_;
  351. m.msg_controllen = cmsg->cmsg_len;
  352. result = sendmsg(sendsock_, &m, 0);
  353. if (result < 0) {
  354. cout << "Send packet failed." << endl;
  355. }
  356. cout << "Sent " << result << " bytes." << endl;
  357. cout << "Sent " << pkt->data_len_ << " bytes over "
  358. << pkt->iface_ << "/" << pkt->ifindex_ << " interface: "
  359. << " dst=" << pkt->remote_addr_.toText()
  360. << ", src=" << pkt->local_addr_.toText()
  361. << endl;
  362. return (result);
  363. }
  364. boost::shared_ptr<Pkt6>
  365. IfaceMgr::receive() {
  366. struct msghdr m;
  367. struct iovec v;
  368. int result;
  369. struct cmsghdr* cmsg;
  370. struct in6_pktinfo* pktinfo;
  371. struct sockaddr_in6 from;
  372. struct in6_addr to_addr;
  373. boost::shared_ptr<Pkt6> pkt;
  374. char addr_str[INET6_ADDRSTRLEN];
  375. try {
  376. // RFC3315 states that server responses may be
  377. // fragmented if they are over MTU. There is no
  378. // text whether client's packets may be larger
  379. // than 1500. Nevertheless to be on the safe side
  380. // we use larger buffer. This buffer limit is checked
  381. // during reception (see iov_len below), so we are
  382. // safe
  383. pkt = boost::shared_ptr<Pkt6>(new Pkt6(65536));
  384. } catch (const std::exception& ex) {
  385. cout << "Failed to create new packet." << endl;
  386. return (boost::shared_ptr<Pkt6>()); // NULL
  387. }
  388. memset(&control_buf_[0], 0, control_buf_len_);
  389. memset(&from, 0, sizeof(from));
  390. memset(&to_addr, 0, sizeof(to_addr));
  391. /*
  392. * Initialize our message header structure.
  393. */
  394. memset(&m, 0, sizeof(m));
  395. /*
  396. * Point so we can get the from address.
  397. */
  398. m.msg_name = &from;
  399. m.msg_namelen = sizeof(from);
  400. /*
  401. * Set the data buffer we're receiving. (Using this wacky
  402. * "scatter-gather" stuff... but we that doesn't really make
  403. * sense for us, so we use a single vector entry.)
  404. */
  405. v.iov_base = (void*)&pkt->data_[0];
  406. v.iov_len = pkt->data_len_;
  407. m.msg_iov = &v;
  408. m.msg_iovlen = 1;
  409. /*
  410. * Getting the interface is a bit more involved.
  411. *
  412. * We set up some space for a "control message". We have
  413. * previously asked the kernel to give us packet
  414. * information (when we initialized the interface), so we
  415. * should get the destination address from that.
  416. */
  417. m.msg_control = &control_buf_[0];
  418. m.msg_controllen = control_buf_len_;
  419. result = recvmsg(recvsock_, &m, 0);
  420. if (result >= 0) {
  421. /*
  422. * If we did read successfully, then we need to loop
  423. * through the control messages we received and
  424. * find the one with our destination address.
  425. *
  426. * We also keep a flag to see if we found it. If we
  427. * didn't, then we consider this to be an error.
  428. */
  429. int found_pktinfo = 0;
  430. cmsg = CMSG_FIRSTHDR(&m);
  431. while (cmsg != NULL) {
  432. if ((cmsg->cmsg_level == IPPROTO_IPV6) &&
  433. (cmsg->cmsg_type == IPV6_PKTINFO)) {
  434. pktinfo = (struct in6_pktinfo*)CMSG_DATA(cmsg);
  435. to_addr = pktinfo->ipi6_addr;
  436. pkt->ifindex_ = pktinfo->ipi6_ifindex;
  437. found_pktinfo = 1;
  438. }
  439. cmsg = CMSG_NXTHDR(&m, cmsg);
  440. }
  441. if (!found_pktinfo) {
  442. cout << "Unable to find pktinfo" << endl;
  443. return (boost::shared_ptr<Pkt6>()); // NULL
  444. }
  445. } else {
  446. cout << "Failed to receive data." << endl;
  447. return (boost::shared_ptr<Pkt6>()); // NULL
  448. }
  449. // That's ugly.
  450. // TODO add IOAddress constructor that will take struct in6_addr*
  451. // TODO: there's from_bytes() method added in IOAddress. Use it!
  452. inet_ntop(AF_INET6, &to_addr, addr_str,INET6_ADDRSTRLEN);
  453. pkt->local_addr_ = IOAddress(string(addr_str));
  454. // TODO: there's from_bytes() method added in IOAddress. Use it!
  455. inet_ntop(AF_INET6, &from.sin6_addr, addr_str, INET6_ADDRSTRLEN);
  456. pkt->remote_addr_ = IOAddress(string(addr_str));
  457. pkt->remote_port_ = ntohs(from.sin6_port);
  458. Iface* received = getIface(pkt->ifindex_);
  459. if (received) {
  460. pkt->iface_ = received->name_;
  461. } else {
  462. cout << "Received packet over unknown interface (ifindex="
  463. << pkt->ifindex_ << ")." << endl;
  464. return (boost::shared_ptr<Pkt6>()); // NULL
  465. }
  466. pkt->data_len_ = result;
  467. // TODO Move this to LOG_DEBUG
  468. cout << "Received " << pkt->data_len_ << " bytes over "
  469. << pkt->iface_ << "/" << pkt->ifindex_ << " interface: "
  470. << " src=" << pkt->remote_addr_.toText()
  471. << ", dst=" << pkt->local_addr_.toText()
  472. << endl;
  473. return (pkt);
  474. }
  475. }