dhcp4_srv_unittest.cc 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952
  1. // Copyright (C) 2011-2013 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 <sstream>
  16. #include <asiolink/io_address.h>
  17. #include <config/ccsession.h>
  18. #include <dhcp4/tests/dhcp4_test_utils.h>
  19. #include <dhcp/dhcp4.h>
  20. #include <dhcp/iface_mgr.h>
  21. #include <dhcp/option.h>
  22. #include <dhcp/option_int.h>
  23. #include <dhcp/option4_addrlst.h>
  24. #include <dhcp/option_custom.h>
  25. #include <dhcp/option_int_array.h>
  26. #include <dhcp/option_vendor.h>
  27. #include <dhcp/pkt_filter.h>
  28. #include <dhcp/pkt_filter_inet.h>
  29. #include <dhcp/docsis3_option_defs.h>
  30. #include <dhcp4/dhcp4_srv.h>
  31. #include <dhcp4/dhcp4_log.h>
  32. #include <dhcp4/config_parser.h>
  33. #include <hooks/server_hooks.h>
  34. #include <dhcpsrv/cfgmgr.h>
  35. #include <dhcpsrv/lease_mgr.h>
  36. #include <dhcpsrv/lease_mgr_factory.h>
  37. #include <dhcpsrv/utils.h>
  38. #include <gtest/gtest.h>
  39. #include <hooks/server_hooks.h>
  40. #include <hooks/hooks_manager.h>
  41. #include <config/ccsession.h>
  42. #include <boost/scoped_ptr.hpp>
  43. #include <fstream>
  44. #include <iostream>
  45. #include <arpa/inet.h>
  46. using namespace std;
  47. using namespace isc;
  48. using namespace isc::dhcp;
  49. using namespace isc::data;
  50. using namespace isc::asiolink;
  51. using namespace isc::hooks;
  52. using namespace isc::dhcp::test;
  53. namespace {
  54. /// dummy server-id file location
  55. const char* SRVID_FILE = "server-id-test.txt";
  56. // Sanity check. Verifies that both Dhcpv4Srv and its derived
  57. // class NakedDhcpv4Srv can be instantiated and destroyed.
  58. TEST_F(Dhcpv4SrvTest, basic) {
  59. // Check that the base class can be instantiated
  60. boost::scoped_ptr<Dhcpv4Srv> srv;
  61. ASSERT_NO_THROW(srv.reset(new Dhcpv4Srv(DHCP4_SERVER_PORT + 10000, "type=memfile",
  62. false, false)));
  63. srv.reset();
  64. // We have to close open sockets because further in this test we will
  65. // call the Dhcpv4Srv constructor again. This constructor will try to
  66. // set the appropriate packet filter class for IfaceMgr. This requires
  67. // that all sockets are closed.
  68. IfaceMgr::instance().closeSockets();
  69. // Check that the derived class can be instantiated
  70. boost::scoped_ptr<NakedDhcpv4Srv> naked_srv;
  71. ASSERT_NO_THROW(
  72. naked_srv.reset(new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000)));
  73. EXPECT_TRUE(naked_srv->getServerID());
  74. // Close sockets again for the next test.
  75. IfaceMgr::instance().closeSockets();
  76. ASSERT_NO_THROW(naked_srv.reset(new NakedDhcpv4Srv(0)));
  77. EXPECT_TRUE(naked_srv->getServerID());
  78. }
  79. // This test verifies that exception is not thrown when an error occurs during
  80. // opening sockets. This test forces an error by adding a fictious interface
  81. // to the IfaceMgr. An attempt to open socket on this interface must always
  82. // fail. The DHCPv4 installs the error handler function to prevent exceptions
  83. // being thrown from the openSockets4 function.
  84. // @todo The server tests for socket should be extended but currently the
  85. // ability to unit test the sockets code is somewhat limited.
  86. TEST_F(Dhcpv4SrvTest, openActiveSockets) {
  87. ASSERT_NO_THROW(CfgMgr::instance().activateAllIfaces());
  88. Iface iface("bogusiface", 255);
  89. iface.flag_loopback_ = false;
  90. iface.flag_up_ = true;
  91. iface.flag_running_ = true;
  92. iface.inactive4_ = false;
  93. iface.addAddress(IOAddress("192.0.0.0"));
  94. IfaceMgr::instance().addInterface(iface);
  95. ASSERT_NO_THROW(Dhcpv4Srv::openActiveSockets(DHCP4_SERVER_PORT, false));
  96. }
  97. // This test verifies that the destination address of the response
  98. // message is set to giaddr, when giaddr is set to non-zero address
  99. // in the received message.
  100. TEST_F(Dhcpv4SrvTest, adjustRemoteAddressRelay) {
  101. boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));
  102. // Create the instance of the incoming packet.
  103. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));
  104. // Set the giaddr to non-zero address as if it was relayed.
  105. req->setGiaddr(IOAddress("192.0.2.1"));
  106. // Set ciaddr to zero. This simulates the client which applies
  107. // for the new lease.
  108. req->setCiaddr(IOAddress("0.0.0.0"));
  109. // Clear broadcast flag.
  110. req->setFlags(0x0000);
  111. // Create a response packet. Assume that the new lease have
  112. // been created and new address allocated. This address is
  113. // stored in yiaddr field.
  114. boost::shared_ptr<Pkt4> resp(new Pkt4(DHCPOFFER, 1234));
  115. resp->setYiaddr(IOAddress("192.0.2.100"));
  116. // Clear the remote address.
  117. resp->setRemoteAddr(IOAddress("0.0.0.0"));
  118. // This function never throws.
  119. ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));
  120. // Now the destination address should be relay's address.
  121. EXPECT_EQ("192.0.2.1", resp->getRemoteAddr().toText());
  122. // Let's do another test and set other fields: ciaddr and
  123. // flags. By doing it, we want to make sure that the relay
  124. // address will take precedence.
  125. req->setGiaddr(IOAddress("192.0.2.50"));
  126. req->setCiaddr(IOAddress("192.0.2.11"));
  127. req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
  128. resp->setYiaddr(IOAddress("192.0.2.100"));
  129. // Clear remote address.
  130. resp->setRemoteAddr(IOAddress("0.0.0.0"));
  131. ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));
  132. // Response should be sent back to the relay address.
  133. EXPECT_EQ("192.0.2.50", resp->getRemoteAddr().toText());
  134. }
  135. // This test verifies that the destination address of the response message
  136. // is set to ciaddr when giaddr is set to zero and the ciaddr is set to
  137. // non-zero address in the received message. This is the case when the
  138. // client is in Renew or Rebind state.
  139. TEST_F(Dhcpv4SrvTest, adjustRemoteAddressRenewRebind) {
  140. boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));
  141. // Create instance of the incoming packet.
  142. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));
  143. // Clear giaddr to simulate direct packet.
  144. req->setGiaddr(IOAddress("0.0.0.0"));
  145. // Set ciaddr to non-zero address. The response should be sent to this
  146. // address as the client is in renewing or rebinding state (it is fully
  147. // configured).
  148. req->setCiaddr(IOAddress("192.0.2.15"));
  149. // Let's configure broadcast flag. It should be ignored because
  150. // we are responding directly to the client having an address
  151. // and trying to extend his lease. Broadcast flag is only used
  152. // when new lease is acquired and server must make a decision
  153. // whether to unicast the response to the acquired address or
  154. // broadcast it.
  155. req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
  156. // Create a response.
  157. boost::shared_ptr<Pkt4> resp(new Pkt4(DHCPOFFER, 1234));
  158. // Let's extend the lease for the client in such a way that
  159. // it will actually get different address. The response
  160. // should not be sent to this address but rather to ciaddr
  161. // as client still have ciaddr configured.
  162. resp->setYiaddr(IOAddress("192.0.2.13"));
  163. // Clear the remote address.
  164. resp->setRemoteAddr(IOAddress("0.0.0.0"));
  165. ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));
  166. // Check that server responds to ciaddr
  167. EXPECT_EQ("192.0.2.15", resp->getRemoteAddr().toText());
  168. }
  169. // This test verifies that the destination address of the response message
  170. // is set correctly when giaddr and ciaddr is zeroed in the received message
  171. // and the new lease is acquired. The lease address is carried in the
  172. // response message in the yiaddr field. In this case destination address
  173. // of the response should be set to yiaddr if server supports direct responses
  174. // to the client which doesn't have an address yet or broadcast if the server
  175. // doesn't support direct responses.
  176. TEST_F(Dhcpv4SrvTest, adjustRemoteAddressSelect) {
  177. boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));
  178. // Create instance of the incoming packet.
  179. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));
  180. // Clear giaddr to simulate direct packet.
  181. req->setGiaddr(IOAddress("0.0.0.0"));
  182. // Clear client address as it hasn't got any address configured yet.
  183. req->setCiaddr(IOAddress("0.0.0.0"));
  184. // Let's clear the broadcast flag.
  185. req->setFlags(0);
  186. // Create a response.
  187. boost::shared_ptr<Pkt4> resp(new Pkt4(DHCPOFFER, 1234));
  188. // Assign some new address for this client.
  189. resp->setYiaddr(IOAddress("192.0.2.13"));
  190. // Clear the remote address.
  191. resp->setRemoteAddr(IOAddress("0.0.0.0"));
  192. // When running unit tests, the IfaceMgr is using the default Packet
  193. // Filtering class, PktFilterInet. This class does not support direct
  194. // responses to clients without address assigned. When giaddr and ciaddr
  195. // are zero and client has just got new lease, the assigned address is
  196. // carried in yiaddr. In order to send this address to the client,
  197. // server must broadcast its response.
  198. ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));
  199. // Check that the response is sent to broadcast address as the
  200. // server doesn't have capability to respond directly.
  201. EXPECT_EQ("255.255.255.255", resp->getRemoteAddr().toText());
  202. // We also want to test the case when the server has capability to
  203. // respond directly to the client which is not configured. Server
  204. // makes decision whether it responds directly or broadcast its
  205. // response based on the capability reported by IfaceMgr. In order
  206. // to set this capability we have to provide a dummy Packet Filter
  207. // class which would report the support for direct responses.
  208. // This class is called PktFilterTest.
  209. IfaceMgr::instance().setPacketFilter(PktFilterPtr(new PktFilterTest()));
  210. // Now we expect that the server will send its response to the
  211. // address assigned for the client.
  212. ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));
  213. EXPECT_EQ("192.0.2.13", resp->getRemoteAddr().toText());
  214. }
  215. // This test verifies that the destination address of the response message
  216. // is set to broadcast address when client set broadcast flag in its
  217. // query. Client sets this flag to indicate that it can't receive direct
  218. // responses from the server when it doesn't have its interface configured.
  219. // Server must respect broadcast flag.
  220. TEST_F(Dhcpv4SrvTest, adjustRemoteAddressBroadcast) {
  221. boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));
  222. // Create instance of the incoming packet.
  223. boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));
  224. // Clear giaddr to simulate direct packet.
  225. req->setGiaddr(IOAddress("0.0.0.0"));
  226. // Clear client address as it hasn't got any address configured yet.
  227. req->setCiaddr(IOAddress("0.0.0.0"));
  228. // Let's set the broadcast flag.
  229. req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
  230. // Create a response.
  231. boost::shared_ptr<Pkt4> resp(new Pkt4(DHCPOFFER, 1234));
  232. // Assign some new address for this client.
  233. resp->setYiaddr(IOAddress("192.0.2.13"));
  234. // Clear the remote address.
  235. resp->setRemoteAddr(IOAddress("0.0.0.0"));
  236. // When running unit tests, the IfaceMgr is using the default Packet
  237. // Filtering class, PktFilterInet. This class does not support direct
  238. // responses to the clients without address assigned. If giaddr and
  239. // ciaddr are zero and client has just got the new lease, the assigned
  240. // address is carried in yiaddr. In order to send this address to the
  241. // client, server must send the response to the broadcast address when
  242. // direct response is not supported. This conflicts with the purpose
  243. // of this test which is supposed to verify that responses are sent
  244. // to broadcast address only, when broadcast flag is set. Therefore,
  245. // in order to simulate that direct responses are supported we have
  246. // to replace the default packet filtering class with a dummy class
  247. // which reports direct response capability.
  248. IfaceMgr::instance().setPacketFilter(PktFilterPtr(new PktFilterTest()));
  249. ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));
  250. // Server must repond to broadcast address when client desired that
  251. // by setting the broadcast flag in its request.
  252. EXPECT_EQ("255.255.255.255", resp->getRemoteAddr().toText());
  253. }
  254. // Verifies that DISCOVER message can be processed correctly,
  255. // that the OFFER message generated in response is valid and
  256. // contains necessary options.
  257. //
  258. // Note: this test focuses on the packet correctness. There
  259. // are other tests that verify correctness of the allocation
  260. // engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId
  261. // and DiscoverInvalidHint.
  262. TEST_F(Dhcpv4SrvTest, processDiscover) {
  263. testDiscoverRequest(DHCPDISCOVER);
  264. }
  265. // Verifies that REQUEST message can be processed correctly,
  266. // that the OFFER message generated in response is valid and
  267. // contains necessary options.
  268. //
  269. // Note: this test focuses on the packet correctness. There
  270. // are other tests that verify correctness of the allocation
  271. // engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId
  272. // and DiscoverInvalidHint.
  273. TEST_F(Dhcpv4SrvTest, processRequest) {
  274. testDiscoverRequest(DHCPREQUEST);
  275. }
  276. TEST_F(Dhcpv4SrvTest, processRelease) {
  277. NakedDhcpv4Srv srv;
  278. Pkt4Ptr pkt(new Pkt4(DHCPRELEASE, 1234));
  279. // Should not throw
  280. EXPECT_NO_THROW(srv.processRelease(pkt));
  281. }
  282. TEST_F(Dhcpv4SrvTest, processDecline) {
  283. NakedDhcpv4Srv srv;
  284. Pkt4Ptr pkt(new Pkt4(DHCPDECLINE, 1234));
  285. // Should not throw
  286. EXPECT_NO_THROW(srv.processDecline(pkt));
  287. }
  288. TEST_F(Dhcpv4SrvTest, processInform) {
  289. NakedDhcpv4Srv srv;
  290. Pkt4Ptr pkt(new Pkt4(DHCPINFORM, 1234));
  291. // Should not throw
  292. EXPECT_NO_THROW(srv.processInform(pkt));
  293. // Should return something
  294. EXPECT_TRUE(srv.processInform(pkt));
  295. // @todo Implement more reasonable tests before starting
  296. // work on processSomething() method.
  297. }
  298. TEST_F(Dhcpv4SrvTest, serverReceivedPacketName) {
  299. // Check all possible packet types
  300. for (int itype = 0; itype < 256; ++itype) {
  301. uint8_t type = itype;
  302. switch (type) {
  303. case DHCPDECLINE:
  304. EXPECT_STREQ("DECLINE", Dhcpv4Srv::serverReceivedPacketName(type));
  305. break;
  306. case DHCPDISCOVER:
  307. EXPECT_STREQ("DISCOVER", Dhcpv4Srv::serverReceivedPacketName(type));
  308. break;
  309. case DHCPINFORM:
  310. EXPECT_STREQ("INFORM", Dhcpv4Srv::serverReceivedPacketName(type));
  311. break;
  312. case DHCPRELEASE:
  313. EXPECT_STREQ("RELEASE", Dhcpv4Srv::serverReceivedPacketName(type));
  314. break;
  315. case DHCPREQUEST:
  316. EXPECT_STREQ("REQUEST", Dhcpv4Srv::serverReceivedPacketName(type));
  317. break;
  318. default:
  319. EXPECT_STREQ("UNKNOWN", Dhcpv4Srv::serverReceivedPacketName(type));
  320. }
  321. }
  322. }
  323. // This test verifies that incoming DISCOVER can be handled properly, that an
  324. // OFFER is generated, that the response has an address and that address
  325. // really belongs to the configured pool.
  326. //
  327. // constructed very simple DISCOVER message with:
  328. // - client-id option
  329. //
  330. // expected returned OFFER message:
  331. // - copy of client-id
  332. // - server-id
  333. // - offered address
  334. TEST_F(Dhcpv4SrvTest, DiscoverBasic) {
  335. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  336. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  337. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  338. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  339. OptionPtr clientid = generateClientId();
  340. dis->addOption(clientid);
  341. // Pass it to the server and get an offer
  342. Pkt4Ptr offer = srv->processDiscover(dis);
  343. // Check if we get response at all
  344. checkResponse(offer, DHCPOFFER, 1234);
  345. // Check that address was returned from proper range, that its lease
  346. // lifetime is correct, that T1 and T2 are returned properly
  347. checkAddressParams(offer, subnet_);
  348. // Check identifiers
  349. checkServerId(offer, srv->getServerID());
  350. checkClientId(offer, clientid);
  351. }
  352. // This test verifies that incoming DISCOVER can be handled properly, that an
  353. // OFFER is generated, that the response has an address and that address
  354. // really belongs to the configured pool.
  355. //
  356. // constructed very simple DISCOVER message with:
  357. // - client-id option
  358. // - address set to specific value as hint
  359. //
  360. // expected returned OFFER message:
  361. // - copy of client-id
  362. // - server-id
  363. // - offered address
  364. TEST_F(Dhcpv4SrvTest, DiscoverHint) {
  365. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  366. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  367. IOAddress hint("192.0.2.107");
  368. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  369. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  370. OptionPtr clientid = generateClientId();
  371. dis->addOption(clientid);
  372. dis->setYiaddr(hint);
  373. // Pass it to the server and get an offer
  374. Pkt4Ptr offer = srv->processDiscover(dis);
  375. // Check if we get response at all
  376. checkResponse(offer, DHCPOFFER, 1234);
  377. // Check that address was returned from proper range, that its lease
  378. // lifetime is correct, that T1 and T2 are returned properly
  379. checkAddressParams(offer, subnet_);
  380. EXPECT_EQ(offer->getYiaddr().toText(), hint.toText());
  381. // Check identifiers
  382. checkServerId(offer, srv->getServerID());
  383. checkClientId(offer, clientid);
  384. }
  385. // This test verifies that incoming DISCOVER can be handled properly, that an
  386. // OFFER is generated, that the response has an address and that address
  387. // really belongs to the configured pool.
  388. //
  389. // constructed very simple DISCOVER message with:
  390. // - address set to specific value as hint
  391. //
  392. // expected returned OFFER message:
  393. // - copy of client-id
  394. // - server-id
  395. // - offered address
  396. TEST_F(Dhcpv4SrvTest, DiscoverNoClientId) {
  397. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  398. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  399. IOAddress hint("192.0.2.107");
  400. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  401. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  402. dis->setYiaddr(hint);
  403. dis->setHWAddr(generateHWAddr(6));
  404. // Pass it to the server and get an offer
  405. Pkt4Ptr offer = srv->processDiscover(dis);
  406. // Check if we get response at all
  407. checkResponse(offer, DHCPOFFER, 1234);
  408. // Check that address was returned from proper range, that its lease
  409. // lifetime is correct, that T1 and T2 are returned properly
  410. checkAddressParams(offer, subnet_);
  411. EXPECT_EQ(offer->getYiaddr().toText(), hint.toText());
  412. // Check identifiers
  413. checkServerId(offer, srv->getServerID());
  414. }
  415. // This test verifies that incoming DISCOVER can be handled properly, that an
  416. // OFFER is generated, that the response has an address and that address
  417. // really belongs to the configured pool.
  418. //
  419. // constructed very simple DISCOVER message with:
  420. // - client-id option
  421. // - address set to specific value as hint, but that hint is invalid
  422. //
  423. // expected returned OFFER message:
  424. // - copy of client-id
  425. // - server-id
  426. // - offered address (!= hint)
  427. TEST_F(Dhcpv4SrvTest, DiscoverInvalidHint) {
  428. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  429. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  430. IOAddress hint("10.1.2.3");
  431. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  432. dis->setRemoteAddr(IOAddress("192.0.2.107"));
  433. OptionPtr clientid = generateClientId();
  434. dis->addOption(clientid);
  435. dis->setYiaddr(hint);
  436. // Pass it to the server and get an offer
  437. Pkt4Ptr offer = srv->processDiscover(dis);
  438. // Check if we get response at all
  439. checkResponse(offer, DHCPOFFER, 1234);
  440. // Check that address was returned from proper range, that its lease
  441. // lifetime is correct, that T1 and T2 are returned properly
  442. checkAddressParams(offer, subnet_);
  443. EXPECT_NE(offer->getYiaddr().toText(), hint.toText());
  444. // Check identifiers
  445. checkServerId(offer, srv->getServerID());
  446. checkClientId(offer, clientid);
  447. }
  448. /// @todo: Add a test that client sends hint that is in pool, but currently
  449. /// being used by a different client.
  450. // This test checks that the server is offering different addresses to different
  451. // clients in OFFERs. Please note that OFFER is not a guarantee that such
  452. // an address will be assigned. Had the pool was very small and contained only
  453. // 2 addresses, the third client would get the same offer as the first one
  454. // and this is a correct behavior. It is REQUEST that will fail for the third
  455. // client. OFFER is basically saying "if you send me a request, you will
  456. // probably get an address like this" (there are no guarantees).
  457. TEST_F(Dhcpv4SrvTest, ManyDiscovers) {
  458. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  459. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  460. Pkt4Ptr dis1 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  461. Pkt4Ptr dis2 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 2345));
  462. Pkt4Ptr dis3 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 3456));
  463. dis1->setRemoteAddr(IOAddress("192.0.2.1"));
  464. dis2->setRemoteAddr(IOAddress("192.0.2.2"));
  465. dis3->setRemoteAddr(IOAddress("192.0.2.3"));
  466. // Different client-id sizes
  467. OptionPtr clientid1 = generateClientId(4); // length 4
  468. OptionPtr clientid2 = generateClientId(5); // length 5
  469. OptionPtr clientid3 = generateClientId(6); // length 6
  470. dis1->addOption(clientid1);
  471. dis2->addOption(clientid2);
  472. dis3->addOption(clientid3);
  473. // Pass it to the server and get an offer
  474. Pkt4Ptr offer1 = srv->processDiscover(dis1);
  475. Pkt4Ptr offer2 = srv->processDiscover(dis2);
  476. Pkt4Ptr offer3 = srv->processDiscover(dis3);
  477. // Check if we get response at all
  478. checkResponse(offer1, DHCPOFFER, 1234);
  479. checkResponse(offer2, DHCPOFFER, 2345);
  480. checkResponse(offer3, DHCPOFFER, 3456);
  481. IOAddress addr1 = offer1->getYiaddr();
  482. IOAddress addr2 = offer2->getYiaddr();
  483. IOAddress addr3 = offer3->getYiaddr();
  484. // Check that the assigned address is indeed from the configured pool
  485. checkAddressParams(offer1, subnet_);
  486. checkAddressParams(offer2, subnet_);
  487. checkAddressParams(offer3, subnet_);
  488. // Check server-ids
  489. checkServerId(offer1, srv->getServerID());
  490. checkServerId(offer2, srv->getServerID());
  491. checkServerId(offer3, srv->getServerID());
  492. checkClientId(offer1, clientid1);
  493. checkClientId(offer2, clientid2);
  494. checkClientId(offer3, clientid3);
  495. // Finally check that the addresses offered are different
  496. EXPECT_NE(addr1.toText(), addr2.toText());
  497. EXPECT_NE(addr2.toText(), addr3.toText());
  498. EXPECT_NE(addr3.toText(), addr1.toText());
  499. cout << "Offered address to client1=" << addr1.toText() << endl;
  500. cout << "Offered address to client2=" << addr2.toText() << endl;
  501. cout << "Offered address to client3=" << addr3.toText() << endl;
  502. }
  503. // This test verifies that incoming REQUEST can be handled properly, that an
  504. // ACK is generated, that the response has an address and that address
  505. // really belongs to the configured pool.
  506. //
  507. // constructed a single REQUEST message with:
  508. // - client-id option
  509. // - hwaddr information
  510. // - requested address (that the client received in DISCOVER/OFFER exchange)
  511. //
  512. // expected returned ACK message:
  513. // - copy of client-id
  514. // - server-id
  515. // - assigned address
  516. //
  517. // Test verifies that the lease is actually in the database.
  518. TEST_F(Dhcpv4SrvTest, RequestBasic) {
  519. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  520. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  521. IOAddress hint("192.0.2.107");
  522. Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234));
  523. req->setRemoteAddr(IOAddress("192.0.2.1"));
  524. OptionPtr clientid = generateClientId();
  525. req->addOption(clientid);
  526. req->setYiaddr(hint);
  527. // Pass it to the server and get an advertise
  528. Pkt4Ptr ack = srv->processRequest(req);
  529. // Check if we get response at all
  530. checkResponse(ack, DHCPACK, 1234);
  531. EXPECT_EQ(hint.toText(), ack->getYiaddr().toText());
  532. // Check that address was returned from proper range, that its lease
  533. // lifetime is correct, that T1 and T2 are returned properly
  534. checkAddressParams(ack, subnet_);
  535. // Check identifiers
  536. checkServerId(ack, srv->getServerID());
  537. checkClientId(ack, clientid);
  538. // Check that the lease is really in the database
  539. Lease4Ptr l = checkLease(ack, clientid, req->getHWAddr(), hint);
  540. ASSERT_TRUE(l);
  541. LeaseMgrFactory::instance().deleteLease(l->addr_);
  542. }
  543. // This test verifies that incoming REQUEST can be handled properly, that an
  544. // ACK is generated, that the response has an address and that address
  545. // really belongs to the configured pool.
  546. //
  547. // constructed 3 REQUEST messages with:
  548. // - client-id option (differs between messages)
  549. // - hwaddr information (differs between messages)
  550. //
  551. // expected returned ACK message:
  552. // - copy of client-id
  553. // - server-id
  554. // - assigned address (different for each client)
  555. TEST_F(Dhcpv4SrvTest, ManyRequests) {
  556. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  557. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  558. const IOAddress req_addr1("192.0.2.105");
  559. const IOAddress req_addr2("192.0.2.101");
  560. const IOAddress req_addr3("192.0.2.109");
  561. const IOAddress relay("192.0.2.1");
  562. Pkt4Ptr req1 = Pkt4Ptr(new Pkt4(DHCPOFFER, 1234));
  563. Pkt4Ptr req2 = Pkt4Ptr(new Pkt4(DHCPOFFER, 2345));
  564. Pkt4Ptr req3 = Pkt4Ptr(new Pkt4(DHCPOFFER, 3456));
  565. req1->setRemoteAddr(relay);
  566. req2->setRemoteAddr(relay);
  567. req3->setRemoteAddr(relay);
  568. req1->setYiaddr(req_addr1);
  569. req2->setYiaddr(req_addr2);
  570. req3->setYiaddr(req_addr3);
  571. req1->setHWAddr(generateHWAddr(6));
  572. req2->setHWAddr(generateHWAddr(7));
  573. req3->setHWAddr(generateHWAddr(8));
  574. // Different client-id sizes
  575. OptionPtr clientid1 = generateClientId(4); // length 4
  576. OptionPtr clientid2 = generateClientId(5); // length 5
  577. OptionPtr clientid3 = generateClientId(6); // length 6
  578. req1->addOption(clientid1);
  579. req2->addOption(clientid2);
  580. req3->addOption(clientid3);
  581. // Pass it to the server and get an advertise
  582. Pkt4Ptr ack1 = srv->processRequest(req1);
  583. Pkt4Ptr ack2 = srv->processRequest(req2);
  584. Pkt4Ptr ack3 = srv->processRequest(req3);
  585. // Check if we get response at all
  586. checkResponse(ack1, DHCPACK, 1234);
  587. checkResponse(ack2, DHCPACK, 2345);
  588. checkResponse(ack3, DHCPACK, 3456);
  589. IOAddress addr1 = ack1->getYiaddr();
  590. IOAddress addr2 = ack2->getYiaddr();
  591. IOAddress addr3 = ack3->getYiaddr();
  592. // Check that every client received the address it requested
  593. EXPECT_EQ(req_addr1.toText(), addr1.toText());
  594. EXPECT_EQ(req_addr2.toText(), addr2.toText());
  595. EXPECT_EQ(req_addr3.toText(), addr3.toText());
  596. // Check that the assigned address is indeed from the configured pool
  597. checkAddressParams(ack1, subnet_);
  598. checkAddressParams(ack2, subnet_);
  599. checkAddressParams(ack3, subnet_);
  600. // Check DUIDs
  601. checkServerId(ack1, srv->getServerID());
  602. checkServerId(ack2, srv->getServerID());
  603. checkServerId(ack3, srv->getServerID());
  604. checkClientId(ack1, clientid1);
  605. checkClientId(ack2, clientid2);
  606. checkClientId(ack3, clientid3);
  607. // Check that leases are in the database
  608. Lease4Ptr l = checkLease(ack1, clientid1, req1->getHWAddr(), addr1);
  609. EXPECT_TRUE(l);
  610. l = checkLease(ack2, clientid2, req2->getHWAddr(), addr2);
  611. l = checkLease(ack3, clientid3, req3->getHWAddr(), addr3);
  612. // Finally check that the addresses offered are different
  613. EXPECT_NE(addr1.toText(), addr2.toText());
  614. EXPECT_NE(addr2.toText(), addr3.toText());
  615. EXPECT_NE(addr3.toText(), addr1.toText());
  616. cout << "Offered address to client1=" << addr1.toText() << endl;
  617. cout << "Offered address to client2=" << addr2.toText() << endl;
  618. cout << "Offered address to client3=" << addr3.toText() << endl;
  619. }
  620. // This test verifies that incoming (positive) REQUEST/Renewing can be handled properly, that a
  621. // REPLY is generated, that the response has an address and that address
  622. // really belongs to the configured pool and that lease is actually renewed.
  623. //
  624. // expected:
  625. // - returned REPLY message has copy of client-id
  626. // - returned REPLY message has server-id
  627. // - returned REPLY message has IA that includes IAADDR
  628. // - lease is actually renewed in LeaseMgr
  629. TEST_F(Dhcpv4SrvTest, RenewBasic) {
  630. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  631. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  632. const IOAddress addr("192.0.2.106");
  633. const uint32_t temp_t1 = 50;
  634. const uint32_t temp_t2 = 75;
  635. const uint32_t temp_valid = 100;
  636. const time_t temp_timestamp = time(NULL) - 10;
  637. // Generate client-id also sets client_id_ member
  638. OptionPtr clientid = generateClientId();
  639. // Check that the address we are about to use is indeed in pool
  640. ASSERT_TRUE(subnet_->inPool(Lease::TYPE_V4, addr));
  641. // let's create a lease and put it in the LeaseMgr
  642. uint8_t hwaddr2[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  643. Lease4Ptr used(new Lease4(IOAddress("192.0.2.106"), hwaddr2, sizeof(hwaddr2),
  644. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  645. temp_valid, temp_t1, temp_t2, temp_timestamp,
  646. subnet_->getID()));
  647. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  648. // Check that the lease is really in the database
  649. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  650. ASSERT_TRUE(l);
  651. // Check that T1, T2, preferred, valid and cltt really set.
  652. // Constructed lease looks as if it was assigned 10 seconds ago
  653. // EXPECT_EQ(l->t1_, temp_t1);
  654. // EXPECT_EQ(l->t2_, temp_t2);
  655. EXPECT_EQ(l->valid_lft_, temp_valid);
  656. EXPECT_EQ(l->cltt_, temp_timestamp);
  657. // Let's create a RENEW
  658. Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234));
  659. req->setRemoteAddr(IOAddress(addr));
  660. req->setYiaddr(addr);
  661. req->setCiaddr(addr); // client's address
  662. req->addOption(clientid);
  663. req->addOption(srv->getServerID());
  664. // Pass it to the server and hope for a REPLY
  665. Pkt4Ptr ack = srv->processRequest(req);
  666. // Check if we get response at all
  667. checkResponse(ack, DHCPACK, 1234);
  668. EXPECT_EQ(addr.toText(), ack->getYiaddr().toText());
  669. // Check that address was returned from proper range, that its lease
  670. // lifetime is correct, that T1 and T2 are returned properly
  671. checkAddressParams(ack, subnet_);
  672. // Check identifiers
  673. checkServerId(ack, srv->getServerID());
  674. checkClientId(ack, clientid);
  675. // Check that the lease is really in the database
  676. l = checkLease(ack, clientid, req->getHWAddr(), addr);
  677. ASSERT_TRUE(l);
  678. // Check that T1, T2, preferred, valid and cltt were really updated
  679. EXPECT_EQ(l->t1_, subnet_->getT1());
  680. EXPECT_EQ(l->t2_, subnet_->getT2());
  681. EXPECT_EQ(l->valid_lft_, subnet_->getValid());
  682. // Checking for CLTT is a bit tricky if we want to avoid off by 1 errors
  683. int32_t cltt = static_cast<int32_t>(l->cltt_);
  684. int32_t expected = static_cast<int32_t>(time(NULL));
  685. // Equality or difference by 1 between cltt and expected is ok.
  686. EXPECT_GE(1, abs(cltt - expected));
  687. EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(addr));
  688. }
  689. // @todo: Implement tests for rejecting renewals
  690. // This test verifies if the sanityCheck() really checks options presence.
  691. TEST_F(Dhcpv4SrvTest, sanityCheck) {
  692. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  693. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  694. Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  695. pkt->setHWAddr(generateHWAddr(6));
  696. // Server-id is optional for information-request, so
  697. EXPECT_NO_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::OPTIONAL));
  698. // Empty packet, no server-id
  699. EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation);
  700. pkt->addOption(srv->getServerID());
  701. // Server-id is mandatory and present = no exception
  702. EXPECT_NO_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY));
  703. // Server-id is forbidden, but present => exception
  704. EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::FORBIDDEN),
  705. RFCViolation);
  706. // There's no client-id and no HWADDR. Server needs something to
  707. // identify the client
  708. pkt->setHWAddr(generateHWAddr(0));
  709. EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation);
  710. }
  711. // This test verifies that incoming (positive) RELEASE can be handled properly.
  712. // As there is no REPLY in DHCPv4, the only thing to verify here is that
  713. // the lease is indeed removed from the database.
  714. TEST_F(Dhcpv4SrvTest, ReleaseBasic) {
  715. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  716. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  717. const IOAddress addr("192.0.2.106");
  718. const uint32_t temp_t1 = 50;
  719. const uint32_t temp_t2 = 75;
  720. const uint32_t temp_valid = 100;
  721. const time_t temp_timestamp = time(NULL) - 10;
  722. // Generate client-id also duid_
  723. OptionPtr clientid = generateClientId();
  724. // Check that the address we are about to use is indeed in pool
  725. ASSERT_TRUE(subnet_->inPool(Lease::TYPE_V4, addr));
  726. // Let's create a lease and put it in the LeaseMgr
  727. uint8_t mac_addr[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  728. HWAddrPtr hw(new HWAddr(mac_addr, sizeof(mac_addr), HTYPE_ETHER));
  729. Lease4Ptr used(new Lease4(addr, mac_addr, sizeof(mac_addr),
  730. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  731. temp_valid, temp_t1, temp_t2, temp_timestamp,
  732. subnet_->getID()));
  733. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  734. // Check that the lease is really in the database
  735. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  736. ASSERT_TRUE(l);
  737. // Let's create a RELEASE
  738. // Generate client-id also duid_
  739. Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
  740. rel->setRemoteAddr(addr);
  741. rel->setCiaddr(addr);
  742. rel->addOption(clientid);
  743. rel->addOption(srv->getServerID());
  744. rel->setHWAddr(hw);
  745. // Pass it to the server and hope for a REPLY
  746. // Note: this is no response to RELEASE in DHCPv4
  747. EXPECT_NO_THROW(srv->processRelease(rel));
  748. // The lease should be gone from LeaseMgr
  749. l = LeaseMgrFactory::instance().getLease4(addr);
  750. EXPECT_FALSE(l);
  751. // Try to get the lease by hardware address
  752. Lease4Collection leases = LeaseMgrFactory::instance().getLease4(hw->hwaddr_);
  753. EXPECT_EQ(leases.size(), 0);
  754. // Try to get it by hw/subnet_id combination
  755. l = LeaseMgrFactory::instance().getLease4(hw->hwaddr_, subnet_->getID());
  756. EXPECT_FALSE(l);
  757. // Try by client-id
  758. leases = LeaseMgrFactory::instance().getLease4(*client_id_);
  759. EXPECT_EQ(leases.size(), 0);
  760. // Try by client-id/subnet-id
  761. l = LeaseMgrFactory::instance().getLease4(*client_id_, subnet_->getID());
  762. EXPECT_FALSE(l);
  763. // Ok, the lease is *really* not there.
  764. }
  765. // This test verifies that incoming (invalid) RELEASE can be handled properly.
  766. //
  767. // This test checks 3 scenarios:
  768. // 1. there is no such lease at all
  769. // 2. there is such a lease, but it is assigned to a different IAID
  770. // 3. there is such a lease, but it belongs to a different client
  771. TEST_F(Dhcpv4SrvTest, ReleaseReject) {
  772. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  773. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  774. const IOAddress addr("192.0.2.106");
  775. const uint32_t t1 = 50;
  776. const uint32_t t2 = 75;
  777. const uint32_t valid = 100;
  778. const time_t timestamp = time(NULL) - 10;
  779. // Let's create a lease and put it in the LeaseMgr
  780. uint8_t bogus_mac_addr[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  781. HWAddrPtr bogus_hw(new HWAddr(bogus_mac_addr, sizeof(bogus_mac_addr), HTYPE_ETHER));
  782. OptionPtr bogus_clientid = generateClientId(7); // different length
  783. // Generate client-id also duid_
  784. OptionPtr clientid = generateClientId();
  785. // Check that the address we are about to use is indeed in pool
  786. ASSERT_TRUE(subnet_->inPool(Lease::TYPE_V4, addr));
  787. // Let's create a RELEASE
  788. // Generate client-id also duid_
  789. Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
  790. rel->setRemoteAddr(addr);
  791. rel->setCiaddr(addr);
  792. rel->addOption(clientid);
  793. rel->addOption(srv->getServerID());
  794. rel->setHWAddr(bogus_hw);
  795. // Case 1: No lease known to server
  796. SCOPED_TRACE("CASE 1: Lease is not known to the server");
  797. // There is nothing to check here. The lease is not there and server does
  798. // not send anything back. This case is enumerated here just for keeping
  799. // parity with similar test in DHCPv6.
  800. EXPECT_NO_THROW(srv->processRelease(rel));
  801. // CASE 2: Lease is known and belongs to this client, but to a different hardware
  802. SCOPED_TRACE("CASE 2: Lease is known and belongs to this client, but uses different HW addr");
  803. // Let's create a lease and put it in the LeaseMgr
  804. uint8_t mac_addr[] = { 0, 0x1, 0x2, 0x3, 0x4, 0x5};
  805. HWAddrPtr hw(new HWAddr(mac_addr, sizeof(mac_addr), HTYPE_ETHER));
  806. Lease4Ptr used(new Lease4(addr, mac_addr, sizeof(mac_addr),
  807. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  808. valid, t1, t2, timestamp, subnet_->getID()));
  809. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  810. // Check that the lease is really in the database
  811. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  812. ASSERT_TRUE(l);
  813. rel->setHWAddr(bogus_hw);
  814. EXPECT_NO_THROW(srv->processRelease(rel));
  815. // Check that the lease was not removed (due to hardware address mis-match)
  816. l = LeaseMgrFactory::instance().getLease4(addr);
  817. ASSERT_TRUE(l);
  818. // CASE 3: Lease belongs to a client with different client-id
  819. SCOPED_TRACE("CASE 3: Lease belongs to a client with different client-id");
  820. rel->setHWAddr(hw); // proper HW address this time
  821. rel->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
  822. rel->addOption(bogus_clientid); // but invalid client-id
  823. OptionPtr x = rel->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  824. EXPECT_NO_THROW(srv->processRelease(rel));
  825. // Check that the lease is still there
  826. l = LeaseMgrFactory::instance().getLease4(addr);
  827. ASSERT_TRUE(l);
  828. // Final sanity check. Verify that with valid hw and client-id release is successful
  829. rel->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
  830. rel->addOption(clientid);
  831. // It should work this time
  832. EXPECT_NO_THROW(srv->processRelease(rel));
  833. // Check that the lease is not there
  834. l = LeaseMgrFactory::instance().getLease4(addr);
  835. EXPECT_FALSE(l);
  836. }
  837. // This test verifies if the server-id disk operations (read, write) are
  838. // working properly.
  839. TEST_F(Dhcpv4SrvTest, ServerID) {
  840. NakedDhcpv4Srv srv(0);
  841. string srvid_text = "192.0.2.100";
  842. IOAddress srvid(srvid_text);
  843. fstream file1(SRVID_FILE, ios::out | ios::trunc);
  844. file1 << srvid_text;
  845. file1.close();
  846. // Test reading from a file
  847. EXPECT_TRUE(srv.loadServerID(SRVID_FILE));
  848. ASSERT_TRUE(srv.getServerID());
  849. EXPECT_EQ(srvid_text, srv.srvidToString(srv.getServerID()));
  850. // Now test writing to a file
  851. EXPECT_EQ(0, unlink(SRVID_FILE));
  852. EXPECT_NO_THROW(srv.writeServerID(SRVID_FILE));
  853. fstream file2(SRVID_FILE, ios::in);
  854. ASSERT_TRUE(file2.good());
  855. string text;
  856. file2 >> text;
  857. file2.close();
  858. EXPECT_EQ(srvid_text, text);
  859. }
  860. // Checks if received relay agent info option is echoed back to the client
  861. TEST_F(Dhcpv4SrvTest, relayAgentInfoEcho) {
  862. NakedDhcpv4Srv srv(0);
  863. // Let's create a relayed DISCOVER. This particular relayed DISCOVER has
  864. // added option 82 (relay agent info) with 3 suboptions. The server
  865. // is supposed to echo it back in its response.
  866. Pkt4Ptr dis;
  867. ASSERT_NO_THROW(dis = captureRelayedDiscover());
  868. // Simulate that we have received that traffic
  869. srv.fakeReceive(dis);
  870. // Server will now process to run its normal loop, but instead of calling
  871. // IfaceMgr::receive4(), it will read all packets from the list set by
  872. // fakeReceive()
  873. // In particular, it should call registered buffer4_receive callback.
  874. srv.run();
  875. // Check that the server did send a reposonse
  876. ASSERT_EQ(1, srv.fake_sent_.size());
  877. // Make sure that we received a response
  878. Pkt4Ptr offer = srv.fake_sent_.front();
  879. ASSERT_TRUE(offer);
  880. // Get Relay Agent Info from query...
  881. OptionPtr rai_query = dis->getOption(DHO_DHCP_AGENT_OPTIONS);
  882. ASSERT_TRUE(rai_query);
  883. // Get Relay Agent Info from response...
  884. OptionPtr rai_response = offer->getOption(DHO_DHCP_AGENT_OPTIONS);
  885. ASSERT_TRUE(rai_response);
  886. EXPECT_TRUE(rai_response->equal(rai_query));
  887. }
  888. /// @todo move vendor options tests to a separate file.
  889. /// @todo Add more extensive vendor options tests, including multiple
  890. /// vendor options
  891. // Checks if vendor options are parsed correctly and requested vendor options
  892. // are echoed back.
  893. TEST_F(Dhcpv4SrvTest, vendorOptionsDocsis) {
  894. NakedDhcpv4Srv srv(0);
  895. string config = "{ \"interfaces\": [ \"*\" ],"
  896. "\"rebind-timer\": 2000, "
  897. "\"renew-timer\": 1000, "
  898. " \"option-data\": [ {"
  899. " \"name\": \"tftp-servers\","
  900. " \"space\": \"vendor-4491\","
  901. " \"code\": 2,"
  902. " \"data\": \"10.253.175.16\","
  903. " \"csv-format\": True"
  904. " }],"
  905. "\"subnet4\": [ { "
  906. " \"pool\": [ \"10.254.226.0/25\" ],"
  907. " \"subnet\": \"10.254.226.0/24\", "
  908. " \"rebind-timer\": 2000, "
  909. " \"renew-timer\": 1000, "
  910. " \"valid-lifetime\": 4000,"
  911. " \"interface\": \"" + valid_iface_ + "\" "
  912. " } ],"
  913. "\"valid-lifetime\": 4000 }";
  914. ElementPtr json = Element::fromJSON(config);
  915. ConstElementPtr status;
  916. // Configure the server and make sure the config is accepted
  917. EXPECT_NO_THROW(status = configureDhcp4Server(srv, json));
  918. ASSERT_TRUE(status);
  919. comment_ = config::parseAnswer(rcode_, status);
  920. ASSERT_EQ(0, rcode_);
  921. // Let's create a relayed DISCOVER. This particular relayed DISCOVER has
  922. // added option 82 (relay agent info) with 3 suboptions. The server
  923. // is supposed to echo it back in its response.
  924. Pkt4Ptr dis;
  925. ASSERT_NO_THROW(dis = captureRelayedDiscover());
  926. // Simulate that we have received that traffic
  927. srv.fakeReceive(dis);
  928. // Server will now process to run its normal loop, but instead of calling
  929. // IfaceMgr::receive4(), it will read all packets from the list set by
  930. // fakeReceive()
  931. // In particular, it should call registered buffer4_receive callback.
  932. srv.run();
  933. // Check that the server did send a reposonse
  934. ASSERT_EQ(1, srv.fake_sent_.size());
  935. // Make sure that we received a response
  936. Pkt4Ptr offer = srv.fake_sent_.front();
  937. ASSERT_TRUE(offer);
  938. // Get Relay Agent Info from query...
  939. OptionPtr vendor_opt_response = offer->getOption(DHO_VIVSO_SUBOPTIONS);
  940. ASSERT_TRUE(vendor_opt_response);
  941. // Check if it's of a correct type
  942. boost::shared_ptr<OptionVendor> vendor_opt =
  943. boost::dynamic_pointer_cast<OptionVendor>(vendor_opt_response);
  944. ASSERT_TRUE(vendor_opt);
  945. // Get Relay Agent Info from response...
  946. OptionPtr tftp_servers_generic = vendor_opt->getOption(DOCSIS3_V4_TFTP_SERVERS);
  947. ASSERT_TRUE(tftp_servers_generic);
  948. Option4AddrLstPtr tftp_servers =
  949. boost::dynamic_pointer_cast<Option4AddrLst>(tftp_servers_generic);
  950. ASSERT_TRUE(tftp_servers);
  951. Option4AddrLst::AddressContainer addrs = tftp_servers->getAddresses();
  952. ASSERT_EQ(1, addrs.size());
  953. EXPECT_EQ("10.253.175.16", addrs[0].toText());
  954. }
  955. /// @todo Implement tests for subnetSelect See tests in dhcp6_srv_unittest.cc:
  956. /// selectSubnetAddr, selectSubnetIface, selectSubnetRelayLinkaddr,
  957. /// selectSubnetRelayInterfaceId. Note that the concept of interface-id is not
  958. /// present in the DHCPv4, so not everything is applicable directly.
  959. /// See ticket #3057
  960. // Checks if hooks are registered properly.
  961. TEST_F(Dhcpv4SrvTest, Hooks) {
  962. NakedDhcpv4Srv srv(0);
  963. // check if appropriate hooks are registered
  964. int hook_index_buffer4_receive = -1;
  965. int hook_index_pkt4_receive = -1;
  966. int hook_index_select_subnet = -1;
  967. int hook_index_lease4_release = -1;
  968. int hook_index_pkt4_send = -1;
  969. int hook_index_buffer4_send = -1;
  970. // check if appropriate indexes are set
  971. EXPECT_NO_THROW(hook_index_buffer4_receive = ServerHooks::getServerHooks()
  972. .getIndex("buffer4_receive"));
  973. EXPECT_NO_THROW(hook_index_pkt4_receive = ServerHooks::getServerHooks()
  974. .getIndex("pkt4_receive"));
  975. EXPECT_NO_THROW(hook_index_select_subnet = ServerHooks::getServerHooks()
  976. .getIndex("subnet4_select"));
  977. EXPECT_NO_THROW(hook_index_lease4_release = ServerHooks::getServerHooks()
  978. .getIndex("lease4_release"));
  979. EXPECT_NO_THROW(hook_index_pkt4_send = ServerHooks::getServerHooks()
  980. .getIndex("pkt4_send"));
  981. EXPECT_NO_THROW(hook_index_buffer4_send = ServerHooks::getServerHooks()
  982. .getIndex("buffer4_send"));
  983. EXPECT_TRUE(hook_index_buffer4_receive > 0);
  984. EXPECT_TRUE(hook_index_pkt4_receive > 0);
  985. EXPECT_TRUE(hook_index_select_subnet > 0);
  986. EXPECT_TRUE(hook_index_lease4_release > 0);
  987. EXPECT_TRUE(hook_index_pkt4_send > 0);
  988. EXPECT_TRUE(hook_index_buffer4_send > 0);
  989. }
  990. // This test verifies that the following option structure can be parsed:
  991. // - option (option space 'foobar')
  992. // - sub option (option space 'foo')
  993. // - sub option (option space 'bar')
  994. // @todo Add more thorough unit tests for unpackOptions.
  995. TEST_F(Dhcpv4SrvTest, unpackOptions) {
  996. // Create option definition for each level of encapsulation. Each option
  997. // definition is for the option code 1. Options may have the same
  998. // option code because they belong to different option spaces.
  999. // Top level option encapsulates options which belong to 'space-foo'.
  1000. OptionDefinitionPtr opt_def(new OptionDefinition("option-foobar", 1, "uint32",
  1001. "space-foo"));\
  1002. // Middle option encapsulates options which belong to 'space-bar'
  1003. OptionDefinitionPtr opt_def2(new OptionDefinition("option-foo", 1, "uint16",
  1004. "space-bar"));
  1005. // Low level option doesn't encapsulate any option space.
  1006. OptionDefinitionPtr opt_def3(new OptionDefinition("option-bar", 1,
  1007. "uint8"));
  1008. // Add option definitions to the Configuration Manager. Each goes under
  1009. // different option space.
  1010. CfgMgr& cfgmgr = CfgMgr::instance();
  1011. ASSERT_NO_THROW(cfgmgr.addOptionDef(opt_def, "space-foobar"));
  1012. ASSERT_NO_THROW(cfgmgr.addOptionDef(opt_def2, "space-foo"));
  1013. ASSERT_NO_THROW(cfgmgr.addOptionDef(opt_def3, "space-bar"));
  1014. // Create the buffer holding the structure of options.
  1015. const char raw_data[] = {
  1016. // First option starts here.
  1017. 0x01, // option code = 1
  1018. 0x0B, // option length = 11
  1019. 0x00, 0x01, 0x02, 0x03, // This option carries uint32 value
  1020. // Sub option starts here.
  1021. 0x01, // option code = 1
  1022. 0x05, // option length = 5
  1023. 0x01, 0x02, // this option carries uint16 value
  1024. // Last option starts here.
  1025. 0x01, // option code = 1
  1026. 0x01, // option length = 1
  1027. 0x00 // This option carries a single uint8
  1028. // value and has no sub options.
  1029. };
  1030. OptionBuffer buf(raw_data, raw_data + sizeof(raw_data));
  1031. // Parse options.
  1032. NakedDhcpv4Srv srv(0);
  1033. OptionCollection options;
  1034. ASSERT_NO_THROW(srv.unpackOptions(buf, "space-foobar", options));
  1035. // There should be one top level option.
  1036. ASSERT_EQ(1, options.size());
  1037. boost::shared_ptr<OptionInt<uint32_t> > option_foobar =
  1038. boost::dynamic_pointer_cast<OptionInt<uint32_t> >(options.begin()->
  1039. second);
  1040. ASSERT_TRUE(option_foobar);
  1041. EXPECT_EQ(1, option_foobar->getType());
  1042. EXPECT_EQ(0x00010203, option_foobar->getValue());
  1043. // There should be a middle level option held in option_foobar.
  1044. boost::shared_ptr<OptionInt<uint16_t> > option_foo =
  1045. boost::dynamic_pointer_cast<OptionInt<uint16_t> >(option_foobar->
  1046. getOption(1));
  1047. ASSERT_TRUE(option_foo);
  1048. EXPECT_EQ(1, option_foo->getType());
  1049. EXPECT_EQ(0x0102, option_foo->getValue());
  1050. // Finally, there should be a low level option under option_foo.
  1051. boost::shared_ptr<OptionInt<uint8_t> > option_bar =
  1052. boost::dynamic_pointer_cast<OptionInt<uint8_t> >(option_foo->getOption(1));
  1053. ASSERT_TRUE(option_bar);
  1054. EXPECT_EQ(1, option_bar->getType());
  1055. EXPECT_EQ(0x0, option_bar->getValue());
  1056. }
  1057. // Checks whether the server uses default (0.0.0.0) siaddr value, unless
  1058. // explicitly specified
  1059. TEST_F(Dhcpv4SrvTest, siaddrDefault) {
  1060. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  1061. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  1062. IOAddress hint("192.0.2.107");
  1063. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  1064. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  1065. OptionPtr clientid = generateClientId();
  1066. dis->addOption(clientid);
  1067. dis->setYiaddr(hint);
  1068. // Pass it to the server and get an offer
  1069. Pkt4Ptr offer = srv->processDiscover(dis);
  1070. ASSERT_TRUE(offer);
  1071. // Check if we get response at all
  1072. checkResponse(offer, DHCPOFFER, 1234);
  1073. // Verify that it is 0.0.0.0
  1074. EXPECT_EQ("0.0.0.0", offer->getSiaddr().toText());
  1075. }
  1076. // Checks whether the server uses specified siaddr value
  1077. TEST_F(Dhcpv4SrvTest, siaddr) {
  1078. boost::scoped_ptr<NakedDhcpv4Srv> srv;
  1079. ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
  1080. subnet_->setSiaddr(IOAddress("192.0.2.123"));
  1081. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  1082. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  1083. OptionPtr clientid = generateClientId();
  1084. dis->addOption(clientid);
  1085. // Pass it to the server and get an offer
  1086. Pkt4Ptr offer = srv->processDiscover(dis);
  1087. ASSERT_TRUE(offer);
  1088. // Check if we get response at all
  1089. checkResponse(offer, DHCPOFFER, 1234);
  1090. // Verify that its value is proper
  1091. EXPECT_EQ("192.0.2.123", offer->getSiaddr().toText());
  1092. }
  1093. // Checks if the next-server defined as global value is overridden by subnet
  1094. // specific value and returned in server messages. There's also similar test for
  1095. // checking parser only configuration, see Dhcp4ParserTest.nextServerOverride in
  1096. // config_parser_unittest.cc.
  1097. TEST_F(Dhcpv4SrvTest, nextServerOverride) {
  1098. NakedDhcpv4Srv srv(0);
  1099. ConstElementPtr status;
  1100. string config = "{ \"interfaces\": [ \"*\" ],"
  1101. "\"rebind-timer\": 2000, "
  1102. "\"renew-timer\": 1000, "
  1103. "\"next-server\": \"192.0.0.1\", "
  1104. "\"subnet4\": [ { "
  1105. " \"pool\": [ \"192.0.2.1 - 192.0.2.100\" ],"
  1106. " \"next-server\": \"1.2.3.4\", "
  1107. " \"subnet\": \"192.0.2.0/24\" } ],"
  1108. "\"valid-lifetime\": 4000 }";
  1109. ElementPtr json = Element::fromJSON(config);
  1110. EXPECT_NO_THROW(status = configureDhcp4Server(srv, json));
  1111. // check if returned status is OK
  1112. ASSERT_TRUE(status);
  1113. comment_ = config::parseAnswer(rcode_, status);
  1114. ASSERT_EQ(0, rcode_);
  1115. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  1116. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  1117. OptionPtr clientid = generateClientId();
  1118. dis->addOption(clientid);
  1119. // Pass it to the server and get an offer
  1120. Pkt4Ptr offer = srv.processDiscover(dis);
  1121. ASSERT_TRUE(offer);
  1122. EXPECT_EQ(DHCPOFFER, offer->getType());
  1123. EXPECT_EQ("1.2.3.4", offer->getSiaddr().toText());
  1124. }
  1125. // Checks if the next-server defined as global value is used in responses
  1126. // when there is no specific value defined in subnet and returned to the client
  1127. // properly. There's also similar test for checking parser only configuration,
  1128. // see Dhcp4ParserTest.nextServerGlobal in config_parser_unittest.cc.
  1129. TEST_F(Dhcpv4SrvTest, nextServerGlobal) {
  1130. NakedDhcpv4Srv srv(0);
  1131. ConstElementPtr status;
  1132. string config = "{ \"interfaces\": [ \"*\" ],"
  1133. "\"rebind-timer\": 2000, "
  1134. "\"renew-timer\": 1000, "
  1135. "\"next-server\": \"192.0.0.1\", "
  1136. "\"subnet4\": [ { "
  1137. " \"pool\": [ \"192.0.2.1 - 192.0.2.100\" ],"
  1138. " \"subnet\": \"192.0.2.0/24\" } ],"
  1139. "\"valid-lifetime\": 4000 }";
  1140. ElementPtr json = Element::fromJSON(config);
  1141. EXPECT_NO_THROW(status = configureDhcp4Server(srv, json));
  1142. // check if returned status is OK
  1143. ASSERT_TRUE(status);
  1144. comment_ = config::parseAnswer(rcode_, status);
  1145. ASSERT_EQ(0, rcode_);
  1146. Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  1147. dis->setRemoteAddr(IOAddress("192.0.2.1"));
  1148. OptionPtr clientid = generateClientId();
  1149. dis->addOption(clientid);
  1150. // Pass it to the server and get an offer
  1151. Pkt4Ptr offer = srv.processDiscover(dis);
  1152. ASSERT_TRUE(offer);
  1153. EXPECT_EQ(DHCPOFFER, offer->getType());
  1154. EXPECT_EQ("192.0.0.1", offer->getSiaddr().toText());
  1155. }
  1156. // a dummy MAC address
  1157. const uint8_t dummyMacAddr[] = {0, 1, 2, 3, 4, 5};
  1158. // A dummy MAC address, padded with 0s
  1159. const uint8_t dummyChaddr[16] = {0, 1, 2, 3, 4, 5, 0, 0,
  1160. 0, 0, 0, 0, 0, 0, 0, 0 };
  1161. // Let's use some creative test content here (128 chars + \0)
  1162. const uint8_t dummyFile[] = "Lorem ipsum dolor sit amet, consectetur "
  1163. "adipiscing elit. Proin mollis placerat metus, at "
  1164. "lacinia orci ornare vitae. Mauris amet.";
  1165. // Yet another type of test content (64 chars + \0)
  1166. const uint8_t dummySname[] = "Lorem ipsum dolor sit amet, consectetur "
  1167. "adipiscing elit posuere.";
  1168. /// @brief a class dedicated to Hooks testing in DHCPv4 server
  1169. ///
  1170. /// This class has a number of static members, because each non-static
  1171. /// method has implicit 'this' parameter, so it does not match callout
  1172. /// signature and couldn't be registered. Furthermore, static methods
  1173. /// can't modify non-static members (for obvious reasons), so many
  1174. /// fields are declared static. It is still better to keep them as
  1175. /// one class rather than unrelated collection of global objects.
  1176. class HooksDhcpv4SrvTest : public Dhcpv4SrvTest {
  1177. public:
  1178. /// @brief creates Dhcpv4Srv and prepares buffers for callouts
  1179. HooksDhcpv4SrvTest() {
  1180. // Allocate new DHCPv6 Server
  1181. srv_ = new NakedDhcpv4Srv(0);
  1182. // clear static buffers
  1183. resetCalloutBuffers();
  1184. }
  1185. /// @brief destructor (deletes Dhcpv4Srv)
  1186. virtual ~HooksDhcpv4SrvTest() {
  1187. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("buffer4_receive");
  1188. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("buffer4_send");
  1189. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("pkt4_receive");
  1190. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("pkt4_send");
  1191. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("subnet4_select");
  1192. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("lease4_renew");
  1193. HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("lease4_release");
  1194. delete srv_;
  1195. }
  1196. /// @brief creates an option with specified option code
  1197. ///
  1198. /// This method is static, because it is used from callouts
  1199. /// that do not have a pointer to HooksDhcpv4SSrvTest object
  1200. ///
  1201. /// @param option_code code of option to be created
  1202. ///
  1203. /// @return pointer to create option object
  1204. static OptionPtr createOption(uint16_t option_code) {
  1205. char payload[] = {
  1206. 0xa, 0xb, 0xc, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14
  1207. };
  1208. OptionBuffer tmp(payload, payload + sizeof(payload));
  1209. return OptionPtr(new Option(Option::V4, option_code, tmp));
  1210. }
  1211. /// @brief Generates test packet.
  1212. ///
  1213. /// Allocates and generates on-wire buffer that represents test packet, with all
  1214. /// fixed fields set to non-zero values. Content is not always reasonable.
  1215. ///
  1216. /// See generateTestPacket1() function that returns exactly the same packet as
  1217. /// Pkt4 object.
  1218. ///
  1219. /// @return pointer to allocated Pkt4 object
  1220. // Returns a vector containing a DHCPv4 packet header.
  1221. Pkt4Ptr
  1222. generateSimpleDiscover() {
  1223. // That is only part of the header. It contains all "short" fields,
  1224. // larger fields are constructed separately.
  1225. uint8_t hdr[] = {
  1226. 1, 6, 6, 13, // op, htype, hlen, hops,
  1227. 0x12, 0x34, 0x56, 0x78, // transaction-id
  1228. 0, 42, 0x80, 0x00, // 42 secs, BROADCAST flags
  1229. 192, 0, 2, 1, // ciaddr
  1230. 1, 2, 3, 4, // yiaddr
  1231. 192, 0, 2, 255, // siaddr
  1232. 255, 255, 255, 255, // giaddr
  1233. };
  1234. // Initialize the vector with the header fields defined above.
  1235. vector<uint8_t> buf(hdr, hdr + sizeof(hdr));
  1236. // Append the large header fields.
  1237. copy(dummyChaddr, dummyChaddr + Pkt4::MAX_CHADDR_LEN, back_inserter(buf));
  1238. copy(dummySname, dummySname + Pkt4::MAX_SNAME_LEN, back_inserter(buf));
  1239. copy(dummyFile, dummyFile + Pkt4::MAX_FILE_LEN, back_inserter(buf));
  1240. // Should now have all the header, so check. The "static_cast" is used
  1241. // to get round an odd bug whereby the linker appears not to find the
  1242. // definition of DHCPV4_PKT_HDR_LEN if it appears within an EXPECT_EQ().
  1243. EXPECT_EQ(static_cast<size_t>(Pkt4::DHCPV4_PKT_HDR_LEN), buf.size());
  1244. // Add magic cookie
  1245. buf.push_back(0x63);
  1246. buf.push_back(0x82);
  1247. buf.push_back(0x53);
  1248. buf.push_back(0x63);
  1249. // Add message type DISCOVER
  1250. buf.push_back(static_cast<uint8_t>(DHO_DHCP_MESSAGE_TYPE));
  1251. buf.push_back(1); // length (just one byte)
  1252. buf.push_back(static_cast<uint8_t>(DHCPDISCOVER));
  1253. return (Pkt4Ptr(new Pkt4(&buf[0], buf.size())));
  1254. }
  1255. /// Test callback that stores received callout name and pkt4 value
  1256. /// @param callout_handle handle passed by the hooks framework
  1257. /// @return always 0
  1258. static int
  1259. buffer4_receive_callout(CalloutHandle& callout_handle) {
  1260. callback_name_ = string("buffer4_receive");
  1261. callout_handle.getArgument("query4", callback_pkt4_);
  1262. callback_argument_names_ = callout_handle.getArgumentNames();
  1263. return (0);
  1264. }
  1265. /// Test callback that changes hwaddr value
  1266. /// @param callout_handle handle passed by the hooks framework
  1267. /// @return always 0
  1268. static int
  1269. buffer4_receive_change_hwaddr(CalloutHandle& callout_handle) {
  1270. Pkt4Ptr pkt;
  1271. callout_handle.getArgument("query4", pkt);
  1272. // If there is at least one option with data
  1273. if (pkt->data_.size() >= Pkt4::DHCPV4_PKT_HDR_LEN) {
  1274. // Offset of the first byte of the CHWADDR field. Let's the first
  1275. // byte to some new value that we could later check
  1276. pkt->data_[28] = 0xff;
  1277. }
  1278. // Carry on as usual
  1279. return buffer4_receive_callout(callout_handle);
  1280. }
  1281. /// Test callback that deletes MAC address
  1282. /// @param callout_handle handle passed by the hooks framework
  1283. /// @return always 0
  1284. static int
  1285. buffer4_receive_delete_hwaddr(CalloutHandle& callout_handle) {
  1286. Pkt4Ptr pkt;
  1287. callout_handle.getArgument("query4", pkt);
  1288. pkt->data_[2] = 0; // offset 2 is hlen, let's set it to zero
  1289. memset(&pkt->data_[28], 0, Pkt4::MAX_CHADDR_LEN); // Clear CHADDR content
  1290. // carry on as usual
  1291. return buffer4_receive_callout(callout_handle);
  1292. }
  1293. /// Test callback that sets skip flag
  1294. /// @param callout_handle handle passed by the hooks framework
  1295. /// @return always 0
  1296. static int
  1297. buffer4_receive_skip(CalloutHandle& callout_handle) {
  1298. callout_handle.setSkip(true);
  1299. // Carry on as usual
  1300. return buffer4_receive_callout(callout_handle);
  1301. }
  1302. /// test callback that stores received callout name and pkt4 value
  1303. /// @param callout_handle handle passed by the hooks framework
  1304. /// @return always 0
  1305. static int
  1306. pkt4_receive_callout(CalloutHandle& callout_handle) {
  1307. callback_name_ = string("pkt4_receive");
  1308. callout_handle.getArgument("query4", callback_pkt4_);
  1309. callback_argument_names_ = callout_handle.getArgumentNames();
  1310. return (0);
  1311. }
  1312. /// test callback that changes client-id value
  1313. /// @param callout_handle handle passed by the hooks framework
  1314. /// @return always 0
  1315. static int
  1316. pkt4_receive_change_clientid(CalloutHandle& callout_handle) {
  1317. Pkt4Ptr pkt;
  1318. callout_handle.getArgument("query4", pkt);
  1319. // get rid of the old client-id
  1320. pkt->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1321. // add a new option
  1322. pkt->addOption(createOption(DHO_DHCP_CLIENT_IDENTIFIER));
  1323. // carry on as usual
  1324. return pkt4_receive_callout(callout_handle);
  1325. }
  1326. /// test callback that deletes client-id
  1327. /// @param callout_handle handle passed by the hooks framework
  1328. /// @return always 0
  1329. static int
  1330. pkt4_receive_delete_clientid(CalloutHandle& callout_handle) {
  1331. Pkt4Ptr pkt;
  1332. callout_handle.getArgument("query4", pkt);
  1333. // get rid of the old client-id (and no HWADDR)
  1334. vector<uint8_t> mac;
  1335. pkt->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1336. pkt->setHWAddr(1, 0, mac); // HWtype 1, hwardware len = 0
  1337. // carry on as usual
  1338. return pkt4_receive_callout(callout_handle);
  1339. }
  1340. /// test callback that sets skip flag
  1341. /// @param callout_handle handle passed by the hooks framework
  1342. /// @return always 0
  1343. static int
  1344. pkt4_receive_skip(CalloutHandle& callout_handle) {
  1345. Pkt4Ptr pkt;
  1346. callout_handle.getArgument("query4", pkt);
  1347. callout_handle.setSkip(true);
  1348. // carry on as usual
  1349. return pkt4_receive_callout(callout_handle);
  1350. }
  1351. /// Test callback that stores received callout name and pkt4 value
  1352. /// @param callout_handle handle passed by the hooks framework
  1353. /// @return always 0
  1354. static int
  1355. pkt4_send_callout(CalloutHandle& callout_handle) {
  1356. callback_name_ = string("pkt4_send");
  1357. callout_handle.getArgument("response4", callback_pkt4_);
  1358. callback_argument_names_ = callout_handle.getArgumentNames();
  1359. return (0);
  1360. }
  1361. // Test callback that changes server-id
  1362. /// @param callout_handle handle passed by the hooks framework
  1363. /// @return always 0
  1364. static int
  1365. pkt4_send_change_serverid(CalloutHandle& callout_handle) {
  1366. Pkt4Ptr pkt;
  1367. callout_handle.getArgument("response4", pkt);
  1368. // get rid of the old server-id
  1369. pkt->delOption(DHO_DHCP_SERVER_IDENTIFIER);
  1370. // add a new option
  1371. pkt->addOption(createOption(DHO_DHCP_SERVER_IDENTIFIER));
  1372. // carry on as usual
  1373. return pkt4_send_callout(callout_handle);
  1374. }
  1375. /// test callback that deletes server-id
  1376. /// @param callout_handle handle passed by the hooks framework
  1377. /// @return always 0
  1378. static int
  1379. pkt4_send_delete_serverid(CalloutHandle& callout_handle) {
  1380. Pkt4Ptr pkt;
  1381. callout_handle.getArgument("response4", pkt);
  1382. // get rid of the old client-id
  1383. pkt->delOption(DHO_DHCP_SERVER_IDENTIFIER);
  1384. // carry on as usual
  1385. return pkt4_send_callout(callout_handle);
  1386. }
  1387. /// Test callback that sets skip flag
  1388. /// @param callout_handle handle passed by the hooks framework
  1389. /// @return always 0
  1390. static int
  1391. pkt4_send_skip(CalloutHandle& callout_handle) {
  1392. Pkt4Ptr pkt;
  1393. callout_handle.getArgument("response4", pkt);
  1394. callout_handle.setSkip(true);
  1395. // carry on as usual
  1396. return pkt4_send_callout(callout_handle);
  1397. }
  1398. /// Test callback that stores received callout name and pkt4 value
  1399. /// @param callout_handle handle passed by the hooks framework
  1400. /// @return always 0
  1401. static int
  1402. buffer4_send_callout(CalloutHandle& callout_handle) {
  1403. callback_name_ = string("buffer4_send");
  1404. callout_handle.getArgument("response4", callback_pkt4_);
  1405. callback_argument_names_ = callout_handle.getArgumentNames();
  1406. return (0);
  1407. }
  1408. /// Test callback changes the output buffer to a hardcoded value
  1409. /// @param callout_handle handle passed by the hooks framework
  1410. /// @return always 0
  1411. static int
  1412. buffer4_send_change_callout(CalloutHandle& callout_handle) {
  1413. Pkt4Ptr pkt;
  1414. callout_handle.getArgument("response4", pkt);
  1415. // modify buffer to set a diffferent payload
  1416. pkt->getBuffer().clear();
  1417. pkt->getBuffer().writeData(dummyFile, sizeof(dummyFile));
  1418. return (0);
  1419. }
  1420. /// Test callback that stores received callout name and pkt4 value
  1421. /// @param callout_handle handle passed by the hooks framework
  1422. /// @return always 0
  1423. static int
  1424. skip_callout(CalloutHandle& callout_handle) {
  1425. callout_handle.setSkip(true);
  1426. return (0);
  1427. }
  1428. /// Test callback that stores received callout name and subnet4 values
  1429. /// @param callout_handle handle passed by the hooks framework
  1430. /// @return always 0
  1431. static int
  1432. subnet4_select_callout(CalloutHandle& callout_handle) {
  1433. callback_name_ = string("subnet4_select");
  1434. callout_handle.getArgument("query4", callback_pkt4_);
  1435. callout_handle.getArgument("subnet4", callback_subnet4_);
  1436. callout_handle.getArgument("subnet4collection", callback_subnet4collection_);
  1437. callback_argument_names_ = callout_handle.getArgumentNames();
  1438. return (0);
  1439. }
  1440. /// Test callback that picks the other subnet if possible.
  1441. /// @param callout_handle handle passed by the hooks framework
  1442. /// @return always 0
  1443. static int
  1444. subnet4_select_different_subnet_callout(CalloutHandle& callout_handle) {
  1445. // Call the basic calllout to record all passed values
  1446. subnet4_select_callout(callout_handle);
  1447. const Subnet4Collection* subnets;
  1448. Subnet4Ptr subnet;
  1449. callout_handle.getArgument("subnet4", subnet);
  1450. callout_handle.getArgument("subnet4collection", subnets);
  1451. // Let's change to a different subnet
  1452. if (subnets->size() > 1) {
  1453. subnet = (*subnets)[1]; // Let's pick the other subnet
  1454. callout_handle.setArgument("subnet4", subnet);
  1455. }
  1456. return (0);
  1457. }
  1458. /// Test callback that stores received callout name passed parameters
  1459. /// @param callout_handle handle passed by the hooks framework
  1460. /// @return always 0
  1461. static int
  1462. lease4_release_callout(CalloutHandle& callout_handle) {
  1463. callback_name_ = string("lease4_release");
  1464. callout_handle.getArgument("query4", callback_pkt4_);
  1465. callout_handle.getArgument("lease4", callback_lease4_);
  1466. callback_argument_names_ = callout_handle.getArgumentNames();
  1467. return (0);
  1468. }
  1469. /// Test callback that stores received callout name and subnet4 values
  1470. /// @param callout_handle handle passed by the hooks framework
  1471. /// @return always 0
  1472. static int
  1473. lease4_renew_callout(CalloutHandle& callout_handle) {
  1474. callback_name_ = string("lease4_renew");
  1475. callout_handle.getArgument("subnet4", callback_subnet4_);
  1476. callout_handle.getArgument("lease4", callback_lease4_);
  1477. callout_handle.getArgument("hwaddr", callback_hwaddr_);
  1478. callout_handle.getArgument("clientid", callback_clientid_);
  1479. callback_argument_names_ = callout_handle.getArgumentNames();
  1480. return (0);
  1481. }
  1482. /// resets buffers used to store data received by callouts
  1483. void resetCalloutBuffers() {
  1484. callback_name_ = string("");
  1485. callback_pkt4_.reset();
  1486. callback_lease4_.reset();
  1487. callback_hwaddr_.reset();
  1488. callback_clientid_.reset();
  1489. callback_subnet4_.reset();
  1490. callback_subnet4collection_ = NULL;
  1491. callback_argument_names_.clear();
  1492. }
  1493. /// pointer to Dhcpv4Srv that is used in tests
  1494. NakedDhcpv4Srv* srv_;
  1495. // The following fields are used in testing pkt4_receive_callout
  1496. /// String name of the received callout
  1497. static string callback_name_;
  1498. /// Pkt4 structure returned in the callout
  1499. static Pkt4Ptr callback_pkt4_;
  1500. /// Lease4 structure returned in the callout
  1501. static Lease4Ptr callback_lease4_;
  1502. /// Hardware address returned in the callout
  1503. static HWAddrPtr callback_hwaddr_;
  1504. /// Client-id returned in the callout
  1505. static ClientIdPtr callback_clientid_;
  1506. /// Pointer to a subnet received by callout
  1507. static Subnet4Ptr callback_subnet4_;
  1508. /// A list of all available subnets (received by callout)
  1509. static const Subnet4Collection* callback_subnet4collection_;
  1510. /// A list of all received arguments
  1511. static vector<string> callback_argument_names_;
  1512. };
  1513. // The following fields are used in testing pkt4_receive_callout.
  1514. // See fields description in the class for details
  1515. string HooksDhcpv4SrvTest::callback_name_;
  1516. Pkt4Ptr HooksDhcpv4SrvTest::callback_pkt4_;
  1517. Subnet4Ptr HooksDhcpv4SrvTest::callback_subnet4_;
  1518. HWAddrPtr HooksDhcpv4SrvTest::callback_hwaddr_;
  1519. ClientIdPtr HooksDhcpv4SrvTest::callback_clientid_;
  1520. Lease4Ptr HooksDhcpv4SrvTest::callback_lease4_;
  1521. const Subnet4Collection* HooksDhcpv4SrvTest::callback_subnet4collection_;
  1522. vector<string> HooksDhcpv4SrvTest::callback_argument_names_;
  1523. // Checks if callouts installed on pkt4_receive are indeed called and the
  1524. // all necessary parameters are passed.
  1525. //
  1526. // Note that the test name does not follow test naming convention,
  1527. // but the proper hook name is "buffer4_receive".
  1528. TEST_F(HooksDhcpv4SrvTest, Buffer4ReceiveSimple) {
  1529. // Install pkt4_receive_callout
  1530. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1531. "buffer4_receive", buffer4_receive_callout));
  1532. // Let's create a simple DISCOVER
  1533. Pkt4Ptr dis = generateSimpleDiscover();
  1534. // Simulate that we have received that traffic
  1535. srv_->fakeReceive(dis);
  1536. // Server will now process to run its normal loop, but instead of calling
  1537. // IfaceMgr::receive4(), it will read all packets from the list set by
  1538. // fakeReceive()
  1539. // In particular, it should call registered buffer4_receive callback.
  1540. srv_->run();
  1541. // Check that the callback called is indeed the one we installed
  1542. EXPECT_EQ("buffer4_receive", callback_name_);
  1543. // Check that pkt4 argument passing was successful and returned proper value
  1544. EXPECT_TRUE(callback_pkt4_.get() == dis.get());
  1545. // Check that all expected parameters are there
  1546. vector<string> expected_argument_names;
  1547. expected_argument_names.push_back(string("query4"));
  1548. EXPECT_TRUE(expected_argument_names == callback_argument_names_);
  1549. }
  1550. // Checks if callouts installed on buffer4_receive is able to change
  1551. // the values and the parameters are indeed used by the server.
  1552. TEST_F(HooksDhcpv4SrvTest, buffer4RreceiveValueChange) {
  1553. // Install callback that modifies MAC addr of incoming packet
  1554. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1555. "buffer4_receive", buffer4_receive_change_hwaddr));
  1556. // Let's create a simple DISCOVER
  1557. Pkt4Ptr discover = generateSimpleDiscover();
  1558. // Simulate that we have received that traffic
  1559. srv_->fakeReceive(discover);
  1560. // Server will now process to run its normal loop, but instead of calling
  1561. // IfaceMgr::receive6(), it will read all packets from the list set by
  1562. // fakeReceive()
  1563. // In particular, it should call registered buffer4_receive callback.
  1564. srv_->run();
  1565. // Check that the server did send a reposonse
  1566. ASSERT_EQ(1, srv_->fake_sent_.size());
  1567. // Make sure that we received a response
  1568. Pkt4Ptr offer = srv_->fake_sent_.front();
  1569. ASSERT_TRUE(offer);
  1570. // Get client-id...
  1571. HWAddrPtr hwaddr = offer->getHWAddr();
  1572. ASSERT_TRUE(hwaddr); // basic sanity check. HWAddr is always present
  1573. // ... and check if it is the modified value
  1574. ASSERT_FALSE(hwaddr->hwaddr_.empty()); // there must be a MAC address
  1575. EXPECT_EQ(0xff, hwaddr->hwaddr_[0]); // check that its first byte was modified
  1576. }
  1577. // Checks if callouts installed on buffer4_receive is able to set skip flag that
  1578. // will cause the server to not parse the packet. Even though the packet is valid,
  1579. // the server should eventually drop it, because there won't be mandatory options
  1580. // (or rather option objects) in it.
  1581. TEST_F(HooksDhcpv4SrvTest, buffer4ReceiveSkip) {
  1582. // Install pkt4_receive_callout
  1583. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1584. "buffer4_receive", buffer4_receive_skip));
  1585. // Let's create a simple DISCOVER
  1586. Pkt4Ptr discover = generateSimpleDiscover();
  1587. // Simulate that we have received that traffic
  1588. srv_->fakeReceive(discover);
  1589. // Server will now process to run its normal loop, but instead of calling
  1590. // IfaceMgr::receive6(), it will read all packets from the list set by
  1591. // fakeReceive()
  1592. // In particular, it should call registered pkt4_receive callback.
  1593. srv_->run();
  1594. // Check that the server dropped the packet and did not produce any response
  1595. ASSERT_EQ(0, srv_->fake_sent_.size());
  1596. }
  1597. // Checks if callouts installed on pkt4_receive are indeed called and the
  1598. // all necessary parameters are passed.
  1599. //
  1600. // Note that the test name does not follow test naming convention,
  1601. // but the proper hook name is "pkt4_receive".
  1602. TEST_F(HooksDhcpv4SrvTest, pkt4ReceiveSimple) {
  1603. // Install pkt4_receive_callout
  1604. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1605. "pkt4_receive", pkt4_receive_callout));
  1606. // Let's create a simple DISCOVER
  1607. Pkt4Ptr sol = generateSimpleDiscover();
  1608. // Simulate that we have received that traffic
  1609. srv_->fakeReceive(sol);
  1610. // Server will now process to run its normal loop, but instead of calling
  1611. // IfaceMgr::receive4(), it will read all packets from the list set by
  1612. // fakeReceive()
  1613. // In particular, it should call registered pkt4_receive callback.
  1614. srv_->run();
  1615. // check that the callback called is indeed the one we installed
  1616. EXPECT_EQ("pkt4_receive", callback_name_);
  1617. // check that pkt4 argument passing was successful and returned proper value
  1618. EXPECT_TRUE(callback_pkt4_.get() == sol.get());
  1619. // Check that all expected parameters are there
  1620. vector<string> expected_argument_names;
  1621. expected_argument_names.push_back(string("query4"));
  1622. EXPECT_TRUE(expected_argument_names == callback_argument_names_);
  1623. }
  1624. // Checks if callouts installed on pkt4_received is able to change
  1625. // the values and the parameters are indeed used by the server.
  1626. TEST_F(HooksDhcpv4SrvTest, valueChange_pkt4_receive) {
  1627. // Install pkt4_receive_callout
  1628. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1629. "pkt4_receive", pkt4_receive_change_clientid));
  1630. // Let's create a simple DISCOVER
  1631. Pkt4Ptr sol = generateSimpleDiscover();
  1632. // Simulate that we have received that traffic
  1633. srv_->fakeReceive(sol);
  1634. // Server will now process to run its normal loop, but instead of calling
  1635. // IfaceMgr::receive4(), it will read all packets from the list set by
  1636. // fakeReceive()
  1637. // In particular, it should call registered pkt4_receive callback.
  1638. srv_->run();
  1639. // check that the server did send a reposonce
  1640. ASSERT_EQ(1, srv_->fake_sent_.size());
  1641. // Make sure that we received a response
  1642. Pkt4Ptr adv = srv_->fake_sent_.front();
  1643. ASSERT_TRUE(adv);
  1644. // Get client-id...
  1645. OptionPtr clientid = adv->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1646. // ... and check if it is the modified value
  1647. OptionPtr expected = createOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1648. EXPECT_TRUE(clientid->equal(expected));
  1649. }
  1650. // Checks if callouts installed on pkt4_received is able to delete
  1651. // existing options and that change impacts server processing (mandatory
  1652. // client-id option is deleted, so the packet is expected to be dropped)
  1653. TEST_F(HooksDhcpv4SrvTest, pkt4ReceiveDeleteClientId) {
  1654. // Install pkt4_receive_callout
  1655. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1656. "pkt4_receive", pkt4_receive_delete_clientid));
  1657. // Let's create a simple DISCOVER
  1658. Pkt4Ptr sol = generateSimpleDiscover();
  1659. // Simulate that we have received that traffic
  1660. srv_->fakeReceive(sol);
  1661. // Server will now process to run its normal loop, but instead of calling
  1662. // IfaceMgr::receive4(), it will read all packets from the list set by
  1663. // fakeReceive()
  1664. // In particular, it should call registered pkt4_receive callback.
  1665. srv_->run();
  1666. // Check that the server dropped the packet and did not send a response
  1667. ASSERT_EQ(0, srv_->fake_sent_.size());
  1668. }
  1669. // Checks if callouts installed on pkt4_received is able to set skip flag that
  1670. // will cause the server to not process the packet (drop), even though it is valid.
  1671. TEST_F(HooksDhcpv4SrvTest, pkt4ReceiveSkip) {
  1672. // Install pkt4_receive_callout
  1673. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1674. "pkt4_receive", pkt4_receive_skip));
  1675. // Let's create a simple DISCOVER
  1676. Pkt4Ptr sol = generateSimpleDiscover();
  1677. // Simulate that we have received that traffic
  1678. srv_->fakeReceive(sol);
  1679. // Server will now process to run its normal loop, but instead of calling
  1680. // IfaceMgr::receive4(), it will read all packets from the list set by
  1681. // fakeReceive()
  1682. // In particular, it should call registered pkt4_receive callback.
  1683. srv_->run();
  1684. // check that the server dropped the packet and did not produce any response
  1685. ASSERT_EQ(0, srv_->fake_sent_.size());
  1686. }
  1687. // Checks if callouts installed on pkt4_send are indeed called and the
  1688. // all necessary parameters are passed.
  1689. TEST_F(HooksDhcpv4SrvTest, pkt4SendSimple) {
  1690. // Install pkt4_receive_callout
  1691. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1692. "pkt4_send", pkt4_send_callout));
  1693. // Let's create a simple DISCOVER
  1694. Pkt4Ptr sol = generateSimpleDiscover();
  1695. // Simulate that we have received that traffic
  1696. srv_->fakeReceive(sol);
  1697. // Server will now process to run its normal loop, but instead of calling
  1698. // IfaceMgr::receive4(), it will read all packets from the list set by
  1699. // fakeReceive()
  1700. // In particular, it should call registered pkt4_receive callback.
  1701. srv_->run();
  1702. // Check that the callback called is indeed the one we installed
  1703. EXPECT_EQ("pkt4_send", callback_name_);
  1704. // Check that there is one packet sent
  1705. ASSERT_EQ(1, srv_->fake_sent_.size());
  1706. Pkt4Ptr adv = srv_->fake_sent_.front();
  1707. // Check that pkt4 argument passing was successful and returned proper value
  1708. EXPECT_TRUE(callback_pkt4_.get() == adv.get());
  1709. // Check that all expected parameters are there
  1710. vector<string> expected_argument_names;
  1711. expected_argument_names.push_back(string("response4"));
  1712. EXPECT_TRUE(expected_argument_names == callback_argument_names_);
  1713. }
  1714. // Checks if callouts installed on pkt4_send is able to change
  1715. // the values and the packet sent contains those changes
  1716. TEST_F(HooksDhcpv4SrvTest, pkt4SendValueChange) {
  1717. // Install pkt4_receive_callout
  1718. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1719. "pkt4_send", pkt4_send_change_serverid));
  1720. // Let's create a simple DISCOVER
  1721. Pkt4Ptr sol = generateSimpleDiscover();
  1722. // Simulate that we have received that traffic
  1723. srv_->fakeReceive(sol);
  1724. // Server will now process to run its normal loop, but instead of calling
  1725. // IfaceMgr::receive4(), it will read all packets from the list set by
  1726. // fakeReceive()
  1727. // In particular, it should call registered pkt4_receive callback.
  1728. srv_->run();
  1729. // check that the server did send a reposonce
  1730. ASSERT_EQ(1, srv_->fake_sent_.size());
  1731. // Make sure that we received a response
  1732. Pkt4Ptr adv = srv_->fake_sent_.front();
  1733. ASSERT_TRUE(adv);
  1734. // Get client-id...
  1735. OptionPtr clientid = adv->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1736. // ... and check if it is the modified value
  1737. OptionPtr expected = createOption(DHO_DHCP_SERVER_IDENTIFIER);
  1738. EXPECT_TRUE(clientid->equal(expected));
  1739. }
  1740. // Checks if callouts installed on pkt4_send is able to delete
  1741. // existing options and that server applies those changes. In particular,
  1742. // we are trying to send a packet without server-id. The packet should
  1743. // be sent
  1744. TEST_F(HooksDhcpv4SrvTest, pkt4SendDeleteServerId) {
  1745. // Install pkt4_receive_callout
  1746. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1747. "pkt4_send", pkt4_send_delete_serverid));
  1748. // Let's create a simple DISCOVER
  1749. Pkt4Ptr sol = generateSimpleDiscover();
  1750. // Simulate that we have received that traffic
  1751. srv_->fakeReceive(sol);
  1752. // Server will now process to run its normal loop, but instead of calling
  1753. // IfaceMgr::receive4(), it will read all packets from the list set by
  1754. // fakeReceive()
  1755. // In particular, it should call registered pkt4_receive callback.
  1756. srv_->run();
  1757. // Check that the server indeed sent a malformed ADVERTISE
  1758. ASSERT_EQ(1, srv_->fake_sent_.size());
  1759. // Get that ADVERTISE
  1760. Pkt4Ptr adv = srv_->fake_sent_.front();
  1761. ASSERT_TRUE(adv);
  1762. // Make sure that it does not have server-id
  1763. EXPECT_FALSE(adv->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  1764. }
  1765. // Checks if callouts installed on pkt4_skip is able to set skip flag that
  1766. // will cause the server to not process the packet (drop), even though it is valid.
  1767. TEST_F(HooksDhcpv4SrvTest, skip_pkt4_send) {
  1768. // Install pkt4_receive_callout
  1769. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1770. "pkt4_send", pkt4_send_skip));
  1771. // Let's create a simple REQUEST
  1772. Pkt4Ptr sol = generateSimpleDiscover();
  1773. // Simulate that we have received that traffic
  1774. srv_->fakeReceive(sol);
  1775. // Server will now process to run its normal loop, but instead of calling
  1776. // IfaceMgr::receive4(), it will read all packets from the list set by
  1777. // fakeReceive()
  1778. // In particular, it should call registered pkt4_send callback.
  1779. srv_->run();
  1780. // Check that the server sent the message
  1781. ASSERT_EQ(1, srv_->fake_sent_.size());
  1782. // Get the first packet and check that it has zero length (i.e. the server
  1783. // did not do packing on its own)
  1784. Pkt4Ptr sent = srv_->fake_sent_.front();
  1785. EXPECT_EQ(0, sent->getBuffer().getLength());
  1786. }
  1787. // Checks if callouts installed on buffer4_send are indeed called and the
  1788. // all necessary parameters are passed.
  1789. TEST_F(HooksDhcpv4SrvTest, buffer4SendSimple) {
  1790. // Install pkt4_receive_callout
  1791. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1792. "buffer4_send", buffer4_send_callout));
  1793. // Let's create a simple DISCOVER
  1794. Pkt4Ptr discover = generateSimpleDiscover();
  1795. // Simulate that we have received that traffic
  1796. srv_->fakeReceive(discover);
  1797. // Server will now process to run its normal loop, but instead of calling
  1798. // IfaceMgr::receive4(), it will read all packets from the list set by
  1799. // fakeReceive()
  1800. // In particular, it should call registered pkt4_receive callback.
  1801. srv_->run();
  1802. // Check that the callback called is indeed the one we installed
  1803. EXPECT_EQ("buffer4_send", callback_name_);
  1804. // Check that there is one packet sent
  1805. ASSERT_EQ(1, srv_->fake_sent_.size());
  1806. Pkt4Ptr adv = srv_->fake_sent_.front();
  1807. // Check that pkt4 argument passing was successful and returned proper value
  1808. EXPECT_TRUE(callback_pkt4_.get() == adv.get());
  1809. // Check that all expected parameters are there
  1810. vector<string> expected_argument_names;
  1811. expected_argument_names.push_back(string("response4"));
  1812. EXPECT_TRUE(expected_argument_names == callback_argument_names_);
  1813. }
  1814. // Checks if callouts installed on buffer4_send are indeed called and that
  1815. // the output buffer can be changed.
  1816. TEST_F(HooksDhcpv4SrvTest, buffer4Send) {
  1817. // Install pkt4_receive_callout
  1818. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1819. "buffer4_send", buffer4_send_change_callout));
  1820. // Let's create a simple DISCOVER
  1821. Pkt4Ptr discover = generateSimpleDiscover();
  1822. // Simulate that we have received that traffic
  1823. srv_->fakeReceive(discover);
  1824. // Server will now process to run its normal loop, but instead of calling
  1825. // IfaceMgr::receive4(), it will read all packets from the list set by
  1826. // fakeReceive()
  1827. // In particular, it should call registered pkt4_receive callback.
  1828. srv_->run();
  1829. // Check that there is one packet sent
  1830. ASSERT_EQ(1, srv_->fake_sent_.size());
  1831. Pkt4Ptr adv = srv_->fake_sent_.front();
  1832. // The callout is supposed to fill the output buffer with dummyFile content
  1833. ASSERT_EQ(sizeof(dummyFile), adv->getBuffer().getLength());
  1834. EXPECT_EQ(0, memcmp(adv->getBuffer().getData(), dummyFile, sizeof(dummyFile)));
  1835. }
  1836. // Checks if callouts installed on buffer4_send can set skip flag and that flag
  1837. // causes the packet to not be sent
  1838. TEST_F(HooksDhcpv4SrvTest, buffer4SendSkip) {
  1839. // Install pkt4_receive_callout
  1840. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1841. "buffer4_send", skip_callout));
  1842. // Let's create a simple DISCOVER
  1843. Pkt4Ptr discover = generateSimpleDiscover();
  1844. // Simulate that we have received that traffic
  1845. srv_->fakeReceive(discover);
  1846. // Server will now process to run its normal loop, but instead of calling
  1847. // IfaceMgr::receive4(), it will read all packets from the list set by
  1848. // fakeReceive()
  1849. // In particular, it should call registered pkt4_receive callback.
  1850. srv_->run();
  1851. // Check that there is no packet sent.
  1852. ASSERT_EQ(0, srv_->fake_sent_.size());
  1853. }
  1854. // This test checks if subnet4_select callout is triggered and reports
  1855. // valid parameters
  1856. TEST_F(HooksDhcpv4SrvTest, subnet4SelectSimple) {
  1857. // Install pkt4_receive_callout
  1858. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1859. "subnet4_select", subnet4_select_callout));
  1860. // Configure 2 subnets, both directly reachable over local interface
  1861. // (let's not complicate the matter with relays)
  1862. string config = "{ \"interfaces\": [ \"*\" ],"
  1863. "\"rebind-timer\": 2000, "
  1864. "\"renew-timer\": 1000, "
  1865. "\"subnet4\": [ { "
  1866. " \"pool\": [ \"192.0.2.0/25\" ],"
  1867. " \"subnet\": \"192.0.2.0/24\", "
  1868. " \"interface\": \"" + valid_iface_ + "\" "
  1869. " }, {"
  1870. " \"pool\": [ \"192.0.3.0/25\" ],"
  1871. " \"subnet\": \"192.0.3.0/24\" "
  1872. " } ],"
  1873. "\"valid-lifetime\": 4000 }";
  1874. ElementPtr json = Element::fromJSON(config);
  1875. ConstElementPtr status;
  1876. // Configure the server and make sure the config is accepted
  1877. EXPECT_NO_THROW(status = configureDhcp4Server(*srv_, json));
  1878. ASSERT_TRUE(status);
  1879. comment_ = config::parseAnswer(rcode_, status);
  1880. ASSERT_EQ(0, rcode_);
  1881. // Prepare discover packet. Server should select first subnet for it
  1882. Pkt4Ptr sol = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  1883. sol->setRemoteAddr(IOAddress("192.0.2.1"));
  1884. sol->setIface(valid_iface_);
  1885. OptionPtr clientid = generateClientId();
  1886. sol->addOption(clientid);
  1887. // Pass it to the server and get an advertise
  1888. Pkt4Ptr adv = srv_->processDiscover(sol);
  1889. // check if we get response at all
  1890. ASSERT_TRUE(adv);
  1891. // Check that the callback called is indeed the one we installed
  1892. EXPECT_EQ("subnet4_select", callback_name_);
  1893. // Check that pkt4 argument passing was successful and returned proper value
  1894. EXPECT_TRUE(callback_pkt4_.get() == sol.get());
  1895. const Subnet4Collection* exp_subnets = CfgMgr::instance().getSubnets4();
  1896. // The server is supposed to pick the first subnet, because of matching
  1897. // interface. Check that the value is reported properly.
  1898. ASSERT_TRUE(callback_subnet4_);
  1899. EXPECT_EQ(exp_subnets->front().get(), callback_subnet4_.get());
  1900. // Server is supposed to report two subnets
  1901. ASSERT_EQ(exp_subnets->size(), callback_subnet4collection_->size());
  1902. // Compare that the available subnets are reported as expected
  1903. EXPECT_TRUE((*exp_subnets)[0].get() == (*callback_subnet4collection_)[0].get());
  1904. EXPECT_TRUE((*exp_subnets)[1].get() == (*callback_subnet4collection_)[1].get());
  1905. }
  1906. // This test checks if callout installed on subnet4_select hook point can pick
  1907. // a different subnet.
  1908. TEST_F(HooksDhcpv4SrvTest, subnet4SelectChange) {
  1909. // Install a callout
  1910. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1911. "subnet4_select", subnet4_select_different_subnet_callout));
  1912. // Configure 2 subnets, both directly reachable over local interface
  1913. // (let's not complicate the matter with relays)
  1914. string config = "{ \"interfaces\": [ \"*\" ],"
  1915. "\"rebind-timer\": 2000, "
  1916. "\"renew-timer\": 1000, "
  1917. "\"subnet4\": [ { "
  1918. " \"pool\": [ \"192.0.2.0/25\" ],"
  1919. " \"subnet\": \"192.0.2.0/24\", "
  1920. " \"interface\": \"" + valid_iface_ + "\" "
  1921. " }, {"
  1922. " \"pool\": [ \"192.0.3.0/25\" ],"
  1923. " \"subnet\": \"192.0.3.0/24\" "
  1924. " } ],"
  1925. "\"valid-lifetime\": 4000 }";
  1926. ElementPtr json = Element::fromJSON(config);
  1927. ConstElementPtr status;
  1928. // Configure the server and make sure the config is accepted
  1929. EXPECT_NO_THROW(status = configureDhcp4Server(*srv_, json));
  1930. ASSERT_TRUE(status);
  1931. comment_ = config::parseAnswer(rcode_, status);
  1932. ASSERT_EQ(0, rcode_);
  1933. // Prepare discover packet. Server should select first subnet for it
  1934. Pkt4Ptr sol = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
  1935. sol->setRemoteAddr(IOAddress("192.0.2.1"));
  1936. sol->setIface(valid_iface_);
  1937. OptionPtr clientid = generateClientId();
  1938. sol->addOption(clientid);
  1939. // Pass it to the server and get an advertise
  1940. Pkt4Ptr adv = srv_->processDiscover(sol);
  1941. // check if we get response at all
  1942. ASSERT_TRUE(adv);
  1943. // The response should have an address from second pool, so let's check it
  1944. IOAddress addr = adv->getYiaddr();
  1945. EXPECT_NE("0.0.0.0", addr.toText());
  1946. // Get all subnets and use second subnet for verification
  1947. const Subnet4Collection* subnets = CfgMgr::instance().getSubnets4();
  1948. ASSERT_EQ(2, subnets->size());
  1949. // Advertised address must belong to the second pool (in subnet's range,
  1950. // in dynamic pool)
  1951. EXPECT_TRUE((*subnets)[1]->inRange(addr));
  1952. EXPECT_TRUE((*subnets)[1]->inPool(Lease::TYPE_V4, addr));
  1953. }
  1954. // This test verifies that incoming (positive) REQUEST/Renewing can be handled
  1955. // properly and that callout installed on lease4_renew is triggered with
  1956. // expected parameters.
  1957. TEST_F(HooksDhcpv4SrvTest, lease4RenewSimple) {
  1958. const IOAddress addr("192.0.2.106");
  1959. const uint32_t temp_t1 = 50;
  1960. const uint32_t temp_t2 = 75;
  1961. const uint32_t temp_valid = 100;
  1962. const time_t temp_timestamp = time(NULL) - 10;
  1963. // Install a callout
  1964. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  1965. "lease4_renew", lease4_renew_callout));
  1966. // Generate client-id also sets client_id_ member
  1967. OptionPtr clientid = generateClientId();
  1968. // Check that the address we are about to use is indeed in pool
  1969. ASSERT_TRUE(subnet_->inPool(Lease::TYPE_V4, addr));
  1970. // let's create a lease and put it in the LeaseMgr
  1971. uint8_t hwaddr2[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  1972. Lease4Ptr used(new Lease4(IOAddress("192.0.2.106"), hwaddr2, sizeof(hwaddr2),
  1973. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  1974. temp_valid, temp_t1, temp_t2, temp_timestamp,
  1975. subnet_->getID()));
  1976. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  1977. // Check that the lease is really in the database
  1978. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  1979. ASSERT_TRUE(l);
  1980. // Let's create a RENEW
  1981. Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234));
  1982. req->setRemoteAddr(IOAddress(addr));
  1983. req->setYiaddr(addr);
  1984. req->setCiaddr(addr); // client's address
  1985. req->addOption(clientid);
  1986. req->addOption(srv_->getServerID());
  1987. // Pass it to the server and hope for a REPLY
  1988. Pkt4Ptr ack = srv_->processRequest(req);
  1989. // Check if we get response at all
  1990. checkResponse(ack, DHCPACK, 1234);
  1991. // Check that the lease is really in the database
  1992. l = checkLease(ack, clientid, req->getHWAddr(), addr);
  1993. ASSERT_TRUE(l);
  1994. // Check that T1, T2, preferred, valid and cltt were really updated
  1995. EXPECT_EQ(l->t1_, subnet_->getT1());
  1996. EXPECT_EQ(l->t2_, subnet_->getT2());
  1997. EXPECT_EQ(l->valid_lft_, subnet_->getValid());
  1998. // Check that the callback called is indeed the one we installed
  1999. EXPECT_EQ("lease4_renew", callback_name_);
  2000. // Check that hwaddr parameter is passed properly
  2001. ASSERT_TRUE(callback_hwaddr_);
  2002. EXPECT_TRUE(*callback_hwaddr_ == *req->getHWAddr());
  2003. // Check that the subnet is passed properly
  2004. ASSERT_TRUE(callback_subnet4_);
  2005. EXPECT_EQ(callback_subnet4_->toText(), subnet_->toText());
  2006. ASSERT_TRUE(callback_clientid_);
  2007. ASSERT_TRUE(client_id_);
  2008. EXPECT_TRUE(*client_id_ == *callback_clientid_);
  2009. // Check if all expected parameters were really received
  2010. vector<string> expected_argument_names;
  2011. expected_argument_names.push_back("subnet4");
  2012. expected_argument_names.push_back("clientid");
  2013. expected_argument_names.push_back("hwaddr");
  2014. expected_argument_names.push_back("lease4");
  2015. sort(callback_argument_names_.begin(), callback_argument_names_.end());
  2016. sort(expected_argument_names.begin(), expected_argument_names.end());
  2017. EXPECT_TRUE(callback_argument_names_ == expected_argument_names);
  2018. EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(addr));
  2019. }
  2020. // This test verifies that a callout installed on lease4_renew can trigger
  2021. // the server to not renew a lease.
  2022. TEST_F(HooksDhcpv4SrvTest, lease4RenewSkip) {
  2023. const IOAddress addr("192.0.2.106");
  2024. const uint32_t temp_t1 = 50;
  2025. const uint32_t temp_t2 = 75;
  2026. const uint32_t temp_valid = 100;
  2027. const time_t temp_timestamp = time(NULL) - 10;
  2028. // Install a callout
  2029. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  2030. "lease4_renew", skip_callout));
  2031. // Generate client-id also sets client_id_ member
  2032. OptionPtr clientid = generateClientId();
  2033. // Check that the address we are about to use is indeed in pool
  2034. ASSERT_TRUE(subnet_->inPool(Lease::TYPE_V4, addr));
  2035. // let's create a lease and put it in the LeaseMgr
  2036. uint8_t hwaddr2[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  2037. Lease4Ptr used(new Lease4(IOAddress("192.0.2.106"), hwaddr2, sizeof(hwaddr2),
  2038. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  2039. temp_valid, temp_t1, temp_t2, temp_timestamp,
  2040. subnet_->getID()));
  2041. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  2042. // Check that the lease is really in the database
  2043. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  2044. ASSERT_TRUE(l);
  2045. // Check that T1, T2, preferred, valid and cltt really set.
  2046. // Constructed lease looks as if it was assigned 10 seconds ago
  2047. // EXPECT_EQ(l->t1_, temp_t1);
  2048. // EXPECT_EQ(l->t2_, temp_t2);
  2049. EXPECT_EQ(l->valid_lft_, temp_valid);
  2050. EXPECT_EQ(l->cltt_, temp_timestamp);
  2051. // Let's create a RENEW
  2052. Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234));
  2053. req->setRemoteAddr(IOAddress(addr));
  2054. req->setYiaddr(addr);
  2055. req->setCiaddr(addr); // client's address
  2056. req->addOption(clientid);
  2057. req->addOption(srv_->getServerID());
  2058. // Pass it to the server and hope for a REPLY
  2059. Pkt4Ptr ack = srv_->processRequest(req);
  2060. ASSERT_TRUE(ack);
  2061. // Check that the lease is really in the database
  2062. l = checkLease(ack, clientid, req->getHWAddr(), addr);
  2063. ASSERT_TRUE(l);
  2064. // Check that T1, T2, valid and cltt were NOT updated
  2065. EXPECT_EQ(temp_t1, l->t1_);
  2066. EXPECT_EQ(temp_t2, l->t2_);
  2067. EXPECT_EQ(temp_valid, l->valid_lft_);
  2068. EXPECT_EQ(temp_timestamp, l->cltt_);
  2069. EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(addr));
  2070. }
  2071. // This test verifies that valid RELEASE triggers lease4_release callouts
  2072. TEST_F(HooksDhcpv4SrvTest, lease4ReleaseSimple) {
  2073. const IOAddress addr("192.0.2.106");
  2074. const uint32_t temp_t1 = 50;
  2075. const uint32_t temp_t2 = 75;
  2076. const uint32_t temp_valid = 100;
  2077. const time_t temp_timestamp = time(NULL) - 10;
  2078. // Install a callout
  2079. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  2080. "lease4_release", lease4_release_callout));
  2081. // Generate client-id also duid_
  2082. OptionPtr clientid = generateClientId();
  2083. // Check that the address we are about to use is indeed in pool
  2084. ASSERT_TRUE(subnet_->inPool(Lease::TYPE_V4, addr));
  2085. // Let's create a lease and put it in the LeaseMgr
  2086. uint8_t mac_addr[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  2087. HWAddrPtr hw(new HWAddr(mac_addr, sizeof(mac_addr), HTYPE_ETHER));
  2088. Lease4Ptr used(new Lease4(addr, mac_addr, sizeof(mac_addr),
  2089. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  2090. temp_valid, temp_t1, temp_t2, temp_timestamp,
  2091. subnet_->getID()));
  2092. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  2093. // Check that the lease is really in the database
  2094. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  2095. ASSERT_TRUE(l);
  2096. // Let's create a RELEASE
  2097. // Generate client-id also duid_
  2098. Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
  2099. rel->setRemoteAddr(addr);
  2100. rel->setCiaddr(addr);
  2101. rel->addOption(clientid);
  2102. rel->addOption(srv_->getServerID());
  2103. rel->setHWAddr(hw);
  2104. // Pass it to the server and hope for a REPLY
  2105. // Note: this is no response to RELEASE in DHCPv4
  2106. EXPECT_NO_THROW(srv_->processRelease(rel));
  2107. // The lease should be gone from LeaseMgr
  2108. l = LeaseMgrFactory::instance().getLease4(addr);
  2109. EXPECT_FALSE(l);
  2110. // Try to get the lease by hardware address
  2111. // @todo: Uncomment this once trac2592 is implemented
  2112. // Lease4Collection leases = LeaseMgrFactory::instance().getLease4(hw->hwaddr_);
  2113. // EXPECT_EQ(leases.size(), 0);
  2114. // Try to get it by hw/subnet_id combination
  2115. l = LeaseMgrFactory::instance().getLease4(hw->hwaddr_, subnet_->getID());
  2116. EXPECT_FALSE(l);
  2117. // Try by client-id
  2118. // @todo: Uncomment this once trac2592 is implemented
  2119. //Lease4Collection leases = LeaseMgrFactory::instance().getLease4(*client_id_);
  2120. //EXPECT_EQ(leases.size(), 0);
  2121. // Try by client-id/subnet-id
  2122. l = LeaseMgrFactory::instance().getLease4(*client_id_, subnet_->getID());
  2123. EXPECT_FALSE(l);
  2124. // Ok, the lease is *really* not there.
  2125. // Check that the callback called is indeed the one we installed
  2126. EXPECT_EQ("lease4_release", callback_name_);
  2127. // Check that pkt4 argument passing was successful and returned proper value
  2128. EXPECT_TRUE(callback_pkt4_.get() == rel.get());
  2129. // Check if all expected parameters were really received
  2130. vector<string> expected_argument_names;
  2131. expected_argument_names.push_back("query4");
  2132. expected_argument_names.push_back("lease4");
  2133. sort(callback_argument_names_.begin(), callback_argument_names_.end());
  2134. sort(expected_argument_names.begin(), expected_argument_names.end());
  2135. EXPECT_TRUE(callback_argument_names_ == expected_argument_names);
  2136. }
  2137. // This test verifies that skip flag returned by a callout installed on the
  2138. // lease4_release hook point will keep the lease
  2139. TEST_F(HooksDhcpv4SrvTest, lease4ReleaseSkip) {
  2140. const IOAddress addr("192.0.2.106");
  2141. const uint32_t temp_t1 = 50;
  2142. const uint32_t temp_t2 = 75;
  2143. const uint32_t temp_valid = 100;
  2144. const time_t temp_timestamp = time(NULL) - 10;
  2145. // Install a callout
  2146. EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
  2147. "lease4_release", skip_callout));
  2148. // Generate client-id also duid_
  2149. OptionPtr clientid = generateClientId();
  2150. // Check that the address we are about to use is indeed in pool
  2151. ASSERT_TRUE(subnet_->inPool(Lease::TYPE_V4, addr));
  2152. // Let's create a lease and put it in the LeaseMgr
  2153. uint8_t mac_addr[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
  2154. HWAddrPtr hw(new HWAddr(mac_addr, sizeof(mac_addr), HTYPE_ETHER));
  2155. Lease4Ptr used(new Lease4(addr, mac_addr, sizeof(mac_addr),
  2156. &client_id_->getDuid()[0], client_id_->getDuid().size(),
  2157. temp_valid, temp_t1, temp_t2, temp_timestamp,
  2158. subnet_->getID()));
  2159. ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
  2160. // Check that the lease is really in the database
  2161. Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
  2162. ASSERT_TRUE(l);
  2163. // Let's create a RELEASE
  2164. // Generate client-id also duid_
  2165. Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
  2166. rel->setRemoteAddr(addr);
  2167. rel->setYiaddr(addr);
  2168. rel->addOption(clientid);
  2169. rel->addOption(srv_->getServerID());
  2170. rel->setHWAddr(hw);
  2171. // Pass it to the server and hope for a REPLY
  2172. // Note: this is no response to RELEASE in DHCPv4
  2173. EXPECT_NO_THROW(srv_->processRelease(rel));
  2174. // The lease should be still there
  2175. l = LeaseMgrFactory::instance().getLease4(addr);
  2176. EXPECT_TRUE(l);
  2177. // Try by client-id/subnet-id
  2178. l = LeaseMgrFactory::instance().getLease4(*client_id_, subnet_->getID());
  2179. EXPECT_TRUE(l);
  2180. // Try to get the lease by hardware address
  2181. // @todo: Uncomment this once trac2592 is implemented
  2182. // Lease4Collection leases = LeaseMgrFactory::instance().getLease4(hw->hwaddr_);
  2183. // EXPECT_EQ(leases.size(), 1);
  2184. // Try by client-id
  2185. // @todo: Uncomment this once trac2592 is implemented
  2186. //Lease4Collection leases = LeaseMgrFactory::instance().getLease4(*client_id_);
  2187. //EXPECT_EQ(leases.size(), 1);
  2188. }
  2189. // Checks if server is able to handle a relayed traffic from DOCSIS3.0 modems
  2190. TEST_F(Dhcpv4SrvTest, docsisVendorOptionsParse) {
  2191. // Let's get a traffic capture from DOCSIS3.0 modem
  2192. Pkt4Ptr dis = captureRelayedDiscover();
  2193. ASSERT_NO_THROW(dis->unpack());
  2194. // Check if the packet contain
  2195. OptionPtr opt = dis->getOption(DHO_VIVSO_SUBOPTIONS);
  2196. ASSERT_TRUE(opt);
  2197. boost::shared_ptr<OptionVendor> vendor = boost::dynamic_pointer_cast<OptionVendor>(opt);
  2198. ASSERT_TRUE(vendor);
  2199. // This particular capture that we have included options 1 and 5
  2200. EXPECT_TRUE(vendor->getOption(1));
  2201. EXPECT_TRUE(vendor->getOption(5));
  2202. // It did not include options any other options
  2203. EXPECT_FALSE(vendor->getOption(2));
  2204. EXPECT_FALSE(vendor->getOption(3));
  2205. EXPECT_FALSE(vendor->getOption(17));
  2206. }
  2207. // Checks if server is able to parse incoming docsis option and extract suboption 1 (docsis ORO)
  2208. TEST_F(Dhcpv4SrvTest, docsisVendorORO) {
  2209. // Let's get a traffic capture from DOCSIS3.0 modem
  2210. Pkt4Ptr dis = captureRelayedDiscover();
  2211. EXPECT_NO_THROW(dis->unpack());
  2212. // Check if the packet contains vendor specific information option
  2213. OptionPtr opt = dis->getOption(DHO_VIVSO_SUBOPTIONS);
  2214. ASSERT_TRUE(opt);
  2215. boost::shared_ptr<OptionVendor> vendor = boost::dynamic_pointer_cast<OptionVendor>(opt);
  2216. ASSERT_TRUE(vendor);
  2217. opt = vendor->getOption(DOCSIS3_V4_ORO);
  2218. ASSERT_TRUE(opt);
  2219. OptionUint8ArrayPtr oro = boost::dynamic_pointer_cast<OptionUint8Array>(opt);
  2220. EXPECT_TRUE(oro);
  2221. }
  2222. // This test checks if Option Request Option (ORO) in docsis (vendor-id=4491)
  2223. // vendor options is parsed correctly and the requested options are actually assigned.
  2224. TEST_F(Dhcpv4SrvTest, vendorOptionsORO) {
  2225. NakedDhcpv4Srv srv(0);
  2226. ConstElementPtr x;
  2227. string config = "{ \"interfaces\": [ \"all\" ],"
  2228. "\"rebind-timer\": 2000, "
  2229. "\"renew-timer\": 1000, "
  2230. " \"option-data\": [ {"
  2231. " \"name\": \"tftp-servers\","
  2232. " \"space\": \"vendor-4491\","
  2233. " \"code\": 2,"
  2234. " \"data\": \"192.0.2.1, 192.0.2.2\","
  2235. " \"csv-format\": True"
  2236. " }],"
  2237. "\"subnet4\": [ { "
  2238. " \"pool\": [ \"192.0.2.0/25\" ],"
  2239. " \"subnet\": \"192.0.2.0/24\", "
  2240. " \"rebind-timer\": 2000, "
  2241. " \"renew-timer\": 1000, "
  2242. " \"valid-lifetime\": 4000,"
  2243. " \"interface\": \"" + valid_iface_ + "\" "
  2244. " } ],"
  2245. "\"valid-lifetime\": 4000 }";
  2246. ElementPtr json = Element::fromJSON(config);
  2247. EXPECT_NO_THROW(x = configureDhcp4Server(srv, json));
  2248. ASSERT_TRUE(x);
  2249. comment_ = isc::config::parseAnswer(rcode_, x);
  2250. ASSERT_EQ(0, rcode_);
  2251. boost::shared_ptr<Pkt4> dis(new Pkt4(DHCPDISCOVER, 1234));
  2252. // Set the giaddr to non-zero address as if it was relayed.
  2253. dis->setGiaddr(IOAddress("192.0.2.1"));
  2254. OptionPtr clientid = generateClientId();
  2255. dis->addOption(clientid);
  2256. // Pass it to the server and get an advertise
  2257. Pkt4Ptr offer = srv.processDiscover(dis);
  2258. // check if we get response at all
  2259. ASSERT_TRUE(offer);
  2260. // We did not include any vendor opts in DISCOVER, so there should be none
  2261. // in OFFER.
  2262. ASSERT_FALSE(offer->getOption(DHO_VIVSO_SUBOPTIONS));
  2263. // Let's add a vendor-option (vendor-id=4491) with a single sub-option.
  2264. // That suboption has code 1 and is a docsis ORO option.
  2265. boost::shared_ptr<OptionUint8Array> vendor_oro(new OptionUint8Array(Option::V4,
  2266. DOCSIS3_V4_ORO));
  2267. vendor_oro->addValue(DOCSIS3_V4_TFTP_SERVERS); // Request option 33
  2268. OptionPtr vendor(new OptionVendor(Option::V4, 4491));
  2269. vendor->addOption(vendor_oro);
  2270. dis->addOption(vendor);
  2271. // Need to process SOLICIT again after requesting new option.
  2272. offer = srv.processDiscover(dis);
  2273. ASSERT_TRUE(offer);
  2274. // Check if thre is vendor option response
  2275. OptionPtr tmp = offer->getOption(DHO_VIVSO_SUBOPTIONS);
  2276. ASSERT_TRUE(tmp);
  2277. // The response should be OptionVendor object
  2278. boost::shared_ptr<OptionVendor> vendor_resp =
  2279. boost::dynamic_pointer_cast<OptionVendor>(tmp);
  2280. ASSERT_TRUE(vendor_resp);
  2281. OptionPtr docsis2 = vendor_resp->getOption(DOCSIS3_V4_TFTP_SERVERS);
  2282. ASSERT_TRUE(docsis2);
  2283. Option4AddrLstPtr tftp_srvs = boost::dynamic_pointer_cast<Option4AddrLst>(docsis2);
  2284. ASSERT_TRUE(tftp_srvs);
  2285. Option4AddrLst::AddressContainer addrs = tftp_srvs->getAddresses();
  2286. ASSERT_EQ(2, addrs.size());
  2287. EXPECT_EQ("192.0.2.1", addrs[0].toText());
  2288. EXPECT_EQ("192.0.2.2", addrs[1].toText());
  2289. }
  2290. // Test checks whether it is possible to use option definitions defined in
  2291. // src/lib/dhcp/docsis3_option_defs.h.
  2292. TEST_F(Dhcpv4SrvTest, vendorOptionsDocsisDefinitions) {
  2293. ConstElementPtr x;
  2294. string config_prefix = "{ \"interfaces\": [ \"all\" ],"
  2295. "\"rebind-timer\": 2000, "
  2296. "\"renew-timer\": 1000, "
  2297. " \"option-data\": [ {"
  2298. " \"name\": \"tftp-servers\","
  2299. " \"space\": \"vendor-4491\","
  2300. " \"code\": ";
  2301. string config_postfix = ","
  2302. " \"data\": \"192.0.2.1\","
  2303. " \"csv-format\": True"
  2304. " }],"
  2305. "\"subnet4\": [ { "
  2306. " \"pool\": [ \"192.0.2.1 - 192.0.2.50\" ],"
  2307. " \"subnet\": \"192.0.2.0/24\", "
  2308. " \"renew-timer\": 1000, "
  2309. " \"rebind-timer\": 1000, "
  2310. " \"valid-lifetime\": 4000,"
  2311. " \"interface\": \"\""
  2312. " } ],"
  2313. "\"valid-lifetime\": 4000 }";
  2314. // There is docsis3 (vendor-id=4491) vendor option 2, which is a
  2315. // tftp-server. Its format is list of IPv4 addresses.
  2316. string config_valid = config_prefix + "2" + config_postfix;
  2317. // There is no option 99 defined in vendor-id=4491. As there is no
  2318. // definition, the config should fail.
  2319. string config_bogus = config_prefix + "99" + config_postfix;
  2320. ElementPtr json_bogus = Element::fromJSON(config_bogus);
  2321. ElementPtr json_valid = Element::fromJSON(config_valid);
  2322. NakedDhcpv4Srv srv(0);
  2323. // This should fail (missing option definition)
  2324. EXPECT_NO_THROW(x = configureDhcp4Server(srv, json_bogus));
  2325. ASSERT_TRUE(x);
  2326. comment_ = isc::config::parseAnswer(rcode_, x);
  2327. ASSERT_EQ(1, rcode_);
  2328. // This should work (option definition present)
  2329. EXPECT_NO_THROW(x = configureDhcp4Server(srv, json_valid));
  2330. ASSERT_TRUE(x);
  2331. comment_ = isc::config::parseAnswer(rcode_, x);
  2332. ASSERT_EQ(0, rcode_);
  2333. }
  2334. }
  2335. /*I}; // end of isc::dhcp::test namespace
  2336. }; // end of isc::dhcp namespace
  2337. }; // end of isc namespace */