iface_mgr.cc 42 KB

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