iface_mgr_unittest.cc 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. // Copyright (C) 2011-2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <iostream>
  16. #include <fstream>
  17. #include <sstream>
  18. #include <unistd.h>
  19. #include <arpa/inet.h>
  20. #include <boost/scoped_ptr.hpp>
  21. #include <gtest/gtest.h>
  22. #include <asiolink/io_address.h>
  23. #include <dhcp/pkt6.h>
  24. #include <dhcp/iface_mgr.h>
  25. #include <dhcp/dhcp4.h>
  26. using namespace std;
  27. using namespace isc;
  28. using namespace isc::asiolink;
  29. using namespace isc::dhcp;
  30. namespace {
  31. // Name of loopback interface detection
  32. const size_t BUF_SIZE = 32;
  33. char LOOPBACK[BUF_SIZE] = "lo";
  34. // Ports used during testing
  35. const uint16_t PORT1 = 10547; // V6 socket
  36. const uint16_t PORT2 = 10548; // V4 socket
  37. // On some systems measured duration of receive6() and
  38. // receive4() appears to be shorter than select() timeout.
  39. // called by these functions. This may be the case
  40. // if different ime resolutions are used by these functions.
  41. // For such cases we set the tolerance of 0.01s.
  42. const uint32_t TIMEOUT_TOLERANCE = 10000;
  43. class NakedIfaceMgr: public IfaceMgr {
  44. // "naked" Interface Manager, exposes internal fields
  45. public:
  46. NakedIfaceMgr() { }
  47. IfaceCollection & getIfacesLst() { return ifaces_; }
  48. };
  49. // dummy class for now, but this will be expanded when needed
  50. class IfaceMgrTest : public ::testing::Test {
  51. public:
  52. // these are empty for now, but let's keep them around
  53. IfaceMgrTest() {
  54. }
  55. ~IfaceMgrTest() {
  56. }
  57. };
  58. // We need some known interface to work reliably. Loopback interface
  59. // is named lo on Linux and lo0 on BSD boxes. We need to find out
  60. // which is available. This is not a real test, but rather a workaround
  61. // that will go away when interface detection is implemented.
  62. // NOTE: At this stage of development, write access to current directory
  63. // during running tests is required.
  64. TEST_F(IfaceMgrTest, loDetect) {
  65. // poor man's interface detection
  66. // it will go away as soon as proper interface detection
  67. // is implemented
  68. if (if_nametoindex("lo") > 0) {
  69. snprintf(LOOPBACK, BUF_SIZE - 1, "lo");
  70. } else if (if_nametoindex("lo0") > 0) {
  71. snprintf(LOOPBACK, BUF_SIZE - 1, "lo0");
  72. } else {
  73. cout << "Failed to detect loopback interface. Neither "
  74. << "lo nor lo0 worked. I give up." << endl;
  75. FAIL();
  76. }
  77. }
  78. // Uncomment this test to create packet writer. It will
  79. // write incoming DHCPv6 packets as C arrays. That is useful
  80. // for generating test sequences based on actual traffic
  81. //
  82. // TODO: this potentially should be moved to a separate tool
  83. //
  84. #if 0
  85. TEST_F(IfaceMgrTest, dhcp6Sniffer) {
  86. // testing socket operation in a portable way is tricky
  87. // without interface detection implemented
  88. unlink("interfaces.txt");
  89. ofstream interfaces("interfaces.txt", ios::ate);
  90. interfaces << "eth0 fe80::21e:8cff:fe9b:7349";
  91. interfaces.close();
  92. NakedIfaceMgr* ifacemgr = new NakedIfaceMgr();
  93. Pkt6* pkt = NULL;
  94. int cnt = 0;
  95. cout << "---8X-----------------------------------------" << endl;
  96. while (true) {
  97. pkt = ifacemgr->receive();
  98. cout << "// this code is autogenerated. Do NOT edit." << endl;
  99. cout << "// Received " << pkt->data_len_ << " bytes packet:" << endl;
  100. cout << "Pkt6 *capture" << cnt++ << "() {" << endl;
  101. cout << " Pkt6* pkt;" << endl;
  102. cout << " pkt = new Pkt6(" << pkt->data_len_ << ");" << endl;
  103. cout << " pkt->remote_port_ = " << pkt-> remote_port_ << ";" << endl;
  104. cout << " pkt->remote_addr_ = IOAddress(\""
  105. << pkt->remote_addr_.toText() << "\");" << endl;
  106. cout << " pkt->local_port_ = " << pkt-> local_port_ << ";" << endl;
  107. cout << " pkt->local_addr_ = IOAddress(\""
  108. << pkt->local_addr_.toText() << "\");" << endl;
  109. cout << " pkt->ifindex_ = " << pkt->ifindex_ << ";" << endl;
  110. cout << " pkt->iface_ = \"" << pkt->iface_ << "\";" << endl;
  111. // TODO it is better to declare statically initialize the array
  112. // and then memcpy it to packet.
  113. for (int i=0; i< pkt->data_len_; i++) {
  114. cout << " pkt->data_[" << i << "]="
  115. << (int)(unsigned char)pkt->data_[i] << "; ";
  116. if (!(i%4))
  117. cout << endl;
  118. }
  119. cout << endl;
  120. cout << " return (pkt);" << endl;
  121. cout << "}" << endl << endl;
  122. delete pkt;
  123. }
  124. cout << "---8X-----------------------------------------" << endl;
  125. // never happens. Infinite loop is infinite
  126. delete pkt;
  127. delete ifacemgr;
  128. }
  129. #endif
  130. TEST_F(IfaceMgrTest, basic) {
  131. // checks that IfaceManager can be instantiated
  132. IfaceMgr & ifacemgr = IfaceMgr::instance();
  133. ASSERT_TRUE(&ifacemgr != 0);
  134. }
  135. TEST_F(IfaceMgrTest, ifaceClass) {
  136. // basic tests for Iface inner class
  137. IfaceMgr::Iface* iface = new IfaceMgr::Iface("eth5", 7);
  138. EXPECT_STREQ("eth5/7", iface->getFullName().c_str());
  139. delete iface;
  140. }
  141. // TODO: Implement getPlainMac() test as soon as interface detection
  142. // is implemented.
  143. TEST_F(IfaceMgrTest, getIface) {
  144. cout << "Interface checks. Please ignore socket binding errors." << endl;
  145. NakedIfaceMgr* ifacemgr = new NakedIfaceMgr();
  146. // interface name, ifindex
  147. IfaceMgr::Iface iface1("lo1", 100);
  148. IfaceMgr::Iface iface2("eth9", 101);
  149. IfaceMgr::Iface iface3("en3", 102);
  150. IfaceMgr::Iface iface4("e1000g4", 103);
  151. cout << "This test assumes that there are less than 100 network interfaces"
  152. << " in the tested system and there are no lo1, eth9, en3, e1000g4"
  153. << " or wifi15 interfaces present." << endl;
  154. // note: real interfaces may be detected as well
  155. ifacemgr->getIfacesLst().push_back(iface1);
  156. ifacemgr->getIfacesLst().push_back(iface2);
  157. ifacemgr->getIfacesLst().push_back(iface3);
  158. ifacemgr->getIfacesLst().push_back(iface4);
  159. cout << "There are " << ifacemgr->getIfacesLst().size()
  160. << " interfaces." << endl;
  161. for (IfaceMgr::IfaceCollection::iterator iface=ifacemgr->getIfacesLst().begin();
  162. iface != ifacemgr->getIfacesLst().end();
  163. ++iface) {
  164. cout << " " << iface->getFullName() << endl;
  165. }
  166. // check that interface can be retrieved by ifindex
  167. IfaceMgr::Iface* tmp = ifacemgr->getIface(102);
  168. ASSERT_TRUE(tmp != NULL);
  169. EXPECT_EQ("en3", tmp->getName());
  170. EXPECT_EQ(102, tmp->getIndex());
  171. // check that interface can be retrieved by name
  172. tmp = ifacemgr->getIface("lo1");
  173. ASSERT_TRUE(tmp != NULL);
  174. EXPECT_EQ("lo1", tmp->getName());
  175. EXPECT_EQ(100, tmp->getIndex());
  176. // check that non-existing interfaces are not returned
  177. EXPECT_EQ(static_cast<void*>(NULL), ifacemgr->getIface("wifi15") );
  178. delete ifacemgr;
  179. }
  180. TEST_F(IfaceMgrTest, receiveTimeout6) {
  181. using namespace boost::posix_time;
  182. std::cout << "Testing DHCPv6 packet reception timeouts."
  183. << " Test will block for a few seconds when waiting"
  184. << " for timeout to occur." << std::endl;
  185. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  186. // Open socket on the lo interface.
  187. IOAddress loAddr("::1");
  188. int socket1 = 0;
  189. ASSERT_NO_THROW(
  190. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, 10547)
  191. );
  192. // Socket is open if its descriptor is greater than zero.
  193. ASSERT_GT(socket1, 0);
  194. // Remember when we call receive6().
  195. ptime start_time = microsec_clock::universal_time();
  196. // Call receive with timeout of 1s + 400000us = 1.4s.
  197. Pkt6Ptr pkt;
  198. ASSERT_NO_THROW(pkt = ifacemgr->receive6(1, 400000));
  199. // Remember when call to receive6() ended.
  200. ptime stop_time = microsec_clock::universal_time();
  201. // We did not send a packet to lo interface so we expect that
  202. // nothing has been received and timeout has been reached.
  203. ASSERT_FALSE(pkt);
  204. // Calculate duration of call to receive6().
  205. time_duration duration = stop_time - start_time;
  206. // We stop the clock when the call completes so it does not
  207. // precisely reflect the receive timeout. However the
  208. // uncertainity should be low enough to expect that measured
  209. // value is in the range <1.4s; 1.7s>.
  210. EXPECT_GE(duration.total_microseconds(),
  211. 1400000 - TIMEOUT_TOLERANCE);
  212. EXPECT_LE(duration.total_microseconds(), 1700000);
  213. // Test timeout shorter than 1s.
  214. start_time = microsec_clock::universal_time();
  215. ASSERT_NO_THROW(pkt = ifacemgr->receive6(0, 500000));
  216. stop_time = microsec_clock::universal_time();
  217. ASSERT_FALSE(pkt);
  218. duration = stop_time - start_time;
  219. // Check if measured duration is within <0.5s; 0.8s>.
  220. EXPECT_GE(duration.total_microseconds(),
  221. 500000 - TIMEOUT_TOLERANCE);
  222. EXPECT_LE(duration.total_microseconds(), 800000);
  223. // Test with invalid fractional timeout values.
  224. EXPECT_THROW(ifacemgr->receive6(0, 1000000), isc::BadValue);
  225. EXPECT_THROW(ifacemgr->receive6(1, 1000010), isc::BadValue);
  226. }
  227. TEST_F(IfaceMgrTest, receiveTimeout4) {
  228. using namespace boost::posix_time;
  229. std::cout << "Testing DHCPv6 packet reception timeouts."
  230. << " Test will block for a few seconds when waiting"
  231. << " for timeout to occur." << std::endl;
  232. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  233. // Open socket on the lo interface.
  234. IOAddress loAddr("127.0.0.1");
  235. int socket1 = 0;
  236. ASSERT_NO_THROW(
  237. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, 10067)
  238. );
  239. // Socket is open if its descriptor is greater than zero.
  240. ASSERT_GT(socket1, 0);
  241. Pkt4Ptr pkt;
  242. // Remember when we call receive4().
  243. ptime start_time = microsec_clock::universal_time();
  244. // Call receive with timeout of 2s + 300000us = 2.3s.
  245. ASSERT_NO_THROW(pkt = ifacemgr->receive4(2, 300000));
  246. // Remember when call to receive4() ended.
  247. ptime stop_time = microsec_clock::universal_time();
  248. // We did not send a packet to lo interface so we expect that
  249. // nothing has been received and timeout has been reached.
  250. ASSERT_FALSE(pkt);
  251. // Calculate duration of call to receive4().
  252. time_duration duration = stop_time - start_time;
  253. // We stop the clock when the call completes so it does not
  254. // precisely reflect the receive timeout. However the
  255. // uncertainity should be low enough to expect that measured
  256. // value is in the range <2.3s; 2.6s>.
  257. EXPECT_GE(duration.total_microseconds(),
  258. 2300000 - TIMEOUT_TOLERANCE);
  259. EXPECT_LE(duration.total_microseconds(), 2600000);
  260. // Test timeout shorter than 1s.
  261. start_time = microsec_clock::universal_time();
  262. ASSERT_NO_THROW(pkt = ifacemgr->receive4(0, 400000));
  263. stop_time = microsec_clock::universal_time();
  264. ASSERT_FALSE(pkt);
  265. duration = stop_time - start_time;
  266. // Check if measured duration is within <0.4s; 0.7s>.
  267. EXPECT_GE(duration.total_microseconds(),
  268. 400000 - TIMEOUT_TOLERANCE);
  269. EXPECT_LE(duration.total_microseconds(), 700000);
  270. // Test with invalid fractional timeout values.
  271. EXPECT_THROW(ifacemgr->receive6(0, 1000000), isc::BadValue);
  272. EXPECT_THROW(ifacemgr->receive6(2, 1000005), isc::BadValue);
  273. }
  274. TEST_F(IfaceMgrTest, multipleSockets) {
  275. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  276. // container for initialized socket descriptors
  277. std::list<uint16_t> init_sockets;
  278. // create socket #1
  279. int socket1 = 0;
  280. ASSERT_NO_THROW(
  281. socket1 = ifacemgr->openSocketFromIface(LOOPBACK, PORT1, AF_INET);
  282. );
  283. ASSERT_GT(socket1, 0);
  284. init_sockets.push_back(socket1);
  285. // create socket #2
  286. IOAddress loAddr("127.0.0.1");
  287. int socket2 = 0;
  288. ASSERT_NO_THROW(
  289. socket2 = ifacemgr->openSocketFromRemoteAddress(loAddr, PORT2);
  290. );
  291. ASSERT_GT(socket2, 0);
  292. init_sockets.push_back(socket2);
  293. // Get loopback interface. If we don't find one we are unable to run
  294. // this test but we don't want to fail.
  295. IfaceMgr::Iface* iface_ptr = ifacemgr->getIface(LOOPBACK);
  296. if (iface_ptr == NULL) {
  297. cout << "Local loopback interface not found. Skipping test. " << endl;
  298. return;
  299. }
  300. // Once sockets have been sucessfully opened, they are supposed to
  301. // be on the list. Here we start to test if all expected sockets
  302. // are on the list and no other (unexpected) socket is there.
  303. IfaceMgr::SocketCollection sockets = iface_ptr->getSockets();
  304. int matched_sockets = 0;
  305. for (std::list<uint16_t>::iterator init_sockets_it =
  306. init_sockets.begin();
  307. init_sockets_it != init_sockets.end(); ++init_sockets_it) {
  308. // Set socket descriptors non blocking in order to be able
  309. // to call recv() on them without hang.
  310. int flags = fcntl(*init_sockets_it, F_GETFL, 0);
  311. ASSERT_GE(flags, 0);
  312. ASSERT_GE(fcntl(*init_sockets_it, F_SETFL, flags | O_NONBLOCK), 0);
  313. // recv() is expected to result in EWOULDBLOCK error on non-blocking
  314. // socket in case socket is valid but simply no data are coming in.
  315. char buf;
  316. recv(*init_sockets_it, &buf, 1, MSG_PEEK);
  317. EXPECT_EQ(EWOULDBLOCK, errno);
  318. // Apart from the ability to use the socket we want to make
  319. // sure that socket on the list is the one that we created.
  320. for (IfaceMgr::SocketCollection::const_iterator socket_it =
  321. sockets.begin(); socket_it != sockets.end(); ++socket_it) {
  322. if (*init_sockets_it == socket_it->sockfd_) {
  323. // This socket is the one that we created.
  324. ++matched_sockets;
  325. break;
  326. }
  327. }
  328. }
  329. // all created sockets have been matched if this condition works.
  330. EXPECT_EQ(sockets.size(), matched_sockets);
  331. // closeSockets() is the other function that we want to test. It
  332. // is supposed to close all sockets so as we will not be able to use
  333. // them anymore communication.
  334. ifacemgr->closeSockets();
  335. // closed sockets are supposed to be removed from the list
  336. sockets = iface_ptr->getSockets();
  337. ASSERT_EQ(0, sockets.size());
  338. // We are still in posession of socket descriptors that we created
  339. // on the beginning of this test. We can use them to check whether
  340. // closeSockets() only removed them from the list or they have been
  341. // really closed.
  342. for (std::list<uint16_t>::const_iterator init_sockets_it =
  343. init_sockets.begin();
  344. init_sockets_it != init_sockets.end(); ++init_sockets_it) {
  345. // recv() must result in error when using invalid socket.
  346. char buf;
  347. recv(*init_sockets_it, &buf, 1, MSG_PEEK);
  348. // EWOULDBLOCK would mean that socket is valid/open but
  349. // simply no data is received so we have to check for
  350. // other errors.
  351. EXPECT_NE(EWOULDBLOCK, errno);
  352. }
  353. }
  354. TEST_F(IfaceMgrTest, sockets6) {
  355. // testing socket operation in a portable way is tricky
  356. // without interface detection implemented
  357. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  358. IOAddress loAddr("::1");
  359. Pkt6 pkt6(DHCPV6_SOLICIT, 123);
  360. pkt6.setIface(LOOPBACK);
  361. // bind multicast socket to port 10547
  362. int socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, 10547);
  363. EXPECT_GT(socket1, 0); // socket > 0
  364. EXPECT_EQ(socket1, ifacemgr->getSocket(pkt6));
  365. // bind unicast socket to port 10548
  366. int socket2 = ifacemgr->openSocket(LOOPBACK, loAddr, 10548);
  367. EXPECT_GT(socket2, 0);
  368. // removed code for binding socket twice to the same address/port
  369. // as it caused problems on some platforms (e.g. Mac OS X)
  370. // Close sockets here because the following tests will want to
  371. // open sockets on the same ports.
  372. ifacemgr->closeSockets();
  373. // Use address that is not assigned to LOOPBACK iface.
  374. IOAddress invalidAddr("::2");
  375. EXPECT_THROW(
  376. ifacemgr->openSocket(LOOPBACK, invalidAddr, 10547),
  377. SocketConfigError
  378. );
  379. // Use non-existing interface name.
  380. EXPECT_THROW(
  381. ifacemgr->openSocket("non_existing_interface", loAddr, 10548),
  382. BadValue
  383. );
  384. // Do not call closeSockets() because it is called by IfaceMgr's
  385. // virtual destructor.
  386. }
  387. TEST_F(IfaceMgrTest, socketsFromIface) {
  388. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  389. // Open v6 socket on loopback interface and bind to port
  390. int socket1 = 0;
  391. EXPECT_NO_THROW(
  392. socket1 = ifacemgr->openSocketFromIface(LOOPBACK, PORT1, AF_INET6);
  393. );
  394. // Socket descriptor must be positive integer
  395. EXPECT_GT(socket1, 0);
  396. close(socket1);
  397. // Open v4 socket on loopback interface and bind to different port
  398. int socket2 = 0;
  399. EXPECT_NO_THROW(
  400. socket2 = ifacemgr->openSocketFromIface(LOOPBACK, PORT2, AF_INET);
  401. );
  402. // socket descriptor must be positive integer
  403. EXPECT_GT(socket2, 0);
  404. close(socket2);
  405. // Close sockets here because the following tests will want to
  406. // open sockets on the same ports.
  407. ifacemgr->closeSockets();
  408. // Use invalid interface name.
  409. EXPECT_THROW(
  410. ifacemgr->openSocketFromIface("non_existing_interface", PORT1, AF_INET),
  411. BadValue
  412. );
  413. // Do not call closeSockets() because it is called by IfaceMgr's
  414. // virtual destructor.
  415. }
  416. TEST_F(IfaceMgrTest, socketsFromAddress) {
  417. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  418. // Open v6 socket on loopback interface and bind to port
  419. int socket1 = 0;
  420. IOAddress loAddr6("::1");
  421. EXPECT_NO_THROW(
  422. socket1 = ifacemgr->openSocketFromAddress(loAddr6, PORT1);
  423. );
  424. // socket descriptor must be positive integer
  425. EXPECT_GT(socket1, 0);
  426. // Open v4 socket on loopback interface and bind to different port
  427. int socket2 = 0;
  428. IOAddress loAddr("127.0.0.1");
  429. EXPECT_NO_THROW(
  430. socket2 = ifacemgr->openSocketFromAddress(loAddr, PORT2);
  431. );
  432. // socket descriptor must be positive integer
  433. EXPECT_GT(socket2, 0);
  434. // Close sockets here because the following tests will want to
  435. // open sockets on the same ports.
  436. ifacemgr->closeSockets();
  437. // Use non-existing address.
  438. IOAddress invalidAddr("1.2.3.4");
  439. EXPECT_THROW(
  440. ifacemgr->openSocketFromAddress(invalidAddr, PORT1), BadValue
  441. );
  442. // Do not call closeSockets() because it is called by IfaceMgr's
  443. // virtual destructor.
  444. }
  445. TEST_F(IfaceMgrTest, socketsFromRemoteAddress) {
  446. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  447. // Open v6 socket to connect to remote address.
  448. // Loopback address is the only one that we know
  449. // so let's treat it as remote address.
  450. int socket1 = 0;
  451. IOAddress loAddr6("::1");
  452. EXPECT_NO_THROW(
  453. socket1 = ifacemgr->openSocketFromRemoteAddress(loAddr6, PORT1);
  454. );
  455. EXPECT_GT(socket1, 0);
  456. // Open v4 socket to connect to remote address.
  457. int socket2 = 0;
  458. IOAddress loAddr("127.0.0.1");
  459. EXPECT_NO_THROW(
  460. socket2 = ifacemgr->openSocketFromRemoteAddress(loAddr, PORT2);
  461. );
  462. EXPECT_GT(socket2, 0);
  463. // Close sockets here because the following tests will want to
  464. // open sockets on the same ports.
  465. ifacemgr->closeSockets();
  466. // The following test is currently disabled for OSes other than
  467. // Linux because interface detection is not implemented on them.
  468. // @todo enable this test for all OSes once interface detection
  469. // is implemented.
  470. #if defined(OS_LINUX)
  471. // Open v4 socket to connect to broadcast address.
  472. int socket3 = 0;
  473. IOAddress bcastAddr("255.255.255.255");
  474. EXPECT_NO_THROW(
  475. socket3 = ifacemgr->openSocketFromRemoteAddress(bcastAddr, PORT2);
  476. );
  477. EXPECT_GT(socket3, 0);
  478. #endif
  479. // Do not call closeSockets() because it is called by IfaceMgr's
  480. // virtual destructor.
  481. }
  482. // TODO: disabled due to other naming on various systems
  483. // (lo in Linux, lo0 in BSD systems)
  484. TEST_F(IfaceMgrTest, DISABLED_sockets6Mcast) {
  485. // testing socket operation in a portable way is tricky
  486. // without interface detection implemented
  487. NakedIfaceMgr* ifacemgr = new NakedIfaceMgr();
  488. IOAddress loAddr("::1");
  489. IOAddress mcastAddr("ff02::1:2");
  490. // bind multicast socket to port 10547
  491. int socket1 = ifacemgr->openSocket(LOOPBACK, mcastAddr, 10547);
  492. EXPECT_GT(socket1, 0); // socket > 0
  493. // expect success. This address/port is already bound, but
  494. // we are using SO_REUSEADDR, so we can bind it twice
  495. int socket2 = ifacemgr->openSocket(LOOPBACK, mcastAddr, 10547);
  496. EXPECT_GT(socket2, 0);
  497. // there's no good way to test negative case here.
  498. // we would need non-multicast interface. We will be able
  499. // to iterate thru available interfaces and check if there
  500. // are interfaces without multicast-capable flag.
  501. close(socket1);
  502. close(socket2);
  503. delete ifacemgr;
  504. }
  505. TEST_F(IfaceMgrTest, sendReceive6) {
  506. // testing socket operation in a portable way is tricky
  507. // without interface detection implemented
  508. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  509. // let's assume that every supported OS have lo interface
  510. IOAddress loAddr("::1");
  511. int socket1 = 0, socket2 = 0;
  512. EXPECT_NO_THROW(
  513. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, 10547);
  514. socket2 = ifacemgr->openSocket(LOOPBACK, loAddr, 10546);
  515. );
  516. EXPECT_GT(socket1, 0);
  517. EXPECT_GT(socket2, 0);
  518. // prepare dummy payload
  519. uint8_t data[128];
  520. for (int i = 0; i < 128; i++) {
  521. data[i] = i;
  522. }
  523. Pkt6Ptr sendPkt = Pkt6Ptr(new Pkt6(data, 128));
  524. sendPkt->repack();
  525. sendPkt->setRemotePort(10547);
  526. sendPkt->setRemoteAddr(IOAddress("::1"));
  527. sendPkt->setIndex(1);
  528. sendPkt->setIface(LOOPBACK);
  529. Pkt6Ptr rcvPkt;
  530. EXPECT_EQ(true, ifacemgr->send(sendPkt));
  531. rcvPkt = ifacemgr->receive6(10);
  532. ASSERT_TRUE(rcvPkt); // received our own packet
  533. // let's check that we received what was sent
  534. ASSERT_EQ(sendPkt->getData().size(), rcvPkt->getData().size());
  535. EXPECT_EQ(0, memcmp(&sendPkt->getData()[0], &rcvPkt->getData()[0],
  536. rcvPkt->getData().size()));
  537. EXPECT_EQ(sendPkt->getRemoteAddr().toText(), rcvPkt->getRemoteAddr().toText());
  538. // since we opened 2 sockets on the same interface and none of them is multicast,
  539. // none is preferred over the other for sending data, so we really should not
  540. // assume the one or the other will always be choosen for sending data. Therefore
  541. // we should accept both values as source ports.
  542. EXPECT_TRUE((rcvPkt->getRemotePort() == 10546) || (rcvPkt->getRemotePort() == 10547));
  543. // try to send/receive data over the closed socket. Closed socket's descriptor is
  544. // still being hold by IfaceMgr which will try to use it to receive data.
  545. close(socket1);
  546. EXPECT_THROW(ifacemgr->receive6(10), SocketReadError);
  547. EXPECT_THROW(ifacemgr->send(sendPkt), SocketWriteError);
  548. }
  549. TEST_F(IfaceMgrTest, sendReceive4) {
  550. // testing socket operation in a portable way is tricky
  551. // without interface detection implemented
  552. boost::scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  553. // let's assume that every supported OS have lo interface
  554. IOAddress loAddr("127.0.0.1");
  555. int socket1 = 0, socket2 = 0;
  556. EXPECT_NO_THROW(
  557. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, DHCP4_SERVER_PORT + 10000);
  558. socket2 = ifacemgr->openSocket(LOOPBACK, loAddr, DHCP4_SERVER_PORT + 10000 + 1);
  559. );
  560. EXPECT_GE(socket1, 0);
  561. EXPECT_GE(socket2, 0);
  562. boost::shared_ptr<Pkt4> sendPkt(new Pkt4(DHCPDISCOVER, 1234) );
  563. sendPkt->setLocalAddr(IOAddress("127.0.0.1"));
  564. sendPkt->setLocalPort(DHCP4_SERVER_PORT + 10000 + 1);
  565. sendPkt->setRemotePort(DHCP4_SERVER_PORT + 10000);
  566. sendPkt->setRemoteAddr(IOAddress("127.0.0.1"));
  567. sendPkt->setIndex(1);
  568. sendPkt->setIface(string(LOOPBACK));
  569. sendPkt->setHops(6);
  570. sendPkt->setSecs(42);
  571. sendPkt->setCiaddr(IOAddress("192.0.2.1"));
  572. sendPkt->setSiaddr(IOAddress("192.0.2.2"));
  573. sendPkt->setYiaddr(IOAddress("192.0.2.3"));
  574. sendPkt->setGiaddr(IOAddress("192.0.2.4"));
  575. // unpack() now checks if mandatory DHCP_MESSAGE_TYPE is present
  576. boost::shared_ptr<Option> msgType(new Option(Option::V4,
  577. static_cast<uint16_t>(DHO_DHCP_MESSAGE_TYPE)));
  578. msgType->setUint8(static_cast<uint8_t>(DHCPDISCOVER));
  579. sendPkt->addOption(msgType);
  580. uint8_t sname[] = "That's just a string that will act as SNAME";
  581. sendPkt->setSname(sname, strlen((const char*)sname));
  582. uint8_t file[] = "/another/string/that/acts/as/a/file_name.txt";
  583. sendPkt->setFile(file, strlen((const char*)file));
  584. ASSERT_NO_THROW(
  585. sendPkt->pack();
  586. );
  587. boost::shared_ptr<Pkt4> rcvPkt;
  588. EXPECT_EQ(true, ifacemgr->send(sendPkt));
  589. ASSERT_NO_THROW(rcvPkt = ifacemgr->receive4(10));
  590. ASSERT_TRUE(rcvPkt); // received our own packet
  591. ASSERT_NO_THROW(
  592. rcvPkt->unpack();
  593. );
  594. // let's check that we received what was sent
  595. EXPECT_EQ(sendPkt->len(), rcvPkt->len());
  596. EXPECT_EQ("127.0.0.1", rcvPkt->getRemoteAddr().toText());
  597. EXPECT_EQ(sendPkt->getRemotePort(), rcvPkt->getLocalPort());
  598. // now let's check content
  599. EXPECT_EQ(sendPkt->getHops(), rcvPkt->getHops());
  600. EXPECT_EQ(sendPkt->getOp(), rcvPkt->getOp());
  601. EXPECT_EQ(sendPkt->getSecs(), rcvPkt->getSecs());
  602. EXPECT_EQ(sendPkt->getFlags(), rcvPkt->getFlags());
  603. EXPECT_EQ(sendPkt->getCiaddr(), rcvPkt->getCiaddr());
  604. EXPECT_EQ(sendPkt->getSiaddr(), rcvPkt->getSiaddr());
  605. EXPECT_EQ(sendPkt->getYiaddr(), rcvPkt->getYiaddr());
  606. EXPECT_EQ(sendPkt->getGiaddr(), rcvPkt->getGiaddr());
  607. EXPECT_EQ(sendPkt->getTransid(), rcvPkt->getTransid());
  608. EXPECT_EQ(sendPkt->getType(), rcvPkt->getType());
  609. EXPECT_TRUE(sendPkt->getSname() == rcvPkt->getSname());
  610. EXPECT_TRUE(sendPkt->getFile() == rcvPkt->getFile());
  611. EXPECT_EQ(sendPkt->getHtype(), rcvPkt->getHtype());
  612. EXPECT_EQ(sendPkt->getHlen(), rcvPkt->getHlen());
  613. // since we opened 2 sockets on the same interface and none of them is multicast,
  614. // none is preferred over the other for sending data, so we really should not
  615. // assume the one or the other will always be choosen for sending data. We should
  616. // skip checking source port of sent address.
  617. // try to receive data over the closed socket. Closed socket's descriptor is
  618. // still being hold by IfaceMgr which will try to use it to receive data.
  619. close(socket1);
  620. EXPECT_THROW(ifacemgr->receive4(10), SocketReadError);
  621. EXPECT_THROW(ifacemgr->send(sendPkt), SocketWriteError);
  622. }
  623. TEST_F(IfaceMgrTest, socket4) {
  624. NakedIfaceMgr* ifacemgr = new NakedIfaceMgr();
  625. // Let's assume that every supported OS have lo interface.
  626. IOAddress loAddr("127.0.0.1");
  627. // Use unprivileged port (it's convenient for running tests as non-root).
  628. int socket1 = 0;
  629. EXPECT_NO_THROW(
  630. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, DHCP4_SERVER_PORT + 10000);
  631. );
  632. EXPECT_GT(socket1, 0);
  633. Pkt4 pkt(DHCPDISCOVER, 1234);
  634. pkt.setIface(LOOPBACK);
  635. // Expect that we get the socket that we just opened.
  636. EXPECT_EQ(socket1, ifacemgr->getSocket(pkt));
  637. close(socket1);
  638. delete ifacemgr;
  639. }
  640. // Test the Iface structure itself
  641. TEST_F(IfaceMgrTest, iface) {
  642. IfaceMgr::Iface* iface = NULL;
  643. EXPECT_NO_THROW(
  644. iface = new IfaceMgr::Iface("eth0",1);
  645. );
  646. EXPECT_EQ("eth0", iface->getName());
  647. EXPECT_EQ(1, iface->getIndex());
  648. EXPECT_EQ("eth0/1", iface->getFullName());
  649. // Let's make a copy of this address collection.
  650. IfaceMgr::AddressCollection addrs = iface->getAddresses();
  651. EXPECT_EQ(0, addrs.size());
  652. IOAddress addr1("192.0.2.6");
  653. iface->addAddress(addr1);
  654. addrs = iface->getAddresses();
  655. ASSERT_EQ(1, addrs.size());
  656. EXPECT_EQ("192.0.2.6", addrs.at(0).toText());
  657. // No such address, should return false.
  658. EXPECT_FALSE(iface->delAddress(IOAddress("192.0.8.9")));
  659. // This address is present, delete it!
  660. EXPECT_TRUE(iface->delAddress(IOAddress("192.0.2.6")));
  661. // Not really necessary, previous reference still points to the same
  662. // collection. Let's do it anyway, as test code may serve as example
  663. // usage code as well.
  664. addrs = iface->getAddresses();
  665. EXPECT_EQ(0, addrs.size());
  666. EXPECT_NO_THROW(
  667. delete iface;
  668. );
  669. }
  670. TEST_F(IfaceMgrTest, iface_methods) {
  671. IfaceMgr::Iface iface("foo", 1234);
  672. iface.setHWType(42);
  673. EXPECT_EQ(42, iface.getHWType());
  674. uint8_t mac[IfaceMgr::MAX_MAC_LEN+10];
  675. for (int i = 0; i < IfaceMgr::MAX_MAC_LEN + 10; i++)
  676. mac[i] = 255 - i;
  677. EXPECT_EQ("foo", iface.getName());
  678. EXPECT_EQ(1234, iface.getIndex());
  679. // MAC is too long. Exception should be thrown and
  680. // MAC length should not be set.
  681. EXPECT_THROW(
  682. iface.setMac(mac, IfaceMgr::MAX_MAC_LEN + 1),
  683. OutOfRange
  684. );
  685. // MAC length should stay not set as excep
  686. EXPECT_EQ(0, iface.getMacLen());
  687. // Setting maximum length MAC should be ok.
  688. iface.setMac(mac, IfaceMgr::MAX_MAC_LEN);
  689. // For some reason constants cannot be used directly in EXPECT_EQ
  690. // as this produces linking error.
  691. size_t len = IfaceMgr::MAX_MAC_LEN;
  692. EXPECT_EQ(len, iface.getMacLen());
  693. EXPECT_EQ(0, memcmp(mac, iface.getMac(), iface.getMacLen()));
  694. }
  695. TEST_F(IfaceMgrTest, socketInfo) {
  696. // check that socketinfo for IPv4 socket is functional
  697. IfaceMgr::SocketInfo sock1(7, IOAddress("192.0.2.56"), DHCP4_SERVER_PORT + 7);
  698. EXPECT_EQ(7, sock1.sockfd_);
  699. EXPECT_EQ("192.0.2.56", sock1.addr_.toText());
  700. EXPECT_EQ(AF_INET, sock1.family_);
  701. EXPECT_EQ(DHCP4_SERVER_PORT + 7, sock1.port_);
  702. // check that socketinfo for IPv6 socket is functional
  703. IfaceMgr::SocketInfo sock2(9, IOAddress("2001:db8:1::56"), DHCP4_SERVER_PORT + 9);
  704. EXPECT_EQ(9, sock2.sockfd_);
  705. EXPECT_EQ("2001:db8:1::56", sock2.addr_.toText());
  706. EXPECT_EQ(AF_INET6, sock2.family_);
  707. EXPECT_EQ(DHCP4_SERVER_PORT + 9, sock2.port_);
  708. // now let's test if IfaceMgr handles socket info properly
  709. NakedIfaceMgr* ifacemgr = new NakedIfaceMgr();
  710. IfaceMgr::Iface* loopback = ifacemgr->getIface(LOOPBACK);
  711. ASSERT_TRUE(loopback);
  712. loopback->addSocket(sock1);
  713. loopback->addSocket(sock2);
  714. Pkt6 pkt6(DHCPV6_REPLY, 123456);
  715. // pkt6 dos not have interface set yet
  716. EXPECT_THROW(
  717. ifacemgr->getSocket(pkt6),
  718. BadValue
  719. );
  720. // try to send over non-existing interface
  721. pkt6.setIface("nosuchinterface45");
  722. EXPECT_THROW(
  723. ifacemgr->getSocket(pkt6),
  724. BadValue
  725. );
  726. // this will work
  727. pkt6.setIface(LOOPBACK);
  728. EXPECT_EQ(9, ifacemgr->getSocket(pkt6));
  729. bool deleted = false;
  730. EXPECT_NO_THROW(
  731. deleted = ifacemgr->getIface(LOOPBACK)->delSocket(9);
  732. );
  733. EXPECT_EQ(true, deleted);
  734. // it should throw again, there's no usable socket anymore
  735. EXPECT_THROW(
  736. ifacemgr->getSocket(pkt6),
  737. Unexpected
  738. );
  739. // repeat for pkt4
  740. Pkt4 pkt4(DHCPDISCOVER, 1);
  741. // pkt4 does not have interface set yet.
  742. EXPECT_THROW(
  743. ifacemgr->getSocket(pkt4),
  744. BadValue
  745. );
  746. // Try to send over non-existing interface.
  747. pkt4.setIface("nosuchinterface45");
  748. EXPECT_THROW(
  749. ifacemgr->getSocket(pkt4),
  750. BadValue
  751. );
  752. // Socket info is set, packet has well defined interface. It should work.
  753. pkt4.setIface(LOOPBACK);
  754. EXPECT_EQ(7, ifacemgr->getSocket(pkt4));
  755. EXPECT_NO_THROW(
  756. ifacemgr->getIface(LOOPBACK)->delSocket(7);
  757. );
  758. // It should throw again, there's no usable socket anymore.
  759. EXPECT_THROW(
  760. ifacemgr->getSocket(pkt4),
  761. Unexpected
  762. );
  763. delete ifacemgr;
  764. }
  765. #if defined(OS_LINUX)
  766. /// @brief parses text representation of MAC address
  767. ///
  768. /// This function parses text representation of a MAC address and stores
  769. /// it in binary format. Text format is expecte to be separate with
  770. /// semicolons, e.g. f4:6d:04:96:58:f2
  771. ///
  772. /// TODO: IfaceMgr::Iface::mac_ uses uint8_t* type, should be vector<uint8_t>
  773. ///
  774. /// @param textMac string with MAC address to parse
  775. /// @param mac pointer to output buffer
  776. /// @param macLen length of output buffer
  777. ///
  778. /// @return number of bytes filled in output buffer
  779. size_t parse_mac(const std::string& textMac, uint8_t* mac, size_t macLen) {
  780. stringstream tmp(textMac);
  781. tmp.flags(ios::hex);
  782. int i = 0;
  783. uint8_t octet = 0; // output octet
  784. uint8_t byte; // parsed charater from text representation
  785. while (!tmp.eof()) {
  786. tmp >> byte; // hex value
  787. if (byte == ':') {
  788. mac[i++] = octet;
  789. if (i == macLen) {
  790. // parsing aborted. We hit output buffer size
  791. return(i);
  792. }
  793. octet = 0;
  794. continue;
  795. }
  796. if (isalpha(byte)) {
  797. byte = toupper(byte) - 'A' + 10;
  798. } else if (isdigit(byte)) {
  799. byte -= '0';
  800. } else {
  801. // parse error. Let's return what we were able to parse so far
  802. break;
  803. }
  804. octet <<= 4;
  805. octet += byte;
  806. }
  807. mac[i++] = octet;
  808. return (i);
  809. }
  810. /// @brief Parses 'ifconfig -a' output and creates list of interfaces
  811. ///
  812. /// This method tries to parse ifconfig output. Note that there are some
  813. /// oddities in recent versions of ifconfig, like putting extra spaces
  814. /// after MAC address, inconsistent naming and spacing between inet and inet6.
  815. /// This is an attempt to find a balance between tight parsing of every piece
  816. /// of text that ifconfig prints and robustness to handle slight differences
  817. /// in ifconfig output.
  818. ///
  819. /// @todo: Consider using isc::util::str::tokens here.
  820. ///
  821. /// @param textFile name of a text file that holds output of ifconfig -a
  822. /// @param ifaces empty list of interfaces to be filled
  823. void parse_ifconfig(const std::string& textFile, IfaceMgr::IfaceCollection& ifaces) {
  824. fstream f(textFile.c_str());
  825. bool first_line = true;
  826. IfaceMgr::IfaceCollection::iterator iface;
  827. while (!f.eof()) {
  828. string line;
  829. getline(f, line);
  830. // interfaces are separated by empty line
  831. if (line.length() == 0) {
  832. first_line = true;
  833. continue;
  834. }
  835. // uncomment this for ifconfig output debug
  836. // cout << "line[" << line << "]" << endl;
  837. // this is first line of a new interface
  838. if (first_line) {
  839. first_line = false;
  840. size_t offset;
  841. offset = line.find_first_of(" ");
  842. if (offset == string::npos) {
  843. isc_throw(BadValue, "Malformed output of ifconfig");
  844. }
  845. // ifconfig in Gentoo prints out eth0: instead of eth0
  846. if (line[offset - 1] == ':') {
  847. offset--;
  848. }
  849. string name = line.substr(0, offset);
  850. // sadly, ifconfig does not return ifindex
  851. ifaces.push_back(IfaceMgr::Iface(name, 0));
  852. iface = ifaces.end();
  853. --iface; // points to the last element
  854. offset = line.find(string("HWaddr"));
  855. string mac = "";
  856. if (offset != string::npos) { // some interfaces don't have MAC (e.g. lo)
  857. offset += 7;
  858. mac = line.substr(offset, string::npos);
  859. mac = mac.substr(0, mac.find_first_of(" "));
  860. uint8_t buf[IfaceMgr::MAX_MAC_LEN];
  861. int mac_len = parse_mac(mac, buf, IfaceMgr::MAX_MAC_LEN);
  862. iface->setMac(buf, mac_len);
  863. }
  864. }
  865. if (line.find("inet6") != string::npos) {
  866. // IPv6 address
  867. string addr;
  868. if (line.find("addr:", line.find("inet6")) != string::npos) {
  869. // Ubuntu style format: inet6 addr: ::1/128 Scope:Host
  870. addr = line.substr(line.find("addr:") + 6, string::npos);
  871. } else {
  872. // Gentoo style format: inet6 fe80::6ef0:49ff:fe96:ba17 prefixlen 64 scopeid 0x20<link>
  873. addr = line.substr(line.find("inet6") + 6, string::npos);
  874. }
  875. // handle Ubuntu format: inet6 addr: fe80::f66d:4ff:fe96:58f2/64 Scope:Link
  876. addr = addr.substr(0, addr.find("/"));
  877. // handle inet6 fe80::ca3a:35ff:fed4:8f1d prefixlen 64 scopeid 0x20<link>
  878. addr = addr.substr(0, addr.find(" "));
  879. IOAddress a(addr);
  880. iface->addAddress(a);
  881. } else if(line.find("inet") != string::npos) {
  882. // IPv4 address
  883. string addr;
  884. if (line.find("addr:", line.find("inet")) != string::npos) {
  885. // Ubuntu style format: inet addr:127.0.0.1 Mask:255.0.0.0
  886. addr = line.substr(line.find("addr:") + 5, string::npos);
  887. } else {
  888. // Gentoo style format: inet 10.53.0.4 netmask 255.255.255.0
  889. addr = line.substr(line.find("inet") + 5, string::npos);
  890. }
  891. addr = addr.substr(0, addr.find_first_of(" "));
  892. IOAddress a(addr);
  893. iface->addAddress(a);
  894. } else if(line.find("Metric")) {
  895. // flags
  896. if (line.find("UP") != string::npos) {
  897. iface->flag_up_ = true;
  898. }
  899. if (line.find("LOOPBACK") != string::npos) {
  900. iface->flag_loopback_ = true;
  901. }
  902. if (line.find("RUNNING") != string::npos) {
  903. iface->flag_running_ = true;
  904. }
  905. if (line.find("BROADCAST") != string::npos) {
  906. iface->flag_broadcast_ = true;
  907. }
  908. if (line.find("MULTICAST") != string::npos) {
  909. iface->flag_multicast_ = true;
  910. }
  911. }
  912. }
  913. }
  914. // This test compares implemented detection routines to output of "ifconfig -a" command.
  915. // It is far from perfect, but it is able to verify that interface names, flags,
  916. // MAC address, IPv4 and IPv6 addresses are detected properly. Interface list completeness
  917. // (check that each interface is reported, i.e. no missing or extra interfaces) and
  918. // address completeness is verified.
  919. //
  920. // Things that are not tested:
  921. // - ifindex (ifconfig does not print it out)
  922. // - address scopes and lifetimes (we don't need it, so it is not implemented in IfaceMgr)
  923. // TODO: temporarily disabled, see ticket #1529
  924. TEST_F(IfaceMgrTest, DISABLED_detectIfaces_linux) {
  925. NakedIfaceMgr* ifacemgr = new NakedIfaceMgr();
  926. IfaceMgr::IfaceCollection& detectedIfaces = ifacemgr->getIfacesLst();
  927. const std::string textFile = "ifconfig.txt";
  928. unlink(textFile.c_str());
  929. int result = system( ("/sbin/ifconfig -a > " + textFile).c_str());
  930. ASSERT_EQ(0, result);
  931. // list of interfaces parsed from ifconfig
  932. IfaceMgr::IfaceCollection parsedIfaces;
  933. ASSERT_NO_THROW(
  934. parse_ifconfig(textFile, parsedIfaces);
  935. );
  936. unlink(textFile.c_str());
  937. cout << "------Parsed interfaces---" << endl;
  938. for (IfaceMgr::IfaceCollection::iterator i = parsedIfaces.begin();
  939. i != parsedIfaces.end(); ++i) {
  940. cout << i->getName() << ": ifindex=" << i->getIndex() << ", mac=" << i->getPlainMac();
  941. cout << ", flags:";
  942. if (i->flag_up_) {
  943. cout << " UP";
  944. }
  945. if (i->flag_running_) {
  946. cout << " RUNNING";
  947. }
  948. if (i->flag_multicast_) {
  949. cout << " MULTICAST";
  950. }
  951. if (i->flag_broadcast_) {
  952. cout << " BROADCAST";
  953. }
  954. cout << ", addrs:";
  955. const IfaceMgr::AddressCollection& addrs = i->getAddresses();
  956. for (IfaceMgr::AddressCollection::const_iterator a= addrs.begin();
  957. a != addrs.end(); ++a) {
  958. cout << a->toText() << " ";
  959. }
  960. cout << endl;
  961. }
  962. // Ok, now we have 2 lists of interfaces. Need to compare them
  963. ASSERT_EQ(detectedIfaces.size(), parsedIfaces.size());
  964. // TODO: This could could probably be written simple with find()
  965. for (IfaceMgr::IfaceCollection::iterator detected = detectedIfaces.begin();
  966. detected != detectedIfaces.end(); ++detected) {
  967. // let's find out if this interface is
  968. bool found = false;
  969. for (IfaceMgr::IfaceCollection::iterator i = parsedIfaces.begin();
  970. i != parsedIfaces.end(); ++i) {
  971. if (detected->getName() != i->getName()) {
  972. continue;
  973. }
  974. found = true;
  975. cout << "Checking interface " << detected->getName() << endl;
  976. // start with checking flags
  977. EXPECT_EQ(detected->flag_loopback_, i->flag_loopback_);
  978. EXPECT_EQ(detected->flag_up_, i->flag_up_);
  979. EXPECT_EQ(detected->flag_running_, i->flag_running_);
  980. EXPECT_EQ(detected->flag_multicast_, i->flag_multicast_);
  981. EXPECT_EQ(detected->flag_broadcast_, i->flag_broadcast_);
  982. // skip MAC comparison for loopback as netlink returns MAC
  983. // 00:00:00:00:00:00 for lo
  984. if (!detected->flag_loopback_) {
  985. ASSERT_EQ(detected->getMacLen(), i->getMacLen());
  986. EXPECT_EQ(0, memcmp(detected->getMac(), i->getMac(), i->getMacLen()));
  987. }
  988. EXPECT_EQ(detected->getAddresses().size(), i->getAddresses().size());
  989. // now compare addresses
  990. const IfaceMgr::AddressCollection& addrs = detected->getAddresses();
  991. for (IfaceMgr::AddressCollection::const_iterator addr = addrs.begin();
  992. addr != addrs.end(); ++addr) {
  993. bool addr_found = false;
  994. const IfaceMgr::AddressCollection& addrs2 = detected->getAddresses();
  995. for (IfaceMgr::AddressCollection::const_iterator a = addrs2.begin();
  996. a != addrs2.end(); ++a) {
  997. if (*addr != *a) {
  998. continue;
  999. }
  1000. addr_found = true;
  1001. }
  1002. if (!addr_found) {
  1003. cout << "ifconfig does not seem to report " << addr->toText()
  1004. << " address on " << detected->getFullName() << " interface." << endl;
  1005. FAIL();
  1006. }
  1007. cout << "Address " << addr->toText() << " on interface " << detected->getFullName()
  1008. << " matched with 'ifconfig -a' output." << endl;
  1009. }
  1010. }
  1011. if (!found) { // corresponding interface was not found
  1012. FAIL();
  1013. }
  1014. }
  1015. delete ifacemgr;
  1016. }
  1017. #endif
  1018. volatile bool callback_ok;
  1019. void my_callback(void) {
  1020. cout << "Callback triggered." << endl;
  1021. callback_ok = true;
  1022. }
  1023. TEST_F(IfaceMgrTest, controlSession) {
  1024. // tests if extra control socket and its callback can be passed and
  1025. // it is supported properly by receive4() method.
  1026. callback_ok = false;
  1027. NakedIfaceMgr* ifacemgr = new NakedIfaceMgr();
  1028. // create pipe and register it as extra socket
  1029. int pipefd[2];
  1030. EXPECT_TRUE(pipe(pipefd) == 0);
  1031. EXPECT_NO_THROW(ifacemgr->set_session_socket(pipefd[0], my_callback));
  1032. Pkt4Ptr pkt4;
  1033. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  1034. // Our callback should not be called this time (there was no data)
  1035. EXPECT_FALSE(callback_ok);
  1036. // IfaceMgr should not process control socket data as incoming packets
  1037. EXPECT_FALSE(pkt4);
  1038. // Now, send some data over pipe (38 bytes)
  1039. EXPECT_EQ(38, write(pipefd[1], "Hi, this is a message sent over a pipe", 38));
  1040. // ... and repeat
  1041. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  1042. // IfaceMgr should not process control socket data as incoming packets
  1043. EXPECT_FALSE(pkt4);
  1044. // There was some data, so this time callback should be called
  1045. EXPECT_TRUE(callback_ok);
  1046. delete ifacemgr;
  1047. // close both pipe ends
  1048. close(pipefd[1]);
  1049. close(pipefd[0]);
  1050. }
  1051. }