dhcp4_srv.cc 107 KB

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