iface_mgr.cc 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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. BOOST_FOREACH(SocketCallbackInfo s, callbacks_) {
  259. // There's such a socket description there already.
  260. // Update the callback and we're done
  261. if (s.socket_ == socketfd) {
  262. s.callback_ = callback;
  263. return;
  264. }
  265. }
  266. // Add a new entry to the callbacks vector
  267. SocketCallbackInfo x;
  268. x.socket_ = socketfd;
  269. x.callback_ = callback;
  270. callbacks_.push_back(x);
  271. }
  272. void
  273. IfaceMgr::deleteExternalSocket(int socketfd) {
  274. for (SocketCallbackInfoContainer::iterator s = callbacks_.begin();
  275. s != callbacks_.end(); ++s) {
  276. if (s->socket_ == socketfd) {
  277. callbacks_.erase(s);
  278. return;
  279. }
  280. }
  281. }
  282. void
  283. IfaceMgr::setPacketFilter(const PktFilterPtr& packet_filter) {
  284. // Do not allow NULL pointer.
  285. if (!packet_filter) {
  286. isc_throw(InvalidPacketFilter, "NULL packet filter object specified for"
  287. " DHCPv4");
  288. }
  289. // Different packet filters use different socket types. It does not make
  290. // sense to allow the change of packet filter when there are IPv4 sockets
  291. // open because they can't be used by the receive/send functions of the
  292. // new packet filter. Below, we check that there are no open IPv4 sockets.
  293. // If we find at least one, we have to fail. However, caller still has a
  294. // chance to replace the packet filter if he closes sockets explicitly.
  295. if (hasOpenSocket(AF_INET)) {
  296. // There is at least one socket open, so we have to fail.
  297. isc_throw(PacketFilterChangeDenied,
  298. "it is not allowed to set new packet"
  299. << " filter when there are open IPv4 sockets - need"
  300. << " to close them first");
  301. }
  302. // Everything is fine, so replace packet filter.
  303. packet_filter_ = packet_filter;
  304. }
  305. void
  306. IfaceMgr::setPacketFilter(const PktFilter6Ptr& packet_filter) {
  307. if (!packet_filter) {
  308. isc_throw(InvalidPacketFilter, "NULL packet filter object specified for"
  309. " DHCPv6");
  310. }
  311. if (hasOpenSocket(AF_INET6)) {
  312. // There is at least one socket open, so we have to fail.
  313. isc_throw(PacketFilterChangeDenied,
  314. "it is not allowed to set new packet"
  315. << " filter when there are open IPv6 sockets - need"
  316. << " to close them first");
  317. }
  318. packet_filter6_ = packet_filter;
  319. }
  320. bool
  321. IfaceMgr::hasOpenSocket(const uint16_t family) const {
  322. // Iterate over all interfaces and search for open sockets.
  323. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  324. BOOST_FOREACH(SocketInfo sock, iface->getSockets()) {
  325. // Check if the socket matches specified family.
  326. if (sock.family_ == family) {
  327. // There is at least one socket open, so return.
  328. return (true);
  329. }
  330. }
  331. }
  332. // There are no open sockets found for the specified family.
  333. return (false);
  334. }
  335. bool
  336. IfaceMgr::hasOpenSocket(const IOAddress& addr) const {
  337. // Iterate over all interfaces and search for open sockets.
  338. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  339. BOOST_FOREACH(SocketInfo sock, iface->getSockets()) {
  340. // Check if the socket address matches the specified address or
  341. // if address is unspecified (in6addr_any).
  342. if (sock.addr_ == addr) {
  343. return (true);
  344. } else if (sock.addr_ == IOAddress("::")) {
  345. // Handle the case that the address is unspecified (any).
  346. // In this case, we should check if the specified address
  347. // belongs to any of the interfaces.
  348. BOOST_FOREACH(Iface::Address a, iface->getAddresses()) {
  349. if (addr == a.get()) {
  350. return (true);
  351. }
  352. }
  353. }
  354. }
  355. }
  356. // There are no open sockets found for the specified family.
  357. return (false);
  358. }
  359. void IfaceMgr::stubDetectIfaces() {
  360. string ifaceName;
  361. const string v4addr("127.0.0.1"), v6addr("::1");
  362. // This is a stub implementation for interface detection. Actual detection
  363. // is faked by detecting loopback interface (lo or lo0). It will eventually
  364. // be removed once we have actual implementations for all supported systems.
  365. if (if_nametoindex("lo") > 0) {
  366. ifaceName = "lo";
  367. // this is Linux-like OS
  368. } else if (if_nametoindex("lo0") > 0) {
  369. ifaceName = "lo0";
  370. // this is BSD-like OS
  371. } else {
  372. // we give up. What OS is this, anyway? Solaris? Hurd?
  373. isc_throw(NotImplemented,
  374. "Interface detection on this OS is not supported.");
  375. }
  376. IfacePtr iface(new Iface(ifaceName, if_nametoindex(ifaceName.c_str())));
  377. iface->flag_up_ = true;
  378. iface->flag_running_ = true;
  379. // Note that we claim that this is not a loopback. iface_mgr tries to open a
  380. // socket on all interaces that are up, running and not loopback. As this is
  381. // the only interface we were able to detect, let's pretend this is a normal
  382. // interface.
  383. iface->flag_loopback_ = false;
  384. iface->flag_multicast_ = true;
  385. iface->flag_broadcast_ = true;
  386. iface->setHWType(HWTYPE_ETHERNET);
  387. iface->addAddress(IOAddress(v4addr));
  388. iface->addAddress(IOAddress(v6addr));
  389. addInterface(iface);
  390. }
  391. bool
  392. IfaceMgr::openSockets4(const uint16_t port, const bool use_bcast,
  393. IfaceMgrErrorMsgCallback error_handler) {
  394. int count = 0;
  395. int bcast_num = 0;
  396. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  397. // If the interface is inactive, there is nothing to do. Simply
  398. // proceed to the next detected interface.
  399. if (iface->inactive4_) {
  400. continue;
  401. } else {
  402. // If the interface has been specified in the configuration that
  403. // it should be used to listen the DHCP traffic we have to check
  404. // that the interface configuration is valid and that the interface
  405. // is not a loopback interface. In both cases, we want to report
  406. // that the socket will not be opened.
  407. if (iface->flag_loopback_) {
  408. IFACEMGR_ERROR(SocketConfigError, error_handler,
  409. "must not open socket on the loopback"
  410. " interface " << iface->getName());
  411. continue;
  412. }
  413. IOAddress out_address("0.0.0.0");
  414. if (!iface->flag_up_ || !iface->flag_running_ ||
  415. !iface->getAddress4(out_address)) {
  416. IFACEMGR_ERROR(SocketConfigError, error_handler,
  417. "the interface " << iface->getName()
  418. << " is down or has no usable IPv4"
  419. " addresses configured");
  420. continue;
  421. }
  422. }
  423. Iface::AddressCollection addrs = iface->getAddresses();
  424. BOOST_FOREACH(Iface::Address addr, iface->getAddresses()) {
  425. // Skip non-IPv4 addresses and those that weren't selected..
  426. if (!addr.get().isV4() || !addr.isSpecified()) {
  427. continue;
  428. }
  429. // If selected interface is broadcast capable set appropriate
  430. // options on the socket so as it can receive and send broadcast
  431. // messages.
  432. if (iface->flag_broadcast_ && use_bcast) {
  433. // The DHCP server must have means to determine which interface
  434. // the broadcast packets are coming from. This is achieved by
  435. // binding a socket to the device (interface) and specialized
  436. // packet filters (e.g. BPF and LPF) implement this mechanism.
  437. // If the PktFilterInet (generic one) is used, the socket is
  438. // bound to INADDR_ANY which effectively binds the socket to
  439. // all addresses on all interfaces. So, only one of those can
  440. // be opened. Currently, the direct response support is
  441. // provided by the PktFilterLPF and PktFilterBPF, so by checking
  442. // the support for direct response we actually determine that
  443. // one of those objects is in use. For all other objects we
  444. // assume that binding to the device is not supported and we
  445. // cease opening sockets and display the appropriate message.
  446. if (!isDirectResponseSupported() && bcast_num > 0) {
  447. IFACEMGR_ERROR(SocketConfigError, error_handler,
  448. "Binding socket to an interface is not"
  449. " supported on this OS; therefore only"
  450. " one socket listening to broadcast traffic"
  451. " can be opened. Sockets will not be opened"
  452. " on remaining interfaces");
  453. continue;
  454. } else {
  455. try {
  456. // We haven't open any broadcast sockets yet, so we can
  457. // open at least one more.
  458. openSocket(iface->getName(), addr.get(), port, true, true);
  459. } catch (const Exception& ex) {
  460. IFACEMGR_ERROR(SocketConfigError, error_handler,
  461. "failed to open socket on interface "
  462. << iface->getName() << ", reason: "
  463. << ex.what());
  464. continue;
  465. }
  466. // Binding socket to an interface is not supported so we
  467. // can't open any more broadcast sockets. Increase the
  468. // number of open broadcast sockets.
  469. ++bcast_num;
  470. }
  471. } else {
  472. try {
  473. // Not broadcast capable, do not set broadcast flags.
  474. openSocket(iface->getName(), addr.get(), port, false, false);
  475. } catch (const Exception& ex) {
  476. IFACEMGR_ERROR(SocketConfigError, error_handler,
  477. "failed to open socket on interface "
  478. << iface->getName() << ", reason: "
  479. << ex.what());
  480. continue;
  481. }
  482. }
  483. ++count;
  484. }
  485. }
  486. return (count > 0);
  487. }
  488. bool
  489. IfaceMgr::openSockets6(const uint16_t port,
  490. IfaceMgrErrorMsgCallback error_handler) {
  491. int count = 0;
  492. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  493. if (iface->inactive6_) {
  494. continue;
  495. } else {
  496. // If the interface has been specified in the configuration that
  497. // it should be used to listen the DHCP traffic we have to check
  498. // that the interface configuration is valid and that the interface
  499. // is not a loopback interface. In both cases, we want to report
  500. // that the socket will not be opened.
  501. if (iface->flag_loopback_) {
  502. IFACEMGR_ERROR(SocketConfigError, error_handler,
  503. "must not open socket on the loopback"
  504. " interface " << iface->getName());
  505. continue;
  506. } else if (!iface->flag_up_ || !iface->flag_running_) {
  507. IFACEMGR_ERROR(SocketConfigError, error_handler,
  508. "the interface " << iface->getName()
  509. << " is down or has no usable IPv6"
  510. " addresses configured");
  511. continue;
  512. }
  513. }
  514. // Open unicast sockets if there are any unicast addresses defined
  515. BOOST_FOREACH(Iface::Address addr, iface->getUnicasts()) {
  516. try {
  517. openSocket(iface->getName(), addr, port);
  518. } catch (const Exception& ex) {
  519. IFACEMGR_ERROR(SocketConfigError, error_handler,
  520. "Failed to open unicast socket on interface "
  521. << iface->getName() << ", reason: "
  522. << ex.what());
  523. continue;
  524. }
  525. count++;
  526. }
  527. BOOST_FOREACH(Iface::Address addr, iface->getAddresses()) {
  528. // Skip all but V6 addresses.
  529. if (!addr.get().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.get().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. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  553. const Iface::AddressCollection& addrs = iface->getAddresses();
  554. out << "Detected interface " << iface->getFullName()
  555. << ", hwtype=" << iface->getHWType()
  556. << ", mac=" << iface->getPlainMac();
  557. out << ", flags=" << hex << iface->flags_ << dec << "("
  558. << (iface->flag_loopback_?"LOOPBACK ":"")
  559. << (iface->flag_up_?"UP ":"")
  560. << (iface->flag_running_?"RUNNING ":"")
  561. << (iface->flag_multicast_?"MULTICAST ":"")
  562. << (iface->flag_broadcast_?"BROADCAST ":"")
  563. << ")" << endl;
  564. out << " " << addrs.size() << " addr(s):";
  565. BOOST_FOREACH(Iface::Address addr, addrs) {
  566. out << " " << addr.get().toText();
  567. }
  568. out << endl;
  569. }
  570. }
  571. IfacePtr
  572. IfaceMgr::getIface(int ifindex) {
  573. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  574. if (iface->getIndex() == ifindex)
  575. return (iface);
  576. }
  577. return (IfacePtr()); // not found
  578. }
  579. IfacePtr
  580. IfaceMgr::getIface(const std::string& ifname) {
  581. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  582. if (iface->getName() == ifname)
  583. return (iface);
  584. }
  585. return (IfacePtr()); // not found
  586. }
  587. void
  588. IfaceMgr::clearIfaces() {
  589. ifaces_.clear();
  590. }
  591. void
  592. IfaceMgr::clearUnicasts() {
  593. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  594. iface->clearUnicasts();
  595. }
  596. }
  597. int IfaceMgr::openSocket(const std::string& ifname, const IOAddress& addr,
  598. const uint16_t port, const bool receive_bcast,
  599. const bool send_bcast) {
  600. IfacePtr iface = getIface(ifname);
  601. if (!iface) {
  602. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  603. }
  604. if (addr.isV4()) {
  605. return openSocket4(*iface, addr, port, receive_bcast, send_bcast);
  606. } else if (addr.isV6()) {
  607. return openSocket6(*iface, addr, port, receive_bcast);
  608. } else {
  609. isc_throw(BadValue, "Failed to detect family of address: "
  610. << addr);
  611. }
  612. }
  613. int IfaceMgr::openSocketFromIface(const std::string& ifname,
  614. const uint16_t port,
  615. const uint8_t family) {
  616. // Search for specified interface among detected interfaces.
  617. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  618. if ((iface->getFullName() != ifname) &&
  619. (iface->getName() != ifname)) {
  620. continue;
  621. }
  622. // Interface is now detected. Search for address on interface
  623. // that matches address family (v6 or v4).
  624. Iface::AddressCollection addrs = iface->getAddresses();
  625. Iface::AddressCollection::iterator addr_it = addrs.begin();
  626. while (addr_it != addrs.end()) {
  627. if (addr_it->get().getFamily() == family) {
  628. // We have interface and address so let's open socket.
  629. // This may cause isc::Unexpected exception.
  630. return (openSocket(iface->getName(), *addr_it, port, false));
  631. }
  632. ++addr_it;
  633. }
  634. // If we are at the end of address collection it means that we found
  635. // interface but there is no address for family specified.
  636. if (addr_it == addrs.end()) {
  637. // Stringify the family value to append it to exception string.
  638. std::string family_name("AF_INET");
  639. if (family == AF_INET6) {
  640. family_name = "AF_INET6";
  641. }
  642. // We did not find address on the interface.
  643. isc_throw(SocketConfigError, "There is no address for interface: "
  644. << ifname << ", port: " << port << ", address "
  645. " family: " << family_name);
  646. }
  647. }
  648. // If we got here it means that we had not found the specified interface.
  649. // Otherwise we would have returned from previous exist points.
  650. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  651. }
  652. int IfaceMgr::openSocketFromAddress(const IOAddress& addr,
  653. const uint16_t port) {
  654. // Search through detected interfaces and addresses to match
  655. // local address we got.
  656. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  657. BOOST_FOREACH(Iface::Address a, iface->getAddresses()) {
  658. // Local address must match one of the addresses
  659. // on detected interfaces. If it does, we have
  660. // address and interface detected so we can open
  661. // socket.
  662. if (a.get() == addr) {
  663. // Open socket using local interface, address and port.
  664. // This may cause isc::Unexpected exception.
  665. return (openSocket(iface->getName(), a, port, false));
  666. }
  667. }
  668. }
  669. // If we got here it means that we did not find specified address
  670. // on any available interface.
  671. isc_throw(BadValue, "There is no such address " << addr);
  672. }
  673. int IfaceMgr::openSocketFromRemoteAddress(const IOAddress& remote_addr,
  674. const uint16_t port) {
  675. try {
  676. // Get local address to be used to connect to remote location.
  677. IOAddress local_address(getLocalAddress(remote_addr, port));
  678. return openSocketFromAddress(local_address, port);
  679. } catch (const Exception& e) {
  680. isc_throw(SocketConfigError, e.what());
  681. }
  682. }
  683. isc::asiolink::IOAddress
  684. IfaceMgr::getLocalAddress(const IOAddress& remote_addr, const uint16_t port) {
  685. // Create remote endpoint, we will be connecting to it.
  686. boost::scoped_ptr<const UDPEndpoint>
  687. remote_endpoint(static_cast<const UDPEndpoint*>
  688. (UDPEndpoint::create(IPPROTO_UDP, remote_addr, port)));
  689. if (!remote_endpoint) {
  690. isc_throw(Unexpected, "Unable to create remote endpoint");
  691. }
  692. // Create socket that will be used to connect to remote endpoint.
  693. asio::io_service io_service;
  694. asio::ip::udp::socket sock(io_service);
  695. asio::error_code err_code;
  696. // If remote address is broadcast address we have to
  697. // allow this on the socket.
  698. if (remote_addr.isV4() &&
  699. (remote_addr == IOAddress(DHCP_IPV4_BROADCAST_ADDRESS))) {
  700. // Socket has to be open prior to setting the broadcast
  701. // option. Otherwise set_option will complain about
  702. // bad file descriptor.
  703. // @todo: We don't specify interface in any way here. 255.255.255.255
  704. // We can very easily end up with a socket working on a different
  705. // interface.
  706. sock.open(asio::ip::udp::v4(), err_code);
  707. if (err_code) {
  708. const char* errstr = strerror(errno);
  709. isc_throw(Unexpected, "failed to open UDPv4 socket, reason:"
  710. << errstr);
  711. }
  712. sock.set_option(asio::socket_base::broadcast(true), err_code);
  713. if (err_code) {
  714. sock.close();
  715. isc_throw(Unexpected, "failed to enable broadcast on the socket");
  716. }
  717. }
  718. // Try to connect to remote endpoint and check if attempt is successful.
  719. sock.connect(remote_endpoint->getASIOEndpoint(), err_code);
  720. if (err_code) {
  721. sock.close();
  722. isc_throw(Unexpected, "failed to connect to remote endpoint.");
  723. }
  724. // Once we are connected socket object holds local endpoint.
  725. asio::ip::udp::socket::endpoint_type local_endpoint =
  726. sock.local_endpoint();
  727. asio::ip::address local_address(local_endpoint.address());
  728. // Close the socket.
  729. sock.close();
  730. // Return address of local endpoint.
  731. return IOAddress(local_address);
  732. }
  733. int
  734. IfaceMgr::openSocket4(Iface& iface, const IOAddress& addr,
  735. const uint16_t port, const bool receive_bcast,
  736. const bool send_bcast) {
  737. // Assuming that packet filter is not NULL, because its modifier checks it.
  738. SocketInfo info = packet_filter_->openSocket(iface, addr, port,
  739. receive_bcast, send_bcast);
  740. iface.addSocket(info);
  741. return (info.sockfd_);
  742. }
  743. bool
  744. IfaceMgr::send(const Pkt6Ptr& pkt) {
  745. IfacePtr iface = getIface(pkt->getIface());
  746. if (!iface) {
  747. isc_throw(BadValue, "Unable to send DHCPv6 message. Invalid interface ("
  748. << pkt->getIface() << ") specified.");
  749. }
  750. // Assuming that packet filter is not NULL, because its modifier checks it.
  751. return (packet_filter6_->send(*iface, getSocket(*pkt), pkt));
  752. }
  753. bool
  754. IfaceMgr::send(const Pkt4Ptr& pkt) {
  755. IfacePtr iface = getIface(pkt->getIface());
  756. if (!iface) {
  757. isc_throw(BadValue, "Unable to send DHCPv4 message. Invalid interface ("
  758. << pkt->getIface() << ") specified.");
  759. }
  760. // Assuming that packet filter is not NULL, because its modifier checks it.
  761. return (packet_filter_->send(*iface, getSocket(*pkt).sockfd_, pkt));
  762. }
  763. boost::shared_ptr<Pkt4>
  764. IfaceMgr::receive4(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */) {
  765. // Sanity check for microsecond timeout.
  766. if (timeout_usec >= 1000000) {
  767. isc_throw(BadValue, "fractional timeout must be shorter than"
  768. " one million microseconds");
  769. }
  770. const SocketInfo* candidate = 0;
  771. IfacePtr iface;
  772. fd_set sockets;
  773. int maxfd = 0;
  774. FD_ZERO(&sockets);
  775. /// @todo: marginal performance optimization. We could create the set once
  776. /// and then use its copy for select(). Please note that select() modifies
  777. /// provided set to indicated which sockets have something to read.
  778. BOOST_FOREACH(iface, ifaces_) {
  779. BOOST_FOREACH(SocketInfo s, iface->getSockets()) {
  780. // Only deal with IPv4 addresses.
  781. if (s.addr_.isV4()) {
  782. // Add this socket to listening set
  783. FD_SET(s.sockfd_, &sockets);
  784. if (maxfd < s.sockfd_) {
  785. maxfd = s.sockfd_;
  786. }
  787. }
  788. }
  789. }
  790. // if there are any callbacks for external sockets registered...
  791. if (!callbacks_.empty()) {
  792. BOOST_FOREACH(SocketCallbackInfo s, callbacks_) {
  793. FD_SET(s.socket_, &sockets);
  794. if (maxfd < s.socket_) {
  795. maxfd = s.socket_;
  796. }
  797. }
  798. }
  799. struct timeval select_timeout;
  800. select_timeout.tv_sec = timeout_sec;
  801. select_timeout.tv_usec = timeout_usec;
  802. int result = select(maxfd + 1, &sockets, NULL, NULL, &select_timeout);
  803. if (result == 0) {
  804. // nothing received and timeout has been reached
  805. return (Pkt4Ptr()); // NULL
  806. } else if (result < 0) {
  807. // In most cases we would like to know whether select() returned
  808. // an error because of a signal being received or for some other
  809. // reasaon. This is because DHCP servers use signals to trigger
  810. // certain actions, like reconfiguration or graceful shutdown.
  811. // By catching a dedicated exception the caller will know if the
  812. // error returned by the function is due to the reception of the
  813. // signal or for some other reason.
  814. if (errno == EINTR) {
  815. isc_throw(SignalInterruptOnSelect, strerror(errno));
  816. } else {
  817. isc_throw(SocketReadError, strerror(errno));
  818. }
  819. }
  820. // Let's find out which socket has the data
  821. BOOST_FOREACH(SocketCallbackInfo s, callbacks_) {
  822. if (!FD_ISSET(s.socket_, &sockets)) {
  823. continue;
  824. }
  825. // something received over external socket
  826. // Calling the external socket's callback provides its service
  827. // layer access without integrating any specific features
  828. // in IfaceMgr
  829. if (s.callback_) {
  830. s.callback_();
  831. }
  832. return (Pkt4Ptr());
  833. }
  834. // Let's find out which interface/socket has the data
  835. BOOST_FOREACH(iface, ifaces_) {
  836. BOOST_FOREACH(SocketInfo s, iface->getSockets()) {
  837. if (FD_ISSET(s.sockfd_, &sockets)) {
  838. candidate = &(s);
  839. break;
  840. }
  841. }
  842. if (candidate) {
  843. break;
  844. }
  845. }
  846. if (!candidate) {
  847. isc_throw(SocketReadError, "received data over unknown socket");
  848. }
  849. // Now we have a socket, let's get some data from it!
  850. // Assuming that packet filter is not NULL, because its modifier checks it.
  851. return (packet_filter_->receive(*iface, *candidate));
  852. }
  853. Pkt6Ptr IfaceMgr::receive6(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */ ) {
  854. // Sanity check for microsecond timeout.
  855. if (timeout_usec >= 1000000) {
  856. isc_throw(BadValue, "fractional timeout must be shorter than"
  857. " one million microseconds");
  858. }
  859. const SocketInfo* candidate = 0;
  860. fd_set sockets;
  861. int maxfd = 0;
  862. FD_ZERO(&sockets);
  863. /// @todo: marginal performance optimization. We could create the set once
  864. /// and then use its copy for select(). Please note that select() modifies
  865. /// provided set to indicated which sockets have something to read.
  866. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  867. BOOST_FOREACH(SocketInfo s, iface->getSockets()) {
  868. // Only deal with IPv6 addresses.
  869. if (s.addr_.isV6()) {
  870. // Add this socket to listening set
  871. FD_SET(s.sockfd_, &sockets);
  872. if (maxfd < s.sockfd_) {
  873. maxfd = s.sockfd_;
  874. }
  875. }
  876. }
  877. }
  878. // if there are any callbacks for external sockets registered...
  879. if (!callbacks_.empty()) {
  880. BOOST_FOREACH(SocketCallbackInfo s, callbacks_) {
  881. // Add it to the set as well
  882. FD_SET(s.socket_, &sockets);
  883. if (maxfd < s.socket_) {
  884. maxfd = s.socket_;
  885. }
  886. }
  887. }
  888. struct timeval select_timeout;
  889. select_timeout.tv_sec = timeout_sec;
  890. select_timeout.tv_usec = timeout_usec;
  891. int result = select(maxfd + 1, &sockets, NULL, NULL, &select_timeout);
  892. if (result == 0) {
  893. // nothing received and timeout has been reached
  894. return (Pkt6Ptr()); // NULL
  895. } else if (result < 0) {
  896. // In most cases we would like to know whether select() returned
  897. // an error because of a signal being received or for some other
  898. // reasaon. This is because DHCP servers use signals to trigger
  899. // certain actions, like reconfiguration or graceful shutdown.
  900. // By catching a dedicated exception the caller will know if the
  901. // error returned by the function is due to the reception of the
  902. // signal or for some other reason.
  903. if (errno == EINTR) {
  904. isc_throw(SignalInterruptOnSelect, strerror(errno));
  905. } else {
  906. isc_throw(SocketReadError, strerror(errno));
  907. }
  908. }
  909. // Let's find out which socket has the data
  910. BOOST_FOREACH(SocketCallbackInfo s, callbacks_) {
  911. if (!FD_ISSET(s.socket_, &sockets)) {
  912. continue;
  913. }
  914. // something received over external socket
  915. // Calling the external socket's callback provides its service
  916. // layer access without integrating any specific features
  917. // in IfaceMgr
  918. if (s.callback_) {
  919. s.callback_();
  920. }
  921. return (Pkt6Ptr());
  922. }
  923. // Let's find out which interface/socket has the data
  924. BOOST_FOREACH(IfacePtr iface, ifaces_) {
  925. BOOST_FOREACH(SocketInfo s, iface->getSockets()) {
  926. if (FD_ISSET(s.sockfd_, &sockets)) {
  927. candidate = &(s);
  928. break;
  929. }
  930. }
  931. if (candidate) {
  932. break;
  933. }
  934. }
  935. if (!candidate) {
  936. isc_throw(SocketReadError, "received data over unknown socket");
  937. }
  938. // Assuming that packet filter is not NULL, because its modifier checks it.
  939. return (packet_filter6_->receive(*candidate));
  940. }
  941. uint16_t IfaceMgr::getSocket(const isc::dhcp::Pkt6& pkt) {
  942. IfacePtr iface = getIface(pkt.getIface());
  943. if (!iface) {
  944. isc_throw(IfaceNotFound, "Tried to find socket for non-existent interface");
  945. }
  946. const Iface::SocketCollection& socket_collection = iface->getSockets();
  947. Iface::SocketCollection::const_iterator candidate = socket_collection.end();
  948. Iface::SocketCollection::const_iterator s;
  949. for (s = socket_collection.begin(); s != socket_collection.end(); ++s) {
  950. // We should not merge those conditions for debugging reasons.
  951. // V4 sockets are useless for sending v6 packets.
  952. if (s->family_ != AF_INET6) {
  953. continue;
  954. }
  955. // Sockets bound to multicast address are useless for sending anything.
  956. if (s->addr_.isV6Multicast()) {
  957. continue;
  958. }
  959. if (s->addr_ == pkt.getLocalAddr()) {
  960. // This socket is bound to the source address. This is perfect
  961. // match, no need to look any further.
  962. return (s->sockfd_);
  963. }
  964. // If we don't have any other candidate, this one will do
  965. if (candidate == socket_collection.end()) {
  966. candidate = s;
  967. } else {
  968. // If we want to send something to link-local and the socket is
  969. // bound to link-local or we want to send to global and the socket
  970. // is bound to global, then use it as candidate
  971. if ( (pkt.getRemoteAddr().isV6LinkLocal() &&
  972. s->addr_.isV6LinkLocal()) ||
  973. (!pkt.getRemoteAddr().isV6LinkLocal() &&
  974. !s->addr_.isV6LinkLocal()) ) {
  975. candidate = s;
  976. }
  977. }
  978. }
  979. if (candidate != socket_collection.end()) {
  980. return (candidate->sockfd_);
  981. }
  982. isc_throw(SocketNotFound, "Interface " << iface->getFullName()
  983. << " does not have any suitable IPv6 sockets open.");
  984. }
  985. SocketInfo
  986. IfaceMgr::getSocket(isc::dhcp::Pkt4 const& pkt) {
  987. IfacePtr iface = getIface(pkt.getIface());
  988. if (iface == NULL) {
  989. isc_throw(IfaceNotFound, "Tried to find socket for non-existent interface");
  990. }
  991. const Iface::SocketCollection& socket_collection = iface->getSockets();
  992. // A candidate being an end of the iterator marks that it is a begining of
  993. // the socket search and that the candidate needs to be set to the first
  994. // socket found.
  995. Iface::SocketCollection::const_iterator candidate = socket_collection.end();
  996. Iface::SocketCollection::const_iterator s;
  997. for (s = socket_collection.begin(); s != socket_collection.end(); ++s) {
  998. if (s->family_ == AF_INET) {
  999. if (s->addr_ == pkt.getLocalAddr()) {
  1000. return (*s);
  1001. }
  1002. if (candidate == socket_collection.end()) {
  1003. candidate = s;
  1004. }
  1005. }
  1006. }
  1007. if (candidate == socket_collection.end()) {
  1008. isc_throw(SocketNotFound, "Interface " << iface->getFullName()
  1009. << " does not have any suitable IPv4 sockets open.");
  1010. }
  1011. return (*candidate);
  1012. }
  1013. } // end of namespace isc::dhcp
  1014. } // end of namespace isc