iface_mgr.cc 34 KB

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