dhcp4_srv.cc 75 KB

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