iface_mgr.cc 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. // Copyright (C) 2011 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. #include <sstream>
  16. #include <fstream>
  17. #include <string.h>
  18. #include <netinet/in.h>
  19. #include <arpa/inet.h>
  20. #include <dhcp/dhcp4.h>
  21. #include <dhcp/dhcp6.h>
  22. #include <dhcp/iface_mgr.h>
  23. #include <exceptions/exceptions.h>
  24. using namespace std;
  25. using namespace isc;
  26. using namespace isc::asiolink;
  27. using namespace isc::dhcp;
  28. namespace isc {
  29. /// IfaceMgr is a singleton implementation
  30. IfaceMgr* IfaceMgr::instance_ = 0;
  31. void
  32. IfaceMgr::instanceCreate() {
  33. if (instance_) {
  34. // no need to do anything. Instance is already created.
  35. // Who called it again anyway? Uh oh. Had to be us, as
  36. // this is private method.
  37. return;
  38. }
  39. instance_ = new IfaceMgr();
  40. }
  41. IfaceMgr&
  42. IfaceMgr::instance() {
  43. if (instance_ == 0) {
  44. instanceCreate();
  45. }
  46. return (*instance_);
  47. }
  48. IfaceMgr::Iface::Iface(const std::string& name, int ifindex)
  49. :name_(name), ifindex_(ifindex), mac_len_(0), flag_loopback_(false),
  50. flag_up_(false), flag_running_(false), flag_multicast_(false),
  51. flag_broadcast_(false), flags_(0), hardware_type_(0)
  52. {
  53. memset(mac_, 0, sizeof(mac_));
  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. bool IfaceMgr::Iface::delAddress(const isc::asiolink::IOAddress& addr) {
  76. for (AddressCollection::iterator a = addrs_.begin();
  77. a!=addrs_.end(); ++a) {
  78. if (*a==addr) {
  79. addrs_.erase(a);
  80. return (true);
  81. }
  82. }
  83. return (false);
  84. }
  85. bool IfaceMgr::Iface::delSocket(uint16_t sockfd) {
  86. list<SocketInfo>::iterator sock = sockets_.begin();
  87. while (sock!=sockets_.end()) {
  88. if (sock->sockfd_ == sockfd) {
  89. close(sockfd);
  90. sockets_.erase(sock);
  91. return (true); //socket found
  92. }
  93. ++sock;
  94. }
  95. return (false); // socket not found
  96. }
  97. IfaceMgr::IfaceMgr()
  98. :control_buf_len_(CMSG_SPACE(sizeof(struct in6_pktinfo))),
  99. control_buf_(new char[control_buf_len_])
  100. {
  101. cout << "IfaceMgr initialization." << endl;
  102. try {
  103. // required for sending/receiving packets
  104. // let's keep it in front, just in case someone
  105. // wants to send anything during initialization
  106. // control_buf_ = boost::scoped_array<char>();
  107. detectIfaces();
  108. } catch (const std::exception& ex) {
  109. cout << "IfaceMgr creation failed:" << ex.what() << endl;
  110. // TODO Uncomment this (or call LOG_FATAL) once
  111. // interface detection is implemented. Otherwise
  112. // it is not possible to run tests in a portable
  113. // way (see detectIfaces() method).
  114. throw ex;
  115. }
  116. }
  117. void IfaceMgr::closeSockets() {
  118. for (IfaceCollection::iterator iface = ifaces_.begin();
  119. iface != ifaces_.end(); ++iface) {
  120. for (SocketCollection::iterator sock = iface->sockets_.begin();
  121. sock != iface->sockets_.end(); ++sock) {
  122. cout << "Closing socket " << sock->sockfd_ << endl;
  123. close(sock->sockfd_);
  124. }
  125. iface->sockets_.clear();
  126. }
  127. }
  128. IfaceMgr::~IfaceMgr() {
  129. // control_buf_ is deleted automatically (scoped_ptr)
  130. control_buf_len_ = 0;
  131. closeSockets();
  132. }
  133. void
  134. IfaceMgr::stubDetectIfaces() {
  135. string ifaceName, linkLocal;
  136. // TODO do the actual detection. Currently interface detection is faked
  137. // by reading a text file.
  138. cout << "Interface detection is not implemented yet. "
  139. << "Reading interfaces.txt file instead." << endl;
  140. cout << "Please use format: interface-name link-local-address" << endl;
  141. try {
  142. ifstream interfaces("interfaces.txt");
  143. if (!interfaces.good()) {
  144. cout << "interfaces.txt file is not available. Stub interface detection skipped." << endl;
  145. return;
  146. }
  147. interfaces >> ifaceName;
  148. interfaces >> linkLocal;
  149. cout << "Detected interface " << ifaceName << "/" << linkLocal << endl;
  150. Iface iface(ifaceName, if_nametoindex( ifaceName.c_str() ) );
  151. IOAddress addr(linkLocal);
  152. iface.addAddress(addr);
  153. addInterface(iface);
  154. interfaces.close();
  155. } catch (const std::exception& ex) {
  156. // TODO: deallocate whatever memory we used
  157. // not that important, since this function is going to be
  158. // thrown away as soon as we get proper interface detection
  159. // implemented
  160. // TODO Do LOG_FATAL here
  161. std::cerr << "Interface detection failed." << std::endl;
  162. throw ex;
  163. }
  164. }
  165. #if !defined(OS_LINUX) && !defined(OS_BSD)
  166. void IfaceMgr::detectIfaces() {
  167. stubDetectIfaces();
  168. }
  169. #endif
  170. bool IfaceMgr::openSockets4(uint16_t port) {
  171. int sock;
  172. int count = 0;
  173. for (IfaceCollection::iterator iface=ifaces_.begin();
  174. iface!=ifaces_.end();
  175. ++iface) {
  176. cout << "Trying interface " << iface->getFullName() << endl;
  177. #if 0
  178. if (iface->flag_loopback_ ||
  179. !iface->flag_up_ ||
  180. !iface->flag_running_) {
  181. continue;
  182. }
  183. #endif
  184. AddressCollection addrs = iface->getAddresses();
  185. for (AddressCollection::iterator addr= addrs.begin();
  186. addr != addrs.end();
  187. ++addr) {
  188. // skip IPv4 addresses
  189. if (addr->getFamily() != AF_INET) {
  190. continue;
  191. }
  192. sock = openSocket(iface->getName(), *addr, port);
  193. if (sock<0) {
  194. cout << "Failed to open unicast socket." << endl;
  195. return (false);
  196. }
  197. count++;
  198. }
  199. }
  200. return (count > 0);
  201. }
  202. bool IfaceMgr::openSockets6(uint16_t port) {
  203. int sock;
  204. int count = 0;
  205. for (IfaceCollection::iterator iface=ifaces_.begin();
  206. iface!=ifaces_.end();
  207. ++iface) {
  208. AddressCollection addrs = iface->getAddresses();
  209. for (AddressCollection::iterator addr= addrs.begin();
  210. addr != addrs.end();
  211. ++addr) {
  212. // skip IPv4 addresses
  213. if (addr->getFamily() != AF_INET6) {
  214. continue;
  215. }
  216. sock = openSocket(iface->getName(), *addr, port);
  217. if (sock<0) {
  218. cout << "Failed to open unicast socket." << endl;
  219. return (false);
  220. }
  221. if ( !joinMulticast(sock, iface->getName(),
  222. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  223. close(sock);
  224. isc_throw(Unexpected, "Failed to join " << ALL_DHCP_RELAY_AGENTS_AND_SERVERS
  225. << " multicast group.");
  226. }
  227. count++;
  228. #if 0
  229. // this doesn't work too well on NetBSD
  230. sock2 = openSocket(iface->getName(),
  231. IOAddress(ALL_DHCP_RELAY_AGENTS_AND_SERVERS),
  232. DHCP6_SERVER_PORT);
  233. if (sock2<0) {
  234. isc_throw(Unexpected, "Failed to open multicast socket on "
  235. << " interface " << iface->getFullName());
  236. iface->delSocket(sock1); // delete previously opened socket
  237. }
  238. #endif
  239. }
  240. }
  241. return (count > 0);
  242. }
  243. void
  244. IfaceMgr::printIfaces(std::ostream& out /*= std::cout*/) {
  245. for (IfaceCollection::const_iterator iface=ifaces_.begin();
  246. iface!=ifaces_.end();
  247. ++iface) {
  248. const AddressCollection& addrs = iface->getAddresses();
  249. out << "Detected interface " << iface->getFullName()
  250. << ", hwtype=" << iface->hardware_type_ << ", maclen=" << iface->mac_len_
  251. << ", mac=" << iface->getPlainMac();
  252. out << ", flags=" << hex << iface->flags_ << dec << "("
  253. << (iface->flag_loopback_?"LOOPBACK ":"")
  254. << (iface->flag_up_?"UP ":"")
  255. << (iface->flag_running_?"RUNNING ":"")
  256. << (iface->flag_multicast_?"MULTICAST ":"")
  257. << (iface->flag_broadcast_?"BROADCAST ":"")
  258. << ")" << endl;
  259. out << " " << addrs.size() << " addr(s):";
  260. for (AddressCollection::const_iterator addr = addrs.begin();
  261. addr != addrs.end(); ++addr) {
  262. out << " " << addr->toText();
  263. }
  264. out << endl;
  265. }
  266. }
  267. IfaceMgr::Iface*
  268. IfaceMgr::getIface(int ifindex) {
  269. for (IfaceCollection::iterator iface=ifaces_.begin();
  270. iface!=ifaces_.end();
  271. ++iface) {
  272. if (iface->getIndex() == ifindex)
  273. return (&(*iface));
  274. }
  275. return (NULL); // not found
  276. }
  277. IfaceMgr::Iface*
  278. IfaceMgr::getIface(const std::string& ifname) {
  279. for (IfaceCollection::iterator iface=ifaces_.begin();
  280. iface!=ifaces_.end();
  281. ++iface) {
  282. if (iface->getName() == ifname)
  283. return (&(*iface));
  284. }
  285. return (NULL); // not found
  286. }
  287. int IfaceMgr::openSocket(const std::string& ifname,
  288. const IOAddress& addr,
  289. int port) {
  290. Iface* iface = getIface(ifname);
  291. if (!iface) {
  292. isc_throw(BadValue, "There is no " << ifname << " interface present.");
  293. }
  294. switch (addr.getFamily()) {
  295. case AF_INET:
  296. return openSocket4(*iface, addr, port);
  297. case AF_INET6:
  298. return openSocket6(*iface, addr, port);
  299. default:
  300. isc_throw(BadValue, "Failed to detect family of address: "
  301. << addr.toText());
  302. }
  303. }
  304. int IfaceMgr::openSocket4(Iface& iface, const IOAddress& addr, int port) {
  305. cout << "Creating UDP4 socket on " << iface.getFullName()
  306. << " " << addr.toText() << "/port=" << port << endl;
  307. struct sockaddr_in addr4;
  308. memset(&addr4, 0, sizeof(sockaddr));
  309. addr4.sin_family = AF_INET;
  310. addr4.sin_port = htons(port);
  311. addr4.sin_addr.s_addr = htonl(addr);
  312. //addr4.sin_addr.s_addr = 0; // anyaddr: this will receive 0.0.0.0 => 255.255.255.255 traffic
  313. // addr4.sin_addr.s_addr = 0xffffffffu; // broadcast address. This will receive 0.0.0.0 => 255.255.255.255 as well
  314. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  315. if (sock < 0) {
  316. isc_throw(Unexpected, "Failed to create UDP6 socket.");
  317. }
  318. if (bind(sock, (struct sockaddr *)&addr4, sizeof(addr4)) < 0) {
  319. close(sock);
  320. isc_throw(Unexpected, "Failed to bind socket " << sock << " to " << addr.toText()
  321. << "/port=" << port);
  322. }
  323. // if there is no support for IP_PKTINFO, we are really out of luck
  324. // it will be difficult to undersand, where this packet came from
  325. #if defined(IP_PKTINFO)
  326. int flag = 1;
  327. if (setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &flag, sizeof(flag)) != 0) {
  328. close(sock);
  329. isc_throw(Unexpected, "setsockopt: IP_PKTINFO: failed.");
  330. }
  331. #endif
  332. cout << "Created socket " << sock << " on " << iface.getName() << "/" <<
  333. addr.toText() << "/port=" << port << endl;
  334. SocketInfo info(sock, addr, port);
  335. iface.addSocket(info);
  336. return (sock);
  337. }
  338. int IfaceMgr::openSocket6(Iface& iface, const IOAddress& addr, int port) {
  339. cout << "Creating UDP6 socket on " << iface.getFullName()
  340. << " " << addr.toText() << "/port=" << port << endl;
  341. struct sockaddr_in6 addr6;
  342. memset(&addr6, 0, sizeof(addr6));
  343. addr6.sin6_family = AF_INET6;
  344. addr6.sin6_port = htons(port);
  345. if (addr.toText() != "::1")
  346. addr6.sin6_scope_id = if_nametoindex(iface.getName().c_str());
  347. memcpy(&addr6.sin6_addr,
  348. addr.getAddress().to_v6().to_bytes().data(),
  349. sizeof(addr6.sin6_addr));
  350. #ifdef HAVE_SA_LEN
  351. addr6.sin6_len = sizeof(addr6);
  352. #endif
  353. // TODO: use sockcreator once it becomes available
  354. // make a socket
  355. int sock = socket(AF_INET6, SOCK_DGRAM, 0);
  356. if (sock < 0) {
  357. isc_throw(Unexpected, "Failed to create UDP6 socket.");
  358. }
  359. /* Set the REUSEADDR option so that we don't fail to start if
  360. we're being restarted. */
  361. int flag = 1;
  362. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  363. (char *)&flag, sizeof(flag)) < 0) {
  364. close(sock);
  365. isc_throw(Unexpected, "Can't set SO_REUSEADDR option on dhcpv6 socket.");
  366. }
  367. if (bind(sock, (struct sockaddr *)&addr6, sizeof(addr6)) < 0) {
  368. close(sock);
  369. isc_throw(Unexpected, "Failed to bind socket " << sock << " to " << addr.toText()
  370. << "/port=" << port);
  371. }
  372. #ifdef IPV6_RECVPKTINFO
  373. /* RFC3542 - a new way */
  374. if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
  375. &flag, sizeof(flag)) != 0) {
  376. close(sock);
  377. isc_throw(Unexpected, "setsockopt: IPV6_RECVPKTINFO failed.");
  378. }
  379. #else
  380. /* RFC2292 - an old way */
  381. if (setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO,
  382. &flag, sizeof(flag)) != 0) {
  383. close(sock);
  384. isc_throw(Unexpected, "setsockopt: IPV6_PKTINFO: failed.");
  385. }
  386. #endif
  387. // multicast stuff
  388. if (addr.getAddress().to_v6().is_multicast()) {
  389. // both mcast (ALL_DHCP_RELAY_AGENTS_AND_SERVERS and ALL_DHCP_SERVERS)
  390. // are link and site-scoped, so there is no sense to join those groups
  391. // with global addresses.
  392. if ( !joinMulticast( sock, iface.getName(),
  393. string(ALL_DHCP_RELAY_AGENTS_AND_SERVERS) ) ) {
  394. close(sock);
  395. isc_throw(Unexpected, "Failed to join " << ALL_DHCP_RELAY_AGENTS_AND_SERVERS
  396. << " multicast group.");
  397. }
  398. }
  399. cout << "Created socket " << sock << " on " << iface.getName() << "/" <<
  400. addr.toText() << "/port=" << port << endl;
  401. SocketInfo info(sock, addr, port);
  402. iface.addSocket(info);
  403. return (sock);
  404. }
  405. bool
  406. IfaceMgr::joinMulticast(int sock, const std::string& ifname,
  407. const std::string & mcast) {
  408. struct ipv6_mreq mreq;
  409. if (inet_pton(AF_INET6, mcast.c_str(),
  410. &mreq.ipv6mr_multiaddr) <= 0) {
  411. cout << "Failed to convert " << ifname
  412. << " to IPv6 multicast address." << endl;
  413. return (false);
  414. }
  415. mreq.ipv6mr_interface = if_nametoindex(ifname.c_str());
  416. if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
  417. &mreq, sizeof(mreq)) < 0) {
  418. cout << "Failed to join " << mcast << " multicast group." << endl;
  419. return (false);
  420. }
  421. cout << "Joined multicast " << mcast << " group." << endl;
  422. return (true);
  423. }
  424. bool
  425. IfaceMgr::send(boost::shared_ptr<Pkt6>& pkt) {
  426. struct msghdr m;
  427. struct iovec v;
  428. int result;
  429. struct in6_pktinfo *pktinfo;
  430. struct cmsghdr *cmsg;
  431. Iface* iface = getIface(pkt->iface_);
  432. if (!iface) {
  433. isc_throw(BadValue, "Unable to send Pkt6. Invalid interface ("
  434. << pkt->iface_ << ") specified.");
  435. }
  436. memset(&control_buf_[0], 0, control_buf_len_);
  437. // Initialize our message header structure.
  438. memset(&m, 0, sizeof(m));
  439. // Set the target address we're sending to.
  440. sockaddr_in6 to;
  441. memset(&to, 0, sizeof(to));
  442. to.sin6_family = AF_INET6;
  443. to.sin6_port = htons(pkt->remote_port_);
  444. memcpy(&to.sin6_addr,
  445. pkt->remote_addr_.getAddress().to_v6().to_bytes().data(),
  446. 16);
  447. to.sin6_scope_id = pkt->ifindex_;
  448. m.msg_name = &to;
  449. m.msg_namelen = sizeof(to);
  450. // Set the data buffer we're sending. (Using this wacky
  451. // "scatter-gather" stuff... we only have a single chunk
  452. // of data to send, so we declare a single vector entry.)
  453. v.iov_base = (char *) &pkt->data_[0];
  454. v.iov_len = pkt->data_len_;
  455. m.msg_iov = &v;
  456. m.msg_iovlen = 1;
  457. // Setting the interface is a bit more involved.
  458. //
  459. // We have to create a "control message", and set that to
  460. // define the IPv6 packet information. We could set the
  461. // source address if we wanted, but we can safely let the
  462. // kernel decide what that should be.
  463. m.msg_control = &control_buf_[0];
  464. m.msg_controllen = control_buf_len_;
  465. cmsg = CMSG_FIRSTHDR(&m);
  466. cmsg->cmsg_level = IPPROTO_IPV6;
  467. cmsg->cmsg_type = IPV6_PKTINFO;
  468. cmsg->cmsg_len = CMSG_LEN(sizeof(*pktinfo));
  469. pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
  470. memset(pktinfo, 0, sizeof(*pktinfo));
  471. pktinfo->ipi6_ifindex = pkt->ifindex_;
  472. m.msg_controllen = cmsg->cmsg_len;
  473. result = sendmsg(getSocket(*pkt), &m, 0);
  474. if (result < 0) {
  475. cout << "Send packet failed." << endl;
  476. }
  477. cout << "Sent " << pkt->data_len_ << " bytes over socket " << getSocket(*pkt)
  478. << " on " << iface->getFullName() << " interface: "
  479. << " dst=" << pkt->remote_addr_.toText()
  480. << ", src=" << pkt->local_addr_.toText()
  481. << endl;
  482. return (result);
  483. }
  484. bool
  485. IfaceMgr::send(boost::shared_ptr<Pkt4>& pkt)
  486. {
  487. struct msghdr m;
  488. struct iovec v;
  489. int result;
  490. Iface* iface = getIface(pkt->getIface());
  491. if (!iface) {
  492. isc_throw(BadValue, "Unable to send Pkt4. Invalid interface ("
  493. << pkt->getIface() << ") specified.");
  494. }
  495. memset(&control_buf_[0], 0, control_buf_len_);
  496. // Initialize our message header structure.
  497. memset(&m, 0, sizeof(m));
  498. // Set the target address we're sending to.
  499. sockaddr_in to;
  500. memset(&to, 0, sizeof(to));
  501. to.sin_family = AF_INET;
  502. to.sin_port = htons(pkt->getRemotePort());
  503. to.sin_addr.s_addr = htonl(pkt->getRemoteAddr());
  504. m.msg_name = &to;
  505. m.msg_namelen = sizeof(to);
  506. // Set the data buffer we're sending. (Using this wacky
  507. // "scatter-gather" stuff... we only have a single chunk
  508. // of data to send, so we declare a single vector entry.)
  509. v.iov_base = (char *) pkt->getBuffer().getData();
  510. v.iov_len = pkt->getBuffer().getLength();
  511. m.msg_iov = &v;
  512. m.msg_iovlen = 1;
  513. // OS_LINUX defines are part of ticket #1237
  514. #if defined(OS_LINUX)
  515. // Setting the interface is a bit more involved.
  516. //
  517. // We have to create a "control message", and set that to
  518. // define the IPv4 packet information. We could set the
  519. // source address if we wanted, but we can safely let the
  520. // kernel decide what that should be.
  521. struct in_pktinfo *pktinfo;
  522. struct cmsghdr *cmsg;
  523. m.msg_control = &control_buf_[0];
  524. m.msg_controllen = control_buf_len_;
  525. cmsg = CMSG_FIRSTHDR(&m);
  526. cmsg->cmsg_level = IPPROTO_IP;
  527. cmsg->cmsg_type = IP_PKTINFO;
  528. cmsg->cmsg_len = CMSG_LEN(sizeof(*pktinfo));
  529. pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg);
  530. memset(pktinfo, 0, sizeof(*pktinfo));
  531. pktinfo->ipi_ifindex = pkt->getIndex();
  532. m.msg_controllen = cmsg->cmsg_len;
  533. #endif
  534. cout << "Trying to send " << pkt->getBuffer().getLength() << " bytes to "
  535. << pkt->getRemoteAddr().toText() << ":" << pkt->getRemotePort()
  536. << " over socket " << getSocket(*pkt) << " on interface "
  537. << getIface(pkt->getIface())->getFullName() << endl;
  538. result = sendmsg(getSocket(*pkt), &m, 0);
  539. if (result < 0) {
  540. isc_throw(Unexpected, "Pkt4 send failed.");
  541. }
  542. cout << "Sent " << pkt->getBuffer().getLength() << " bytes over socket " << getSocket(*pkt)
  543. << " on " << iface->getFullName() << " interface: "
  544. << " dst=" << pkt->getRemoteAddr().toText() << ":" << pkt->getRemotePort()
  545. << ", src=" << pkt->getLocalAddr().toText() << ":" << pkt->getLocalPort()
  546. << endl;
  547. return (result);
  548. }
  549. boost::shared_ptr<Pkt4>
  550. IfaceMgr::receive4() {
  551. const SocketInfo* candidate = 0;
  552. IfaceCollection::const_iterator iface;
  553. for (iface = ifaces_.begin(); iface != ifaces_.end(); ++iface) {
  554. #if 0
  555. // uncomment this once #1237 is merged
  556. // Let's skip loopback and downed interfaces.
  557. if (iface->flag_loopback_ ||
  558. !iface->flag_up_ ||
  559. !iface->flag_running_) {
  560. continue;
  561. }
  562. #endif
  563. SocketCollection::const_iterator s = iface->sockets_.begin();
  564. while (s != iface->sockets_.end()) {
  565. // We don't want IPv6 addresses here.
  566. if (s->addr_.getFamily() != AF_INET) {
  567. ++s;
  568. continue;
  569. }
  570. // This address looks good.
  571. if (!candidate) {
  572. candidate = &(*s);
  573. break;
  574. }
  575. ++s;
  576. }
  577. if (candidate) {
  578. break;
  579. }
  580. }
  581. if (!candidate) {
  582. isc_throw(Unexpected, "Failed to find any suitable sockets on all interfaces.");
  583. }
  584. cout << "Trying to receive over UDP4 socket " << candidate->sockfd_ << " bound to "
  585. << candidate->addr_.toText() << "/port=" << candidate->port_ << " on "
  586. << iface->getFullName() << endl;
  587. // Now we have a socket, let's get some data from it!
  588. struct msghdr m;
  589. struct iovec v;
  590. int result;
  591. struct sockaddr_in from_addr;
  592. struct in_addr to_addr;
  593. boost::shared_ptr<Pkt4> pkt;
  594. const uint32_t RCVBUFSIZE = 1500;
  595. uint8_t* buf = (uint8_t*) malloc(RCVBUFSIZE);
  596. memset(&control_buf_[0], 0, control_buf_len_);
  597. memset(&from_addr, 0, sizeof(from_addr));
  598. memset(&to_addr, 0, sizeof(to_addr));
  599. // Initialize our message header structure.
  600. memset(&m, 0, sizeof(m));
  601. // Point so we can get the from address.
  602. m.msg_name = &from_addr;
  603. m.msg_namelen = sizeof(from_addr);
  604. v.iov_base = (void*)buf;
  605. v.iov_len = RCVBUFSIZE;
  606. m.msg_iov = &v;
  607. m.msg_iovlen = 1;
  608. // Getting the interface is a bit more involved.
  609. //
  610. // We set up some space for a "control message". We have
  611. // previously asked the kernel to give us packet
  612. // information (when we initialized the interface), so we
  613. // should get the destination address from that.
  614. m.msg_control = &control_buf_[0];
  615. m.msg_controllen = control_buf_len_;
  616. result = recvmsg(candidate->sockfd_, &m, 0);
  617. if (result < 0) {
  618. cout << "Failed to receive UDP4 data." << endl;
  619. delete buf;
  620. return (boost::shared_ptr<Pkt4>()); // NULL
  621. }
  622. // OS_LINUX defines are part of ticket #1237
  623. #if defined(OS_LINUX)
  624. struct cmsghdr* cmsg;
  625. struct in_pktinfo* pktinfo;
  626. unsigned int ifindex = 0;
  627. int found_pktinfo = 0;
  628. cmsg = CMSG_FIRSTHDR(&m);
  629. while (cmsg != NULL) {
  630. if ((cmsg->cmsg_level == IPPROTO_IP) &&
  631. (cmsg->cmsg_type == IP_PKTINFO)) {
  632. pktinfo = (struct in_pktinfo*)CMSG_DATA(cmsg);
  633. ifindex = pktinfo->ipi_ifindex;
  634. to_addr = pktinfo->ipi_addr;
  635. // This field is useful, when we are bound to unicast
  636. // address e.g. 192.0.2.1 and the packet was sent to
  637. // broadcast. This will return broadcast address, not
  638. // the address we are bound to.
  639. // IOAddress tmp(htonl(pktinfo->ipi_spec_dst.s_addr));
  640. // cout << "The other addr is: " << tmp.toText() << endl;
  641. // Perhaps we should uncomment this:
  642. // to_addr = pktinfo->ipi_spec_dst;
  643. found_pktinfo = 1;
  644. }
  645. cmsg = CMSG_NXTHDR(&m, cmsg);
  646. }
  647. if (!found_pktinfo) {
  648. cout << "Unable to find pktinfo" << endl;
  649. delete buf;
  650. return (boost::shared_ptr<Pkt4>()); // NULL
  651. }
  652. #endif
  653. IOAddress to(htonl(to_addr.s_addr));
  654. IOAddress from(htonl(from_addr.sin_addr.s_addr));
  655. uint16_t from_port = htons(from_addr.sin_port);
  656. cout << "Received " << result << " bytes from " << from.toText()
  657. << "/port=" << from_port
  658. << " sent to " << to.toText() << " over interface "
  659. << iface->getFullName() << endl;
  660. // we have all data let's create Pkt4 object
  661. pkt = boost::shared_ptr<Pkt4>(new Pkt4(buf, result));
  662. pkt->setIface(iface->getName());
  663. pkt->setIndex(iface->getIndex());
  664. pkt->setLocalAddr(to);
  665. pkt->setRemoteAddr(from);
  666. pkt->setRemotePort(from_port);
  667. pkt->setLocalPort(candidate->port_);
  668. return (pkt);
  669. }
  670. boost::shared_ptr<Pkt6>
  671. IfaceMgr::receive6() {
  672. struct msghdr m;
  673. struct iovec v;
  674. int result;
  675. struct cmsghdr* cmsg;
  676. struct in6_pktinfo* pktinfo;
  677. struct sockaddr_in6 from;
  678. struct in6_addr to_addr;
  679. boost::shared_ptr<Pkt6> pkt;
  680. char addr_str[INET6_ADDRSTRLEN];
  681. try {
  682. // RFC3315 states that server responses may be
  683. // fragmented if they are over MTU. There is no
  684. // text whether client's packets may be larger
  685. // than 1500. Nevertheless to be on the safe side
  686. // we use larger buffer. This buffer limit is checked
  687. // during reception (see iov_len below), so we are
  688. // safe
  689. pkt = boost::shared_ptr<Pkt6>(new Pkt6(65536));
  690. } catch (const std::exception& ex) {
  691. cout << "Failed to create new packet." << endl;
  692. return (boost::shared_ptr<Pkt6>()); // NULL
  693. }
  694. memset(&control_buf_[0], 0, control_buf_len_);
  695. memset(&from, 0, sizeof(from));
  696. memset(&to_addr, 0, sizeof(to_addr));
  697. /*
  698. * Initialize our message header structure.
  699. */
  700. memset(&m, 0, sizeof(m));
  701. /*
  702. * Point so we can get the from address.
  703. */
  704. m.msg_name = &from;
  705. m.msg_namelen = sizeof(from);
  706. /*
  707. * Set the data buffer we're receiving. (Using this wacky
  708. * "scatter-gather" stuff... but we that doesn't really make
  709. * sense for us, so we use a single vector entry.)
  710. */
  711. v.iov_base = (void*)&pkt->data_[0];
  712. v.iov_len = pkt->data_len_;
  713. m.msg_iov = &v;
  714. m.msg_iovlen = 1;
  715. /*
  716. * Getting the interface is a bit more involved.
  717. *
  718. * We set up some space for a "control message". We have
  719. * previously asked the kernel to give us packet
  720. * information (when we initialized the interface), so we
  721. * should get the destination address from that.
  722. */
  723. m.msg_control = &control_buf_[0];
  724. m.msg_controllen = control_buf_len_;
  725. /// TODO: Need to move to select() and pool over
  726. /// all available sockets. For now, we just take the
  727. /// first interface and use first socket from it.
  728. IfaceCollection::const_iterator iface = ifaces_.begin();
  729. if (iface == ifaces_.end()) {
  730. isc_throw(Unexpected, "No interfaces detected. Can't receive anything.");
  731. }
  732. SocketCollection::const_iterator s = iface->sockets_.begin();
  733. const SocketInfo* candidate = 0;
  734. while (s != iface->sockets_.end()) {
  735. if (s->addr_.getFamily() != AF_INET6) {
  736. ++s;
  737. continue;
  738. }
  739. if (s->addr_.getAddress().to_v6().is_multicast()) {
  740. candidate = &(*s);
  741. break;
  742. }
  743. if (!candidate) {
  744. candidate = &(*s); // it's not multicast, but it's better than nothing
  745. }
  746. ++s;
  747. }
  748. if (!candidate) {
  749. isc_throw(Unexpected, "Interface " << iface->getFullName()
  750. << " does not have any sockets open.");
  751. }
  752. cout << "Trying to receive over UDP6 socket " << candidate->sockfd_ << " bound to "
  753. << candidate->addr_.toText() << "/port=" << candidate->port_ << " on "
  754. << iface->getFullName() << endl;
  755. result = recvmsg(candidate->sockfd_, &m, 0);
  756. if (result >= 0) {
  757. /*
  758. * If we did read successfully, then we need to loop
  759. * through the control messages we received and
  760. * find the one with our destination address.
  761. *
  762. * We also keep a flag to see if we found it. If we
  763. * didn't, then we consider this to be an error.
  764. */
  765. int found_pktinfo = 0;
  766. cmsg = CMSG_FIRSTHDR(&m);
  767. while (cmsg != NULL) {
  768. if ((cmsg->cmsg_level == IPPROTO_IPV6) &&
  769. (cmsg->cmsg_type == IPV6_PKTINFO)) {
  770. pktinfo = (struct in6_pktinfo*)CMSG_DATA(cmsg);
  771. to_addr = pktinfo->ipi6_addr;
  772. pkt->ifindex_ = pktinfo->ipi6_ifindex;
  773. found_pktinfo = 1;
  774. }
  775. cmsg = CMSG_NXTHDR(&m, cmsg);
  776. }
  777. if (!found_pktinfo) {
  778. cout << "Unable to find pktinfo" << endl;
  779. return (boost::shared_ptr<Pkt6>()); // NULL
  780. }
  781. } else {
  782. cout << "Failed to receive data." << endl;
  783. return (boost::shared_ptr<Pkt6>()); // NULL
  784. }
  785. // That's ugly.
  786. // TODO add IOAddress constructor that will take struct in6_addr*
  787. // TODO: there's from_bytes() method added in IOAddress. Use it!
  788. inet_ntop(AF_INET6, &to_addr, addr_str,INET6_ADDRSTRLEN);
  789. pkt->local_addr_ = IOAddress(string(addr_str));
  790. // TODO: there's from_bytes() method added in IOAddress. Use it!
  791. inet_ntop(AF_INET6, &from.sin6_addr, addr_str, INET6_ADDRSTRLEN);
  792. pkt->remote_addr_ = IOAddress(string(addr_str));
  793. pkt->remote_port_ = ntohs(from.sin6_port);
  794. Iface* received = getIface(pkt->ifindex_);
  795. if (received) {
  796. pkt->iface_ = received->getName();
  797. } else {
  798. cout << "Received packet over unknown interface (ifindex="
  799. << pkt->ifindex_ << ")." << endl;
  800. return (boost::shared_ptr<Pkt6>()); // NULL
  801. }
  802. pkt->data_len_ = result;
  803. // TODO Move this to LOG_DEBUG
  804. cout << "Received " << pkt->data_len_ << " bytes over "
  805. << pkt->iface_ << "/" << pkt->ifindex_ << " interface: "
  806. << " src=" << pkt->remote_addr_.toText()
  807. << ", dst=" << pkt->local_addr_.toText()
  808. << endl;
  809. return (pkt);
  810. }
  811. uint16_t
  812. IfaceMgr::getSocket(isc::dhcp::Pkt6 const& pkt) {
  813. Iface* iface = getIface(pkt.iface_);
  814. if (!iface) {
  815. isc_throw(BadValue, "Tried to find socket for non-existent interface "
  816. << pkt.iface_);
  817. }
  818. SocketCollection::const_iterator s;
  819. for (s = iface->sockets_.begin(); s != iface->sockets_.end(); ++s) {
  820. if (s->family_ != AF_INET6) {
  821. // don't use IPv4 sockets
  822. continue;
  823. }
  824. if (s->addr_.getAddress().to_v6().is_multicast()) {
  825. // don't use IPv6 sockets bound to multicast address
  826. continue;
  827. }
  828. /// TODO: Add more checks here later. If remote address is
  829. /// not link-local, we can't use link local bound socket
  830. /// to send data.
  831. return (s->sockfd_);
  832. }
  833. isc_throw(Unexpected, "Interface " << iface->getFullName()
  834. << " does not have any suitable IPv6 sockets open.");
  835. }
  836. uint16_t
  837. IfaceMgr::getSocket(isc::dhcp::Pkt4 const& pkt) {
  838. Iface* iface = getIface(pkt.getIface());
  839. if (!iface) {
  840. isc_throw(BadValue, "Tried to find socket for non-existent interface "
  841. << pkt.getIface());
  842. }
  843. SocketCollection::const_iterator s;
  844. for (s = iface->sockets_.begin(); s != iface->sockets_.end(); ++s) {
  845. if (s->family_ != AF_INET) {
  846. // don't use IPv4 sockets
  847. continue;
  848. }
  849. /// TODO: Add more checks here later. If remote address is
  850. /// not link-local, we can't use link local bound socket
  851. /// to send data.
  852. return (s->sockfd_);
  853. }
  854. isc_throw(Unexpected, "Interface " << iface->getFullName()
  855. << " does not have any suitable IPv4 sockets open.");
  856. }
  857. }