iface_mgr.cc 40 KB

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