dhcp4_srv.cc 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203
  1. // Copyright (C) 2011-2017 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include <dhcp/dhcp4.h>
  8. #include <dhcp/duid.h>
  9. #include <dhcp/hwaddr.h>
  10. #include <dhcp/iface_mgr.h>
  11. #include <dhcp/libdhcp++.h>
  12. #include <dhcp/option4_addrlst.h>
  13. #include <dhcp/option_custom.h>
  14. #include <dhcp/option_int.h>
  15. #include <dhcp/option_int_array.h>
  16. #include <dhcp/option_vendor.h>
  17. #include <dhcp/option_string.h>
  18. #include <dhcp/pkt4.h>
  19. #include <dhcp/pkt4o6.h>
  20. #include <dhcp/pkt6.h>
  21. #include <dhcp/docsis3_option_defs.h>
  22. #include <dhcp4/dhcp4to6_ipc.h>
  23. #include <dhcp4/dhcp4_log.h>
  24. #include <dhcp4/dhcp4_srv.h>
  25. #include <dhcpsrv/addr_utilities.h>
  26. #include <dhcpsrv/callout_handle_store.h>
  27. #include <dhcpsrv/cfgmgr.h>
  28. #include <dhcpsrv/cfg_host_operations.h>
  29. #include <dhcpsrv/cfg_iface.h>
  30. #include <dhcpsrv/cfg_shared_networks.h>
  31. #include <dhcpsrv/cfg_subnets4.h>
  32. #include <dhcpsrv/lease_mgr.h>
  33. #include <dhcpsrv/lease_mgr_factory.h>
  34. #include <dhcpsrv/ncr_generator.h>
  35. #include <dhcpsrv/shared_network.h>
  36. #include <dhcpsrv/subnet.h>
  37. #include <dhcpsrv/subnet_selector.h>
  38. #include <dhcpsrv/utils.h>
  39. #include <dhcpsrv/utils.h>
  40. #include <eval/evaluate.h>
  41. #include <eval/eval_messages.h>
  42. #include <hooks/callout_handle.h>
  43. #include <hooks/hooks_log.h>
  44. #include <hooks/hooks_manager.h>
  45. #include <stats/stats_mgr.h>
  46. #include <util/strutil.h>
  47. #include <stats/stats_mgr.h>
  48. #include <log/logger.h>
  49. #include <cryptolink/cryptolink.h>
  50. #include <cfgrpt/config_report.h>
  51. #ifdef HAVE_MYSQL
  52. #include <dhcpsrv/mysql_lease_mgr.h>
  53. #endif
  54. #ifdef HAVE_PGSQL
  55. #include <dhcpsrv/pgsql_lease_mgr.h>
  56. #endif
  57. #ifdef HAVE_CQL
  58. #include <dhcpsrv/cql_lease_mgr.h>
  59. #endif
  60. #include <dhcpsrv/memfile_lease_mgr.h>
  61. #include <boost/algorithm/string/join.hpp>
  62. #include <boost/bind.hpp>
  63. #include <boost/foreach.hpp>
  64. #include <boost/pointer_cast.hpp>
  65. #include <boost/shared_ptr.hpp>
  66. #include <iomanip>
  67. using namespace isc;
  68. using namespace isc::asiolink;
  69. using namespace isc::cryptolink;
  70. using namespace isc::dhcp;
  71. using namespace isc::dhcp_ddns;
  72. using namespace isc::hooks;
  73. using namespace isc::log;
  74. using namespace isc::stats;
  75. using namespace std;
  76. /// Structure that holds registered hook indexes
  77. struct Dhcp4Hooks {
  78. int hook_index_buffer4_receive_; ///< index for "buffer4_receive" hook point
  79. int hook_index_pkt4_receive_; ///< index for "pkt4_receive" hook point
  80. int hook_index_subnet4_select_; ///< index for "subnet4_select" hook point
  81. int hook_index_lease4_release_; ///< index for "lease4_release" hook point
  82. int hook_index_pkt4_send_; ///< index for "pkt4_send" hook point
  83. int hook_index_buffer4_send_; ///< index for "buffer4_send" hook point
  84. int hook_index_lease4_decline_; ///< index for "lease4_decline" hook point
  85. int hook_index_host4_identifier_;///< index for "host4_identifier" hook point
  86. /// Constructor that registers hook points for DHCPv4 engine
  87. Dhcp4Hooks() {
  88. hook_index_buffer4_receive_ = HooksManager::registerHook("buffer4_receive");
  89. hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
  90. hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
  91. hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
  92. hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
  93. hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
  94. hook_index_lease4_decline_ = HooksManager::registerHook("lease4_decline");
  95. hook_index_host4_identifier_ = HooksManager::registerHook("host4_identifier");
  96. }
  97. };
  98. // Declare a Hooks object. As this is outside any function or method, it
  99. // will be instantiated (and the constructor run) when the module is loaded.
  100. // As a result, the hook indexes will be defined before any method in this
  101. // module is called.
  102. Dhcp4Hooks Hooks;
  103. namespace isc {
  104. namespace dhcp {
  105. Dhcpv4Exchange::Dhcpv4Exchange(const AllocEnginePtr& alloc_engine,
  106. const Pkt4Ptr& query,
  107. const Subnet4Ptr& subnet)
  108. : alloc_engine_(alloc_engine), query_(query), resp_(),
  109. context_(new AllocEngine::ClientContext4()) {
  110. if (!alloc_engine_) {
  111. isc_throw(BadValue, "alloc_engine value must not be NULL"
  112. " when creating an instance of the Dhcpv4Exchange");
  113. }
  114. if (!query_) {
  115. isc_throw(BadValue, "query value must not be NULL when"
  116. " creating an instance of the Dhcpv4Exchange");
  117. }
  118. // Create response message.
  119. initResponse();
  120. // Select subnet for the query message.
  121. context_->subnet_ = subnet;
  122. // Hardware address.
  123. context_->hwaddr_ = query->getHWAddr();
  124. // Pointer to client's query.
  125. context_->query_ = query;
  126. // If subnet found, retrieve client identifier which will be needed
  127. // for allocations and search for reservations associated with a
  128. // subnet/shared network.
  129. if (subnet) {
  130. OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  131. if (opt_clientid) {
  132. context_->clientid_.reset(new ClientId(opt_clientid->getData()));
  133. }
  134. // Find static reservations if not disabled for our subnet.
  135. if (subnet->getHostReservationMode() != Network::HR_DISABLED) {
  136. // Before we can check for static reservations, we need to prepare a set
  137. // of identifiers to be used for this.
  138. setHostIdentifiers();
  139. // Check for static reservations.
  140. alloc_engine->findReservation(*context_);
  141. }
  142. }
  143. const ClientClasses& classes = query_->getClasses();
  144. if (!classes.empty()) {
  145. std::string joined_classes = boost::algorithm::join(classes, ", ");
  146. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_CLASS_ASSIGNED)
  147. .arg(query_->getLabel())
  148. .arg(joined_classes);
  149. }
  150. };
  151. void
  152. Dhcpv4Exchange::initResponse() {
  153. uint8_t resp_type = 0;
  154. switch (getQuery()->getType()) {
  155. case DHCPDISCOVER:
  156. resp_type = DHCPOFFER;
  157. break;
  158. case DHCPREQUEST:
  159. case DHCPINFORM:
  160. resp_type = DHCPACK;
  161. break;
  162. default:
  163. ;
  164. }
  165. // Only create a response if one is required.
  166. if (resp_type > 0) {
  167. resp_.reset(new Pkt4(resp_type, getQuery()->getTransid()));
  168. copyDefaultFields();
  169. copyDefaultOptions();
  170. if (getQuery()->isDhcp4o6()) {
  171. initResponse4o6();
  172. }
  173. }
  174. }
  175. void
  176. Dhcpv4Exchange::initResponse4o6() {
  177. Pkt4o6Ptr query = boost::dynamic_pointer_cast<Pkt4o6>(getQuery());
  178. if (!query) {
  179. return;
  180. }
  181. const Pkt6Ptr& query6 = query->getPkt6();
  182. Pkt6Ptr resp6(new Pkt6(DHCPV6_DHCPV4_RESPONSE, query6->getTransid()));
  183. // Don't add client-id or server-id
  184. // But copy relay info
  185. if (!query6->relay_info_.empty()) {
  186. resp6->copyRelayInfo(query6);
  187. }
  188. // Copy interface and remote address
  189. resp6->setIface(query6->getIface());
  190. resp6->setIndex(query6->getIndex());
  191. resp6->setRemoteAddr(query6->getRemoteAddr());
  192. resp_.reset(new Pkt4o6(resp_, resp6));
  193. }
  194. void
  195. Dhcpv4Exchange::copyDefaultFields() {
  196. resp_->setIface(query_->getIface());
  197. resp_->setIndex(query_->getIndex());
  198. // explicitly set this to 0
  199. resp_->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  200. // ciaddr is always 0, except for the Renew/Rebind state when it may
  201. // be set to the ciaddr sent by the client.
  202. resp_->setCiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  203. resp_->setHops(query_->getHops());
  204. // copy MAC address
  205. resp_->setHWAddr(query_->getHWAddr());
  206. // relay address
  207. resp_->setGiaddr(query_->getGiaddr());
  208. // If src/dest HW addresses are used by the packet filtering class
  209. // we need to copy them as well. There is a need to check that the
  210. // address being set is not-NULL because an attempt to set the NULL
  211. // HW would result in exception. If these values are not set, the
  212. // the default HW addresses (zeroed) should be generated by the
  213. // packet filtering class when creating Ethernet header for
  214. // outgoing packet.
  215. HWAddrPtr src_hw_addr = query_->getLocalHWAddr();
  216. if (src_hw_addr) {
  217. resp_->setLocalHWAddr(src_hw_addr);
  218. }
  219. HWAddrPtr dst_hw_addr = query_->getRemoteHWAddr();
  220. if (dst_hw_addr) {
  221. resp_->setRemoteHWAddr(dst_hw_addr);
  222. }
  223. // Copy flags from the request to the response per RFC 2131
  224. resp_->setFlags(query_->getFlags());
  225. }
  226. void
  227. Dhcpv4Exchange::copyDefaultOptions() {
  228. // Let's copy client-id to response. See RFC6842.
  229. // It is possible to disable RFC6842 to keep backward compatibility
  230. bool echo = CfgMgr::instance().getCurrentCfg()->getEchoClientId();
  231. OptionPtr client_id = query_->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  232. if (client_id && echo) {
  233. resp_->addOption(client_id);
  234. }
  235. // If this packet is relayed, we want to copy Relay Agent Info option
  236. OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
  237. if (rai) {
  238. resp_->addOption(rai);
  239. }
  240. // RFC 3011 states about the Subnet Selection Option
  241. // "Servers configured to support this option MUST return an
  242. // identical copy of the option to any client that sends it,
  243. // regardless of whether or not the client requests the option in
  244. // a parameter request list. Clients using this option MUST
  245. // discard DHCPOFFER or DHCPACK packets that do not contain this
  246. // option."
  247. OptionPtr subnet_sel = query_->getOption(DHO_SUBNET_SELECTION);
  248. if (subnet_sel) {
  249. resp_->addOption(subnet_sel);
  250. }
  251. }
  252. void
  253. Dhcpv4Exchange::setHostIdentifiers() {
  254. const ConstCfgHostOperationsPtr cfg =
  255. CfgMgr::instance().getCurrentCfg()->getCfgHostOperations4();
  256. // Collect host identifiers. The identifiers are stored in order of preference.
  257. // The server will use them in that order to search for host reservations.
  258. BOOST_FOREACH(const Host::IdentifierType& id_type,
  259. cfg->getIdentifierTypes()) {
  260. switch (id_type) {
  261. case Host::IDENT_HWADDR:
  262. if (context_->hwaddr_ && !context_->hwaddr_->hwaddr_.empty()) {
  263. context_->addHostIdentifier(id_type, context_->hwaddr_->hwaddr_);
  264. }
  265. break;
  266. case Host::IDENT_DUID:
  267. if (context_->clientid_) {
  268. const std::vector<uint8_t>& vec = context_->clientid_->getDuid();
  269. if (!vec.empty()) {
  270. // Client identifier type = DUID? Client identifier holding a DUID
  271. // comprises Type (1 byte), IAID (4 bytes), followed by the actual
  272. // DUID. Thus, the minimal length is 6.
  273. if ((vec[0] == CLIENT_ID_OPTION_TYPE_DUID) && (vec.size() > 5)) {
  274. // Extract DUID, skip IAID.
  275. context_->addHostIdentifier(id_type,
  276. std::vector<uint8_t>(vec.begin() + 5,
  277. vec.end()));
  278. }
  279. }
  280. }
  281. break;
  282. case Host::IDENT_CIRCUIT_ID:
  283. {
  284. OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
  285. if (rai) {
  286. OptionPtr circuit_id_opt = rai->getOption(RAI_OPTION_AGENT_CIRCUIT_ID);
  287. if (circuit_id_opt) {
  288. const OptionBuffer& circuit_id_vec = circuit_id_opt->getData();
  289. if (!circuit_id_vec.empty()) {
  290. context_->addHostIdentifier(id_type, circuit_id_vec);
  291. }
  292. }
  293. }
  294. }
  295. break;
  296. case Host::IDENT_CLIENT_ID:
  297. if (context_->clientid_) {
  298. const std::vector<uint8_t>& vec = context_->clientid_->getDuid();
  299. if (!vec.empty()) {
  300. context_->addHostIdentifier(id_type, vec);
  301. }
  302. }
  303. break;
  304. case Host::IDENT_FLEX:
  305. {
  306. if (!HooksManager::calloutsPresent(Hooks.hook_index_host4_identifier_)) {
  307. break;
  308. }
  309. CalloutHandlePtr callout_handle = getCalloutHandle(context_->query_);
  310. Host::IdentifierType type = Host::IDENT_FLEX;
  311. std::vector<uint8_t> id;
  312. // Delete previously set arguments
  313. callout_handle->deleteAllArguments();
  314. // Pass incoming packet as argument
  315. callout_handle->setArgument("query4", context_->query_);
  316. callout_handle->setArgument("id_type", type);
  317. callout_handle->setArgument("id_value", id);
  318. // Call callouts
  319. HooksManager::callCallouts(Hooks.hook_index_host4_identifier_,
  320. *callout_handle);
  321. callout_handle->getArgument("id_type", type);
  322. callout_handle->getArgument("id_value", id);
  323. if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_CONTINUE) &&
  324. !id.empty()) {
  325. LOG_DEBUG(packet4_logger, DBGLVL_TRACE_BASIC, DHCP4_FLEX_ID)
  326. .arg(Host::getIdentifierAsText(type, &id[0], id.size()));
  327. context_->addHostIdentifier(type, id);
  328. }
  329. break;
  330. }
  331. default:
  332. ;
  333. }
  334. }
  335. }
  336. void
  337. Dhcpv4Exchange::setReservedClientClasses() {
  338. if (context_->currentHost() && query_) {
  339. BOOST_FOREACH(const std::string& client_class,
  340. context_->currentHost()->getClientClasses4()) {
  341. query_->addClass(client_class);
  342. }
  343. }
  344. }
  345. void
  346. Dhcpv4Exchange::setReservedMessageFields() {
  347. ConstHostPtr host = context_->currentHost();
  348. // Nothing to do if host reservations not specified for this client.
  349. if (host) {
  350. if (!host->getNextServer().isV4Zero()) {
  351. resp_->setSiaddr(host->getNextServer());
  352. }
  353. std::string sname = host->getServerHostname();
  354. if (!sname.empty()) {
  355. resp_->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
  356. sname.size());
  357. }
  358. std::string bootfile = host->getBootFileName();
  359. if (!bootfile.empty()) {
  360. resp_->setFile(reinterpret_cast<const uint8_t*>(bootfile.c_str()),
  361. bootfile.size());
  362. }
  363. }
  364. }
  365. const std::string Dhcpv4Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");
  366. Dhcpv4Srv::Dhcpv4Srv(uint16_t port, const bool use_bcast,
  367. const bool direct_response_desired)
  368. : io_service_(new IOService()), shutdown_(true), alloc_engine_(), port_(port),
  369. use_bcast_(use_bcast) {
  370. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_OPEN_SOCKET).arg(port);
  371. try {
  372. // Port 0 is used for testing purposes where we don't open broadcast
  373. // capable sockets. So, set the packet filter handling direct traffic
  374. // only if we are in non-test mode.
  375. if (port) {
  376. // First call to instance() will create IfaceMgr (it's a singleton)
  377. // it may throw something if things go wrong.
  378. // The 'true' value of the call to setMatchingPacketFilter imposes
  379. // that IfaceMgr will try to use the mechanism to respond directly
  380. // to the client which doesn't have address assigned. This capability
  381. // may be lacking on some OSes, so there is no guarantee that server
  382. // will be able to respond directly.
  383. IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
  384. }
  385. // Instantiate allocation engine. The number of allocation attempts equal
  386. // to zero indicates that the allocation engine will use the number of
  387. // attempts depending on the pool size.
  388. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 0,
  389. false /* false = IPv4 */));
  390. /// @todo call loadLibraries() when handling configuration changes
  391. } catch (const std::exception &e) {
  392. LOG_ERROR(dhcp4_logger, DHCP4_SRV_CONSTRUCT_ERROR).arg(e.what());
  393. shutdown_ = true;
  394. return;
  395. }
  396. shutdown_ = false;
  397. }
  398. Dhcpv4Srv::~Dhcpv4Srv() {
  399. try {
  400. stopD2();
  401. } catch(const std::exception& ex) {
  402. // Highly unlikely, but lets Report it but go on
  403. LOG_ERROR(dhcp4_logger, DHCP4_SRV_D2STOP_ERROR).arg(ex.what());
  404. }
  405. try {
  406. Dhcp4to6Ipc::instance().close();
  407. } catch(const std::exception& ex) {
  408. // Highly unlikely, but lets Report it but go on
  409. LOG_ERROR(dhcp4_logger, DHCP4_SRV_DHCP4O6_ERROR).arg(ex.what());
  410. }
  411. IfaceMgr::instance().closeSockets();
  412. // The lease manager was instantiated during DHCPv4Srv configuration,
  413. // so we should clean up after ourselves.
  414. LeaseMgrFactory::destroy();
  415. // Explicitly unload hooks
  416. HooksManager::getHooksManager().unloadLibraries();
  417. }
  418. void
  419. Dhcpv4Srv::shutdown() {
  420. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_SHUTDOWN_REQUEST);
  421. shutdown_ = true;
  422. }
  423. isc::dhcp::Subnet4Ptr
  424. Dhcpv4Srv::selectSubnet(const Pkt4Ptr& query) const {
  425. // DHCPv4-over-DHCPv6 is a special (and complex) case
  426. if (query->isDhcp4o6()) {
  427. return (selectSubnet4o6(query));
  428. }
  429. Subnet4Ptr subnet;
  430. SubnetSelector selector;
  431. selector.ciaddr_ = query->getCiaddr();
  432. selector.giaddr_ = query->getGiaddr();
  433. selector.local_address_ = query->getLocalAddr();
  434. selector.remote_address_ = query->getRemoteAddr();
  435. selector.client_classes_ = query->classes_;
  436. selector.iface_name_ = query->getIface();
  437. // If the link-selection sub-option is present, extract its value.
  438. // "The link-selection sub-option is used by any DHCP relay agent
  439. // that desires to specify a subnet/link for a DHCP client request
  440. // that it is relaying but needs the subnet/link specification to
  441. // be different from the IP address the DHCP server should use
  442. // when communicating with the relay agent." (RFC 3527)
  443. //
  444. // Try first Relay Agent Link Selection sub-option
  445. OptionPtr rai = query->getOption(DHO_DHCP_AGENT_OPTIONS);
  446. if (rai) {
  447. OptionCustomPtr rai_custom =
  448. boost::dynamic_pointer_cast<OptionCustom>(rai);
  449. if (rai_custom) {
  450. OptionPtr link_select =
  451. rai_custom->getOption(RAI_OPTION_LINK_SELECTION);
  452. if (link_select) {
  453. OptionBuffer link_select_buf = link_select->getData();
  454. if (link_select_buf.size() == sizeof(uint32_t)) {
  455. selector.option_select_ =
  456. IOAddress::fromBytes(AF_INET, &link_select_buf[0]);
  457. }
  458. }
  459. }
  460. } else {
  461. // Or Subnet Selection option
  462. OptionPtr sbnsel = query->getOption(DHO_SUBNET_SELECTION);
  463. if (sbnsel) {
  464. OptionCustomPtr oc =
  465. boost::dynamic_pointer_cast<OptionCustom>(sbnsel);
  466. if (oc) {
  467. selector.option_select_ = oc->readAddress();
  468. }
  469. }
  470. }
  471. CfgMgr& cfgmgr = CfgMgr::instance();
  472. subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet(selector);
  473. // Let's execute all callouts registered for subnet4_select
  474. if (HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
  475. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  476. // We're reusing callout_handle from previous calls
  477. callout_handle->deleteAllArguments();
  478. // Enable copying options from the packet within hook library.
  479. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
  480. // Set new arguments
  481. callout_handle->setArgument("query4", query);
  482. callout_handle->setArgument("subnet4", subnet);
  483. callout_handle->setArgument("subnet4collection",
  484. cfgmgr.getCurrentCfg()->
  485. getCfgSubnets4()->getAll());
  486. // Call user (and server-side) callouts
  487. HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
  488. *callout_handle);
  489. // Callouts decided to skip this step. This means that no subnet
  490. // will be selected. Packet processing will continue, but it will
  491. // be severely limited (i.e. only global options will be assigned)
  492. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  493. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  494. DHCP4_HOOK_SUBNET4_SELECT_SKIP)
  495. .arg(query->getLabel());
  496. return (Subnet4Ptr());
  497. }
  498. /// @todo: Add support for DROP status
  499. // Use whatever subnet was specified by the callout
  500. callout_handle->getArgument("subnet4", subnet);
  501. }
  502. if (subnet) {
  503. // Log at higher debug level that subnet has been found.
  504. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC_DATA, DHCP4_SUBNET_SELECTED)
  505. .arg(query->getLabel())
  506. .arg(subnet->getID());
  507. // Log detailed information about the selected subnet at the
  508. // lower debug level.
  509. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_DATA)
  510. .arg(query->getLabel())
  511. .arg(subnet->toText());
  512. } else {
  513. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL,
  514. DHCP4_SUBNET_SELECTION_FAILED)
  515. .arg(query->getLabel());
  516. }
  517. return (subnet);
  518. }
  519. isc::dhcp::Subnet4Ptr
  520. Dhcpv4Srv::selectSubnet4o6(const Pkt4Ptr& query) const {
  521. Subnet4Ptr subnet;
  522. SubnetSelector selector;
  523. selector.ciaddr_ = query->getCiaddr();
  524. selector.giaddr_ = query->getGiaddr();
  525. selector.local_address_ = query->getLocalAddr();
  526. selector.client_classes_ = query->classes_;
  527. selector.iface_name_ = query->getIface();
  528. // Mark it as DHCPv4-over-DHCPv6
  529. selector.dhcp4o6_ = true;
  530. // Now the DHCPv6 part
  531. selector.remote_address_ = query->getRemoteAddr();
  532. selector.first_relay_linkaddr_ = IOAddress("::");
  533. // Handle a DHCPv6 relayed query
  534. Pkt4o6Ptr query4o6 = boost::dynamic_pointer_cast<Pkt4o6>(query);
  535. if (!query4o6) {
  536. isc_throw(Unexpected, "Can't get DHCP4o6 message");
  537. }
  538. const Pkt6Ptr& query6 = query4o6->getPkt6();
  539. // Initialize fields specific to relayed messages.
  540. if (query6 && !query6->relay_info_.empty()) {
  541. BOOST_REVERSE_FOREACH(Pkt6::RelayInfo relay, query6->relay_info_) {
  542. if (!relay.linkaddr_.isV6Zero() &&
  543. !relay.linkaddr_.isV6LinkLocal()) {
  544. selector.first_relay_linkaddr_ = relay.linkaddr_;
  545. break;
  546. }
  547. }
  548. selector.interface_id_ =
  549. query6->getAnyRelayOption(D6O_INTERFACE_ID,
  550. Pkt6::RELAY_GET_FIRST);
  551. }
  552. // If the Subnet Selection option is present, extract its value.
  553. OptionPtr sbnsel = query->getOption(DHO_SUBNET_SELECTION);
  554. if (sbnsel) {
  555. OptionCustomPtr oc = boost::dynamic_pointer_cast<OptionCustom>(sbnsel);
  556. if (oc) {
  557. selector.option_select_ = oc->readAddress();
  558. }
  559. }
  560. CfgMgr& cfgmgr = CfgMgr::instance();
  561. subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet4o6(selector);
  562. // Let's execute all callouts registered for subnet4_select
  563. if (HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
  564. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  565. // We're reusing callout_handle from previous calls
  566. callout_handle->deleteAllArguments();
  567. // Set new arguments
  568. callout_handle->setArgument("query4", query);
  569. callout_handle->setArgument("subnet4", subnet);
  570. callout_handle->setArgument("subnet4collection",
  571. cfgmgr.getCurrentCfg()->
  572. getCfgSubnets4()->getAll());
  573. // Call user (and server-side) callouts
  574. HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
  575. *callout_handle);
  576. // Callouts decided to skip this step. This means that no subnet
  577. // will be selected. Packet processing will continue, but it will
  578. // be severely limited (i.e. only global options will be assigned)
  579. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  580. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  581. DHCP4_HOOK_SUBNET4_SELECT_SKIP)
  582. .arg(query->getLabel());
  583. return (Subnet4Ptr());
  584. }
  585. /// @todo: Add support for DROP status
  586. // Use whatever subnet was specified by the callout
  587. callout_handle->getArgument("subnet4", subnet);
  588. }
  589. if (subnet) {
  590. // Log at higher debug level that subnet has been found.
  591. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC_DATA, DHCP4_SUBNET_SELECTED)
  592. .arg(query->getLabel())
  593. .arg(subnet->getID());
  594. // Log detailed information about the selected subnet at the
  595. // lower debug level.
  596. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_DATA)
  597. .arg(query->getLabel())
  598. .arg(subnet->toText());
  599. } else {
  600. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL,
  601. DHCP4_SUBNET_SELECTION_FAILED)
  602. .arg(query->getLabel());
  603. }
  604. return (subnet);
  605. }
  606. Pkt4Ptr
  607. Dhcpv4Srv::receivePacket(int timeout) {
  608. return (IfaceMgr::instance().receive4(timeout));
  609. }
  610. void
  611. Dhcpv4Srv::sendPacket(const Pkt4Ptr& packet) {
  612. IfaceMgr::instance().send(packet);
  613. }
  614. bool
  615. Dhcpv4Srv::run() {
  616. while (!shutdown_) {
  617. try {
  618. run_one();
  619. getIOService()->poll();
  620. } catch (const std::exception& e) {
  621. // General catch-all exception that are not caught by more specific
  622. // catches. This one is for exceptions derived from std::exception.
  623. LOG_ERROR(packet4_logger, DHCP4_PACKET_PROCESS_STD_EXCEPTION)
  624. .arg(e.what());
  625. } catch (...) {
  626. // General catch-all exception that are not caught by more specific
  627. // catches. This one is for other exceptions, not derived from
  628. // std::exception.
  629. LOG_ERROR(packet4_logger, DHCP4_PACKET_PROCESS_EXCEPTION);
  630. }
  631. }
  632. return (true);
  633. }
  634. void
  635. Dhcpv4Srv::run_one() {
  636. // client's message and server's response
  637. Pkt4Ptr query;
  638. Pkt4Ptr rsp;
  639. try {
  640. // Set select() timeout to 1s. This value should not be modified
  641. // because it is important that the select() returns control
  642. // frequently so as the IOService can be polled for ready handlers.
  643. uint32_t timeout = 1;
  644. query = receivePacket(timeout);
  645. // Log if packet has arrived. We can't log the detailed information
  646. // about the DHCP message because it hasn't been unpacked/parsed
  647. // yet, and it can't be parsed at this point because hooks will
  648. // have to process it first. The only information available at this
  649. // point are: the interface, source address and destination addresses
  650. // and ports.
  651. if (query) {
  652. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC, DHCP4_BUFFER_RECEIVED)
  653. .arg(query->getRemoteAddr().toText())
  654. .arg(query->getRemotePort())
  655. .arg(query->getLocalAddr().toText())
  656. .arg(query->getLocalPort())
  657. .arg(query->getIface());
  658. }
  659. // We used to log that the wait was interrupted, but this is no longer
  660. // the case. Our wait time is 1s now, so the lack of query packet more
  661. // likely means that nothing new appeared within a second, rather than
  662. // we were interrupted. And we don't want to print a message every
  663. // second.
  664. } catch (const SignalInterruptOnSelect) {
  665. // Packet reception interrupted because a signal has been received.
  666. // This is not an error because we might have received a SIGTERM,
  667. // SIGINT, SIGHUP or SIGCHLD which are handled by the server. For
  668. // signals that are not handled by the server we rely on the default
  669. // behavior of the system.
  670. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_WAIT_SIGNAL)
  671. .arg(signal_set_->getNext());
  672. } catch (const std::exception& e) {
  673. // Log all other errors.
  674. LOG_ERROR(packet4_logger, DHCP4_BUFFER_RECEIVE_FAIL).arg(e.what());
  675. }
  676. // Handle next signal received by the process. It must be called after
  677. // an attempt to receive a packet to properly handle server shut down.
  678. // The SIGTERM or SIGINT will be received prior to, or during execution
  679. // of select() (select is invoked by receivePacket()). When that
  680. // happens, select will be interrupted. The signal handler will be
  681. // invoked immediately after select(). The handler will set the
  682. // shutdown flag and cause the process to terminate before the next
  683. // select() function is called. If the function was called before
  684. // receivePacket the process could wait up to the duration of timeout
  685. // of select() to terminate.
  686. try {
  687. handleSignal();
  688. } catch (const std::exception& e) {
  689. // Standard exception occurred. Let's be on the safe side to
  690. // catch std::exception.
  691. LOG_ERROR(dhcp4_logger, DHCP4_HANDLE_SIGNAL_EXCEPTION)
  692. .arg(e.what());
  693. }
  694. // Timeout may be reached or signal received, which breaks select()
  695. // with no reception occurred. No need to log anything here because
  696. // we have logged right after the call to receivePacket().
  697. if (!query) {
  698. return;
  699. }
  700. processPacket(query, rsp);
  701. if (!rsp) {
  702. return;
  703. }
  704. try {
  705. // Now all fields and options are constructed into output wire buffer.
  706. // Option objects modification does not make sense anymore. Hooks
  707. // can only manipulate wire buffer at this stage.
  708. // Let's execute all callouts registered for buffer4_send
  709. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_send_)) {
  710. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  711. // Delete previously set arguments
  712. callout_handle->deleteAllArguments();
  713. // Enable copying options from the packet within hook library.
  714. ScopedEnableOptionsCopy<Pkt4> resp4_options_copy(rsp);
  715. // Pass incoming packet as argument
  716. callout_handle->setArgument("response4", rsp);
  717. // Call callouts
  718. HooksManager::callCallouts(Hooks.hook_index_buffer4_send_,
  719. *callout_handle);
  720. // Callouts decided to skip the next processing step. The next
  721. // processing step would to parse the packet, so skip at this
  722. // stage means drop.
  723. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  724. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  725. DHCP4_HOOK_BUFFER_SEND_SKIP)
  726. .arg(rsp->getLabel());
  727. return;
  728. }
  729. /// @todo: Add support for DROP status.
  730. callout_handle->getArgument("response4", rsp);
  731. }
  732. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC, DHCP4_PACKET_SEND)
  733. .arg(rsp->getLabel())
  734. .arg(rsp->getName())
  735. .arg(static_cast<int>(rsp->getType()))
  736. .arg(rsp->getLocalAddr().isV4Zero() ? "*" : rsp->getLocalAddr().toText())
  737. .arg(rsp->getLocalPort())
  738. .arg(rsp->getRemoteAddr())
  739. .arg(rsp->getRemotePort())
  740. .arg(rsp->getIface().empty() ? "to be determined from routing" :
  741. rsp->getIface());
  742. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL_DATA,
  743. DHCP4_RESPONSE_DATA)
  744. .arg(rsp->getLabel())
  745. .arg(rsp->getName())
  746. .arg(static_cast<int>(rsp->getType()))
  747. .arg(rsp->toText());
  748. sendPacket(rsp);
  749. // Update statistics accordingly for sent packet.
  750. processStatsSent(rsp);
  751. } catch (const std::exception& e) {
  752. LOG_ERROR(packet4_logger, DHCP4_PACKET_SEND_FAIL)
  753. .arg(rsp->getLabel())
  754. .arg(e.what());
  755. }
  756. }
  757. void
  758. Dhcpv4Srv::processPacket(Pkt4Ptr& query, Pkt4Ptr& rsp) {
  759. // Log reception of the packet. We need to increase it early, as any
  760. // failures in unpacking will cause the packet to be dropped. We
  761. // will increase type specific statistic further down the road.
  762. // See processStatsReceived().
  763. isc::stats::StatsMgr::instance().addValue("pkt4-received",
  764. static_cast<int64_t>(1));
  765. bool skip_unpack = false;
  766. // The packet has just been received so contains the uninterpreted wire
  767. // data; execute callouts registered for buffer4_receive.
  768. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
  769. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  770. // Delete previously set arguments
  771. callout_handle->deleteAllArguments();
  772. // Enable copying options from the packet within hook library.
  773. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
  774. // Pass incoming packet as argument
  775. callout_handle->setArgument("query4", query);
  776. // Call callouts
  777. HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_,
  778. *callout_handle);
  779. // Callouts decided to skip the next processing step. The next
  780. // processing step would to parse the packet, so skip at this
  781. // stage means that callouts did the parsing already, so server
  782. // should skip parsing.
  783. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  784. LOG_DEBUG(hooks_logger, DBG_DHCP4_DETAIL,
  785. DHCP4_HOOK_BUFFER_RCVD_SKIP)
  786. .arg(query->getRemoteAddr().toText())
  787. .arg(query->getLocalAddr().toText())
  788. .arg(query->getIface());
  789. skip_unpack = true;
  790. }
  791. callout_handle->getArgument("query4", query);
  792. /// @todo: add support for DROP status
  793. }
  794. // Unpack the packet information unless the buffer4_receive callouts
  795. // indicated they did it
  796. if (!skip_unpack) {
  797. try {
  798. LOG_DEBUG(options4_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_UNPACK)
  799. .arg(query->getRemoteAddr().toText())
  800. .arg(query->getLocalAddr().toText())
  801. .arg(query->getIface());
  802. query->unpack();
  803. } catch (const std::exception& e) {
  804. // Failed to parse the packet.
  805. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL,
  806. DHCP4_PACKET_DROP_0001)
  807. .arg(query->getRemoteAddr().toText())
  808. .arg(query->getLocalAddr().toText())
  809. .arg(query->getIface())
  810. .arg(e.what());
  811. // Increase the statistics of parse failures and dropped packets.
  812. isc::stats::StatsMgr::instance().addValue("pkt4-parse-failed",
  813. static_cast<int64_t>(1));
  814. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  815. static_cast<int64_t>(1));
  816. return;
  817. }
  818. }
  819. // Update statistics accordingly for received packet.
  820. processStatsReceived(query);
  821. // Assign this packet to one or more classes if needed. We need to do
  822. // this before calling accept(), because getSubnet4() may need client
  823. // class information.
  824. classifyPacket(query);
  825. // Now it is classified the deferred unpacking can be done.
  826. deferredUnpack(query);
  827. // Check whether the message should be further processed or discarded.
  828. // There is no need to log anything here. This function logs by itself.
  829. if (!accept(query)) {
  830. // Increase the statistic of dropped packets.
  831. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  832. static_cast<int64_t>(1));
  833. return;
  834. }
  835. // We have sanity checked (in accept() that the Message Type option
  836. // exists, so we can safely get it here.
  837. int type = query->getType();
  838. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC_DATA, DHCP4_PACKET_RECEIVED)
  839. .arg(query->getLabel())
  840. .arg(query->getName())
  841. .arg(type)
  842. .arg(query->getRemoteAddr())
  843. .arg(query->getLocalAddr())
  844. .arg(query->getIface());
  845. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUERY_DATA)
  846. .arg(query->getLabel())
  847. .arg(query->toText());
  848. // Let's execute all callouts registered for pkt4_receive
  849. if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_receive_)) {
  850. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  851. // Delete previously set arguments
  852. callout_handle->deleteAllArguments();
  853. // Enable copying options from the packet within hook library.
  854. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
  855. // Pass incoming packet as argument
  856. callout_handle->setArgument("query4", query);
  857. // Call callouts
  858. HooksManager::callCallouts(Hooks.hook_index_pkt4_receive_,
  859. *callout_handle);
  860. // Callouts decided to skip the next processing step. The next
  861. // processing step would to process the packet, so skip at this
  862. // stage means drop.
  863. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  864. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  865. DHCP4_HOOK_PACKET_RCVD_SKIP)
  866. .arg(query->getLabel());
  867. return;
  868. }
  869. /// @todo: Add support for DROP status
  870. callout_handle->getArgument("query4", query);
  871. }
  872. try {
  873. switch (query->getType()) {
  874. case DHCPDISCOVER:
  875. rsp = processDiscover(query);
  876. break;
  877. case DHCPREQUEST:
  878. // Note that REQUEST is used for many things in DHCPv4: for
  879. // requesting new leases, renewing existing ones and even
  880. // for rebinding.
  881. rsp = processRequest(query);
  882. break;
  883. case DHCPRELEASE:
  884. processRelease(query);
  885. break;
  886. case DHCPDECLINE:
  887. processDecline(query);
  888. break;
  889. case DHCPINFORM:
  890. rsp = processInform(query);
  891. break;
  892. default:
  893. // Only action is to output a message if debug is enabled,
  894. // and that is covered by the debug statement before the
  895. // "switch" statement.
  896. ;
  897. }
  898. } catch (const std::exception& e) {
  899. // Catch-all exception (we used to call only isc::Exception, but
  900. // std::exception could potentially be raised and if we don't catch
  901. // it here, it would be caught in main() and the process would
  902. // terminate). Just log the problem and ignore the packet.
  903. // (The problem is logged as a debug message because debug is
  904. // disabled by default - it prevents a DDOS attack based on the
  905. // sending of problem packets.)
  906. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_BASIC,
  907. DHCP4_PACKET_DROP_0007)
  908. .arg(query->getLabel())
  909. .arg(e.what());
  910. // Increase the statistic of dropped packets.
  911. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  912. static_cast<int64_t>(1));
  913. }
  914. if (!rsp) {
  915. return;
  916. }
  917. // Specifies if server should do the packing
  918. bool skip_pack = false;
  919. // Execute all callouts registered for pkt4_send
  920. if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_send_)) {
  921. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  922. // Delete all previous arguments
  923. callout_handle->deleteAllArguments();
  924. // Clear skip flag if it was set in previous callouts
  925. callout_handle->setStatus(CalloutHandle::NEXT_STEP_CONTINUE);
  926. // Enable copying options from the query and response packets within
  927. // hook library.
  928. ScopedEnableOptionsCopy<Pkt4> query_resp_options_copy(query, rsp);
  929. // Set our response
  930. callout_handle->setArgument("response4", rsp);
  931. // Also pass the corresponding query packet as argument
  932. callout_handle->setArgument("query4", query);
  933. // Call all installed callouts
  934. HooksManager::callCallouts(Hooks.hook_index_pkt4_send_,
  935. *callout_handle);
  936. // Callouts decided to skip the next processing step. The next
  937. // processing step would to send the packet, so skip at this
  938. // stage means "drop response".
  939. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  940. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  941. DHCP4_HOOK_PACKET_SEND_SKIP)
  942. .arg(query->getLabel());
  943. skip_pack = true;
  944. }
  945. /// @todo: Add support for DROP status
  946. }
  947. if (!skip_pack) {
  948. try {
  949. LOG_DEBUG(options4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_PACK)
  950. .arg(rsp->getLabel());
  951. rsp->pack();
  952. } catch (const std::exception& e) {
  953. LOG_ERROR(options4_logger, DHCP4_PACKET_PACK_FAIL)
  954. .arg(rsp->getLabel())
  955. .arg(e.what());
  956. }
  957. }
  958. }
  959. string
  960. Dhcpv4Srv::srvidToString(const OptionPtr& srvid) {
  961. if (!srvid) {
  962. isc_throw(BadValue, "NULL pointer passed to srvidToString()");
  963. }
  964. boost::shared_ptr<Option4AddrLst> generated =
  965. boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
  966. if (!srvid) {
  967. isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
  968. }
  969. Option4AddrLst::AddressContainer addrs = generated->getAddresses();
  970. if (addrs.size() != 1) {
  971. isc_throw(BadValue, "Malformed option passed to srvidToString(). "
  972. << "Expected to contain a single IPv4 address.");
  973. }
  974. return (addrs[0].toText());
  975. }
  976. void
  977. Dhcpv4Srv::appendServerID(Dhcpv4Exchange& ex) {
  978. // Do not append generated server identifier if there is one appended already.
  979. // This is when explicitly configured server identifier option is present.
  980. if (ex.getResponse()->getOption(DHO_DHCP_SERVER_IDENTIFIER)) {
  981. return;
  982. }
  983. // Use local address on which the packet has been received as a
  984. // server identifier. In some cases it may be a different address,
  985. // e.g. broadcast packet or DHCPv4o6 packet.
  986. IOAddress local_addr = ex.getQuery()->getLocalAddr();
  987. Pkt4Ptr query = ex.getQuery();
  988. if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
  989. SocketInfo sock_info = IfaceMgr::instance().getSocket(*query);
  990. local_addr = sock_info.addr_;
  991. }
  992. OptionPtr opt_srvid(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER,
  993. local_addr));
  994. ex.getResponse()->addOption(opt_srvid);
  995. }
  996. void
  997. Dhcpv4Srv::buildCfgOptionList(Dhcpv4Exchange& ex) {
  998. CfgOptionList& co_list = ex.getCfgOptionList();
  999. // Retrieve subnet.
  1000. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1001. if (!subnet) {
  1002. // All methods using the CfgOptionList object return soon when
  1003. // there is no subnet so do the same
  1004. return;
  1005. }
  1006. // Firstly, host specific options.
  1007. const ConstHostPtr& host = ex.getContext()->currentHost();
  1008. if (host && !host->getCfgOption4()->empty()) {
  1009. co_list.push_back(host->getCfgOption4());
  1010. }
  1011. // Secondly, subnet configured options.
  1012. if (!subnet->getCfgOption()->empty()) {
  1013. co_list.push_back(subnet->getCfgOption());
  1014. }
  1015. // Thirdly, shared network specific options.
  1016. SharedNetwork4Ptr network;
  1017. subnet->getSharedNetwork(network);
  1018. if (network && !network->getCfgOption()->empty()) {
  1019. co_list.push_back(network->getCfgOption());
  1020. }
  1021. // Each class in the incoming packet
  1022. const ClientClasses& classes = ex.getQuery()->getClasses();
  1023. for (ClientClasses::const_iterator cclass = classes.begin();
  1024. cclass != classes.end(); ++cclass) {
  1025. // Find the client class definition for this class
  1026. const ClientClassDefPtr& ccdef = CfgMgr::instance().getCurrentCfg()->
  1027. getClientClassDictionary()->findClass(*cclass);
  1028. if (!ccdef) {
  1029. // Not found: the class is not configured
  1030. if (((*cclass).size() <= VENDOR_CLASS_PREFIX.size()) ||
  1031. ((*cclass).compare(0, VENDOR_CLASS_PREFIX.size(), VENDOR_CLASS_PREFIX) != 0)) {
  1032. // Not a VENDOR_CLASS_* so should be configured
  1033. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_CLASS_UNCONFIGURED)
  1034. .arg(ex.getQuery()->getLabel())
  1035. .arg(*cclass);
  1036. }
  1037. // Skip it
  1038. continue;
  1039. }
  1040. if (ccdef->getCfgOption()->empty()) {
  1041. // Skip classes which don't configure options
  1042. continue;
  1043. }
  1044. co_list.push_back(ccdef->getCfgOption());
  1045. }
  1046. // Last global options
  1047. if (!CfgMgr::instance().getCurrentCfg()->getCfgOption()->empty()) {
  1048. co_list.push_back(CfgMgr::instance().getCurrentCfg()->getCfgOption());
  1049. }
  1050. }
  1051. void
  1052. Dhcpv4Srv::appendRequestedOptions(Dhcpv4Exchange& ex) {
  1053. // Get the subnet relevant for the client. We will need it
  1054. // to get the options associated with it.
  1055. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1056. // If we can't find the subnet for the client there is no way
  1057. // to get the options to be sent to a client. We don't log an
  1058. // error because it will be logged by the assignLease method
  1059. // anyway.
  1060. if (!subnet) {
  1061. return;
  1062. }
  1063. // Unlikely short cut
  1064. const CfgOptionList& co_list = ex.getCfgOptionList();
  1065. if (co_list.empty()) {
  1066. return;
  1067. }
  1068. Pkt4Ptr query = ex.getQuery();
  1069. Pkt4Ptr resp = ex.getResponse();
  1070. std::vector<uint8_t> requested_opts;
  1071. // try to get the 'Parameter Request List' option which holds the
  1072. // codes of requested options.
  1073. OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
  1074. OptionUint8Array>(query->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  1075. // Get the codes of requested options.
  1076. if (option_prl) {
  1077. requested_opts = option_prl->getValues();
  1078. }
  1079. // Iterate on the configured option list to add persistent options
  1080. for (CfgOptionList::const_iterator copts = co_list.begin();
  1081. copts != co_list.end(); ++copts) {
  1082. const OptionContainerPtr& opts = (*copts)->getAll(DHCP4_OPTION_SPACE);
  1083. if (!opts) {
  1084. continue;
  1085. }
  1086. // Get persistent options
  1087. const OptionContainerPersistIndex& idx = opts->get<2>();
  1088. const OptionContainerPersistRange& range = idx.equal_range(true);
  1089. for (OptionContainerPersistIndex::const_iterator desc = range.first;
  1090. desc != range.second; ++desc) {
  1091. // Add the persistent option code to requested options
  1092. if (desc->option_) {
  1093. uint8_t code = static_cast<uint8_t>(desc->option_->getType());
  1094. requested_opts.push_back(code);
  1095. }
  1096. }
  1097. }
  1098. // For each requested option code get the instance of the option
  1099. // to be returned to the client.
  1100. for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
  1101. opt != requested_opts.end(); ++opt) {
  1102. // Add nothing when it is already there
  1103. if (!resp->getOption(*opt)) {
  1104. // Iterate on the configured option list
  1105. for (CfgOptionList::const_iterator copts = co_list.begin();
  1106. copts != co_list.end(); ++copts) {
  1107. OptionDescriptor desc = (*copts)->get(DHCP4_OPTION_SPACE, *opt);
  1108. // Got it: add it and jump to the outer loop
  1109. if (desc.option_) {
  1110. resp->addOption(desc.option_);
  1111. break;
  1112. }
  1113. }
  1114. }
  1115. }
  1116. }
  1117. void
  1118. Dhcpv4Srv::appendRequestedVendorOptions(Dhcpv4Exchange& ex) {
  1119. // Get the configured subnet suitable for the incoming packet.
  1120. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1121. // Leave if there is no subnet matching the incoming packet.
  1122. // There is no need to log the error message here because
  1123. // it will be logged in the assignLease() when it fails to
  1124. // pick the suitable subnet. We don't want to duplicate
  1125. // error messages in such case.
  1126. if (!subnet) {
  1127. return;
  1128. }
  1129. // Unlikely short cut
  1130. const CfgOptionList& co_list = ex.getCfgOptionList();
  1131. if (co_list.empty()) {
  1132. return;
  1133. }
  1134. // Try to get the vendor option
  1135. boost::shared_ptr<OptionVendor> vendor_req = boost::dynamic_pointer_cast<
  1136. OptionVendor>(ex.getQuery()->getOption(DHO_VIVSO_SUBOPTIONS));
  1137. if (!vendor_req) {
  1138. return;
  1139. }
  1140. uint32_t vendor_id = vendor_req->getVendorId();
  1141. std::vector<uint8_t> requested_opts;
  1142. // Let's try to get ORO within that vendor-option
  1143. /// @todo This is very specific to vendor-id=4491 (Cable Labs). Other
  1144. /// vendors may have different policies.
  1145. OptionUint8ArrayPtr oro =
  1146. boost::dynamic_pointer_cast<OptionUint8Array>(vendor_req->getOption(DOCSIS3_V4_ORO));
  1147. // Get the list of options that client requested.
  1148. if (oro) {
  1149. requested_opts = oro->getValues();
  1150. }
  1151. // Iterate on the configured option list to add persistent options
  1152. for (CfgOptionList::const_iterator copts = co_list.begin();
  1153. copts != co_list.end(); ++copts) {
  1154. const OptionContainerPtr& opts = (*copts)->getAll(vendor_id);
  1155. if (!opts) {
  1156. continue;
  1157. }
  1158. // Get persistent options
  1159. const OptionContainerPersistIndex& idx = opts->get<2>();
  1160. const OptionContainerPersistRange& range = idx.equal_range(true);
  1161. for (OptionContainerPersistIndex::const_iterator desc = range.first;
  1162. desc != range.second; ++desc) {
  1163. // Add the persistent option code to requested options
  1164. if (desc->option_) {
  1165. uint8_t code = static_cast<uint8_t>(desc->option_->getType());
  1166. requested_opts.push_back(code);
  1167. }
  1168. }
  1169. }
  1170. // If there is nothing to add don't do anything then.
  1171. if (requested_opts.empty()) {
  1172. return;
  1173. }
  1174. boost::shared_ptr<OptionVendor> vendor_rsp(new OptionVendor(Option::V4, vendor_id));
  1175. // Get the list of options that client requested.
  1176. bool added = false;
  1177. for (std::vector<uint8_t>::const_iterator code = requested_opts.begin();
  1178. code != requested_opts.end(); ++code) {
  1179. if (!vendor_rsp->getOption(*code)) {
  1180. for (CfgOptionList::const_iterator copts = co_list.begin();
  1181. copts != co_list.end(); ++copts) {
  1182. OptionDescriptor desc = (*copts)->get(vendor_id, *code);
  1183. if (desc.option_) {
  1184. vendor_rsp->addOption(desc.option_);
  1185. added = true;
  1186. break;
  1187. }
  1188. }
  1189. }
  1190. if (added) {
  1191. ex.getResponse()->addOption(vendor_rsp);
  1192. }
  1193. }
  1194. }
  1195. void
  1196. Dhcpv4Srv::appendBasicOptions(Dhcpv4Exchange& ex) {
  1197. // Identify options that we always want to send to the
  1198. // client (if they are configured).
  1199. static const uint16_t required_options[] = {
  1200. DHO_ROUTERS,
  1201. DHO_DOMAIN_NAME_SERVERS,
  1202. DHO_DOMAIN_NAME,
  1203. DHO_DHCP_SERVER_IDENTIFIER };
  1204. static size_t required_options_size =
  1205. sizeof(required_options) / sizeof(required_options[0]);
  1206. // Get the subnet.
  1207. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1208. if (!subnet) {
  1209. return;
  1210. }
  1211. // Unlikely short cut
  1212. const CfgOptionList& co_list = ex.getCfgOptionList();
  1213. if (co_list.empty()) {
  1214. return;
  1215. }
  1216. Pkt4Ptr resp = ex.getResponse();
  1217. // Try to find all 'required' options in the outgoing
  1218. // message. Those that are not present will be added.
  1219. for (int i = 0; i < required_options_size; ++i) {
  1220. OptionPtr opt = resp->getOption(required_options[i]);
  1221. if (!opt) {
  1222. // Check whether option has been configured.
  1223. for (CfgOptionList::const_iterator copts = co_list.begin();
  1224. copts != co_list.end(); ++copts) {
  1225. OptionDescriptor desc = (*copts)->get(DHCP4_OPTION_SPACE,
  1226. required_options[i]);
  1227. if (desc.option_) {
  1228. resp->addOption(desc.option_);
  1229. break;
  1230. }
  1231. }
  1232. }
  1233. }
  1234. }
  1235. void
  1236. Dhcpv4Srv::processClientName(Dhcpv4Exchange& ex) {
  1237. // It is possible that client has sent both Client FQDN and Hostname
  1238. // option. In such case, server should prefer Client FQDN option and
  1239. // ignore the Hostname option.
  1240. try {
  1241. Pkt4Ptr resp = ex.getResponse();
  1242. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
  1243. (ex.getQuery()->getOption(DHO_FQDN));
  1244. if (fqdn) {
  1245. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_CLIENT_FQDN_PROCESS)
  1246. .arg(ex.getQuery()->getLabel());
  1247. processClientFqdnOption(ex);
  1248. } else {
  1249. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL,
  1250. DHCP4_CLIENT_HOSTNAME_PROCESS)
  1251. .arg(ex.getQuery()->getLabel());
  1252. processHostnameOption(ex);
  1253. }
  1254. } catch (const Exception& e) {
  1255. // In some rare cases it is possible that the client's name processing
  1256. // fails. For example, the Hostname option may be malformed, or there
  1257. // may be an error in the server's logic which would cause multiple
  1258. // attempts to add the same option to the response message. This
  1259. // error message aggregates all these errors so they can be diagnosed
  1260. // from the log. We don't want to throw an exception here because,
  1261. // it will impact the processing of the whole packet. We rather want
  1262. // the processing to continue, even if the client's name is wrong.
  1263. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_NAME_PROC_FAIL)
  1264. .arg(ex.getQuery()->getLabel())
  1265. .arg(e.what());
  1266. }
  1267. }
  1268. void
  1269. Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
  1270. // Obtain the FQDN option from the client's message.
  1271. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1272. Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
  1273. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_FQDN_DATA)
  1274. .arg(ex.getQuery()->getLabel())
  1275. .arg(fqdn->toText());
  1276. // Create the DHCPv4 Client FQDN Option to be included in the server's
  1277. // response to a client.
  1278. Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
  1279. // Set the server S, N, and O flags based on client's flags and
  1280. // current configuration.
  1281. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1282. d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  1283. // Carry over the client's E flag.
  1284. fqdn_resp->setFlag(Option4ClientFqdn::FLAG_E,
  1285. fqdn->getFlag(Option4ClientFqdn::FLAG_E));
  1286. if (ex.getContext()->currentHost() &&
  1287. !ex.getContext()->currentHost()->getHostname().empty()) {
  1288. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1289. fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->currentHost()->getHostname(),
  1290. true), Option4ClientFqdn::FULL);
  1291. } else {
  1292. // Adjust the domain name based on domain name value and type sent by the
  1293. // client and current configuration.
  1294. d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  1295. }
  1296. // Add FQDN option to the response message. Note that, there may be some
  1297. // cases when server may choose not to include the FQDN option in a
  1298. // response to a client. In such cases, the FQDN should be removed from the
  1299. // outgoing message. In theory we could cease to include the FQDN option
  1300. // in this function until it is confirmed that it should be included.
  1301. // However, we include it here for simplicity. Functions used to acquire
  1302. // lease for a client will scan the response message for FQDN and if it
  1303. // is found they will take necessary actions to store the FQDN information
  1304. // in the lease database as well as to generate NameChangeRequests to DNS.
  1305. // If we don't store the option in the response message, we will have to
  1306. // propagate it in the different way to the functions which acquire the
  1307. // lease. This would require modifications to the API of this class.
  1308. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_RESPONSE_FQDN_DATA)
  1309. .arg(ex.getQuery()->getLabel())
  1310. .arg(fqdn_resp->toText());
  1311. ex.getResponse()->addOption(fqdn_resp);
  1312. }
  1313. void
  1314. Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
  1315. // Fetch D2 configuration.
  1316. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1317. // Obtain the Hostname option from the client's message.
  1318. OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
  1319. (ex.getQuery()->getOption(DHO_HOST_NAME));
  1320. if (opt_hostname) {
  1321. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_HOSTNAME_DATA)
  1322. .arg(ex.getQuery()->getLabel())
  1323. .arg(opt_hostname->getValue());
  1324. }
  1325. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  1326. // Hostname reservations take precedence over any other configuration,
  1327. // i.e. DDNS configuration.
  1328. if (ctx->currentHost() && !ctx->currentHost()->getHostname().empty()) {
  1329. // In order to send a reserved hostname value we expect that at least
  1330. // one of the following is the case: the client has sent us a hostname
  1331. // option, or the client has sent Parameter Request List option with
  1332. // the hostname option code included.
  1333. // It is going to be less expensive to first check the presence of the
  1334. // hostname option.
  1335. bool should_send_hostname = static_cast<bool>(opt_hostname);
  1336. // Hostname option is not present, so we have to check PRL option.
  1337. if (!should_send_hostname) {
  1338. OptionUint8ArrayPtr
  1339. option_prl = boost::dynamic_pointer_cast<OptionUint8Array>
  1340. (ex.getQuery()->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  1341. if (option_prl) {
  1342. // PRL option exists, so check if the hostname option code is
  1343. // included in it.
  1344. const std::vector<uint8_t>&
  1345. requested_opts = option_prl->getValues();
  1346. if (std::find(requested_opts.begin(), requested_opts.end(),
  1347. DHO_HOST_NAME) != requested_opts.end()) {
  1348. // Client has requested hostname via Parameter Request
  1349. // List option.
  1350. should_send_hostname = true;
  1351. }
  1352. }
  1353. }
  1354. // If the hostname or PRL option indicates that the server should
  1355. // send back a hostname option, send this option with a reserved
  1356. // name for this client.
  1357. if (should_send_hostname) {
  1358. const std::string& hostname =
  1359. d2_mgr.qualifyName(ctx->currentHost()->getHostname(),
  1360. false);
  1361. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA,
  1362. DHCP4_RESERVED_HOSTNAME_ASSIGNED)
  1363. .arg(ex.getQuery()->getLabel())
  1364. .arg(hostname);
  1365. OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
  1366. DHO_HOST_NAME,
  1367. hostname));
  1368. ex.getResponse()->addOption(opt_hostname_resp);
  1369. // We're done here.
  1370. return;
  1371. }
  1372. }
  1373. // There is no reservation for this client or the client hasn't requested
  1374. // hostname option. There is still a possibility that we'll have to send
  1375. // hostname option to this client if the client has included hostname option
  1376. // but there is no reservation, or the configuration of the server requires
  1377. // that we send the option regardless.
  1378. D2ClientConfig::ReplaceClientNameMode replace_name_mode =
  1379. d2_mgr.getD2ClientConfig()->getReplaceClientNameMode();
  1380. // If we don't have a hostname then either we'll supply it or do nothing.
  1381. if (!opt_hostname) {
  1382. // If we're configured to supply it then add it to the response.
  1383. // Use the root domain to signal later on that we should replace it.
  1384. if (replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
  1385. replace_name_mode == D2ClientConfig::RCM_WHEN_NOT_PRESENT) {
  1386. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA,
  1387. DHCP4_GENERATE_FQDN)
  1388. .arg(ex.getQuery()->getLabel());
  1389. OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
  1390. DHO_HOST_NAME,
  1391. "."));
  1392. ex.getResponse()->addOption(opt_hostname_resp);
  1393. }
  1394. return;
  1395. }
  1396. // Client sent us a hostname option so figure out what to do with it.
  1397. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_HOSTNAME_DATA)
  1398. .arg(ex.getQuery()->getLabel())
  1399. .arg(opt_hostname->getValue());
  1400. std::string hostname = isc::util::str::trim(opt_hostname->getValue());
  1401. unsigned int label_count = OptionDataTypeUtil::getLabelCount(hostname);
  1402. // The hostname option sent by the client should be at least 1 octet long.
  1403. // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
  1404. /// @todo It would be more liberal to accept this and let it fall into
  1405. /// the case of replace or less than two below.
  1406. if (label_count == 0) {
  1407. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_EMPTY_HOSTNAME)
  1408. .arg(ex.getQuery()->getLabel());
  1409. return;
  1410. }
  1411. // Copy construct the hostname provided by the client. It is entirely
  1412. // possible that we will use the hostname option provided by the client
  1413. // to perform the DNS update and we will send the same option to him to
  1414. // indicate that we accepted this hostname.
  1415. OptionStringPtr opt_hostname_resp(new OptionString(*opt_hostname));
  1416. // The hostname option may be unqualified or fully qualified. The lab_count
  1417. // holds the number of labels for the name. The number of 1 means that
  1418. // there is only root label "." (even for unqualified names, as the
  1419. // getLabelCount function treats each name as a fully qualified one).
  1420. // By checking the number of labels present in the hostname we may infer
  1421. // whether client has sent the fully qualified or unqualified hostname.
  1422. if ((replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
  1423. replace_name_mode == D2ClientConfig::RCM_WHEN_PRESENT)
  1424. || label_count < 2) {
  1425. // Set to root domain to signal later on that we should replace it.
  1426. // DHO_HOST_NAME is a string option which cannot be empty.
  1427. /// @todo We may want to reconsider whether it is appropriate for the
  1428. /// client to send a root domain name as a Hostname. There are
  1429. /// also extensions to the auto generation of the client's name,
  1430. /// e.g. conversion to the puny code which may be considered at some
  1431. /// point.
  1432. /// For now, we just remain liberal and expect that the DNS will handle
  1433. /// conversion if needed and possible.
  1434. opt_hostname_resp->setValue(".");
  1435. } else if (label_count == 2) {
  1436. // If there are two labels, it means that the client has specified
  1437. // the unqualified name. We have to concatenate the unqualified name
  1438. // with the domain name. The false value passed as a second argument
  1439. // indicates that the trailing dot should not be appended to the
  1440. // hostname. We don't want to append the trailing dot because
  1441. // we don't know whether the hostname is partial or not and some
  1442. // clients do not handle the hostnames with the trailing dot.
  1443. opt_hostname_resp->setValue(d2_mgr.qualifyName(hostname, false));
  1444. }
  1445. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_RESPONSE_HOSTNAME_DATA)
  1446. .arg(ex.getQuery()->getLabel())
  1447. .arg(opt_hostname_resp->getValue());
  1448. ex.getResponse()->addOption(opt_hostname_resp);
  1449. }
  1450. void
  1451. Dhcpv4Srv::createNameChangeRequests(const Lease4Ptr& lease,
  1452. const Lease4Ptr& old_lease) {
  1453. if (!lease) {
  1454. isc_throw(isc::Unexpected,
  1455. "NULL lease specified when creating NameChangeRequest");
  1456. } else if (!old_lease || !lease->hasIdenticalFqdn(*old_lease)) {
  1457. if (old_lease) {
  1458. // Queue's up a remove of the old lease's DNS (if needed)
  1459. queueNCR(CHG_REMOVE, old_lease);
  1460. }
  1461. // We may need to generate the NameChangeRequest for the new lease. It
  1462. // will be generated only if hostname is set and if forward or reverse
  1463. // update has been requested.
  1464. queueNCR(CHG_ADD, lease);
  1465. }
  1466. }
  1467. void
  1468. Dhcpv4Srv::assignLease(Dhcpv4Exchange& ex) {
  1469. // Get the pointers to the query and the response messages.
  1470. Pkt4Ptr query = ex.getQuery();
  1471. Pkt4Ptr resp = ex.getResponse();
  1472. // Get the context.
  1473. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  1474. // Subnet should have been already selected when the context was created.
  1475. Subnet4Ptr subnet = ctx->subnet_;
  1476. if (!subnet) {
  1477. // This particular client is out of luck today. We do not have
  1478. // information about the subnet he is connected to. This likely means
  1479. // misconfiguration of the server (or some relays).
  1480. // Perhaps this should be logged on some higher level?
  1481. LOG_ERROR(bad_packet4_logger, DHCP4_PACKET_NAK_0001)
  1482. .arg(query->getLabel())
  1483. .arg(query->getRemoteAddr().toText())
  1484. .arg(query->getName());
  1485. resp->setType(DHCPNAK);
  1486. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1487. return;
  1488. }
  1489. // Get the server identifier. It will be used to determine the state
  1490. // of the client.
  1491. OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
  1492. OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  1493. // Check if the client has sent a requested IP address option or
  1494. // ciaddr.
  1495. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  1496. OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  1497. IOAddress hint(IOAddress::IPV4_ZERO_ADDRESS());
  1498. if (opt_requested_address) {
  1499. hint = opt_requested_address->readAddress();
  1500. } else if (!query->getCiaddr().isV4Zero()) {
  1501. hint = query->getCiaddr();
  1502. }
  1503. HWAddrPtr hwaddr = query->getHWAddr();
  1504. // "Fake" allocation is processing of DISCOVER message. We pretend to do an
  1505. // allocation, but we do not put the lease in the database. That is ok,
  1506. // because we do not guarantee that the user will get that exact lease. If
  1507. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  1508. // it should include this hint. That will help us during the actual lease
  1509. // allocation.
  1510. bool fake_allocation = (query->getType() == DHCPDISCOVER);
  1511. // Get client-id. It is not mandatory in DHCPv4.
  1512. ClientIdPtr client_id = ex.getContext()->clientid_;
  1513. // If there is no server id and there is a Requested IP Address option
  1514. // the client is in the INIT-REBOOT state in which the server has to
  1515. // determine whether the client's notion of the address is correct
  1516. // and whether the client is known, i.e., has a lease.
  1517. if (!fake_allocation && !opt_serverid && opt_requested_address) {
  1518. LOG_INFO(lease4_logger, DHCP4_INIT_REBOOT)
  1519. .arg(query->getLabel())
  1520. .arg(hint.toText());
  1521. Lease4Ptr lease;
  1522. Subnet4Ptr original_subnet = subnet;
  1523. Subnet4Ptr s = original_subnet;
  1524. while (s) {
  1525. if (client_id) {
  1526. lease = LeaseMgrFactory::instance().getLease4(*client_id, s->getID());
  1527. }
  1528. if (!lease && hwaddr) {
  1529. lease = LeaseMgrFactory::instance().getLease4(*hwaddr, s->getID());
  1530. }
  1531. if (lease ) {
  1532. break;
  1533. } else {
  1534. s = s->getNextSubnet(original_subnet, query->getClasses());
  1535. }
  1536. }
  1537. // Check the first error case: unknown client. We check this before
  1538. // validating the address sent because we don't want to respond if
  1539. // we don't know this client.
  1540. if (!lease || !lease->belongsToClient(hwaddr, client_id)) {
  1541. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL,
  1542. DHCP4_NO_LEASE_INIT_REBOOT)
  1543. .arg(query->getLabel())
  1544. .arg(hint.toText());
  1545. ex.deleteResponse();
  1546. return;
  1547. }
  1548. // We know this client so we can now check if his notion of the
  1549. // IP address is correct.
  1550. if (lease && (lease->addr_ != hint)) {
  1551. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL,
  1552. DHCP4_PACKET_NAK_0002)
  1553. .arg(query->getLabel())
  1554. .arg(hint.toText());
  1555. resp->setType(DHCPNAK);
  1556. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1557. return;
  1558. }
  1559. }
  1560. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1561. std::string hostname;
  1562. bool fqdn_fwd = false;
  1563. bool fqdn_rev = false;
  1564. OptionStringPtr opt_hostname;
  1565. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1566. Option4ClientFqdn>(resp->getOption(DHO_FQDN));
  1567. if (fqdn) {
  1568. hostname = fqdn->getDomainName();
  1569. CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn,
  1570. fqdn_fwd,
  1571. fqdn_rev);
  1572. } else {
  1573. opt_hostname = boost::dynamic_pointer_cast<OptionString>
  1574. (resp->getOption(DHO_HOST_NAME));
  1575. if (opt_hostname) {
  1576. hostname = opt_hostname->getValue();
  1577. // DHO_HOST_NAME is string option which cannot be blank,
  1578. // we use "." to know we should replace it with a fully
  1579. // generated name. The local string variable needs to be
  1580. // blank in logic below.
  1581. if (hostname == ".") {
  1582. hostname = "";
  1583. }
  1584. /// @todo It could be configurable what sort of updates the
  1585. /// server is doing when Hostname option was sent.
  1586. fqdn_fwd = true;
  1587. fqdn_rev = true;
  1588. }
  1589. }
  1590. // We need to set these values in the context as they haven't been set yet.
  1591. ctx->requested_address_ = hint;
  1592. ctx->fwd_dns_update_ = fqdn_fwd;
  1593. ctx->rev_dns_update_ = fqdn_rev;
  1594. ctx->hostname_ = hostname;
  1595. ctx->fake_allocation_ = fake_allocation;
  1596. ctx->callout_handle_ = callout_handle;
  1597. Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
  1598. // Subnet may be modified by the allocation engine, if the initial subnet
  1599. // belongs to a shared network.
  1600. if (subnet->getID() != ctx->subnet_->getID()) {
  1601. SharedNetwork4Ptr network;
  1602. subnet->getSharedNetwork(network);
  1603. if (network) {
  1604. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC_DATA, DHCP4_SUBNET_DYNAMICALLY_CHANGED)
  1605. .arg(query->getLabel())
  1606. .arg(subnet->toText())
  1607. .arg(ctx->subnet_->toText())
  1608. .arg(network->getName());
  1609. }
  1610. subnet = ctx->subnet_;
  1611. }
  1612. if (lease) {
  1613. // We have a lease! Let's set it in the packet and send it back to
  1614. // the client.
  1615. LOG_INFO(lease4_logger, fake_allocation ? DHCP4_LEASE_ADVERT : DHCP4_LEASE_ALLOC)
  1616. .arg(query->getLabel())
  1617. .arg(lease->addr_.toText());
  1618. // We're logging this here, because this is the place where we know
  1619. // which subnet has been actually used for allocation. If the
  1620. // client identifier matching is disabled, we want to make sure that
  1621. // the user is notified.
  1622. if (!ctx->subnet_->getMatchClientId()) {
  1623. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_CLIENTID_IGNORED_FOR_LEASES)
  1624. .arg(ctx->query_->getLabel())
  1625. .arg(ctx->subnet_->getID());
  1626. }
  1627. resp->setYiaddr(lease->addr_);
  1628. /// @todo The server should check what ciaddr the client has supplied
  1629. /// in ciaddr. Currently the ciaddr is ignored except for the subnet
  1630. /// selection. If the client supplied an invalid address, the server
  1631. /// will also return an invalid address here.
  1632. if (!fake_allocation) {
  1633. // If this is a renewing client it will set a ciaddr which the
  1634. // server may include in the response. If this is a new allocation
  1635. // the client will set ciaddr to 0 and this will also be propagated
  1636. // to the server's resp.
  1637. resp->setCiaddr(query->getCiaddr());
  1638. }
  1639. // We may need to update FQDN or hostname if the server is to generate
  1640. // new name from the allocated IP address or if the allocation engine
  1641. // has switched to a different subnet (from the same shared network)
  1642. // where the client has hostname reservations.
  1643. if (fqdn || opt_hostname) {
  1644. bool should_update = false;
  1645. // If there is a reservation in the current subnet for a hostname,
  1646. // we need to use this reserved name.
  1647. if (ctx->currentHost() && !ctx->currentHost()->getHostname().empty()) {
  1648. lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
  1649. .qualifyName(ctx->currentHost()->getHostname(),
  1650. static_cast<bool>(fqdn));
  1651. should_update = true;
  1652. // If there has been Client FQDN or Hostname option sent, but the
  1653. // hostname is empty, it means that server is responsible for
  1654. // generating the entire hostname for the client. The example of the
  1655. // client's name, generated from the IP address is: host-192-0-2-3.
  1656. } else if (lease->hostname_.empty()) {
  1657. // Note that if we have received the hostname option, rather than
  1658. // Client FQDN the trailing dot is not appended to the generated
  1659. // hostname because some clients don't handle the trailing dot in
  1660. // the hostname. Whether the trailing dot is appended or not is
  1661. // controlled by the second argument to the generateFqdn().
  1662. lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
  1663. .generateFqdn(lease->addr_, static_cast<bool>(fqdn));
  1664. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_RESPONSE_HOSTNAME_GENERATE)
  1665. .arg(query->getLabel())
  1666. .arg(lease->hostname_);
  1667. should_update = true;
  1668. }
  1669. if (should_update) {
  1670. // The operations below are rather safe, but we want to catch
  1671. // any potential exceptions (e.g. invalid lease database backend
  1672. // implementation) and log an error.
  1673. try {
  1674. if (!fake_allocation) {
  1675. // The lease update should be safe, because the lease should
  1676. // be already in the database. In most cases the exception
  1677. // would be thrown if the lease was missing.
  1678. LeaseMgrFactory::instance().updateLease4(lease);
  1679. }
  1680. // The name update in the option should be also safe,
  1681. // because the generated name is well formed.
  1682. if (fqdn) {
  1683. fqdn->setDomainName(lease->hostname_,
  1684. Option4ClientFqdn::FULL);
  1685. } else if (opt_hostname) {
  1686. opt_hostname->setValue(lease->hostname_);
  1687. }
  1688. } catch (const Exception& ex) {
  1689. LOG_ERROR(ddns4_logger, DHCP4_POST_ALLOCATION_NAME_UPDATE_FAIL)
  1690. .arg(query->getLabel())
  1691. .arg(lease->hostname_)
  1692. .arg(ex.what());
  1693. }
  1694. }
  1695. }
  1696. // IP Address Lease time (type 51)
  1697. OptionPtr opt(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME,
  1698. lease->valid_lft_));
  1699. resp->addOption(opt);
  1700. // Subnet mask (type 1)
  1701. resp->addOption(getNetmaskOption(subnet));
  1702. // renewal-timer (type 58)
  1703. if (!subnet->getT1().unspecified()) {
  1704. OptionUint32Ptr t1(new OptionUint32(Option::V4,
  1705. DHO_DHCP_RENEWAL_TIME,
  1706. subnet->getT1()));
  1707. resp->addOption(t1);
  1708. }
  1709. // rebind timer (type 59)
  1710. if (!subnet->getT2().unspecified()) {
  1711. OptionUint32Ptr t2(new OptionUint32(Option::V4,
  1712. DHO_DHCP_REBINDING_TIME,
  1713. subnet->getT2()));
  1714. resp->addOption(t2);
  1715. }
  1716. // Create NameChangeRequests if DDNS is enabled and this is a
  1717. // real allocation.
  1718. if (!fake_allocation && CfgMgr::instance().ddnsEnabled()) {
  1719. try {
  1720. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_NCR_CREATE)
  1721. .arg(query->getLabel());
  1722. createNameChangeRequests(lease, ctx->old_lease_);
  1723. } catch (const Exception& ex) {
  1724. LOG_ERROR(ddns4_logger, DHCP4_NCR_CREATION_FAILED)
  1725. .arg(query->getLabel())
  1726. .arg(ex.what());
  1727. }
  1728. }
  1729. } else {
  1730. // Allocation engine did not allocate a lease. The engine logged
  1731. // cause of that failure.
  1732. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, fake_allocation ?
  1733. DHCP4_PACKET_NAK_0003 : DHCP4_PACKET_NAK_0004)
  1734. .arg(query->getLabel())
  1735. .arg(query->getCiaddr().toText())
  1736. .arg(opt_requested_address ?
  1737. opt_requested_address->readAddress().toText() : "(no address)");
  1738. resp->setType(DHCPNAK);
  1739. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1740. resp->delOption(DHO_FQDN);
  1741. resp->delOption(DHO_HOST_NAME);
  1742. }
  1743. }
  1744. void
  1745. Dhcpv4Srv::adjustIfaceData(Dhcpv4Exchange& ex) {
  1746. adjustRemoteAddr(ex);
  1747. // Initialize the pointers to the client's message and the server's
  1748. // response.
  1749. Pkt4Ptr query = ex.getQuery();
  1750. Pkt4Ptr response = ex.getResponse();
  1751. // The DHCPINFORM is generally unicast to the client. The only situation
  1752. // when the server is unable to unicast to the client is when the client
  1753. // doesn't include ciaddr and the message is relayed. In this case the
  1754. // server has to reply via relay agent. For other messages we send back
  1755. // through relay if message is relayed, and unicast to the client if the
  1756. // message is not relayed.
  1757. // Note that the call to this function may throw if invalid combination
  1758. // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
  1759. // giaddr != 0). The exception will propagate down and eventually cause the
  1760. // packet to be discarded.
  1761. if (((query->getType() == DHCPINFORM) &&
  1762. ((!query->getCiaddr().isV4Zero()) ||
  1763. (!query->isRelayed() && !query->getRemoteAddr().isV4Zero()))) ||
  1764. ((query->getType() != DHCPINFORM) && !query->isRelayed())) {
  1765. response->setRemotePort(DHCP4_CLIENT_PORT);
  1766. } else {
  1767. response->setRemotePort(DHCP4_SERVER_PORT);
  1768. }
  1769. CfgIfacePtr cfg_iface = CfgMgr::instance().getCurrentCfg()->getCfgIface();
  1770. if (query->isRelayed() &&
  1771. (cfg_iface->getSocketType() == CfgIface::SOCKET_UDP) &&
  1772. (cfg_iface->getOutboundIface() == CfgIface::USE_ROUTING)) {
  1773. response->setLocalAddr(IOAddress::IPV4_ZERO_ADDRESS());
  1774. response->setIface("");
  1775. response->resetIndex();
  1776. } else {
  1777. IOAddress local_addr = query->getLocalAddr();
  1778. // In many cases the query is sent to a broadcast address. This address
  1779. // appears as a local address in the query message. We can't simply copy
  1780. // this address to a response message and use it as a source address.
  1781. // Instead we will need to use the address assigned to the interface
  1782. // on which the query has been received. In other cases, we will just
  1783. // use this address as a source address for the response.
  1784. // Do the same for DHCPv4-over-DHCPv6 exchanges.
  1785. if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
  1786. SocketInfo sock_info = IfaceMgr::instance().getSocket(*query);
  1787. local_addr = sock_info.addr_;
  1788. }
  1789. // We assume that there is an appropriate socket bound to this address
  1790. // and that the address is correct. This is safe assumption because
  1791. // the local address of the query is set when the query is received.
  1792. // The query sent to an incorrect address wouldn't have been received.
  1793. // However, if socket is closed for this address between the reception
  1794. // of the query and sending a response, the IfaceMgr should detect it
  1795. // and return an error.
  1796. response->setLocalAddr(local_addr);
  1797. // In many cases the query is sent to a broadcast address. This address
  1798. // appears as a local address in the query message. Therefore we can't
  1799. // simply copy local address from the query and use it as a source
  1800. // address for the response. Instead, we have to check what address our
  1801. // socket is bound to and use it as a source address. This operation
  1802. // may throw if for some reason the socket is closed.
  1803. /// @todo Consider an optimization that we use local address from
  1804. /// the query if this address is not broadcast.
  1805. response->setIface(query->getIface());
  1806. response->setIndex(query->getIndex());
  1807. }
  1808. response->setLocalPort(DHCP4_SERVER_PORT);
  1809. }
  1810. void
  1811. Dhcpv4Srv::adjustRemoteAddr(Dhcpv4Exchange& ex) {
  1812. // Initialize the pointers to the client's message and the server's
  1813. // response.
  1814. Pkt4Ptr query = ex.getQuery();
  1815. Pkt4Ptr response = ex.getResponse();
  1816. // DHCPv4-over-DHCPv6 is simple
  1817. if (query->isDhcp4o6()) {
  1818. response->setRemoteAddr(query->getRemoteAddr());
  1819. return;
  1820. }
  1821. // The DHCPINFORM is slightly different than other messages in a sense
  1822. // that the server should always unicast the response to the ciaddr.
  1823. // It appears however that some clients don't set the ciaddr. We still
  1824. // want to provision these clients and we do what we can't to send the
  1825. // packet to the address where client can receive it.
  1826. if (query->getType() == DHCPINFORM) {
  1827. // If client adheres to RFC2131 it will set the ciaddr and in this
  1828. // case we always unicast our response to this address.
  1829. if (!query->getCiaddr().isV4Zero()) {
  1830. response->setRemoteAddr(query->getCiaddr());
  1831. // If we received DHCPINFORM via relay and the ciaddr is not set we
  1832. // will try to send the response via relay. The caveat is that the
  1833. // relay will not have any idea where to forward the packet because
  1834. // the yiaddr is likely not set. So, the broadcast flag is set so
  1835. // as the response may be broadcast.
  1836. } else if (query->isRelayed()) {
  1837. response->setRemoteAddr(query->getGiaddr());
  1838. response->setFlags(response->getFlags() | BOOTP_BROADCAST);
  1839. // If there is no ciaddr and no giaddr the only thing we can do is
  1840. // to use the source address of the packet.
  1841. } else {
  1842. response->setRemoteAddr(query->getRemoteAddr());
  1843. }
  1844. // Remote address is now set so return.
  1845. return;
  1846. }
  1847. // If received relayed message, server responds to the relay address.
  1848. if (query->isRelayed()) {
  1849. // The client should set the ciaddr when sending the DHCPINFORM
  1850. // but in case he didn't, the relay may not be able to determine the
  1851. // address of the client, because yiaddr is not set when responding
  1852. // to Confirm and the only address available was the source address
  1853. // of the client. The source address is however not used here because
  1854. // the message is relayed. Therefore, we set the BROADCAST flag so
  1855. // as the relay can broadcast the packet.
  1856. if ((query->getType() == DHCPINFORM) &&
  1857. query->getCiaddr().isV4Zero()) {
  1858. response->setFlags(BOOTP_BROADCAST);
  1859. }
  1860. response->setRemoteAddr(query->getGiaddr());
  1861. // If giaddr is 0 but client set ciaddr, server should unicast the
  1862. // response to ciaddr.
  1863. } else if (!query->getCiaddr().isV4Zero()) {
  1864. response->setRemoteAddr(query->getCiaddr());
  1865. // We can't unicast the response to the client when sending NAK,
  1866. // because we haven't allocated address for him. Therefore,
  1867. // NAK is broadcast.
  1868. } else if (response->getType() == DHCPNAK) {
  1869. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1870. // If yiaddr is set it means that we have created a lease for a client.
  1871. } else if (!response->getYiaddr().isV4Zero()) {
  1872. // If the broadcast bit is set in the flags field, we have to
  1873. // send the response to broadcast address. Client may have requested it
  1874. // because it doesn't support reception of messages on the interface
  1875. // which doesn't have an address assigned. The other case when response
  1876. // must be broadcasted is when our server does not support responding
  1877. // directly to a client without address assigned.
  1878. const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
  1879. if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
  1880. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1881. // Client cleared the broadcast bit and we support direct responses
  1882. // so we should unicast the response to a newly allocated address -
  1883. // yiaddr.
  1884. } else {
  1885. response->setRemoteAddr(response ->getYiaddr());
  1886. }
  1887. // In most cases, we should have the remote address found already. If we
  1888. // found ourselves at this point, the rational thing to do is to respond
  1889. // to the address we got the query from.
  1890. } else {
  1891. response->setRemoteAddr(query->getRemoteAddr());
  1892. }
  1893. }
  1894. void
  1895. Dhcpv4Srv::setFixedFields(Dhcpv4Exchange& ex) {
  1896. Pkt4Ptr query = ex.getQuery();
  1897. Pkt4Ptr response = ex.getResponse();
  1898. // Step 1: Start with fixed fields defined on subnet level.
  1899. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1900. if (subnet) {
  1901. IOAddress subnet_next_server = subnet->getSiaddr();
  1902. if (!subnet_next_server.isV4Zero()) {
  1903. response->setSiaddr(subnet_next_server);
  1904. }
  1905. }
  1906. // Step 2: Try to set the values based on classes.
  1907. // Any values defined in classes will override those from subnet level.
  1908. const ClientClasses classes = query->getClasses();
  1909. if (!classes.empty()) {
  1910. // Let's get class definitions
  1911. const ClientClassDefMapPtr& defs = CfgMgr::instance().getCurrentCfg()->
  1912. getClientClassDictionary()->getClasses();
  1913. // Now we need to iterate over the classes assigned to the
  1914. // query packet and find corresponding class definitions for it.
  1915. for (ClientClasses::const_iterator name = classes.begin();
  1916. name != classes.end(); ++name) {
  1917. ClientClassDefMap::const_iterator cl = defs->find(*name);
  1918. if (cl == defs->end()) {
  1919. // Let's skip classes that don't have definitions. Currently
  1920. // these are automatic classes VENDOR_CLASS_something, but there
  1921. // may be other classes assigned under other circumstances, e.g.
  1922. // by hooks.
  1923. continue;
  1924. }
  1925. IOAddress next_server = cl->second->getNextServer();
  1926. if (!next_server.isV4Zero()) {
  1927. response->setSiaddr(next_server);
  1928. }
  1929. const string& sname = cl->second->getSname();
  1930. if (!sname.empty()) {
  1931. // Converting string to (const uint8_t*, size_t len) format is
  1932. // tricky. reinterpret_cast is not the most elegant solution,
  1933. // but it does avoid us making unnecessary copy. We will convert
  1934. // sname and file fields in Pkt4 to string one day and life
  1935. // will be easier.
  1936. response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
  1937. sname.size());
  1938. }
  1939. const string& filename = cl->second->getFilename();
  1940. if (!filename.empty()) {
  1941. // Converting string to (const uint8_t*, size_t len) format is
  1942. // tricky. reinterpret_cast is not the most elegant solution,
  1943. // but it does avoid us making unnecessary copy. We will convert
  1944. // sname and file fields in Pkt4 to string one day and life
  1945. // will be easier.
  1946. response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
  1947. filename.size());
  1948. }
  1949. }
  1950. }
  1951. // Step 3: try to set values using HR. Any values coming from there will override
  1952. // the subnet or class values.
  1953. ex.setReservedMessageFields();
  1954. }
  1955. OptionPtr
  1956. Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
  1957. uint32_t netmask = getNetmask4(subnet->get().second).toUint32();
  1958. OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
  1959. DHO_SUBNET_MASK, netmask));
  1960. return (opt);
  1961. }
  1962. Pkt4Ptr
  1963. Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
  1964. sanityCheck(discover, FORBIDDEN);
  1965. Dhcpv4Exchange ex(alloc_engine_, discover, selectSubnet(discover));
  1966. // If DHCPDISCOVER message contains the FQDN or Hostname option, server
  1967. // may respond to the client with the appropriate FQDN or Hostname
  1968. // option to indicate that whether it will take responsibility for
  1969. // updating DNS when the client sends DHCPREQUEST message.
  1970. processClientName(ex);
  1971. assignLease(ex);
  1972. if (!ex.getResponse()) {
  1973. // The offer is empty so return it *now*!
  1974. return (Pkt4Ptr());
  1975. }
  1976. // Assign reserved classes.
  1977. ex.setReservedClientClasses();
  1978. // Adding any other options makes sense only when we got the lease.
  1979. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1980. buildCfgOptionList(ex);
  1981. appendRequestedOptions(ex);
  1982. appendRequestedVendorOptions(ex);
  1983. // There are a few basic options that we always want to
  1984. // include in the response. If client did not request
  1985. // them we append them for him.
  1986. appendBasicOptions(ex);
  1987. // Set fixed fields (siaddr, sname, filename) if defined in
  1988. // the reservation, class or subnet specific configuration.
  1989. setFixedFields(ex);
  1990. } else {
  1991. // If the server can't offer an address, it drops the packet.
  1992. return (Pkt4Ptr());
  1993. }
  1994. // Set the src/dest IP address, port and interface for the outgoing
  1995. // packet.
  1996. adjustIfaceData(ex);
  1997. appendServerID(ex);
  1998. return (ex.getResponse());
  1999. }
  2000. Pkt4Ptr
  2001. Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
  2002. /// @todo Uncomment this (see ticket #3116)
  2003. /// sanityCheck(request, MANDATORY);
  2004. Dhcpv4Exchange ex(alloc_engine_, request, selectSubnet(request));
  2005. // If DHCPREQUEST message contains the FQDN or Hostname option, server
  2006. // should respond to the client with the appropriate FQDN or Hostname
  2007. // option to indicate if it takes responsibility for the DNS updates.
  2008. // This is performed by the function below.
  2009. processClientName(ex);
  2010. // Note that we treat REQUEST message uniformly, regardless if this is a
  2011. // first request (requesting for new address), renewing existing address
  2012. // or even rebinding.
  2013. assignLease(ex);
  2014. if (!ex.getResponse()) {
  2015. // The ack is empty so return it *now*!
  2016. return (Pkt4Ptr());
  2017. }
  2018. // Assign reserved classes.
  2019. ex.setReservedClientClasses();
  2020. // Adding any other options makes sense only when we got the lease.
  2021. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  2022. buildCfgOptionList(ex);
  2023. appendRequestedOptions(ex);
  2024. appendRequestedVendorOptions(ex);
  2025. // There are a few basic options that we always want to
  2026. // include in the response. If client did not request
  2027. // them we append them for him.
  2028. appendBasicOptions(ex);
  2029. // Set fixed fields (siaddr, sname, filename) if defined in
  2030. // the reservation, class or subnet specific configuration.
  2031. setFixedFields(ex);
  2032. }
  2033. // Set the src/dest IP address, port and interface for the outgoing
  2034. // packet.
  2035. adjustIfaceData(ex);
  2036. appendServerID(ex);
  2037. return (ex.getResponse());
  2038. }
  2039. void
  2040. Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
  2041. /// @todo Uncomment this (see ticket #3116)
  2042. /// sanityCheck(release, MANDATORY);
  2043. // Try to find client-id. Note that for the DHCPRELEASE we don't check if the
  2044. // match-client-id configuration parameter is disabled because this parameter
  2045. // is configured for subnets and we don't select subnet for the DHCPRELEASE.
  2046. // Bogus clients usually generate new client identifiers when they first
  2047. // connect to the network, so whatever client identifier has been used to
  2048. // acquire the lease, the client identifier carried in the DHCPRELEASE is
  2049. // likely to be the same and the lease will be correctly identified in the
  2050. // lease database. If supplied client identifier differs from the one used
  2051. // to acquire the lease then the lease will remain in the database and
  2052. // simply expire.
  2053. ClientIdPtr client_id;
  2054. OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  2055. if (opt) {
  2056. client_id = ClientIdPtr(new ClientId(opt->getData()));
  2057. }
  2058. try {
  2059. // Do we have a lease for that particular address?
  2060. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
  2061. if (!lease) {
  2062. // No such lease - bogus release
  2063. LOG_DEBUG(lease4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_NO_LEASE)
  2064. .arg(release->getLabel())
  2065. .arg(release->getCiaddr().toText());
  2066. return;
  2067. }
  2068. if (!lease->belongsToClient(release->getHWAddr(), client_id)) {
  2069. LOG_DEBUG(lease4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT)
  2070. .arg(release->getLabel())
  2071. .arg(release->getCiaddr().toText());
  2072. return;
  2073. }
  2074. bool skip = false;
  2075. // Execute all callouts registered for lease4_release
  2076. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
  2077. CalloutHandlePtr callout_handle = getCalloutHandle(release);
  2078. // Delete all previous arguments
  2079. callout_handle->deleteAllArguments();
  2080. // Enable copying options from the packet within hook library.
  2081. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(release);
  2082. // Pass the original packet
  2083. callout_handle->setArgument("query4", release);
  2084. // Pass the lease to be updated
  2085. callout_handle->setArgument("lease4", lease);
  2086. // Call all installed callouts
  2087. HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
  2088. *callout_handle);
  2089. // Callouts decided to skip the next processing step. The next
  2090. // processing step would to send the packet, so skip at this
  2091. // stage means "drop response".
  2092. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  2093. skip = true;
  2094. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  2095. DHCP4_HOOK_LEASE4_RELEASE_SKIP)
  2096. .arg(release->getLabel());
  2097. }
  2098. /// @todo add support for DROP status
  2099. }
  2100. // Callout didn't indicate to skip the release process. Let's release
  2101. // the lease.
  2102. if (!skip) {
  2103. bool success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  2104. if (success) {
  2105. // Release successful
  2106. LOG_INFO(lease4_logger, DHCP4_RELEASE)
  2107. .arg(release->getLabel())
  2108. .arg(lease->addr_.toText());
  2109. // Need to decrease statistic for assigned addresses.
  2110. StatsMgr::instance().addValue(
  2111. StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-addresses"),
  2112. static_cast<int64_t>(-1));
  2113. // Remove existing DNS entries for the lease, if any.
  2114. queueNCR(CHG_REMOVE, lease);
  2115. } else {
  2116. // Release failed
  2117. LOG_ERROR(lease4_logger, DHCP4_RELEASE_FAIL)
  2118. .arg(release->getLabel())
  2119. .arg(lease->addr_.toText());
  2120. }
  2121. }
  2122. } catch (const isc::Exception& ex) {
  2123. LOG_ERROR(lease4_logger, DHCP4_RELEASE_EXCEPTION)
  2124. .arg(release->getLabel())
  2125. .arg(release->getCiaddr())
  2126. .arg(ex.what());
  2127. }
  2128. }
  2129. void
  2130. Dhcpv4Srv::processDecline(Pkt4Ptr& decline) {
  2131. // Server-id is mandatory in DHCPDECLINE (see table 5, RFC2131)
  2132. /// @todo Uncomment this (see ticket #3116)
  2133. // sanityCheck(decline, MANDATORY);
  2134. // Client is supposed to specify the address being declined in
  2135. // Requested IP address option, but must not set its ciaddr.
  2136. // (again, see table 5 in RFC2131).
  2137. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  2138. OptionCustom>(decline->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  2139. if (!opt_requested_address) {
  2140. isc_throw(RFCViolation, "Mandatory 'Requested IP address' option missing"
  2141. "in DHCPDECLINE sent from " << decline->getLabel());
  2142. }
  2143. IOAddress addr(opt_requested_address->readAddress());
  2144. // We could also extract client's address from ciaddr, but that's clearly
  2145. // against RFC2131.
  2146. // Now we need to check whether this address really belongs to the client
  2147. // that attempts to decline it.
  2148. const Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(addr);
  2149. if (!lease) {
  2150. // Client tried to decline an address, but we don't have a lease for
  2151. // that address. Let's ignore it.
  2152. //
  2153. // We could assume that we're recovering from a mishandled migration
  2154. // to a new server and mark the address as declined, but the window of
  2155. // opportunity for that to be useful is small and the attack vector
  2156. // would be pretty severe.
  2157. LOG_WARN(dhcp4_logger, DHCP4_DECLINE_LEASE_NOT_FOUND)
  2158. .arg(addr.toText()).arg(decline->getLabel());
  2159. return;
  2160. }
  2161. // Get client-id, if available.
  2162. OptionPtr opt_clientid = decline->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  2163. ClientIdPtr client_id;
  2164. if (opt_clientid) {
  2165. client_id.reset(new ClientId(opt_clientid->getData()));
  2166. }
  2167. // Check if the client attempted to decline a lease it doesn't own.
  2168. if (!lease->belongsToClient(decline->getHWAddr(), client_id)) {
  2169. // Get printable hardware addresses
  2170. string client_hw = decline->getHWAddr() ?
  2171. decline->getHWAddr()->toText(false) : "(none)";
  2172. string lease_hw = lease->hwaddr_ ?
  2173. lease->hwaddr_->toText(false) : "(none)";
  2174. // Get printable client-ids
  2175. string client_id_txt = client_id ? client_id->toText() : "(none)";
  2176. string lease_id_txt = lease->client_id_ ?
  2177. lease->client_id_->toText() : "(none)";
  2178. // Print the warning and we're done here.
  2179. LOG_WARN(dhcp4_logger, DHCP4_DECLINE_LEASE_MISMATCH)
  2180. .arg(addr.toText()).arg(decline->getLabel())
  2181. .arg(client_hw).arg(lease_hw).arg(client_id_txt).arg(lease_id_txt);
  2182. return;
  2183. }
  2184. // Ok, all is good. The client is reporting its own address. Let's
  2185. // process it.
  2186. declineLease(lease, decline);
  2187. }
  2188. void
  2189. Dhcpv4Srv::declineLease(const Lease4Ptr& lease, const Pkt4Ptr& decline) {
  2190. // Let's check if there are hooks installed for decline4 hook point.
  2191. // If they are, let's pass the lease and client's packet. If the hook
  2192. // sets status to drop, we reject this Decline.
  2193. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_decline_)) {
  2194. CalloutHandlePtr callout_handle = getCalloutHandle(decline);
  2195. // Delete previously set arguments
  2196. callout_handle->deleteAllArguments();
  2197. // Enable copying options from the packet within hook library.
  2198. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(decline);
  2199. // Pass incoming Decline and the lease to be declined.
  2200. callout_handle->setArgument("lease4", lease);
  2201. callout_handle->setArgument("query4", decline);
  2202. // Call callouts
  2203. HooksManager::callCallouts(Hooks.hook_index_lease4_decline_,
  2204. *callout_handle);
  2205. // Check if callouts decided to drop the packet. If any of them did,
  2206. // we will drop the packet.
  2207. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
  2208. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_DECLINE_SKIP)
  2209. .arg(decline->getLabel()).arg(lease->addr_.toText());
  2210. return;
  2211. }
  2212. }
  2213. // Remove existing DNS entries for the lease, if any.
  2214. // queueNCR will do the necessary checks and will skip the update, if not needed.
  2215. queueNCR(CHG_REMOVE, lease);
  2216. // Bump up the statistics.
  2217. // Per subnet declined addresses counter.
  2218. StatsMgr::instance().addValue(
  2219. StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
  2220. static_cast<int64_t>(1));
  2221. // Global declined addresses counter.
  2222. StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));
  2223. // We do not want to decrease the assigned-addresses at this time. While
  2224. // technically a declined address is no longer allocated, the primary usage
  2225. // of the assigned-addresses statistic is to monitor pool utilization. Most
  2226. // people would forget to include declined-addresses in the calculation,
  2227. // and simply do assigned-addresses/total-addresses. This would have a bias
  2228. // towards under-representing pool utilization, if we decreased allocated
  2229. // immediately after receiving DHCPDECLINE, rather than later when we recover
  2230. // the address.
  2231. // @todo: Call hooks.
  2232. // We need to disassociate the lease from the client. Once we move a lease
  2233. // to declined state, it is no longer associated with the client in any
  2234. // way.
  2235. lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());
  2236. LeaseMgrFactory::instance().updateLease4(lease);
  2237. LOG_INFO(lease4_logger, DHCP4_DECLINE_LEASE).arg(lease->addr_.toText())
  2238. .arg(decline->getLabel()).arg(lease->valid_lft_);
  2239. }
  2240. Pkt4Ptr
  2241. Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
  2242. // DHCPINFORM MUST not include server identifier.
  2243. sanityCheck(inform, FORBIDDEN);
  2244. Dhcpv4Exchange ex(alloc_engine_, inform, selectSubnet(inform));
  2245. Pkt4Ptr ack = ex.getResponse();
  2246. ex.setReservedClientClasses();
  2247. buildCfgOptionList(ex);
  2248. appendRequestedOptions(ex);
  2249. appendRequestedVendorOptions(ex);
  2250. appendBasicOptions(ex);
  2251. adjustIfaceData(ex);
  2252. // Set fixed fields (siaddr, sname, filename) if defined in
  2253. // the reservation, class or subnet specific configuration.
  2254. setFixedFields(ex);
  2255. // There are cases for the DHCPINFORM that the server receives it via
  2256. // relay but will send the response to the client's unicast address
  2257. // carried in the ciaddr. In this case, the giaddr and hops field should
  2258. // be cleared (these fields were copied by the copyDefaultFields function).
  2259. // Also Relay Agent Options should be removed if present.
  2260. if (ack->getRemoteAddr() != inform->getGiaddr()) {
  2261. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL, DHCP4_INFORM_DIRECT_REPLY)
  2262. .arg(inform->getLabel())
  2263. .arg(ack->getRemoteAddr())
  2264. .arg(ack->getIface());
  2265. ack->setHops(0);
  2266. ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  2267. ack->delOption(DHO_DHCP_AGENT_OPTIONS);
  2268. }
  2269. // The DHCPACK must contain server id.
  2270. appendServerID(ex);
  2271. return (ex.getResponse());
  2272. }
  2273. bool
  2274. Dhcpv4Srv::accept(const Pkt4Ptr& query) const {
  2275. // Check that the message type is accepted by the server. We rely on the
  2276. // function called to log a message if needed.
  2277. if (!acceptMessageType(query)) {
  2278. return (false);
  2279. }
  2280. // Check if the message from directly connected client (if directly
  2281. // connected) should be dropped or processed.
  2282. if (!acceptDirectRequest(query)) {
  2283. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0002)
  2284. .arg(query->getLabel())
  2285. .arg(query->getIface());
  2286. return (false);
  2287. }
  2288. // Check if the DHCPv4 packet has been sent to us or to someone else.
  2289. // If it hasn't been sent to us, drop it!
  2290. if (!acceptServerId(query)) {
  2291. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0003)
  2292. .arg(query->getLabel())
  2293. .arg(query->getIface());
  2294. return (false);
  2295. }
  2296. return (true);
  2297. }
  2298. bool
  2299. Dhcpv4Srv::acceptDirectRequest(const Pkt4Ptr& pkt) const {
  2300. // Accept all relayed messages.
  2301. if (pkt->isRelayed()) {
  2302. return (true);
  2303. }
  2304. // Accept all DHCPv4-over-DHCPv6 messages.
  2305. if (pkt->isDhcp4o6()) {
  2306. return (true);
  2307. }
  2308. // The source address must not be zero for the DHCPINFORM message from
  2309. // the directly connected client because the server will not know where
  2310. // to respond if the ciaddr was not present.
  2311. try {
  2312. if (pkt->getType() == DHCPINFORM) {
  2313. if (pkt->getRemoteAddr().isV4Zero() &&
  2314. pkt->getCiaddr().isV4Zero()) {
  2315. return (false);
  2316. }
  2317. }
  2318. } catch (...) {
  2319. // If we got here, it is probably because the message type hasn't
  2320. // been set. But, this should not really happen assuming that
  2321. // we validate the message type prior to calling this function.
  2322. return (false);
  2323. }
  2324. return (!pkt->getLocalAddr().isV4Bcast() || selectSubnet(pkt));
  2325. }
  2326. bool
  2327. Dhcpv4Srv::acceptMessageType(const Pkt4Ptr& query) const {
  2328. // When receiving a packet without message type option, getType() will
  2329. // throw.
  2330. int type;
  2331. try {
  2332. type = query->getType();
  2333. } catch (...) {
  2334. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0004)
  2335. .arg(query->getLabel())
  2336. .arg(query->getIface());
  2337. return (false);
  2338. }
  2339. // If we receive a message with a non-existing type, we are logging it.
  2340. if (type > DHCPLEASEQUERYDONE) {
  2341. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0005)
  2342. .arg(query->getLabel())
  2343. .arg(type);
  2344. return (false);
  2345. }
  2346. // Once we know that the message type is within a range of defined DHCPv4
  2347. // messages, we do a detailed check to make sure that the received message
  2348. // is targeted at server. Note that we could have received some Offer
  2349. // message broadcasted by the other server to a relay. Even though, the
  2350. // server would rather unicast its response to a relay, let's be on the
  2351. // safe side. Also, we want to drop other messages which we don't support.
  2352. // All these valid messages that we are not going to process are dropped
  2353. // silently.
  2354. if ((type != DHCPDISCOVER) && (type != DHCPREQUEST) &&
  2355. (type != DHCPRELEASE) && (type != DHCPDECLINE) &&
  2356. (type != DHCPINFORM)) {
  2357. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0006)
  2358. .arg(query->getLabel())
  2359. .arg(type);
  2360. return (false);
  2361. }
  2362. return (true);
  2363. }
  2364. bool
  2365. Dhcpv4Srv::acceptServerId(const Pkt4Ptr& query) const {
  2366. // This function is meant to be called internally by the server class, so
  2367. // we rely on the caller to sanity check the pointer and we don't check
  2368. // it here.
  2369. // Check if server identifier option is present. If it is not present
  2370. // we accept the message because it is targeted to all servers.
  2371. // Note that we don't check cases that server identifier is mandatory
  2372. // but not present. This is meant to be sanity checked in other
  2373. // functions.
  2374. OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  2375. if (!option) {
  2376. return (true);
  2377. }
  2378. // Server identifier is present. Let's convert it to 4-byte address
  2379. // and try to match with server identifiers used by the server.
  2380. OptionCustomPtr option_custom =
  2381. boost::dynamic_pointer_cast<OptionCustom>(option);
  2382. // Unable to convert the option to the option type which encapsulates it.
  2383. // We treat this as non-matching server id.
  2384. if (!option_custom) {
  2385. return (false);
  2386. }
  2387. // The server identifier option should carry exactly one IPv4 address.
  2388. // If the option definition for the server identifier doesn't change,
  2389. // the OptionCustom object should have exactly one IPv4 address and
  2390. // this check is somewhat redundant. On the other hand, if someone
  2391. // breaks option it may be better to check that here.
  2392. if (option_custom->getDataFieldsNum() != 1) {
  2393. return (false);
  2394. }
  2395. // The server identifier MUST be an IPv4 address. If given address is
  2396. // v6, it is wrong.
  2397. IOAddress server_id = option_custom->readAddress();
  2398. if (!server_id.isV4()) {
  2399. return (false);
  2400. }
  2401. // This function iterates over all interfaces on which the
  2402. // server is listening to find the one which has a socket bound
  2403. // to the address carried in the server identifier option.
  2404. // This has some performance implications. However, given that
  2405. // typically there will be just a few active interfaces the
  2406. // performance hit should be acceptable. If it turns out to
  2407. // be significant, we will have to cache server identifiers
  2408. // when sockets are opened.
  2409. if (IfaceMgr::instance().hasOpenSocket(server_id)) {
  2410. return (true);
  2411. }
  2412. // There are some cases when an administrator explicitly sets server
  2413. // identifier (option 54) that should be used for a given, subnet,
  2414. // network etc. It doesn't have to be an address assigned to any of
  2415. // the server interfaces. Thus, we have to check if the server
  2416. // identifier received is the one that we explicitly set in the
  2417. // server configuration. At this point, we don't know which subnet
  2418. // the client belongs to so we can't match the server id with any
  2419. // subnet. We simply check if this server identifier is configured
  2420. // anywhere. This should be good enough to eliminate exchanges
  2421. // with other servers in the same network.
  2422. /// @todo Currently we only check subnet identifiers configured on the
  2423. /// subnet level, shared network level and global level. This should
  2424. /// be sufficient for most of cases. At this point, trying to support
  2425. /// server identifiers on the class level seems to be an overkill and
  2426. /// is probably not needed. Same with host reservations. In fact,
  2427. /// at this point we don't know the reservations for the client
  2428. /// communicating with the server. We may revise some of these choices
  2429. /// in the future.
  2430. SrvConfigPtr cfg = CfgMgr::instance().getCurrentCfg();
  2431. // Check if there is at least one subnet configured with this server
  2432. // identifier.
  2433. ConstCfgSubnets4Ptr cfg_subnets = cfg->getCfgSubnets4();
  2434. if (cfg_subnets->hasSubnetWithServerId(server_id)) {
  2435. return (true);
  2436. }
  2437. // This server identifier is not configured for any of the subnets, so
  2438. // check on the shared network level.
  2439. CfgSharedNetworks4Ptr cfg_networks = cfg->getCfgSharedNetworks4();
  2440. if (cfg_networks->hasNetworkWithServerId(server_id)) {
  2441. return (true);
  2442. }
  2443. // Finally, it is possible that the server identifier is specified
  2444. // on the global level.
  2445. ConstCfgOptionPtr cfg_global_options = cfg->getCfgOption();
  2446. OptionCustomPtr opt_server_id = boost::dynamic_pointer_cast<OptionCustom>
  2447. (cfg_global_options->get(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER).option_);
  2448. return (opt_server_id && (opt_server_id->readAddress() == server_id));
  2449. }
  2450. void
  2451. Dhcpv4Srv::sanityCheck(const Pkt4Ptr& query, RequirementLevel serverid) {
  2452. OptionPtr server_id = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  2453. switch (serverid) {
  2454. case FORBIDDEN:
  2455. if (server_id) {
  2456. isc_throw(RFCViolation, "Server-id option was not expected, but "
  2457. << "received in "
  2458. << query->getName());
  2459. }
  2460. break;
  2461. case MANDATORY:
  2462. if (!server_id) {
  2463. isc_throw(RFCViolation, "Server-id option was expected, but not "
  2464. " received in message "
  2465. << query->getName());
  2466. }
  2467. break;
  2468. case OPTIONAL:
  2469. // do nothing here
  2470. ;
  2471. }
  2472. // If there is HWAddress set and it is non-empty, then we're good
  2473. if (query->getHWAddr() && !query->getHWAddr()->hwaddr_.empty()) {
  2474. return;
  2475. }
  2476. // There has to be something to uniquely identify the client:
  2477. // either non-zero MAC address or client-id option present (or both)
  2478. OptionPtr client_id = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  2479. // If there's no client-id (or a useless one is provided, i.e. 0 length)
  2480. if (!client_id || client_id->len() == client_id->getHeaderLen()) {
  2481. isc_throw(RFCViolation, "Missing or useless client-id and no HW address "
  2482. " provided in message "
  2483. << query->getName());
  2484. }
  2485. }
  2486. void Dhcpv4Srv::classifyByVendor(const Pkt4Ptr& pkt) {
  2487. // Built-in vendor class processing
  2488. boost::shared_ptr<OptionString> vendor_class =
  2489. boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
  2490. if (!vendor_class) {
  2491. return;
  2492. }
  2493. pkt->addClass(VENDOR_CLASS_PREFIX + vendor_class->getValue());
  2494. }
  2495. void Dhcpv4Srv::classifyPacket(const Pkt4Ptr& pkt) {
  2496. // First phase: built-in vendor class processing
  2497. classifyByVendor(pkt);
  2498. // Run match expressions
  2499. // Note getClientClassDictionary() cannot be null
  2500. const ClientClassDefMapPtr& defs_ptr = CfgMgr::instance().getCurrentCfg()->
  2501. getClientClassDictionary()->getClasses();
  2502. for (ClientClassDefMap::const_iterator it = defs_ptr->begin();
  2503. it != defs_ptr->end(); ++it) {
  2504. // Note second cannot be null
  2505. const ExpressionPtr& expr_ptr = it->second->getMatchExpr();
  2506. // Nothing to do without an expression to evaluate
  2507. if (!expr_ptr) {
  2508. continue;
  2509. }
  2510. // Evaluate the expression which can return false (no match),
  2511. // true (match) or raise an exception (error)
  2512. try {
  2513. bool status = evaluateBool(*expr_ptr, *pkt);
  2514. if (status) {
  2515. LOG_INFO(options4_logger, EVAL_RESULT)
  2516. .arg(it->first)
  2517. .arg(status);
  2518. // Matching: add the class
  2519. pkt->addClass(it->first);
  2520. } else {
  2521. LOG_DEBUG(options4_logger, DBG_DHCP4_DETAIL, EVAL_RESULT)
  2522. .arg(it->first)
  2523. .arg(status);
  2524. }
  2525. } catch (const Exception& ex) {
  2526. LOG_ERROR(options4_logger, EVAL_RESULT)
  2527. .arg(it->first)
  2528. .arg(ex.what());
  2529. } catch (...) {
  2530. LOG_ERROR(options4_logger, EVAL_RESULT)
  2531. .arg(it->first)
  2532. .arg("get exception?");
  2533. }
  2534. }
  2535. }
  2536. void
  2537. Dhcpv4Srv::deferredUnpack(Pkt4Ptr& query)
  2538. {
  2539. // Iterate on the list of deferred option codes
  2540. BOOST_FOREACH(const uint16_t& code, query->getDeferredOptions()) {
  2541. OptionDefinitionPtr def;
  2542. // Iterate on client classes
  2543. const ClientClasses& classes = query->getClasses();
  2544. for (ClientClasses::const_iterator cclass = classes.begin();
  2545. cclass != classes.end(); ++cclass) {
  2546. // Get the client class definition for this class
  2547. const ClientClassDefPtr& ccdef =
  2548. CfgMgr::instance().getCurrentCfg()->
  2549. getClientClassDictionary()->findClass(*cclass);
  2550. // If not found skip it
  2551. if (!ccdef) {
  2552. continue;
  2553. }
  2554. // If there is no option definition skip it
  2555. if (!ccdef->getCfgOptionDef()) {
  2556. continue;
  2557. }
  2558. def = ccdef->getCfgOptionDef()->get(DHCP4_OPTION_SPACE, code);
  2559. // Stop at the first client class with a defition
  2560. if (def) {
  2561. break;
  2562. }
  2563. }
  2564. // If not found try the global definition
  2565. if (!def) {
  2566. def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, code);
  2567. }
  2568. if (!def) {
  2569. def = LibDHCP::getRuntimeOptionDef(DHCP4_OPTION_SPACE, code);
  2570. }
  2571. // Finish by last resort definition
  2572. if (!def) {
  2573. def = LibDHCP::getLastResortOptionDef(DHCP4_OPTION_SPACE, code);
  2574. }
  2575. // If not defined go to the next option
  2576. if (!def) {
  2577. continue;
  2578. }
  2579. // Get the existing option for its content and remove all
  2580. OptionPtr opt = query->getOption(code);
  2581. if (!opt) {
  2582. // should not happen but do not crash anyway
  2583. continue;
  2584. }
  2585. const OptionBuffer buf = opt->getData();
  2586. while (query->delOption(code)) {
  2587. // continue
  2588. }
  2589. // Unpack the option and add it
  2590. opt = def->optionFactory(Option::V4, code, buf.cbegin(), buf.cend());
  2591. query->addOption(opt);
  2592. }
  2593. }
  2594. void
  2595. Dhcpv4Srv::startD2() {
  2596. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  2597. if (d2_mgr.ddnsEnabled()) {
  2598. // Updates are enabled, so lets start the sender, passing in
  2599. // our error handler.
  2600. // This may throw so wherever this is called needs to ready.
  2601. d2_mgr.startSender(boost::bind(&Dhcpv4Srv::d2ClientErrorHandler,
  2602. this, _1, _2));
  2603. }
  2604. }
  2605. void
  2606. Dhcpv4Srv::stopD2() {
  2607. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  2608. if (d2_mgr.ddnsEnabled()) {
  2609. // Updates are enabled, so lets stop the sender
  2610. d2_mgr.stopSender();
  2611. }
  2612. }
  2613. void
  2614. Dhcpv4Srv::d2ClientErrorHandler(const
  2615. dhcp_ddns::NameChangeSender::Result result,
  2616. dhcp_ddns::NameChangeRequestPtr& ncr) {
  2617. LOG_ERROR(ddns4_logger, DHCP4_DDNS_REQUEST_SEND_FAILED).
  2618. arg(result).arg((ncr ? ncr->toText() : " NULL "));
  2619. // We cannot communicate with kea-dhcp-ddns, suspend further updates.
  2620. /// @todo We may wish to revisit this, but for now we will simply turn
  2621. /// them off.
  2622. CfgMgr::instance().getD2ClientMgr().suspendUpdates();
  2623. }
  2624. // Refer to config_report so it will be embedded in the binary
  2625. const char* const* dhcp4_config_report = isc::detail::config_report;
  2626. std::string
  2627. Dhcpv4Srv::getVersion(bool extended) {
  2628. std::stringstream tmp;
  2629. tmp << VERSION;
  2630. if (extended) {
  2631. tmp << endl << EXTENDED_VERSION << endl;
  2632. tmp << "linked with:" << endl;
  2633. tmp << Logger::getVersion() << endl;
  2634. tmp << CryptoLink::getVersion() << endl;
  2635. tmp << "database:" << endl;
  2636. #ifdef HAVE_MYSQL
  2637. tmp << MySqlLeaseMgr::getDBVersion() << endl;
  2638. #endif
  2639. #ifdef HAVE_PGSQL
  2640. tmp << PgSqlLeaseMgr::getDBVersion() << endl;
  2641. #endif
  2642. #ifdef HAVE_CQL
  2643. tmp << CqlLeaseMgr::getDBVersion() << endl;
  2644. #endif
  2645. tmp << Memfile_LeaseMgr::getDBVersion();
  2646. // @todo: more details about database runtime
  2647. }
  2648. return (tmp.str());
  2649. }
  2650. void Dhcpv4Srv::processStatsReceived(const Pkt4Ptr& query) {
  2651. // Note that we're not bumping pkt4-received statistic as it was
  2652. // increased early in the packet reception code.
  2653. string stat_name = "pkt4-unknown-received";
  2654. try {
  2655. switch (query->getType()) {
  2656. case DHCPDISCOVER:
  2657. stat_name = "pkt4-discover-received";
  2658. break;
  2659. case DHCPOFFER:
  2660. // Should not happen, but let's keep a counter for it
  2661. stat_name = "pkt4-offer-received";
  2662. break;
  2663. case DHCPREQUEST:
  2664. stat_name = "pkt4-request-received";
  2665. break;
  2666. case DHCPACK:
  2667. // Should not happen, but let's keep a counter for it
  2668. stat_name = "pkt4-ack-received";
  2669. break;
  2670. case DHCPNAK:
  2671. // Should not happen, but let's keep a counter for it
  2672. stat_name = "pkt4-nak-received";
  2673. break;
  2674. case DHCPRELEASE:
  2675. stat_name = "pkt4-release-received";
  2676. break;
  2677. case DHCPDECLINE:
  2678. stat_name = "pkt4-decline-received";
  2679. break;
  2680. case DHCPINFORM:
  2681. stat_name = "pkt4-inform-received";
  2682. break;
  2683. default:
  2684. ; // do nothing
  2685. }
  2686. }
  2687. catch (...) {
  2688. // If the incoming packet doesn't have option 53 (message type)
  2689. // or a hook set pkt4_receive_skip, then Pkt4::getType() may
  2690. // throw an exception. That's ok, we'll then use the default
  2691. // name of pkt4-unknown-received.
  2692. }
  2693. isc::stats::StatsMgr::instance().addValue(stat_name,
  2694. static_cast<int64_t>(1));
  2695. }
  2696. void Dhcpv4Srv::processStatsSent(const Pkt4Ptr& response) {
  2697. // Increase generic counter for sent packets.
  2698. isc::stats::StatsMgr::instance().addValue("pkt4-sent",
  2699. static_cast<int64_t>(1));
  2700. // Increase packet type specific counter for packets sent.
  2701. string stat_name;
  2702. switch (response->getType()) {
  2703. case DHCPOFFER:
  2704. stat_name = "pkt4-offer-sent";
  2705. break;
  2706. case DHCPACK:
  2707. stat_name = "pkt4-ack-sent";
  2708. break;
  2709. case DHCPNAK:
  2710. stat_name = "pkt4-nak-sent";
  2711. break;
  2712. default:
  2713. // That should never happen
  2714. return;
  2715. }
  2716. isc::stats::StatsMgr::instance().addValue(stat_name,
  2717. static_cast<int64_t>(1));
  2718. }
  2719. int Dhcpv4Srv::getHookIndexBuffer4Receive() {
  2720. return (Hooks.hook_index_buffer4_receive_);
  2721. }
  2722. int Dhcpv4Srv::getHookIndexPkt4Receive() {
  2723. return (Hooks.hook_index_pkt4_receive_);
  2724. }
  2725. int Dhcpv4Srv::getHookIndexSubnet4Select() {
  2726. return (Hooks.hook_index_subnet4_select_);
  2727. }
  2728. int Dhcpv4Srv::getHookIndexLease4Release() {
  2729. return (Hooks.hook_index_lease4_release_);
  2730. }
  2731. int Dhcpv4Srv::getHookIndexPkt4Send() {
  2732. return (Hooks.hook_index_pkt4_send_);
  2733. }
  2734. int Dhcpv4Srv::getHookIndexBuffer4Send() {
  2735. return (Hooks.hook_index_buffer4_send_);
  2736. }
  2737. int Dhcpv4Srv::getHookIndexLease4Decline() {
  2738. return (Hooks.hook_index_lease4_decline_);
  2739. }
  2740. } // namespace dhcp
  2741. } // namespace isc