dhcp4_srv.cc 79 KB

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