iface_mgr.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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 <config.h>
  15. #include <sstream>
  16. #include <fstream>
  17. #include <string.h>
  18. #include <netinet/in.h>
  19. #include <arpa/inet.h>
  20. #include <dhcp/dhcp4.h>
  21. #include <dhcp/dhcp6.h>
  22. #include <dhcp/iface_mgr.h>
  23. #include <exceptions/exceptions.h>
  24. using namespace std;
  25. using namespace isc::asiolink;
  26. namespace isc {
  27. namespace dhcp {
  28. /// IfaceMgr is a singleton implementation
  29. IfaceMgr* IfaceMgr::instance_ = 0;
  30. void
  31. IfaceMgr::instanceCreate() {
  32. if (instance_) {
  33. // no need to do anything. Instance is already created.
  34. // Who called it again anyway? Uh oh. Had to be us, as
  35. // this is private method.
  36. return;
  37. }
  38. instance_ = new IfaceMgr();
  39. }
  40. IfaceMgr&
  41. IfaceMgr::instance() {
  42. if (instance_ == 0) {
  43. instanceCreate();
  44. }
  45. return (*instance_);
  46. }
  47. IfaceMgr::Iface::Iface(const std::string& name, int ifindex)
  48. :name_(name), ifindex_(ifindex), mac_len_(0), flag_loopback_(false),
  49. flag_up_(false), flag_running_(false), flag_multicast_(false),
  50. flag_broadcast_(false), flags_(0), hardware_type_(0)
  51. {
  52. memset(mac_, 0, sizeof(mac_));
  53. }
  54. std::string
  55. IfaceMgr::Iface::getFullName() const {
  56. ostringstream tmp;
  57. tmp << name_ << "/" << ifindex_;
  58. return (tmp.str());
  59. }
  60. std::string
  61. IfaceMgr::Iface::getPlainMac() const {
  62. ostringstream tmp;
  63. tmp.fill('0');
  64. tmp << hex;
  65. for (int i = 0; i < mac_len_; i++) {
  66. tmp.width(2);
  67. tmp << static_cast<int>(mac_[i]);
  68. if (i < mac_len_-1) {
  69. tmp << ":";
  70. }
  71. }
  72. return (tmp.str());
  73. }
  74. bool IfaceMgr::Iface::delAddress(const isc::asiolink::IOAddress& addr) {
  75. for (AddressCollection::iterator a = addrs_.begin();
  76. a!=addrs_.end(); ++a) {
  77. if (*a==addr) {
  78. addrs_.erase(a);
  79. return (true);
  80. }
  81. }
  82. return (false);
  83. }
  84. bool IfaceMgr::Iface::delSocket(uint16_t sockfd) {
  85. list<SocketInfo>::iterator sock = sockets_.begin();
  86. while (sock!=sockets_.end()) {
  87. if (sock->sockfd_ == sockfd) {
  88. close(sockfd);
  89. sockets_.erase(sock);
  90. return (true); //socket found
  91. }
  92. ++sock;
  93. }
  94. return (false); // socket not found
  95. }
  96. IfaceMgr::IfaceMgr()
  97. :control_buf_len_(CMSG_SPACE(sizeof(struct in6_pktinfo))),
  98. control_buf_(new char[control_buf_len_])
  99. {
  100. cout << "IfaceMgr initialization." << endl;
  101. try {
  102. // required for sending/receiving packets
  103. // let's keep it in front, just in case someone
  104. // wants to send anything during initialization
  105. // control_buf_ = boost::scoped_array<char>();
  106. detectIfaces();
  107. } catch (const std::exception& ex) {
  108. cout << "IfaceMgr creation failed:" << ex.what() << endl;
  109. // TODO Uncomment this (or call LOG_FATAL) once
  110. // interface detection is implemented. Otherwise
  111. // it is not possible to run tests in a portable
  112. // way (see detectIfaces() method).
  113. throw ex;
  114. }
  115. }
  116. void IfaceMgr::closeSockets() {
  117. for (IfaceCollection::iterator iface = ifaces_.begin();
  118. iface != ifaces_.end(); ++iface) {
  119. for (SocketCollection::iterator sock = iface->sockets_.begin();
  120. sock != iface->sockets_.end(); ++sock) {
  121. cout << "Closing socket " << sock->sockfd_ << endl;
  122. close(sock->sockfd_);
  123. }
  124. iface->sockets_.clear();
  125. }
  126. }
  127. IfaceMgr::~IfaceMgr() {
  128. // control_buf_ is deleted automatically (scoped_ptr)
  129. control_buf_len_ = 0;
  130. closeSockets();
  131. }
  132. void
  133. IfaceMgr::stubDetectIfaces() {
  134. string ifaceName, linkLocal;
  135. // TODO do the actual detection. Currently interface detection is faked
  136. // by reading a text file.
  137. cout << "Interface detection is not implemented yet. "
  138. << "Reading interfaces.txt file instead." << endl;
  139. cout << "Please use format: interface-name link-local-address" << endl;
  140. try {
  141. ifstream interfaces("interfaces.txt");
  142. if (!interfaces.good()) {
  143. cout << "interfaces.txt file is not available. Stub interface detection skipped." << endl;
  144. return;
  145. }
  146. interfaces >> ifaceName;
  147. interfaces >> linkLocal;
  148. cout << "Detected interface " << ifaceName << "/" << linkLocal << endl;
  149. Iface iface(ifaceName, if_nametoindex( ifaceName.c_str() ) );
  150. iface.flag_up_ = true;
  151. iface.flag_running_ = true;
  152. iface.flag_loopback_ = false;
  153. iface.flag_multicast_ = true;
  154. iface.flag_broadcast_ = true;
  155. iface.hardware_type_ = HWTYPE_ETHERNET;
  156. IOAddress addr(linkLocal);
  157. iface.addAddress(addr);
  158. addInterface(iface);
  159. interfaces.close();
  160. } catch (const std::exception& ex) {
  161. // TODO: deallocate whatever memory we used
  162. // not that important, since this function is going to be
  163. // thrown away as soon as we get proper interface detection
  164. // implemented
  165. // TODO Do LOG_FATAL here
  166. std::cerr << "Interface detection failed." << std::endl;
  167. throw ex;
  168. }
  169. }
  170. #if !defined(OS_LINUX) && !defined(OS_BSD)
  171. void IfaceMgr::detectIfaces() {
  172. stubDetectIfaces();
  173. }
  174. #endif
  175. bool IfaceMgr::openSockets4(uint16_t port) {
  176. int sock;
  177. int count = 0;
  178. for (IfaceCollection::iterator iface=ifaces_.begin();
  179. iface!=ifaces_.end();
  180. ++iface) {
  181. cout << "Trying interface " << iface->getFullName() << endl;
  182. if (iface->flag_loopback_ ||
  183. !iface->flag_up_ ||
  184. !iface->flag_running_) {
  185. continue;
  186. }
  187. AddressCollection addrs = iface->getAddresses();
  188. for (AddressCollection::iterator addr= addrs.begin();
  189. addr != addrs.end();
  190. ++addr) {
  191. // skip IPv6 addresses
  192. if (addr->getFamily() != AF_INET) {
  193. continue;
  194. }
  195. sock = openSocket(iface->getName(), *addr, port);
  196. if (sock<0) {
  197. cout << "Failed to open unicast socket." << endl;
  198. return (false);
  199. }
  200. count++;
  201. }
  202. }
  203. return (count > 0);
  204. }
  205. bool IfaceMgr::openSockets6(uint16_t port) {
  206. int sock;
  207. int count = 0;
  208. for (IfaceCollection::iterator iface=ifaces_.begin();
  209. iface!=ifaces_.end();
  210. ++iface) {
  211. if (iface->flag_loopback_ ||
  212. !iface->flag_up_ ||
  213. !iface->flag_running_) {
  214. continue;
  215. }
  216. AddressCollection addrs = iface->getAddresses();
  217. for (AddressCollection::iterator addr= addrs.begin();
  218. addr != addrs.end();
  219. ++addr) {
  220. // skip IPv4 addresses
  221. if (addr->getFamily() != AF_INET6) {
  222. continue;
  223. }
  224. sock = openSocket(iface->getName(), *addr, port);
  225. if (sock<0) {
  226. cout << "Failed to open unicast socket." << endl;
  227. return (false);
  228. }
  229. if ( !joinMulticast(sock, iface->getName(),
  230. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  231. close(sock);
  232. isc_throw(Unexpected, "Failed to join " << ALL_DHCP_RELAY_AGENTS_AND_SERVERS
  233. << " multicast group.");
  234. }
  235. count++;
  236. #if defined(OS_LINUX)
  237. // this doesn't work too well on NetBSD
  238. int sock2 = openSocket(iface->getName(),
  239. IOAddress(ALL_DHCP_RELAY_AGENTS_AND_SERVERS),
  240. port);
  241. if (sock2<0) {
  242. isc_throw(Unexpected, "Failed to open multicast socket on "
  243. << " interface " << iface->getFullName());
  244. iface->delSocket(sock); // delete previously opened socket
  245. }
  246. #endif
  247. }
  248. }
  249. return (count > 0);
  250. }
  251. void
  252. IfaceMgr::printIfaces(std::ostream& out /*= std::cout*/) {
  253. for (IfaceCollection::const_iterator iface=ifaces_.begin();
  254. iface!=ifaces_.end();
  255. ++iface) {
  256. const AddressCollection& addrs = iface->getAddresses();
  257. out << "Detected interface " << iface->getFullName()
  258. << ", hwtype=" << iface->hardware_type_ << ", maclen=" << iface->mac_len_
  259. << ", mac=" << iface->getPlainMac();
  260. out << ", flags=" << hex << iface->flags_ << dec << "("
  261. << (iface->flag_loopback_?"LOOPBACK ":"")
  262. << (iface->flag_up_?"UP ":"")
  263. << (iface->flag_running_?"RUNNING ":"")
  264. << (iface->flag_multicast_?"MULTICAST ":"")
  265. << (iface->flag_broadcast_?"BROADCAST ":"")
  266. << ")" << endl;
  267. out << " " << addrs.size() << " addr(s):";
  268. for (AddressCollection::const_iterator addr = addrs.begin();
  269. addr != addrs.end(); ++addr) {
  270. out << " " << addr->toText();
  271. }
  272. out << endl;
  273. }
  274. }
  275. IfaceMgr::Iface*
  276. IfaceMgr::getIface(int ifindex) {
  277. for (IfaceCollection::iterator iface=ifaces_.begin();
  278. iface!=ifaces_.end();
  279. ++iface) {
  280. if (iface->getIndex() == ifindex)
  281. return (&(*iface));
  282. }
  283. return (NULL); // not found
  284. }
  285. IfaceMgr::Iface*
  286. IfaceMgr::getIface(const std::string& ifname) {
  287. for (IfaceCollection::iterator iface=ifaces_.begin();
  288. iface!=ifaces_.end();
  289. ++iface) {
  290. if (iface->getName() == ifname)
  291. return (&(*iface));
  292. }
  293. return (NULL); // not found
  294. }
  295. int IfaceMgr::openSocket(const std::string& ifname, const IOAddress& addr, uint16_t port) {
  296. Iface* iface = getIface(ifname);
  297. if (!iface) {
  298. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  299. }
  300. switch (addr.getFamily()) {
  301. case AF_INET:
  302. return openSocket4(*iface, addr, port);
  303. case AF_INET6:
  304. return openSocket6(*iface, addr, port);
  305. default:
  306. isc_throw(BadValue, "Failed to detect family of address: "
  307. << addr.toText());
  308. }
  309. }
  310. int IfaceMgr::openSocket4(Iface& iface, const IOAddress& addr, uint16_t port) {
  311. cout << "Creating UDP4 socket on " << iface.getFullName()
  312. << " " << addr.toText() << "/port=" << port << endl;
  313. struct sockaddr_in addr4;
  314. memset(&addr4, 0, sizeof(sockaddr));
  315. addr4.sin_family = AF_INET;
  316. addr4.sin_port = htons(port);
  317. addr4.sin_addr.s_addr = htonl(addr);
  318. //addr4.sin_addr.s_addr = 0; // anyaddr: this will receive 0.0.0.0 => 255.255.255.255 traffic
  319. // addr4.sin_addr.s_addr = 0xffffffffu; // broadcast address. This will receive 0.0.0.0 => 255.255.255.255 as well
  320. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  321. if (sock < 0) {
  322. isc_throw(Unexpected, "Failed to create UDP6 socket.");
  323. }
  324. if (bind(sock, (struct sockaddr *)&addr4, sizeof(addr4)) < 0) {
  325. close(sock);
  326. isc_throw(Unexpected, "Failed to bind socket " << sock << " to " << addr.toText()
  327. << "/port=" << port);
  328. }
  329. // if there is no support for IP_PKTINFO, we are really out of luck
  330. // it will be difficult to undersand, where this packet came from
  331. #if defined(IP_PKTINFO)
  332. int flag = 1;
  333. if (setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &flag, sizeof(flag)) != 0) {
  334. close(sock);
  335. isc_throw(Unexpected, "setsockopt: IP_PKTINFO: failed.");
  336. }
  337. #endif
  338. cout << "Created socket " << sock << " on " << iface.getName() << "/" <<
  339. addr.toText() << "/port=" << port << endl;
  340. SocketInfo info(sock, addr, port);
  341. iface.addSocket(info);
  342. return (sock);
  343. }
  344. int IfaceMgr::openSocket6(Iface& iface, const IOAddress& addr, uint16_t port) {
  345. cout << "Creating UDP6 socket on " << iface.getFullName()
  346. << " " << addr.toText() << "/port=" << port << endl;
  347. struct sockaddr_in6 addr6;
  348. memset(&addr6, 0, sizeof(addr6));
  349. addr6.sin6_family = AF_INET6;
  350. addr6.sin6_port = htons(port);
  351. if (addr.toText() != "::1")
  352. addr6.sin6_scope_id = if_nametoindex(iface.getName().c_str());
  353. memcpy(&addr6.sin6_addr,
  354. addr.getAddress().to_v6().to_bytes().data(),
  355. sizeof(addr6.sin6_addr));
  356. #ifdef HAVE_SA_LEN
  357. addr6.sin6_len = sizeof(addr6);
  358. #endif
  359. // TODO: use sockcreator once it becomes available
  360. // make a socket
  361. int sock = socket(AF_INET6, SOCK_DGRAM, 0);
  362. if (sock < 0) {
  363. isc_throw(Unexpected, "Failed to create UDP6 socket.");
  364. }
  365. // Set the REUSEADDR option so that we don't fail to start if
  366. // we're being restarted.
  367. int flag = 1;
  368. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  369. (char *)&flag, sizeof(flag)) < 0) {
  370. close(sock);
  371. isc_throw(Unexpected, "Can't set SO_REUSEADDR option on dhcpv6 socket.");
  372. }
  373. if (bind(sock, (struct sockaddr *)&addr6, sizeof(addr6)) < 0) {
  374. close(sock);
  375. isc_throw(Unexpected, "Failed to bind socket " << sock << " to " << addr.toText()
  376. << "/port=" << port);
  377. }
  378. #ifdef IPV6_RECVPKTINFO
  379. // RFC3542 - a new way
  380. if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
  381. &flag, sizeof(flag)) != 0) {
  382. close(sock);
  383. isc_throw(Unexpected, "setsockopt: IPV6_RECVPKTINFO failed.");
  384. }
  385. #else
  386. // RFC2292 - an old way
  387. if (setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO,
  388. &flag, sizeof(flag)) != 0) {
  389. close(sock);
  390. isc_throw(Unexpected, "setsockopt: IPV6_PKTINFO: failed.");
  391. }
  392. #endif
  393. // multicast stuff
  394. if (addr.getAddress().to_v6().is_multicast()) {
  395. // both mcast (ALL_DHCP_RELAY_AGENTS_AND_SERVERS and ALL_DHCP_SERVERS)
  396. // are link and site-scoped, so there is no sense to join those groups
  397. // with global addresses.
  398. if ( !joinMulticast( sock, iface.getName(),
  399. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  400. close(sock);
  401. isc_throw(Unexpected, "Failed to join " << ALL_DHCP_RELAY_AGENTS_AND_SERVERS
  402. << " multicast group.");
  403. }
  404. }
  405. cout << "Created socket " << sock << " on " << iface.getName() << "/" <<
  406. addr.toText() << "/port=" << port << endl;
  407. SocketInfo info(sock, addr, port);
  408. iface.addSocket(info);
  409. return (sock);
  410. }
  411. bool
  412. IfaceMgr::joinMulticast(int sock, const std::string& ifname,
  413. const std::string & mcast) {
  414. struct ipv6_mreq mreq;
  415. if (inet_pton(AF_INET6, mcast.c_str(),
  416. &mreq.ipv6mr_multiaddr) <= 0) {
  417. cout << "Failed to convert " << ifname
  418. << " to IPv6 multicast address." << endl;
  419. return (false);
  420. }
  421. mreq.ipv6mr_interface = if_nametoindex(ifname.c_str());
  422. if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
  423. &mreq, sizeof(mreq)) < 0) {
  424. cout << "Failed to join " << mcast << " multicast group." << endl;
  425. return (false);
  426. }
  427. cout << "Joined multicast " << mcast << " group." << endl;
  428. return (true);
  429. }
  430. bool
  431. IfaceMgr::send(const Pkt6Ptr& pkt) {
  432. struct msghdr m;
  433. struct iovec v;
  434. int result;
  435. struct in6_pktinfo *pktinfo;
  436. struct cmsghdr *cmsg;
  437. Iface* iface = getIface(pkt->getIface());
  438. if (!iface) {
  439. isc_throw(BadValue, "Unable to send Pkt6. Invalid interface ("
  440. << pkt->getIface() << ") specified.");
  441. }
  442. memset(&control_buf_[0], 0, control_buf_len_);
  443. // Initialize our message header structure.
  444. memset(&m, 0, sizeof(m));
  445. // Set the target address we're sending to.
  446. sockaddr_in6 to;
  447. memset(&to, 0, sizeof(to));
  448. to.sin6_family = AF_INET6;
  449. to.sin6_port = htons(pkt->getRemotePort());
  450. memcpy(&to.sin6_addr,
  451. pkt->getRemoteAddr().getAddress().to_v6().to_bytes().data(),
  452. 16);
  453. to.sin6_scope_id = pkt->getIndex();
  454. m.msg_name = &to;
  455. m.msg_namelen = sizeof(to);
  456. // Set the data buffer we're sending. (Using this wacky
  457. // "scatter-gather" stuff... we only have a single chunk
  458. // of data to send, so we declare a single vector entry.)
  459. v.iov_base = const_cast<void *>(pkt->getBuffer().getData());
  460. v.iov_len = pkt->getBuffer().getLength();
  461. m.msg_iov = &v;
  462. m.msg_iovlen = 1;
  463. // Setting the interface is a bit more involved.
  464. //
  465. // We have to create a "control message", and set that to
  466. // define the IPv6 packet information. We could set the
  467. // source address if we wanted, but we can safely let the
  468. // kernel decide what that should be.
  469. m.msg_control = &control_buf_[0];
  470. m.msg_controllen = control_buf_len_;
  471. cmsg = CMSG_FIRSTHDR(&m);
  472. cmsg->cmsg_level = IPPROTO_IPV6;
  473. cmsg->cmsg_type = IPV6_PKTINFO;
  474. cmsg->cmsg_len = CMSG_LEN(sizeof(*pktinfo));
  475. pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
  476. memset(pktinfo, 0, sizeof(*pktinfo));
  477. pktinfo->ipi6_ifindex = pkt->getIndex();
  478. m.msg_controllen = cmsg->cmsg_len;
  479. result = sendmsg(getSocket(*pkt), &m, 0);
  480. if (result < 0) {
  481. isc_throw(Unexpected, "Pkt6 send failed: sendmsg() returned " << result);
  482. }
  483. cout << "Sent " << pkt->getBuffer().getLength() << " bytes over socket " << getSocket(*pkt)
  484. << " on " << iface->getFullName() << " interface: "
  485. << " dst=[" << pkt->getRemoteAddr().toText() << "]:" << pkt->getRemotePort()
  486. << ", src=" << pkt->getLocalAddr().toText() << "]:" << pkt->getLocalPort()
  487. << endl;
  488. return (result);
  489. }
  490. bool
  491. IfaceMgr::send(const Pkt4Ptr& pkt)
  492. {
  493. struct msghdr m;
  494. struct iovec v;
  495. Iface* iface = getIface(pkt->getIface());
  496. if (!iface) {
  497. isc_throw(BadValue, "Unable to send Pkt4. Invalid interface ("
  498. << pkt->getIface() << ") specified.");
  499. }
  500. memset(&control_buf_[0], 0, control_buf_len_);
  501. // Initialize our message header structure.
  502. memset(&m, 0, sizeof(m));
  503. // Set the target address we're sending to.
  504. sockaddr_in to;
  505. memset(&to, 0, sizeof(to));
  506. to.sin_family = AF_INET;
  507. to.sin_port = htons(pkt->getRemotePort());
  508. to.sin_addr.s_addr = htonl(pkt->getRemoteAddr());
  509. m.msg_name = &to;
  510. m.msg_namelen = sizeof(to);
  511. // Set the data buffer we're sending. (Using this wacky
  512. // "scatter-gather" stuff... we only have a single chunk
  513. // of data to send, so we declare a single vector entry.)
  514. v.iov_base = (char *) pkt->getBuffer().getData();
  515. v.iov_len = pkt->getBuffer().getLength();
  516. m.msg_iov = &v;
  517. m.msg_iovlen = 1;
  518. #if defined(OS_LINUX)
  519. // Setting the interface is a bit more involved.
  520. //
  521. // We have to create a "control message", and set that to
  522. // define the IPv4 packet information. We could set the
  523. // source address if we wanted, but we can safely let the
  524. // kernel decide what that should be.
  525. m.msg_control = &control_buf_[0];
  526. m.msg_controllen = control_buf_len_;
  527. struct cmsghdr* cmsg = CMSG_FIRSTHDR(&m);
  528. cmsg->cmsg_level = IPPROTO_IP;
  529. cmsg->cmsg_type = IP_PKTINFO;
  530. cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
  531. struct in_pktinfo* pktinfo =(struct in_pktinfo *)CMSG_DATA(cmsg);
  532. memset(pktinfo, 0, sizeof(struct in_pktinfo));
  533. pktinfo->ipi_ifindex = pkt->getIndex();
  534. m.msg_controllen = cmsg->cmsg_len;
  535. #endif
  536. cout << "Trying to send " << pkt->getBuffer().getLength() << " bytes to "
  537. << pkt->getRemoteAddr().toText() << ":" << pkt->getRemotePort()
  538. << " over socket " << getSocket(*pkt) << " on interface "
  539. << getIface(pkt->getIface())->getFullName() << endl;
  540. int result = sendmsg(getSocket(*pkt), &m, 0);
  541. if (result < 0) {
  542. isc_throw(Unexpected, "Pkt4 send failed.");
  543. }
  544. cout << "Sent " << pkt->getBuffer().getLength() << " bytes over socket " << getSocket(*pkt)
  545. << " on " << iface->getFullName() << " interface: "
  546. << " dst=" << pkt->getRemoteAddr().toText() << ":" << pkt->getRemotePort()
  547. << ", src=" << pkt->getLocalAddr().toText() << ":" << pkt->getLocalPort()
  548. << endl;
  549. return (result);
  550. }
  551. boost::shared_ptr<Pkt4>
  552. IfaceMgr::receive4() {
  553. const SocketInfo* candidate = 0;
  554. IfaceCollection::const_iterator iface;
  555. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  556. /// @todo: rewrite this as part of #1555
  557. for (SocketCollection::const_iterator s = iface->sockets_.begin();
  558. s != iface->sockets_.end(); ++s) {
  559. // We don't want IPv6 addresses here.
  560. if (s->addr_.getFamily() != AF_INET) {
  561. continue;
  562. }
  563. // This address looks good.
  564. if (!candidate) {
  565. candidate = &(*s);
  566. break;
  567. }
  568. }
  569. if (candidate) {
  570. break;
  571. }
  572. }
  573. if (!candidate) {
  574. isc_throw(Unexpected, "Failed to find any suitable sockets on all interfaces.");
  575. }
  576. cout << "Trying to receive over UDP4 socket " << candidate->sockfd_ << " bound to "
  577. << candidate->addr_.toText() << "/port=" << candidate->port_ << " on "
  578. << iface->getFullName() << endl;
  579. // Now we have a socket, let's get some data from it!
  580. struct sockaddr_in from_addr;
  581. struct in_addr to_addr;
  582. const uint32_t RCVBUFSIZE = 1500;
  583. static uint8_t buf[RCVBUFSIZE];
  584. memset(&control_buf_[0], 0, control_buf_len_);
  585. memset(&from_addr, 0, sizeof(from_addr));
  586. memset(&to_addr, 0, sizeof(to_addr));
  587. // Initialize our message header structure.
  588. struct msghdr m;
  589. memset(&m, 0, sizeof(m));
  590. // Point so we can get the from address.
  591. m.msg_name = &from_addr;
  592. m.msg_namelen = sizeof(from_addr);
  593. struct iovec v;
  594. v.iov_base = static_cast<void*>(buf);
  595. v.iov_len = RCVBUFSIZE;
  596. m.msg_iov = &v;
  597. m.msg_iovlen = 1;
  598. // Getting the interface is a bit more involved.
  599. //
  600. // We set up some space for a "control message". We have
  601. // previously asked the kernel to give us packet
  602. // information (when we initialized the interface), so we
  603. // should get the destination address from that.
  604. m.msg_control = &control_buf_[0];
  605. m.msg_controllen = control_buf_len_;
  606. int result = recvmsg(candidate->sockfd_, &m, 0);
  607. if (result < 0) {
  608. cout << "Failed to receive UDP4 data." << endl;
  609. return (Pkt4Ptr()); // NULL
  610. }
  611. unsigned int ifindex = iface->getIndex();
  612. #if defined(OS_LINUX)
  613. struct cmsghdr* cmsg;
  614. struct in_pktinfo* pktinfo;
  615. int found_pktinfo = 0;
  616. cmsg = CMSG_FIRSTHDR(&m);
  617. while (cmsg != NULL) {
  618. if ((cmsg->cmsg_level == IPPROTO_IP) &&
  619. (cmsg->cmsg_type == IP_PKTINFO)) {
  620. pktinfo = (struct in_pktinfo*)CMSG_DATA(cmsg);
  621. ifindex = pktinfo->ipi_ifindex;
  622. to_addr = pktinfo->ipi_addr;
  623. // This field is useful, when we are bound to unicast
  624. // address e.g. 192.0.2.1 and the packet was sent to
  625. // broadcast. This will return broadcast address, not
  626. // the address we are bound to.
  627. // IOAddress tmp(htonl(pktinfo->ipi_spec_dst.s_addr));
  628. // cout << "The other addr is: " << tmp.toText() << endl;
  629. // Perhaps we should uncomment this:
  630. // to_addr = pktinfo->ipi_spec_dst;
  631. found_pktinfo = 1;
  632. }
  633. cmsg = CMSG_NXTHDR(&m, cmsg);
  634. }
  635. if (!found_pktinfo) {
  636. cout << "Unable to find pktinfo" << endl;
  637. return (boost::shared_ptr<Pkt4>()); // NULL
  638. }
  639. #endif
  640. IOAddress to(htonl(to_addr.s_addr));
  641. IOAddress from(htonl(from_addr.sin_addr.s_addr));
  642. uint16_t from_port = htons(from_addr.sin_port);
  643. cout << "Received " << result << " bytes from " << from.toText()
  644. << "/port=" << from_port
  645. << " sent to " << to.toText() << " over interface "
  646. << iface->getFullName() << endl;
  647. // we have all data let's create Pkt4 object
  648. Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(buf, result));
  649. pkt->setIface(iface->getName());
  650. pkt->setIndex(ifindex);
  651. pkt->setLocalAddr(to);
  652. pkt->setRemoteAddr(from);
  653. pkt->setRemotePort(from_port);
  654. pkt->setLocalPort(candidate->port_);
  655. return (pkt);
  656. }
  657. Pkt6Ptr IfaceMgr::receive6() {
  658. struct msghdr m;
  659. struct iovec v;
  660. int result;
  661. struct cmsghdr* cmsg;
  662. struct in6_pktinfo* pktinfo;
  663. struct sockaddr_in6 from;
  664. struct in6_addr to_addr;
  665. int ifindex = -1;
  666. Pkt6Ptr pkt;
  667. // RFC3315 states that server responses may be
  668. // fragmented if they are over MTU. There is no
  669. // text whether client's packets may be larger
  670. // than 1500. For now, we can assume that
  671. // we don't support packets larger than 1500.
  672. const uint32_t RCVBUFSIZE = 1500;
  673. static uint8_t buf[RCVBUFSIZE];
  674. memset(&control_buf_[0], 0, control_buf_len_);
  675. memset(&from, 0, sizeof(from));
  676. memset(&to_addr, 0, sizeof(to_addr));
  677. // Initialize our message header structure.
  678. memset(&m, 0, sizeof(m));
  679. // Point so we can get the from address.
  680. m.msg_name = &from;
  681. m.msg_namelen = sizeof(from);
  682. // Set the data buffer we're receiving. (Using this wacky
  683. // "scatter-gather" stuff... but we that doesn't really make
  684. // sense for us, so we use a single vector entry.)
  685. v.iov_base = (void*)buf;
  686. v.iov_len = RCVBUFSIZE;
  687. m.msg_iov = &v;
  688. m.msg_iovlen = 1;
  689. // Getting the interface is a bit more involved.
  690. //
  691. // We set up some space for a "control message". We have
  692. // previously asked the kernel to give us packet
  693. // information (when we initialized the interface), so we
  694. // should get the destination address from that.
  695. m.msg_control = &control_buf_[0];
  696. m.msg_controllen = control_buf_len_;
  697. /// TODO: Need to move to select() and pool over
  698. /// all available sockets. For now, we just take the
  699. /// first interface and use first socket from it.
  700. IfaceCollection::const_iterator iface = ifaces_.begin();
  701. const SocketInfo* candidate = 0;
  702. while (iface != ifaces_.end()) {
  703. for (SocketCollection::const_iterator s = iface->sockets_.begin();
  704. s != iface->sockets_.end(); ++s) {
  705. if (s->addr_.getFamily() != AF_INET6) {
  706. continue;
  707. }
  708. if (s->addr_.getAddress().to_v6().is_multicast()) {
  709. candidate = &(*s);
  710. break;
  711. }
  712. if (!candidate) {
  713. candidate = &(*s); // it's not multicast, but it's better than nothing
  714. }
  715. }
  716. if (candidate) {
  717. break;
  718. }
  719. ++iface;
  720. }
  721. if (iface == ifaces_.end()) {
  722. isc_throw(Unexpected, "No suitable IPv6 interfaces detected. Can't receive anything.");
  723. }
  724. if (!candidate) {
  725. isc_throw(Unexpected, "Interface " << iface->getFullName()
  726. << " does not have any sockets open.");
  727. }
  728. cout << "Trying to receive over UDP6 socket " << candidate->sockfd_ << " bound to "
  729. << candidate->addr_.toText() << "/port=" << candidate->port_ << " on "
  730. << iface->getFullName() << endl;
  731. result = recvmsg(candidate->sockfd_, &m, 0);
  732. if (result >= 0) {
  733. // If we did read successfully, then we need to loop
  734. // through the control messages we received and
  735. // find the one with our destination address.
  736. //
  737. // We also keep a flag to see if we found it. If we
  738. // didn't, then we consider this to be an error.
  739. int found_pktinfo = 0;
  740. cmsg = CMSG_FIRSTHDR(&m);
  741. while (cmsg != NULL) {
  742. if ((cmsg->cmsg_level == IPPROTO_IPV6) &&
  743. (cmsg->cmsg_type == IPV6_PKTINFO)) {
  744. pktinfo = (struct in6_pktinfo*)CMSG_DATA(cmsg);
  745. to_addr = pktinfo->ipi6_addr;
  746. ifindex = pktinfo->ipi6_ifindex;
  747. found_pktinfo = 1;
  748. }
  749. cmsg = CMSG_NXTHDR(&m, cmsg);
  750. }
  751. if (!found_pktinfo) {
  752. cout << "Unable to find pktinfo" << endl;
  753. return (Pkt6Ptr()); // NULL
  754. }
  755. } else {
  756. cout << "Failed to receive data." << endl;
  757. return (Pkt6Ptr()); // NULL
  758. }
  759. try {
  760. pkt = Pkt6Ptr(new Pkt6(buf, result));
  761. } catch (const std::exception& ex) {
  762. cout << "Failed to create new packet." << endl;
  763. return (Pkt6Ptr()); // NULL
  764. }
  765. pkt->setLocalAddr(IOAddress::from_bytes(AF_INET6, reinterpret_cast<const uint8_t*>(&to_addr)));
  766. pkt->setRemoteAddr(IOAddress::from_bytes(AF_INET6, reinterpret_cast<const uint8_t*>(&from.sin6_addr)));
  767. pkt->setRemotePort(ntohs(from.sin6_port));
  768. pkt->setIndex(ifindex);
  769. Iface* received = getIface(pkt->getIndex());
  770. if (received) {
  771. pkt->setIface(received->getName());
  772. } else {
  773. cout << "Received packet over unknown interface (ifindex="
  774. << pkt->getIndex() << ")." << endl;
  775. return (boost::shared_ptr<Pkt6>()); // NULL
  776. }
  777. // TODO Move this to LOG_DEBUG
  778. cout << "Received " << pkt->getBuffer().getLength() << " bytes over "
  779. << pkt->getIface() << "/" << pkt->getIndex() << " interface: "
  780. << " src=" << pkt->getRemoteAddr().toText()
  781. << ", dst=" << pkt->getLocalAddr().toText()
  782. << endl;
  783. return (pkt);
  784. }
  785. uint16_t IfaceMgr::getSocket(const isc::dhcp::Pkt6& pkt) {
  786. Iface* iface = getIface(pkt.getIface());
  787. if (!iface) {
  788. isc_throw(BadValue, "Tried to find socket for non-existent interface "
  789. << pkt.getIface());
  790. }
  791. SocketCollection::const_iterator s;
  792. for (s = iface->sockets_.begin(); s != iface->sockets_.end(); ++s) {
  793. if ( (s->family_ == AF_INET6) &&
  794. (!s->addr_.getAddress().to_v6().is_multicast()) ) {
  795. return (s->sockfd_);
  796. }
  797. /// TODO: Add more checks here later. If remote address is
  798. /// not link-local, we can't use link local bound socket
  799. /// to send data.
  800. }
  801. isc_throw(Unexpected, "Interface " << iface->getFullName()
  802. << " does not have any suitable IPv6 sockets open.");
  803. }
  804. uint16_t IfaceMgr::getSocket(isc::dhcp::Pkt4 const& pkt) {
  805. Iface* iface = getIface(pkt.getIface());
  806. if (!iface) {
  807. isc_throw(BadValue, "Tried to find socket for non-existent interface "
  808. << pkt.getIface());
  809. }
  810. SocketCollection::const_iterator s;
  811. for (s = iface->sockets_.begin(); s != iface->sockets_.end(); ++s) {
  812. if (s->family_ == AF_INET) {
  813. return (s->sockfd_);
  814. }
  815. /// TODO: Add more checks here later. If remote address is
  816. /// not link-local, we can't use link local bound socket
  817. /// to send data.
  818. }
  819. isc_throw(Unexpected, "Interface " << iface->getFullName()
  820. << " does not have any suitable IPv4 sockets open.");
  821. }
  822. } // end of namespace isc::dhcp
  823. } // end of namespace isc