dhcp4_srv_unittest.cc 130 KB

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