iface_mgr.cc 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. // Copyright (C) 2011-2012 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 <exceptions/exceptions.h>
  23. #include <util/io/pktinfo_utilities.h>
  24. #include <fstream>
  25. #include <sstream>
  26. #include <arpa/inet.h>
  27. #include <netinet/in.h>
  28. #include <string.h>
  29. #include <sys/select.h>
  30. using namespace std;
  31. using namespace isc::asiolink;
  32. using namespace isc::util::io::internal;
  33. namespace isc {
  34. namespace dhcp {
  35. IfaceMgr&
  36. IfaceMgr::instance() {
  37. static IfaceMgr iface_mgr;
  38. return (iface_mgr);
  39. }
  40. IfaceMgr::Iface::Iface(const std::string& name, int ifindex)
  41. :name_(name), ifindex_(ifindex), mac_len_(0), hardware_type_(0),
  42. flag_loopback_(false), flag_up_(false), flag_running_(false),
  43. flag_multicast_(false), flag_broadcast_(false), flags_(0)
  44. {
  45. memset(mac_, 0, sizeof(mac_));
  46. }
  47. void
  48. IfaceMgr::Iface::closeSockets() {
  49. for (SocketCollection::iterator sock = sockets_.begin();
  50. sock != sockets_.end(); ++sock) {
  51. close(sock->sockfd_);
  52. }
  53. sockets_.clear();
  54. }
  55. std::string
  56. IfaceMgr::Iface::getFullName() const {
  57. ostringstream tmp;
  58. tmp << name_ << "/" << ifindex_;
  59. return (tmp.str());
  60. }
  61. std::string
  62. IfaceMgr::Iface::getPlainMac() const {
  63. ostringstream tmp;
  64. tmp.fill('0');
  65. tmp << hex;
  66. for (int i = 0; i < mac_len_; i++) {
  67. tmp.width(2);
  68. tmp << static_cast<int>(mac_[i]);
  69. if (i < mac_len_-1) {
  70. tmp << ":";
  71. }
  72. }
  73. return (tmp.str());
  74. }
  75. void IfaceMgr::Iface::setMac(const uint8_t* mac, size_t len) {
  76. if (len > IfaceMgr::MAX_MAC_LEN) {
  77. isc_throw(OutOfRange, "Interface " << getFullName()
  78. << " was detected to have link address of length "
  79. << len << ", but maximum supported length is "
  80. << IfaceMgr::MAX_MAC_LEN);
  81. }
  82. mac_len_ = len;
  83. memcpy(mac_, mac, len);
  84. }
  85. bool IfaceMgr::Iface::delAddress(const isc::asiolink::IOAddress& addr) {
  86. for (AddressCollection::iterator a = addrs_.begin();
  87. a!=addrs_.end(); ++a) {
  88. if (*a==addr) {
  89. addrs_.erase(a);
  90. return (true);
  91. }
  92. }
  93. return (false);
  94. }
  95. bool IfaceMgr::Iface::delSocket(uint16_t sockfd) {
  96. list<SocketInfo>::iterator sock = sockets_.begin();
  97. while (sock!=sockets_.end()) {
  98. if (sock->sockfd_ == sockfd) {
  99. close(sockfd);
  100. sockets_.erase(sock);
  101. return (true); //socket found
  102. }
  103. ++sock;
  104. }
  105. return (false); // socket not found
  106. }
  107. IfaceMgr::IfaceMgr()
  108. :control_buf_len_(CMSG_SPACE(sizeof(struct in6_pktinfo))),
  109. control_buf_(new char[control_buf_len_]),
  110. session_socket_(INVALID_SOCKET), session_callback_(NULL)
  111. {
  112. try {
  113. // required for sending/receiving packets
  114. // let's keep it in front, just in case someone
  115. // wants to send anything during initialization
  116. // control_buf_ = boost::scoped_array<char>();
  117. detectIfaces();
  118. } catch (const std::exception& ex) {
  119. isc_throw(IfaceDetectError, ex.what());
  120. }
  121. }
  122. void IfaceMgr::closeSockets() {
  123. for (IfaceCollection::iterator iface = ifaces_.begin();
  124. iface != ifaces_.end(); ++iface) {
  125. iface->closeSockets();
  126. }
  127. }
  128. IfaceMgr::~IfaceMgr() {
  129. // control_buf_ is deleted automatically (scoped_ptr)
  130. control_buf_len_ = 0;
  131. closeSockets();
  132. }
  133. void IfaceMgr::stubDetectIfaces() {
  134. string ifaceName;
  135. const string v4addr("127.0.0.1"), v6addr("::1");
  136. // This is a stub implementation for interface detection. Actual detection
  137. // is faked by detecting loopback interface (lo or lo0). It will eventually
  138. // be removed once we have actual implementations for all supported systems.
  139. if (if_nametoindex("lo") > 0) {
  140. ifaceName = "lo";
  141. // this is Linux-like OS
  142. } else if (if_nametoindex("lo0") > 0) {
  143. ifaceName = "lo0";
  144. // this is BSD-like OS
  145. } else {
  146. // we give up. What OS is this, anyway? Solaris? Hurd?
  147. isc_throw(NotImplemented,
  148. "Interface detection on this OS is not supported.");
  149. }
  150. Iface iface(ifaceName, if_nametoindex(ifaceName.c_str()));
  151. iface.flag_up_ = true;
  152. iface.flag_running_ = true;
  153. // Note that we claim that this is not a loopback. iface_mgr tries to open a
  154. // socket on all interaces that are up, running and not loopback. As this is
  155. // the only interface we were able to detect, let's pretend this is a normal
  156. // interface.
  157. iface.flag_loopback_ = false;
  158. iface.flag_multicast_ = true;
  159. iface.flag_broadcast_ = true;
  160. iface.setHWType(HWTYPE_ETHERNET);
  161. iface.addAddress(IOAddress(v4addr));
  162. iface.addAddress(IOAddress(v6addr));
  163. addInterface(iface);
  164. }
  165. bool IfaceMgr::openSockets4(const uint16_t port) {
  166. int sock;
  167. int count = 0;
  168. for (IfaceCollection::iterator iface = ifaces_.begin();
  169. iface != ifaces_.end();
  170. ++iface) {
  171. if (iface->flag_loopback_ ||
  172. !iface->flag_up_ ||
  173. !iface->flag_running_) {
  174. continue;
  175. }
  176. AddressCollection addrs = iface->getAddresses();
  177. for (AddressCollection::iterator addr = addrs.begin();
  178. addr != addrs.end();
  179. ++addr) {
  180. // Skip IPv6 addresses
  181. if (addr->getFamily() != AF_INET) {
  182. continue;
  183. }
  184. sock = openSocket(iface->getName(), *addr, port);
  185. if (sock < 0) {
  186. isc_throw(SocketConfigError, "failed to open unicast socket");
  187. }
  188. count++;
  189. }
  190. }
  191. return (count > 0);
  192. }
  193. bool IfaceMgr::openSockets6(const uint16_t port) {
  194. int sock;
  195. int count = 0;
  196. for (IfaceCollection::iterator iface = ifaces_.begin();
  197. iface != ifaces_.end();
  198. ++iface) {
  199. if (iface->flag_loopback_ ||
  200. !iface->flag_up_ ||
  201. !iface->flag_running_) {
  202. continue;
  203. }
  204. AddressCollection addrs = iface->getAddresses();
  205. for (AddressCollection::iterator addr = addrs.begin();
  206. addr != addrs.end();
  207. ++addr) {
  208. // skip IPv4 addresses
  209. if (addr->getFamily() != AF_INET6) {
  210. continue;
  211. }
  212. // Bind link-local addresses only. Otherwise we bind several sockets
  213. // on interfaces that have several global addresses. For examples
  214. // with interface with 2 global addresses, we would bind 3 sockets
  215. // (one for link-local and two for global). That would result in
  216. // getting each message 3 times.
  217. if (!addr->getAddress().to_v6().is_link_local()){
  218. continue;
  219. }
  220. sock = openSocket(iface->getName(), *addr, port);
  221. if (sock < 0) {
  222. isc_throw(SocketConfigError, "failed to open unicast socket");
  223. }
  224. // Binding socket to unicast address and then joining multicast group
  225. // works well on Mac OS (and possibly other BSDs), but does not work
  226. // on Linux.
  227. if ( !joinMulticast(sock, iface->getName(),
  228. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS))) {
  229. close(sock);
  230. isc_throw(SocketConfigError, "Failed to join "
  231. << ALL_DHCP_RELAY_AGENTS_AND_SERVERS
  232. << " multicast group.");
  233. }
  234. count++;
  235. /// @todo: Remove this ifdef once we start supporting BSD systems.
  236. #if defined(OS_LINUX)
  237. // To receive multicast traffic, Linux requires binding socket to
  238. // a multicast group. That in turn doesn't work on NetBSD.
  239. int sock2 = openSocket(iface->getName(),
  240. IOAddress(ALL_DHCP_RELAY_AGENTS_AND_SERVERS),
  241. port);
  242. if (sock2 < 0) {
  243. isc_throw(SocketConfigError, "Failed to open multicast socket on "
  244. << " interface " << iface->getFullName());
  245. iface->delSocket(sock); // delete previously opened socket
  246. }
  247. #endif
  248. }
  249. }
  250. return (count > 0);
  251. }
  252. void
  253. IfaceMgr::printIfaces(std::ostream& out /*= std::cout*/) {
  254. for (IfaceCollection::const_iterator iface=ifaces_.begin();
  255. iface!=ifaces_.end();
  256. ++iface) {
  257. const AddressCollection& addrs = iface->getAddresses();
  258. out << "Detected interface " << iface->getFullName()
  259. << ", hwtype=" << iface->getHWType()
  260. << ", mac=" << iface->getPlainMac();
  261. out << ", flags=" << hex << iface->flags_ << dec << "("
  262. << (iface->flag_loopback_?"LOOPBACK ":"")
  263. << (iface->flag_up_?"UP ":"")
  264. << (iface->flag_running_?"RUNNING ":"")
  265. << (iface->flag_multicast_?"MULTICAST ":"")
  266. << (iface->flag_broadcast_?"BROADCAST ":"")
  267. << ")" << endl;
  268. out << " " << addrs.size() << " addr(s):";
  269. for (AddressCollection::const_iterator addr = addrs.begin();
  270. addr != addrs.end(); ++addr) {
  271. out << " " << addr->toText();
  272. }
  273. out << endl;
  274. }
  275. }
  276. IfaceMgr::Iface*
  277. IfaceMgr::getIface(int ifindex) {
  278. for (IfaceCollection::iterator iface=ifaces_.begin();
  279. iface!=ifaces_.end();
  280. ++iface) {
  281. if (iface->getIndex() == ifindex)
  282. return (&(*iface));
  283. }
  284. return (NULL); // not found
  285. }
  286. IfaceMgr::Iface*
  287. IfaceMgr::getIface(const std::string& ifname) {
  288. for (IfaceCollection::iterator iface=ifaces_.begin();
  289. iface!=ifaces_.end();
  290. ++iface) {
  291. if (iface->getName() == ifname)
  292. return (&(*iface));
  293. }
  294. return (NULL); // not found
  295. }
  296. int IfaceMgr::openSocket(const std::string& ifname, const IOAddress& addr,
  297. const uint16_t port) {
  298. Iface* iface = getIface(ifname);
  299. if (!iface) {
  300. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  301. }
  302. switch (addr.getFamily()) {
  303. case AF_INET:
  304. return openSocket4(*iface, addr, port);
  305. case AF_INET6:
  306. return openSocket6(*iface, addr, port);
  307. default:
  308. isc_throw(BadValue, "Failed to detect family of address: "
  309. << addr.toText());
  310. }
  311. }
  312. int IfaceMgr::openSocketFromIface(const std::string& ifname,
  313. const uint16_t port,
  314. const uint8_t family) {
  315. // Search for specified interface among detected interfaces.
  316. for (IfaceCollection::iterator iface = ifaces_.begin();
  317. iface != ifaces_.end();
  318. ++iface) {
  319. if ((iface->getFullName() != ifname) &&
  320. (iface->getName() != ifname)) {
  321. continue;
  322. }
  323. // Interface is now detected. Search for address on interface
  324. // that matches address family (v6 or v4).
  325. AddressCollection addrs = iface->getAddresses();
  326. AddressCollection::iterator addr_it = addrs.begin();
  327. while (addr_it != addrs.end()) {
  328. if (addr_it->getFamily() == family) {
  329. // We have interface and address so let's open socket.
  330. // This may cause isc::Unexpected exception.
  331. return (openSocket(iface->getName(), *addr_it, port));
  332. }
  333. ++addr_it;
  334. }
  335. // If we are at the end of address collection it means that we found
  336. // interface but there is no address for family specified.
  337. if (addr_it == addrs.end()) {
  338. // Stringify the family value to append it to exception string.
  339. std::string family_name("AF_INET");
  340. if (family == AF_INET6) {
  341. family_name = "AF_INET6";
  342. }
  343. // We did not find address on the interface.
  344. isc_throw(SocketConfigError, "There is no address for interface: "
  345. << ifname << ", port: " << port << ", address "
  346. " family: " << family_name);
  347. }
  348. }
  349. // If we got here it means that we had not found the specified interface.
  350. // Otherwise we would have returned from previous exist points.
  351. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  352. }
  353. int IfaceMgr::openSocketFromAddress(const IOAddress& addr,
  354. const uint16_t port) {
  355. // Search through detected interfaces and addresses to match
  356. // local address we got.
  357. for (IfaceCollection::iterator iface = ifaces_.begin();
  358. iface != ifaces_.end();
  359. ++iface) {
  360. AddressCollection addrs = iface->getAddresses();
  361. for (AddressCollection::iterator addr_it = addrs.begin();
  362. addr_it != addrs.end();
  363. ++addr_it) {
  364. // Local address must match one of the addresses
  365. // on detected interfaces. If it does, we have
  366. // address and interface detected so we can open
  367. // socket.
  368. if (*addr_it == addr) {
  369. // Open socket using local interface, address and port.
  370. // This may cause isc::Unexpected exception.
  371. return (openSocket(iface->getName(), *addr_it, port));
  372. }
  373. }
  374. }
  375. // If we got here it means that we did not find specified address
  376. // on any available interface.
  377. isc_throw(BadValue, "There is no such address " << addr.toText());
  378. }
  379. int IfaceMgr::openSocketFromRemoteAddress(const IOAddress& remote_addr,
  380. const uint16_t port) {
  381. try {
  382. // Get local address to be used to connect to remote location.
  383. IOAddress local_address(getLocalAddress(remote_addr, port).getAddress());
  384. return openSocketFromAddress(local_address, port);
  385. } catch (const Exception& e) {
  386. isc_throw(SocketConfigError, e.what());
  387. }
  388. }
  389. isc::asiolink::IOAddress
  390. IfaceMgr::getLocalAddress(const IOAddress& remote_addr, const uint16_t port) {
  391. // Create remote endpoint, we will be connecting to it.
  392. boost::scoped_ptr<const UDPEndpoint>
  393. remote_endpoint(static_cast<const UDPEndpoint*>
  394. (UDPEndpoint::create(IPPROTO_UDP, remote_addr, port)));
  395. if (!remote_endpoint) {
  396. isc_throw(Unexpected, "Unable to create remote endpoint");
  397. }
  398. // Create socket that will be used to connect to remote endpoint.
  399. asio::io_service io_service;
  400. asio::ip::udp::socket sock(io_service);
  401. asio::error_code err_code;
  402. // If remote address is broadcast address we have to
  403. // allow this on the socket.
  404. if (remote_addr.getAddress().is_v4() &&
  405. (remote_addr == IOAddress(DHCP_IPV4_BROADCAST_ADDRESS))) {
  406. // Socket has to be open prior to setting the broadcast
  407. // option. Otherwise set_option will complain about
  408. // bad file descriptor.
  409. // @todo: We don't specify interface in any way here. 255.255.255.255
  410. // We can very easily end up with a socket working on a different
  411. // interface.
  412. sock.open(asio::ip::udp::v4(), err_code);
  413. if (err_code) {
  414. isc_throw(Unexpected, "failed to open UDPv4 socket");
  415. }
  416. sock.set_option(asio::socket_base::broadcast(true), err_code);
  417. if (err_code) {
  418. sock.close();
  419. isc_throw(Unexpected, "failed to enable broadcast on the socket");
  420. }
  421. }
  422. // Try to connect to remote endpoint and check if attempt is successful.
  423. sock.connect(remote_endpoint->getASIOEndpoint(), err_code);
  424. if (err_code) {
  425. sock.close();
  426. isc_throw(Unexpected, "failed to connect to remote endpoint.");
  427. }
  428. // Once we are connected socket object holds local endpoint.
  429. asio::ip::udp::socket::endpoint_type local_endpoint =
  430. sock.local_endpoint();
  431. asio::ip::address local_address(local_endpoint.address());
  432. // Close the socket.
  433. sock.close();
  434. // Return address of local endpoint.
  435. return IOAddress(local_address);
  436. }
  437. int IfaceMgr::openSocket4(Iface& iface, const IOAddress& addr, uint16_t port) {
  438. struct sockaddr_in addr4;
  439. memset(&addr4, 0, sizeof(sockaddr));
  440. addr4.sin_family = AF_INET;
  441. addr4.sin_port = htons(port);
  442. addr4.sin_addr.s_addr = htonl(addr);
  443. //addr4.sin_addr.s_addr = 0; // anyaddr: this will receive 0.0.0.0 => 255.255.255.255 traffic
  444. // addr4.sin_addr.s_addr = 0xffffffffu; // broadcast address. This will receive 0.0.0.0 => 255.255.255.255 as well
  445. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  446. if (sock < 0) {
  447. isc_throw(SocketConfigError, "Failed to create UDP6 socket.");
  448. }
  449. if (bind(sock, (struct sockaddr *)&addr4, sizeof(addr4)) < 0) {
  450. close(sock);
  451. isc_throw(SocketConfigError, "Failed to bind socket " << sock << " to " << addr.toText()
  452. << "/port=" << port);
  453. }
  454. // if there is no support for IP_PKTINFO, we are really out of luck
  455. // it will be difficult to undersand, where this packet came from
  456. #if defined(IP_PKTINFO)
  457. int flag = 1;
  458. if (setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &flag, sizeof(flag)) != 0) {
  459. close(sock);
  460. isc_throw(SocketConfigError, "setsockopt: IP_PKTINFO: failed.");
  461. }
  462. #endif
  463. SocketInfo info(sock, addr, port);
  464. iface.addSocket(info);
  465. return (sock);
  466. }
  467. int IfaceMgr::openSocket6(Iface& iface, const IOAddress& addr, uint16_t port) {
  468. struct sockaddr_in6 addr6;
  469. memset(&addr6, 0, sizeof(addr6));
  470. addr6.sin6_family = AF_INET6;
  471. addr6.sin6_port = htons(port);
  472. if (addr.toText() != "::1") {
  473. addr6.sin6_scope_id = if_nametoindex(iface.getName().c_str());
  474. }
  475. memcpy(&addr6.sin6_addr,
  476. addr.getAddress().to_v6().to_bytes().data(),
  477. sizeof(addr6.sin6_addr));
  478. #ifdef HAVE_SA_LEN
  479. addr6.sin6_len = sizeof(addr6);
  480. #endif
  481. // TODO: use sockcreator once it becomes available
  482. // make a socket
  483. int sock = socket(AF_INET6, SOCK_DGRAM, 0);
  484. if (sock < 0) {
  485. isc_throw(SocketConfigError, "Failed to create UDP6 socket.");
  486. }
  487. // Set the REUSEADDR option so that we don't fail to start if
  488. // we're being restarted.
  489. int flag = 1;
  490. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  491. (char *)&flag, sizeof(flag)) < 0) {
  492. close(sock);
  493. isc_throw(SocketConfigError, "Can't set SO_REUSEADDR option on dhcpv6 socket.");
  494. }
  495. if (bind(sock, (struct sockaddr *)&addr6, sizeof(addr6)) < 0) {
  496. close(sock);
  497. isc_throw(SocketConfigError, "Failed to bind socket " << sock << " to " << addr.toText()
  498. << "/port=" << port);
  499. }
  500. #ifdef IPV6_RECVPKTINFO
  501. // RFC3542 - a new way
  502. if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
  503. &flag, sizeof(flag)) != 0) {
  504. close(sock);
  505. isc_throw(SocketConfigError, "setsockopt: IPV6_RECVPKTINFO failed.");
  506. }
  507. #else
  508. // RFC2292 - an old way
  509. if (setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO,
  510. &flag, sizeof(flag)) != 0) {
  511. close(sock);
  512. isc_throw(SocketConfigError, "setsockopt: IPV6_PKTINFO: failed.");
  513. }
  514. #endif
  515. // multicast stuff
  516. if (addr.getAddress().to_v6().is_multicast()) {
  517. // both mcast (ALL_DHCP_RELAY_AGENTS_AND_SERVERS and ALL_DHCP_SERVERS)
  518. // are link and site-scoped, so there is no sense to join those groups
  519. // with global addresses.
  520. if ( !joinMulticast( sock, iface.getName(),
  521. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  522. close(sock);
  523. isc_throw(SocketConfigError, "Failed to join " << ALL_DHCP_RELAY_AGENTS_AND_SERVERS
  524. << " multicast group.");
  525. }
  526. }
  527. SocketInfo info(sock, addr, port);
  528. iface.addSocket(info);
  529. return (sock);
  530. }
  531. bool
  532. IfaceMgr::joinMulticast(int sock, const std::string& ifname,
  533. const std::string & mcast) {
  534. struct ipv6_mreq mreq;
  535. if (inet_pton(AF_INET6, mcast.c_str(),
  536. &mreq.ipv6mr_multiaddr) <= 0) {
  537. return (false);
  538. }
  539. mreq.ipv6mr_interface = if_nametoindex(ifname.c_str());
  540. if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
  541. &mreq, sizeof(mreq)) < 0) {
  542. return (false);
  543. }
  544. return (true);
  545. }
  546. bool
  547. IfaceMgr::send(const Pkt6Ptr& pkt) {
  548. int result;
  549. Iface* iface = getIface(pkt->getIface());
  550. if (!iface) {
  551. isc_throw(BadValue, "Unable to send Pkt6. Invalid interface ("
  552. << pkt->getIface() << ") specified.");
  553. }
  554. memset(&control_buf_[0], 0, control_buf_len_);
  555. // Set the target address we're sending to.
  556. sockaddr_in6 to;
  557. memset(&to, 0, sizeof(to));
  558. to.sin6_family = AF_INET6;
  559. to.sin6_port = htons(pkt->getRemotePort());
  560. memcpy(&to.sin6_addr,
  561. pkt->getRemoteAddr().getAddress().to_v6().to_bytes().data(),
  562. 16);
  563. to.sin6_scope_id = pkt->getIndex();
  564. // Initialize our message header structure.
  565. struct msghdr m;
  566. memset(&m, 0, sizeof(m));
  567. m.msg_name = &to;
  568. m.msg_namelen = sizeof(to);
  569. // Set the data buffer we're sending. (Using this wacky
  570. // "scatter-gather" stuff... we only have a single chunk
  571. // of data to send, so we declare a single vector entry.)
  572. // As v structure is a C-style is used for both sending and
  573. // receiving data, it is shared between sending and receiving
  574. // (sendmsg and recvmsg). It is also defined in system headers,
  575. // so we have no control over its definition. To set iov_base
  576. // (defined as void*) we must use const cast from void *.
  577. // Otherwise C++ compiler would complain that we are trying
  578. // to assign const void* to void*.
  579. struct iovec v;
  580. memset(&v, 0, sizeof(v));
  581. v.iov_base = const_cast<void *>(pkt->getBuffer().getData());
  582. v.iov_len = pkt->getBuffer().getLength();
  583. m.msg_iov = &v;
  584. m.msg_iovlen = 1;
  585. // Setting the interface is a bit more involved.
  586. //
  587. // We have to create a "control message", and set that to
  588. // define the IPv6 packet information. We could set the
  589. // source address if we wanted, but we can safely let the
  590. // kernel decide what that should be.
  591. m.msg_control = &control_buf_[0];
  592. m.msg_controllen = control_buf_len_;
  593. struct cmsghdr *cmsg = CMSG_FIRSTHDR(&m);
  594. // FIXME: Code below assumes that cmsg is not NULL, but
  595. // CMSG_FIRSTHDR() is coded to return NULL as a possibility. The
  596. // following assertion should never fail, but if it did and you came
  597. // here, fix the code. :)
  598. assert(cmsg != NULL);
  599. cmsg->cmsg_level = IPPROTO_IPV6;
  600. cmsg->cmsg_type = IPV6_PKTINFO;
  601. cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
  602. struct in6_pktinfo *pktinfo = convertPktInfo6(CMSG_DATA(cmsg));
  603. memset(pktinfo, 0, sizeof(struct in6_pktinfo));
  604. pktinfo->ipi6_ifindex = pkt->getIndex();
  605. m.msg_controllen = cmsg->cmsg_len;
  606. pkt->updateTimestamp();
  607. result = sendmsg(getSocket(*pkt), &m, 0);
  608. if (result < 0) {
  609. isc_throw(SocketWriteError, "Pkt6 send failed: sendmsg() returned " << result);
  610. }
  611. return (result);
  612. }
  613. bool
  614. IfaceMgr::send(const Pkt4Ptr& pkt)
  615. {
  616. Iface* iface = getIface(pkt->getIface());
  617. if (!iface) {
  618. isc_throw(BadValue, "Unable to send Pkt4. Invalid interface ("
  619. << pkt->getIface() << ") specified.");
  620. }
  621. memset(&control_buf_[0], 0, control_buf_len_);
  622. // Set the target address we're sending to.
  623. sockaddr_in to;
  624. memset(&to, 0, sizeof(to));
  625. to.sin_family = AF_INET;
  626. to.sin_port = htons(pkt->getRemotePort());
  627. to.sin_addr.s_addr = htonl(pkt->getRemoteAddr());
  628. struct msghdr m;
  629. // Initialize our message header structure.
  630. memset(&m, 0, sizeof(m));
  631. m.msg_name = &to;
  632. m.msg_namelen = sizeof(to);
  633. // Set the data buffer we're sending. (Using this wacky
  634. // "scatter-gather" stuff... we only have a single chunk
  635. // of data to send, so we declare a single vector entry.)
  636. struct iovec v;
  637. memset(&v, 0, sizeof(v));
  638. // iov_base field is of void * type. We use it for packet
  639. // transmission, so this buffer will not be modified.
  640. v.iov_base = const_cast<void *>(pkt->getBuffer().getData());
  641. v.iov_len = pkt->getBuffer().getLength();
  642. m.msg_iov = &v;
  643. m.msg_iovlen = 1;
  644. // call OS-specific routines (like setting interface index)
  645. os_send4(m, control_buf_, control_buf_len_, pkt);
  646. pkt->updateTimestamp();
  647. int result = sendmsg(getSocket(*pkt), &m, 0);
  648. if (result < 0) {
  649. isc_throw(SocketWriteError, "pkt4 send failed");
  650. }
  651. return (result);
  652. }
  653. boost::shared_ptr<Pkt4>
  654. IfaceMgr::receive4(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */) {
  655. // Sanity check for microsecond timeout.
  656. if (timeout_usec >= 1000000) {
  657. isc_throw(BadValue, "fractional timeout must be shorter than"
  658. " one million microseconds");
  659. }
  660. const SocketInfo* candidate = 0;
  661. IfaceCollection::const_iterator iface;
  662. fd_set sockets;
  663. int maxfd = 0;
  664. stringstream names;
  665. FD_ZERO(&sockets);
  666. /// @todo: marginal performance optimization. We could create the set once
  667. /// and then use its copy for select(). Please note that select() modifies
  668. /// provided set to indicated which sockets have something to read.
  669. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  670. const SocketCollection& socket_collection = iface->getSockets();
  671. for (SocketCollection::const_iterator s = socket_collection.begin();
  672. s != socket_collection.end(); ++s) {
  673. // Only deal with IPv4 addresses.
  674. if (s->addr_.getFamily() == AF_INET) {
  675. names << s->sockfd_ << "(" << iface->getName() << ") ";
  676. // Add this socket to listening set
  677. FD_SET(s->sockfd_, &sockets);
  678. if (maxfd < s->sockfd_) {
  679. maxfd = s->sockfd_;
  680. }
  681. }
  682. }
  683. }
  684. // if there is session socket registered...
  685. if (session_socket_ != INVALID_SOCKET) {
  686. // at it to the set as well
  687. FD_SET(session_socket_, &sockets);
  688. if (maxfd < session_socket_)
  689. maxfd = session_socket_;
  690. names << session_socket_ << "(session)";
  691. }
  692. struct timeval select_timeout;
  693. select_timeout.tv_sec = timeout_sec;
  694. select_timeout.tv_usec = timeout_usec;
  695. int result = select(maxfd + 1, &sockets, NULL, NULL, &select_timeout);
  696. if (result == 0) {
  697. // nothing received and timeout has been reached
  698. return (Pkt4Ptr()); // NULL
  699. } else if (result < 0) {
  700. isc_throw(SocketReadError, strerror(errno));
  701. }
  702. // Let's find out which socket has the data
  703. if ((session_socket_ != INVALID_SOCKET) && (FD_ISSET(session_socket_, &sockets))) {
  704. // something received over session socket
  705. if (session_callback_) {
  706. // in theory we could call io_service.run_one() here, instead of
  707. // implementing callback mechanism, but that would introduce
  708. // asiolink dependency to libdhcp++ and that is something we want
  709. // to avoid (see CPE market and out long term plans for minimalistic
  710. // implementations.
  711. session_callback_();
  712. }
  713. return (Pkt4Ptr()); // NULL
  714. }
  715. // Let's find out which interface/socket has the data
  716. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  717. const SocketCollection& socket_collection = iface->getSockets();
  718. for (SocketCollection::const_iterator s = socket_collection.begin();
  719. s != socket_collection.end(); ++s) {
  720. if (FD_ISSET(s->sockfd_, &sockets)) {
  721. candidate = &(*s);
  722. break;
  723. }
  724. }
  725. if (candidate) {
  726. break;
  727. }
  728. }
  729. if (!candidate) {
  730. isc_throw(SocketReadError, "received data over unknown socket");
  731. }
  732. // Now we have a socket, let's get some data from it!
  733. struct sockaddr_in from_addr;
  734. uint8_t buf[RCVBUFSIZE];
  735. memset(&control_buf_[0], 0, control_buf_len_);
  736. memset(&from_addr, 0, sizeof(from_addr));
  737. // Initialize our message header structure.
  738. struct msghdr m;
  739. memset(&m, 0, sizeof(m));
  740. // Point so we can get the from address.
  741. m.msg_name = &from_addr;
  742. m.msg_namelen = sizeof(from_addr);
  743. struct iovec v;
  744. v.iov_base = static_cast<void*>(buf);
  745. v.iov_len = RCVBUFSIZE;
  746. m.msg_iov = &v;
  747. m.msg_iovlen = 1;
  748. // Getting the interface is a bit more involved.
  749. //
  750. // We set up some space for a "control message". We have
  751. // previously asked the kernel to give us packet
  752. // information (when we initialized the interface), so we
  753. // should get the destination address from that.
  754. m.msg_control = &control_buf_[0];
  755. m.msg_controllen = control_buf_len_;
  756. result = recvmsg(candidate->sockfd_, &m, 0);
  757. if (result < 0) {
  758. isc_throw(SocketReadError, "failed to receive UDP4 data");
  759. }
  760. // We have all data let's create Pkt4 object.
  761. Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(buf, result));
  762. pkt->updateTimestamp();
  763. unsigned int ifindex = iface->getIndex();
  764. IOAddress from(htonl(from_addr.sin_addr.s_addr));
  765. uint16_t from_port = htons(from_addr.sin_port);
  766. // Set receiving interface based on information, which socket was used to
  767. // receive data. OS-specific info (see os_receive4()) may be more reliable,
  768. // so this value may be overwritten.
  769. pkt->setIndex(ifindex);
  770. pkt->setIface(iface->getName());
  771. pkt->setRemoteAddr(from);
  772. pkt->setRemotePort(from_port);
  773. pkt->setLocalPort(candidate->port_);
  774. if (!os_receive4(m, pkt)) {
  775. isc_throw(SocketReadError, "unable to find pktinfo");
  776. }
  777. return (pkt);
  778. }
  779. Pkt6Ptr IfaceMgr::receive6(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */ ) {
  780. // Sanity check for microsecond timeout.
  781. if (timeout_usec >= 1000000) {
  782. isc_throw(BadValue, "fractional timeout must be shorter than"
  783. " one million microseconds");
  784. }
  785. const SocketInfo* candidate = 0;
  786. fd_set sockets;
  787. int maxfd = 0;
  788. stringstream names;
  789. FD_ZERO(&sockets);
  790. /// @todo: marginal performance optimization. We could create the set once
  791. /// and then use its copy for select(). Please note that select() modifies
  792. /// provided set to indicated which sockets have something to read.
  793. IfaceCollection::const_iterator iface;
  794. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  795. const SocketCollection& socket_collection = iface->getSockets();
  796. for (SocketCollection::const_iterator s = socket_collection.begin();
  797. s != socket_collection.end(); ++s) {
  798. // Only deal with IPv4 addresses.
  799. if (s->addr_.getFamily() == AF_INET6) {
  800. names << s->sockfd_ << "(" << iface->getName() << ") ";
  801. // Add this socket to listening set
  802. FD_SET(s->sockfd_, &sockets);
  803. if (maxfd < s->sockfd_) {
  804. maxfd = s->sockfd_;
  805. }
  806. }
  807. }
  808. }
  809. // if there is session socket registered...
  810. if (session_socket_ != INVALID_SOCKET) {
  811. // at it to the set as well
  812. FD_SET(session_socket_, &sockets);
  813. if (maxfd < session_socket_)
  814. maxfd = session_socket_;
  815. names << session_socket_ << "(session)";
  816. }
  817. struct timeval select_timeout;
  818. select_timeout.tv_sec = timeout_sec;
  819. select_timeout.tv_usec = timeout_usec;
  820. int result = select(maxfd + 1, &sockets, NULL, NULL, &select_timeout);
  821. if (result == 0) {
  822. // nothing received and timeout has been reached
  823. return (Pkt6Ptr()); // NULL
  824. } else if (result < 0) {
  825. isc_throw(SocketReadError, strerror(errno));
  826. }
  827. // Let's find out which socket has the data
  828. if ((session_socket_ != INVALID_SOCKET) && (FD_ISSET(session_socket_, &sockets))) {
  829. // something received over session socket
  830. if (session_callback_) {
  831. // in theory we could call io_service.run_one() here, instead of
  832. // implementing callback mechanism, but that would introduce
  833. // asiolink dependency to libdhcp++ and that is something we want
  834. // to avoid (see CPE market and out long term plans for minimalistic
  835. // implementations.
  836. session_callback_();
  837. }
  838. return (Pkt6Ptr()); // NULL
  839. }
  840. // Let's find out which interface/socket has the data
  841. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  842. const SocketCollection& socket_collection = iface->getSockets();
  843. for (SocketCollection::const_iterator s = socket_collection.begin();
  844. s != socket_collection.end(); ++s) {
  845. if (FD_ISSET(s->sockfd_, &sockets)) {
  846. candidate = &(*s);
  847. break;
  848. }
  849. }
  850. if (candidate) {
  851. break;
  852. }
  853. }
  854. if (!candidate) {
  855. isc_throw(SocketReadError, "received data over unknown socket");
  856. }
  857. // Now we have a socket, let's get some data from it!
  858. uint8_t buf[RCVBUFSIZE];
  859. memset(&control_buf_[0], 0, control_buf_len_);
  860. struct sockaddr_in6 from;
  861. memset(&from, 0, sizeof(from));
  862. // Initialize our message header structure.
  863. struct msghdr m;
  864. memset(&m, 0, sizeof(m));
  865. // Point so we can get the from address.
  866. m.msg_name = &from;
  867. m.msg_namelen = sizeof(from);
  868. // Set the data buffer we're receiving. (Using this wacky
  869. // "scatter-gather" stuff... but we that doesn't really make
  870. // sense for us, so we use a single vector entry.)
  871. struct iovec v;
  872. memset(&v, 0, sizeof(v));
  873. v.iov_base = static_cast<void*>(buf);
  874. v.iov_len = RCVBUFSIZE;
  875. m.msg_iov = &v;
  876. m.msg_iovlen = 1;
  877. // Getting the interface is a bit more involved.
  878. //
  879. // We set up some space for a "control message". We have
  880. // previously asked the kernel to give us packet
  881. // information (when we initialized the interface), so we
  882. // should get the destination address from that.
  883. m.msg_control = &control_buf_[0];
  884. m.msg_controllen = control_buf_len_;
  885. result = recvmsg(candidate->sockfd_, &m, 0);
  886. struct in6_addr to_addr;
  887. memset(&to_addr, 0, sizeof(to_addr));
  888. int ifindex = -1;
  889. if (result >= 0) {
  890. struct in6_pktinfo* pktinfo = NULL;
  891. // If we did read successfully, then we need to loop
  892. // through the control messages we received and
  893. // find the one with our destination address.
  894. //
  895. // We also keep a flag to see if we found it. If we
  896. // didn't, then we consider this to be an error.
  897. bool found_pktinfo = false;
  898. struct cmsghdr* cmsg = CMSG_FIRSTHDR(&m);
  899. while (cmsg != NULL) {
  900. if ((cmsg->cmsg_level == IPPROTO_IPV6) &&
  901. (cmsg->cmsg_type == IPV6_PKTINFO)) {
  902. pktinfo = convertPktInfo6(CMSG_DATA(cmsg));
  903. to_addr = pktinfo->ipi6_addr;
  904. ifindex = pktinfo->ipi6_ifindex;
  905. found_pktinfo = true;
  906. break;
  907. }
  908. cmsg = CMSG_NXTHDR(&m, cmsg);
  909. }
  910. if (!found_pktinfo) {
  911. isc_throw(SocketReadError, "unable to find pktinfo");
  912. }
  913. } else {
  914. isc_throw(SocketReadError, "failed to receive data");
  915. }
  916. // Let's create a packet.
  917. Pkt6Ptr pkt;
  918. try {
  919. pkt = Pkt6Ptr(new Pkt6(buf, result));
  920. } catch (const std::exception& ex) {
  921. isc_throw(SocketReadError, "failed to create new packet");
  922. }
  923. pkt->updateTimestamp();
  924. pkt->setLocalAddr(IOAddress::fromBytes(AF_INET6,
  925. reinterpret_cast<const uint8_t*>(&to_addr)));
  926. pkt->setRemoteAddr(IOAddress::fromBytes(AF_INET6,
  927. reinterpret_cast<const uint8_t*>(&from.sin6_addr)));
  928. pkt->setRemotePort(ntohs(from.sin6_port));
  929. pkt->setIndex(ifindex);
  930. Iface* received = getIface(pkt->getIndex());
  931. if (received) {
  932. pkt->setIface(received->getName());
  933. } else {
  934. isc_throw(SocketReadError, "received packet over unknown interface"
  935. << "(ifindex=" << pkt->getIndex() << ")");
  936. }
  937. return (pkt);
  938. }
  939. uint16_t IfaceMgr::getSocket(const isc::dhcp::Pkt6& pkt) {
  940. Iface* iface = getIface(pkt.getIface());
  941. if (iface == NULL) {
  942. isc_throw(BadValue, "Tried to find socket for non-existent interface "
  943. << pkt.getIface());
  944. }
  945. const SocketCollection& socket_collection = iface->getSockets();
  946. SocketCollection::const_iterator s;
  947. for (s = socket_collection.begin(); s != socket_collection.end(); ++s) {
  948. if ((s->family_ == AF_INET6) &&
  949. (!s->addr_.getAddress().to_v6().is_multicast())) {
  950. return (s->sockfd_);
  951. }
  952. /// @todo: Add more checks here later. If remote address is
  953. /// not link-local, we can't use link local bound socket
  954. /// to send data.
  955. }
  956. isc_throw(Unexpected, "Interface " << iface->getFullName()
  957. << " does not have any suitable IPv6 sockets open.");
  958. }
  959. uint16_t IfaceMgr::getSocket(isc::dhcp::Pkt4 const& pkt) {
  960. Iface* iface = getIface(pkt.getIface());
  961. if (iface == NULL) {
  962. isc_throw(BadValue, "Tried to find socket for non-existent interface "
  963. << pkt.getIface());
  964. }
  965. const SocketCollection& socket_collection = iface->getSockets();
  966. SocketCollection::const_iterator s;
  967. for (s = socket_collection.begin(); s != socket_collection.end(); ++s) {
  968. if (s->family_ == AF_INET) {
  969. return (s->sockfd_);
  970. }
  971. /// TODO: Add more checks here later. If remote address is
  972. /// not link-local, we can't use link local bound socket
  973. /// to send data.
  974. }
  975. isc_throw(Unexpected, "Interface " << iface->getFullName()
  976. << " does not have any suitable IPv4 sockets open.");
  977. }
  978. } // end of namespace isc::dhcp
  979. } // end of namespace isc