dhcp4_srv.cc 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. // Copyright (C) 2011-2013 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/iface_mgr.h>
  17. #include <dhcp/option4_addrlst.h>
  18. #include <dhcp/option_int.h>
  19. #include <dhcp/option_int_array.h>
  20. #include <dhcp/pkt4.h>
  21. #include <dhcp/duid.h>
  22. #include <dhcp/hwaddr.h>
  23. #include <dhcp4/dhcp4_log.h>
  24. #include <dhcp4/dhcp4_srv.h>
  25. #include <dhcpsrv/utils.h>
  26. #include <dhcpsrv/cfgmgr.h>
  27. #include <dhcpsrv/lease_mgr.h>
  28. #include <dhcpsrv/lease_mgr_factory.h>
  29. #include <dhcpsrv/subnet.h>
  30. #include <dhcpsrv/utils.h>
  31. #include <dhcpsrv/addr_utilities.h>
  32. #include <hooks/hooks_manager.h>
  33. #include <hooks/callout_handle.h>
  34. #include <boost/algorithm/string/erase.hpp>
  35. #include <iomanip>
  36. #include <fstream>
  37. using namespace isc;
  38. using namespace isc::asiolink;
  39. using namespace isc::dhcp;
  40. using namespace isc::hooks;
  41. using namespace isc::log;
  42. using namespace std;
  43. /// Structure that holds registered hook indexes
  44. struct Dhcp4Hooks {
  45. int hook_index_buffer4_receive_;///< index for "buffer4_receive" hook point
  46. int hook_index_pkt4_receive_; ///< index for "pkt4_receive" hook point
  47. int hook_index_subnet4_select_; ///< index for "subnet4_select" hook point
  48. int hook_index_lease4_release_; ///< index for "lease4_release" hook point
  49. int hook_index_pkt4_send_; ///< index for "pkt4_send" hook point
  50. int hook_index_buffer4_send_; ///< index for "buffer4_send" hook point
  51. /// Constructor that registers hook points for DHCPv4 engine
  52. Dhcp4Hooks() {
  53. hook_index_buffer4_receive_= HooksManager::registerHook("buffer4_receive");
  54. hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
  55. hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
  56. hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
  57. hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
  58. hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
  59. }
  60. };
  61. // Declare a Hooks object. As this is outside any function or method, it
  62. // will be instantiated (and the constructor run) when the module is loaded.
  63. // As a result, the hook indexes will be defined before any method in this
  64. // module is called.
  65. Dhcp4Hooks Hooks;
  66. namespace isc {
  67. namespace dhcp {
  68. /// @brief file name of a server-id file
  69. ///
  70. /// Server must store its server identifier in persistent storage that must not
  71. /// change between restarts. This is name of the file that is created in dataDir
  72. /// (see isc::dhcp::CfgMgr::getDataDir()). It is a text file that uses
  73. /// regular IPv4 address, e.g. 192.0.2.1. Server will create it during
  74. /// first run and then use it afterwards.
  75. static const char* SERVER_ID_FILE = "b10-dhcp4-serverid";
  76. // These are hardcoded parameters. Currently this is a skeleton server that only
  77. // grants those options and a single, fixed, hardcoded lease.
  78. Dhcpv4Srv::Dhcpv4Srv(uint16_t port, const char* dbconfig, const bool use_bcast,
  79. const bool direct_response_desired)
  80. : serverid_(), shutdown_(true), alloc_engine_(), port_(port),
  81. use_bcast_(use_bcast), hook_index_pkt4_receive_(-1),
  82. hook_index_subnet4_select_(-1), hook_index_pkt4_send_(-1) {
  83. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_OPEN_SOCKET).arg(port);
  84. try {
  85. // First call to instance() will create IfaceMgr (it's a singleton)
  86. // it may throw something if things go wrong.
  87. // The 'true' value of the call to setMatchingPacketFilter imposes
  88. // that IfaceMgr will try to use the mechanism to respond directly
  89. // to the client which doesn't have address assigned. This capability
  90. // may be lacking on some OSes, so there is no guarantee that server
  91. // will be able to respond directly.
  92. IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
  93. if (port) {
  94. // open sockets only if port is non-zero. Port 0 is used
  95. // for non-socket related testing.
  96. IfaceMgr::instance().openSockets4(port_, use_bcast_);
  97. }
  98. string srvid_file = CfgMgr::instance().getDataDir() + "/" + string(SERVER_ID_FILE);
  99. if (loadServerID(srvid_file)) {
  100. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_SERVERID_LOADED)
  101. .arg(srvidToString(getServerID()))
  102. .arg(srvid_file);
  103. } else {
  104. generateServerID();
  105. LOG_INFO(dhcp4_logger, DHCP4_SERVERID_GENERATED)
  106. .arg(srvidToString(getServerID()))
  107. .arg(srvid_file);
  108. if (!writeServerID(srvid_file)) {
  109. LOG_WARN(dhcp4_logger, DHCP4_SERVERID_WRITE_FAIL)
  110. .arg(srvid_file);
  111. }
  112. }
  113. // Instantiate LeaseMgr
  114. LeaseMgrFactory::create(dbconfig);
  115. LOG_INFO(dhcp4_logger, DHCP4_DB_BACKEND_STARTED)
  116. .arg(LeaseMgrFactory::instance().getType())
  117. .arg(LeaseMgrFactory::instance().getName());
  118. // Instantiate allocation engine
  119. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
  120. // Register hook points
  121. hook_index_pkt4_receive_ = Hooks.hook_index_pkt4_receive_;
  122. hook_index_subnet4_select_ = Hooks.hook_index_subnet4_select_;
  123. hook_index_pkt4_send_ = Hooks.hook_index_pkt4_send_;
  124. /// @todo call loadLibraries() when handling configuration changes
  125. } catch (const std::exception &e) {
  126. LOG_ERROR(dhcp4_logger, DHCP4_SRV_CONSTRUCT_ERROR).arg(e.what());
  127. shutdown_ = true;
  128. return;
  129. }
  130. shutdown_ = false;
  131. }
  132. Dhcpv4Srv::~Dhcpv4Srv() {
  133. IfaceMgr::instance().closeSockets();
  134. }
  135. void
  136. Dhcpv4Srv::shutdown() {
  137. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_SHUTDOWN_REQUEST);
  138. shutdown_ = true;
  139. }
  140. Pkt4Ptr
  141. Dhcpv4Srv::receivePacket(int timeout) {
  142. return (IfaceMgr::instance().receive4(timeout));
  143. }
  144. void
  145. Dhcpv4Srv::sendPacket(const Pkt4Ptr& packet) {
  146. IfaceMgr::instance().send(packet);
  147. }
  148. bool
  149. Dhcpv4Srv::run() {
  150. while (!shutdown_) {
  151. /// @todo: calculate actual timeout once we have lease database
  152. //cppcheck-suppress variableScope This is temporary anyway
  153. const int timeout = 1000;
  154. // client's message and server's response
  155. Pkt4Ptr query;
  156. Pkt4Ptr rsp;
  157. try {
  158. query = receivePacket(timeout);
  159. } catch (const std::exception& e) {
  160. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_RECEIVE_FAIL).arg(e.what());
  161. }
  162. // Timeout may be reached or signal received, which breaks select()
  163. // with no reception ocurred
  164. if (!query) {
  165. continue;
  166. }
  167. bool skip_unpack = false;
  168. // The packet has just been received so contains the uninterpreted wire
  169. // data; execute callouts registered for buffer6_receive.
  170. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
  171. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  172. // Delete previously set arguments
  173. callout_handle->deleteAllArguments();
  174. // Pass incoming packet as argument
  175. callout_handle->setArgument("query4", query);
  176. // Call callouts
  177. HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_, *callout_handle);
  178. // Callouts decided to skip the next processing step. The next
  179. // processing step would to parse the packet, so skip at this
  180. // stage means that callouts did the parsing already, so server
  181. // should skip parsing.
  182. if (callout_handle->getSkip()) {
  183. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_BUFFER_RCVD_SKIP);
  184. skip_unpack = true;
  185. }
  186. callout_handle->getArgument("query4", query);
  187. }
  188. // Unpack the packet information unless the buffer4_receive callouts
  189. // indicated they did it
  190. if (!skip_unpack) {
  191. try {
  192. query->unpack();
  193. } catch (const std::exception& e) {
  194. // Failed to parse the packet.
  195. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  196. DHCP4_PACKET_PARSE_FAIL).arg(e.what());
  197. continue;
  198. }
  199. }
  200. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_RECEIVED)
  201. .arg(serverReceivedPacketName(query->getType()))
  202. .arg(query->getType())
  203. .arg(query->getIface());
  204. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUERY_DATA)
  205. .arg(static_cast<int>(query->getType()))
  206. .arg(query->toText());
  207. // Let's execute all callouts registered for packet_received
  208. if (HooksManager::calloutsPresent(hook_index_pkt4_receive_)) {
  209. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  210. // Delete previously set arguments
  211. callout_handle->deleteAllArguments();
  212. // Pass incoming packet as argument
  213. callout_handle->setArgument("query4", query);
  214. // Call callouts
  215. HooksManager::callCallouts(hook_index_pkt4_receive_,
  216. *callout_handle);
  217. // Callouts decided to skip the next processing step. The next
  218. // processing step would to process the packet, so skip at this
  219. // stage means drop.
  220. if (callout_handle->getSkip()) {
  221. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_RCVD_SKIP);
  222. continue;
  223. }
  224. callout_handle->getArgument("query4", query);
  225. }
  226. try {
  227. switch (query->getType()) {
  228. case DHCPDISCOVER:
  229. rsp = processDiscover(query);
  230. break;
  231. case DHCPREQUEST:
  232. // Note that REQUEST is used for many things in DHCPv4: for
  233. // requesting new leases, renewing existing ones and even
  234. // for rebinding.
  235. rsp = processRequest(query);
  236. break;
  237. case DHCPRELEASE:
  238. processRelease(query);
  239. break;
  240. case DHCPDECLINE:
  241. processDecline(query);
  242. break;
  243. case DHCPINFORM:
  244. processInform(query);
  245. break;
  246. default:
  247. // Only action is to output a message if debug is enabled,
  248. // and that is covered by the debug statement before the
  249. // "switch" statement.
  250. ;
  251. }
  252. } catch (const isc::Exception& e) {
  253. // Catch-all exception (at least for ones based on the isc
  254. // Exception class, which covers more or less all that
  255. // are explicitly raised in the BIND 10 code). Just log
  256. // the problem and ignore the packet. (The problem is logged
  257. // as a debug message because debug is disabled by default -
  258. // it prevents a DDOS attack based on the sending of problem
  259. // packets.)
  260. if (dhcp4_logger.isDebugEnabled(DBG_DHCP4_BASIC)) {
  261. std::string source = "unknown";
  262. HWAddrPtr hwptr = query->getHWAddr();
  263. if (hwptr) {
  264. source = hwptr->toText();
  265. }
  266. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC,
  267. DHCP4_PACKET_PROCESS_FAIL)
  268. .arg(source).arg(e.what());
  269. }
  270. }
  271. if (!rsp) {
  272. continue;
  273. }
  274. adjustRemoteAddr(query, rsp);
  275. if (!rsp->getHops()) {
  276. rsp->setRemotePort(DHCP4_CLIENT_PORT);
  277. } else {
  278. rsp->setRemotePort(DHCP4_SERVER_PORT);
  279. }
  280. rsp->setLocalAddr(query->getLocalAddr());
  281. rsp->setLocalPort(DHCP4_SERVER_PORT);
  282. rsp->setIface(query->getIface());
  283. rsp->setIndex(query->getIndex());
  284. // Specifies if server should do the packing
  285. bool skip_pack = false;
  286. // Execute all callouts registered for packet6_send
  287. if (HooksManager::calloutsPresent(hook_index_pkt4_send_)) {
  288. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  289. // Delete all previous arguments
  290. callout_handle->deleteAllArguments();
  291. // Clear skip flag if it was set in previous callouts
  292. callout_handle->setSkip(false);
  293. // Set our response
  294. callout_handle->setArgument("response4", rsp);
  295. // Call all installed callouts
  296. HooksManager::callCallouts(hook_index_pkt4_send_,
  297. *callout_handle);
  298. // Callouts decided to skip the next processing step. The next
  299. // processing step would to send the packet, so skip at this
  300. // stage means "drop response".
  301. if (callout_handle->getSkip()) {
  302. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_SEND_SKIP);
  303. skip_pack = true;
  304. }
  305. }
  306. if (!skip_pack) {
  307. try {
  308. rsp->pack();
  309. } catch (const std::exception& e) {
  310. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL)
  311. .arg(e.what());
  312. }
  313. }
  314. try {
  315. // Now all fields and options are constructed into output wire buffer.
  316. // Option objects modification does not make sense anymore. Hooks
  317. // can only manipulate wire buffer at this stage.
  318. // Let's execute all callouts registered for buffer6_send
  319. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_buffer4_send_)) {
  320. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  321. // Delete previously set arguments
  322. callout_handle->deleteAllArguments();
  323. // Pass incoming packet as argument
  324. callout_handle->setArgument("response4", rsp);
  325. // Call callouts
  326. HooksManager::callCallouts(Hooks.hook_index_buffer4_send_, *callout_handle);
  327. // Callouts decided to skip the next processing step. The next
  328. // processing step would to parse the packet, so skip at this
  329. // stage means drop.
  330. if (callout_handle->getSkip()) {
  331. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_BUFFER_SEND_SKIP);
  332. continue;
  333. }
  334. callout_handle->getArgument("response4", rsp);
  335. }
  336. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA,
  337. DHCP4_RESPONSE_DATA)
  338. .arg(static_cast<int>(rsp->getType())).arg(rsp->toText());
  339. sendPacket(rsp);
  340. } catch (const std::exception& e) {
  341. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL)
  342. .arg(e.what());
  343. }
  344. }
  345. return (true);
  346. }
  347. bool
  348. Dhcpv4Srv::loadServerID(const std::string& file_name) {
  349. // load content of the file into a string
  350. fstream f(file_name.c_str(), ios::in);
  351. if (!f.is_open()) {
  352. return (false);
  353. }
  354. string hex_string;
  355. f >> hex_string;
  356. f.close();
  357. // remove any spaces
  358. boost::algorithm::erase_all(hex_string, " ");
  359. try {
  360. IOAddress addr(hex_string);
  361. if (!addr.isV4()) {
  362. return (false);
  363. }
  364. // Now create server-id option
  365. serverid_.reset(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER, addr));
  366. } catch(...) {
  367. // any kind of malformed input (empty string, IPv6 address, complete
  368. // garbate etc.)
  369. return (false);
  370. }
  371. return (true);
  372. }
  373. void
  374. Dhcpv4Srv::generateServerID() {
  375. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  376. // Let's find suitable interface.
  377. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  378. iface != ifaces.end(); ++iface) {
  379. // Let's don't use loopback.
  380. if (iface->flag_loopback_) {
  381. continue;
  382. }
  383. // Let's skip downed interfaces. It is better to use working ones.
  384. if (!iface->flag_up_) {
  385. continue;
  386. }
  387. const Iface::AddressCollection addrs = iface->getAddresses();
  388. for (Iface::AddressCollection::const_iterator addr = addrs.begin();
  389. addr != addrs.end(); ++addr) {
  390. if (addr->getFamily() != AF_INET) {
  391. continue;
  392. }
  393. serverid_ = OptionPtr(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER,
  394. *addr));
  395. return;
  396. }
  397. }
  398. isc_throw(BadValue, "No suitable interfaces for server-identifier found");
  399. }
  400. bool
  401. Dhcpv4Srv::writeServerID(const std::string& file_name) {
  402. fstream f(file_name.c_str(), ios::out | ios::trunc);
  403. if (!f.good()) {
  404. return (false);
  405. }
  406. f << srvidToString(getServerID());
  407. f.close();
  408. return (true);
  409. }
  410. string
  411. Dhcpv4Srv::srvidToString(const OptionPtr& srvid) {
  412. if (!srvid) {
  413. isc_throw(BadValue, "NULL pointer passed to srvidToString()");
  414. }
  415. boost::shared_ptr<Option4AddrLst> generated =
  416. boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
  417. if (!srvid) {
  418. isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
  419. }
  420. Option4AddrLst::AddressContainer addrs = generated->getAddresses();
  421. if (addrs.size() != 1) {
  422. isc_throw(BadValue, "Malformed option passed to srvidToString(). "
  423. << "Expected to contain a single IPv4 address.");
  424. }
  425. return (addrs[0].toText());
  426. }
  427. void
  428. Dhcpv4Srv::copyDefaultFields(const Pkt4Ptr& question, Pkt4Ptr& answer) {
  429. answer->setIface(question->getIface());
  430. answer->setIndex(question->getIndex());
  431. answer->setCiaddr(question->getCiaddr());
  432. answer->setSiaddr(IOAddress("0.0.0.0")); // explicitly set this to 0
  433. answer->setHops(question->getHops());
  434. // copy MAC address
  435. answer->setHWAddr(question->getHWAddr());
  436. // relay address
  437. answer->setGiaddr(question->getGiaddr());
  438. // Let's copy client-id to response. See RFC6842.
  439. OptionPtr client_id = question->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  440. if (client_id) {
  441. answer->addOption(client_id);
  442. }
  443. // If src/dest HW addresses are used by the packet filtering class
  444. // we need to copy them as well. There is a need to check that the
  445. // address being set is not-NULL because an attempt to set the NULL
  446. // HW would result in exception. If these values are not set, the
  447. // the default HW addresses (zeroed) should be generated by the
  448. // packet filtering class when creating Ethernet header for
  449. // outgoing packet.
  450. HWAddrPtr src_hw_addr = question->getLocalHWAddr();
  451. if (src_hw_addr) {
  452. answer->setLocalHWAddr(src_hw_addr);
  453. }
  454. HWAddrPtr dst_hw_addr = question->getRemoteHWAddr();
  455. if (dst_hw_addr) {
  456. answer->setRemoteHWAddr(dst_hw_addr);
  457. }
  458. }
  459. void
  460. Dhcpv4Srv::appendDefaultOptions(Pkt4Ptr& msg, uint8_t msg_type) {
  461. OptionPtr opt;
  462. // add Message Type Option (type 53)
  463. msg->setType(msg_type);
  464. // DHCP Server Identifier (type 54)
  465. msg->addOption(getServerID());
  466. // more options will be added here later
  467. }
  468. void
  469. Dhcpv4Srv::appendRequestedOptions(const Pkt4Ptr& question, Pkt4Ptr& msg) {
  470. // Get the subnet relevant for the client. We will need it
  471. // to get the options associated with it.
  472. Subnet4Ptr subnet = selectSubnet(question);
  473. // If we can't find the subnet for the client there is no way
  474. // to get the options to be sent to a client. We don't log an
  475. // error because it will be logged by the assignLease method
  476. // anyway.
  477. if (!subnet) {
  478. return;
  479. }
  480. // try to get the 'Parameter Request List' option which holds the
  481. // codes of requested options.
  482. OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
  483. OptionUint8Array>(question->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  484. // If there is no PRL option in the message from the client then
  485. // there is nothing to do.
  486. if (!option_prl) {
  487. return;
  488. }
  489. // Get the codes of requested options.
  490. const std::vector<uint8_t>& requested_opts = option_prl->getValues();
  491. // For each requested option code get the instance of the option
  492. // to be returned to the client.
  493. for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
  494. opt != requested_opts.end(); ++opt) {
  495. Subnet::OptionDescriptor desc =
  496. subnet->getOptionDescriptor("dhcp4", *opt);
  497. if (desc.option) {
  498. msg->addOption(desc.option);
  499. }
  500. }
  501. }
  502. void
  503. Dhcpv4Srv::appendBasicOptions(const Pkt4Ptr& question, Pkt4Ptr& msg) {
  504. // Identify options that we always want to send to the
  505. // client (if they are configured).
  506. static const uint16_t required_options[] = {
  507. DHO_SUBNET_MASK,
  508. DHO_ROUTERS,
  509. DHO_DOMAIN_NAME_SERVERS,
  510. DHO_DOMAIN_NAME };
  511. static size_t required_options_size =
  512. sizeof(required_options) / sizeof(required_options[0]);
  513. // Get the subnet.
  514. Subnet4Ptr subnet = selectSubnet(question);
  515. if (!subnet) {
  516. return;
  517. }
  518. // Try to find all 'required' options in the outgoing
  519. // message. Those that are not present will be added.
  520. for (int i = 0; i < required_options_size; ++i) {
  521. OptionPtr opt = msg->getOption(required_options[i]);
  522. if (!opt) {
  523. // Check whether option has been configured.
  524. Subnet::OptionDescriptor desc =
  525. subnet->getOptionDescriptor("dhcp4", required_options[i]);
  526. if (desc.option) {
  527. msg->addOption(desc.option);
  528. }
  529. }
  530. }
  531. }
  532. void
  533. Dhcpv4Srv::assignLease(const Pkt4Ptr& question, Pkt4Ptr& answer) {
  534. // We need to select a subnet the client is connected in.
  535. Subnet4Ptr subnet = selectSubnet(question);
  536. if (!subnet) {
  537. // This particular client is out of luck today. We do not have
  538. // information about the subnet he is connected to. This likely means
  539. // misconfiguration of the server (or some relays). We will continue to
  540. // process this message, but our response will be almost useless: no
  541. // addresses or prefixes, no subnet specific configuration etc. The only
  542. // thing this client can get is some global information (like DNS
  543. // servers).
  544. // perhaps this should be logged on some higher level? This is most likely
  545. // configuration bug.
  546. LOG_ERROR(dhcp4_logger, DHCP4_SUBNET_SELECTION_FAILED)
  547. .arg(question->getRemoteAddr().toText())
  548. .arg(serverReceivedPacketName(question->getType()));
  549. answer->setType(DHCPNAK);
  550. answer->setYiaddr(IOAddress("0.0.0.0"));
  551. return;
  552. }
  553. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_SELECTED)
  554. .arg(subnet->toText());
  555. // Get client-id option
  556. ClientIdPtr client_id;
  557. OptionPtr opt = question->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  558. if (opt) {
  559. client_id = ClientIdPtr(new ClientId(opt->getData()));
  560. }
  561. // client-id is not mandatory in DHCPv4
  562. IOAddress hint = question->getYiaddr();
  563. HWAddrPtr hwaddr = question->getHWAddr();
  564. // "Fake" allocation is processing of DISCOVER message. We pretend to do an
  565. // allocation, but we do not put the lease in the database. That is ok,
  566. // because we do not guarantee that the user will get that exact lease. If
  567. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  568. // it should include this hint. That will help us during the actual lease
  569. // allocation.
  570. bool fake_allocation = (question->getType() == DHCPDISCOVER);
  571. CalloutHandlePtr callout_handle = getCalloutHandle(question);
  572. // Use allocation engine to pick a lease for this client. Allocation engine
  573. // will try to honour the hint, but it is just a hint - some other address
  574. // may be used instead. If fake_allocation is set to false, the lease will
  575. // be inserted into the LeaseMgr as well.
  576. Lease4Ptr lease = alloc_engine_->allocateAddress4(subnet, client_id, hwaddr,
  577. hint, fake_allocation,
  578. callout_handle);
  579. if (lease) {
  580. // We have a lease! Let's set it in the packet and send it back to
  581. // the client.
  582. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
  583. DHCP4_LEASE_ADVERT:DHCP4_LEASE_ALLOC)
  584. .arg(lease->addr_.toText())
  585. .arg(client_id?client_id->toText():"(no client-id)")
  586. .arg(hwaddr?hwaddr->toText():"(no hwaddr info)");
  587. answer->setYiaddr(lease->addr_);
  588. // IP Address Lease time (type 51)
  589. opt = OptionPtr(new Option(Option::V4, DHO_DHCP_LEASE_TIME));
  590. opt->setUint32(lease->valid_lft_);
  591. answer->addOption(opt);
  592. // Router (type 3)
  593. Subnet::OptionDescriptor opt_routers =
  594. subnet->getOptionDescriptor("dhcp4", DHO_ROUTERS);
  595. if (opt_routers.option) {
  596. answer->addOption(opt_routers.option);
  597. }
  598. // Subnet mask (type 1)
  599. answer->addOption(getNetmaskOption(subnet));
  600. // @todo: send renew timer option (T1, option 58)
  601. // @todo: send rebind timer option (T2, option 59)
  602. } else {
  603. // Allocation engine did not allocate a lease. The engine logged
  604. // cause of that failure. The only thing left is to insert
  605. // status code to pass the sad news to the client.
  606. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
  607. DHCP4_LEASE_ADVERT_FAIL:DHCP4_LEASE_ALLOC_FAIL)
  608. .arg(client_id?client_id->toText():"(no client-id)")
  609. .arg(hwaddr?hwaddr->toText():"(no hwaddr info)")
  610. .arg(hint.toText());
  611. answer->setType(DHCPNAK);
  612. answer->setYiaddr(IOAddress("0.0.0.0"));
  613. }
  614. }
  615. void
  616. Dhcpv4Srv::adjustRemoteAddr(const Pkt4Ptr& question, Pkt4Ptr& msg) {
  617. // Let's create static objects representing zeroed and broadcast
  618. // addresses. We will use them further in this function to test
  619. // other addresses against them. Since they are static, they will
  620. // be created only once.
  621. static const IOAddress zero_addr("0.0.0.0");
  622. static const IOAddress bcast_addr("255.255.255.255");
  623. // If received relayed message, server responds to the relay address.
  624. if (question->getGiaddr() != zero_addr) {
  625. msg->setRemoteAddr(question->getGiaddr());
  626. // If giaddr is 0 but client set ciaddr, server should unicast the
  627. // response to ciaddr.
  628. } else if (question->getCiaddr() != zero_addr) {
  629. msg->setRemoteAddr(question->getCiaddr());
  630. // We can't unicast the response to the client when sending NAK,
  631. // because we haven't allocated address for him. Therefore,
  632. // NAK is broadcast.
  633. } else if (msg->getType() == DHCPNAK) {
  634. msg->setRemoteAddr(bcast_addr);
  635. // If yiaddr is set it means that we have created a lease for a client.
  636. } else if (msg->getYiaddr() != zero_addr) {
  637. // If the broadcast bit is set in the flags field, we have to
  638. // send the response to broadcast address. Client may have requested it
  639. // because it doesn't support reception of messages on the interface
  640. // which doesn't have an address assigned. The other case when response
  641. // must be broadcasted is when our server does not support responding
  642. // directly to a client without address assigned.
  643. const bool bcast_flag = ((question->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
  644. if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
  645. msg->setRemoteAddr(bcast_addr);
  646. // Client cleared the broadcast bit and we support direct responses
  647. // so we should unicast the response to a newly allocated address -
  648. // yiaddr.
  649. } else {
  650. msg->setRemoteAddr(msg->getYiaddr());
  651. }
  652. // In most cases, we should have the remote address found already. If we
  653. // found ourselves at this point, the rational thing to do is to respond
  654. // to the address we got the query from.
  655. } else {
  656. msg->setRemoteAddr(question->getRemoteAddr());
  657. }
  658. }
  659. OptionPtr
  660. Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
  661. uint32_t netmask = getNetmask4(subnet->get().second);
  662. OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
  663. DHO_SUBNET_MASK, netmask));
  664. return (opt);
  665. }
  666. Pkt4Ptr
  667. Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
  668. sanityCheck(discover, FORBIDDEN);
  669. Pkt4Ptr offer = Pkt4Ptr
  670. (new Pkt4(DHCPOFFER, discover->getTransid()));
  671. copyDefaultFields(discover, offer);
  672. appendDefaultOptions(offer, DHCPOFFER);
  673. appendRequestedOptions(discover, offer);
  674. assignLease(discover, offer);
  675. // There are a few basic options that we always want to
  676. // include in the response. If client did not request
  677. // them we append them for him.
  678. appendBasicOptions(discover, offer);
  679. return (offer);
  680. }
  681. Pkt4Ptr
  682. Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
  683. Pkt4Ptr ack = Pkt4Ptr
  684. (new Pkt4(DHCPACK, request->getTransid()));
  685. copyDefaultFields(request, ack);
  686. appendDefaultOptions(ack, DHCPACK);
  687. appendRequestedOptions(request, ack);
  688. // Note that we treat REQUEST message uniformly, regardless if this is a
  689. // first request (requesting for new address), renewing existing address
  690. // or even rebinding.
  691. assignLease(request, ack);
  692. // There are a few basic options that we always want to
  693. // include in the response. If client did not request
  694. // them we append them for him.
  695. appendBasicOptions(request, ack);
  696. return (ack);
  697. }
  698. void
  699. Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
  700. // Try to find client-id
  701. ClientIdPtr client_id;
  702. OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  703. if (opt) {
  704. client_id = ClientIdPtr(new ClientId(opt->getData()));
  705. }
  706. try {
  707. // Do we have a lease for that particular address?
  708. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getYiaddr());
  709. if (!lease) {
  710. // No such lease - bogus release
  711. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_NO_LEASE)
  712. .arg(release->getYiaddr().toText())
  713. .arg(release->getHWAddr()->toText())
  714. .arg(client_id ? client_id->toText() : "(no client-id)");
  715. return;
  716. }
  717. // Does the hardware address match? We don't want one client releasing
  718. // second client's leases.
  719. if (lease->hwaddr_ != release->getHWAddr()->hwaddr_) {
  720. // @todo: Print hwaddr from lease as part of ticket #2589
  721. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_HWADDR)
  722. .arg(release->getYiaddr().toText())
  723. .arg(client_id ? client_id->toText() : "(no client-id)")
  724. .arg(release->getHWAddr()->toText());
  725. return;
  726. }
  727. // Does the lease have client-id info? If it has, then check it with what
  728. // the client sent us.
  729. if (lease->client_id_ && client_id && *lease->client_id_ != *client_id) {
  730. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT_ID)
  731. .arg(release->getYiaddr().toText())
  732. .arg(client_id->toText())
  733. .arg(lease->client_id_->toText());
  734. return;
  735. }
  736. bool skip = false;
  737. // Execute all callouts registered for packet6_send
  738. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_release_)) {
  739. CalloutHandlePtr callout_handle = getCalloutHandle(release);
  740. // Delete all previous arguments
  741. callout_handle->deleteAllArguments();
  742. // Pass the original packet
  743. callout_handle->setArgument("query4", release);
  744. // Pass the lease to be updated
  745. callout_handle->setArgument("lease4", lease);
  746. // Call all installed callouts
  747. HooksManager::callCallouts(Hooks.hook_index_lease4_release_, *callout_handle);
  748. // Callouts decided to skip the next processing step. The next
  749. // processing step would to send the packet, so skip at this
  750. // stage means "drop response".
  751. if (callout_handle->getSkip()) {
  752. skip = true;
  753. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_LEASE4_RELEASE_SKIP);
  754. }
  755. }
  756. // Ok, we've passed all checks. Let's release this address.
  757. bool success = false; // was the removal operation succeessful?
  758. // Ok, hw and client-id match - let's release the lease.
  759. if (!skip) {
  760. success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  761. if (success) {
  762. // Release successful - we're done here
  763. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE)
  764. .arg(lease->addr_.toText())
  765. .arg(client_id ? client_id->toText() : "(no client-id)")
  766. .arg(release->getHWAddr()->toText());
  767. } else {
  768. // Release failed -
  769. LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_FAIL)
  770. .arg(lease->addr_.toText())
  771. .arg(client_id ? client_id->toText() : "(no client-id)")
  772. .arg(release->getHWAddr()->toText());
  773. }
  774. }
  775. } catch (const isc::Exception& ex) {
  776. // Rethrow the exception with a bit more data.
  777. LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_EXCEPTION)
  778. .arg(ex.what())
  779. .arg(release->getYiaddr());
  780. }
  781. }
  782. void
  783. Dhcpv4Srv::processDecline(Pkt4Ptr& /* decline */) {
  784. /// TODO: Implement this.
  785. }
  786. Pkt4Ptr
  787. Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
  788. /// TODO: Currently implemented echo mode. Implement this for real
  789. return (inform);
  790. }
  791. const char*
  792. Dhcpv4Srv::serverReceivedPacketName(uint8_t type) {
  793. static const char* DISCOVER = "DISCOVER";
  794. static const char* REQUEST = "REQUEST";
  795. static const char* RELEASE = "RELEASE";
  796. static const char* DECLINE = "DECLINE";
  797. static const char* INFORM = "INFORM";
  798. static const char* UNKNOWN = "UNKNOWN";
  799. switch (type) {
  800. case DHCPDISCOVER:
  801. return (DISCOVER);
  802. case DHCPREQUEST:
  803. return (REQUEST);
  804. case DHCPRELEASE:
  805. return (RELEASE);
  806. case DHCPDECLINE:
  807. return (DECLINE);
  808. case DHCPINFORM:
  809. return (INFORM);
  810. default:
  811. ;
  812. }
  813. return (UNKNOWN);
  814. }
  815. Subnet4Ptr
  816. Dhcpv4Srv::selectSubnet(const Pkt4Ptr& question) {
  817. Subnet4Ptr subnet;
  818. // Is this relayed message?
  819. IOAddress relay = question->getGiaddr();
  820. static const IOAddress notset("0.0.0.0");
  821. if (relay != notset) {
  822. // Yes: Use relay address to select subnet
  823. subnet = CfgMgr::instance().getSubnet4(relay);
  824. } else {
  825. // No: Use client's address to select subnet
  826. subnet = CfgMgr::instance().getSubnet4(question->getRemoteAddr());
  827. }
  828. /// @todo Implement getSubnet4(interface-name)
  829. // Let's execute all callouts registered for packet_received
  830. if (HooksManager::calloutsPresent(hook_index_subnet4_select_)) {
  831. CalloutHandlePtr callout_handle = getCalloutHandle(question);
  832. // We're reusing callout_handle from previous calls
  833. callout_handle->deleteAllArguments();
  834. // Set new arguments
  835. callout_handle->setArgument("query4", question);
  836. callout_handle->setArgument("subnet4", subnet);
  837. callout_handle->setArgument("subnet4collection", CfgMgr::instance().getSubnets4());
  838. // Call user (and server-side) callouts
  839. HooksManager::callCallouts(hook_index_subnet4_select_, *callout_handle);
  840. // Callouts decided to skip this step. This means that no subnet will be
  841. // selected. Packet processing will continue, but it will be severly limited
  842. // (i.e. only global options will be assigned)
  843. if (callout_handle->getSkip()) {
  844. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_SUBNET4_SELECT_SKIP);
  845. return (Subnet4Ptr());
  846. }
  847. // Use whatever subnet was specified by the callout
  848. callout_handle->getArgument("subnet4", subnet);
  849. }
  850. return (subnet);
  851. }
  852. void
  853. Dhcpv4Srv::sanityCheck(const Pkt4Ptr& pkt, RequirementLevel serverid) {
  854. OptionPtr server_id = pkt->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  855. switch (serverid) {
  856. case FORBIDDEN:
  857. if (server_id) {
  858. isc_throw(RFCViolation, "Server-id option was not expected, but "
  859. << "received in " << serverReceivedPacketName(pkt->getType()));
  860. }
  861. break;
  862. case MANDATORY:
  863. if (!server_id) {
  864. isc_throw(RFCViolation, "Server-id option was expected, but not "
  865. " received in message "
  866. << serverReceivedPacketName(pkt->getType()));
  867. }
  868. break;
  869. case OPTIONAL:
  870. // do nothing here
  871. ;
  872. }
  873. // If there is HWAddress set and it is non-empty, then we're good
  874. if (pkt->getHWAddr() && !pkt->getHWAddr()->hwaddr_.empty()) {
  875. return;
  876. }
  877. // There has to be something to uniquely identify the client:
  878. // either non-zero MAC address or client-id option present (or both)
  879. OptionPtr client_id = pkt->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  880. // If there's no client-id (or a useless one is provided, i.e. 0 length)
  881. if (!client_id || client_id->len() == client_id->getHeaderLen()) {
  882. isc_throw(RFCViolation, "Missing or useless client-id and no HW address "
  883. " provided in message "
  884. << serverReceivedPacketName(pkt->getType()));
  885. }
  886. }
  887. isc::hooks::CalloutHandlePtr Dhcpv4Srv::getCalloutHandle(const Pkt4Ptr& pkt) {
  888. // This method returns a CalloutHandle for a given packet. It is guaranteed
  889. // to return the same callout_handle (so user library contexts are
  890. // preserved). This method works well if the server processes one packet
  891. // at a time. Once the server architecture is extended to cover parallel
  892. // packets processing (e.g. delayed-ack, some form of buffering etc.), this
  893. // method has to be extended (e.g. store callouts in a map and use pkt as
  894. // a key). Additional code would be required to release the callout handle
  895. // once the server finished processing.
  896. CalloutHandlePtr callout_handle;
  897. static Pkt4Ptr old_pointer;
  898. if (!callout_handle ||
  899. old_pointer != pkt) {
  900. // This is the first packet or a different packet than previously
  901. // passed to getCalloutHandle()
  902. // Remember the pointer to this packet
  903. old_pointer = pkt;
  904. callout_handle = HooksManager::createCalloutHandle();
  905. }
  906. return (callout_handle);
  907. }
  908. void
  909. Dhcpv4Srv::openActiveSockets(const uint16_t port,
  910. const bool use_bcast) {
  911. IfaceMgr::instance().closeSockets();
  912. // Get the reference to the collection of interfaces. This reference should
  913. // be valid as long as the program is run because IfaceMgr is a singleton.
  914. // Therefore we can safely iterate over instances of all interfaces and
  915. // modify their flags. Here we modify flags which indicate whether socket
  916. // should be open for a particular interface or not.
  917. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  918. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  919. iface != ifaces.end(); ++iface) {
  920. Iface* iface_ptr = IfaceMgr::instance().getIface(iface->getName());
  921. if (iface_ptr == NULL) {
  922. isc_throw(isc::Unexpected, "Interface Manager returned NULL"
  923. << " instance of the interface when DHCPv4 server was"
  924. << " trying to reopen sockets after reconfiguration");
  925. }
  926. if (CfgMgr::instance().isActiveIface(iface->getName())) {
  927. iface_ptr->inactive4_ = false;
  928. LOG_INFO(dhcp4_logger, DHCP4_ACTIVATE_INTERFACE)
  929. .arg(iface->getFullName());
  930. } else {
  931. // For deactivating interface, it should be sufficient to log it
  932. // on the debug level because it is more useful to know what
  933. // interface is activated which is logged on the info level.
  934. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC,
  935. DHCP4_DEACTIVATE_INTERFACE).arg(iface->getName());
  936. iface_ptr->inactive4_ = true;
  937. }
  938. }
  939. // Let's reopen active sockets. openSockets4 will check internally whether
  940. // sockets are marked active or inactive.
  941. // @todo Optimization: we should not reopen all sockets but rather select
  942. // those that have been affected by the new configuration.
  943. if (!IfaceMgr::instance().openSockets4(port, use_bcast)) {
  944. LOG_WARN(dhcp4_logger, DHCP4_NO_SOCKETS_OPEN);
  945. }
  946. }
  947. } // namespace dhcp
  948. } // namespace isc