dhcp4_srv_unittest.cc 128 KB

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