dhcp4_srv.cc 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159
  1. // Copyright (C) 2011-2015 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <asiolink/io_address.h>
  15. #include <dhcp/dhcp4.h>
  16. #include <dhcp/duid.h>
  17. #include <dhcp/hwaddr.h>
  18. #include <dhcp/iface_mgr.h>
  19. #include <dhcp/option4_addrlst.h>
  20. #include <dhcp/option_int.h>
  21. #include <dhcp/option_int_array.h>
  22. #include <dhcp/option_vendor.h>
  23. #include <dhcp/option_string.h>
  24. #include <dhcp/pkt4.h>
  25. #include <dhcp/docsis3_option_defs.h>
  26. #include <dhcp4/dhcp4_log.h>
  27. #include <dhcp4/dhcp4_srv.h>
  28. #include <dhcpsrv/addr_utilities.h>
  29. #include <dhcpsrv/callout_handle_store.h>
  30. #include <dhcpsrv/cfgmgr.h>
  31. #include <dhcpsrv/cfg_subnets4.h>
  32. #include <dhcpsrv/lease_mgr.h>
  33. #include <dhcpsrv/lease_mgr_factory.h>
  34. #include <dhcpsrv/subnet.h>
  35. #include <dhcpsrv/subnet_selector.h>
  36. #include <dhcpsrv/utils.h>
  37. #include <dhcpsrv/utils.h>
  38. #include <hooks/callout_handle.h>
  39. #include <hooks/hooks_manager.h>
  40. #include <util/strutil.h>
  41. #include <asio.hpp>
  42. #include <boost/bind.hpp>
  43. #include <boost/foreach.hpp>
  44. #include <boost/shared_ptr.hpp>
  45. #include <iomanip>
  46. using namespace isc;
  47. using namespace isc::asiolink;
  48. using namespace isc::dhcp;
  49. using namespace isc::dhcp_ddns;
  50. using namespace isc::hooks;
  51. using namespace isc::log;
  52. using namespace std;
  53. /// Structure that holds registered hook indexes
  54. struct Dhcp4Hooks {
  55. int hook_index_buffer4_receive_;///< index for "buffer4_receive" hook point
  56. int hook_index_pkt4_receive_; ///< index for "pkt4_receive" hook point
  57. int hook_index_subnet4_select_; ///< index for "subnet4_select" hook point
  58. int hook_index_lease4_release_; ///< index for "lease4_release" hook point
  59. int hook_index_pkt4_send_; ///< index for "pkt4_send" hook point
  60. int hook_index_buffer4_send_; ///< index for "buffer4_send" hook point
  61. /// Constructor that registers hook points for DHCPv4 engine
  62. Dhcp4Hooks() {
  63. hook_index_buffer4_receive_= HooksManager::registerHook("buffer4_receive");
  64. hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
  65. hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
  66. hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
  67. hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
  68. hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
  69. }
  70. };
  71. // Declare a Hooks object. As this is outside any function or method, it
  72. // will be instantiated (and the constructor run) when the module is loaded.
  73. // As a result, the hook indexes will be defined before any method in this
  74. // module is called.
  75. Dhcp4Hooks Hooks;
  76. namespace isc {
  77. namespace dhcp {
  78. Dhcpv4Exchange::Dhcpv4Exchange(const AllocEnginePtr& alloc_engine,
  79. const Pkt4Ptr& query,
  80. const Subnet4Ptr& subnet)
  81. : alloc_engine_(alloc_engine), query_(query), resp_(),
  82. context_(new AllocEngine::ClientContext4()) {
  83. if (!alloc_engine_) {
  84. isc_throw(BadValue, "alloc_engine value must not be NULL"
  85. " when creating an instance of the Dhcpv4Exchange");
  86. }
  87. if (!query_) {
  88. isc_throw(BadValue, "query value must not be NULL when"
  89. " creating an instance of the Dhcpv4Exchange");
  90. }
  91. // Create response message.
  92. initResponse();
  93. // Select subnet for the query message.
  94. context_->subnet_ = subnet;
  95. // Hardware address.
  96. context_->hwaddr_ = query->getHWAddr();
  97. // Client Identifier
  98. OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  99. if (opt_clientid) {
  100. context_->clientid_.reset(new ClientId(opt_clientid->getData()));
  101. }
  102. // Check for static reservations.
  103. alloc_engine->findReservation(*context_);
  104. };
  105. void
  106. Dhcpv4Exchange::initResponse() {
  107. uint8_t resp_type = 0;
  108. switch (getQuery()->getType()) {
  109. case DHCPDISCOVER:
  110. resp_type = DHCPOFFER;
  111. break;
  112. case DHCPREQUEST:
  113. case DHCPINFORM:
  114. resp_type = DHCPACK;
  115. break;
  116. default:
  117. ;
  118. }
  119. // Only create a response if one is required.
  120. if (resp_type > 0) {
  121. resp_.reset(new Pkt4(resp_type, getQuery()->getTransid()));
  122. copyDefaultFields();
  123. }
  124. }
  125. void
  126. Dhcpv4Exchange::copyDefaultFields() {
  127. resp_->setIface(query_->getIface());
  128. resp_->setIndex(query_->getIndex());
  129. // explicitly set this to 0
  130. resp_->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  131. // ciaddr is always 0, except for the Renew/Rebind state when it may
  132. // be set to the ciaddr sent by the client.
  133. resp_->setCiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  134. resp_->setHops(query_->getHops());
  135. // copy MAC address
  136. resp_->setHWAddr(query_->getHWAddr());
  137. // relay address
  138. resp_->setGiaddr(query_->getGiaddr());
  139. // Let's copy client-id to response. See RFC6842.
  140. // It is possible to disable RFC6842 to keep backward compatibility
  141. bool echo = CfgMgr::instance().echoClientId();
  142. OptionPtr client_id = query_->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  143. if (client_id && echo) {
  144. resp_->addOption(client_id);
  145. }
  146. // If src/dest HW addresses are used by the packet filtering class
  147. // we need to copy them as well. There is a need to check that the
  148. // address being set is not-NULL because an attempt to set the NULL
  149. // HW would result in exception. If these values are not set, the
  150. // the default HW addresses (zeroed) should be generated by the
  151. // packet filtering class when creating Ethernet header for
  152. // outgoing packet.
  153. HWAddrPtr src_hw_addr = query_->getLocalHWAddr();
  154. if (src_hw_addr) {
  155. resp_->setLocalHWAddr(src_hw_addr);
  156. }
  157. HWAddrPtr dst_hw_addr = query_->getRemoteHWAddr();
  158. if (dst_hw_addr) {
  159. resp_->setRemoteHWAddr(dst_hw_addr);
  160. }
  161. // If this packet is relayed, we want to copy Relay Agent Info option
  162. OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
  163. if (rai) {
  164. resp_->addOption(rai);
  165. }
  166. }
  167. const std::string Dhcpv4Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");
  168. Dhcpv4Srv::Dhcpv4Srv(uint16_t port, const bool use_bcast,
  169. const bool direct_response_desired)
  170. : shutdown_(true), alloc_engine_(), port_(port),
  171. use_bcast_(use_bcast), hook_index_pkt4_receive_(-1),
  172. hook_index_subnet4_select_(-1), hook_index_pkt4_send_(-1) {
  173. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_OPEN_SOCKET).arg(port);
  174. try {
  175. // Port 0 is used for testing purposes where we don't open broadcast
  176. // capable sockets. So, set the packet filter handling direct traffic
  177. // only if we are in non-test mode.
  178. if (port) {
  179. // First call to instance() will create IfaceMgr (it's a singleton)
  180. // it may throw something if things go wrong.
  181. // The 'true' value of the call to setMatchingPacketFilter imposes
  182. // that IfaceMgr will try to use the mechanism to respond directly
  183. // to the client which doesn't have address assigned. This capability
  184. // may be lacking on some OSes, so there is no guarantee that server
  185. // will be able to respond directly.
  186. IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
  187. }
  188. // Instantiate allocation engine
  189. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100,
  190. false /* false = IPv4 */));
  191. // Register hook points
  192. hook_index_pkt4_receive_ = Hooks.hook_index_pkt4_receive_;
  193. hook_index_subnet4_select_ = Hooks.hook_index_subnet4_select_;
  194. hook_index_pkt4_send_ = Hooks.hook_index_pkt4_send_;
  195. /// @todo call loadLibraries() when handling configuration changes
  196. } catch (const std::exception &e) {
  197. LOG_ERROR(dhcp4_logger, DHCP4_SRV_CONSTRUCT_ERROR).arg(e.what());
  198. shutdown_ = true;
  199. return;
  200. }
  201. shutdown_ = false;
  202. }
  203. Dhcpv4Srv::~Dhcpv4Srv() {
  204. IfaceMgr::instance().closeSockets();
  205. }
  206. void
  207. Dhcpv4Srv::shutdown() {
  208. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_SHUTDOWN_REQUEST);
  209. shutdown_ = true;
  210. }
  211. isc::dhcp::Subnet4Ptr
  212. Dhcpv4Srv::selectSubnet(const Pkt4Ptr& query) const {
  213. Subnet4Ptr subnet;
  214. SubnetSelector selector;
  215. selector.ciaddr_ = query->getCiaddr();
  216. selector.giaddr_ = query->getGiaddr();
  217. selector.local_address_ = query->getLocalAddr();
  218. selector.remote_address_ = query->getRemoteAddr();
  219. selector.client_classes_ = query->classes_;
  220. selector.iface_name_ = query->getIface();
  221. CfgMgr& cfgmgr = CfgMgr::instance();
  222. subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet(selector);
  223. // Let's execute all callouts registered for subnet4_select
  224. if (HooksManager::calloutsPresent(hook_index_subnet4_select_)) {
  225. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  226. // We're reusing callout_handle from previous calls
  227. callout_handle->deleteAllArguments();
  228. // Set new arguments
  229. callout_handle->setArgument("query4", query);
  230. callout_handle->setArgument("subnet4", subnet);
  231. callout_handle->setArgument("subnet4collection",
  232. cfgmgr.getCurrentCfg()->
  233. getCfgSubnets4()->getAll());
  234. // Call user (and server-side) callouts
  235. HooksManager::callCallouts(hook_index_subnet4_select_,
  236. *callout_handle);
  237. // Callouts decided to skip this step. This means that no subnet
  238. // will be selected. Packet processing will continue, but it will
  239. // be severely limited (i.e. only global options will be assigned)
  240. if (callout_handle->getSkip()) {
  241. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS,
  242. DHCP4_HOOK_SUBNET4_SELECT_SKIP);
  243. return (Subnet4Ptr());
  244. }
  245. // Use whatever subnet was specified by the callout
  246. callout_handle->getArgument("subnet4", subnet);
  247. }
  248. return (subnet);
  249. }
  250. Pkt4Ptr
  251. Dhcpv4Srv::receivePacket(int timeout) {
  252. return (IfaceMgr::instance().receive4(timeout));
  253. }
  254. void
  255. Dhcpv4Srv::sendPacket(const Pkt4Ptr& packet) {
  256. IfaceMgr::instance().send(packet);
  257. }
  258. bool
  259. Dhcpv4Srv::run() {
  260. while (!shutdown_) {
  261. // client's message and server's response
  262. Pkt4Ptr query;
  263. Pkt4Ptr rsp;
  264. try {
  265. // The lease database backend may install some timers for which
  266. // the handlers need to be executed periodically. Retrieve the
  267. // maximum interval at which the handlers must be executed from
  268. // the lease manager.
  269. uint32_t timeout = LeaseMgrFactory::instance().getIOServiceExecInterval();
  270. // If the returned value is zero it means that there are no
  271. // timers installed, so use a default value.
  272. if (timeout == 0) {
  273. timeout = 1000;
  274. }
  275. query = receivePacket(timeout);
  276. } catch (const SignalInterruptOnSelect) {
  277. // Packet reception interrupted because a signal has been received.
  278. // This is not an error because we might have received a SIGTERM,
  279. // SIGINT or SIGHUP which are handled by the server. For signals
  280. // that are not handled by the server we rely on the default
  281. // behavior of the system, but there is nothing we should log here.
  282. } catch (const std::exception& e) {
  283. // Log all other errors.
  284. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_RECEIVE_FAIL).arg(e.what());
  285. }
  286. // Handle next signal received by the process. It must be called after
  287. // an attempt to receive a packet to properly handle server shut down.
  288. // The SIGTERM or SIGINT will be received prior to, or during execution
  289. // of select() (select is invoked by receivePacket()). When that
  290. // happens, select will be interrupted. The signal handler will be
  291. // invoked immediately after select(). The handler will set the
  292. // shutdown flag and cause the process to terminate before the next
  293. // select() function is called. If the function was called before
  294. // receivePacket the process could wait up to the duration of timeout
  295. // of select() to terminate.
  296. handleSignal();
  297. // Execute ready timers for the lease database, e.g. Lease File Cleanup.
  298. try {
  299. LeaseMgrFactory::instance().getIOService()->poll();
  300. } catch (const std::exception& ex) {
  301. LOG_WARN(dhcp4_logger, DHCP4_LEASE_DATABASE_TIMERS_EXEC_FAIL)
  302. .arg(ex.what());
  303. }
  304. // Timeout may be reached or signal received, which breaks select()
  305. // with no reception occurred
  306. if (!query) {
  307. continue;
  308. }
  309. // In order to parse the DHCP options, the server needs to use some
  310. // configuration information such as: existing option spaces, option
  311. // definitions etc. This is the kind of information which is not
  312. // available in the libdhcp, so we need to supply our own implementation
  313. // of the option parsing function here, which would rely on the
  314. // configuration data.
  315. query->setCallback(boost::bind(&Dhcpv4Srv::unpackOptions, this,
  316. _1, _2, _3));
  317. bool skip_unpack = false;
  318. // The packet has just been received so contains the uninterpreted wire
  319. // data; execute callouts registered for buffer4_receive.
  320. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
  321. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  322. // Delete previously set arguments
  323. callout_handle->deleteAllArguments();
  324. // Pass incoming packet as argument
  325. callout_handle->setArgument("query4", query);
  326. // Call callouts
  327. HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_,
  328. *callout_handle);
  329. // Callouts decided to skip the next processing step. The next
  330. // processing step would to parse the packet, so skip at this
  331. // stage means that callouts did the parsing already, so server
  332. // should skip parsing.
  333. if (callout_handle->getSkip()) {
  334. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_BUFFER_RCVD_SKIP);
  335. skip_unpack = true;
  336. }
  337. callout_handle->getArgument("query4", query);
  338. }
  339. // Unpack the packet information unless the buffer4_receive callouts
  340. // indicated they did it
  341. if (!skip_unpack) {
  342. try {
  343. query->unpack();
  344. } catch (const std::exception& e) {
  345. // Failed to parse the packet.
  346. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL,
  347. DHCP4_PACKET_DROP_0001)
  348. .arg(query->getLabel()).arg(e.what());
  349. continue;
  350. }
  351. }
  352. // Assign this packet to one or more classes if needed. We need to do
  353. // this before calling accept(), because getSubnet4() may need client
  354. // class information.
  355. classifyPacket(query);
  356. // Check whether the message should be further processed or discarded.
  357. // There is no need to log anything here. This function logs by itself.
  358. if (!accept(query)) {
  359. continue;
  360. }
  361. // We have sanity checked (in accept() that the Message Type option
  362. // exists, so we can safely get it here.
  363. int type = query->getType();
  364. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_RECEIVED)
  365. .arg(serverReceivedPacketName(type))
  366. .arg(type)
  367. .arg(query->getIface());
  368. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUERY_DATA)
  369. .arg(type)
  370. .arg(query->toText());
  371. // Let's execute all callouts registered for pkt4_receive
  372. if (HooksManager::calloutsPresent(hook_index_pkt4_receive_)) {
  373. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  374. // Delete previously set arguments
  375. callout_handle->deleteAllArguments();
  376. // Pass incoming packet as argument
  377. callout_handle->setArgument("query4", query);
  378. // Call callouts
  379. HooksManager::callCallouts(hook_index_pkt4_receive_,
  380. *callout_handle);
  381. // Callouts decided to skip the next processing step. The next
  382. // processing step would to process the packet, so skip at this
  383. // stage means drop.
  384. if (callout_handle->getSkip()) {
  385. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_RCVD_SKIP);
  386. continue;
  387. }
  388. callout_handle->getArgument("query4", query);
  389. }
  390. try {
  391. switch (query->getType()) {
  392. case DHCPDISCOVER:
  393. rsp = processDiscover(query);
  394. break;
  395. case DHCPREQUEST:
  396. // Note that REQUEST is used for many things in DHCPv4: for
  397. // requesting new leases, renewing existing ones and even
  398. // for rebinding.
  399. rsp = processRequest(query);
  400. break;
  401. case DHCPRELEASE:
  402. processRelease(query);
  403. break;
  404. case DHCPDECLINE:
  405. processDecline(query);
  406. break;
  407. case DHCPINFORM:
  408. rsp = processInform(query);
  409. break;
  410. default:
  411. // Only action is to output a message if debug is enabled,
  412. // and that is covered by the debug statement before the
  413. // "switch" statement.
  414. ;
  415. }
  416. } catch (const isc::Exception& e) {
  417. // Catch-all exception (at least for ones based on the isc Exception
  418. // class, which covers more or less all that are explicitly raised
  419. // in the Kea code). Just log the problem and ignore the packet.
  420. // (The problem is logged as a debug message because debug is
  421. // disabled by default - it prevents a DDOS attack based on the
  422. // sending of problem packets.)
  423. if (dhcp4_logger.isDebugEnabled(DBG_DHCP4_BASIC)) {
  424. std::string source = "unknown";
  425. HWAddrPtr hwptr = query->getHWAddr();
  426. if (hwptr) {
  427. source = hwptr->toText();
  428. }
  429. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_BASIC,
  430. DHCP4_PACKET_DROP_0007)
  431. .arg(query->getLabel())
  432. .arg(e.what());
  433. }
  434. }
  435. if (!rsp) {
  436. continue;
  437. }
  438. // Specifies if server should do the packing
  439. bool skip_pack = false;
  440. // Execute all callouts registered for pkt4_send
  441. if (HooksManager::calloutsPresent(hook_index_pkt4_send_)) {
  442. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  443. // Delete all previous arguments
  444. callout_handle->deleteAllArguments();
  445. // Clear skip flag if it was set in previous callouts
  446. callout_handle->setSkip(false);
  447. // Set our response
  448. callout_handle->setArgument("response4", rsp);
  449. // Call all installed callouts
  450. HooksManager::callCallouts(hook_index_pkt4_send_,
  451. *callout_handle);
  452. // Callouts decided to skip the next processing step. The next
  453. // processing step would to send the packet, so skip at this
  454. // stage means "drop response".
  455. if (callout_handle->getSkip()) {
  456. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_SEND_SKIP);
  457. skip_pack = true;
  458. }
  459. }
  460. if (!skip_pack) {
  461. try {
  462. rsp->pack();
  463. } catch (const std::exception& e) {
  464. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL)
  465. .arg(e.what());
  466. }
  467. }
  468. try {
  469. // Now all fields and options are constructed into output wire buffer.
  470. // Option objects modification does not make sense anymore. Hooks
  471. // can only manipulate wire buffer at this stage.
  472. // Let's execute all callouts registered for buffer4_send
  473. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_send_)) {
  474. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  475. // Delete previously set arguments
  476. callout_handle->deleteAllArguments();
  477. // Pass incoming packet as argument
  478. callout_handle->setArgument("response4", rsp);
  479. // Call callouts
  480. HooksManager::callCallouts(Hooks.hook_index_buffer4_send_,
  481. *callout_handle);
  482. // Callouts decided to skip the next processing step. The next
  483. // processing step would to parse the packet, so skip at this
  484. // stage means drop.
  485. if (callout_handle->getSkip()) {
  486. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS,
  487. DHCP4_HOOK_BUFFER_SEND_SKIP);
  488. continue;
  489. }
  490. callout_handle->getArgument("response4", rsp);
  491. }
  492. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA,
  493. DHCP4_RESPONSE_DATA)
  494. .arg(static_cast<int>(rsp->getType())).arg(rsp->toText());
  495. sendPacket(rsp);
  496. } catch (const std::exception& e) {
  497. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL)
  498. .arg(e.what());
  499. }
  500. }
  501. return (true);
  502. }
  503. string
  504. Dhcpv4Srv::srvidToString(const OptionPtr& srvid) {
  505. if (!srvid) {
  506. isc_throw(BadValue, "NULL pointer passed to srvidToString()");
  507. }
  508. boost::shared_ptr<Option4AddrLst> generated =
  509. boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
  510. if (!srvid) {
  511. isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
  512. }
  513. Option4AddrLst::AddressContainer addrs = generated->getAddresses();
  514. if (addrs.size() != 1) {
  515. isc_throw(BadValue, "Malformed option passed to srvidToString(). "
  516. << "Expected to contain a single IPv4 address.");
  517. }
  518. return (addrs[0].toText());
  519. }
  520. isc::dhcp_ddns::D2Dhcid
  521. Dhcpv4Srv::computeDhcid(const Lease4Ptr& lease) {
  522. if (!lease) {
  523. isc_throw(DhcidComputeError, "a pointer to the lease must be not"
  524. " NULL to compute DHCID");
  525. } else if (lease->hostname_.empty()) {
  526. isc_throw(DhcidComputeError, "unable to compute the DHCID for the"
  527. " lease which has empty hostname set");
  528. }
  529. // In order to compute DHCID the client's hostname must be encoded in
  530. // canonical wire format. It is unlikely that the FQDN is malformed
  531. // because it is validated by the classes which encapsulate options
  532. // carrying client FQDN. However, if the client name was carried in the
  533. // Hostname option it is more likely as it carries the hostname as a
  534. // regular string.
  535. std::vector<uint8_t> fqdn_wire;
  536. try {
  537. OptionDataTypeUtil::writeFqdn(lease->hostname_, fqdn_wire, true);
  538. } catch (const Exception& ex) {
  539. isc_throw(DhcidComputeError, "unable to compute DHCID because the"
  540. " hostname: " << lease->hostname_ << " is invalid");
  541. }
  542. // Prefer client id to HW address to compute DHCID. If Client Id is
  543. // NULL, use HW address.
  544. try {
  545. if (lease->client_id_) {
  546. return (D2Dhcid(lease->client_id_->getClientId(), fqdn_wire));
  547. } else {
  548. return (D2Dhcid(lease->hwaddr_, fqdn_wire));
  549. }
  550. } catch (const Exception& ex) {
  551. isc_throw(DhcidComputeError, "unable to compute DHCID: "
  552. << ex.what());
  553. }
  554. }
  555. void
  556. Dhcpv4Srv::appendServerID(Dhcpv4Exchange& ex) {
  557. // The source address for the outbound message should have been set already.
  558. // This is the address that to the best of the server's knowledge will be
  559. // available from the client.
  560. /// @todo: perhaps we should consider some more sophisticated server id
  561. /// generation, but for the current use cases, it should be ok.
  562. OptionPtr opt_srvid(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER,
  563. ex.getResponse()->getLocalAddr()));
  564. ex.getResponse()->addOption(opt_srvid);
  565. }
  566. void
  567. Dhcpv4Srv::appendRequestedOptions(Dhcpv4Exchange& ex) {
  568. // Get the subnet relevant for the client. We will need it
  569. // to get the options associated with it.
  570. Subnet4Ptr subnet = ex.getContext()->subnet_;
  571. // If we can't find the subnet for the client there is no way
  572. // to get the options to be sent to a client. We don't log an
  573. // error because it will be logged by the assignLease method
  574. // anyway.
  575. if (!subnet) {
  576. return;
  577. }
  578. Pkt4Ptr query = ex.getQuery();
  579. // try to get the 'Parameter Request List' option which holds the
  580. // codes of requested options.
  581. OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
  582. OptionUint8Array>(query->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  583. // If there is no PRL option in the message from the client then
  584. // there is nothing to do.
  585. if (!option_prl) {
  586. return;
  587. }
  588. Pkt4Ptr resp = ex.getResponse();
  589. // Get the codes of requested options.
  590. const std::vector<uint8_t>& requested_opts = option_prl->getValues();
  591. // For each requested option code get the instance of the option
  592. // to be returned to the client.
  593. for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
  594. opt != requested_opts.end(); ++opt) {
  595. if (!resp->getOption(*opt)) {
  596. OptionDescriptor desc = subnet->getCfgOption()->get("dhcp4", *opt);
  597. if (desc.option_) {
  598. resp->addOption(desc.option_);
  599. }
  600. }
  601. }
  602. }
  603. void
  604. Dhcpv4Srv::appendRequestedVendorOptions(Dhcpv4Exchange& ex) {
  605. // Get the configured subnet suitable for the incoming packet.
  606. Subnet4Ptr subnet = ex.getContext()->subnet_;
  607. // Leave if there is no subnet matching the incoming packet.
  608. // There is no need to log the error message here because
  609. // it will be logged in the assignLease() when it fails to
  610. // pick the suitable subnet. We don't want to duplicate
  611. // error messages in such case.
  612. if (!subnet) {
  613. return;
  614. }
  615. // Try to get the vendor option
  616. boost::shared_ptr<OptionVendor> vendor_req = boost::dynamic_pointer_cast<
  617. OptionVendor>(ex.getQuery()->getOption(DHO_VIVSO_SUBOPTIONS));
  618. if (!vendor_req) {
  619. return;
  620. }
  621. uint32_t vendor_id = vendor_req->getVendorId();
  622. // Let's try to get ORO within that vendor-option
  623. /// @todo This is very specific to vendor-id=4491 (Cable Labs). Other
  624. /// vendors may have different policies.
  625. OptionUint8ArrayPtr oro =
  626. boost::dynamic_pointer_cast<OptionUint8Array>(vendor_req->getOption(DOCSIS3_V4_ORO));
  627. // Option ORO not found. Don't do anything then.
  628. if (!oro) {
  629. return;
  630. }
  631. boost::shared_ptr<OptionVendor> vendor_rsp(new OptionVendor(Option::V4, vendor_id));
  632. // Get the list of options that client requested.
  633. bool added = false;
  634. const std::vector<uint8_t>& requested_opts = oro->getValues();
  635. for (std::vector<uint8_t>::const_iterator code = requested_opts.begin();
  636. code != requested_opts.end(); ++code) {
  637. if (!vendor_rsp->getOption(*code)) {
  638. OptionDescriptor desc = subnet->getCfgOption()->get(vendor_id,
  639. *code);
  640. if (desc.option_) {
  641. vendor_rsp->addOption(desc.option_);
  642. added = true;
  643. }
  644. }
  645. if (added) {
  646. ex.getResponse()->addOption(vendor_rsp);
  647. }
  648. }
  649. }
  650. void
  651. Dhcpv4Srv::appendBasicOptions(Dhcpv4Exchange& ex) {
  652. // Identify options that we always want to send to the
  653. // client (if they are configured).
  654. static const uint16_t required_options[] = {
  655. DHO_ROUTERS,
  656. DHO_DOMAIN_NAME_SERVERS,
  657. DHO_DOMAIN_NAME };
  658. static size_t required_options_size =
  659. sizeof(required_options) / sizeof(required_options[0]);
  660. // Get the subnet.
  661. Subnet4Ptr subnet = ex.getContext()->subnet_;
  662. if (!subnet) {
  663. return;
  664. }
  665. Pkt4Ptr resp = ex.getResponse();
  666. // Try to find all 'required' options in the outgoing
  667. // message. Those that are not present will be added.
  668. for (int i = 0; i < required_options_size; ++i) {
  669. OptionPtr opt = resp->getOption(required_options[i]);
  670. if (!opt) {
  671. // Check whether option has been configured.
  672. OptionDescriptor desc = subnet->getCfgOption()->
  673. get("dhcp4", required_options[i]);
  674. if (desc.option_) {
  675. resp->addOption(desc.option_);
  676. }
  677. }
  678. }
  679. }
  680. void
  681. Dhcpv4Srv::processClientName(Dhcpv4Exchange& ex) {
  682. // It is possible that client has sent both Client FQDN and Hostname
  683. // option. In such case, server should prefer Client FQDN option and
  684. // ignore the Hostname option.
  685. try {
  686. Pkt4Ptr resp = ex.getResponse();
  687. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
  688. (ex.getQuery()->getOption(DHO_FQDN));
  689. if (fqdn) {
  690. processClientFqdnOption(ex);
  691. } else {
  692. OptionStringPtr hostname = boost::dynamic_pointer_cast<OptionString>
  693. (ex.getQuery()->getOption(DHO_HOST_NAME));
  694. if (hostname) {
  695. processHostnameOption(ex);
  696. }
  697. }
  698. } catch (const Exception& ex) {
  699. // In some rare cases it is possible that the client's name processing
  700. // fails. For example, the Hostname option may be malformed, or there
  701. // may be an error in the server's logic which would cause multiple
  702. // attempts to add the same option to the response message. This
  703. // error message aggregates all these errors so they can be diagnosed
  704. // from the log. We don't want to throw an exception here because,
  705. // it will impact the processing of the whole packet. We rather want
  706. // the processing to continue, even if the client's name is wrong.
  707. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_NAME_PROC_FAIL)
  708. .arg(ex.what());
  709. }
  710. }
  711. void
  712. Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
  713. // Obtain the FQDN option from the client's message.
  714. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  715. Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
  716. // Create the DHCPv4 Client FQDN Option to be included in the server's
  717. // response to a client.
  718. Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
  719. // Set the server S, N, and O flags based on client's flags and
  720. // current configuration.
  721. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  722. d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  723. // Carry over the client's E flag.
  724. fqdn_resp->setFlag(Option4ClientFqdn::FLAG_E,
  725. fqdn->getFlag(Option4ClientFqdn::FLAG_E));
  726. if (ex.getContext()->host_ && !ex.getContext()->host_->getHostname().empty()) {
  727. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  728. fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->host_->getHostname(),
  729. true), Option4ClientFqdn::FULL);
  730. } else {
  731. // Adjust the domain name based on domain name value and type sent by the
  732. // client and current configuration.
  733. d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  734. }
  735. // Add FQDN option to the response message. Note that, there may be some
  736. // cases when server may choose not to include the FQDN option in a
  737. // response to a client. In such cases, the FQDN should be removed from the
  738. // outgoing message. In theory we could cease to include the FQDN option
  739. // in this function until it is confirmed that it should be included.
  740. // However, we include it here for simplicity. Functions used to acquire
  741. // lease for a client will scan the response message for FQDN and if it
  742. // is found they will take necessary actions to store the FQDN information
  743. // in the lease database as well as to generate NameChangeRequests to DNS.
  744. // If we don't store the option in the response message, we will have to
  745. // propagate it in the different way to the functions which acquire the
  746. // lease. This would require modifications to the API of this class.
  747. ex.getResponse()->addOption(fqdn_resp);
  748. }
  749. void
  750. Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
  751. // Obtain the Hostname option from the client's message.
  752. OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
  753. (ex.getQuery()->getOption(DHO_HOST_NAME));
  754. // Fetch D2 configuration.
  755. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  756. // Do nothing if the DNS updates are disabled.
  757. if (!d2_mgr.ddnsEnabled()) {
  758. return;
  759. }
  760. std::string hostname = isc::util::str::trim(opt_hostname->getValue());
  761. unsigned int label_count = OptionDataTypeUtil::getLabelCount(hostname);
  762. // The hostname option sent by the client should be at least 1 octet long.
  763. // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
  764. /// @todo It would be more liberal to accept this and let it fall into
  765. /// the case of replace or less than two below.
  766. if (label_count == 0) {
  767. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_EMPTY_HOSTNAME);
  768. return;
  769. }
  770. // Copy construct the hostname provided by the client. It is entirely
  771. // possible that we will use the hostname option provided by the client
  772. // to perform the DNS update and we will send the same option to him to
  773. // indicate that we accepted this hostname.
  774. OptionStringPtr opt_hostname_resp(new OptionString(*opt_hostname));
  775. // The hostname option may be unqualified or fully qualified. The lab_count
  776. // holds the number of labels for the name. The number of 1 means that
  777. // there is only root label "." (even for unqualified names, as the
  778. // getLabelCount function treats each name as a fully qualified one).
  779. // By checking the number of labels present in the hostname we may infer
  780. // whether client has sent the fully qualified or unqualified hostname.
  781. // If there is a hostname reservation for this client, use it.
  782. if (ex.getContext()->host_ && !ex.getContext()->host_->getHostname().empty()) {
  783. opt_hostname_resp->setValue(d2_mgr.qualifyName(ex.getContext()->host_->getHostname(),
  784. false));
  785. } else if ((d2_mgr.getD2ClientConfig()->getReplaceClientName()) ||
  786. (label_count < 2)) {
  787. // Set to root domain to signal later on that we should replace it.
  788. // DHO_HOST_NAME is a string option which cannot be empty.
  789. /// @todo We may want to reconsider whether it is appropriate for the
  790. /// client to send a root domain name as a Hostname. There are
  791. /// also extensions to the auto generation of the client's name,
  792. /// e.g. conversion to the puny code which may be considered at some point.
  793. /// For now, we just remain liberal and expect that the DNS will handle
  794. /// conversion if needed and possible.
  795. opt_hostname_resp->setValue(".");
  796. } else if (label_count == 2) {
  797. // If there are two labels, it means that the client has specified
  798. // the unqualified name. We have to concatenate the unqualified name
  799. // with the domain name. The false value passed as a second argument
  800. // indicates that the trailing dot should not be appended to the
  801. // hostname. We don't want to append the trailing dot because
  802. // we don't know whether the hostname is partial or not and some
  803. // clients do not handle the hostnames with the trailing dot.
  804. opt_hostname_resp->setValue(d2_mgr.qualifyName(hostname, false));
  805. }
  806. ex.getResponse()->addOption(opt_hostname_resp);
  807. }
  808. void
  809. Dhcpv4Srv::createNameChangeRequests(const Lease4Ptr& lease,
  810. const Lease4Ptr& old_lease) {
  811. if (!lease) {
  812. isc_throw(isc::Unexpected,
  813. "NULL lease specified when creating NameChangeRequest");
  814. }
  815. // If old lease is not NULL, it is an indication that the lease has
  816. // just been renewed. In such case we may need to generate the
  817. // additional NameChangeRequest to remove an existing entry before
  818. // we create a NameChangeRequest to add the entry for an updated lease.
  819. // We may also decide not to generate any requests at all. This is when
  820. // we discover that nothing has changed in the client's FQDN data.
  821. if (old_lease) {
  822. if (!lease->matches(*old_lease)) {
  823. isc_throw(isc::Unexpected,
  824. "there is no match between the current instance of the"
  825. " lease: " << lease->toText() << ", and the previous"
  826. " instance: " << lease->toText());
  827. } else {
  828. // There will be a NameChangeRequest generated to remove existing
  829. // DNS entries if the following conditions are met:
  830. // - The hostname is set for the existing lease, we can't generate
  831. // removal request for non-existent hostname.
  832. // - A server has performed reverse, forward or both updates.
  833. // - FQDN data between the new and old lease do not match.
  834. if (!lease->hasIdenticalFqdn(*old_lease)) {
  835. queueNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE,
  836. old_lease);
  837. // If FQDN data from both leases match, there is no need to update.
  838. } else if (lease->hasIdenticalFqdn(*old_lease)) {
  839. return;
  840. }
  841. }
  842. }
  843. // We may need to generate the NameChangeRequest for the new lease. It
  844. // will be generated only if hostname is set and if forward or reverse
  845. // update has been requested.
  846. queueNameChangeRequest(isc::dhcp_ddns::CHG_ADD, lease);
  847. }
  848. void
  849. Dhcpv4Srv::
  850. queueNameChangeRequest(const isc::dhcp_ddns::NameChangeType chg_type,
  851. const Lease4Ptr& lease) {
  852. // The hostname must not be empty, and at least one type of update
  853. // should be requested.
  854. if (!lease || lease->hostname_.empty() ||
  855. (!lease->fqdn_rev_ && !lease->fqdn_fwd_)) {
  856. return;
  857. }
  858. // Create the DHCID for the NameChangeRequest.
  859. D2Dhcid dhcid;
  860. try {
  861. dhcid = computeDhcid(lease);
  862. } catch (const DhcidComputeError& ex) {
  863. LOG_ERROR(dhcp4_logger, DHCP4_DHCID_COMPUTE_ERROR)
  864. .arg(lease->toText())
  865. .arg(ex.what());
  866. return;
  867. }
  868. // Create NameChangeRequest
  869. NameChangeRequestPtr ncr(new NameChangeRequest(chg_type, lease->fqdn_fwd_,
  870. lease->fqdn_rev_,
  871. lease->hostname_,
  872. lease->addr_.toText(),
  873. dhcid,
  874. (lease->cltt_ +
  875. lease->valid_lft_),
  876. lease->valid_lft_));
  877. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUEUE_NCR)
  878. .arg(chg_type == CHG_ADD ? "add" : "remove")
  879. .arg(ncr->toText());
  880. // And pass it to the the manager.
  881. CfgMgr::instance().getD2ClientMgr().sendRequest(ncr);
  882. }
  883. void
  884. Dhcpv4Srv::assignLease(Dhcpv4Exchange& ex) {
  885. // Get the pointers to the query and the response messages.
  886. Pkt4Ptr query = ex.getQuery();
  887. Pkt4Ptr resp = ex.getResponse();
  888. // Get the context.
  889. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  890. // Subnet should have been already selected when the context was created.
  891. Subnet4Ptr subnet = ctx->subnet_;
  892. if (!subnet) {
  893. // This particular client is out of luck today. We do not have
  894. // information about the subnet he is connected to. This likely means
  895. // misconfiguration of the server (or some relays). We will continue to
  896. // process this message, but our response will be almost useless: no
  897. // addresses or prefixes, no subnet specific configuration etc. The only
  898. // thing this client can get is some global information (like DNS
  899. // servers).
  900. // perhaps this should be logged on some higher level? This is most
  901. // likely configuration bug.
  902. LOG_ERROR(bad_packet_logger, DHCP4_PACKET_NAK_0001)
  903. .arg(query->getLabel())
  904. .arg(query->getRemoteAddr().toText())
  905. .arg(serverReceivedPacketName(query->getType()));
  906. resp->setType(DHCPNAK);
  907. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  908. return;
  909. }
  910. // Set up siaddr. Perhaps assignLease is not the best place to call this
  911. // as siaddr has nothing to do with a lease, but otherwise we would have
  912. // to select subnet twice (performance hit) or update too many functions
  913. // at once.
  914. /// @todo: move subnet selection to a common code
  915. resp->setSiaddr(subnet->getSiaddr());
  916. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_SELECTED)
  917. .arg(subnet->toText());
  918. // Get client-id. It is not mandatory in DHCPv4.
  919. ClientIdPtr client_id = ex.getContext()->clientid_;
  920. // Get the server identifier. It will be used to determine the state
  921. // of the client.
  922. OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
  923. OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  924. // Check if the client has sent a requested IP address option or
  925. // ciaddr.
  926. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  927. OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  928. IOAddress hint(0);
  929. if (opt_requested_address) {
  930. hint = opt_requested_address->readAddress();
  931. } else if (!query->getCiaddr().isV4Zero()) {
  932. hint = query->getCiaddr();
  933. }
  934. HWAddrPtr hwaddr = query->getHWAddr();
  935. // "Fake" allocation is processing of DISCOVER message. We pretend to do an
  936. // allocation, but we do not put the lease in the database. That is ok,
  937. // because we do not guarantee that the user will get that exact lease. If
  938. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  939. // it should include this hint. That will help us during the actual lease
  940. // allocation.
  941. bool fake_allocation = (query->getType() == DHCPDISCOVER);
  942. // If there is no server id and there is a Requested IP Address option
  943. // the client is in the INIT-REBOOT state in which the server has to
  944. // determine whether the client's notion of the address is correct
  945. // and whether the client is known, i.e., has a lease.
  946. if (!fake_allocation && !opt_serverid && opt_requested_address) {
  947. Lease4Ptr lease;
  948. if (hwaddr) {
  949. lease = LeaseMgrFactory::instance().getLease4(*hwaddr,
  950. subnet->getID());
  951. }
  952. if (!lease && client_id) {
  953. lease = LeaseMgrFactory::instance().getLease4(*client_id,
  954. subnet->getID());
  955. }
  956. // Got a lease so we can check the address.
  957. if (lease && (lease->addr_ != hint)) {
  958. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL,
  959. DHCP4_PACKET_NAK_0002)
  960. .arg(query->getLabel())
  961. .arg(hint.toText());
  962. resp->setType(DHCPNAK);
  963. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  964. return;
  965. }
  966. // Now check the second error case: unknown client.
  967. if (!lease) {
  968. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  969. DHCP4_NO_LEASE_INIT_REBOOT)
  970. .arg(hint.toText())
  971. .arg(client_id ? client_id->toText():"(no client-id)")
  972. .arg(hwaddr ? hwaddr->toText():"(no hwaddr info)");
  973. ex.deleteResponse();
  974. return;
  975. }
  976. }
  977. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  978. std::string hostname;
  979. bool fqdn_fwd = false;
  980. bool fqdn_rev = false;
  981. OptionStringPtr opt_hostname;
  982. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  983. Option4ClientFqdn>(resp->getOption(DHO_FQDN));
  984. if (fqdn) {
  985. hostname = fqdn->getDomainName();
  986. CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn,
  987. fqdn_fwd,
  988. fqdn_rev);
  989. } else {
  990. opt_hostname = boost::dynamic_pointer_cast<OptionString>
  991. (resp->getOption(DHO_HOST_NAME));
  992. if (opt_hostname) {
  993. hostname = opt_hostname->getValue();
  994. // DHO_HOST_NAME is string option which cannot be blank,
  995. // we use "." to know we should replace it with a fully
  996. // generated name. The local string variable needs to be
  997. // blank in logic below.
  998. if (hostname == ".") {
  999. hostname = "";
  1000. }
  1001. /// @todo It could be configurable what sort of updates the
  1002. /// server is doing when Hostname option was sent.
  1003. fqdn_fwd = true;
  1004. fqdn_rev = true;
  1005. }
  1006. }
  1007. // We need to set these values in the context as they haven't been set yet.
  1008. ctx->requested_address_ = hint;
  1009. ctx->fwd_dns_update_ = fqdn_fwd;
  1010. ctx->rev_dns_update_ = fqdn_rev;
  1011. ctx->hostname_ = hostname;
  1012. ctx->fake_allocation_ = fake_allocation;
  1013. ctx->callout_handle_ = callout_handle;
  1014. Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
  1015. if (lease) {
  1016. // We have a lease! Let's set it in the packet and send it back to
  1017. // the client.
  1018. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
  1019. DHCP4_LEASE_ADVERT:DHCP4_LEASE_ALLOC)
  1020. .arg(lease->addr_.toText())
  1021. .arg(client_id?client_id->toText():"(no client-id)")
  1022. .arg(hwaddr?hwaddr->toText():"(no hwaddr info)");
  1023. resp->setYiaddr(lease->addr_);
  1024. /// @todo The server should check what ciaddr the client has supplied
  1025. /// in ciaddr. Currently the ciaddr is ignored except for the subnet
  1026. /// selection. If the client supplied an invalid address, the server
  1027. /// will also return an invalid address here.
  1028. if (!fake_allocation) {
  1029. // If this is a renewing client it will set a ciaddr which the
  1030. // server may include in the response. If this is a new allocation
  1031. // the client will set ciaddr to 0 and this will also be propagated
  1032. // to the server's resp.
  1033. resp->setCiaddr(query->getCiaddr());
  1034. }
  1035. // If there has been Client FQDN or Hostname option sent, but the
  1036. // hostname is empty, it means that server is responsible for
  1037. // generating the entire hostname for the client. The example of the
  1038. // client's name, generated from the IP address is: host-192-0-2-3.
  1039. if ((fqdn || opt_hostname) && lease->hostname_.empty()) {
  1040. // Note that if we have received the hostname option, rather than
  1041. // Client FQDN the trailing dot is not appended to the generated
  1042. // hostname because some clients don't handle the trailing dot in
  1043. // the hostname. Whether the trailing dot is appended or not is
  1044. // controlled by the second argument to the generateFqdn().
  1045. lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
  1046. .generateFqdn(lease->addr_, static_cast<bool>(fqdn));
  1047. // The operations below are rather safe, but we want to catch
  1048. // any potential exceptions (e.g. invalid lease database backend
  1049. // implementation) and log an error.
  1050. try {
  1051. // The lease update should be safe, because the lease should
  1052. // be already in the database. In most cases the exception
  1053. // would be thrown if the lease was missing.
  1054. LeaseMgrFactory::instance().updateLease4(lease);
  1055. // The name update in the option should be also safe,
  1056. // because the generated name is well formed.
  1057. if (fqdn) {
  1058. fqdn->setDomainName(lease->hostname_,
  1059. Option4ClientFqdn::FULL);
  1060. } else if (opt_hostname) {
  1061. opt_hostname->setValue(lease->hostname_);
  1062. }
  1063. } catch (const Exception& ex) {
  1064. LOG_ERROR(dhcp4_logger, DHCP4_NAME_GEN_UPDATE_FAIL)
  1065. .arg(ex.what());
  1066. }
  1067. }
  1068. // IP Address Lease time (type 51)
  1069. OptionPtr opt(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME,
  1070. lease->valid_lft_));
  1071. resp->addOption(opt);
  1072. // Subnet mask (type 1)
  1073. resp->addOption(getNetmaskOption(subnet));
  1074. // renewal-timer (type 58)
  1075. if (!subnet->getT1().unspecified()) {
  1076. OptionUint32Ptr t1(new OptionUint32(Option::V4,
  1077. DHO_DHCP_RENEWAL_TIME,
  1078. subnet->getT1()));
  1079. resp->addOption(t1);
  1080. }
  1081. // rebind timer (type 59)
  1082. if (!subnet->getT2().unspecified()) {
  1083. OptionUint32Ptr t2(new OptionUint32(Option::V4,
  1084. DHO_DHCP_REBINDING_TIME,
  1085. subnet->getT2()));
  1086. resp->addOption(t2);
  1087. }
  1088. // Create NameChangeRequests if DDNS is enabled and this is a
  1089. // real allocation.
  1090. if (!fake_allocation && CfgMgr::instance().ddnsEnabled()) {
  1091. try {
  1092. createNameChangeRequests(lease, ctx->old_lease_);
  1093. } catch (const Exception& ex) {
  1094. LOG_ERROR(dhcp4_logger, DHCP4_NCR_CREATION_FAILED)
  1095. .arg(ex.what());
  1096. }
  1097. }
  1098. } else {
  1099. // Allocation engine did not allocate a lease. The engine logged
  1100. // cause of that failure. The only thing left is to insert
  1101. // status code to pass the sad news to the client.
  1102. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation ?
  1103. DHCP4_PACKET_NAK_0003 : DHCP4_PACKET_NAK_0004)
  1104. .arg(query->getLabel())
  1105. .arg(query->getCiaddr().toText())
  1106. .arg(opt_requested_address ?
  1107. opt_requested_address->readAddress().toText() : "(no address)");
  1108. resp->setType(DHCPNAK);
  1109. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1110. resp->delOption(DHO_FQDN);
  1111. resp->delOption(DHO_HOST_NAME);
  1112. }
  1113. }
  1114. void
  1115. Dhcpv4Srv::adjustIfaceData(Dhcpv4Exchange& ex) {
  1116. adjustRemoteAddr(ex);
  1117. // Initialize the pointers to the client's message and the server's
  1118. // response.
  1119. Pkt4Ptr query = ex.getQuery();
  1120. Pkt4Ptr response = ex.getResponse();
  1121. // For the non-relayed message, the destination port is the client's port.
  1122. // For the relayed message, the server/relay port is a destination.
  1123. // Note that the call to this function may throw if invalid combination
  1124. // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
  1125. // giaddr != 0). The exception will propagate down and eventually cause the
  1126. // packet to be discarded.
  1127. response->setRemotePort(query->isRelayed() ? DHCP4_SERVER_PORT :
  1128. DHCP4_CLIENT_PORT);
  1129. IOAddress local_addr = query->getLocalAddr();
  1130. // In many cases the query is sent to a broadcast address. This address
  1131. // apears as a local address in the query message. We can't simply copy
  1132. // this address to a response message and use it as a source address.
  1133. // Instead we will need to use the address assigned to the interface
  1134. // on which the query has been received. In other cases, we will just
  1135. // use this address as a source address for the response.
  1136. if (local_addr == IOAddress::IPV4_BCAST_ADDRESS()) {
  1137. SocketInfo sock_info = IfaceMgr::instance().getSocket(*query);
  1138. local_addr = sock_info.addr_;
  1139. }
  1140. // We assume that there is an appropriate socket bound to this address
  1141. // and that the address is correct. This is safe assumption because
  1142. // the local address of the query is set when the query is received.
  1143. // The query sent to an incorrect address wouldn't have been received.
  1144. // However, if socket is closed for this address between the reception
  1145. // of the query and sending a response, the IfaceMgr should detect it
  1146. // and return an error.
  1147. response->setLocalAddr(local_addr);
  1148. // In many cases the query is sent to a broadcast address. This address
  1149. // appears as a local address in the query message. Therefore we can't
  1150. // simply copy local address from the query and use it as a source
  1151. // address for the response. Instead, we have to check what address our
  1152. // socket is bound to and use it as a source address. This operation
  1153. // may throw if for some reason the socket is closed.
  1154. /// @todo Consider an optimization that we use local address from
  1155. /// the query if this address is not broadcast.
  1156. response->setLocalPort(DHCP4_SERVER_PORT);
  1157. response->setIface(query->getIface());
  1158. response->setIndex(query->getIndex());
  1159. }
  1160. void
  1161. Dhcpv4Srv::adjustRemoteAddr(Dhcpv4Exchange& ex) {
  1162. // Initialize the pointers to the client's message and the server's
  1163. // response.
  1164. Pkt4Ptr query = ex.getQuery();
  1165. Pkt4Ptr response = ex.getResponse();
  1166. // The DHCPINFORM is slightly different than other messages in a sense
  1167. // that the server should always unicast the response to the ciaddr.
  1168. // It appears however that some clients don't set the ciaddr. We still
  1169. // want to provision these clients and we do what we can't to send the
  1170. // packet to the address where client can receive it.
  1171. if (query->getType() == DHCPINFORM) {
  1172. // If client adheres to RFC2131 it will set the ciaddr and in this
  1173. // case we always unicast our response to this address.
  1174. if (query->getCiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1175. response->setRemoteAddr(query->getCiaddr());
  1176. // If we received DHCPINFORM via relay and the ciaddr is not set we
  1177. // will try to send the response via relay. The caveat is that the
  1178. // relay will not have any idea where to forward the packet because
  1179. // the yiaddr is likely not set. So, the broadcast flag is set so
  1180. // as the response may be broadcast.
  1181. } else if (query->isRelayed()) {
  1182. response->setRemoteAddr(query->getGiaddr());
  1183. response->setFlags(response->getFlags() | BOOTP_BROADCAST);
  1184. // If there is no ciaddr and no giaddr the only thing we can do is
  1185. // to use the source address of the packet.
  1186. } else {
  1187. response->setRemoteAddr(query->getRemoteAddr());
  1188. }
  1189. // Remote address is now set so return.
  1190. return;
  1191. }
  1192. // If received relayed message, server responds to the relay address.
  1193. if (query->isRelayed()) {
  1194. // The client should set the ciaddr when sending the DHCPINFORM
  1195. // but in case he didn't, the relay may not be able to determine the
  1196. // address of the client, because yiaddr is not set when responding
  1197. // to Confirm and the only address available was the source address
  1198. // of the client. The source address is however not used here because
  1199. // the message is relayed. Therefore, we set the BROADCAST flag so
  1200. // as the relay can broadcast the packet.
  1201. if ((query->getType() == DHCPINFORM) &&
  1202. (query->getCiaddr() == IOAddress::IPV4_ZERO_ADDRESS())) {
  1203. response->setFlags(BOOTP_BROADCAST);
  1204. }
  1205. response->setRemoteAddr(query->getGiaddr());
  1206. // If giaddr is 0 but client set ciaddr, server should unicast the
  1207. // response to ciaddr.
  1208. } else if (query->getCiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1209. response->setRemoteAddr(query->getCiaddr());
  1210. // We can't unicast the response to the client when sending NAK,
  1211. // because we haven't allocated address for him. Therefore,
  1212. // NAK is broadcast.
  1213. } else if (response->getType() == DHCPNAK) {
  1214. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1215. // If yiaddr is set it means that we have created a lease for a client.
  1216. } else if (response->getYiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1217. // If the broadcast bit is set in the flags field, we have to
  1218. // send the response to broadcast address. Client may have requested it
  1219. // because it doesn't support reception of messages on the interface
  1220. // which doesn't have an address assigned. The other case when response
  1221. // must be broadcasted is when our server does not support responding
  1222. // directly to a client without address assigned.
  1223. const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
  1224. if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
  1225. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1226. // Client cleared the broadcast bit and we support direct responses
  1227. // so we should unicast the response to a newly allocated address -
  1228. // yiaddr.
  1229. } else {
  1230. response->setRemoteAddr(response ->getYiaddr());
  1231. }
  1232. // In most cases, we should have the remote address found already. If we
  1233. // found ourselves at this point, the rational thing to do is to respond
  1234. // to the address we got the query from.
  1235. } else {
  1236. response->setRemoteAddr(query->getRemoteAddr());
  1237. }
  1238. }
  1239. OptionPtr
  1240. Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
  1241. uint32_t netmask = getNetmask4(subnet->get().second);
  1242. OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
  1243. DHO_SUBNET_MASK, netmask));
  1244. return (opt);
  1245. }
  1246. Pkt4Ptr
  1247. Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
  1248. sanityCheck(discover, FORBIDDEN);
  1249. Dhcpv4Exchange ex(alloc_engine_, discover, selectSubnet(discover));
  1250. // If DHCPDISCOVER message contains the FQDN or Hostname option, server
  1251. // may respond to the client with the appropriate FQDN or Hostname
  1252. // option to indicate that whether it will take responsibility for
  1253. // updating DNS when the client sends DHCPREQUEST message.
  1254. processClientName(ex);
  1255. assignLease(ex);
  1256. if (!ex.getResponse()) {
  1257. // The offer is empty so return it *now*!
  1258. return (Pkt4Ptr());
  1259. }
  1260. // Adding any other options makes sense only when we got the lease.
  1261. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1262. appendRequestedOptions(ex);
  1263. appendRequestedVendorOptions(ex);
  1264. // There are a few basic options that we always want to
  1265. // include in the response. If client did not request
  1266. // them we append them for him.
  1267. appendBasicOptions(ex);
  1268. } else {
  1269. // If the server can't offer an address, it drops the packet.
  1270. return (Pkt4Ptr());
  1271. }
  1272. // Set the src/dest IP address, port and interface for the outgoing
  1273. // packet.
  1274. adjustIfaceData(ex);
  1275. appendServerID(ex);
  1276. /// @todo: decide whether we want to add a new hook point for
  1277. /// doing class specific processing.
  1278. if (!classSpecificProcessing(ex)) {
  1279. /// @todo add more verbosity here
  1280. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_DISCOVER_CLASS_PROCESSING_FAILED);
  1281. }
  1282. return (ex.getResponse());
  1283. }
  1284. Pkt4Ptr
  1285. Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
  1286. /// @todo Uncomment this (see ticket #3116)
  1287. /// sanityCheck(request, MANDATORY);
  1288. Dhcpv4Exchange ex(alloc_engine_, request, selectSubnet(request));
  1289. // If DHCPREQUEST message contains the FQDN or Hostname option, server
  1290. // should respond to the client with the appropriate FQDN or Hostname
  1291. // option to indicate if it takes responsibility for the DNS updates.
  1292. // This is performed by the function below.
  1293. processClientName(ex);
  1294. // Note that we treat REQUEST message uniformly, regardless if this is a
  1295. // first request (requesting for new address), renewing existing address
  1296. // or even rebinding.
  1297. assignLease(ex);
  1298. if (!ex.getResponse()) {
  1299. // The ack is empty so return it *now*!
  1300. return (Pkt4Ptr());
  1301. }
  1302. // Adding any other options makes sense only when we got the lease.
  1303. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1304. appendRequestedOptions(ex);
  1305. appendRequestedVendorOptions(ex);
  1306. // There are a few basic options that we always want to
  1307. // include in the response. If client did not request
  1308. // them we append them for him.
  1309. appendBasicOptions(ex);
  1310. }
  1311. // Set the src/dest IP address, port and interface for the outgoing
  1312. // packet.
  1313. adjustIfaceData(ex);
  1314. appendServerID(ex);
  1315. /// @todo: decide whether we want to add a new hook point for
  1316. /// doing class specific processing.
  1317. if (!classSpecificProcessing(ex)) {
  1318. /// @todo add more verbosity here
  1319. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_REQUEST_CLASS_PROCESSING_FAILED);
  1320. }
  1321. return (ex.getResponse());
  1322. }
  1323. void
  1324. Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
  1325. /// @todo Uncomment this (see ticket #3116)
  1326. /// sanityCheck(release, MANDATORY);
  1327. // Try to find client-id
  1328. ClientIdPtr client_id;
  1329. OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1330. if (opt) {
  1331. client_id = ClientIdPtr(new ClientId(opt->getData()));
  1332. }
  1333. try {
  1334. // Do we have a lease for that particular address?
  1335. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
  1336. if (!lease) {
  1337. // No such lease - bogus release
  1338. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  1339. DHCP4_RELEASE_FAIL_NO_LEASE)
  1340. .arg(client_id ? client_id->toText() : "(no client-id)")
  1341. .arg(release->getHWAddr() ?
  1342. release->getHWAddr()->toText() : "(no hwaddr info)")
  1343. .arg(release->getCiaddr().toText());
  1344. return;
  1345. }
  1346. // Does the hardware address match? We don't want one client releasing
  1347. // second client's leases. Note that we're comparing the hardware
  1348. // addresses only, not hardware types or sources of the hardware
  1349. // addresses. Thus we don't use HWAddr::equals().
  1350. if (lease->hwaddr_->hwaddr_ != release->getHWAddr()->hwaddr_) {
  1351. /// @todo: Print hwaddr from lease as part of ticket #2589
  1352. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_HWADDR)
  1353. .arg(release->getCiaddr().toText())
  1354. .arg(client_id ? client_id->toText() : "(no client-id)")
  1355. .arg(release->getHWAddr()->toText());
  1356. return;
  1357. }
  1358. // Does the lease have client-id info? If it has, then check it with what
  1359. // the client sent us.
  1360. if (lease->client_id_ && client_id && *lease->client_id_ != *client_id) {
  1361. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT_ID)
  1362. .arg(release->getCiaddr().toText())
  1363. .arg(client_id->toText())
  1364. .arg(lease->client_id_->toText());
  1365. return;
  1366. }
  1367. bool skip = false;
  1368. // Execute all callouts registered for lease4_release
  1369. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
  1370. CalloutHandlePtr callout_handle = getCalloutHandle(release);
  1371. // Delete all previous arguments
  1372. callout_handle->deleteAllArguments();
  1373. // Pass the original packet
  1374. callout_handle->setArgument("query4", release);
  1375. // Pass the lease to be updated
  1376. callout_handle->setArgument("lease4", lease);
  1377. // Call all installed callouts
  1378. HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
  1379. *callout_handle);
  1380. // Callouts decided to skip the next processing step. The next
  1381. // processing step would to send the packet, so skip at this
  1382. // stage means "drop response".
  1383. if (callout_handle->getSkip()) {
  1384. skip = true;
  1385. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS,
  1386. DHCP4_HOOK_LEASE4_RELEASE_SKIP);
  1387. }
  1388. }
  1389. // Ok, hw and client-id match - let's release the lease.
  1390. if (!skip) {
  1391. bool success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1392. if (success) {
  1393. // Release successful
  1394. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE)
  1395. .arg(lease->addr_.toText())
  1396. .arg(client_id ? client_id->toText() : "(no client-id)")
  1397. .arg(release->getHWAddr()->toText());
  1398. if (CfgMgr::instance().ddnsEnabled()) {
  1399. // Remove existing DNS entries for the lease, if any.
  1400. queueNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE, lease);
  1401. }
  1402. } else {
  1403. // Release failed -
  1404. LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_FAIL)
  1405. .arg(lease->addr_.toText())
  1406. .arg(client_id ? client_id->toText() : "(no client-id)")
  1407. .arg(release->getHWAddr()->toText());
  1408. }
  1409. }
  1410. } catch (const isc::Exception& ex) {
  1411. // Rethrow the exception with a bit more data.
  1412. LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_EXCEPTION)
  1413. .arg(ex.what())
  1414. .arg(release->getYiaddr());
  1415. }
  1416. }
  1417. void
  1418. Dhcpv4Srv::processDecline(Pkt4Ptr&) {
  1419. /// @todo Implement this (also see ticket #3116)
  1420. }
  1421. Pkt4Ptr
  1422. Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
  1423. // DHCPINFORM MUST not include server identifier.
  1424. sanityCheck(inform, FORBIDDEN);
  1425. Dhcpv4Exchange ex(alloc_engine_, inform, selectSubnet(inform));
  1426. Pkt4Ptr ack = ex.getResponse();
  1427. appendRequestedOptions(ex);
  1428. appendRequestedVendorOptions(ex);
  1429. appendBasicOptions(ex);
  1430. adjustIfaceData(ex);
  1431. // There are cases for the DHCPINFORM that the server receives it via
  1432. // relay but will send the response to the client's unicast address
  1433. // carried in the ciaddr. In this case, the giaddr and hops field should
  1434. // be cleared (these fields were copied by the copyDefaultFields function).
  1435. // Also Relay Agent Options should be removed if present.
  1436. if (ack->getRemoteAddr() != inform->getGiaddr()) {
  1437. ack->setHops(0);
  1438. ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1439. ack->delOption(DHO_DHCP_AGENT_OPTIONS);
  1440. }
  1441. // The DHCPACK must contain server id.
  1442. appendServerID(ex);
  1443. /// @todo: decide whether we want to add a new hook point for
  1444. /// doing class specific processing.
  1445. if (!classSpecificProcessing(ex)) {
  1446. /// @todo add more verbosity here
  1447. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_INFORM_CLASS_PROCESSING_FAILED);
  1448. }
  1449. return (ex.getResponse());
  1450. }
  1451. const char*
  1452. Dhcpv4Srv::serverReceivedPacketName(uint8_t type) {
  1453. static const char* DISCOVER = "DISCOVER";
  1454. static const char* REQUEST = "REQUEST";
  1455. static const char* RELEASE = "RELEASE";
  1456. static const char* DECLINE = "DECLINE";
  1457. static const char* INFORM = "INFORM";
  1458. static const char* UNKNOWN = "UNKNOWN";
  1459. switch (type) {
  1460. case DHCPDISCOVER:
  1461. return (DISCOVER);
  1462. case DHCPREQUEST:
  1463. return (REQUEST);
  1464. case DHCPRELEASE:
  1465. return (RELEASE);
  1466. case DHCPDECLINE:
  1467. return (DECLINE);
  1468. case DHCPINFORM:
  1469. return (INFORM);
  1470. default:
  1471. ;
  1472. }
  1473. return (UNKNOWN);
  1474. }
  1475. bool
  1476. Dhcpv4Srv::accept(const Pkt4Ptr& query) const {
  1477. // Check that the message type is accepted by the server. We rely on the
  1478. // function called to log a message if needed.
  1479. if (!acceptMessageType(query)) {
  1480. return (false);
  1481. }
  1482. // Check if the message from directly connected client (if directly
  1483. // connected) should be dropped or processed.
  1484. if (!acceptDirectRequest(query)) {
  1485. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0002)
  1486. .arg(query->getLabel())
  1487. .arg(query->getIface());
  1488. return (false);
  1489. }
  1490. // Check if the DHCPv4 packet has been sent to us or to someone else.
  1491. // If it hasn't been sent to us, drop it!
  1492. if (!acceptServerId(query)) {
  1493. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0003)
  1494. .arg(query->getLabel())
  1495. .arg(query->getIface());
  1496. return (false);
  1497. }
  1498. return (true);
  1499. }
  1500. bool
  1501. Dhcpv4Srv::acceptDirectRequest(const Pkt4Ptr& pkt) const {
  1502. // Accept all relayed messages.
  1503. if (pkt->isRelayed()) {
  1504. return (true);
  1505. }
  1506. // The source address must not be zero for the DHCPINFORM message from
  1507. // the directly connected client because the server will not know where
  1508. // to respond if the ciaddr was not present.
  1509. try {
  1510. if (pkt->getType() == DHCPINFORM) {
  1511. if ((pkt->getRemoteAddr() == IOAddress::IPV4_ZERO_ADDRESS()) &&
  1512. (pkt->getCiaddr() == IOAddress::IPV4_ZERO_ADDRESS())) {
  1513. return (false);
  1514. }
  1515. }
  1516. } catch (...) {
  1517. // If we got here, it is probably because the message type hasn't
  1518. // been set. But, this should not really happen assuming that
  1519. // we validate the message type prior to calling this function.
  1520. return (false);
  1521. }
  1522. return ((pkt->getLocalAddr() != IOAddress::IPV4_BCAST_ADDRESS()
  1523. || selectSubnet(pkt)));
  1524. }
  1525. bool
  1526. Dhcpv4Srv::acceptMessageType(const Pkt4Ptr& query) const {
  1527. // When receiving a packet without message type option, getType() will
  1528. // throw.
  1529. int type;
  1530. try {
  1531. type = query->getType();
  1532. } catch (...) {
  1533. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0004)
  1534. .arg(query->getLabel())
  1535. .arg(query->getIface());
  1536. return (false);
  1537. }
  1538. // If we receive a message with a non-existing type, we are logging it.
  1539. if (type > DHCPLEASEQUERYDONE) {
  1540. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0005)
  1541. .arg(query->getLabel())
  1542. .arg(type);
  1543. return (false);
  1544. }
  1545. // Once we know that the message type is within a range of defined DHCPv4
  1546. // messages, we do a detailed check to make sure that the received message
  1547. // is targeted at server. Note that we could have received some Offer
  1548. // message broadcasted by the other server to a relay. Even though, the
  1549. // server would rather unicast its response to a relay, let's be on the
  1550. // safe side. Also, we want to drop other messages which we don't support.
  1551. // All these valid messages that we are not going to process are dropped
  1552. // silently.
  1553. if ((type != DHCPDISCOVER) && (type != DHCPREQUEST) &&
  1554. (type != DHCPRELEASE) && (type != DHCPDECLINE) &&
  1555. (type != DHCPINFORM)) {
  1556. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0006)
  1557. .arg(query->getLabel())
  1558. .arg(type);
  1559. return (false);
  1560. }
  1561. return (true);
  1562. }
  1563. bool
  1564. Dhcpv4Srv::acceptServerId(const Pkt4Ptr& query) const {
  1565. // This function is meant to be called internally by the server class, so
  1566. // we rely on the caller to sanity check the pointer and we don't check
  1567. // it here.
  1568. // Check if server identifier option is present. If it is not present
  1569. // we accept the message because it is targeted to all servers.
  1570. // Note that we don't check cases that server identifier is mandatory
  1571. // but not present. This is meant to be sanity checked in other
  1572. // functions.
  1573. OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1574. if (!option) {
  1575. return (true);
  1576. }
  1577. // Server identifier is present. Let's convert it to 4-byte address
  1578. // and try to match with server identifiers used by the server.
  1579. OptionCustomPtr option_custom =
  1580. boost::dynamic_pointer_cast<OptionCustom>(option);
  1581. // Unable to convert the option to the option type which encapsulates it.
  1582. // We treat this as non-matching server id.
  1583. if (!option_custom) {
  1584. return (false);
  1585. }
  1586. // The server identifier option should carry exactly one IPv4 address.
  1587. // If the option definition for the server identifier doesn't change,
  1588. // the OptionCustom object should have exactly one IPv4 address and
  1589. // this check is somewhat redundant. On the other hand, if someone
  1590. // breaks option it may be better to check that here.
  1591. if (option_custom->getDataFieldsNum() != 1) {
  1592. return (false);
  1593. }
  1594. // The server identifier MUST be an IPv4 address. If given address is
  1595. // v6, it is wrong.
  1596. IOAddress server_id = option_custom->readAddress();
  1597. if (!server_id.isV4()) {
  1598. return (false);
  1599. }
  1600. // This function iterates over all interfaces on which the
  1601. // server is listening to find the one which has a socket bound
  1602. // to the address carried in the server identifier option.
  1603. // This has some performance implications. However, given that
  1604. // typically there will be just a few active interfaces the
  1605. // performance hit should be acceptable. If it turns out to
  1606. // be significant, we will have to cache server identifiers
  1607. // when sockets are opened.
  1608. return (IfaceMgr::instance().hasOpenSocket(server_id));
  1609. }
  1610. void
  1611. Dhcpv4Srv::sanityCheck(const Pkt4Ptr& query, RequirementLevel serverid) {
  1612. OptionPtr server_id = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1613. switch (serverid) {
  1614. case FORBIDDEN:
  1615. if (server_id) {
  1616. isc_throw(RFCViolation, "Server-id option was not expected, but "
  1617. << "received in "
  1618. << serverReceivedPacketName(query->getType()));
  1619. }
  1620. break;
  1621. case MANDATORY:
  1622. if (!server_id) {
  1623. isc_throw(RFCViolation, "Server-id option was expected, but not "
  1624. " received in message "
  1625. << serverReceivedPacketName(query->getType()));
  1626. }
  1627. break;
  1628. case OPTIONAL:
  1629. // do nothing here
  1630. ;
  1631. }
  1632. // If there is HWAddress set and it is non-empty, then we're good
  1633. if (query->getHWAddr() && !query->getHWAddr()->hwaddr_.empty()) {
  1634. return;
  1635. }
  1636. // There has to be something to uniquely identify the client:
  1637. // either non-zero MAC address or client-id option present (or both)
  1638. OptionPtr client_id = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1639. // If there's no client-id (or a useless one is provided, i.e. 0 length)
  1640. if (!client_id || client_id->len() == client_id->getHeaderLen()) {
  1641. isc_throw(RFCViolation, "Missing or useless client-id and no HW address "
  1642. " provided in message "
  1643. << serverReceivedPacketName(query->getType()));
  1644. }
  1645. }
  1646. size_t
  1647. Dhcpv4Srv::unpackOptions(const OptionBuffer& buf,
  1648. const std::string& option_space,
  1649. isc::dhcp::OptionCollection& options) {
  1650. size_t offset = 0;
  1651. OptionDefContainer option_defs;
  1652. if (option_space == "dhcp4") {
  1653. // Get the list of standard option definitions.
  1654. option_defs = LibDHCP::getOptionDefs(Option::V4);
  1655. } else if (!option_space.empty()) {
  1656. OptionDefContainerPtr option_defs_ptr = CfgMgr::instance()
  1657. .getCurrentCfg()->getCfgOptionDef()->getAll(option_space);
  1658. if (option_defs_ptr != NULL) {
  1659. option_defs = *option_defs_ptr;
  1660. }
  1661. }
  1662. // Get the search index #1. It allows to search for option definitions
  1663. // using option code.
  1664. const OptionDefContainerTypeIndex& idx = option_defs.get<1>();
  1665. // The buffer being read comprises a set of options, each starting with
  1666. // a one-byte type code and a one-byte length field.
  1667. while (offset + 1 <= buf.size()) {
  1668. uint8_t opt_type = buf[offset++];
  1669. // DHO_END is a special, one octet long option
  1670. if (opt_type == DHO_END)
  1671. return (offset); // just return. Don't need to add DHO_END option
  1672. // DHO_PAD is just a padding after DHO_END. Let's continue parsing
  1673. // in case we receive a message without DHO_END.
  1674. if (opt_type == DHO_PAD)
  1675. continue;
  1676. if (offset + 1 > buf.size()) {
  1677. // opt_type must be cast to integer so as it is not treated as
  1678. // unsigned char value (a number is presented in error message).
  1679. isc_throw(OutOfRange, "Attempt to parse truncated option "
  1680. << static_cast<int>(opt_type));
  1681. }
  1682. uint8_t opt_len = buf[offset++];
  1683. if (offset + opt_len > buf.size()) {
  1684. // We peeked at the option header of the next option, but discovered
  1685. // that it would end up beyond buffer end, so the option is
  1686. // truncated. Hence we can't parse it. Therefore we revert
  1687. // back by two bytes (as if we never parsed them).
  1688. return (offset - 2);
  1689. // isc_throw(OutOfRange, "Option parse failed. Tried to parse "
  1690. // << offset + opt_len << " bytes from " << buf.size()
  1691. // << "-byte long buffer.");
  1692. }
  1693. // Get all definitions with the particular option code. Note that option code
  1694. // is non-unique within this container however at this point we expect
  1695. // to get one option definition with the particular code. If more are
  1696. // returned we report an error.
  1697. const OptionDefContainerTypeRange& range = idx.equal_range(opt_type);
  1698. // Get the number of returned option definitions for the option code.
  1699. size_t num_defs = distance(range.first, range.second);
  1700. OptionPtr opt;
  1701. if (num_defs > 1) {
  1702. // Multiple options of the same code are not supported right now!
  1703. isc_throw(isc::Unexpected, "Internal error: multiple option definitions"
  1704. " for option type " << static_cast<int>(opt_type)
  1705. << " returned. Currently it is not supported to initialize"
  1706. << " multiple option definitions for the same option code."
  1707. << " This will be supported once support for option spaces"
  1708. << " is implemented");
  1709. } else if (num_defs == 0) {
  1710. opt = OptionPtr(new Option(Option::V4, opt_type,
  1711. buf.begin() + offset,
  1712. buf.begin() + offset + opt_len));
  1713. opt->setEncapsulatedSpace("dhcp4");
  1714. } else {
  1715. // The option definition has been found. Use it to create
  1716. // the option instance from the provided buffer chunk.
  1717. const OptionDefinitionPtr& def = *(range.first);
  1718. assert(def);
  1719. opt = def->optionFactory(Option::V4, opt_type,
  1720. buf.begin() + offset,
  1721. buf.begin() + offset + opt_len,
  1722. boost::bind(&Dhcpv4Srv::unpackOptions,
  1723. this, _1, _2, _3));
  1724. }
  1725. options.insert(std::make_pair(opt_type, opt));
  1726. offset += opt_len;
  1727. }
  1728. return (offset);
  1729. }
  1730. void Dhcpv4Srv::classifyPacket(const Pkt4Ptr& pkt) {
  1731. boost::shared_ptr<OptionString> vendor_class =
  1732. boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
  1733. string classes = "";
  1734. if (!vendor_class) {
  1735. return;
  1736. }
  1737. // DOCSIS specific section
  1738. // Let's keep this as a series of checks. So far we're supporting only
  1739. // docsis3.0, but there are also docsis2.0, docsis1.1 and docsis1.0. We
  1740. // may come up with adding several classes, e.g. for docsis2.0 we would
  1741. // add classes docsis2.0, docsis1.1 and docsis1.0.
  1742. // Also we are using find, because we have at least one traffic capture
  1743. // where the user class was followed by a space ("docsis3.0 ").
  1744. // For now, the code is very simple, but it is expected to get much more
  1745. // complex soon. One specific case is that the vendor class is an option
  1746. // sent by the client, so we should not trust it. To confirm that the device
  1747. // is indeed a modem, John B. suggested to check whether chaddr field
  1748. // quals subscriber-id option that was inserted by the relay (CMTS).
  1749. // This kind of logic will appear here soon.
  1750. if (vendor_class->getValue().find(DOCSIS3_CLASS_MODEM) != std::string::npos) {
  1751. pkt->addClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM);
  1752. classes += string(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM) + " ";
  1753. } else
  1754. if (vendor_class->getValue().find(DOCSIS3_CLASS_EROUTER) != std::string::npos) {
  1755. pkt->addClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER);
  1756. classes += string(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER) + " ";
  1757. } else {
  1758. classes += VENDOR_CLASS_PREFIX + vendor_class->getValue();
  1759. pkt->addClass(VENDOR_CLASS_PREFIX + vendor_class->getValue());
  1760. }
  1761. if (!classes.empty()) {
  1762. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_CLASS_ASSIGNED)
  1763. .arg(classes);
  1764. }
  1765. }
  1766. bool
  1767. Dhcpv4Srv::classSpecificProcessing(const Dhcpv4Exchange& ex) {
  1768. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1769. Pkt4Ptr query = ex.getQuery();
  1770. Pkt4Ptr rsp = ex.getResponse();
  1771. // If any of those is missing, there is nothing to do.
  1772. if (!subnet || !query || !rsp) {
  1773. return (true);
  1774. }
  1775. if (query->inClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM)) {
  1776. // Set next-server. This is TFTP server address. Cable modems will
  1777. // download their configuration from that server.
  1778. rsp->setSiaddr(subnet->getSiaddr());
  1779. // Now try to set up file field in DHCPv4 packet. We will just copy
  1780. // content of the boot-file option, which contains the same information.
  1781. OptionDescriptor desc = subnet->getCfgOption()->
  1782. get("dhcp4", DHO_BOOT_FILE_NAME);
  1783. if (desc.option_) {
  1784. boost::shared_ptr<OptionString> boot =
  1785. boost::dynamic_pointer_cast<OptionString>(desc.option_);
  1786. if (boot) {
  1787. std::string filename = boot->getValue();
  1788. rsp->setFile((const uint8_t*)filename.c_str(), filename.size());
  1789. }
  1790. }
  1791. }
  1792. if (query->inClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER)) {
  1793. // Do not set TFTP server address for eRouter devices.
  1794. rsp->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1795. }
  1796. return (true);
  1797. }
  1798. void
  1799. Dhcpv4Srv::startD2() {
  1800. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1801. if (d2_mgr.ddnsEnabled()) {
  1802. // Updates are enabled, so lets start the sender, passing in
  1803. // our error handler.
  1804. // This may throw so wherever this is called needs to ready.
  1805. d2_mgr.startSender(boost::bind(&Dhcpv4Srv::d2ClientErrorHandler,
  1806. this, _1, _2));
  1807. }
  1808. }
  1809. void
  1810. Dhcpv4Srv::d2ClientErrorHandler(const
  1811. dhcp_ddns::NameChangeSender::Result result,
  1812. dhcp_ddns::NameChangeRequestPtr& ncr) {
  1813. LOG_ERROR(dhcp4_logger, DHCP4_DDNS_REQUEST_SEND_FAILED).
  1814. arg(result).arg((ncr ? ncr->toText() : " NULL "));
  1815. // We cannot communicate with kea-dhcp-ddns, suspend further updates.
  1816. /// @todo We may wish to revisit this, but for now we will simply turn
  1817. /// them off.
  1818. CfgMgr::instance().getD2ClientMgr().suspendUpdates();
  1819. }
  1820. std::string
  1821. Daemon::getVersion(bool extended) {
  1822. std::stringstream tmp;
  1823. tmp << VERSION;
  1824. if (extended) {
  1825. tmp << endl << EXTENDED_VERSION;
  1826. // @todo print more details (is it Botan or OpenSSL build,
  1827. // with or without MySQL/Postgres? What compilation options were
  1828. // used? etc)
  1829. }
  1830. return (tmp.str());
  1831. }
  1832. } // namespace dhcp
  1833. } // namespace isc