iface_mgr_unittest.cc 106 KB

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