iface_mgr.cc 32 KB

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