iface_mgr.cc 41 KB

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