iface_mgr.cc 32 KB

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