iface_mgr_unittest.cc 107 KB

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