iface_mgr.cc 42 KB

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