iface_mgr_unittest.cc 106 KB

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