dhcp4_srv.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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 <boost/algorithm/string/erase.hpp>
  33. #include <iomanip>
  34. #include <fstream>
  35. using namespace isc;
  36. using namespace isc::asiolink;
  37. using namespace isc::dhcp;
  38. using namespace isc::log;
  39. using namespace std;
  40. namespace isc {
  41. namespace dhcp {
  42. /// @brief file name of a server-id file
  43. ///
  44. /// Server must store its server identifier in persistent storage that must not
  45. /// change between restarts. This is name of the file that is created in dataDir
  46. /// (see isc::dhcp::CfgMgr::getDataDir()). It is a text file that uses
  47. /// regular IPv4 address, e.g. 192.0.2.1. Server will create it during
  48. /// first run and then use it afterwards.
  49. static const char* SERVER_ID_FILE = "b10-dhcp4-serverid";
  50. // These are hardcoded parameters. Currently this is a skeleton server that only
  51. // grants those options and a single, fixed, hardcoded lease.
  52. Dhcpv4Srv::Dhcpv4Srv(uint16_t port, const char* dbconfig) {
  53. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_OPEN_SOCKET).arg(port);
  54. try {
  55. // First call to instance() will create IfaceMgr (it's a singleton)
  56. // it may throw something if things go wrong
  57. IfaceMgr::instance();
  58. if (port) {
  59. // open sockets only if port is non-zero. Port 0 is used
  60. // for non-socket related testing.
  61. IfaceMgr::instance().openSockets4(port);
  62. }
  63. string srvid_file = CfgMgr::instance().getDataDir() + "/" + string(SERVER_ID_FILE);
  64. if (loadServerID(srvid_file)) {
  65. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_SERVERID_LOADED)
  66. .arg(srvidToString(getServerID()))
  67. .arg(srvid_file);
  68. } else {
  69. generateServerID();
  70. LOG_INFO(dhcp4_logger, DHCP4_SERVERID_GENERATED)
  71. .arg(srvidToString(getServerID()))
  72. .arg(srvid_file);
  73. if (!writeServerID(srvid_file)) {
  74. LOG_WARN(dhcp4_logger, DHCP4_SERVERID_WRITE_FAIL)
  75. .arg(srvid_file);
  76. }
  77. }
  78. // Instantiate LeaseMgr
  79. LeaseMgrFactory::create(dbconfig);
  80. LOG_INFO(dhcp4_logger, DHCP4_DB_BACKEND_STARTED)
  81. .arg(LeaseMgrFactory::instance().getType())
  82. .arg(LeaseMgrFactory::instance().getName());
  83. // Instantiate allocation engine
  84. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
  85. } catch (const std::exception &e) {
  86. LOG_ERROR(dhcp4_logger, DHCP4_SRV_CONSTRUCT_ERROR).arg(e.what());
  87. shutdown_ = true;
  88. return;
  89. }
  90. shutdown_ = false;
  91. }
  92. Dhcpv4Srv::~Dhcpv4Srv() {
  93. IfaceMgr::instance().closeSockets();
  94. }
  95. void
  96. Dhcpv4Srv::shutdown() {
  97. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_SHUTDOWN_REQUEST);
  98. shutdown_ = true;
  99. }
  100. bool
  101. Dhcpv4Srv::run() {
  102. while (!shutdown_) {
  103. /// @todo: calculate actual timeout once we have lease database
  104. int timeout = 1000;
  105. // client's message and server's response
  106. Pkt4Ptr query;
  107. Pkt4Ptr rsp;
  108. try {
  109. query = IfaceMgr::instance().receive4(timeout);
  110. } catch (const std::exception& e) {
  111. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_RECEIVE_FAIL).arg(e.what());
  112. }
  113. if (query) {
  114. try {
  115. query->unpack();
  116. } catch (const std::exception& e) {
  117. // Failed to parse the packet.
  118. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  119. DHCP4_PACKET_PARSE_FAIL).arg(e.what());
  120. continue;
  121. }
  122. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_RECEIVED)
  123. .arg(serverReceivedPacketName(query->getType()))
  124. .arg(query->getType())
  125. .arg(query->getIface());
  126. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUERY_DATA)
  127. .arg(query->toText());
  128. try {
  129. switch (query->getType()) {
  130. case DHCPDISCOVER:
  131. rsp = processDiscover(query);
  132. break;
  133. case DHCPREQUEST:
  134. rsp = processRequest(query);
  135. break;
  136. case DHCPRELEASE:
  137. processRelease(query);
  138. break;
  139. case DHCPDECLINE:
  140. processDecline(query);
  141. break;
  142. case DHCPINFORM:
  143. processInform(query);
  144. break;
  145. default:
  146. // Only action is to output a message if debug is enabled,
  147. // and that is covered by the debug statement before the
  148. // "switch" statement.
  149. ;
  150. }
  151. } catch (const isc::Exception& e) {
  152. // Catch-all exception (at least for ones based on the isc
  153. // Exception class, which covers more or less all that
  154. // are explicitly raised in the BIND 10 code). Just log
  155. // the problem and ignore the packet. (The problem is logged
  156. // as a debug message because debug is disabled by default -
  157. // it prevents a DDOS attack based on the sending of problem
  158. // packets.)
  159. if (dhcp4_logger.isDebugEnabled(DBG_DHCP4_BASIC)) {
  160. std::string source = "unknown";
  161. HWAddrPtr hwptr = query->getHWAddr();
  162. if (hwptr) {
  163. source = hwptr->toText();
  164. }
  165. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC,
  166. DHCP4_PACKET_PROCESS_FAIL)
  167. .arg(source).arg(e.what());
  168. }
  169. }
  170. if (rsp) {
  171. if (rsp->getRemoteAddr().toText() == "0.0.0.0") {
  172. rsp->setRemoteAddr(query->getRemoteAddr());
  173. }
  174. if (!rsp->getHops()) {
  175. rsp->setRemotePort(DHCP4_CLIENT_PORT);
  176. } else {
  177. rsp->setRemotePort(DHCP4_SERVER_PORT);
  178. }
  179. rsp->setLocalAddr(query->getLocalAddr());
  180. rsp->setLocalPort(DHCP4_SERVER_PORT);
  181. rsp->setIface(query->getIface());
  182. rsp->setIndex(query->getIndex());
  183. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA,
  184. DHCP4_RESPONSE_DATA)
  185. .arg(rsp->getType()).arg(rsp->toText());
  186. if (rsp->pack()) {
  187. try {
  188. IfaceMgr::instance().send(rsp);
  189. } catch (const std::exception& e) {
  190. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL).arg(e.what());
  191. }
  192. } else {
  193. LOG_ERROR(dhcp4_logger, DHCP4_PACK_FAIL);
  194. }
  195. }
  196. }
  197. }
  198. return (true);
  199. }
  200. bool
  201. Dhcpv4Srv::loadServerID(const std::string& file_name) {
  202. // load content of the file into a string
  203. fstream f(file_name.c_str(), ios::in);
  204. if (!f.is_open()) {
  205. return (false);
  206. }
  207. string hex_string;
  208. f >> hex_string;
  209. f.close();
  210. // remove any spaces
  211. boost::algorithm::erase_all(hex_string, " ");
  212. try {
  213. IOAddress addr(hex_string);
  214. if (!addr.isV4()) {
  215. return (false);
  216. }
  217. // Now create server-id option
  218. serverid_.reset(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER, addr));
  219. } catch(...) {
  220. // any kind of malformed input (empty string, IPv6 address, complete
  221. // garbate etc.)
  222. return (false);
  223. }
  224. return (true);
  225. }
  226. void
  227. Dhcpv4Srv::generateServerID() {
  228. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  229. // Let's find suitable interface.
  230. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  231. iface != ifaces.end(); ++iface) {
  232. // Let's don't use loopback.
  233. if (iface->flag_loopback_) {
  234. continue;
  235. }
  236. // Let's skip downed interfaces. It is better to use working ones.
  237. if (!iface->flag_up_) {
  238. continue;
  239. }
  240. const IfaceMgr::AddressCollection addrs = iface->getAddresses();
  241. for (IfaceMgr::AddressCollection::const_iterator addr = addrs.begin();
  242. addr != addrs.end(); ++addr) {
  243. if (addr->getFamily() != AF_INET) {
  244. continue;
  245. }
  246. serverid_ = OptionPtr(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER,
  247. *addr));
  248. return;
  249. }
  250. }
  251. isc_throw(BadValue, "No suitable interfaces for server-identifier found");
  252. }
  253. bool
  254. Dhcpv4Srv::writeServerID(const std::string& file_name) {
  255. fstream f(file_name.c_str(), ios::out | ios::trunc);
  256. if (!f.good()) {
  257. return (false);
  258. }
  259. f << srvidToString(getServerID());
  260. f.close();
  261. return (true);
  262. }
  263. string
  264. Dhcpv4Srv::srvidToString(const OptionPtr& srvid) {
  265. if (!srvid) {
  266. isc_throw(BadValue, "NULL pointer passed to srvidToString()");
  267. }
  268. boost::shared_ptr<Option4AddrLst> generated =
  269. boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
  270. if (!srvid) {
  271. isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
  272. }
  273. Option4AddrLst::AddressContainer addrs = generated->getAddresses();
  274. if (addrs.size() != 1) {
  275. isc_throw(BadValue, "Malformed option passed to srvidToString(). "
  276. << "Expected to contain a single IPv4 address.");
  277. }
  278. return (addrs[0].toText());
  279. }
  280. void
  281. Dhcpv4Srv::copyDefaultFields(const Pkt4Ptr& question, Pkt4Ptr& answer) {
  282. answer->setIface(question->getIface());
  283. answer->setIndex(question->getIndex());
  284. answer->setCiaddr(question->getCiaddr());
  285. answer->setSiaddr(IOAddress("0.0.0.0")); // explictly set this to 0
  286. answer->setHops(question->getHops());
  287. // copy MAC address
  288. answer->setHWAddr(question->getHWAddr());
  289. // relay address
  290. answer->setGiaddr(question->getGiaddr());
  291. if (question->getGiaddr().toText() != "0.0.0.0") {
  292. // relayed traffic
  293. answer->setRemoteAddr(question->getGiaddr());
  294. } else {
  295. // direct traffic
  296. answer->setRemoteAddr(question->getRemoteAddr());
  297. }
  298. // Let's copy client-id to response. See RFC6842.
  299. OptionPtr client_id = question->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  300. if (client_id) {
  301. answer->addOption(client_id);
  302. }
  303. }
  304. void
  305. Dhcpv4Srv::appendDefaultOptions(Pkt4Ptr& msg, uint8_t msg_type) {
  306. OptionPtr opt;
  307. // add Message Type Option (type 53)
  308. msg->setType(msg_type);
  309. // DHCP Server Identifier (type 54)
  310. msg->addOption(getServerID());
  311. // more options will be added here later
  312. }
  313. void
  314. Dhcpv4Srv::appendRequestedOptions(const Pkt4Ptr& question, Pkt4Ptr& msg) {
  315. // Get the subnet relevant for the client. We will need it
  316. // to get the options associated with it.
  317. Subnet4Ptr subnet = selectSubnet(question);
  318. // If we can't find the subnet for the client there is no way
  319. // to get the options to be sent to a client. We don't log an
  320. // error because it will be logged by the assignLease method
  321. // anyway.
  322. if (!subnet) {
  323. return;
  324. }
  325. // try to get the 'Parameter Request List' option which holds the
  326. // codes of requested options.
  327. OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
  328. OptionUint8Array>(question->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  329. // If there is no PRL option in the message from the client then
  330. // there is nothing to do.
  331. if (!option_prl) {
  332. return;
  333. }
  334. // Get the codes of requested options.
  335. const std::vector<uint8_t>& requested_opts = option_prl->getValues();
  336. // For each requested option code get the instance of the option
  337. // to be returned to the client.
  338. for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
  339. opt != requested_opts.end(); ++opt) {
  340. Subnet::OptionDescriptor desc =
  341. subnet->getOptionDescriptor("dhcp4", *opt);
  342. if (desc.option) {
  343. msg->addOption(desc.option);
  344. }
  345. }
  346. }
  347. void
  348. Dhcpv4Srv::appendBasicOptions(const Pkt4Ptr& question, Pkt4Ptr& msg) {
  349. // Identify options that we always want to send to the
  350. // client (if they are configured).
  351. static const uint16_t required_options[] = {
  352. DHO_SUBNET_MASK,
  353. DHO_ROUTERS,
  354. DHO_DOMAIN_NAME_SERVERS,
  355. DHO_DOMAIN_NAME };
  356. static size_t required_options_size =
  357. sizeof(required_options) / sizeof(required_options[0]);
  358. // Get the subnet.
  359. Subnet4Ptr subnet = selectSubnet(question);
  360. if (!subnet) {
  361. return;
  362. }
  363. // Try to find all 'required' options in the outgoing
  364. // message. Those that are not present will be added.
  365. for (int i = 0; i < required_options_size; ++i) {
  366. OptionPtr opt = msg->getOption(required_options[i]);
  367. if (!opt) {
  368. // Check whether option has been configured.
  369. Subnet::OptionDescriptor desc =
  370. subnet->getOptionDescriptor("dhcp4", required_options[i]);
  371. if (desc.option) {
  372. msg->addOption(desc.option);
  373. }
  374. }
  375. }
  376. }
  377. void
  378. Dhcpv4Srv::assignLease(const Pkt4Ptr& question, Pkt4Ptr& answer) {
  379. // We need to select a subnet the client is connected in.
  380. Subnet4Ptr subnet = selectSubnet(question);
  381. if (!subnet) {
  382. // This particular client is out of luck today. We do not have
  383. // information about the subnet he is connected to. This likely means
  384. // misconfiguration of the server (or some relays). We will continue to
  385. // process this message, but our response will be almost useless: no
  386. // addresses or prefixes, no subnet specific configuration etc. The only
  387. // thing this client can get is some global information (like DNS
  388. // servers).
  389. // perhaps this should be logged on some higher level? This is most likely
  390. // configuration bug.
  391. LOG_ERROR(dhcp4_logger, DHCP4_SUBNET_SELECTION_FAILED)
  392. .arg(question->getRemoteAddr().toText())
  393. .arg(serverReceivedPacketName(question->getType()));
  394. answer->setType(DHCPNAK);
  395. answer->setYiaddr(IOAddress("0.0.0.0"));
  396. return;
  397. }
  398. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_SELECTED)
  399. .arg(subnet->toText());
  400. // Get client-id option
  401. ClientIdPtr client_id;
  402. OptionPtr opt = question->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  403. if (opt) {
  404. client_id = ClientIdPtr(new ClientId(opt->getData()));
  405. }
  406. // client-id is not mandatory in DHCPv4
  407. IOAddress hint = question->getYiaddr();
  408. HWAddrPtr hwaddr = question->getHWAddr();
  409. // "Fake" allocation is processing of DISCOVER message. We pretend to do an
  410. // allocation, but we do not put the lease in the database. That is ok,
  411. // because we do not guarantee that the user will get that exact lease. If
  412. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  413. // it should include this hint. That will help us during the actual lease
  414. // allocation.
  415. bool fake_allocation = (question->getType() == DHCPDISCOVER);
  416. // Use allocation engine to pick a lease for this client. Allocation engine
  417. // will try to honour the hint, but it is just a hint - some other address
  418. // may be used instead. If fake_allocation is set to false, the lease will
  419. // be inserted into the LeaseMgr as well.
  420. Lease4Ptr lease = alloc_engine_->allocateAddress4(subnet, client_id, hwaddr,
  421. hint, fake_allocation);
  422. if (lease) {
  423. // We have a lease! Let's set it in the packet and send it back to
  424. // the client.
  425. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
  426. DHCP4_LEASE_ADVERT:DHCP4_LEASE_ALLOC)
  427. .arg(lease->addr_.toText())
  428. .arg(client_id?client_id->toText():"(no client-id)")
  429. .arg(hwaddr?hwaddr->toText():"(no hwaddr info)");
  430. answer->setYiaddr(lease->addr_);
  431. // IP Address Lease time (type 51)
  432. opt = OptionPtr(new Option(Option::V4, DHO_DHCP_LEASE_TIME));
  433. opt->setUint32(lease->valid_lft_);
  434. answer->addOption(opt);
  435. // Router (type 3)
  436. Subnet::OptionDescriptor opt_routers =
  437. subnet->getOptionDescriptor("dhcp4", DHO_ROUTERS);
  438. if (opt_routers.option) {
  439. answer->addOption(opt_routers.option);
  440. }
  441. // Subnet mask (type 1)
  442. answer->addOption(getNetmaskOption(subnet));
  443. // @todo: send renew timer option (T1, option 58)
  444. // @todo: send rebind timer option (T2, option 59)
  445. } else {
  446. // Allocation engine did not allocate a lease. The engine logged
  447. // cause of that failure. The only thing left is to insert
  448. // status code to pass the sad news to the client.
  449. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
  450. DHCP4_LEASE_ADVERT_FAIL:DHCP4_LEASE_ALLOC_FAIL)
  451. .arg(client_id?client_id->toText():"(no client-id)")
  452. .arg(hwaddr?hwaddr->toText():"(no hwaddr info)")
  453. .arg(hint.toText());
  454. answer->setType(DHCPNAK);
  455. answer->setYiaddr(IOAddress("0.0.0.0"));
  456. }
  457. }
  458. OptionPtr
  459. Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
  460. uint32_t netmask = getNetmask4(subnet->get().second);
  461. OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
  462. DHO_SUBNET_MASK, netmask));
  463. return (opt);
  464. }
  465. Pkt4Ptr
  466. Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
  467. Pkt4Ptr offer = Pkt4Ptr
  468. (new Pkt4(DHCPOFFER, discover->getTransid()));
  469. copyDefaultFields(discover, offer);
  470. appendDefaultOptions(offer, DHCPOFFER);
  471. appendRequestedOptions(discover, offer);
  472. assignLease(discover, offer);
  473. // There are a few basic options that we always want to
  474. // include in the response. If client did not request
  475. // them we append them for him.
  476. appendBasicOptions(discover, offer);
  477. return (offer);
  478. }
  479. Pkt4Ptr
  480. Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
  481. Pkt4Ptr ack = Pkt4Ptr
  482. (new Pkt4(DHCPACK, request->getTransid()));
  483. copyDefaultFields(request, ack);
  484. appendDefaultOptions(ack, DHCPACK);
  485. appendRequestedOptions(request, ack);
  486. assignLease(request, ack);
  487. // There are a few basic options that we always want to
  488. // include in the response. If client did not request
  489. // them we append them for him.
  490. appendBasicOptions(request, ack);
  491. return (ack);
  492. }
  493. void
  494. Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
  495. // Try to find client-id
  496. ClientIdPtr client_id;
  497. OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  498. if (opt) {
  499. client_id = ClientIdPtr(new ClientId(opt->getData()));
  500. }
  501. try {
  502. // Do we have a lease for that particular address?
  503. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getYiaddr());
  504. if (!lease) {
  505. // No such lease - bogus release
  506. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_NO_LEASE)
  507. .arg(release->getYiaddr().toText())
  508. .arg(release->getHWAddr()->toText())
  509. .arg(client_id ? client_id->toText() : "(no client-id)");
  510. return;
  511. }
  512. // Does the hardware address match? We don't want one client releasing
  513. // second client's leases.
  514. if (lease->hwaddr_ != release->getHWAddr()->hwaddr_) {
  515. // @todo: Print hwaddr from lease as part of ticket #2589
  516. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_HWADDR)
  517. .arg(release->getYiaddr().toText())
  518. .arg(client_id ? client_id->toText() : "(no client-id)")
  519. .arg(release->getHWAddr()->toText());
  520. return;
  521. }
  522. // Does the lease have client-id info? If it has, then check it with what
  523. // the client sent us.
  524. if (lease->client_id_ && client_id && *lease->client_id_ != *client_id) {
  525. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT_ID)
  526. .arg(release->getYiaddr().toText())
  527. .arg(client_id->toText())
  528. .arg(lease->client_id_->toText());
  529. return;
  530. }
  531. // Ok, hw and client-id match - let's release the lease.
  532. if (LeaseMgrFactory::instance().deleteLease(lease->addr_)) {
  533. // Release successful - we're done here
  534. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE)
  535. .arg(lease->addr_.toText())
  536. .arg(client_id ? client_id->toText() : "(no client-id)")
  537. .arg(release->getHWAddr()->toText());
  538. } else {
  539. // Release failed -
  540. LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_FAIL)
  541. .arg(lease->addr_.toText())
  542. .arg(client_id ? client_id->toText() : "(no client-id)")
  543. .arg(release->getHWAddr()->toText());
  544. }
  545. } catch (const isc::Exception& ex) {
  546. // Rethrow the exception with a bit more data.
  547. LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_EXCEPTION)
  548. .arg(ex.what())
  549. .arg(release->getYiaddr());
  550. }
  551. }
  552. void
  553. Dhcpv4Srv::processDecline(Pkt4Ptr& /* decline */) {
  554. /// TODO: Implement this.
  555. }
  556. Pkt4Ptr
  557. Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
  558. /// TODO: Currently implemented echo mode. Implement this for real
  559. return (inform);
  560. }
  561. const char*
  562. Dhcpv4Srv::serverReceivedPacketName(uint8_t type) {
  563. static const char* DISCOVER = "DISCOVER";
  564. static const char* REQUEST = "REQUEST";
  565. static const char* RELEASE = "RELEASE";
  566. static const char* DECLINE = "DECLINE";
  567. static const char* INFORM = "INFORM";
  568. static const char* UNKNOWN = "UNKNOWN";
  569. switch (type) {
  570. case DHCPDISCOVER:
  571. return (DISCOVER);
  572. case DHCPREQUEST:
  573. return (REQUEST);
  574. case DHCPRELEASE:
  575. return (RELEASE);
  576. case DHCPDECLINE:
  577. return (DECLINE);
  578. case DHCPINFORM:
  579. return (INFORM);
  580. default:
  581. ;
  582. }
  583. return (UNKNOWN);
  584. }
  585. Subnet4Ptr
  586. Dhcpv4Srv::selectSubnet(const Pkt4Ptr& question) {
  587. // Is this relayed message?
  588. IOAddress relay = question->getGiaddr();
  589. if (relay.toText() == "0.0.0.0") {
  590. // Yes: Use relay address to select subnet
  591. return (CfgMgr::instance().getSubnet4(relay));
  592. } else {
  593. // No: Use client's address to select subnet
  594. return (CfgMgr::instance().getSubnet4(question->getRemoteAddr()));
  595. }
  596. }
  597. void
  598. Dhcpv4Srv::sanityCheck(const Pkt4Ptr& pkt, RequirementLevel serverid) {
  599. OptionPtr server_id = pkt->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  600. switch (serverid) {
  601. case FORBIDDEN:
  602. if (server_id) {
  603. isc_throw(RFCViolation, "Server-id option was not expected, but "
  604. << "received in " << serverReceivedPacketName(pkt->getType()));
  605. }
  606. break;
  607. case MANDATORY:
  608. if (!server_id) {
  609. isc_throw(RFCViolation, "Server-id option was expected, but not "
  610. " received in message "
  611. << serverReceivedPacketName(pkt->getType()));
  612. }
  613. break;
  614. case OPTIONAL:
  615. // do nothing here
  616. ;
  617. }
  618. }
  619. } // namespace dhcp
  620. } // namespace isc