iface_mgr.cc 45 KB

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