dhcp4_srv.cc 41 KB

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