iface_mgr.cc 41 KB

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