iface_mgr.cc 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. // Copyright (C) 2011-2014 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/iface_mgr_error_handler.h>
  23. #include <dhcp/pkt_filter_inet.h>
  24. #include <dhcp/pkt_filter_inet6.h>
  25. #include <exceptions/exceptions.h>
  26. #include <util/io/pktinfo_utilities.h>
  27. #include <cstring>
  28. #include <errno.h>
  29. #include <fstream>
  30. #include <sstream>
  31. #include <arpa/inet.h>
  32. #include <netinet/in.h>
  33. #include <string.h>
  34. #include <sys/select.h>
  35. using namespace std;
  36. using namespace isc::asiolink;
  37. using namespace isc::util::io::internal;
  38. namespace isc {
  39. namespace dhcp {
  40. IfaceMgr&
  41. IfaceMgr::instance() {
  42. static IfaceMgr iface_mgr;
  43. return (iface_mgr);
  44. }
  45. Iface::Iface(const std::string& name, int ifindex)
  46. :name_(name), ifindex_(ifindex), mac_len_(0), hardware_type_(0),
  47. flag_loopback_(false), flag_up_(false), flag_running_(false),
  48. flag_multicast_(false), flag_broadcast_(false), flags_(0),
  49. inactive4_(false), inactive6_(false)
  50. {
  51. memset(mac_, 0, sizeof(mac_));
  52. }
  53. void
  54. Iface::closeSockets() {
  55. // Close IPv4 sockets.
  56. closeSockets(AF_INET);
  57. // Close IPv6 sockets.
  58. closeSockets(AF_INET6);
  59. }
  60. void
  61. Iface::closeSockets(const uint16_t family) {
  62. // Check that the correect 'family' value has been specified.
  63. // The possible values are AF_INET or AF_INET6. Note that, in
  64. // the current code they are used to differentiate that the
  65. // socket is used to transmit IPv4 or IPv6 traffic. However,
  66. // the actual family types of the sockets may be different,
  67. // e.g. for LPF we are using raw sockets of AF_PACKET family.
  68. //
  69. // @todo Consider replacing the AF_INET and AF_INET6 with some
  70. // enum which will not be confused with the actual socket type.
  71. if ((family != AF_INET) && (family != AF_INET6)) {
  72. isc_throw(BadValue, "Invalid socket family " << family
  73. << " specified when requested to close all sockets"
  74. << " which belong to this family");
  75. }
  76. // Search for the socket of the specific type.
  77. SocketCollection::iterator sock = sockets_.begin();
  78. while (sock != sockets_.end()) {
  79. if (sock->family_ == family) {
  80. // Close and delete the socket and move to the
  81. // next one.
  82. close(sock->sockfd_);
  83. // Close fallback socket if open.
  84. if (sock->fallbackfd_ >= 0) {
  85. close(sock->fallbackfd_);
  86. }
  87. sockets_.erase(sock++);
  88. } else {
  89. // Different type of socket. Let's move
  90. // to the next one.
  91. ++sock;
  92. }
  93. }
  94. }
  95. std::string
  96. Iface::getFullName() const {
  97. ostringstream tmp;
  98. tmp << name_ << "/" << ifindex_;
  99. return (tmp.str());
  100. }
  101. std::string
  102. Iface::getPlainMac() const {
  103. ostringstream tmp;
  104. tmp.fill('0');
  105. tmp << hex;
  106. for (int i = 0; i < mac_len_; i++) {
  107. tmp.width(2);
  108. tmp << static_cast<int>(mac_[i]);
  109. if (i < mac_len_-1) {
  110. tmp << ":";
  111. }
  112. }
  113. return (tmp.str());
  114. }
  115. void Iface::setMac(const uint8_t* mac, size_t len) {
  116. if (len > MAX_MAC_LEN) {
  117. isc_throw(OutOfRange, "Interface " << getFullName()
  118. << " was detected to have link address of length "
  119. << len << ", but maximum supported length is "
  120. << MAX_MAC_LEN);
  121. }
  122. mac_len_ = len;
  123. memcpy(mac_, mac, len);
  124. }
  125. bool Iface::delAddress(const isc::asiolink::IOAddress& addr) {
  126. for (AddressCollection::iterator a = addrs_.begin();
  127. a!=addrs_.end(); ++a) {
  128. if (*a==addr) {
  129. addrs_.erase(a);
  130. return (true);
  131. }
  132. }
  133. return (false);
  134. }
  135. bool Iface::delSocket(const uint16_t sockfd) {
  136. list<SocketInfo>::iterator sock = sockets_.begin();
  137. while (sock!=sockets_.end()) {
  138. if (sock->sockfd_ == sockfd) {
  139. close(sockfd);
  140. // Close fallback socket if open.
  141. if (sock->fallbackfd_ >= 0) {
  142. close(sock->fallbackfd_);
  143. }
  144. sockets_.erase(sock);
  145. return (true); //socket found
  146. }
  147. ++sock;
  148. }
  149. return (false); // socket not found
  150. }
  151. IfaceMgr::IfaceMgr()
  152. :control_buf_len_(CMSG_SPACE(sizeof(struct in6_pktinfo))),
  153. control_buf_(new char[control_buf_len_]),
  154. packet_filter_(new PktFilterInet()),
  155. packet_filter6_(new PktFilterInet6())
  156. {
  157. try {
  158. // required for sending/receiving packets
  159. // let's keep it in front, just in case someone
  160. // wants to send anything during initialization
  161. // control_buf_ = boost::scoped_array<char>();
  162. detectIfaces();
  163. } catch (const std::exception& ex) {
  164. isc_throw(IfaceDetectError, ex.what());
  165. }
  166. }
  167. void Iface::addUnicast(const isc::asiolink::IOAddress& addr) {
  168. for (Iface::AddressCollection::const_iterator i = unicasts_.begin();
  169. i != unicasts_.end(); ++i) {
  170. if (*i == addr) {
  171. isc_throw(BadValue, "Address " << addr
  172. << " already defined on the " << name_ << " interface.");
  173. }
  174. }
  175. unicasts_.push_back(addr);
  176. }
  177. void IfaceMgr::closeSockets() {
  178. for (IfaceCollection::iterator iface = ifaces_.begin();
  179. iface != ifaces_.end(); ++iface) {
  180. iface->closeSockets();
  181. }
  182. }
  183. void
  184. IfaceMgr::closeSockets(const uint16_t family) {
  185. for (IfaceCollection::iterator iface = ifaces_.begin();
  186. iface != ifaces_.end(); ++iface) {
  187. iface->closeSockets(family);
  188. }
  189. }
  190. IfaceMgr::~IfaceMgr() {
  191. // control_buf_ is deleted automatically (scoped_ptr)
  192. control_buf_len_ = 0;
  193. closeSockets();
  194. }
  195. bool
  196. IfaceMgr::isDirectResponseSupported() const {
  197. return (packet_filter_->isDirectResponseSupported());
  198. }
  199. void
  200. IfaceMgr::addExternalSocket(int socketfd, SocketCallback callback) {
  201. for (SocketCallbackInfoContainer::iterator s = callbacks_.begin();
  202. s != callbacks_.end(); ++s) {
  203. // There's such a socket description there already.
  204. // Update the callback and we're done
  205. if (s->socket_ == socketfd) {
  206. s->callback_ = callback;
  207. return;
  208. }
  209. }
  210. // Add a new entry to the callbacks vector
  211. SocketCallbackInfo x;
  212. x.socket_ = socketfd;
  213. x.callback_ = callback;
  214. callbacks_.push_back(x);
  215. }
  216. void
  217. IfaceMgr::deleteExternalSocket(int socketfd) {
  218. for (SocketCallbackInfoContainer::iterator s = callbacks_.begin();
  219. s != callbacks_.end(); ++s) {
  220. if (s->socket_ == socketfd) {
  221. callbacks_.erase(s);
  222. return;
  223. }
  224. }
  225. }
  226. void
  227. IfaceMgr::setPacketFilter(const PktFilterPtr& packet_filter) {
  228. // Do not allow NULL pointer.
  229. if (!packet_filter) {
  230. isc_throw(InvalidPacketFilter, "NULL packet filter object specified for"
  231. " DHCPv4");
  232. }
  233. // Different packet filters use different socket types. It does not make
  234. // sense to allow the change of packet filter when there are IPv4 sockets
  235. // open because they can't be used by the receive/send functions of the
  236. // new packet filter. Below, we check that there are no open IPv4 sockets.
  237. // If we find at least one, we have to fail. However, caller still has a
  238. // chance to replace the packet filter if he closes sockets explicitly.
  239. if (hasOpenSocket(AF_INET)) {
  240. // There is at least one socket open, so we have to fail.
  241. isc_throw(PacketFilterChangeDenied,
  242. "it is not allowed to set new packet"
  243. << " filter when there are open IPv4 sockets - need"
  244. << " to close them first");
  245. }
  246. // Everything is fine, so replace packet filter.
  247. packet_filter_ = packet_filter;
  248. }
  249. void
  250. IfaceMgr::setPacketFilter(const PktFilter6Ptr& packet_filter) {
  251. if (!packet_filter) {
  252. isc_throw(InvalidPacketFilter, "NULL packet filter object specified for"
  253. " DHCPv6");
  254. }
  255. if (hasOpenSocket(AF_INET6)) {
  256. // There is at least one socket open, so we have to fail.
  257. isc_throw(PacketFilterChangeDenied,
  258. "it is not allowed to set new packet"
  259. << " filter when there are open IPv6 sockets - need"
  260. << " to close them first");
  261. }
  262. packet_filter6_ = packet_filter;
  263. }
  264. bool
  265. IfaceMgr::hasOpenSocket(const uint16_t family) const {
  266. // Iterate over all interfaces and search for open sockets.
  267. for (IfaceCollection::const_iterator iface = ifaces_.begin();
  268. iface != ifaces_.end(); ++iface) {
  269. const Iface::SocketCollection& sockets = iface->getSockets();
  270. for (Iface::SocketCollection::const_iterator sock = sockets.begin();
  271. sock != sockets.end(); ++sock) {
  272. // Check if the socket matches specified family.
  273. if (sock->family_ == family) {
  274. // There is at least one socket open, so return.
  275. return (true);
  276. }
  277. }
  278. }
  279. // There are no open sockets found for the specified family.
  280. return (false);
  281. }
  282. bool
  283. IfaceMgr::hasOpenSocket(const IOAddress& addr) const {
  284. // Iterate over all interfaces and search for open sockets.
  285. for (IfaceCollection::const_iterator iface = ifaces_.begin();
  286. iface != ifaces_.end(); ++iface) {
  287. const Iface::SocketCollection& sockets = iface->getSockets();
  288. for (Iface::SocketCollection::const_iterator sock = sockets.begin();
  289. sock != sockets.end(); ++sock) {
  290. // Check if the socket address matches the specified address.
  291. if (sock->addr_ == addr) {
  292. return (true);
  293. }
  294. }
  295. }
  296. // There are no open sockets found for the specified family.
  297. return (false);
  298. }
  299. void IfaceMgr::stubDetectIfaces() {
  300. string ifaceName;
  301. const string v4addr("127.0.0.1"), v6addr("::1");
  302. // This is a stub implementation for interface detection. Actual detection
  303. // is faked by detecting loopback interface (lo or lo0). It will eventually
  304. // be removed once we have actual implementations for all supported systems.
  305. if (if_nametoindex("lo") > 0) {
  306. ifaceName = "lo";
  307. // this is Linux-like OS
  308. } else if (if_nametoindex("lo0") > 0) {
  309. ifaceName = "lo0";
  310. // this is BSD-like OS
  311. } else {
  312. // we give up. What OS is this, anyway? Solaris? Hurd?
  313. isc_throw(NotImplemented,
  314. "Interface detection on this OS is not supported.");
  315. }
  316. Iface iface(ifaceName, if_nametoindex(ifaceName.c_str()));
  317. iface.flag_up_ = true;
  318. iface.flag_running_ = true;
  319. // Note that we claim that this is not a loopback. iface_mgr tries to open a
  320. // socket on all interaces that are up, running and not loopback. As this is
  321. // the only interface we were able to detect, let's pretend this is a normal
  322. // interface.
  323. iface.flag_loopback_ = false;
  324. iface.flag_multicast_ = true;
  325. iface.flag_broadcast_ = true;
  326. iface.setHWType(HWTYPE_ETHERNET);
  327. iface.addAddress(IOAddress(v4addr));
  328. iface.addAddress(IOAddress(v6addr));
  329. addInterface(iface);
  330. }
  331. bool
  332. IfaceMgr::openSockets4(const uint16_t port, const bool use_bcast,
  333. IfaceMgrErrorMsgCallback error_handler) {
  334. int count = 0;
  335. // This option is used to bind sockets to particular interfaces.
  336. // This is currently the only way to discover on which interface
  337. // the broadcast packet has been received. If this option is
  338. // not supported then only one interface should be confugured
  339. // to listen for broadcast traffic.
  340. #ifdef SO_BINDTODEVICE
  341. const bool bind_to_device = true;
  342. #else
  343. const bool bind_to_device = false;
  344. #endif
  345. int bcast_num = 0;
  346. for (IfaceCollection::iterator iface = ifaces_.begin();
  347. iface != ifaces_.end();
  348. ++iface) {
  349. if (iface->flag_loopback_ ||
  350. !iface->flag_up_ ||
  351. !iface->flag_running_ ||
  352. iface->inactive4_) {
  353. continue;
  354. }
  355. Iface::AddressCollection addrs = iface->getAddresses();
  356. for (Iface::AddressCollection::iterator addr = addrs.begin();
  357. addr != addrs.end();
  358. ++addr) {
  359. // Skip all but V4 addresses.
  360. if (!addr->isV4()) {
  361. continue;
  362. }
  363. // If selected interface is broadcast capable set appropriate
  364. // options on the socket so as it can receive and send broadcast
  365. // messages.
  366. if (iface->flag_broadcast_ && use_bcast) {
  367. // If our OS supports binding socket to a device we can listen
  368. // for broadcast messages on multiple interfaces. Otherwise we
  369. // bind to INADDR_ANY address but we can do it only once. Thus,
  370. // if one socket has been bound we can't do it any further.
  371. if (!bind_to_device && bcast_num > 0) {
  372. IFACEMGR_ERROR(SocketConfigError, error_handler,
  373. "SO_BINDTODEVICE socket option is"
  374. " not supported on this OS;"
  375. " therefore, DHCP server can only"
  376. " listen broadcast traffic on a"
  377. " single interface");
  378. continue;
  379. } else {
  380. try {
  381. // We haven't open any broadcast sockets yet, so we can
  382. // open at least one more.
  383. openSocket(iface->getName(), *addr, port, true, true);
  384. } catch (const Exception& ex) {
  385. IFACEMGR_ERROR(SocketConfigError, error_handler,
  386. "failed to open socket on interface "
  387. << iface->getName() << ", reason: "
  388. << ex.what());
  389. continue;
  390. }
  391. // Binding socket to an interface is not supported so we
  392. // can't open any more broadcast sockets. Increase the
  393. // number of open broadcast sockets.
  394. if (!bind_to_device) {
  395. ++bcast_num;
  396. }
  397. }
  398. } else {
  399. try {
  400. // Not broadcast capable, do not set broadcast flags.
  401. openSocket(iface->getName(), *addr, port, false, false);
  402. } catch (const Exception& ex) {
  403. IFACEMGR_ERROR(SocketConfigError, error_handler,
  404. "failed to open socket on interface "
  405. << iface->getName() << ", reason: "
  406. << ex.what());
  407. continue;
  408. }
  409. }
  410. ++count;
  411. }
  412. }
  413. return (count > 0);
  414. }
  415. bool
  416. IfaceMgr::openSockets6(const uint16_t port,
  417. IfaceMgrErrorMsgCallback error_handler) {
  418. int count = 0;
  419. for (IfaceCollection::iterator iface = ifaces_.begin();
  420. iface != ifaces_.end();
  421. ++iface) {
  422. if (iface->flag_loopback_ ||
  423. !iface->flag_up_ ||
  424. !iface->flag_running_ ||
  425. iface->inactive6_) {
  426. continue;
  427. }
  428. // Open unicast sockets if there are any unicast addresses defined
  429. Iface::AddressCollection unicasts = iface->getUnicasts();
  430. for (Iface::AddressCollection::iterator addr = unicasts.begin();
  431. addr != unicasts.end(); ++addr) {
  432. try {
  433. openSocket(iface->getName(), *addr, port);
  434. } catch (const Exception& ex) {
  435. IFACEMGR_ERROR(SocketConfigError, error_handler,
  436. "Failed to open unicast socket on interface "
  437. << iface->getName() << ", reason: "
  438. << ex.what());
  439. continue;
  440. }
  441. count++;
  442. }
  443. Iface::AddressCollection addrs = iface->getAddresses();
  444. for (Iface::AddressCollection::iterator addr = addrs.begin();
  445. addr != addrs.end();
  446. ++addr) {
  447. // Skip all but V6 addresses.
  448. if (!addr->isV6()) {
  449. continue;
  450. }
  451. // Bind link-local addresses only. Otherwise we bind several sockets
  452. // on interfaces that have several global addresses. For examples
  453. // with interface with 2 global addresses, we would bind 3 sockets
  454. // (one for link-local and two for global). That would result in
  455. // getting each message 3 times.
  456. if (!addr->getAddress().to_v6().is_link_local()){
  457. continue;
  458. }
  459. // Run OS-specific function to open a socket on link-local address
  460. // and join multicast group (non-Linux OSes), or open two sockets and
  461. // bind one to link-local, another one to multicast address.
  462. if (openMulticastSocket(*iface, *addr, port, error_handler)) {
  463. ++count;
  464. }
  465. }
  466. }
  467. return (count > 0);
  468. }
  469. void
  470. IfaceMgr::printIfaces(std::ostream& out /*= std::cout*/) {
  471. for (IfaceCollection::const_iterator iface=ifaces_.begin();
  472. iface!=ifaces_.end();
  473. ++iface) {
  474. const Iface::AddressCollection& addrs = iface->getAddresses();
  475. out << "Detected interface " << iface->getFullName()
  476. << ", hwtype=" << iface->getHWType()
  477. << ", mac=" << iface->getPlainMac();
  478. out << ", flags=" << hex << iface->flags_ << dec << "("
  479. << (iface->flag_loopback_?"LOOPBACK ":"")
  480. << (iface->flag_up_?"UP ":"")
  481. << (iface->flag_running_?"RUNNING ":"")
  482. << (iface->flag_multicast_?"MULTICAST ":"")
  483. << (iface->flag_broadcast_?"BROADCAST ":"")
  484. << ")" << endl;
  485. out << " " << addrs.size() << " addr(s):";
  486. for (Iface::AddressCollection::const_iterator addr = addrs.begin();
  487. addr != addrs.end(); ++addr) {
  488. out << " " << addr->toText();
  489. }
  490. out << endl;
  491. }
  492. }
  493. Iface*
  494. IfaceMgr::getIface(int ifindex) {
  495. for (IfaceCollection::iterator iface=ifaces_.begin();
  496. iface!=ifaces_.end();
  497. ++iface) {
  498. if (iface->getIndex() == ifindex)
  499. return (&(*iface));
  500. }
  501. return (NULL); // not found
  502. }
  503. Iface*
  504. IfaceMgr::getIface(const std::string& ifname) {
  505. for (IfaceCollection::iterator iface=ifaces_.begin();
  506. iface!=ifaces_.end();
  507. ++iface) {
  508. if (iface->getName() == ifname)
  509. return (&(*iface));
  510. }
  511. return (NULL); // not found
  512. }
  513. void
  514. IfaceMgr::clearIfaces() {
  515. ifaces_.clear();
  516. }
  517. int IfaceMgr::openSocket(const std::string& ifname, const IOAddress& addr,
  518. const uint16_t port, const bool receive_bcast,
  519. const bool send_bcast) {
  520. Iface* iface = getIface(ifname);
  521. if (!iface) {
  522. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  523. }
  524. if (addr.isV4()) {
  525. return openSocket4(*iface, addr, port, receive_bcast, send_bcast);
  526. } else if (addr.isV6()) {
  527. return openSocket6(*iface, addr, port, receive_bcast);
  528. } else {
  529. isc_throw(BadValue, "Failed to detect family of address: "
  530. << addr);
  531. }
  532. }
  533. int IfaceMgr::openSocketFromIface(const std::string& ifname,
  534. const uint16_t port,
  535. const uint8_t family) {
  536. // Search for specified interface among detected interfaces.
  537. for (IfaceCollection::iterator iface = ifaces_.begin();
  538. iface != ifaces_.end();
  539. ++iface) {
  540. if ((iface->getFullName() != ifname) &&
  541. (iface->getName() != ifname)) {
  542. continue;
  543. }
  544. // Interface is now detected. Search for address on interface
  545. // that matches address family (v6 or v4).
  546. Iface::AddressCollection addrs = iface->getAddresses();
  547. Iface::AddressCollection::iterator addr_it = addrs.begin();
  548. while (addr_it != addrs.end()) {
  549. if (addr_it->getFamily() == family) {
  550. // We have interface and address so let's open socket.
  551. // This may cause isc::Unexpected exception.
  552. return (openSocket(iface->getName(), *addr_it, port, false));
  553. }
  554. ++addr_it;
  555. }
  556. // If we are at the end of address collection it means that we found
  557. // interface but there is no address for family specified.
  558. if (addr_it == addrs.end()) {
  559. // Stringify the family value to append it to exception string.
  560. std::string family_name("AF_INET");
  561. if (family == AF_INET6) {
  562. family_name = "AF_INET6";
  563. }
  564. // We did not find address on the interface.
  565. isc_throw(SocketConfigError, "There is no address for interface: "
  566. << ifname << ", port: " << port << ", address "
  567. " family: " << family_name);
  568. }
  569. }
  570. // If we got here it means that we had not found the specified interface.
  571. // Otherwise we would have returned from previous exist points.
  572. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  573. }
  574. int IfaceMgr::openSocketFromAddress(const IOAddress& addr,
  575. const uint16_t port) {
  576. // Search through detected interfaces and addresses to match
  577. // local address we got.
  578. for (IfaceCollection::iterator iface = ifaces_.begin();
  579. iface != ifaces_.end();
  580. ++iface) {
  581. Iface::AddressCollection addrs = iface->getAddresses();
  582. for (Iface::AddressCollection::iterator addr_it = addrs.begin();
  583. addr_it != addrs.end();
  584. ++addr_it) {
  585. // Local address must match one of the addresses
  586. // on detected interfaces. If it does, we have
  587. // address and interface detected so we can open
  588. // socket.
  589. if (*addr_it == addr) {
  590. // Open socket using local interface, address and port.
  591. // This may cause isc::Unexpected exception.
  592. return (openSocket(iface->getName(), *addr_it, port, false));
  593. }
  594. }
  595. }
  596. // If we got here it means that we did not find specified address
  597. // on any available interface.
  598. isc_throw(BadValue, "There is no such address " << addr);
  599. }
  600. int IfaceMgr::openSocketFromRemoteAddress(const IOAddress& remote_addr,
  601. const uint16_t port) {
  602. try {
  603. // Get local address to be used to connect to remote location.
  604. IOAddress local_address(getLocalAddress(remote_addr, port).getAddress());
  605. return openSocketFromAddress(local_address, port);
  606. } catch (const Exception& e) {
  607. isc_throw(SocketConfigError, e.what());
  608. }
  609. }
  610. isc::asiolink::IOAddress
  611. IfaceMgr::getLocalAddress(const IOAddress& remote_addr, const uint16_t port) {
  612. // Create remote endpoint, we will be connecting to it.
  613. boost::scoped_ptr<const UDPEndpoint>
  614. remote_endpoint(static_cast<const UDPEndpoint*>
  615. (UDPEndpoint::create(IPPROTO_UDP, remote_addr, port)));
  616. if (!remote_endpoint) {
  617. isc_throw(Unexpected, "Unable to create remote endpoint");
  618. }
  619. // Create socket that will be used to connect to remote endpoint.
  620. asio::io_service io_service;
  621. asio::ip::udp::socket sock(io_service);
  622. asio::error_code err_code;
  623. // If remote address is broadcast address we have to
  624. // allow this on the socket.
  625. if (remote_addr.isV4() &&
  626. (remote_addr == IOAddress(DHCP_IPV4_BROADCAST_ADDRESS))) {
  627. // Socket has to be open prior to setting the broadcast
  628. // option. Otherwise set_option will complain about
  629. // bad file descriptor.
  630. // @todo: We don't specify interface in any way here. 255.255.255.255
  631. // We can very easily end up with a socket working on a different
  632. // interface.
  633. sock.open(asio::ip::udp::v4(), err_code);
  634. if (err_code) {
  635. const char* errstr = strerror(errno);
  636. isc_throw(Unexpected, "failed to open UDPv4 socket, reason:"
  637. << errstr);
  638. }
  639. sock.set_option(asio::socket_base::broadcast(true), err_code);
  640. if (err_code) {
  641. sock.close();
  642. isc_throw(Unexpected, "failed to enable broadcast on the socket");
  643. }
  644. }
  645. // Try to connect to remote endpoint and check if attempt is successful.
  646. sock.connect(remote_endpoint->getASIOEndpoint(), err_code);
  647. if (err_code) {
  648. sock.close();
  649. isc_throw(Unexpected, "failed to connect to remote endpoint.");
  650. }
  651. // Once we are connected socket object holds local endpoint.
  652. asio::ip::udp::socket::endpoint_type local_endpoint =
  653. sock.local_endpoint();
  654. asio::ip::address local_address(local_endpoint.address());
  655. // Close the socket.
  656. sock.close();
  657. // Return address of local endpoint.
  658. return IOAddress(local_address);
  659. }
  660. int
  661. IfaceMgr::openSocket6(Iface& iface, const IOAddress& addr, uint16_t port,
  662. const bool join_multicast) {
  663. // Assuming that packet filter is not NULL, because its modifier checks it.
  664. SocketInfo info = packet_filter6_->openSocket(iface, addr, port,
  665. join_multicast);
  666. iface.addSocket(info);
  667. return (info.sockfd_);
  668. }
  669. int
  670. IfaceMgr::openSocket4(Iface& iface, const IOAddress& addr,
  671. const uint16_t port, const bool receive_bcast,
  672. const bool send_bcast) {
  673. // Assuming that packet filter is not NULL, because its modifier checks it.
  674. SocketInfo info = packet_filter_->openSocket(iface, addr, port,
  675. receive_bcast, send_bcast);
  676. iface.addSocket(info);
  677. return (info.sockfd_);
  678. }
  679. bool
  680. IfaceMgr::send(const Pkt6Ptr& pkt) {
  681. Iface* iface = getIface(pkt->getIface());
  682. if (!iface) {
  683. isc_throw(BadValue, "Unable to send DHCPv6 message. Invalid interface ("
  684. << pkt->getIface() << ") specified.");
  685. }
  686. // Assuming that packet filter is not NULL, because its modifier checks it.
  687. return (packet_filter6_->send(*iface, getSocket(*pkt), pkt));
  688. }
  689. bool
  690. IfaceMgr::send(const Pkt4Ptr& pkt) {
  691. Iface* iface = getIface(pkt->getIface());
  692. if (!iface) {
  693. isc_throw(BadValue, "Unable to send DHCPv4 message. Invalid interface ("
  694. << pkt->getIface() << ") specified.");
  695. }
  696. // Assuming that packet filter is not NULL, because its modifier checks it.
  697. return (packet_filter_->send(*iface, getSocket(*pkt).sockfd_, pkt));
  698. }
  699. boost::shared_ptr<Pkt4>
  700. IfaceMgr::receive4(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */) {
  701. // Sanity check for microsecond timeout.
  702. if (timeout_usec >= 1000000) {
  703. isc_throw(BadValue, "fractional timeout must be shorter than"
  704. " one million microseconds");
  705. }
  706. const SocketInfo* candidate = 0;
  707. IfaceCollection::const_iterator iface;
  708. fd_set sockets;
  709. int maxfd = 0;
  710. FD_ZERO(&sockets);
  711. /// @todo: marginal performance optimization. We could create the set once
  712. /// and then use its copy for select(). Please note that select() modifies
  713. /// provided set to indicated which sockets have something to read.
  714. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  715. const Iface::SocketCollection& socket_collection = iface->getSockets();
  716. for (Iface::SocketCollection::const_iterator s = socket_collection.begin();
  717. s != socket_collection.end(); ++s) {
  718. // Only deal with IPv4 addresses.
  719. if (s->addr_.isV4()) {
  720. // Add this socket to listening set
  721. FD_SET(s->sockfd_, &sockets);
  722. if (maxfd < s->sockfd_) {
  723. maxfd = s->sockfd_;
  724. }
  725. }
  726. }
  727. }
  728. // if there are any callbacks for external sockets registered...
  729. if (!callbacks_.empty()) {
  730. for (SocketCallbackInfoContainer::const_iterator s = callbacks_.begin();
  731. s != callbacks_.end(); ++s) {
  732. FD_SET(s->socket_, &sockets);
  733. if (maxfd < s->socket_) {
  734. maxfd = s->socket_;
  735. }
  736. }
  737. }
  738. struct timeval select_timeout;
  739. select_timeout.tv_sec = timeout_sec;
  740. select_timeout.tv_usec = timeout_usec;
  741. int result = select(maxfd + 1, &sockets, NULL, NULL, &select_timeout);
  742. if (result == 0) {
  743. // nothing received and timeout has been reached
  744. return (Pkt4Ptr()); // NULL
  745. } else if (result < 0) {
  746. isc_throw(SocketReadError, strerror(errno));
  747. }
  748. // Let's find out which socket has the data
  749. for (SocketCallbackInfoContainer::iterator s = callbacks_.begin();
  750. s != callbacks_.end(); ++s) {
  751. if (!FD_ISSET(s->socket_, &sockets)) {
  752. continue;
  753. }
  754. // something received over external socket
  755. // Calling the external socket's callback provides its service
  756. // layer access without integrating any specific features
  757. // in IfaceMgr
  758. if (s->callback_) {
  759. s->callback_();
  760. }
  761. return (Pkt4Ptr());
  762. }
  763. // Let's find out which interface/socket has the data
  764. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  765. const Iface::SocketCollection& socket_collection = iface->getSockets();
  766. for (Iface::SocketCollection::const_iterator s = socket_collection.begin();
  767. s != socket_collection.end(); ++s) {
  768. if (FD_ISSET(s->sockfd_, &sockets)) {
  769. candidate = &(*s);
  770. break;
  771. }
  772. }
  773. if (candidate) {
  774. break;
  775. }
  776. }
  777. if (!candidate) {
  778. isc_throw(SocketReadError, "received data over unknown socket");
  779. }
  780. // Now we have a socket, let's get some data from it!
  781. // Assuming that packet filter is not NULL, because its modifier checks it.
  782. return (packet_filter_->receive(*iface, *candidate));
  783. }
  784. Pkt6Ptr IfaceMgr::receive6(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */ ) {
  785. // Sanity check for microsecond timeout.
  786. if (timeout_usec >= 1000000) {
  787. isc_throw(BadValue, "fractional timeout must be shorter than"
  788. " one million microseconds");
  789. }
  790. const SocketInfo* candidate = 0;
  791. fd_set sockets;
  792. int maxfd = 0;
  793. FD_ZERO(&sockets);
  794. /// @todo: marginal performance optimization. We could create the set once
  795. /// and then use its copy for select(). Please note that select() modifies
  796. /// provided set to indicated which sockets have something to read.
  797. IfaceCollection::const_iterator iface;
  798. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  799. const Iface::SocketCollection& socket_collection = iface->getSockets();
  800. for (Iface::SocketCollection::const_iterator s = socket_collection.begin();
  801. s != socket_collection.end(); ++s) {
  802. // Only deal with IPv6 addresses.
  803. if (s->addr_.isV6()) {
  804. // Add this socket to listening set
  805. FD_SET(s->sockfd_, &sockets);
  806. if (maxfd < s->sockfd_) {
  807. maxfd = s->sockfd_;
  808. }
  809. }
  810. }
  811. }
  812. // if there are any callbacks for external sockets registered...
  813. if (!callbacks_.empty()) {
  814. for (SocketCallbackInfoContainer::const_iterator s = callbacks_.begin();
  815. s != callbacks_.end(); ++s) {
  816. // Add it to the set as well
  817. FD_SET(s->socket_, &sockets);
  818. if (maxfd < s->socket_) {
  819. maxfd = s->socket_;
  820. }
  821. }
  822. }
  823. struct timeval select_timeout;
  824. select_timeout.tv_sec = timeout_sec;
  825. select_timeout.tv_usec = timeout_usec;
  826. int result = select(maxfd + 1, &sockets, NULL, NULL, &select_timeout);
  827. if (result == 0) {
  828. // nothing received and timeout has been reached
  829. return (Pkt6Ptr()); // NULL
  830. } else if (result < 0) {
  831. isc_throw(SocketReadError, strerror(errno));
  832. }
  833. // Let's find out which socket has the data
  834. for (SocketCallbackInfoContainer::iterator s = callbacks_.begin();
  835. s != callbacks_.end(); ++s) {
  836. if (!FD_ISSET(s->socket_, &sockets)) {
  837. continue;
  838. }
  839. // something received over external socket
  840. // Calling the external socket's callback provides its service
  841. // layer access without integrating any specific features
  842. // in IfaceMgr
  843. if (s->callback_) {
  844. s->callback_();
  845. }
  846. return (Pkt6Ptr());
  847. }
  848. // Let's find out which interface/socket has the data
  849. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  850. const Iface::SocketCollection& socket_collection = iface->getSockets();
  851. for (Iface::SocketCollection::const_iterator s = socket_collection.begin();
  852. s != socket_collection.end(); ++s) {
  853. if (FD_ISSET(s->sockfd_, &sockets)) {
  854. candidate = &(*s);
  855. break;
  856. }
  857. }
  858. if (candidate) {
  859. break;
  860. }
  861. }
  862. if (!candidate) {
  863. isc_throw(SocketReadError, "received data over unknown socket");
  864. }
  865. // Assuming that packet filter is not NULL, because its modifier checks it.
  866. return (packet_filter6_->receive(*candidate));
  867. }
  868. uint16_t IfaceMgr::getSocket(const isc::dhcp::Pkt6& pkt) {
  869. Iface* iface = getIface(pkt.getIface());
  870. if (iface == NULL) {
  871. isc_throw(BadValue, "Tried to find socket for non-existent interface");
  872. }
  873. const Iface::SocketCollection& socket_collection = iface->getSockets();
  874. Iface::SocketCollection::const_iterator candidate = socket_collection.end();
  875. Iface::SocketCollection::const_iterator s;
  876. for (s = socket_collection.begin(); s != socket_collection.end(); ++s) {
  877. // We should not merge those conditions for debugging reasons.
  878. // V4 sockets are useless for sending v6 packets.
  879. if (s->family_ != AF_INET6) {
  880. continue;
  881. }
  882. // Sockets bound to multicast address are useless for sending anything.
  883. if (s->addr_.getAddress().to_v6().is_multicast()) {
  884. continue;
  885. }
  886. if (s->addr_ == pkt.getLocalAddr()) {
  887. // This socket is bound to the source address. This is perfect
  888. // match, no need to look any further.
  889. return (s->sockfd_);
  890. }
  891. // If we don't have any other candidate, this one will do
  892. if (candidate == socket_collection.end()) {
  893. candidate = s;
  894. } else {
  895. // If we want to send something to link-local and the socket is
  896. // bound to link-local or we want to send to global and the socket
  897. // is bound to global, then use it as candidate
  898. if ( (pkt.getRemoteAddr().getAddress().to_v6().is_link_local() &&
  899. s->addr_.getAddress().to_v6().is_link_local()) ||
  900. (!pkt.getRemoteAddr().getAddress().to_v6().is_link_local() &&
  901. !s->addr_.getAddress().to_v6().is_link_local()) ) {
  902. candidate = s;
  903. }
  904. }
  905. }
  906. if (candidate != socket_collection.end()) {
  907. return (candidate->sockfd_);
  908. }
  909. isc_throw(Unexpected, "Interface " << iface->getFullName()
  910. << " does not have any suitable IPv6 sockets open.");
  911. }
  912. SocketInfo
  913. IfaceMgr::getSocket(isc::dhcp::Pkt4 const& pkt) {
  914. Iface* iface = getIface(pkt.getIface());
  915. if (iface == NULL) {
  916. isc_throw(BadValue, "Tried to find socket for non-existent interface");
  917. }
  918. const Iface::SocketCollection& socket_collection = iface->getSockets();
  919. Iface::SocketCollection::const_iterator s;
  920. for (s = socket_collection.begin(); s != socket_collection.end(); ++s) {
  921. if (s->family_ == AF_INET) {
  922. return (*s);
  923. }
  924. /// TODO: Add more checks here later. If remote address is
  925. /// not link-local, we can't use link local bound socket
  926. /// to send data.
  927. }
  928. isc_throw(Unexpected, "Interface " << iface->getFullName()
  929. << " does not have any suitable IPv4 sockets open.");
  930. }
  931. } // end of namespace isc::dhcp
  932. } // end of namespace isc