dhcp4_srv_unittest.cc 125 KB

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