iface_mgr.cc 39 KB

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