iface_mgr_unittest.cc 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909
  1. // Copyright (C) 2011-2015 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 <asiolink/io_address.h>
  16. #include <dhcp/dhcp4.h>
  17. #include <dhcp/iface_mgr.h>
  18. #include <dhcp/option.h>
  19. #include <dhcp/pkt6.h>
  20. #include <dhcp/pkt_filter.h>
  21. #include <dhcp/tests/iface_mgr_test_config.h>
  22. #include <dhcp/tests/pkt_filter6_test_utils.h>
  23. #include <boost/bind.hpp>
  24. #include <boost/foreach.hpp>
  25. #include <boost/scoped_ptr.hpp>
  26. #include <gtest/gtest.h>
  27. #include <fstream>
  28. #include <iostream>
  29. #include <sstream>
  30. #include <arpa/inet.h>
  31. #include <unistd.h>
  32. using namespace std;
  33. using namespace isc;
  34. using namespace isc::asiolink;
  35. using namespace isc::dhcp;
  36. using namespace isc::dhcp::test;
  37. using boost::scoped_ptr;
  38. namespace {
  39. // Name of loopback interface detection
  40. const size_t BUF_SIZE = 32;
  41. char LOOPBACK[BUF_SIZE] = "lo";
  42. // Ports used during testing
  43. const uint16_t PORT1 = 10547; // V6 socket
  44. const uint16_t PORT2 = 10548; // V4 socket
  45. // On some systems measured duration of receive6() and receive4() appears to be
  46. // shorter than select() timeout. This may be the case if different time
  47. // resolutions are used by these functions. For such cases we set the
  48. // tolerance to 0.01s.
  49. const uint32_t TIMEOUT_TOLERANCE = 10000;
  50. /// This test verifies that the socket read buffer can be used to
  51. /// receive the data and that the data can be read from it.
  52. TEST(IfaceTest, readBuffer) {
  53. // Create fake interface object.
  54. Iface iface("em0", 0);
  55. // The size of read buffer should initially be 0 and the returned
  56. // pointer should be NULL.
  57. ASSERT_EQ(0, iface.getReadBufferSize());
  58. EXPECT_EQ(NULL, iface.getReadBuffer());
  59. // Let's resize the buffer.
  60. iface.resizeReadBuffer(256);
  61. // Check that the buffer has expected size.
  62. ASSERT_EQ(256, iface.getReadBufferSize());
  63. // The returned pointer should now be non-NULL.
  64. uint8_t* buf_ptr = iface.getReadBuffer();
  65. ASSERT_FALSE(buf_ptr == NULL);
  66. // Use the pointer to set some data.
  67. for (int i = 0; i < iface.getReadBufferSize(); ++i) {
  68. buf_ptr[i] = i;
  69. }
  70. // Get the pointer again and validate the data.
  71. buf_ptr = iface.getReadBuffer();
  72. ASSERT_EQ(256, iface.getReadBufferSize());
  73. for (int i = 0; i < iface.getReadBufferSize(); ++i) {
  74. // Use assert so as it fails on the first failure, no need
  75. // to continue further checks.
  76. ASSERT_EQ(i, buf_ptr[i]);
  77. }
  78. }
  79. // Check that counting the number of active addresses on the interface
  80. // works as expected.
  81. TEST(IfaceTest, countActive4) {
  82. Iface iface("eth0", 0);
  83. ASSERT_EQ(0, iface.countActive4());
  84. iface.addAddress(IOAddress("192.168.0.2"));
  85. ASSERT_EQ(1, iface.countActive4());
  86. iface.addAddress(IOAddress("2001:db8:1::1"));
  87. ASSERT_EQ(1, iface.countActive4());
  88. iface.addAddress(IOAddress("192.168.0.3"));
  89. ASSERT_EQ(2, iface.countActive4());
  90. ASSERT_NO_THROW(iface.setActive(IOAddress("192.168.0.2"), false));
  91. ASSERT_EQ(1, iface.countActive4());
  92. ASSERT_NO_THROW(iface.setActive(IOAddress("192.168.0.3"), false));
  93. ASSERT_EQ(0, iface.countActive4());
  94. }
  95. /// Mock object implementing PktFilter class. It is used by
  96. /// IfaceMgrTest::setPacketFilter to verify that IfaceMgr::setPacketFilter
  97. /// sets this object as a handler for opening sockets. This dummy
  98. /// class simply records that openSocket function was called by
  99. /// the IfaceMgr as expected.
  100. ///
  101. /// @todo This class currently doesn't verify that send/receive functions
  102. /// were called. In order to test it, there is a need to supply dummy
  103. /// function performing select() on certain sockets. The system select()
  104. /// call will fail when dummy socket descriptor is provided and thus
  105. /// TestPktFilter::receive will never be called. The appropriate extension
  106. /// to IfaceMgr is planned along with implementation of other "Packet
  107. /// Filters" such as these supporting Linux Packet Filtering and
  108. /// Berkley Packet Filtering.
  109. class TestPktFilter : public PktFilter {
  110. public:
  111. /// Constructor
  112. TestPktFilter()
  113. : open_socket_called_(false) {
  114. }
  115. virtual bool isDirectResponseSupported() const {
  116. return (false);
  117. }
  118. /// @brief Pretend to open a socket.
  119. ///
  120. /// This function doesn't open a real socket. It always returns the
  121. /// same fake socket descriptor. It also records the fact that it has
  122. /// been called in the public open_socket_called_ member.
  123. /// As in the case of opening a real socket, this function will check
  124. /// if there is another fake socket "bound" to the same address and port.
  125. /// If there is, it will throw an exception. This allows to simulate the
  126. /// conditions when one of the sockets can't be open because there is
  127. /// a socket already open and test how IfaceMgr will handle it.
  128. ///
  129. /// @param iface An interface on which the socket is to be opened.
  130. /// @param addr An address to which the socket is to be bound.
  131. /// @param port A port to which the socket is to be bound.
  132. virtual SocketInfo openSocket(Iface& iface,
  133. const isc::asiolink::IOAddress& addr,
  134. const uint16_t port,
  135. const bool join_multicast,
  136. const bool) {
  137. // Check if there is any other socket bound to the specified address
  138. // and port on this interface.
  139. const Iface::SocketCollection& sockets = iface.getSockets();
  140. for (Iface::SocketCollection::const_iterator socket = sockets.begin();
  141. socket != sockets.end(); ++socket) {
  142. if (((socket->addr_ == addr) ||
  143. ((socket->addr_ == IOAddress("::")) && join_multicast)) &&
  144. socket->port_ == port) {
  145. isc_throw(SocketConfigError, "test socket bind error");
  146. }
  147. }
  148. open_socket_called_ = true;
  149. return (SocketInfo(addr, port, 255));
  150. }
  151. /// Does nothing
  152. virtual Pkt4Ptr receive(Iface&, const SocketInfo&) {
  153. return (Pkt4Ptr());
  154. }
  155. /// Does nothing
  156. virtual int send(const Iface&, uint16_t, const Pkt4Ptr&) {
  157. return (0);
  158. }
  159. /// Holds the information whether openSocket was called on this
  160. /// object after its creation.
  161. bool open_socket_called_;
  162. };
  163. class NakedIfaceMgr: public IfaceMgr {
  164. // "Naked" Interface Manager, exposes internal fields
  165. public:
  166. /// @brief Constructor.
  167. NakedIfaceMgr() {
  168. loDetect();
  169. }
  170. /// @brief detects name of the loopback interface
  171. ///
  172. /// This method detects name of the loopback interface.
  173. static void loDetect() {
  174. // Poor man's interface detection. It will go away as soon as proper
  175. // interface detection is implemented
  176. if (if_nametoindex("lo") > 0) {
  177. snprintf(LOOPBACK, BUF_SIZE - 1, "lo");
  178. } else if (if_nametoindex("lo0") > 0) {
  179. snprintf(LOOPBACK, BUF_SIZE - 1, "lo0");
  180. } else {
  181. cout << "Failed to detect loopback interface. Neither "
  182. << "lo nor lo0 worked. I give up." << endl;
  183. FAIL();
  184. }
  185. }
  186. /// @brief Returns the collection of existing interfaces.
  187. IfaceCollection& getIfacesLst() { return (ifaces_); }
  188. /// @brief This function creates fictitious interfaces with fictious
  189. /// addresses.
  190. ///
  191. /// These interfaces can be used in tests that don't actually try
  192. /// to open the sockets on these interfaces. Some tests use mock
  193. /// objects to mimic sockets being open. These interfaces are
  194. /// suitable for such tests.
  195. void createIfaces() {
  196. ifaces_.clear();
  197. // local loopback
  198. IfacePtr lo = createIface("lo", 0);
  199. lo->addAddress(IOAddress("127.0.0.1"));
  200. lo->addAddress(IOAddress("::1"));
  201. ifaces_.push_back(lo);
  202. // eth0
  203. IfacePtr eth0 = createIface("eth0", 1);
  204. eth0->addAddress(IOAddress("10.0.0.1"));
  205. eth0->addAddress(IOAddress("fe80::3a60:77ff:fed5:cdef"));
  206. eth0->addAddress(IOAddress("2001:db8:1::1"));
  207. ifaces_.push_back(eth0);
  208. // eth1
  209. IfacePtr eth1 = createIface("eth1", 2);
  210. eth1->addAddress(IOAddress("192.0.2.3"));
  211. eth1->addAddress(IOAddress("fe80::3a60:77ff:fed5:abcd"));
  212. ifaces_.push_back(eth1);
  213. }
  214. /// @brief Create an object representing interface.
  215. ///
  216. /// Apart from creating an interface, this function also sets the
  217. /// interface flags:
  218. /// - loopback flag if interface name is "lo"
  219. /// - up always true
  220. /// - running always true
  221. /// - inactive always to false
  222. /// - multicast always to true
  223. /// - broadcast always to false
  224. ///
  225. /// If one needs to modify the default flag settings, the setIfaceFlags
  226. /// function should be used.
  227. ///
  228. /// @param name A name of the interface to be created.
  229. /// @param ifindex An index of the interface to be created.
  230. ///
  231. /// @return An object representing interface.
  232. static IfacePtr createIface(const std::string& name, const int ifindex) {
  233. IfacePtr iface(new Iface(name, ifindex));
  234. if (name == "lo") {
  235. iface->flag_loopback_ = true;
  236. // Don't open sockets on loopback interface.
  237. iface->inactive4_ = true;
  238. iface->inactive6_ = true;
  239. } else {
  240. iface->inactive4_ = false;
  241. iface->inactive6_ = false;
  242. }
  243. iface->flag_multicast_ = true;
  244. // On BSD systems, the SO_BINDTODEVICE option is not supported.
  245. // Therefore the IfaceMgr will throw an exception on attempt to
  246. // open sockets on more than one broadcast-capable interface at
  247. // the same time. In order to prevent this error, we mark all
  248. // interfaces broadcast-incapable for unit testing.
  249. iface->flag_broadcast_ = false;
  250. iface->flag_up_ = true;
  251. iface->flag_running_ = true;
  252. return (iface);
  253. }
  254. /// @brief Checks if the specified interface has a socket bound to a
  255. /// specified adddress.
  256. ///
  257. /// @param iface_name A name of the interface.
  258. /// @param addr An address to be checked for binding.
  259. ///
  260. /// @return true if there is a socket bound to the specified address.
  261. bool isBound(const std::string& iface_name, const std::string& addr) {
  262. IfacePtr iface = getIface(iface_name);
  263. if (!iface) {
  264. ADD_FAILURE() << "the interface " << iface_name << " doesn't exist";
  265. return (false);
  266. }
  267. const Iface::SocketCollection& sockets = iface->getSockets();
  268. for (Iface::SocketCollection::const_iterator sock = sockets.begin();
  269. sock != sockets.end(); ++sock) {
  270. if (sock->addr_ == IOAddress(addr)) {
  271. return (true);
  272. } else if ((sock->addr_ == IOAddress("::")) &&
  273. (IOAddress(addr).isV6LinkLocal())) {
  274. BOOST_FOREACH(Iface::Address a, iface->getAddresses()) {
  275. if (a.get() == IOAddress(addr)) {
  276. return (true);
  277. }
  278. }
  279. }
  280. }
  281. return (false);
  282. }
  283. /// @brief Modify flags on the interface.
  284. ///
  285. /// @param name A name of the interface.
  286. /// @param loopback A new value of the loopback flag.
  287. /// @param up A new value of the up flag.
  288. /// @param running A new value of the running flag.
  289. /// @param inactive A new value of the inactive flag.
  290. void setIfaceFlags(const std::string& name, const bool loopback,
  291. const bool up, const bool running,
  292. const bool inactive4,
  293. const bool inactive6) {
  294. for (IfaceMgr::IfaceCollection::iterator iface = ifaces_.begin();
  295. iface != ifaces_.end(); ++iface) {
  296. if ((*iface)->getName() == name) {
  297. (*iface)->flag_loopback_ = loopback;
  298. (*iface)->flag_up_ = up;
  299. (*iface)->flag_running_ = running;
  300. (*iface)->inactive4_ = inactive4;
  301. (*iface)->inactive6_ = inactive6;
  302. }
  303. }
  304. }
  305. };
  306. /// @brief A test fixture class for IfaceMgr.
  307. ///
  308. /// @todo Sockets being opened by IfaceMgr tests should be managed by
  309. /// the test fixture. In particular, the class should close sockets after
  310. /// each test. Current approach where test cases are responsible for
  311. /// closing sockets is resource leak prone, especially in case of the
  312. /// test failure path.
  313. class IfaceMgrTest : public ::testing::Test {
  314. public:
  315. /// @brief Constructor.
  316. IfaceMgrTest()
  317. : errors_count_(0) {
  318. }
  319. ~IfaceMgrTest() {
  320. }
  321. /// @brief Tests the number of IPv6 sockets on interface
  322. ///
  323. /// This function checks the expected number of open IPv6 sockets on the
  324. /// specified interface. On non-Linux systems, sockets are bound to a
  325. /// link-local address and the number of unicast addresses specified.
  326. /// On Linux systems, there is one more socket bound to a ff02::1:2
  327. /// multicast address.
  328. ///
  329. /// @param iface An interface on which sockets are open.
  330. /// @param unicast_num A number of unicast addresses bound.
  331. /// @param link_local_num A number of link local addresses bound.
  332. void checkSocketsCount6(const Iface& iface, const int unicast_num,
  333. const int link_local_num = 1) {
  334. // On local-loopback interface, there should be no sockets.
  335. if (iface.flag_loopback_) {
  336. ASSERT_TRUE(iface.getSockets().empty())
  337. << "expected empty socket set on loopback interface "
  338. << iface.getName();
  339. return;
  340. }
  341. #if defined OS_LINUX
  342. // On Linux, for each link-local address there may be an
  343. // additional socket opened and bound to ff02::1:2. This socket
  344. // is only opened if the interface is multicast-capable.
  345. ASSERT_EQ(unicast_num + (iface.flag_multicast_ ? link_local_num : 0)
  346. + link_local_num, iface.getSockets().size())
  347. << "invalid number of sockets on interface "
  348. << iface.getName();
  349. #else
  350. // On non-Linux, there is no additional socket.
  351. ASSERT_EQ(unicast_num + link_local_num, iface.getSockets().size())
  352. << "invalid number of sockets on interface "
  353. << iface.getName();
  354. #endif
  355. }
  356. // Get ther number of IPv4 or IPv6 sockets on the loopback interface
  357. int getOpenSocketsCount(const Iface& iface, uint16_t family) const {
  358. // Get all sockets.
  359. Iface::SocketCollection sockets = iface.getSockets();
  360. // Loop through sockets and try to find the ones which match the
  361. // specified type.
  362. int sockets_count = 0;
  363. for (Iface::SocketCollection::const_iterator sock = sockets.begin();
  364. sock != sockets.end(); ++sock) {
  365. // Match found, increase the counter.
  366. if (sock->family_ == family) {
  367. ++sockets_count;
  368. }
  369. }
  370. return (sockets_count);
  371. }
  372. /// @brief returns socket bound to a specific address (or NULL)
  373. ///
  374. /// A helper function, used to pick a socketinfo that is bound to a given
  375. /// address.
  376. ///
  377. /// @param sockets sockets collection
  378. /// @param addr address the socket is bound to
  379. ///
  380. /// @return socket info structure (or NULL)
  381. const isc::dhcp::SocketInfo*
  382. getSocketByAddr(const isc::dhcp::Iface::SocketCollection& sockets,
  383. const IOAddress& addr) {
  384. for (isc::dhcp::Iface::SocketCollection::const_iterator s =
  385. sockets.begin(); s != sockets.end(); ++s) {
  386. if (s->addr_ == addr) {
  387. return (&(*s));
  388. }
  389. }
  390. return (NULL);
  391. }
  392. /// @brief Implements an IfaceMgr error handler.
  393. ///
  394. /// This function can be installed as an error handler for the
  395. /// IfaceMgr::openSockets4 function. The error handler is invoked
  396. /// when an attempt to open a particular socket fails for any reason.
  397. /// Typically, the error handler will log a warning. When the error
  398. /// handler returns, the openSockets4 function should continue opening
  399. /// sockets on other interfaces.
  400. ///
  401. /// @param errmsg An error string indicating the reason for failure.
  402. void ifaceMgrErrorHandler(const std::string&) {
  403. // Increase the counter of invocations to this function. By checking
  404. // this number, a test amy check if the expected number of errors
  405. // has occurred.
  406. ++errors_count_;
  407. }
  408. /// Holds the invocation counter for ifaceMgrErrorHandler.
  409. int errors_count_;
  410. };
  411. // We need some known interface to work reliably. Loopback interface is named
  412. // lo on Linux and lo0 on BSD boxes. We need to find out which is available.
  413. // This is not a real test, but rather a workaround that will go away when
  414. // interface detection is implemented on all OSes.
  415. TEST_F(IfaceMgrTest, loDetect) {
  416. NakedIfaceMgr::loDetect();
  417. }
  418. // Uncomment this test to create packet writer. It will
  419. // write incoming DHCPv6 packets as C arrays. That is useful
  420. // for generating test sequences based on actual traffic
  421. //
  422. // TODO: this potentially should be moved to a separate tool
  423. //
  424. #if 0
  425. TEST_F(IfaceMgrTest, dhcp6Sniffer) {
  426. // Testing socket operation in a portable way is tricky
  427. // without interface detection implemented
  428. unlink("interfaces.txt");
  429. ofstream interfaces("interfaces.txt", ios::ate);
  430. interfaces << "eth0 fe80::21e:8cff:fe9b:7349";
  431. interfaces.close();
  432. boost::scoped_ptr<NakedIfaceMgr> ifacemgr = new NakedIfaceMgr();
  433. Pkt6Ptr pkt;
  434. int cnt = 0;
  435. cout << "---8X-----------------------------------------" << endl;
  436. while (true) {
  437. pkt.reset(ifacemgr->receive());
  438. cout << "// this code is autogenerated. Do NOT edit." << endl;
  439. cout << "// Received " << pkt->data_len_ << " bytes packet:" << endl;
  440. cout << "Pkt6 *capture" << cnt++ << "() {" << endl;
  441. cout << " Pkt6* pkt;" << endl;
  442. cout << " pkt = new Pkt6(" << pkt->data_len_ << ");" << endl;
  443. cout << " pkt->remote_port_ = " << pkt-> remote_port_ << ";" << endl;
  444. cout << " pkt->remote_addr_ = IOAddress(\""
  445. << pkt->remote_addr_ << "\");" << endl;
  446. cout << " pkt->local_port_ = " << pkt-> local_port_ << ";" << endl;
  447. cout << " pkt->local_addr_ = IOAddress(\""
  448. << pkt->local_addr_ << "\");" << endl;
  449. cout << " pkt->ifindex_ = " << pkt->ifindex_ << ";" << endl;
  450. cout << " pkt->iface_ = \"" << pkt->iface_ << "\";" << endl;
  451. // TODO it is better to declare statically initialize the array
  452. // and then memcpy it to packet.
  453. for (int i=0; i< pkt->data_len_; i++) {
  454. cout << " pkt->data_[" << i << "]="
  455. << (int)(unsigned char)pkt->data_[i] << "; ";
  456. if (!(i%4))
  457. cout << endl;
  458. }
  459. cout << endl;
  460. cout << " return (pkt);" << endl;
  461. cout << "}" << endl << endl;
  462. pkt.reset();
  463. }
  464. cout << "---8X-----------------------------------------" << endl;
  465. // Never happens. Infinite loop is infinite
  466. }
  467. #endif
  468. // This test verifies that creation of the IfaceMgr instance doesn't
  469. // cause an exception.
  470. TEST_F(IfaceMgrTest, instance) {
  471. EXPECT_NO_THROW(IfaceMgr::instance());
  472. }
  473. // This test verifies that sockets can be closed selectively, i.e. all
  474. // IPv4 sockets can be closed first and all IPv6 sockets remain open.
  475. TEST_F(IfaceMgrTest, closeSockets) {
  476. // Will be using local loopback addresses for this test.
  477. IOAddress loaddr("127.0.0.1");
  478. IOAddress loaddr6("::1");
  479. // Create instance of IfaceMgr.
  480. boost::scoped_ptr<NakedIfaceMgr> iface_mgr(new NakedIfaceMgr());
  481. ASSERT_TRUE(iface_mgr);
  482. // Out constructor does not detect interfaces by itself. We need
  483. // to create one and add.
  484. int ifindex = if_nametoindex(LOOPBACK);
  485. ASSERT_GT(ifindex, 0);
  486. IfacePtr lo_iface(new Iface(LOOPBACK, ifindex));
  487. iface_mgr->getIfacesLst().push_back(lo_iface);
  488. // Create set of V4 and V6 sockets on the loopback interface.
  489. // They must differ by a port they are bound to.
  490. for (int i = 0; i < 6; ++i) {
  491. // Every other socket will be IPv4.
  492. if (i % 2) {
  493. ASSERT_NO_THROW(
  494. iface_mgr->openSocket(LOOPBACK, loaddr, 10000 + i)
  495. );
  496. } else {
  497. ASSERT_NO_THROW(
  498. iface_mgr->openSocket(LOOPBACK, loaddr6, 10000 + i)
  499. );
  500. }
  501. }
  502. // At the end we should have 3 IPv4 and 3 IPv6 sockets open.
  503. IfacePtr iface = iface_mgr->getIface(LOOPBACK);
  504. ASSERT_TRUE(iface != NULL);
  505. int v4_sockets_count = getOpenSocketsCount(*iface, AF_INET);
  506. ASSERT_EQ(3, v4_sockets_count);
  507. int v6_sockets_count = getOpenSocketsCount(*iface, AF_INET6);
  508. ASSERT_EQ(3, v6_sockets_count);
  509. // Let's try to close only IPv4 sockets.
  510. ASSERT_NO_THROW(iface_mgr->closeSockets(AF_INET));
  511. v4_sockets_count = getOpenSocketsCount(*iface, AF_INET);
  512. EXPECT_EQ(0, v4_sockets_count);
  513. // The IPv6 sockets should remain open.
  514. v6_sockets_count = getOpenSocketsCount(*iface, AF_INET6);
  515. EXPECT_EQ(3, v6_sockets_count);
  516. // Let's try to close IPv6 sockets.
  517. ASSERT_NO_THROW(iface_mgr->closeSockets(AF_INET6));
  518. v4_sockets_count = getOpenSocketsCount(*iface, AF_INET);
  519. EXPECT_EQ(0, v4_sockets_count);
  520. // They should have been closed now.
  521. v6_sockets_count = getOpenSocketsCount(*iface, AF_INET6);
  522. EXPECT_EQ(0, v6_sockets_count);
  523. }
  524. TEST_F(IfaceMgrTest, ifaceClass) {
  525. // Basic tests for Iface inner class
  526. Iface iface("eth5", 7);
  527. EXPECT_STREQ("eth5/7", iface.getFullName().c_str());
  528. }
  529. // Test that the IPv4 address can be retrieved for the interface.
  530. TEST_F(IfaceMgrTest, ifaceGetAddress) {
  531. Iface iface("eth0", 0);
  532. IOAddress addr("::1");
  533. // Initially, the Iface has no addresses assigned.
  534. EXPECT_FALSE(iface.getAddress4(addr));
  535. // Add some addresses with IPv4 address in the middle.
  536. iface.addAddress(IOAddress("fe80::3a60:77ff:fed5:cdef"));
  537. iface.addAddress(IOAddress("10.1.2.3"));
  538. iface.addAddress(IOAddress("2001:db8:1::2"));
  539. // The v4 address should be returned.
  540. EXPECT_TRUE(iface.getAddress4(addr));
  541. EXPECT_EQ("10.1.2.3", addr.toText());
  542. // Delete the IPv4 address and leave only two IPv6 addresses.
  543. ASSERT_NO_THROW(iface.delAddress(IOAddress("10.1.2.3")));
  544. // The IPv4 address should not be returned.
  545. EXPECT_FALSE(iface.getAddress4(addr));
  546. // Add a different IPv4 address at the end of the list.
  547. iface.addAddress(IOAddress("192.0.2.3"));
  548. // This new address should now be returned.
  549. EXPECT_TRUE(iface.getAddress4(addr));
  550. EXPECT_EQ("192.0.2.3", addr.toText());
  551. }
  552. // This test checks if it is possible to check that the specific address is
  553. // assigned to the interface.
  554. TEST_F(IfaceMgrTest, ifaceHasAddress) {
  555. IfaceMgrTestConfig config(true);
  556. IfacePtr iface = IfaceMgr::instance().getIface("eth0");
  557. ASSERT_TRUE(iface);
  558. EXPECT_TRUE(iface->hasAddress(IOAddress("10.0.0.1")));
  559. EXPECT_FALSE(iface->hasAddress(IOAddress("10.0.0.2")));
  560. EXPECT_TRUE(iface->hasAddress(IOAddress("fe80::3a60:77ff:fed5:cdef")));
  561. EXPECT_TRUE(iface->hasAddress(IOAddress("2001:db8:1::1")));
  562. EXPECT_FALSE(iface->hasAddress(IOAddress("2001:db8:1::2")));
  563. }
  564. // TODO: Implement getPlainMac() test as soon as interface detection
  565. // is implemented.
  566. TEST_F(IfaceMgrTest, getIface) {
  567. cout << "Interface checks. Please ignore socket binding errors." << endl;
  568. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  569. // Interface name, ifindex
  570. IfacePtr iface1(new Iface("lo1", 100));
  571. IfacePtr iface2(new Iface("eth9", 101));
  572. IfacePtr iface3(new Iface("en3", 102));
  573. IfacePtr iface4(new Iface("e1000g4", 103));
  574. cout << "This test assumes that there are less than 100 network interfaces"
  575. << " in the tested system and there are no lo1, eth9, en3, e1000g4"
  576. << " or wifi15 interfaces present." << endl;
  577. // Note: real interfaces may be detected as well
  578. ifacemgr->getIfacesLst().push_back(iface1);
  579. ifacemgr->getIfacesLst().push_back(iface2);
  580. ifacemgr->getIfacesLst().push_back(iface3);
  581. ifacemgr->getIfacesLst().push_back(iface4);
  582. cout << "There are " << ifacemgr->getIfacesLst().size()
  583. << " interfaces." << endl;
  584. for (IfaceMgr::IfaceCollection::iterator iface=ifacemgr->getIfacesLst().begin();
  585. iface != ifacemgr->getIfacesLst().end();
  586. ++iface) {
  587. cout << " " << (*iface)->getFullName() << endl;
  588. }
  589. // Check that interface can be retrieved by ifindex
  590. IfacePtr tmp = ifacemgr->getIface(102);
  591. ASSERT_TRUE(tmp);
  592. EXPECT_EQ("en3", tmp->getName());
  593. EXPECT_EQ(102, tmp->getIndex());
  594. // Check that interface can be retrieved by name
  595. tmp = ifacemgr->getIface("lo1");
  596. ASSERT_TRUE(tmp);
  597. EXPECT_EQ("lo1", tmp->getName());
  598. EXPECT_EQ(100, tmp->getIndex());
  599. // Check that non-existing interfaces are not returned
  600. EXPECT_FALSE(ifacemgr->getIface("wifi15") );
  601. }
  602. TEST_F(IfaceMgrTest, clearIfaces) {
  603. NakedIfaceMgr ifacemgr;
  604. // Create a set of fake interfaces. At the same time, remove the actual
  605. // interfaces that have been detected by the IfaceMgr.
  606. ifacemgr.createIfaces();
  607. ASSERT_GT(ifacemgr.countIfaces(), 0);
  608. boost::shared_ptr<TestPktFilter> custom_packet_filter(new TestPktFilter());
  609. ASSERT_TRUE(custom_packet_filter);
  610. ASSERT_NO_THROW(ifacemgr.setPacketFilter(custom_packet_filter));
  611. ASSERT_NO_THROW(ifacemgr.openSockets4());
  612. ifacemgr.clearIfaces();
  613. EXPECT_EQ(0, ifacemgr.countIfaces());
  614. }
  615. TEST_F(IfaceMgrTest, receiveTimeout6) {
  616. using namespace boost::posix_time;
  617. std::cout << "Testing DHCPv6 packet reception timeouts."
  618. << " Test will block for a few seconds when waiting"
  619. << " for timeout to occur." << std::endl;
  620. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  621. // Open socket on the lo interface.
  622. IOAddress loAddr("::1");
  623. int socket1 = 0;
  624. ASSERT_NO_THROW(
  625. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, 10547)
  626. );
  627. // Socket is open if result is non-negative.
  628. ASSERT_GE(socket1, 0);
  629. // Remember when we call receive6().
  630. ptime start_time = microsec_clock::universal_time();
  631. // Call receive with timeout of 1s + 400000us = 1.4s.
  632. Pkt6Ptr pkt;
  633. ASSERT_NO_THROW(pkt = ifacemgr->receive6(1, 400000));
  634. // Remember when call to receive6() ended.
  635. ptime stop_time = microsec_clock::universal_time();
  636. // We did not send a packet to lo interface so we expect that
  637. // nothing has been received and timeout has been reached.
  638. ASSERT_FALSE(pkt);
  639. // Calculate duration of call to receive6().
  640. time_duration duration = stop_time - start_time;
  641. // We stop the clock when the call completes so it does not
  642. // precisely reflect the receive timeout. However the
  643. // uncertainity should be low enough to expect that measured
  644. // value is in the range <1.4s; 1.7s>.
  645. EXPECT_GE(duration.total_microseconds(),
  646. 1400000 - TIMEOUT_TOLERANCE);
  647. EXPECT_LE(duration.total_microseconds(), 1700000);
  648. // Test timeout shorter than 1s.
  649. start_time = microsec_clock::universal_time();
  650. ASSERT_NO_THROW(pkt = ifacemgr->receive6(0, 500000));
  651. stop_time = microsec_clock::universal_time();
  652. ASSERT_FALSE(pkt);
  653. duration = stop_time - start_time;
  654. // Check if measured duration is within <0.5s; 0.8s>.
  655. EXPECT_GE(duration.total_microseconds(),
  656. 500000 - TIMEOUT_TOLERANCE);
  657. EXPECT_LE(duration.total_microseconds(), 800000);
  658. // Test with invalid fractional timeout values.
  659. EXPECT_THROW(ifacemgr->receive6(0, 1000000), isc::BadValue);
  660. EXPECT_THROW(ifacemgr->receive6(1, 1000010), isc::BadValue);
  661. }
  662. TEST_F(IfaceMgrTest, receiveTimeout4) {
  663. using namespace boost::posix_time;
  664. std::cout << "Testing DHCPv6 packet reception timeouts."
  665. << " Test will block for a few seconds when waiting"
  666. << " for timeout to occur." << std::endl;
  667. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  668. // Open socket on the lo interface.
  669. IOAddress loAddr("127.0.0.1");
  670. int socket1 = 0;
  671. ASSERT_NO_THROW(
  672. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, 10067)
  673. );
  674. // Socket is open if returned value is non-negative.
  675. ASSERT_GE(socket1, 0);
  676. Pkt4Ptr pkt;
  677. // Remember when we call receive4().
  678. ptime start_time = microsec_clock::universal_time();
  679. // Call receive with timeout of 2s + 300000us = 2.3s.
  680. ASSERT_NO_THROW(pkt = ifacemgr->receive4(2, 300000));
  681. // Remember when call to receive4() ended.
  682. ptime stop_time = microsec_clock::universal_time();
  683. // We did not send a packet to lo interface so we expect that
  684. // nothing has been received and timeout has been reached.
  685. ASSERT_FALSE(pkt);
  686. // Calculate duration of call to receive4().
  687. time_duration duration = stop_time - start_time;
  688. // We stop the clock when the call completes so it does not
  689. // precisely reflect the receive timeout. However the
  690. // uncertainity should be low enough to expect that measured
  691. // value is in the range <2.3s; 2.6s>.
  692. EXPECT_GE(duration.total_microseconds(),
  693. 2300000 - TIMEOUT_TOLERANCE);
  694. EXPECT_LE(duration.total_microseconds(), 2600000);
  695. // Test timeout shorter than 1s.
  696. start_time = microsec_clock::universal_time();
  697. ASSERT_NO_THROW(pkt = ifacemgr->receive4(0, 400000));
  698. stop_time = microsec_clock::universal_time();
  699. ASSERT_FALSE(pkt);
  700. duration = stop_time - start_time;
  701. // Check if measured duration is within <0.4s; 0.7s>.
  702. EXPECT_GE(duration.total_microseconds(),
  703. 400000 - TIMEOUT_TOLERANCE);
  704. EXPECT_LE(duration.total_microseconds(), 700000);
  705. // Test with invalid fractional timeout values.
  706. EXPECT_THROW(ifacemgr->receive6(0, 1000000), isc::BadValue);
  707. EXPECT_THROW(ifacemgr->receive6(2, 1000005), isc::BadValue);
  708. }
  709. TEST_F(IfaceMgrTest, multipleSockets) {
  710. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  711. // Container for initialized socket descriptors
  712. std::list<uint16_t> init_sockets;
  713. // Create socket #1
  714. int socket1 = 0;
  715. ASSERT_NO_THROW(
  716. socket1 = ifacemgr->openSocketFromIface(LOOPBACK, PORT1, AF_INET);
  717. );
  718. ASSERT_GE(socket1, 0);
  719. init_sockets.push_back(socket1);
  720. // Create socket #2
  721. IOAddress loAddr("127.0.0.1");
  722. int socket2 = 0;
  723. ASSERT_NO_THROW(
  724. socket2 = ifacemgr->openSocketFromRemoteAddress(loAddr, PORT2);
  725. );
  726. ASSERT_GE(socket2, 0);
  727. init_sockets.push_back(socket2);
  728. // Get loopback interface. If we don't find one we are unable to run
  729. // this test but we don't want to fail.
  730. IfacePtr iface_ptr = ifacemgr->getIface(LOOPBACK);
  731. if (iface_ptr == NULL) {
  732. cout << "Local loopback interface not found. Skipping test. " << endl;
  733. return;
  734. }
  735. // Once sockets have been sucessfully opened, they are supposed to
  736. // be on the list. Here we start to test if all expected sockets
  737. // are on the list and no other (unexpected) socket is there.
  738. Iface::SocketCollection sockets = iface_ptr->getSockets();
  739. int matched_sockets = 0;
  740. for (std::list<uint16_t>::iterator init_sockets_it =
  741. init_sockets.begin();
  742. init_sockets_it != init_sockets.end(); ++init_sockets_it) {
  743. // Set socket descriptors non blocking in order to be able
  744. // to call recv() on them without hang.
  745. int flags = fcntl(*init_sockets_it, F_GETFL, 0);
  746. ASSERT_GE(flags, 0);
  747. ASSERT_GE(fcntl(*init_sockets_it, F_SETFL, flags | O_NONBLOCK), 0);
  748. // recv() is expected to result in EWOULDBLOCK error on non-blocking
  749. // socket in case socket is valid but simply no data are coming in.
  750. char buf;
  751. recv(*init_sockets_it, &buf, 1, MSG_PEEK);
  752. EXPECT_EQ(EWOULDBLOCK, errno);
  753. // Apart from the ability to use the socket we want to make
  754. // sure that socket on the list is the one that we created.
  755. for (Iface::SocketCollection::const_iterator socket_it =
  756. sockets.begin(); socket_it != sockets.end(); ++socket_it) {
  757. if (*init_sockets_it == socket_it->sockfd_) {
  758. // This socket is the one that we created.
  759. ++matched_sockets;
  760. break;
  761. }
  762. }
  763. }
  764. // All created sockets have been matched if this condition works.
  765. EXPECT_EQ(sockets.size(), matched_sockets);
  766. // closeSockets() is the other function that we want to test. It
  767. // is supposed to close all sockets so as we will not be able to use
  768. // them anymore communication.
  769. ifacemgr->closeSockets();
  770. // Closed sockets are supposed to be removed from the list
  771. sockets = iface_ptr->getSockets();
  772. ASSERT_EQ(0, sockets.size());
  773. // We are still in posession of socket descriptors that we created
  774. // on the beginning of this test. We can use them to check whether
  775. // closeSockets() only removed them from the list or they have been
  776. // really closed.
  777. for (std::list<uint16_t>::const_iterator init_sockets_it =
  778. init_sockets.begin();
  779. init_sockets_it != init_sockets.end(); ++init_sockets_it) {
  780. // recv() must result in error when using invalid socket.
  781. char buf;
  782. recv(*init_sockets_it, &buf, 1, MSG_PEEK);
  783. // EWOULDBLOCK would mean that socket is valid/open but
  784. // simply no data is received so we have to check for
  785. // other errors.
  786. EXPECT_NE(EWOULDBLOCK, errno);
  787. }
  788. }
  789. TEST_F(IfaceMgrTest, sockets6) {
  790. // Testing socket operation in a portable way is tricky
  791. // without interface detection implemented.
  792. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  793. IOAddress loAddr("::1");
  794. Pkt6 pkt6(DHCPV6_SOLICIT, 123);
  795. pkt6.setIface(LOOPBACK);
  796. // Bind multicast socket to port 10547
  797. int socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, 10547);
  798. EXPECT_GE(socket1, 0); // socket >= 0
  799. EXPECT_EQ(socket1, ifacemgr->getSocket(pkt6));
  800. // Bind unicast socket to port 10548
  801. int socket2 = ifacemgr->openSocket(LOOPBACK, loAddr, 10548);
  802. EXPECT_GE(socket2, 0);
  803. // Removed code for binding socket twice to the same address/port
  804. // as it caused problems on some platforms (e.g. Mac OS X)
  805. // Close sockets here because the following tests will want to
  806. // open sockets on the same ports.
  807. ifacemgr->closeSockets();
  808. // Use address that is not assigned to LOOPBACK iface.
  809. IOAddress invalidAddr("::2");
  810. EXPECT_THROW(
  811. ifacemgr->openSocket(LOOPBACK, invalidAddr, 10547),
  812. SocketConfigError
  813. );
  814. // Use non-existing interface name.
  815. EXPECT_THROW(
  816. ifacemgr->openSocket("non_existing_interface", loAddr, 10548),
  817. BadValue
  818. );
  819. // Do not call closeSockets() because it is called by IfaceMgr's
  820. // virtual destructor.
  821. }
  822. TEST_F(IfaceMgrTest, socketsFromIface) {
  823. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  824. // Open v6 socket on loopback interface and bind to port
  825. int socket1 = 0;
  826. EXPECT_NO_THROW(
  827. socket1 = ifacemgr->openSocketFromIface(LOOPBACK, PORT1, AF_INET6);
  828. );
  829. // Socket descriptor must be non-negative integer
  830. EXPECT_GE(socket1, 0);
  831. close(socket1);
  832. // Open v4 socket on loopback interface and bind to different port
  833. int socket2 = 0;
  834. EXPECT_NO_THROW(
  835. socket2 = ifacemgr->openSocketFromIface(LOOPBACK, PORT2, AF_INET);
  836. );
  837. // socket descriptor must be non-negative integer
  838. EXPECT_GE(socket2, 0);
  839. close(socket2);
  840. // Close sockets here because the following tests will want to
  841. // open sockets on the same ports.
  842. ifacemgr->closeSockets();
  843. // Use invalid interface name.
  844. EXPECT_THROW(
  845. ifacemgr->openSocketFromIface("non_existing_interface", PORT1, AF_INET),
  846. BadValue
  847. );
  848. // Do not call closeSockets() because it is called by IfaceMgr's
  849. // virtual destructor.
  850. }
  851. TEST_F(IfaceMgrTest, socketsFromAddress) {
  852. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  853. // Open v6 socket on loopback interface and bind to port
  854. int socket1 = 0;
  855. IOAddress loAddr6("::1");
  856. EXPECT_NO_THROW(
  857. socket1 = ifacemgr->openSocketFromAddress(loAddr6, PORT1);
  858. );
  859. // socket descriptor must be non-negative integer
  860. EXPECT_GE(socket1, 0);
  861. // Open v4 socket on loopback interface and bind to different port
  862. int socket2 = 0;
  863. IOAddress loAddr("127.0.0.1");
  864. EXPECT_NO_THROW(
  865. socket2 = ifacemgr->openSocketFromAddress(loAddr, PORT2);
  866. );
  867. // socket descriptor must be positive integer
  868. EXPECT_GE(socket2, 0);
  869. // Close sockets here because the following tests will want to
  870. // open sockets on the same ports.
  871. ifacemgr->closeSockets();
  872. // Use non-existing address.
  873. IOAddress invalidAddr("1.2.3.4");
  874. EXPECT_THROW(
  875. ifacemgr->openSocketFromAddress(invalidAddr, PORT1), BadValue
  876. );
  877. // Do not call closeSockets() because it is called by IfaceMgr's
  878. // virtual destructor.
  879. }
  880. TEST_F(IfaceMgrTest, socketsFromRemoteAddress) {
  881. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  882. // Open v6 socket to connect to remote address.
  883. // Loopback address is the only one that we know
  884. // so let's treat it as remote address.
  885. int socket1 = 0;
  886. IOAddress loAddr6("::1");
  887. EXPECT_NO_THROW(
  888. socket1 = ifacemgr->openSocketFromRemoteAddress(loAddr6, PORT1);
  889. );
  890. EXPECT_GE(socket1, 0);
  891. // Open v4 socket to connect to remote address.
  892. int socket2 = 0;
  893. IOAddress loAddr("127.0.0.1");
  894. EXPECT_NO_THROW(
  895. socket2 = ifacemgr->openSocketFromRemoteAddress(loAddr, PORT2);
  896. );
  897. EXPECT_GE(socket2, 0);
  898. // Close sockets here because the following tests will want to
  899. // open sockets on the same ports.
  900. ifacemgr->closeSockets();
  901. // There used to be a check here that verified the ability to open
  902. // suitable socket for sending broadcast request. However,
  903. // there is no guarantee for such test to work on all systems
  904. // because some systems may have no broadcast capable interfaces at all.
  905. // Thus, this check has been removed.
  906. // Do not call closeSockets() because it is called by IfaceMgr's
  907. // virtual destructor.
  908. }
  909. // TODO: disabled due to other naming on various systems
  910. // (lo in Linux, lo0 in BSD systems)
  911. TEST_F(IfaceMgrTest, DISABLED_sockets6Mcast) {
  912. // testing socket operation in a portable way is tricky
  913. // without interface detection implemented
  914. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  915. IOAddress loAddr("::1");
  916. IOAddress mcastAddr("ff02::1:2");
  917. // bind multicast socket to port 10547
  918. int socket1 = ifacemgr->openSocket(LOOPBACK, mcastAddr, 10547);
  919. EXPECT_GE(socket1, 0); // socket > 0
  920. // expect success. This address/port is already bound, but
  921. // we are using SO_REUSEADDR, so we can bind it twice
  922. int socket2 = ifacemgr->openSocket(LOOPBACK, mcastAddr, 10547);
  923. EXPECT_GE(socket2, 0);
  924. // there's no good way to test negative case here.
  925. // we would need non-multicast interface. We will be able
  926. // to iterate thru available interfaces and check if there
  927. // are interfaces without multicast-capable flag.
  928. close(socket1);
  929. close(socket2);
  930. }
  931. TEST_F(IfaceMgrTest, sendReceive6) {
  932. // testing socket operation in a portable way is tricky
  933. // without interface detection implemented
  934. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  935. // let's assume that every supported OS have lo interface
  936. IOAddress loAddr("::1");
  937. int socket1 = 0, socket2 = 0;
  938. EXPECT_NO_THROW(
  939. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, 10547);
  940. socket2 = ifacemgr->openSocket(LOOPBACK, loAddr, 10546);
  941. );
  942. EXPECT_GE(socket1, 0);
  943. EXPECT_GE(socket2, 0);
  944. // prepare dummy payload
  945. uint8_t data[128];
  946. for (int i = 0; i < 128; i++) {
  947. data[i] = i;
  948. }
  949. Pkt6Ptr sendPkt = Pkt6Ptr(new Pkt6(data, 128));
  950. sendPkt->repack();
  951. sendPkt->setRemotePort(10547);
  952. sendPkt->setRemoteAddr(IOAddress("::1"));
  953. sendPkt->setIndex(1);
  954. sendPkt->setIface(LOOPBACK);
  955. Pkt6Ptr rcvPkt;
  956. EXPECT_EQ(true, ifacemgr->send(sendPkt));
  957. rcvPkt = ifacemgr->receive6(10);
  958. ASSERT_TRUE(rcvPkt); // received our own packet
  959. // let's check that we received what was sent
  960. ASSERT_EQ(sendPkt->data_.size(), rcvPkt->data_.size());
  961. EXPECT_EQ(0, memcmp(&sendPkt->data_[0], &rcvPkt->data_[0],
  962. rcvPkt->data_.size()));
  963. EXPECT_EQ(sendPkt->getRemoteAddr(), rcvPkt->getRemoteAddr());
  964. // since we opened 2 sockets on the same interface and none of them is multicast,
  965. // none is preferred over the other for sending data, so we really should not
  966. // assume the one or the other will always be chosen for sending data. Therefore
  967. // we should accept both values as source ports.
  968. EXPECT_TRUE((rcvPkt->getRemotePort() == 10546) || (rcvPkt->getRemotePort() == 10547));
  969. }
  970. TEST_F(IfaceMgrTest, sendReceive4) {
  971. // testing socket operation in a portable way is tricky
  972. // without interface detection implemented
  973. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  974. // let's assume that every supported OS have lo interface
  975. IOAddress loAddr("127.0.0.1");
  976. int socket1 = 0;
  977. EXPECT_NO_THROW(
  978. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, DHCP4_SERVER_PORT + 10000);
  979. );
  980. EXPECT_GE(socket1, 0);
  981. boost::shared_ptr<Pkt4> sendPkt(new Pkt4(DHCPDISCOVER, 1234) );
  982. sendPkt->setLocalAddr(IOAddress("127.0.0.1"));
  983. sendPkt->setLocalPort(DHCP4_SERVER_PORT + 10000 + 1);
  984. sendPkt->setRemotePort(DHCP4_SERVER_PORT + 10000);
  985. sendPkt->setRemoteAddr(IOAddress("127.0.0.1"));
  986. sendPkt->setIndex(1);
  987. sendPkt->setIface(string(LOOPBACK));
  988. sendPkt->setHops(6);
  989. sendPkt->setSecs(42);
  990. sendPkt->setCiaddr(IOAddress("192.0.2.1"));
  991. sendPkt->setSiaddr(IOAddress("192.0.2.2"));
  992. sendPkt->setYiaddr(IOAddress("192.0.2.3"));
  993. sendPkt->setGiaddr(IOAddress("192.0.2.4"));
  994. // Unpack() now checks if mandatory DHCP_MESSAGE_TYPE is present.
  995. // Workarounds (creating DHCP Message Type Option by hand) are no longer
  996. // needed as setDhcpType() is called in constructor.
  997. uint8_t sname[] = "That's just a string that will act as SNAME";
  998. sendPkt->setSname(sname, strlen((const char*)sname));
  999. uint8_t file[] = "/another/string/that/acts/as/a/file_name.txt";
  1000. sendPkt->setFile(file, strlen((const char*)file));
  1001. ASSERT_NO_THROW(
  1002. sendPkt->pack();
  1003. );
  1004. boost::shared_ptr<Pkt4> rcvPkt;
  1005. EXPECT_NO_THROW(ifacemgr->send(sendPkt));
  1006. ASSERT_NO_THROW(rcvPkt = ifacemgr->receive4(10));
  1007. ASSERT_TRUE(rcvPkt); // received our own packet
  1008. ASSERT_NO_THROW(
  1009. rcvPkt->unpack();
  1010. );
  1011. // let's check that we received what was sent
  1012. EXPECT_EQ(sendPkt->len(), rcvPkt->len());
  1013. EXPECT_EQ("127.0.0.1", rcvPkt->getRemoteAddr().toText());
  1014. EXPECT_EQ(sendPkt->getRemotePort(), rcvPkt->getLocalPort());
  1015. // now let's check content
  1016. EXPECT_EQ(sendPkt->getHops(), rcvPkt->getHops());
  1017. EXPECT_EQ(sendPkt->getOp(), rcvPkt->getOp());
  1018. EXPECT_EQ(sendPkt->getSecs(), rcvPkt->getSecs());
  1019. EXPECT_EQ(sendPkt->getFlags(), rcvPkt->getFlags());
  1020. EXPECT_EQ(sendPkt->getCiaddr(), rcvPkt->getCiaddr());
  1021. EXPECT_EQ(sendPkt->getSiaddr(), rcvPkt->getSiaddr());
  1022. EXPECT_EQ(sendPkt->getYiaddr(), rcvPkt->getYiaddr());
  1023. EXPECT_EQ(sendPkt->getGiaddr(), rcvPkt->getGiaddr());
  1024. EXPECT_EQ(sendPkt->getTransid(), rcvPkt->getTransid());
  1025. EXPECT_TRUE(sendPkt->getSname() == rcvPkt->getSname());
  1026. EXPECT_TRUE(sendPkt->getFile() == rcvPkt->getFile());
  1027. EXPECT_EQ(sendPkt->getHtype(), rcvPkt->getHtype());
  1028. EXPECT_EQ(sendPkt->getHlen(), rcvPkt->getHlen());
  1029. // since we opened 2 sockets on the same interface and none of them is multicast,
  1030. // none is preferred over the other for sending data, so we really should not
  1031. // assume the one or the other will always be chosen for sending data. We should
  1032. // skip checking source port of sent address.
  1033. // Close the socket. Further we will test if errors are reported
  1034. // properly on attempt to use closed soscket.
  1035. close(socket1);
  1036. // Warning: kernel bug on FreeBSD. The following code checks that attempt to
  1037. // read through invalid descriptor will result in exception. The reason why
  1038. // this failure is expected is that select() function should result in EBADF
  1039. // error when invalid descriptor is passed to it. In particular, closed socket
  1040. // descriptor is invalid. On the following OS:
  1041. //
  1042. // 8.1-RELEASE FreeBSD 8.1-RELEASE #0: Mon Jul 19 02:55:53 UTC 2010
  1043. //
  1044. // calling select() using invalid descriptor results in timeout and eventually
  1045. // value of 0 is returned. This has been identified and reported as a bug in
  1046. // FreeBSD: http://www.freebsd.org/cgi/query-pr.cgi?pr=155606
  1047. //
  1048. // @todo: This part of the test is currently disabled on all BSD systems as it was
  1049. // the quick fix. We need a more elegant (config-based) solution to disable
  1050. // this check on affected systems only. The ticket has been submited for this
  1051. // work: http://kea.isc.org/ticket/2971
  1052. #ifndef OS_BSD
  1053. EXPECT_THROW(ifacemgr->receive4(10), SocketReadError);
  1054. #endif
  1055. EXPECT_THROW(ifacemgr->send(sendPkt), SocketWriteError);
  1056. }
  1057. // Verifies that it is possible to set custom packet filter object
  1058. // to handle sockets opening and send/receive operation.
  1059. TEST_F(IfaceMgrTest, setPacketFilter) {
  1060. // Create an instance of IfaceMgr.
  1061. boost::scoped_ptr<NakedIfaceMgr> iface_mgr(new NakedIfaceMgr());
  1062. ASSERT_TRUE(iface_mgr);
  1063. // Try to set NULL packet filter object and make sure it is rejected.
  1064. boost::shared_ptr<TestPktFilter> custom_packet_filter;
  1065. EXPECT_THROW(iface_mgr->setPacketFilter(custom_packet_filter),
  1066. isc::dhcp::InvalidPacketFilter);
  1067. // Create valid object and check if it can be set.
  1068. custom_packet_filter.reset(new TestPktFilter());
  1069. ASSERT_TRUE(custom_packet_filter);
  1070. ASSERT_NO_THROW(iface_mgr->setPacketFilter(custom_packet_filter));
  1071. // Try to open socket using IfaceMgr. It should call the openSocket() function
  1072. // on the packet filter object we have set.
  1073. IOAddress loAddr("127.0.0.1");
  1074. int socket1 = 0;
  1075. EXPECT_NO_THROW(
  1076. socket1 = iface_mgr->openSocket(LOOPBACK, loAddr, DHCP4_SERVER_PORT + 10000);
  1077. );
  1078. // Check that openSocket function was called.
  1079. EXPECT_TRUE(custom_packet_filter->open_socket_called_);
  1080. // This function always returns fake socket descriptor equal to 255.
  1081. EXPECT_EQ(255, socket1);
  1082. // Replacing current packet filter object while there are IPv4
  1083. // sockets open is not allowed!
  1084. EXPECT_THROW(iface_mgr->setPacketFilter(custom_packet_filter),
  1085. PacketFilterChangeDenied);
  1086. // So, let's close the open IPv4 sockets and retry. Now it should succeed.
  1087. iface_mgr->closeSockets(AF_INET);
  1088. EXPECT_NO_THROW(iface_mgr->setPacketFilter(custom_packet_filter));
  1089. }
  1090. // This test checks that the default packet filter for DHCPv6 can be replaced
  1091. // with the custom one.
  1092. TEST_F(IfaceMgrTest, setPacketFilter6) {
  1093. // Create an instance of IfaceMgr.
  1094. boost::scoped_ptr<NakedIfaceMgr> iface_mgr(new NakedIfaceMgr());
  1095. ASSERT_TRUE(iface_mgr);
  1096. // Try to set NULL packet filter object and make sure it is rejected.
  1097. boost::shared_ptr<PktFilter6Stub> custom_packet_filter;
  1098. EXPECT_THROW(iface_mgr->setPacketFilter(custom_packet_filter),
  1099. isc::dhcp::InvalidPacketFilter);
  1100. // Create valid object and check if it can be set.
  1101. custom_packet_filter.reset(new PktFilter6Stub());
  1102. ASSERT_TRUE(custom_packet_filter);
  1103. ASSERT_NO_THROW(iface_mgr->setPacketFilter(custom_packet_filter));
  1104. // Try to open socket using IfaceMgr. It should call the openSocket()
  1105. // function on the packet filter object we have set.
  1106. IOAddress loAddr("::1");
  1107. int socket1 = 0;
  1108. EXPECT_NO_THROW(
  1109. socket1 = iface_mgr->openSocket(LOOPBACK, loAddr,
  1110. DHCP6_SERVER_PORT + 10000);
  1111. );
  1112. // Check that openSocket function has been actually called on the packet
  1113. // filter object.
  1114. EXPECT_EQ(1, custom_packet_filter->open_socket_count_);
  1115. // Also check that the returned socket descriptor has an expected value.
  1116. EXPECT_EQ(0, socket1);
  1117. // Replacing current packet filter object, while there are sockets open,
  1118. // is not allowed!
  1119. EXPECT_THROW(iface_mgr->setPacketFilter(custom_packet_filter),
  1120. PacketFilterChangeDenied);
  1121. // So, let's close the IPv6 sockets and retry. Now it should succeed.
  1122. iface_mgr->closeSockets(AF_INET6);
  1123. EXPECT_NO_THROW(iface_mgr->setPacketFilter(custom_packet_filter));
  1124. }
  1125. #if defined OS_LINUX || OS_BSD
  1126. // This test is only supported on Linux and BSD systems. It checks
  1127. // if it is possible to use the IfaceMgr to select the packet filter
  1128. // object which can be used to send direct responses to the host
  1129. // which doesn't have an address yet.
  1130. TEST_F(IfaceMgrTest, setMatchingPacketFilter) {
  1131. // Create an instance of IfaceMgr.
  1132. boost::scoped_ptr<NakedIfaceMgr> iface_mgr(new NakedIfaceMgr());
  1133. ASSERT_TRUE(iface_mgr);
  1134. // Let IfaceMgr figure out which Packet Filter to use when
  1135. // direct response capability is not desired. It should pick
  1136. // PktFilterInet on Linux.
  1137. EXPECT_NO_THROW(iface_mgr->setMatchingPacketFilter(false));
  1138. // The PktFilterInet is supposed to report lack of direct
  1139. // response capability.
  1140. EXPECT_FALSE(iface_mgr->isDirectResponseSupported());
  1141. // There is working implementation of direct responses on Linux
  1142. // and BSD (using PktFilterLPF and PktFilterBPF. When direct
  1143. // responses are desired the object of this class should be set.
  1144. EXPECT_NO_THROW(iface_mgr->setMatchingPacketFilter(true));
  1145. // This object should report that direct responses are supported.
  1146. EXPECT_TRUE(iface_mgr->isDirectResponseSupported());
  1147. }
  1148. // This test checks that it is not possible to open two sockets: IP/UDP
  1149. // and raw socket and bind to the same address and port. The
  1150. // raw socket should be opened together with the fallback IP/UDP socket.
  1151. // The fallback socket should fail to open when there is another IP/UDP
  1152. // socket bound to the same address and port. Failing to open the fallback
  1153. // socket should preclude the raw socket from being open.
  1154. TEST_F(IfaceMgrTest, checkPacketFilterRawSocket) {
  1155. IOAddress loAddr("127.0.0.1");
  1156. int socket1 = -1, socket2 = -1;
  1157. // Create two instances of IfaceMgr.
  1158. boost::scoped_ptr<NakedIfaceMgr> iface_mgr1(new NakedIfaceMgr());
  1159. ASSERT_TRUE(iface_mgr1);
  1160. boost::scoped_ptr<NakedIfaceMgr> iface_mgr2(new NakedIfaceMgr());
  1161. ASSERT_TRUE(iface_mgr2);
  1162. // Let IfaceMgr figure out which Packet Filter to use when
  1163. // direct response capability is not desired. It should pick
  1164. // PktFilterInet.
  1165. EXPECT_NO_THROW(iface_mgr1->setMatchingPacketFilter(false));
  1166. // Let's open a loopback socket with handy unpriviliged port number
  1167. socket1 = iface_mgr1->openSocket(LOOPBACK, loAddr,
  1168. DHCP4_SERVER_PORT + 10000);
  1169. EXPECT_GE(socket1, 0);
  1170. // Then the second use PkFilterLPF mode
  1171. EXPECT_NO_THROW(iface_mgr2->setMatchingPacketFilter(true));
  1172. // The socket is open and bound. Another attempt to open socket and
  1173. // bind to the same address and port should result in an exception.
  1174. EXPECT_THROW(
  1175. socket2 = iface_mgr2->openSocket(LOOPBACK, loAddr,
  1176. DHCP4_SERVER_PORT + 10000),
  1177. isc::dhcp::SocketConfigError
  1178. );
  1179. // Surprisingly we managed to open another socket. We have to close it
  1180. // to prevent resource leak.
  1181. if (socket2 >= 0) {
  1182. close(socket2);
  1183. ADD_FAILURE() << "Two sockets opened and bound to the same IP"
  1184. " address and UDP port";
  1185. }
  1186. if (socket1 >= 0) {
  1187. close(socket1);
  1188. }
  1189. }
  1190. #else
  1191. // Note: This test will only run on non-Linux and non-BSD systems.
  1192. // This test checks whether it is possible to use IfaceMgr to figure
  1193. // out which Pakcket Filter object should be used when direct responses
  1194. // to hosts, having no address assigned are desired or not desired.
  1195. // Since direct responses aren't supported on systems other than Linux
  1196. // and BSD the function under test should always set object of
  1197. // PktFilterInet type as current Packet Filter. This object does not
  1198. //support direct responses. Once implementation is added on systems
  1199. // other than BSD and Linux the OS specific version of the test will
  1200. // be removed.
  1201. TEST_F(IfaceMgrTest, setMatchingPacketFilter) {
  1202. // Create an instance of IfaceMgr.
  1203. boost::scoped_ptr<NakedIfaceMgr> iface_mgr(new NakedIfaceMgr());
  1204. ASSERT_TRUE(iface_mgr);
  1205. // Let IfaceMgr figure out which Packet Filter to use when
  1206. // direct response capability is not desired. It should pick
  1207. // PktFilterInet.
  1208. EXPECT_NO_THROW(iface_mgr->setMatchingPacketFilter(false));
  1209. // The PktFilterInet is supposed to report lack of direct
  1210. // response capability.
  1211. EXPECT_FALSE(iface_mgr->isDirectResponseSupported());
  1212. // On non-Linux systems, we are missing the direct traffic
  1213. // implementation. Therefore, we expect that PktFilterInet
  1214. // object will be set.
  1215. EXPECT_NO_THROW(iface_mgr->setMatchingPacketFilter(true));
  1216. // This object should report lack of direct response capability.
  1217. EXPECT_FALSE(iface_mgr->isDirectResponseSupported());
  1218. }
  1219. #endif
  1220. TEST_F(IfaceMgrTest, socket4) {
  1221. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  1222. // Let's assume that every supported OS have lo interface.
  1223. IOAddress loAddr("127.0.0.1");
  1224. // Use unprivileged port (it's convenient for running tests as non-root).
  1225. int socket1 = 0;
  1226. EXPECT_NO_THROW(
  1227. socket1 = ifacemgr->openSocket(LOOPBACK, loAddr, DHCP4_SERVER_PORT + 10000);
  1228. );
  1229. EXPECT_GE(socket1, 0);
  1230. Pkt4 pkt(DHCPDISCOVER, 1234);
  1231. pkt.setIface(LOOPBACK);
  1232. // Expect that we get the socket that we just opened.
  1233. EXPECT_EQ(socket1, ifacemgr->getSocket(pkt).sockfd_);
  1234. close(socket1);
  1235. }
  1236. // This test verifies that IPv4 sockets are open on all interfaces (except
  1237. // loopback), when interfaces are up, running and active (not disabled from
  1238. // the DHCP configuration).
  1239. TEST_F(IfaceMgrTest, openSockets4) {
  1240. NakedIfaceMgr ifacemgr;
  1241. // Remove all real interfaces and create a set of dummy interfaces.
  1242. ifacemgr.createIfaces();
  1243. // Use the custom packet filter object. This object mimics the socket
  1244. // opening operation - the real socket is not open.
  1245. boost::shared_ptr<TestPktFilter> custom_packet_filter(new TestPktFilter());
  1246. ASSERT_TRUE(custom_packet_filter);
  1247. ASSERT_NO_THROW(ifacemgr.setPacketFilter(custom_packet_filter));
  1248. // Simulate opening sockets using the dummy packet filter.
  1249. ASSERT_NO_THROW(ifacemgr.openSockets4(DHCP4_SERVER_PORT, true, NULL));
  1250. // Expect that the sockets are open on both eth0 and eth1.
  1251. EXPECT_EQ(1, ifacemgr.getIface("eth0")->getSockets().size());
  1252. EXPECT_EQ(1, ifacemgr.getIface("eth1")->getSockets().size());
  1253. // Socket shouldn't have been opened on loopback.
  1254. EXPECT_TRUE(ifacemgr.getIface("lo")->getSockets().empty());
  1255. }
  1256. // This test verifies that the socket is not open on the interface which is
  1257. // down, but sockets are open on all other non-loopback interfaces.
  1258. TEST_F(IfaceMgrTest, openSockets4IfaceDown) {
  1259. IfaceMgrTestConfig config(true);
  1260. // Boolean parameters specify that eth0 is:
  1261. // - not a loopback
  1262. // - is "down" (not up)
  1263. // - is not running
  1264. // - is active (is not inactive)
  1265. config.setIfaceFlags("eth0", FlagLoopback(false), FlagUp(false),
  1266. FlagRunning(false), FlagInactive4(false),
  1267. FlagInactive6(false));
  1268. ASSERT_FALSE(IfaceMgr::instance().getIface("eth0")->flag_up_);
  1269. // Install an error handler before trying to open sockets. This handler
  1270. // should be called when the IfaceMgr fails to open socket on an interface
  1271. // on which the server is configured to listen.
  1272. isc::dhcp::IfaceMgrErrorMsgCallback error_handler =
  1273. boost::bind(&IfaceMgrTest::ifaceMgrErrorHandler, this, _1);
  1274. ASSERT_NO_THROW(IfaceMgr::instance().openSockets4(DHCP4_SERVER_PORT, true,
  1275. error_handler));
  1276. // Since the interface is down, an attempt to open a socket should result
  1277. // in error.
  1278. EXPECT_EQ(1, errors_count_);
  1279. // There should be no socket on eth0 open, because interface was down.
  1280. EXPECT_TRUE(IfaceMgr::instance().getIface("eth0")->getSockets().empty());
  1281. // Expecting that the socket is open on eth1 because it was up, running
  1282. // and active.
  1283. EXPECT_EQ(2, IfaceMgr::instance().getIface("eth1")->getSockets().size());
  1284. // Never open socket on loopback interface.
  1285. EXPECT_TRUE(IfaceMgr::instance().getIface("lo")->getSockets().empty());
  1286. }
  1287. // This test verifies that the socket is not open on the interface which is
  1288. // disabled from the DHCP configuration, but sockets are open on all other
  1289. // non-loopback interfaces.
  1290. TEST_F(IfaceMgrTest, openSockets4IfaceInactive) {
  1291. NakedIfaceMgr ifacemgr;
  1292. // Remove all real interfaces and create a set of dummy interfaces.
  1293. ifacemgr.createIfaces();
  1294. boost::shared_ptr<TestPktFilter> custom_packet_filter(new TestPktFilter());
  1295. ASSERT_TRUE(custom_packet_filter);
  1296. ASSERT_NO_THROW(ifacemgr.setPacketFilter(custom_packet_filter));
  1297. // Boolean parameters specify that eth1 is:
  1298. // - not a loopback
  1299. // - is up
  1300. // - is running
  1301. // - is inactive
  1302. ifacemgr.setIfaceFlags("eth1", false, true, true, true, false);
  1303. ASSERT_TRUE(ifacemgr.getIface("eth1")->inactive4_);
  1304. ASSERT_NO_THROW(ifacemgr.openSockets4(DHCP4_SERVER_PORT, true, NULL));
  1305. // The socket on eth0 should be open because interface is up, running and
  1306. // active (not disabled through DHCP configuration, for example).
  1307. EXPECT_EQ(1, ifacemgr.getIface("eth0")->getSockets().size());
  1308. // There should be no socket open on eth1 because it was marked inactive.
  1309. EXPECT_TRUE(ifacemgr.getIface("eth1")->getSockets().empty());
  1310. // Sockets are not open on loopback interfaces too.
  1311. EXPECT_TRUE(ifacemgr.getIface("lo")->getSockets().empty());
  1312. }
  1313. // Test that exception is thrown when trying to bind a new socket to the port
  1314. // and address which is already in use by another socket.
  1315. TEST_F(IfaceMgrTest, openSockets4NoErrorHandler) {
  1316. NakedIfaceMgr ifacemgr;
  1317. // Remove all real interfaces and create a set of dummy interfaces.
  1318. ifacemgr.createIfaces();
  1319. boost::shared_ptr<TestPktFilter> custom_packet_filter(new TestPktFilter());
  1320. ASSERT_TRUE(custom_packet_filter);
  1321. ASSERT_NO_THROW(ifacemgr.setPacketFilter(custom_packet_filter));
  1322. // Open socket on eth1. The openSockets4 should detect that this
  1323. // socket has been already open and an attempt to open another socket
  1324. // and bind to this address and port should fail.
  1325. ASSERT_NO_THROW(ifacemgr.openSocket("eth1", IOAddress("192.0.2.3"),
  1326. DHCP4_SERVER_PORT));
  1327. // The function throws an exception when it tries to open a socket
  1328. // and bind it to the address in use.
  1329. EXPECT_THROW(ifacemgr.openSockets4(DHCP4_SERVER_PORT, true, NULL),
  1330. isc::dhcp::SocketConfigError);
  1331. }
  1332. // Test that the external error handler is called when trying to bind a new
  1333. // socket to the address and port being in use. The sockets on the other
  1334. // interfaces should open just fine.
  1335. TEST_F(IfaceMgrTest, openSocket4ErrorHandler) {
  1336. NakedIfaceMgr ifacemgr;
  1337. // Remove all real interfaces and create a set of dummy interfaces.
  1338. ifacemgr.createIfaces();
  1339. boost::shared_ptr<TestPktFilter> custom_packet_filter(new TestPktFilter());
  1340. ASSERT_TRUE(custom_packet_filter);
  1341. ASSERT_NO_THROW(ifacemgr.setPacketFilter(custom_packet_filter));
  1342. // Open socket on eth0.
  1343. ASSERT_NO_THROW(ifacemgr.openSocket("eth0", IOAddress("10.0.0.1"),
  1344. DHCP4_SERVER_PORT));
  1345. // Install an error handler before trying to open sockets. This handler
  1346. // should be called when the IfaceMgr fails to open socket on eth0.
  1347. isc::dhcp::IfaceMgrErrorMsgCallback error_handler =
  1348. boost::bind(&IfaceMgrTest::ifaceMgrErrorHandler, this, _1);
  1349. // The openSockets4 should detect that there is another socket already
  1350. // open and bound to the same address and port. An attempt to open
  1351. // another socket and bind to this address and port should fail.
  1352. ASSERT_NO_THROW(ifacemgr.openSockets4(DHCP4_SERVER_PORT, true, error_handler));
  1353. // We expect that an error occured when we tried to open a socket on
  1354. // eth0, but the socket on eth1 should open just fine.
  1355. EXPECT_EQ(1, errors_count_);
  1356. // Reset errors count.
  1357. errors_count_ = 0;
  1358. // Now that we have two sockets open, we can try this again but this time
  1359. // we should get two errors: one when opening a socket on eth0, another one
  1360. // when opening a socket on eth1.
  1361. ASSERT_NO_THROW(ifacemgr.openSockets4(DHCP4_SERVER_PORT, true, error_handler));
  1362. EXPECT_EQ(2, errors_count_);
  1363. }
  1364. // This test verifies that the function correctly checks that the v4 socket is
  1365. // open and bound to a specific address.
  1366. TEST_F(IfaceMgrTest, hasOpenSocketForAddress4) {
  1367. NakedIfaceMgr ifacemgr;
  1368. // Remove all real interfaces and create a set of dummy interfaces.
  1369. ifacemgr.createIfaces();
  1370. // Use the custom packet filter object. This object mimics the socket
  1371. // opening operation - the real socket is not open.
  1372. boost::shared_ptr<TestPktFilter> custom_packet_filter(new TestPktFilter());
  1373. ASSERT_TRUE(custom_packet_filter);
  1374. ASSERT_NO_THROW(ifacemgr.setPacketFilter(custom_packet_filter));
  1375. // Simulate opening sockets using the dummy packet filter.
  1376. ASSERT_NO_THROW(ifacemgr.openSockets4(DHCP4_SERVER_PORT, true, NULL));
  1377. // Expect that the sockets are open on both eth0 and eth1.
  1378. ASSERT_EQ(1, ifacemgr.getIface("eth0")->getSockets().size());
  1379. ASSERT_EQ(1, ifacemgr.getIface("eth1")->getSockets().size());
  1380. // Socket shouldn't have been opened on loopback.
  1381. ASSERT_TRUE(ifacemgr.getIface("lo")->getSockets().empty());
  1382. // Check that there are sockets bound to addresses that we have
  1383. // set for interfaces.
  1384. EXPECT_TRUE(ifacemgr.hasOpenSocket(IOAddress("192.0.2.3")));
  1385. EXPECT_TRUE(ifacemgr.hasOpenSocket(IOAddress("10.0.0.1")));
  1386. // Check that there is no socket for the address which is not
  1387. // configured on any interface.
  1388. EXPECT_FALSE(ifacemgr.hasOpenSocket(IOAddress("10.1.1.1")));
  1389. // Check that v4 sockets are open, but no v6 socket is open.
  1390. EXPECT_TRUE(ifacemgr.hasOpenSocket(AF_INET));
  1391. EXPECT_FALSE(ifacemgr.hasOpenSocket(AF_INET6));
  1392. }
  1393. // This test checks that the sockets are open and bound to link local addresses
  1394. // only, if unicast addresses are not specified.
  1395. TEST_F(IfaceMgrTest, openSockets6LinkLocal) {
  1396. NakedIfaceMgr ifacemgr;
  1397. // Remove all real interfaces and create a set of dummy interfaces.
  1398. ifacemgr.createIfaces();
  1399. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1400. ASSERT_TRUE(filter);
  1401. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1402. // Simulate opening sockets using the dummy packet filter.
  1403. bool success = false;
  1404. ASSERT_NO_THROW(success = ifacemgr.openSockets6(DHCP6_SERVER_PORT));
  1405. EXPECT_TRUE(success);
  1406. // Check that the number of sockets is correct on each interface.
  1407. checkSocketsCount6(*ifacemgr.getIface("lo"), 0);
  1408. checkSocketsCount6(*ifacemgr.getIface("eth0"), 0);
  1409. checkSocketsCount6(*ifacemgr.getIface("eth1"), 0);
  1410. // Sockets on eth0 should be bound to link-local and should not be bound
  1411. // to global unicast address, even though this address is configured on
  1412. // the eth0.
  1413. EXPECT_TRUE(ifacemgr.isBound("eth0", "fe80::3a60:77ff:fed5:cdef"));
  1414. EXPECT_FALSE(ifacemgr.isBound("eth0", "2001:db8:1::1"));
  1415. // Socket on eth1 should be bound to link local only.
  1416. EXPECT_TRUE(ifacemgr.isBound("eth1", "fe80::3a60:77ff:fed5:abcd"));
  1417. // If we are on Linux, there is one more socket bound to ff02::1:2
  1418. #if defined OS_LINUX
  1419. EXPECT_TRUE(ifacemgr.isBound("eth0", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1420. EXPECT_TRUE(ifacemgr.isBound("eth1", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1421. #endif
  1422. }
  1423. // This test checks that socket is not open on the interface which doesn't
  1424. // have a link-local address.
  1425. TEST_F(IfaceMgrTest, openSockets6NoLinkLocal) {
  1426. NakedIfaceMgr ifacemgr;
  1427. // Remove all real interfaces and create a set of dummy interfaces.
  1428. ifacemgr.createIfaces();
  1429. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1430. ASSERT_TRUE(filter);
  1431. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1432. // Remove a link local address from eth0. If there is no link-local
  1433. // address, the socket should not open.
  1434. ASSERT_TRUE(ifacemgr.getIface("eth0")->
  1435. delAddress(IOAddress("fe80::3a60:77ff:fed5:cdef")));
  1436. // Simulate opening sockets using the dummy packet filter.
  1437. bool success = false;
  1438. ASSERT_NO_THROW(success = ifacemgr.openSockets6(DHCP6_SERVER_PORT));
  1439. EXPECT_TRUE(success);
  1440. // Check that the number of sockets is correct on each interface.
  1441. checkSocketsCount6(*ifacemgr.getIface("lo"), 0);
  1442. // The thrid parameter specifies that the number of link-local
  1443. // addresses for eth0 is equal to 0.
  1444. checkSocketsCount6(*ifacemgr.getIface("eth0"), 0, 0);
  1445. checkSocketsCount6(*ifacemgr.getIface("eth1"), 0, 1);
  1446. // There should be no sockets open on eth0 because it neither has
  1447. // link-local nor global unicast addresses.
  1448. EXPECT_FALSE(ifacemgr.isBound("eth0", "fe80::3a60:77ff:fed5:cdef"));
  1449. EXPECT_FALSE(ifacemgr.isBound("eth0", "2001:db8:1::1"));
  1450. // Socket on eth1 should be bound to link local only.
  1451. EXPECT_TRUE(ifacemgr.isBound("eth1", "fe80::3a60:77ff:fed5:abcd"));
  1452. // If we are on Linux, there is one more socket bound to ff02::1:2
  1453. #if defined OS_LINUX
  1454. EXPECT_FALSE(ifacemgr.isBound("eth0", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1455. #endif
  1456. }
  1457. // This test checks that socket is open on the non-muticast-capable
  1458. // interface. This socket simply doesn't join multicast group.
  1459. TEST_F(IfaceMgrTest, openSockets6NotMulticast) {
  1460. NakedIfaceMgr ifacemgr;
  1461. // Remove all real interfaces and create a set of dummy interfaces.
  1462. ifacemgr.createIfaces();
  1463. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1464. ASSERT_TRUE(filter);
  1465. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1466. // Make eth0 multicast-incapable.
  1467. ifacemgr.getIface("eth0")->flag_multicast_ = false;
  1468. // Simulate opening sockets using the dummy packet filter.
  1469. bool success = false;
  1470. ASSERT_NO_THROW(success = ifacemgr.openSockets6(DHCP6_SERVER_PORT));
  1471. EXPECT_TRUE(success);
  1472. // Check that the number of sockets is correct on each interface.
  1473. checkSocketsCount6(*ifacemgr.getIface("lo"), 0);
  1474. checkSocketsCount6(*ifacemgr.getIface("eth0"), 0);
  1475. checkSocketsCount6(*ifacemgr.getIface("eth1"), 0);
  1476. // Sockets on eth0 should be bound to link-local and should not be bound
  1477. // to global unicast address, even though this address is configured on
  1478. // the eth0.
  1479. EXPECT_TRUE(ifacemgr.isBound("eth0", "fe80::3a60:77ff:fed5:cdef"));
  1480. EXPECT_FALSE(ifacemgr.isBound("eth0", "2001:db8:1::1"));
  1481. // The eth0 is not a multicast-capable interface, so the socket should
  1482. // not be bound to the multicast address.
  1483. EXPECT_FALSE(ifacemgr.isBound("eth0", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1484. // Socket on eth1 should be bound to link local only.
  1485. EXPECT_TRUE(ifacemgr.isBound("eth1", "fe80::3a60:77ff:fed5:abcd"));
  1486. // If we are on Linux, there is one more socket bound to ff02::1:2
  1487. // on eth1.
  1488. #if defined OS_LINUX
  1489. EXPECT_TRUE(ifacemgr.isBound("eth1", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1490. #endif
  1491. }
  1492. // This test checks that the sockets are opened and bound to link local
  1493. // and unicast addresses which have been explicitly specified.
  1494. TEST_F(IfaceMgrTest, openSockets6Unicast) {
  1495. NakedIfaceMgr ifacemgr;
  1496. // Remove all real interfaces and create a set of dummy interfaces.
  1497. ifacemgr.createIfaces();
  1498. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1499. ASSERT_TRUE(filter);
  1500. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1501. // Configure the eth0 to open socket on the unicast address, apart
  1502. // from link-local address.
  1503. ifacemgr.getIface("eth0")->addUnicast(IOAddress("2001:db8:1::1"));
  1504. // Simulate opening sockets using the dummy packet filter.
  1505. bool success = false;
  1506. ASSERT_NO_THROW(success = ifacemgr.openSockets6(DHCP6_SERVER_PORT));
  1507. EXPECT_TRUE(success);
  1508. // Check that we have correct number of sockets on each interface.
  1509. checkSocketsCount6(*ifacemgr.getIface("lo"), 0);
  1510. checkSocketsCount6(*ifacemgr.getIface("eth0"), 1); // one unicast address.
  1511. checkSocketsCount6(*ifacemgr.getIface("eth1"), 0);
  1512. // eth0 should have two sockets, one bound to link-local, another one
  1513. // bound to unicast address.
  1514. EXPECT_TRUE(ifacemgr.isBound("eth0", "fe80::3a60:77ff:fed5:cdef"));
  1515. EXPECT_TRUE(ifacemgr.isBound("eth0", "2001:db8:1::1"));
  1516. // eth1 should have one socket, bound to link-local address.
  1517. EXPECT_TRUE(ifacemgr.isBound("eth1", "fe80::3a60:77ff:fed5:abcd"));
  1518. // If we are on Linux, there is one more socket bound to ff02::1:2
  1519. #if defined OS_LINUX
  1520. EXPECT_TRUE(ifacemgr.isBound("eth0", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1521. EXPECT_TRUE(ifacemgr.isBound("eth1", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1522. #endif
  1523. }
  1524. // This test checks that the socket is open and bound to a global unicast
  1525. // address if the link-local address does not exist for the particular
  1526. // interface.
  1527. TEST_F(IfaceMgrTest, openSockets6UnicastOnly) {
  1528. NakedIfaceMgr ifacemgr;
  1529. // Remove all real interfaces and create a set of dummy interfaces.
  1530. ifacemgr.createIfaces();
  1531. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1532. ASSERT_TRUE(filter);
  1533. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1534. // Configure the eth0 to open socket on the unicast address, apart
  1535. // from link-local address.
  1536. ifacemgr.getIface("eth0")->addUnicast(IOAddress("2001:db8:1::1"));
  1537. // Explicitly remove the link-local address from eth0.
  1538. ASSERT_TRUE(ifacemgr.getIface("eth0")->
  1539. delAddress(IOAddress("fe80::3a60:77ff:fed5:cdef")));
  1540. // Simulate opening sockets using the dummy packet filter.
  1541. bool success = false;
  1542. ASSERT_NO_THROW(success = ifacemgr.openSockets6(DHCP6_SERVER_PORT));
  1543. EXPECT_TRUE(success);
  1544. // Check that we have correct number of sockets on each interface.
  1545. checkSocketsCount6(*ifacemgr.getIface("lo"), 0);
  1546. checkSocketsCount6(*ifacemgr.getIface("eth0"), 1, 0);
  1547. checkSocketsCount6(*ifacemgr.getIface("eth1"), 0);
  1548. // The link-local address is not present on eth0. Therefore, no socket
  1549. // must be bound to this address, nor to multicast address.
  1550. EXPECT_FALSE(ifacemgr.isBound("eth0", "fe80::3a60:77ff:fed5:cdef"));
  1551. EXPECT_FALSE(ifacemgr.isBound("eth0", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1552. // There should be one socket bound to unicast address.
  1553. EXPECT_TRUE(ifacemgr.isBound("eth0", "2001:db8:1::1"));
  1554. // eth1 should have one socket, bound to link-local address.
  1555. EXPECT_TRUE(ifacemgr.isBound("eth1", "fe80::3a60:77ff:fed5:abcd"));
  1556. // If we are on Linux, there is one more socket bound to ff02::1:2
  1557. #if defined OS_LINUX
  1558. EXPECT_TRUE(ifacemgr.isBound("eth1", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1559. #endif
  1560. }
  1561. // This test checks that no sockets are open for the interface which is down.
  1562. TEST_F(IfaceMgrTest, openSockets6IfaceDown) {
  1563. NakedIfaceMgr ifacemgr;
  1564. // Remove all real interfaces and create a set of dummy interfaces.
  1565. ifacemgr.createIfaces();
  1566. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1567. ASSERT_TRUE(filter);
  1568. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1569. // Configure the eth0 to open socket on the unicast address, apart
  1570. // from link-local address.
  1571. ifacemgr.getIface("eth0")->addUnicast(IOAddress("2001:db8:1::1"));
  1572. // Boolean parameters specify that eth0 is:
  1573. // - not a loopback
  1574. // - is "down" (not up)
  1575. // - is not running
  1576. // - is active for both v4 and v6
  1577. ifacemgr.setIfaceFlags("eth0", false, false, false, false, false);
  1578. // Install an error handler before trying to open sockets. This handler
  1579. // should be called when the IfaceMgr fails to open socket on eth0.
  1580. isc::dhcp::IfaceMgrErrorMsgCallback error_handler =
  1581. boost::bind(&IfaceMgrTest::ifaceMgrErrorHandler, this, _1);
  1582. // Simulate opening sockets using the dummy packet filter.
  1583. bool success = false;
  1584. ASSERT_NO_THROW(success = ifacemgr.openSockets6(DHCP6_SERVER_PORT,
  1585. error_handler));
  1586. EXPECT_TRUE(success);
  1587. // Opening socket on the interface which is not configured, should
  1588. // result in error.
  1589. EXPECT_EQ(1, errors_count_);
  1590. // Check that we have correct number of sockets on each interface.
  1591. checkSocketsCount6(*ifacemgr.getIface("lo"), 0);
  1592. // There should be no sockets on eth0 because interface is down.
  1593. ASSERT_TRUE(ifacemgr.getIface("eth0")->getSockets().empty());
  1594. checkSocketsCount6(*ifacemgr.getIface("eth1"), 0);
  1595. // eth0 should have no sockets because the interface is down.
  1596. EXPECT_FALSE(ifacemgr.isBound("eth0", "fe80::3a60:77ff:fed5:cdef"));
  1597. EXPECT_FALSE(ifacemgr.isBound("eth0", "2001:db8:1::1"));
  1598. EXPECT_FALSE(ifacemgr.isBound("eth0", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1599. // eth1 should have one socket, bound to link-local address.
  1600. EXPECT_TRUE(ifacemgr.isBound("eth1", "fe80::3a60:77ff:fed5:abcd"));
  1601. // If we are on Linux, there is one more socket bound to ff02::1:2
  1602. #if defined OS_LINUX
  1603. EXPECT_TRUE(ifacemgr.isBound("eth1", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1604. #endif
  1605. }
  1606. // This test checks that no sockets are open for the interface which is
  1607. // inactive.
  1608. TEST_F(IfaceMgrTest, openSockets6IfaceInactive) {
  1609. NakedIfaceMgr ifacemgr;
  1610. // Remove all real interfaces and create a set of dummy interfaces.
  1611. ifacemgr.createIfaces();
  1612. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1613. ASSERT_TRUE(filter);
  1614. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1615. // Configure the eth0 to open socket on the unicast address, apart
  1616. // from link-local address.
  1617. ifacemgr.getIface("eth0")->addUnicast(IOAddress("2001:db8:1::1"));
  1618. // Boolean parameters specify that eth1 is:
  1619. // - not a loopback
  1620. // - is up
  1621. // - is running
  1622. // - is active for v4
  1623. // - is inactive for v6
  1624. ifacemgr.setIfaceFlags("eth1", false, true, true, false, true);
  1625. // Simulate opening sockets using the dummy packet filter.
  1626. bool success = false;
  1627. ASSERT_NO_THROW(success = ifacemgr.openSockets6(DHCP6_SERVER_PORT));
  1628. EXPECT_TRUE(success);
  1629. // Check that we have correct number of sockets on each interface.
  1630. checkSocketsCount6(*ifacemgr.getIface("lo"), 0);
  1631. checkSocketsCount6(*ifacemgr.getIface("eth0"), 1); // one unicast address
  1632. // There should be no sockets on eth1 because interface is inactive
  1633. ASSERT_TRUE(ifacemgr.getIface("eth1")->getSockets().empty());
  1634. // eth0 should have one socket bound to a link-local address, another one
  1635. // bound to unicast address.
  1636. EXPECT_TRUE(ifacemgr.isBound("eth0", "fe80::3a60:77ff:fed5:cdef"));
  1637. EXPECT_TRUE(ifacemgr.isBound("eth0", "2001:db8:1::1"));
  1638. // eth1 shouldn't have a socket bound to link local address because
  1639. // interface is inactive.
  1640. EXPECT_FALSE(ifacemgr.isBound("eth1", "fe80::3a60:77ff:fed5:abcd"));
  1641. EXPECT_FALSE(ifacemgr.isBound("eth1", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1642. // If we are on Linux, there is one more socket bound to ff02::1:2
  1643. #if defined OS_LINUX
  1644. EXPECT_TRUE(ifacemgr.isBound("eth0", ALL_DHCP_RELAY_AGENTS_AND_SERVERS));
  1645. #endif
  1646. }
  1647. // Test that the openSockets6 function does not throw if there are no interfaces
  1648. // detected. This function is expected to return false.
  1649. TEST_F(IfaceMgrTest, openSockets6NoIfaces) {
  1650. NakedIfaceMgr ifacemgr;
  1651. // Remove existing interfaces.
  1652. ifacemgr.getIfacesLst().clear();
  1653. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1654. ASSERT_TRUE(filter);
  1655. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1656. // This value indicates if at least one socket opens. There are no
  1657. // interfaces, so it should be set to false.
  1658. bool socket_open = false;
  1659. ASSERT_NO_THROW(socket_open = ifacemgr.openSockets6(DHCP6_SERVER_PORT));
  1660. EXPECT_FALSE(socket_open);
  1661. }
  1662. // Test that the external error handler is called when trying to bind a new
  1663. // socket to the address and port being in use. The sockets on the other
  1664. // interfaces should open just fine.
  1665. TEST_F(IfaceMgrTest, openSocket6ErrorHandler) {
  1666. NakedIfaceMgr ifacemgr;
  1667. // Remove all real interfaces and create a set of dummy interfaces.
  1668. ifacemgr.createIfaces();
  1669. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1670. ASSERT_TRUE(filter);
  1671. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1672. // Open multicast socket on eth0.
  1673. ASSERT_NO_THROW(ifacemgr.openSocket("eth0",
  1674. IOAddress("fe80::3a60:77ff:fed5:cdef"),
  1675. DHCP6_SERVER_PORT, true));
  1676. // Install an error handler before trying to open sockets. This handler
  1677. // should be called when the IfaceMgr fails to open socket on eth0.
  1678. isc::dhcp::IfaceMgrErrorMsgCallback error_handler =
  1679. boost::bind(&IfaceMgrTest::ifaceMgrErrorHandler, this, _1);
  1680. // The openSockets6 should detect that a socket has been already
  1681. // opened on eth0 and an attempt to open another socket and bind to
  1682. // the same address and port should fail.
  1683. ASSERT_NO_THROW(ifacemgr.openSockets6(DHCP6_SERVER_PORT, error_handler));
  1684. // We expect that an error occured when we tried to open a socket on
  1685. // eth0, but the socket on eth1 should open just fine.
  1686. EXPECT_EQ(1, errors_count_);
  1687. // Reset errors count.
  1688. errors_count_ = 0;
  1689. // Now that we have two sockets open, we can try this again but this time
  1690. // we should get two errors: one when opening a socket on eth0, another one
  1691. // when opening a socket on eth1.
  1692. ASSERT_NO_THROW(ifacemgr.openSockets6(DHCP6_SERVER_PORT, error_handler));
  1693. EXPECT_EQ(2, errors_count_);
  1694. }
  1695. // This test verifies that the function correctly checks that the v6 socket is
  1696. // open and bound to a specific address.
  1697. TEST_F(IfaceMgrTest, hasOpenSocketForAddress6) {
  1698. NakedIfaceMgr ifacemgr;
  1699. // Remove all real interfaces and create a set of dummy interfaces.
  1700. ifacemgr.createIfaces();
  1701. boost::shared_ptr<PktFilter6Stub> filter(new PktFilter6Stub());
  1702. ASSERT_TRUE(filter);
  1703. ASSERT_NO_THROW(ifacemgr.setPacketFilter(filter));
  1704. // Simulate opening sockets using the dummy packet filter.
  1705. bool success = false;
  1706. ASSERT_NO_THROW(success = ifacemgr.openSockets6(DHCP6_SERVER_PORT));
  1707. EXPECT_TRUE(success);
  1708. // Make sure that the sockets are bound as expected.
  1709. ASSERT_TRUE(ifacemgr.isBound("eth0", "fe80::3a60:77ff:fed5:cdef"));
  1710. EXPECT_TRUE(ifacemgr.isBound("eth1", "fe80::3a60:77ff:fed5:abcd"));
  1711. // There should be v6 sockets only, no v4 sockets.
  1712. EXPECT_TRUE(ifacemgr.hasOpenSocket(AF_INET6));
  1713. EXPECT_FALSE(ifacemgr.hasOpenSocket(AF_INET));
  1714. // Check that there are sockets bound to the addresses we have configured
  1715. // for interfaces.
  1716. EXPECT_TRUE(ifacemgr.hasOpenSocket(IOAddress("fe80::3a60:77ff:fed5:cdef")));
  1717. EXPECT_TRUE(ifacemgr.hasOpenSocket(IOAddress("fe80::3a60:77ff:fed5:abcd")));
  1718. // Check that there is no socket bound to the address which hasn't been
  1719. // configured on any interface.
  1720. EXPECT_FALSE(ifacemgr.hasOpenSocket(IOAddress("fe80::3a60:77ff:feed:1")));
  1721. }
  1722. // Test the Iface structure itself
  1723. TEST_F(IfaceMgrTest, iface) {
  1724. boost::scoped_ptr<Iface> iface;
  1725. EXPECT_NO_THROW(iface.reset(new Iface("eth0",1)));
  1726. EXPECT_EQ("eth0", iface->getName());
  1727. EXPECT_EQ(1, iface->getIndex());
  1728. EXPECT_EQ("eth0/1", iface->getFullName());
  1729. // Let's make a copy of this address collection.
  1730. Iface::AddressCollection addrs = iface->getAddresses();
  1731. EXPECT_EQ(0, addrs.size());
  1732. IOAddress addr1("192.0.2.6");
  1733. iface->addAddress(addr1);
  1734. addrs = iface->getAddresses();
  1735. ASSERT_EQ(1, addrs.size());
  1736. EXPECT_EQ("192.0.2.6", addrs.begin()->get().toText());
  1737. // No such address, should return false.
  1738. EXPECT_FALSE(iface->delAddress(IOAddress("192.0.8.9")));
  1739. // This address is present, delete it!
  1740. EXPECT_TRUE(iface->delAddress(IOAddress("192.0.2.6")));
  1741. // Not really necessary, previous reference still points to the same
  1742. // collection. Let's do it anyway, as test code may serve as example
  1743. // usage code as well.
  1744. addrs = iface->getAddresses();
  1745. EXPECT_EQ(0, addrs.size());
  1746. EXPECT_NO_THROW(iface.reset());
  1747. }
  1748. TEST_F(IfaceMgrTest, iface_methods) {
  1749. Iface iface("foo", 1234);
  1750. iface.setHWType(42);
  1751. EXPECT_EQ(42, iface.getHWType());
  1752. uint8_t mac[Iface::MAX_MAC_LEN+10];
  1753. for (int i = 0; i < Iface::MAX_MAC_LEN + 10; i++)
  1754. mac[i] = 255 - i;
  1755. EXPECT_EQ("foo", iface.getName());
  1756. EXPECT_EQ(1234, iface.getIndex());
  1757. // MAC is too long. Exception should be thrown and
  1758. // MAC length should not be set.
  1759. EXPECT_THROW(
  1760. iface.setMac(mac, Iface::MAX_MAC_LEN + 1),
  1761. OutOfRange
  1762. );
  1763. // MAC length should stay not set as excep
  1764. EXPECT_EQ(0, iface.getMacLen());
  1765. // Setting maximum length MAC should be ok.
  1766. iface.setMac(mac, Iface::MAX_MAC_LEN);
  1767. // For some reason constants cannot be used directly in EXPECT_EQ
  1768. // as this produces linking error.
  1769. size_t len = Iface::MAX_MAC_LEN;
  1770. EXPECT_EQ(len, iface.getMacLen());
  1771. EXPECT_EQ(0, memcmp(mac, iface.getMac(), iface.getMacLen()));
  1772. }
  1773. TEST_F(IfaceMgrTest, socketInfo) {
  1774. // Check that socketinfo for IPv4 socket is functional
  1775. SocketInfo sock1(IOAddress("192.0.2.56"), DHCP4_SERVER_PORT + 7, 7);
  1776. EXPECT_EQ(7, sock1.sockfd_);
  1777. EXPECT_EQ(-1, sock1.fallbackfd_);
  1778. EXPECT_EQ("192.0.2.56", sock1.addr_.toText());
  1779. EXPECT_EQ(AF_INET, sock1.family_);
  1780. EXPECT_EQ(DHCP4_SERVER_PORT + 7, sock1.port_);
  1781. // Check that non-default value of the fallback socket descriptor is set
  1782. SocketInfo sock2(IOAddress("192.0.2.53"), DHCP4_SERVER_PORT + 8, 8, 10);
  1783. EXPECT_EQ(8, sock2.sockfd_);
  1784. EXPECT_EQ(10, sock2.fallbackfd_);
  1785. EXPECT_EQ("192.0.2.53", sock2.addr_.toText());
  1786. EXPECT_EQ(AF_INET, sock2.family_);
  1787. EXPECT_EQ(DHCP4_SERVER_PORT + 8, sock2.port_);
  1788. // Check that socketinfo for IPv6 socket is functional
  1789. SocketInfo sock3(IOAddress("2001:db8:1::56"), DHCP4_SERVER_PORT + 9, 9);
  1790. EXPECT_EQ(9, sock3.sockfd_);
  1791. EXPECT_EQ(-1, sock3.fallbackfd_);
  1792. EXPECT_EQ("2001:db8:1::56", sock3.addr_.toText());
  1793. EXPECT_EQ(AF_INET6, sock3.family_);
  1794. EXPECT_EQ(DHCP4_SERVER_PORT + 9, sock3.port_);
  1795. // Now let's test if IfaceMgr handles socket info properly
  1796. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  1797. IfacePtr loopback = ifacemgr->getIface(LOOPBACK);
  1798. ASSERT_TRUE(loopback);
  1799. loopback->addSocket(sock1);
  1800. loopback->addSocket(sock2);
  1801. loopback->addSocket(sock3);
  1802. Pkt6 pkt6(DHCPV6_REPLY, 123456);
  1803. // pkt6 does not have interface set yet
  1804. EXPECT_THROW(
  1805. ifacemgr->getSocket(pkt6),
  1806. IfaceNotFound
  1807. );
  1808. // Try to send over non-existing interface
  1809. pkt6.setIface("nosuchinterface45");
  1810. EXPECT_THROW(
  1811. ifacemgr->getSocket(pkt6),
  1812. IfaceNotFound
  1813. );
  1814. // This will work
  1815. pkt6.setIface(LOOPBACK);
  1816. EXPECT_EQ(9, ifacemgr->getSocket(pkt6));
  1817. bool deleted = false;
  1818. EXPECT_NO_THROW(
  1819. deleted = ifacemgr->getIface(LOOPBACK)->delSocket(9);
  1820. );
  1821. EXPECT_EQ(true, deleted);
  1822. // It should throw again, there's no usable socket anymore
  1823. EXPECT_THROW(
  1824. ifacemgr->getSocket(pkt6),
  1825. SocketNotFound
  1826. );
  1827. // Repeat for pkt4
  1828. Pkt4 pkt4(DHCPDISCOVER, 1);
  1829. // pkt4 does not have interface set yet.
  1830. EXPECT_THROW(
  1831. ifacemgr->getSocket(pkt4),
  1832. IfaceNotFound
  1833. );
  1834. // Try to send over non-existing interface.
  1835. pkt4.setIface("nosuchinterface45");
  1836. EXPECT_THROW(
  1837. ifacemgr->getSocket(pkt4),
  1838. IfaceNotFound
  1839. );
  1840. // Socket info is set, packet has well defined interface. It should work.
  1841. pkt4.setIface(LOOPBACK);
  1842. EXPECT_EQ(7, ifacemgr->getSocket(pkt4).sockfd_);
  1843. // Set the local address to check if the socket for this address will
  1844. // be returned.
  1845. pkt4.setLocalAddr(IOAddress("192.0.2.56"));
  1846. EXPECT_EQ(7, ifacemgr->getSocket(pkt4).sockfd_);
  1847. // Modify the local address and expect that the other socket will be
  1848. // returned.
  1849. pkt4.setLocalAddr(IOAddress("192.0.2.53"));
  1850. EXPECT_EQ(8, ifacemgr->getSocket(pkt4).sockfd_);
  1851. EXPECT_NO_THROW(
  1852. ifacemgr->getIface(LOOPBACK)->delSocket(7);
  1853. ifacemgr->getIface(LOOPBACK)->delSocket(8);
  1854. );
  1855. // It should throw again, there's no usable socket anymore.
  1856. EXPECT_THROW(
  1857. ifacemgr->getSocket(pkt4),
  1858. SocketNotFound
  1859. );
  1860. }
  1861. #if defined(OS_BSD)
  1862. #include <net/if_dl.h>
  1863. #endif
  1864. #include <sys/socket.h>
  1865. #include <net/if.h>
  1866. #include <ifaddrs.h>
  1867. /// @brief Checks the index of this interface
  1868. /// @param iface Kea interface structure to be checked
  1869. /// @param ifptr original structure returned by getifaddrs
  1870. /// @return true if index is returned properly
  1871. bool
  1872. checkIfIndex(const Iface & iface,
  1873. struct ifaddrs *& ifptr) {
  1874. return (iface.getIndex() == if_nametoindex(ifptr->ifa_name));
  1875. }
  1876. /// @brief Checks if the interface has proper flags set
  1877. /// @param iface Kea interface structure to be checked
  1878. /// @param ifptr original structure returned by getifaddrs
  1879. /// @return true if flags are set properly
  1880. bool
  1881. checkIfFlags(const Iface & iface,
  1882. struct ifaddrs *& ifptr) {
  1883. bool flag_loopback_ = ifptr->ifa_flags & IFF_LOOPBACK;
  1884. bool flag_up_ = ifptr->ifa_flags & IFF_UP;
  1885. bool flag_running_ = ifptr->ifa_flags & IFF_RUNNING;
  1886. bool flag_multicast_ = ifptr->ifa_flags & IFF_MULTICAST;
  1887. return ((iface.flag_loopback_ == flag_loopback_) &&
  1888. (iface.flag_up_ == flag_up_) &&
  1889. (iface.flag_running_ == flag_running_) &&
  1890. (iface.flag_multicast_ == flag_multicast_));
  1891. }
  1892. /// @brief Checks if MAC Address/IP Addresses are properly well formed
  1893. /// @param iface Kea interface structure to be checked
  1894. /// @param ifptr original structure returned by getifaddrs
  1895. /// @return true if addresses are returned properly
  1896. bool
  1897. checkIfAddrs(const Iface & iface, struct ifaddrs *& ifptr) {
  1898. const unsigned char * p = 0;
  1899. #if defined(OS_LINUX)
  1900. // Workaround for Linux ...
  1901. if(ifptr->ifa_data != 0) {
  1902. // We avoid localhost as it has no MAC Address
  1903. if (!strncmp(iface.getName().c_str(), "lo", 2)) {
  1904. return (true);
  1905. }
  1906. struct ifreq ifr;
  1907. memset(& ifr.ifr_name, 0, sizeof ifr.ifr_name);
  1908. strncpy(ifr.ifr_name, iface.getName().c_str(), sizeof ifr.ifr_name);
  1909. int s = -1; // Socket descriptor
  1910. if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
  1911. isc_throw(Unexpected, "Cannot create AF_INET socket");
  1912. }
  1913. if (ioctl(s, SIOCGIFHWADDR, & ifr) < 0) {
  1914. close(s);
  1915. isc_throw(Unexpected, "Cannot set SIOCGIFHWADDR flag");
  1916. }
  1917. const uint8_t * p =
  1918. reinterpret_cast<uint8_t *>(ifr.ifr_ifru.ifru_hwaddr.sa_data);
  1919. close(s);
  1920. /// @todo: Check MAC address length. For some interfaces it is
  1921. /// different than 6. Some have 0, while some exotic ones (like
  1922. /// infiniband) have 20.
  1923. return (!memcmp(p, iface.getMac(), iface.getMacLen()));
  1924. }
  1925. #endif
  1926. if(!ifptr->ifa_addr) {
  1927. return (false);
  1928. }
  1929. switch(ifptr->ifa_addr->sa_family) {
  1930. #if defined(OS_BSD)
  1931. case AF_LINK: {
  1932. // We avoid localhost as it has no MAC Address
  1933. if (!strncmp(iface.getName().c_str(), "lo", 2)) {
  1934. return (true);
  1935. }
  1936. struct sockaddr_dl * hwdata =
  1937. reinterpret_cast<struct sockaddr_dl *>(ifptr->ifa_addr);
  1938. p = reinterpret_cast<uint8_t *>(LLADDR(hwdata));
  1939. // Extract MAC address length
  1940. if (hwdata->sdl_alen != iface.getMacLen()) {
  1941. return (false);
  1942. }
  1943. return (!memcmp(p, iface.getMac(), hwdata->sdl_alen));
  1944. }
  1945. #endif
  1946. case AF_INET: {
  1947. struct sockaddr_in * v4data =
  1948. reinterpret_cast<struct sockaddr_in *>(ifptr->ifa_addr);
  1949. p = reinterpret_cast<uint8_t *>(& v4data->sin_addr);
  1950. IOAddress addrv4 = IOAddress::fromBytes(AF_INET, p);
  1951. BOOST_FOREACH(Iface::Address a, iface.getAddresses()) {
  1952. if(a.get().isV4() && (a.get()) == addrv4) {
  1953. return (true);
  1954. }
  1955. }
  1956. return (false);
  1957. }
  1958. case AF_INET6: {
  1959. struct sockaddr_in6 * v6data =
  1960. reinterpret_cast<struct sockaddr_in6 *>(ifptr->ifa_addr);
  1961. p = reinterpret_cast<uint8_t *>(& v6data->sin6_addr);
  1962. IOAddress addrv6 = IOAddress::fromBytes(AF_INET6, p);
  1963. BOOST_FOREACH(Iface::Address a, iface.getAddresses()) {
  1964. if (a.get().isV6() && (a.get() == addrv6)) {
  1965. return (true);
  1966. }
  1967. }
  1968. return (false);
  1969. }
  1970. default:
  1971. return (true);
  1972. }
  1973. }
  1974. /// This test checks that the IfaceMgr detects interfaces correctly and
  1975. /// that detected interfaces have correct properties.
  1976. TEST_F(IfaceMgrTest, detectIfaces) {
  1977. NakedIfaceMgr ifacemgr;
  1978. // We are using struct ifaddrs as it is the only good portable one
  1979. // ifreq and ioctls are far from portabe. For BSD ifreq::ifa_flags field
  1980. // is only a short which, nowadays, can be negative
  1981. struct ifaddrs *iflist = 0, *ifptr = 0;
  1982. ASSERT_EQ(0, getifaddrs(&iflist))
  1983. << "Unit test failed to detect interfaces.";
  1984. // Go over all interfaces detected by the unit test and see if they
  1985. // match with the interfaces detected by IfaceMgr.
  1986. for (ifptr = iflist; ifptr != 0; ifptr = ifptr->ifa_next) {
  1987. // When more than one IPv4 address is assigned to the particular
  1988. // physical interface, virtual interfaces may be created for each
  1989. // additional IPv4 address. For example, when multiple addresses
  1990. // are assigned to the eth0 interface, additional virtual interfaces
  1991. // will be eth0:0, eth0:1 etc. This is the case on some Linux
  1992. // distributions. The getifaddrs will return virtual interfaces,
  1993. // with single address each, but the Netlink-based implementation
  1994. // (used by IfaceMgr) will rather hold a list of physical interfaces
  1995. // with multiple IPv4 addresses assigned. This means that the test
  1996. // can't use a name of the interface returned by getifaddrs to match
  1997. // with the interface name held by IfaceMgr. Instead, we use the
  1998. // index of the interface because the virtual interfaces have the
  1999. // same indexes as the physical interfaces.
  2000. IfacePtr i = ifacemgr.getIface(if_nametoindex(ifptr->ifa_name));
  2001. // If the given interface was also detected by the IfaceMgr,
  2002. // check that its properties are correct.
  2003. if (i != NULL) {
  2004. // Check if interface index is reported properly
  2005. EXPECT_TRUE(checkIfIndex(*i, ifptr))
  2006. << "Non-matching index of the detected interface "
  2007. << i->getName();
  2008. // Check if flags are reported properly
  2009. EXPECT_TRUE(checkIfFlags(*i, ifptr))
  2010. << "Non-matching flags of the detected interface "
  2011. << i->getName();
  2012. // Check if addresses are reported properly
  2013. EXPECT_TRUE(checkIfAddrs(*i, ifptr))
  2014. << "Non-matching addresses on the detected interface "
  2015. << i->getName();
  2016. } else {
  2017. // The interface detected here seems to be missing in the
  2018. // IfaceMgr.
  2019. ADD_FAILURE() << "Interface " << ifptr->ifa_name
  2020. << " not detected by the Interface Manager";
  2021. }
  2022. }
  2023. freeifaddrs(iflist);
  2024. iflist = 0;
  2025. }
  2026. volatile bool callback_ok;
  2027. volatile bool callback2_ok;
  2028. void my_callback(void) {
  2029. callback_ok = true;
  2030. }
  2031. void my_callback2(void) {
  2032. callback2_ok = true;
  2033. }
  2034. // Tests if a single external socket and its callback can be passed and
  2035. // it is supported properly by receive4() method.
  2036. TEST_F(IfaceMgrTest, SingleExternalSocket4) {
  2037. callback_ok = false;
  2038. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  2039. // Create pipe and register it as extra socket
  2040. int pipefd[2];
  2041. EXPECT_TRUE(pipe(pipefd) == 0);
  2042. EXPECT_NO_THROW(ifacemgr->addExternalSocket(pipefd[0], my_callback));
  2043. Pkt4Ptr pkt4;
  2044. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  2045. // Our callback should not be called this time (there was no data)
  2046. EXPECT_FALSE(callback_ok);
  2047. // IfaceMgr should not process control socket data as incoming packets
  2048. EXPECT_FALSE(pkt4);
  2049. // Now, send some data over pipe (38 bytes)
  2050. EXPECT_EQ(38, write(pipefd[1], "Hi, this is a message sent over a pipe", 38));
  2051. // ... and repeat
  2052. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  2053. // IfaceMgr should not process control socket data as incoming packets
  2054. EXPECT_FALSE(pkt4);
  2055. // There was some data, so this time callback should be called
  2056. EXPECT_TRUE(callback_ok);
  2057. // close both pipe ends
  2058. close(pipefd[1]);
  2059. close(pipefd[0]);
  2060. }
  2061. // Tests if multiple external sockets and their callbacks can be passed and
  2062. // it is supported properly by receive4() method.
  2063. TEST_F(IfaceMgrTest, MiltipleExternalSockets4) {
  2064. callback_ok = false;
  2065. callback2_ok = false;
  2066. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  2067. // Create first pipe and register it as extra socket
  2068. int pipefd[2];
  2069. EXPECT_TRUE(pipe(pipefd) == 0);
  2070. EXPECT_NO_THROW(ifacemgr->addExternalSocket(pipefd[0], my_callback));
  2071. // Let's create a second pipe and register it as well
  2072. int secondpipe[2];
  2073. EXPECT_TRUE(pipe(secondpipe) == 0);
  2074. EXPECT_NO_THROW(ifacemgr->addExternalSocket(secondpipe[0], my_callback2));
  2075. Pkt4Ptr pkt4;
  2076. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  2077. // Our callbacks should not be called this time (there was no data)
  2078. EXPECT_FALSE(callback_ok);
  2079. EXPECT_FALSE(callback2_ok);
  2080. // IfaceMgr should not process control socket data as incoming packets
  2081. EXPECT_FALSE(pkt4);
  2082. // Now, send some data over the first pipe (38 bytes)
  2083. EXPECT_EQ(38, write(pipefd[1], "Hi, this is a message sent over a pipe", 38));
  2084. // ... and repeat
  2085. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  2086. // IfaceMgr should not process control socket data as incoming packets
  2087. EXPECT_FALSE(pkt4);
  2088. // There was some data, so this time callback should be called
  2089. EXPECT_TRUE(callback_ok);
  2090. EXPECT_FALSE(callback2_ok);
  2091. // Read the data sent, because our test callbacks are too dumb to actually
  2092. // do it. We don't care about the content read, because we're testing
  2093. // the callbacks, not pipes.
  2094. char buf[80];
  2095. EXPECT_EQ(38, read(pipefd[0], buf, 80));
  2096. // Clear the status...
  2097. callback_ok = false;
  2098. callback2_ok = false;
  2099. // And try again, using the second pipe
  2100. EXPECT_EQ(38, write(secondpipe[1], "Hi, this is a message sent over a pipe", 38));
  2101. // ... and repeat
  2102. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  2103. // IfaceMgr should not process control socket data as incoming packets
  2104. EXPECT_FALSE(pkt4);
  2105. // There was some data, so this time callback should be called
  2106. EXPECT_FALSE(callback_ok);
  2107. EXPECT_TRUE(callback2_ok);
  2108. // close both pipe ends
  2109. close(pipefd[1]);
  2110. close(pipefd[0]);
  2111. close(secondpipe[1]);
  2112. close(secondpipe[0]);
  2113. }
  2114. // Tests if existing external socket can be deleted and that such deletion does
  2115. // not affect any other existing sockets. Tests uses receive4()
  2116. TEST_F(IfaceMgrTest, DeleteExternalSockets4) {
  2117. callback_ok = false;
  2118. callback2_ok = false;
  2119. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  2120. // Create first pipe and register it as extra socket
  2121. int pipefd[2];
  2122. EXPECT_TRUE(pipe(pipefd) == 0);
  2123. EXPECT_NO_THROW(ifacemgr->addExternalSocket(pipefd[0], my_callback));
  2124. // Let's create a second pipe and register it as well
  2125. int secondpipe[2];
  2126. EXPECT_TRUE(pipe(secondpipe) == 0);
  2127. EXPECT_NO_THROW(ifacemgr->addExternalSocket(secondpipe[0], my_callback2));
  2128. // Now delete the first session socket
  2129. EXPECT_NO_THROW(ifacemgr->deleteExternalSocket(pipefd[0]));
  2130. // Now check whether the second callback is still functional
  2131. EXPECT_EQ(38, write(secondpipe[1], "Hi, this is a message sent over a pipe", 38));
  2132. // ... and repeat
  2133. Pkt4Ptr pkt4;
  2134. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  2135. // IfaceMgr should not process control socket data as incoming packets
  2136. EXPECT_FALSE(pkt4);
  2137. // There was some data, so this time callback should be called
  2138. EXPECT_FALSE(callback_ok);
  2139. EXPECT_TRUE(callback2_ok);
  2140. // Let's reset the status
  2141. callback_ok = false;
  2142. callback2_ok = false;
  2143. // Now let's send something over the first callback that was unregistered.
  2144. // We should NOT receive any callback.
  2145. EXPECT_EQ(38, write(pipefd[1], "Hi, this is a message sent over a pipe", 38));
  2146. // Now check that the first callback is NOT called.
  2147. ASSERT_NO_THROW(pkt4 = ifacemgr->receive4(1));
  2148. EXPECT_FALSE(callback_ok);
  2149. // close both pipe ends
  2150. close(pipefd[1]);
  2151. close(pipefd[0]);
  2152. close(secondpipe[1]);
  2153. close(secondpipe[0]);
  2154. }
  2155. // Tests if a single external socket and its callback can be passed and
  2156. // it is supported properly by receive6() method.
  2157. TEST_F(IfaceMgrTest, SingleExternalSocket6) {
  2158. callback_ok = false;
  2159. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  2160. // Create pipe and register it as extra socket
  2161. int pipefd[2];
  2162. EXPECT_TRUE(pipe(pipefd) == 0);
  2163. EXPECT_NO_THROW(ifacemgr->addExternalSocket(pipefd[0], my_callback));
  2164. Pkt6Ptr pkt6;
  2165. ASSERT_NO_THROW(pkt6 = ifacemgr->receive6(1));
  2166. // Our callback should not be called this time (there was no data)
  2167. EXPECT_FALSE(callback_ok);
  2168. // IfaceMgr should not process control socket data as incoming packets
  2169. EXPECT_FALSE(pkt6);
  2170. // Now, send some data over pipe (38 bytes)
  2171. EXPECT_EQ(38, write(pipefd[1], "Hi, this is a message sent over a pipe", 38));
  2172. // ... and repeat
  2173. ASSERT_NO_THROW(pkt6 = ifacemgr->receive6(1));
  2174. // IfaceMgr should not process control socket data as incoming packets
  2175. EXPECT_FALSE(pkt6);
  2176. // There was some data, so this time callback should be called
  2177. EXPECT_TRUE(callback_ok);
  2178. // close both pipe ends
  2179. close(pipefd[1]);
  2180. close(pipefd[0]);
  2181. }
  2182. // Tests if multiple external sockets and their callbacks can be passed and
  2183. // it is supported properly by receive6() method.
  2184. TEST_F(IfaceMgrTest, MiltipleExternalSockets6) {
  2185. callback_ok = false;
  2186. callback2_ok = false;
  2187. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  2188. // Create first pipe and register it as extra socket
  2189. int pipefd[2];
  2190. EXPECT_TRUE(pipe(pipefd) == 0);
  2191. EXPECT_NO_THROW(ifacemgr->addExternalSocket(pipefd[0], my_callback));
  2192. // Let's create a second pipe and register it as well
  2193. int secondpipe[2];
  2194. EXPECT_TRUE(pipe(secondpipe) == 0);
  2195. EXPECT_NO_THROW(ifacemgr->addExternalSocket(secondpipe[0], my_callback2));
  2196. Pkt6Ptr pkt6;
  2197. ASSERT_NO_THROW(pkt6 = ifacemgr->receive6(1));
  2198. // Our callbacks should not be called this time (there was no data)
  2199. EXPECT_FALSE(callback_ok);
  2200. EXPECT_FALSE(callback2_ok);
  2201. // IfaceMgr should not process control socket data as incoming packets
  2202. EXPECT_FALSE(pkt6);
  2203. // Now, send some data over the first pipe (38 bytes)
  2204. EXPECT_EQ(38, write(pipefd[1], "Hi, this is a message sent over a pipe", 38));
  2205. // ... and repeat
  2206. ASSERT_NO_THROW(pkt6 = ifacemgr->receive6(1));
  2207. // IfaceMgr should not process control socket data as incoming packets
  2208. EXPECT_FALSE(pkt6);
  2209. // There was some data, so this time callback should be called
  2210. EXPECT_TRUE(callback_ok);
  2211. EXPECT_FALSE(callback2_ok);
  2212. // Read the data sent, because our test callbacks are too dumb to actually
  2213. // do it. We don't care about the content read, because we're testing
  2214. // the callbacks, not pipes.
  2215. char buf[80];
  2216. EXPECT_EQ(38, read(pipefd[0], buf, 80));
  2217. // Clear the status...
  2218. callback_ok = false;
  2219. callback2_ok = false;
  2220. // And try again, using the second pipe
  2221. EXPECT_EQ(38, write(secondpipe[1], "Hi, this is a message sent over a pipe", 38));
  2222. // ... and repeat
  2223. ASSERT_NO_THROW(pkt6 = ifacemgr->receive6(1));
  2224. // IfaceMgr should not process control socket data as incoming packets
  2225. EXPECT_FALSE(pkt6);
  2226. // There was some data, so this time callback should be called
  2227. EXPECT_FALSE(callback_ok);
  2228. EXPECT_TRUE(callback2_ok);
  2229. // close both pipe ends
  2230. close(pipefd[1]);
  2231. close(pipefd[0]);
  2232. close(secondpipe[1]);
  2233. close(secondpipe[0]);
  2234. }
  2235. // Tests if existing external socket can be deleted and that such deletion does
  2236. // not affect any other existing sockets. Tests uses receive6()
  2237. TEST_F(IfaceMgrTest, DeleteExternalSockets6) {
  2238. callback_ok = false;
  2239. callback2_ok = false;
  2240. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  2241. // Create first pipe and register it as extra socket
  2242. int pipefd[2];
  2243. EXPECT_TRUE(pipe(pipefd) == 0);
  2244. EXPECT_NO_THROW(ifacemgr->addExternalSocket(pipefd[0], my_callback));
  2245. // Let's create a second pipe and register it as well
  2246. int secondpipe[2];
  2247. EXPECT_TRUE(pipe(secondpipe) == 0);
  2248. EXPECT_NO_THROW(ifacemgr->addExternalSocket(secondpipe[0], my_callback2));
  2249. // Now delete the first session socket
  2250. EXPECT_NO_THROW(ifacemgr->deleteExternalSocket(pipefd[0]));
  2251. // Now check whether the second callback is still functional
  2252. EXPECT_EQ(38, write(secondpipe[1], "Hi, this is a message sent over a pipe", 38));
  2253. // ... and repeat
  2254. Pkt6Ptr pkt6;
  2255. ASSERT_NO_THROW(pkt6 = ifacemgr->receive6(1));
  2256. // IfaceMgr should not process control socket data as incoming packets
  2257. EXPECT_FALSE(pkt6);
  2258. // There was some data, so this time callback should be called
  2259. EXPECT_FALSE(callback_ok);
  2260. EXPECT_TRUE(callback2_ok);
  2261. // Let's reset the status
  2262. callback_ok = false;
  2263. callback2_ok = false;
  2264. // Now let's send something over the first callback that was unregistered.
  2265. // We should NOT receive any callback.
  2266. EXPECT_EQ(38, write(pipefd[1], "Hi, this is a message sent over a pipe", 38));
  2267. // Now check that the first callback is NOT called.
  2268. ASSERT_NO_THROW(pkt6 = ifacemgr->receive6(1));
  2269. EXPECT_FALSE(callback_ok);
  2270. // close both pipe ends
  2271. close(pipefd[1]);
  2272. close(pipefd[0]);
  2273. close(secondpipe[1]);
  2274. close(secondpipe[0]);
  2275. }
  2276. // Test checks if the unicast sockets can be opened.
  2277. // This test is now disabled, because there is no reliable way to test it. We
  2278. // can't even use loopback, beacuse openSockets() skips loopback interface
  2279. // (as it should be, because DHCP server is not supposed to listen on loopback).
  2280. TEST_F(IfaceMgrTest, DISABLED_openUnicastSockets) {
  2281. /// @todo Need to implement a test that is able to check whether we can open
  2282. /// unicast sockets. There are 2 problems with it:
  2283. /// 1. We need to have a non-link-local address on an interface that is
  2284. /// up, running, IPv6 and multicast capable
  2285. /// 2. We need that information on every OS that we run tests on. So far
  2286. /// we are only supporting interface detection in Linux.
  2287. ///
  2288. /// To achieve this, we will probably need a pre-test setup, similar to what
  2289. /// BIND9 is doing (i.e. configuring well known addresses on loopback).
  2290. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  2291. // Get the interface (todo: which interface)
  2292. IfacePtr iface = ifacemgr->getIface("eth0");
  2293. ASSERT_TRUE(iface);
  2294. iface->inactive6_ = false;
  2295. // Tell the interface that it should bind to this global interface
  2296. EXPECT_NO_THROW(iface->addUnicast(IOAddress("2001:db8::1")));
  2297. // Tell IfaceMgr to open sockets. This should trigger at least 2 sockets
  2298. // to open on eth0: link-local and global. On some systems (Linux), an
  2299. // additional socket for multicast may be opened.
  2300. EXPECT_TRUE(ifacemgr->openSockets6(PORT1));
  2301. const Iface::SocketCollection& sockets = iface->getSockets();
  2302. ASSERT_GE(2, sockets.size());
  2303. // Global unicast should be first
  2304. EXPECT_TRUE(getSocketByAddr(sockets, IOAddress("2001:db8::1")));
  2305. EXPECT_TRUE(getSocketByAddr(sockets, IOAddress("figure-out-link-local-addr")));
  2306. }
  2307. // Checks if there is a protection against unicast duplicates.
  2308. TEST_F(IfaceMgrTest, unicastDuplicates) {
  2309. NakedIfaceMgr ifacemgr;
  2310. IfacePtr iface = ifacemgr.getIface(LOOPBACK);
  2311. if (iface) {
  2312. cout << "Local loopback interface not found. Skipping test. " << endl;
  2313. return;
  2314. }
  2315. // Tell the interface that it should bind to this global interface
  2316. EXPECT_NO_THROW(iface->addUnicast(IOAddress("2001:db8::1")));
  2317. // Tell the interface that it should bind to this global interface
  2318. EXPECT_THROW(iface->addUnicast(IOAddress("2001:db8::1")), BadValue);
  2319. }
  2320. // This test requires addresses 2001:db8:15c::1/128 and fe80::1/64 to be
  2321. // configured on loopback interface
  2322. //
  2323. // Useful commands:
  2324. // ip a a 2001:db8:15c::1/128 dev lo
  2325. // ip a a fe80::1/64 dev lo
  2326. //
  2327. // If you do not issue those commands before running this test, it will fail.
  2328. TEST_F(IfaceMgrTest, DISABLED_getSocket) {
  2329. // Testing socket operation in a portable way is tricky
  2330. // without interface detection implemented.
  2331. scoped_ptr<NakedIfaceMgr> ifacemgr(new NakedIfaceMgr());
  2332. IOAddress lo_addr("::1");
  2333. IOAddress link_local("fe80::1");
  2334. IOAddress global("2001:db8:15c::1");
  2335. IOAddress dst_link_local("fe80::dead:beef");
  2336. IOAddress dst_global("2001:db8:15c::dead:beef");
  2337. // Bind loopback address
  2338. int socket1 = ifacemgr->openSocket(LOOPBACK, lo_addr, 10547);
  2339. EXPECT_GE(socket1, 0); // socket >= 0
  2340. // Bind link-local address
  2341. int socket2 = ifacemgr->openSocket(LOOPBACK, link_local, 10547);
  2342. EXPECT_GE(socket2, 0);
  2343. int socket3 = ifacemgr->openSocket(LOOPBACK, global, 10547);
  2344. EXPECT_GE(socket3, 0);
  2345. // Let's make sure those sockets are unique
  2346. EXPECT_NE(socket1, socket2);
  2347. EXPECT_NE(socket2, socket3);
  2348. EXPECT_NE(socket3, socket1);
  2349. // Create a packet
  2350. Pkt6 pkt6(DHCPV6_SOLICIT, 123);
  2351. pkt6.setIface(LOOPBACK);
  2352. // Check that packets sent to link-local will get socket bound to link local
  2353. pkt6.setLocalAddr(global);
  2354. pkt6.setRemoteAddr(dst_global);
  2355. EXPECT_EQ(socket3, ifacemgr->getSocket(pkt6));
  2356. // Check that packets sent to link-local will get socket bound to link local
  2357. pkt6.setLocalAddr(link_local);
  2358. pkt6.setRemoteAddr(dst_link_local);
  2359. EXPECT_EQ(socket2, ifacemgr->getSocket(pkt6));
  2360. // Close sockets here because the following tests will want to
  2361. // open sockets on the same ports.
  2362. ifacemgr->closeSockets();
  2363. }
  2364. }