iface_mgr_unittest.cc 104 KB

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