iface_mgr.cc 43 KB

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