dhcp4_srv.cc 26 KB

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