dhcp4_srv.cc 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327
  1. // Copyright (C) 2011-2015 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 <config.h>
  15. #include <asiolink/io_address.h>
  16. #include <dhcp/dhcp4.h>
  17. #include <dhcp/duid.h>
  18. #include <dhcp/hwaddr.h>
  19. #include <dhcp/iface_mgr.h>
  20. #include <dhcp/option4_addrlst.h>
  21. #include <dhcp/option_int.h>
  22. #include <dhcp/option_int_array.h>
  23. #include <dhcp/option_vendor.h>
  24. #include <dhcp/option_string.h>
  25. #include <dhcp/pkt4.h>
  26. #include <dhcp/docsis3_option_defs.h>
  27. #include <dhcp4/dhcp4_log.h>
  28. #include <dhcp4/dhcp4_srv.h>
  29. #include <dhcpsrv/addr_utilities.h>
  30. #include <dhcpsrv/callout_handle_store.h>
  31. #include <dhcpsrv/cfgmgr.h>
  32. #include <dhcpsrv/cfg_subnets4.h>
  33. #include <dhcpsrv/lease_mgr.h>
  34. #include <dhcpsrv/lease_mgr_factory.h>
  35. #include <dhcpsrv/subnet.h>
  36. #include <dhcpsrv/subnet_selector.h>
  37. #include <dhcpsrv/utils.h>
  38. #include <dhcpsrv/utils.h>
  39. #include <hooks/callout_handle.h>
  40. #include <hooks/hooks_log.h>
  41. #include <hooks/hooks_manager.h>
  42. #include <util/strutil.h>
  43. #include <stats/stats_mgr.h>
  44. #include <asio.hpp>
  45. #include <boost/bind.hpp>
  46. #include <boost/foreach.hpp>
  47. #include <boost/shared_ptr.hpp>
  48. #include <iomanip>
  49. using namespace isc;
  50. using namespace isc::asiolink;
  51. using namespace isc::dhcp;
  52. using namespace isc::dhcp_ddns;
  53. using namespace isc::hooks;
  54. using namespace isc::log;
  55. using namespace std;
  56. /// Structure that holds registered hook indexes
  57. struct Dhcp4Hooks {
  58. int hook_index_buffer4_receive_;///< index for "buffer4_receive" hook point
  59. int hook_index_pkt4_receive_; ///< index for "pkt4_receive" hook point
  60. int hook_index_subnet4_select_; ///< index for "subnet4_select" hook point
  61. int hook_index_lease4_release_; ///< index for "lease4_release" hook point
  62. int hook_index_pkt4_send_; ///< index for "pkt4_send" hook point
  63. int hook_index_buffer4_send_; ///< index for "buffer4_send" hook point
  64. /// Constructor that registers hook points for DHCPv4 engine
  65. Dhcp4Hooks() {
  66. hook_index_buffer4_receive_= HooksManager::registerHook("buffer4_receive");
  67. hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
  68. hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
  69. hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
  70. hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
  71. hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
  72. }
  73. };
  74. // Declare a Hooks object. As this is outside any function or method, it
  75. // will be instantiated (and the constructor run) when the module is loaded.
  76. // As a result, the hook indexes will be defined before any method in this
  77. // module is called.
  78. Dhcp4Hooks Hooks;
  79. namespace isc {
  80. namespace dhcp {
  81. Dhcpv4Exchange::Dhcpv4Exchange(const AllocEnginePtr& alloc_engine,
  82. const Pkt4Ptr& query,
  83. const Subnet4Ptr& subnet)
  84. : alloc_engine_(alloc_engine), query_(query), resp_(),
  85. context_(new AllocEngine::ClientContext4()) {
  86. if (!alloc_engine_) {
  87. isc_throw(BadValue, "alloc_engine value must not be NULL"
  88. " when creating an instance of the Dhcpv4Exchange");
  89. }
  90. if (!query_) {
  91. isc_throw(BadValue, "query value must not be NULL when"
  92. " creating an instance of the Dhcpv4Exchange");
  93. }
  94. // Create response message.
  95. initResponse();
  96. // Select subnet for the query message.
  97. context_->subnet_ = subnet;
  98. // Hardware address.
  99. context_->hwaddr_ = query->getHWAddr();
  100. // Client Identifier
  101. OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  102. if (opt_clientid) {
  103. context_->clientid_.reset(new ClientId(opt_clientid->getData()));
  104. }
  105. // Check for static reservations.
  106. alloc_engine->findReservation(*context_);
  107. };
  108. void
  109. Dhcpv4Exchange::initResponse() {
  110. uint8_t resp_type = 0;
  111. switch (getQuery()->getType()) {
  112. case DHCPDISCOVER:
  113. resp_type = DHCPOFFER;
  114. break;
  115. case DHCPREQUEST:
  116. case DHCPINFORM:
  117. resp_type = DHCPACK;
  118. break;
  119. default:
  120. ;
  121. }
  122. // Only create a response if one is required.
  123. if (resp_type > 0) {
  124. resp_.reset(new Pkt4(resp_type, getQuery()->getTransid()));
  125. copyDefaultFields();
  126. }
  127. }
  128. void
  129. Dhcpv4Exchange::copyDefaultFields() {
  130. resp_->setIface(query_->getIface());
  131. resp_->setIndex(query_->getIndex());
  132. // explicitly set this to 0
  133. resp_->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  134. // ciaddr is always 0, except for the Renew/Rebind state when it may
  135. // be set to the ciaddr sent by the client.
  136. resp_->setCiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  137. resp_->setHops(query_->getHops());
  138. // copy MAC address
  139. resp_->setHWAddr(query_->getHWAddr());
  140. // relay address
  141. resp_->setGiaddr(query_->getGiaddr());
  142. // Let's copy client-id to response. See RFC6842.
  143. // It is possible to disable RFC6842 to keep backward compatibility
  144. bool echo = CfgMgr::instance().echoClientId();
  145. OptionPtr client_id = query_->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  146. if (client_id && echo) {
  147. resp_->addOption(client_id);
  148. }
  149. // If src/dest HW addresses are used by the packet filtering class
  150. // we need to copy them as well. There is a need to check that the
  151. // address being set is not-NULL because an attempt to set the NULL
  152. // HW would result in exception. If these values are not set, the
  153. // the default HW addresses (zeroed) should be generated by the
  154. // packet filtering class when creating Ethernet header for
  155. // outgoing packet.
  156. HWAddrPtr src_hw_addr = query_->getLocalHWAddr();
  157. if (src_hw_addr) {
  158. resp_->setLocalHWAddr(src_hw_addr);
  159. }
  160. HWAddrPtr dst_hw_addr = query_->getRemoteHWAddr();
  161. if (dst_hw_addr) {
  162. resp_->setRemoteHWAddr(dst_hw_addr);
  163. }
  164. // If this packet is relayed, we want to copy Relay Agent Info option
  165. OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
  166. if (rai) {
  167. resp_->addOption(rai);
  168. }
  169. }
  170. const std::string Dhcpv4Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");
  171. Dhcpv4Srv::Dhcpv4Srv(uint16_t port, const bool use_bcast,
  172. const bool direct_response_desired)
  173. : shutdown_(true), alloc_engine_(), port_(port),
  174. use_bcast_(use_bcast), hook_index_pkt4_receive_(-1),
  175. hook_index_subnet4_select_(-1), hook_index_pkt4_send_(-1) {
  176. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_OPEN_SOCKET).arg(port);
  177. try {
  178. // Port 0 is used for testing purposes where we don't open broadcast
  179. // capable sockets. So, set the packet filter handling direct traffic
  180. // only if we are in non-test mode.
  181. if (port) {
  182. // First call to instance() will create IfaceMgr (it's a singleton)
  183. // it may throw something if things go wrong.
  184. // The 'true' value of the call to setMatchingPacketFilter imposes
  185. // that IfaceMgr will try to use the mechanism to respond directly
  186. // to the client which doesn't have address assigned. This capability
  187. // may be lacking on some OSes, so there is no guarantee that server
  188. // will be able to respond directly.
  189. IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
  190. }
  191. // Instantiate allocation engine
  192. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100,
  193. false /* false = IPv4 */));
  194. // Register hook points
  195. hook_index_pkt4_receive_ = Hooks.hook_index_pkt4_receive_;
  196. hook_index_subnet4_select_ = Hooks.hook_index_subnet4_select_;
  197. hook_index_pkt4_send_ = Hooks.hook_index_pkt4_send_;
  198. /// @todo call loadLibraries() when handling configuration changes
  199. } catch (const std::exception &e) {
  200. LOG_ERROR(dhcp4_logger, DHCP4_SRV_CONSTRUCT_ERROR).arg(e.what());
  201. shutdown_ = true;
  202. return;
  203. }
  204. shutdown_ = false;
  205. }
  206. Dhcpv4Srv::~Dhcpv4Srv() {
  207. IfaceMgr::instance().closeSockets();
  208. }
  209. void
  210. Dhcpv4Srv::shutdown() {
  211. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_SHUTDOWN_REQUEST);
  212. shutdown_ = true;
  213. }
  214. isc::dhcp::Subnet4Ptr
  215. Dhcpv4Srv::selectSubnet(const Pkt4Ptr& query) const {
  216. Subnet4Ptr subnet;
  217. SubnetSelector selector;
  218. selector.ciaddr_ = query->getCiaddr();
  219. selector.giaddr_ = query->getGiaddr();
  220. selector.local_address_ = query->getLocalAddr();
  221. selector.remote_address_ = query->getRemoteAddr();
  222. selector.client_classes_ = query->classes_;
  223. selector.iface_name_ = query->getIface();
  224. CfgMgr& cfgmgr = CfgMgr::instance();
  225. subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet(selector);
  226. // Let's execute all callouts registered for subnet4_select
  227. if (HooksManager::calloutsPresent(hook_index_subnet4_select_)) {
  228. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  229. // We're reusing callout_handle from previous calls
  230. callout_handle->deleteAllArguments();
  231. // Set new arguments
  232. callout_handle->setArgument("query4", query);
  233. callout_handle->setArgument("subnet4", subnet);
  234. callout_handle->setArgument("subnet4collection",
  235. cfgmgr.getCurrentCfg()->
  236. getCfgSubnets4()->getAll());
  237. // Call user (and server-side) callouts
  238. HooksManager::callCallouts(hook_index_subnet4_select_,
  239. *callout_handle);
  240. // Callouts decided to skip this step. This means that no subnet
  241. // will be selected. Packet processing will continue, but it will
  242. // be severely limited (i.e. only global options will be assigned)
  243. if (callout_handle->getSkip()) {
  244. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  245. DHCP4_HOOK_SUBNET4_SELECT_SKIP)
  246. .arg(query->getLabel());
  247. return (Subnet4Ptr());
  248. }
  249. // Use whatever subnet was specified by the callout
  250. callout_handle->getArgument("subnet4", subnet);
  251. }
  252. if (subnet) {
  253. // Log at higher debug level that subnet has been found.
  254. LOG_DEBUG(packet_logger, DBG_DHCP4_BASIC_DATA, DHCP4_SUBNET_SELECTED)
  255. .arg(query->getLabel())
  256. .arg(subnet->getID());
  257. // Log detailed information about the selected subnet at the
  258. // lower debug level.
  259. LOG_DEBUG(packet_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_DATA)
  260. .arg(query->getLabel())
  261. .arg(subnet->toText());
  262. } else {
  263. LOG_DEBUG(packet_logger, DBG_DHCP4_DETAIL,
  264. DHCP4_SUBNET_SELECTION_FAILED)
  265. .arg(query->getLabel());
  266. }
  267. return (subnet);
  268. }
  269. Pkt4Ptr
  270. Dhcpv4Srv::receivePacket(int timeout) {
  271. return (IfaceMgr::instance().receive4(timeout));
  272. }
  273. void
  274. Dhcpv4Srv::sendPacket(const Pkt4Ptr& packet) {
  275. IfaceMgr::instance().send(packet);
  276. }
  277. bool
  278. Dhcpv4Srv::run() {
  279. while (!shutdown_) {
  280. // client's message and server's response
  281. Pkt4Ptr query;
  282. Pkt4Ptr rsp;
  283. try {
  284. // The lease database backend may install some timers for which
  285. // the handlers need to be executed periodically. Retrieve the
  286. // maximum interval at which the handlers must be executed from
  287. // the lease manager.
  288. uint32_t timeout = LeaseMgrFactory::instance().getIOServiceExecInterval();
  289. // If the returned value is zero it means that there are no
  290. // timers installed, so use a default value.
  291. if (timeout == 0) {
  292. timeout = 1000;
  293. }
  294. LOG_DEBUG(packet_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_WAIT).arg(timeout);
  295. query = receivePacket(timeout);
  296. // Log if packet has arrived. We can't log the detailed information
  297. // about the DHCP message because it hasn't been unpacked/parsed
  298. // yet, and it can't be parsed at this point because hooks will
  299. // have to process it first. The only information available at this
  300. // point are: the interface, source address and destination addresses
  301. // and ports.
  302. if (query) {
  303. LOG_DEBUG(packet_logger, DBG_DHCP4_BASIC, DHCP4_BUFFER_RECEIVED)
  304. .arg(query->getRemoteAddr().toText())
  305. .arg(query->getRemotePort())
  306. .arg(query->getLocalAddr().toText())
  307. .arg(query->getLocalPort())
  308. .arg(query->getIface());
  309. } else {
  310. LOG_DEBUG(packet_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_WAIT_TIMEOUT)
  311. .arg(timeout);
  312. }
  313. } catch (const SignalInterruptOnSelect) {
  314. // Packet reception interrupted because a signal has been received.
  315. // This is not an error because we might have received a SIGTERM,
  316. // SIGINT or SIGHUP which are handled by the server. For signals
  317. // that are not handled by the server we rely on the default
  318. // behavior of the system, but there is nothing we should log here.
  319. LOG_DEBUG(packet_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_WAIT_SIGNAL)
  320. .arg(signal_set_->getNext());
  321. } catch (const std::exception& e) {
  322. // Log all other errors.
  323. LOG_ERROR(packet_logger, DHCP4_BUFFER_RECEIVE_FAIL).arg(e.what());
  324. }
  325. // Handle next signal received by the process. It must be called after
  326. // an attempt to receive a packet to properly handle server shut down.
  327. // The SIGTERM or SIGINT will be received prior to, or during execution
  328. // of select() (select is invoked by receivePacket()). When that
  329. // happens, select will be interrupted. The signal handler will be
  330. // invoked immediately after select(). The handler will set the
  331. // shutdown flag and cause the process to terminate before the next
  332. // select() function is called. If the function was called before
  333. // receivePacket the process could wait up to the duration of timeout
  334. // of select() to terminate.
  335. handleSignal();
  336. // Execute ready timers for the lease database, e.g. Lease File Cleanup.
  337. try {
  338. LeaseMgrFactory::instance().getIOService()->poll();
  339. } catch (const std::exception& ex) {
  340. LOG_WARN(dhcp4_logger, DHCP4_LEASE_DATABASE_TIMERS_EXEC_FAIL)
  341. .arg(ex.what());
  342. }
  343. // Timeout may be reached or signal received, which breaks select()
  344. // with no reception occurred. No need to log anything here because
  345. // we have logged right after the call to receivePacket().
  346. if (!query) {
  347. continue;
  348. }
  349. // Log reception of the packet. We need to increase it early, as any
  350. // failures in unpacking will cause the packet to be dropped. We
  351. // will increase type specific packets further down the road.
  352. // See processStatsReceived().
  353. isc::stats::StatsMgr::instance().addValue("pkt4-received",
  354. static_cast<uint64_t>(1));
  355. // In order to parse the DHCP options, the server needs to use some
  356. // configuration information such as: existing option spaces, option
  357. // definitions etc. This is the kind of information which is not
  358. // available in the libdhcp, so we need to supply our own implementation
  359. // of the option parsing function here, which would rely on the
  360. // configuration data.
  361. query->setCallback(boost::bind(&Dhcpv4Srv::unpackOptions, this,
  362. _1, _2, _3));
  363. bool skip_unpack = false;
  364. // The packet has just been received so contains the uninterpreted wire
  365. // data; execute callouts registered for buffer4_receive.
  366. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
  367. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  368. // Delete previously set arguments
  369. callout_handle->deleteAllArguments();
  370. // Pass incoming packet as argument
  371. callout_handle->setArgument("query4", query);
  372. // Call callouts
  373. HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_,
  374. *callout_handle);
  375. // Callouts decided to skip the next processing step. The next
  376. // processing step would to parse the packet, so skip at this
  377. // stage means that callouts did the parsing already, so server
  378. // should skip parsing.
  379. if (callout_handle->getSkip()) {
  380. LOG_DEBUG(hooks_logger, DBG_DHCP4_DETAIL, DHCP4_HOOK_BUFFER_RCVD_SKIP)
  381. .arg(query->getRemoteAddr().toText())
  382. .arg(query->getLocalAddr().toText())
  383. .arg(query->getIface());
  384. skip_unpack = true;
  385. }
  386. callout_handle->getArgument("query4", query);
  387. }
  388. // Unpack the packet information unless the buffer4_receive callouts
  389. // indicated they did it
  390. if (!skip_unpack) {
  391. try {
  392. LOG_DEBUG(options_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_UNPACK)
  393. .arg(query->getRemoteAddr().toText())
  394. .arg(query->getLocalAddr().toText())
  395. .arg(query->getIface());
  396. query->unpack();
  397. } catch (const std::exception& e) {
  398. // Failed to parse the packet.
  399. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL,
  400. DHCP4_PACKET_DROP_0001)
  401. .arg(query->getRemoteAddr().toText())
  402. .arg(query->getLocalAddr().toText())
  403. .arg(query->getIface())
  404. .arg(e.what());
  405. // Increase the statistics of parse failues and dropped packets.
  406. isc::stats::StatsMgr::instance().addValue("pkt4-parse-failed",
  407. static_cast<uint64_t>(1));
  408. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  409. static_cast<uint64_t>(1));
  410. continue;
  411. }
  412. }
  413. // Update statistics accordingly for received packet.
  414. processStatsReceived(query);
  415. // Assign this packet to one or more classes if needed. We need to do
  416. // this before calling accept(), because getSubnet4() may need client
  417. // class information.
  418. classifyPacket(query);
  419. // Check whether the message should be further processed or discarded.
  420. // There is no need to log anything here. This function logs by itself.
  421. if (!accept(query)) {
  422. // Increase the statistic of dropped packets.
  423. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  424. static_cast<uint64_t>(1));
  425. continue;
  426. }
  427. // We have sanity checked (in accept() that the Message Type option
  428. // exists, so we can safely get it here.
  429. int type = query->getType();
  430. LOG_DEBUG(packet_logger, DBG_DHCP4_BASIC_DATA, DHCP4_PACKET_RECEIVED)
  431. .arg(query->getLabel())
  432. .arg(query->getName())
  433. .arg(type)
  434. .arg(query->getRemoteAddr())
  435. .arg(query->getLocalAddr())
  436. .arg(query->getIface());
  437. LOG_DEBUG(packet_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUERY_DATA)
  438. .arg(query->getLabel())
  439. .arg(query->toText());
  440. // Let's execute all callouts registered for pkt4_receive
  441. if (HooksManager::calloutsPresent(hook_index_pkt4_receive_)) {
  442. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  443. // Delete previously set arguments
  444. callout_handle->deleteAllArguments();
  445. // Pass incoming packet as argument
  446. callout_handle->setArgument("query4", query);
  447. // Call callouts
  448. HooksManager::callCallouts(hook_index_pkt4_receive_,
  449. *callout_handle);
  450. // Callouts decided to skip the next processing step. The next
  451. // processing step would to process the packet, so skip at this
  452. // stage means drop.
  453. if (callout_handle->getSkip()) {
  454. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_RCVD_SKIP)
  455. .arg(query->getLabel());
  456. continue;
  457. }
  458. callout_handle->getArgument("query4", query);
  459. }
  460. try {
  461. switch (query->getType()) {
  462. case DHCPDISCOVER:
  463. rsp = processDiscover(query);
  464. break;
  465. case DHCPREQUEST:
  466. // Note that REQUEST is used for many things in DHCPv4: for
  467. // requesting new leases, renewing existing ones and even
  468. // for rebinding.
  469. rsp = processRequest(query);
  470. break;
  471. case DHCPRELEASE:
  472. processRelease(query);
  473. break;
  474. case DHCPDECLINE:
  475. processDecline(query);
  476. break;
  477. case DHCPINFORM:
  478. rsp = processInform(query);
  479. break;
  480. default:
  481. // Only action is to output a message if debug is enabled,
  482. // and that is covered by the debug statement before the
  483. // "switch" statement.
  484. ;
  485. }
  486. } catch (const isc::Exception& e) {
  487. // Catch-all exception (at least for ones based on the isc Exception
  488. // class, which covers more or less all that are explicitly raised
  489. // in the Kea code). Just log the problem and ignore the packet.
  490. // (The problem is logged as a debug message because debug is
  491. // disabled by default - it prevents a DDOS attack based on the
  492. // sending of problem packets.)
  493. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_BASIC,
  494. DHCP4_PACKET_DROP_0007)
  495. .arg(query->getLabel())
  496. .arg(e.what());
  497. // Increase the statistic of dropped packets.
  498. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  499. static_cast<uint64_t>(1));
  500. }
  501. if (!rsp) {
  502. continue;
  503. }
  504. // Specifies if server should do the packing
  505. bool skip_pack = false;
  506. // Execute all callouts registered for pkt4_send
  507. if (HooksManager::calloutsPresent(hook_index_pkt4_send_)) {
  508. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  509. // Delete all previous arguments
  510. callout_handle->deleteAllArguments();
  511. // Clear skip flag if it was set in previous callouts
  512. callout_handle->setSkip(false);
  513. // Set our response
  514. callout_handle->setArgument("response4", rsp);
  515. // Call all installed callouts
  516. HooksManager::callCallouts(hook_index_pkt4_send_,
  517. *callout_handle);
  518. // Callouts decided to skip the next processing step. The next
  519. // processing step would to send the packet, so skip at this
  520. // stage means "drop response".
  521. if (callout_handle->getSkip()) {
  522. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_SEND_SKIP)
  523. .arg(query->getLabel());
  524. skip_pack = true;
  525. }
  526. }
  527. if (!skip_pack) {
  528. try {
  529. LOG_DEBUG(options_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_PACK)
  530. .arg(rsp->getLabel());
  531. rsp->pack();
  532. } catch (const std::exception& e) {
  533. LOG_ERROR(options_logger, DHCP4_PACKET_PACK_FAIL)
  534. .arg(rsp->getLabel())
  535. .arg(e.what());
  536. }
  537. }
  538. try {
  539. // Now all fields and options are constructed into output wire buffer.
  540. // Option objects modification does not make sense anymore. Hooks
  541. // can only manipulate wire buffer at this stage.
  542. // Let's execute all callouts registered for buffer4_send
  543. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_send_)) {
  544. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  545. // Delete previously set arguments
  546. callout_handle->deleteAllArguments();
  547. // Pass incoming packet as argument
  548. callout_handle->setArgument("response4", rsp);
  549. // Call callouts
  550. HooksManager::callCallouts(Hooks.hook_index_buffer4_send_,
  551. *callout_handle);
  552. // Callouts decided to skip the next processing step. The next
  553. // processing step would to parse the packet, so skip at this
  554. // stage means drop.
  555. if (callout_handle->getSkip()) {
  556. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  557. DHCP4_HOOK_BUFFER_SEND_SKIP)
  558. .arg(rsp->getLabel());
  559. continue;
  560. }
  561. callout_handle->getArgument("response4", rsp);
  562. }
  563. LOG_DEBUG(packet_logger, DBG_DHCP4_BASIC, DHCP4_PACKET_SEND)
  564. .arg(rsp->getLabel())
  565. .arg(rsp->getName())
  566. .arg(static_cast<int>(rsp->getType()))
  567. .arg(rsp->getLocalAddr())
  568. .arg(rsp->getLocalPort())
  569. .arg(rsp->getRemoteAddr())
  570. .arg(rsp->getRemotePort())
  571. .arg(rsp->getIface());
  572. LOG_DEBUG(packet_logger, DBG_DHCP4_DETAIL_DATA,
  573. DHCP4_RESPONSE_DATA)
  574. .arg(rsp->getLabel())
  575. .arg(rsp->getName())
  576. .arg(static_cast<int>(rsp->getType()))
  577. .arg(rsp->toText());
  578. sendPacket(rsp);
  579. // Update statistics accordingly for sent packet.
  580. processStatsSent(rsp);
  581. } catch (const std::exception& e) {
  582. LOG_ERROR(packet_logger, DHCP4_PACKET_SEND_FAIL)
  583. .arg(rsp->getLabel())
  584. .arg(e.what());
  585. }
  586. }
  587. return (true);
  588. }
  589. string
  590. Dhcpv4Srv::srvidToString(const OptionPtr& srvid) {
  591. if (!srvid) {
  592. isc_throw(BadValue, "NULL pointer passed to srvidToString()");
  593. }
  594. boost::shared_ptr<Option4AddrLst> generated =
  595. boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
  596. if (!srvid) {
  597. isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
  598. }
  599. Option4AddrLst::AddressContainer addrs = generated->getAddresses();
  600. if (addrs.size() != 1) {
  601. isc_throw(BadValue, "Malformed option passed to srvidToString(). "
  602. << "Expected to contain a single IPv4 address.");
  603. }
  604. return (addrs[0].toText());
  605. }
  606. isc::dhcp_ddns::D2Dhcid
  607. Dhcpv4Srv::computeDhcid(const Lease4Ptr& lease) {
  608. if (!lease) {
  609. isc_throw(DhcidComputeError, "a pointer to the lease must be not"
  610. " NULL to compute DHCID");
  611. } else if (lease->hostname_.empty()) {
  612. isc_throw(DhcidComputeError, "unable to compute the DHCID for the"
  613. " lease which has empty hostname set");
  614. }
  615. // In order to compute DHCID the client's hostname must be encoded in
  616. // canonical wire format. It is unlikely that the FQDN is malformed
  617. // because it is validated by the classes which encapsulate options
  618. // carrying client FQDN. However, if the client name was carried in the
  619. // Hostname option it is more likely as it carries the hostname as a
  620. // regular string.
  621. std::vector<uint8_t> fqdn_wire;
  622. try {
  623. OptionDataTypeUtil::writeFqdn(lease->hostname_, fqdn_wire, true);
  624. } catch (const Exception& ex) {
  625. isc_throw(DhcidComputeError, "unable to compute DHCID because the"
  626. " hostname: " << lease->hostname_ << " is invalid");
  627. }
  628. // Prefer client id to HW address to compute DHCID. If Client Id is
  629. // NULL, use HW address.
  630. try {
  631. if (lease->client_id_) {
  632. return (D2Dhcid(lease->client_id_->getClientId(), fqdn_wire));
  633. } else {
  634. return (D2Dhcid(lease->hwaddr_, fqdn_wire));
  635. }
  636. } catch (const Exception& ex) {
  637. isc_throw(DhcidComputeError, "unable to compute DHCID: "
  638. << ex.what());
  639. }
  640. }
  641. void
  642. Dhcpv4Srv::appendServerID(Dhcpv4Exchange& ex) {
  643. // The source address for the outbound message should have been set already.
  644. // This is the address that to the best of the server's knowledge will be
  645. // available from the client.
  646. /// @todo: perhaps we should consider some more sophisticated server id
  647. /// generation, but for the current use cases, it should be ok.
  648. OptionPtr opt_srvid(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER,
  649. ex.getResponse()->getLocalAddr()));
  650. ex.getResponse()->addOption(opt_srvid);
  651. }
  652. void
  653. Dhcpv4Srv::appendRequestedOptions(Dhcpv4Exchange& ex) {
  654. // Get the subnet relevant for the client. We will need it
  655. // to get the options associated with it.
  656. Subnet4Ptr subnet = ex.getContext()->subnet_;
  657. // If we can't find the subnet for the client there is no way
  658. // to get the options to be sent to a client. We don't log an
  659. // error because it will be logged by the assignLease method
  660. // anyway.
  661. if (!subnet) {
  662. return;
  663. }
  664. Pkt4Ptr query = ex.getQuery();
  665. // try to get the 'Parameter Request List' option which holds the
  666. // codes of requested options.
  667. OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
  668. OptionUint8Array>(query->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  669. // If there is no PRL option in the message from the client then
  670. // there is nothing to do.
  671. if (!option_prl) {
  672. return;
  673. }
  674. Pkt4Ptr resp = ex.getResponse();
  675. // Get the codes of requested options.
  676. const std::vector<uint8_t>& requested_opts = option_prl->getValues();
  677. // For each requested option code get the instance of the option
  678. // to be returned to the client.
  679. for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
  680. opt != requested_opts.end(); ++opt) {
  681. if (!resp->getOption(*opt)) {
  682. OptionDescriptor desc = subnet->getCfgOption()->get("dhcp4", *opt);
  683. if (desc.option_) {
  684. resp->addOption(desc.option_);
  685. }
  686. }
  687. }
  688. }
  689. void
  690. Dhcpv4Srv::appendRequestedVendorOptions(Dhcpv4Exchange& ex) {
  691. // Get the configured subnet suitable for the incoming packet.
  692. Subnet4Ptr subnet = ex.getContext()->subnet_;
  693. // Leave if there is no subnet matching the incoming packet.
  694. // There is no need to log the error message here because
  695. // it will be logged in the assignLease() when it fails to
  696. // pick the suitable subnet. We don't want to duplicate
  697. // error messages in such case.
  698. if (!subnet) {
  699. return;
  700. }
  701. // Try to get the vendor option
  702. boost::shared_ptr<OptionVendor> vendor_req = boost::dynamic_pointer_cast<
  703. OptionVendor>(ex.getQuery()->getOption(DHO_VIVSO_SUBOPTIONS));
  704. if (!vendor_req) {
  705. return;
  706. }
  707. uint32_t vendor_id = vendor_req->getVendorId();
  708. // Let's try to get ORO within that vendor-option
  709. /// @todo This is very specific to vendor-id=4491 (Cable Labs). Other
  710. /// vendors may have different policies.
  711. OptionUint8ArrayPtr oro =
  712. boost::dynamic_pointer_cast<OptionUint8Array>(vendor_req->getOption(DOCSIS3_V4_ORO));
  713. // Option ORO not found. Don't do anything then.
  714. if (!oro) {
  715. return;
  716. }
  717. boost::shared_ptr<OptionVendor> vendor_rsp(new OptionVendor(Option::V4, vendor_id));
  718. // Get the list of options that client requested.
  719. bool added = false;
  720. const std::vector<uint8_t>& requested_opts = oro->getValues();
  721. for (std::vector<uint8_t>::const_iterator code = requested_opts.begin();
  722. code != requested_opts.end(); ++code) {
  723. if (!vendor_rsp->getOption(*code)) {
  724. OptionDescriptor desc = subnet->getCfgOption()->get(vendor_id,
  725. *code);
  726. if (desc.option_) {
  727. vendor_rsp->addOption(desc.option_);
  728. added = true;
  729. }
  730. }
  731. if (added) {
  732. ex.getResponse()->addOption(vendor_rsp);
  733. }
  734. }
  735. }
  736. void
  737. Dhcpv4Srv::appendBasicOptions(Dhcpv4Exchange& ex) {
  738. // Identify options that we always want to send to the
  739. // client (if they are configured).
  740. static const uint16_t required_options[] = {
  741. DHO_ROUTERS,
  742. DHO_DOMAIN_NAME_SERVERS,
  743. DHO_DOMAIN_NAME };
  744. static size_t required_options_size =
  745. sizeof(required_options) / sizeof(required_options[0]);
  746. // Get the subnet.
  747. Subnet4Ptr subnet = ex.getContext()->subnet_;
  748. if (!subnet) {
  749. return;
  750. }
  751. Pkt4Ptr resp = ex.getResponse();
  752. // Try to find all 'required' options in the outgoing
  753. // message. Those that are not present will be added.
  754. for (int i = 0; i < required_options_size; ++i) {
  755. OptionPtr opt = resp->getOption(required_options[i]);
  756. if (!opt) {
  757. // Check whether option has been configured.
  758. OptionDescriptor desc = subnet->getCfgOption()->
  759. get("dhcp4", required_options[i]);
  760. if (desc.option_) {
  761. resp->addOption(desc.option_);
  762. }
  763. }
  764. }
  765. }
  766. void
  767. Dhcpv4Srv::processClientName(Dhcpv4Exchange& ex) {
  768. // It is possible that client has sent both Client FQDN and Hostname
  769. // option. In such case, server should prefer Client FQDN option and
  770. // ignore the Hostname option.
  771. try {
  772. Pkt4Ptr resp = ex.getResponse();
  773. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
  774. (ex.getQuery()->getOption(DHO_FQDN));
  775. if (fqdn) {
  776. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL, DHCP4_CLIENT_FQDN_PROCESS)
  777. .arg(ex.getQuery()->getLabel());
  778. processClientFqdnOption(ex);
  779. } else {
  780. OptionStringPtr hostname = boost::dynamic_pointer_cast<OptionString>
  781. (ex.getQuery()->getOption(DHO_HOST_NAME));
  782. if (hostname) {
  783. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL, DHCP4_CLIENT_HOSTNAME_PROCESS)
  784. .arg(ex.getQuery()->getLabel());
  785. processHostnameOption(ex);
  786. }
  787. }
  788. } catch (const Exception& e) {
  789. // In some rare cases it is possible that the client's name processing
  790. // fails. For example, the Hostname option may be malformed, or there
  791. // may be an error in the server's logic which would cause multiple
  792. // attempts to add the same option to the response message. This
  793. // error message aggregates all these errors so they can be diagnosed
  794. // from the log. We don't want to throw an exception here because,
  795. // it will impact the processing of the whole packet. We rather want
  796. // the processing to continue, even if the client's name is wrong.
  797. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_NAME_PROC_FAIL)
  798. .arg(ex.getQuery()->getLabel())
  799. .arg(e.what());
  800. }
  801. }
  802. void
  803. Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
  804. // Obtain the FQDN option from the client's message.
  805. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  806. Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
  807. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_FQDN_DATA)
  808. .arg(ex.getQuery()->getLabel())
  809. .arg(fqdn->toText());
  810. // Create the DHCPv4 Client FQDN Option to be included in the server's
  811. // response to a client.
  812. Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
  813. // Set the server S, N, and O flags based on client's flags and
  814. // current configuration.
  815. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  816. d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  817. // Carry over the client's E flag.
  818. fqdn_resp->setFlag(Option4ClientFqdn::FLAG_E,
  819. fqdn->getFlag(Option4ClientFqdn::FLAG_E));
  820. if (ex.getContext()->host_ && !ex.getContext()->host_->getHostname().empty()) {
  821. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  822. fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->host_->getHostname(),
  823. true), Option4ClientFqdn::FULL);
  824. } else {
  825. // Adjust the domain name based on domain name value and type sent by the
  826. // client and current configuration.
  827. d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  828. }
  829. // Add FQDN option to the response message. Note that, there may be some
  830. // cases when server may choose not to include the FQDN option in a
  831. // response to a client. In such cases, the FQDN should be removed from the
  832. // outgoing message. In theory we could cease to include the FQDN option
  833. // in this function until it is confirmed that it should be included.
  834. // However, we include it here for simplicity. Functions used to acquire
  835. // lease for a client will scan the response message for FQDN and if it
  836. // is found they will take necessary actions to store the FQDN information
  837. // in the lease database as well as to generate NameChangeRequests to DNS.
  838. // If we don't store the option in the response message, we will have to
  839. // propagate it in the different way to the functions which acquire the
  840. // lease. This would require modifications to the API of this class.
  841. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_RESPONSE_FQDN_DATA)
  842. .arg(ex.getQuery()->getLabel())
  843. .arg(fqdn_resp->toText());
  844. ex.getResponse()->addOption(fqdn_resp);
  845. }
  846. void
  847. Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
  848. // Obtain the Hostname option from the client's message.
  849. OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
  850. (ex.getQuery()->getOption(DHO_HOST_NAME));
  851. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_HOSTNAME_DATA)
  852. .arg(ex.getQuery()->getLabel())
  853. .arg(opt_hostname->getValue());
  854. // Fetch D2 configuration.
  855. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  856. // Do nothing if the DNS updates are disabled.
  857. if (!d2_mgr.ddnsEnabled()) {
  858. return;
  859. }
  860. std::string hostname = isc::util::str::trim(opt_hostname->getValue());
  861. unsigned int label_count = OptionDataTypeUtil::getLabelCount(hostname);
  862. // The hostname option sent by the client should be at least 1 octet long.
  863. // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
  864. /// @todo It would be more liberal to accept this and let it fall into
  865. /// the case of replace or less than two below.
  866. if (label_count == 0) {
  867. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_EMPTY_HOSTNAME)
  868. .arg(ex.getQuery()->getLabel());
  869. return;
  870. }
  871. // Copy construct the hostname provided by the client. It is entirely
  872. // possible that we will use the hostname option provided by the client
  873. // to perform the DNS update and we will send the same option to him to
  874. // indicate that we accepted this hostname.
  875. OptionStringPtr opt_hostname_resp(new OptionString(*opt_hostname));
  876. // The hostname option may be unqualified or fully qualified. The lab_count
  877. // holds the number of labels for the name. The number of 1 means that
  878. // there is only root label "." (even for unqualified names, as the
  879. // getLabelCount function treats each name as a fully qualified one).
  880. // By checking the number of labels present in the hostname we may infer
  881. // whether client has sent the fully qualified or unqualified hostname.
  882. // If there is a hostname reservation for this client, use it.
  883. if (ex.getContext()->host_ && !ex.getContext()->host_->getHostname().empty()) {
  884. opt_hostname_resp->setValue(d2_mgr.qualifyName(ex.getContext()->host_->getHostname(),
  885. false));
  886. } else if ((d2_mgr.getD2ClientConfig()->getReplaceClientName()) ||
  887. (label_count < 2)) {
  888. // Set to root domain to signal later on that we should replace it.
  889. // DHO_HOST_NAME is a string option which cannot be empty.
  890. /// @todo We may want to reconsider whether it is appropriate for the
  891. /// client to send a root domain name as a Hostname. There are
  892. /// also extensions to the auto generation of the client's name,
  893. /// e.g. conversion to the puny code which may be considered at some point.
  894. /// For now, we just remain liberal and expect that the DNS will handle
  895. /// conversion if needed and possible.
  896. opt_hostname_resp->setValue(".");
  897. } else if (label_count == 2) {
  898. // If there are two labels, it means that the client has specified
  899. // the unqualified name. We have to concatenate the unqualified name
  900. // with the domain name. The false value passed as a second argument
  901. // indicates that the trailing dot should not be appended to the
  902. // hostname. We don't want to append the trailing dot because
  903. // we don't know whether the hostname is partial or not and some
  904. // clients do not handle the hostnames with the trailing dot.
  905. opt_hostname_resp->setValue(d2_mgr.qualifyName(hostname, false));
  906. }
  907. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_RESPONSE_HOSTNAME_DATA)
  908. .arg(ex.getQuery()->getLabel())
  909. .arg(opt_hostname_resp->getValue());
  910. ex.getResponse()->addOption(opt_hostname_resp);
  911. }
  912. void
  913. Dhcpv4Srv::createNameChangeRequests(const Lease4Ptr& lease,
  914. const Lease4Ptr& old_lease) {
  915. if (!lease) {
  916. isc_throw(isc::Unexpected,
  917. "NULL lease specified when creating NameChangeRequest");
  918. }
  919. // If old lease is not NULL, it is an indication that the lease has
  920. // just been renewed. In such case we may need to generate the
  921. // additional NameChangeRequest to remove an existing entry before
  922. // we create a NameChangeRequest to add the entry for an updated lease.
  923. // We may also decide not to generate any requests at all. This is when
  924. // we discover that nothing has changed in the client's FQDN data.
  925. if (old_lease) {
  926. if (!lease->matches(*old_lease)) {
  927. isc_throw(isc::Unexpected,
  928. "there is no match between the current instance of the"
  929. " lease: " << lease->toText() << ", and the previous"
  930. " instance: " << lease->toText());
  931. } else {
  932. // There will be a NameChangeRequest generated to remove existing
  933. // DNS entries if the following conditions are met:
  934. // - The hostname is set for the existing lease, we can't generate
  935. // removal request for non-existent hostname.
  936. // - A server has performed reverse, forward or both updates.
  937. // - FQDN data between the new and old lease do not match.
  938. if (!lease->hasIdenticalFqdn(*old_lease)) {
  939. queueNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE,
  940. old_lease);
  941. // If FQDN data from both leases match, there is no need to update.
  942. } else if (lease->hasIdenticalFqdn(*old_lease)) {
  943. return;
  944. }
  945. }
  946. }
  947. // We may need to generate the NameChangeRequest for the new lease. It
  948. // will be generated only if hostname is set and if forward or reverse
  949. // update has been requested.
  950. queueNameChangeRequest(isc::dhcp_ddns::CHG_ADD, lease);
  951. }
  952. void
  953. Dhcpv4Srv::
  954. queueNameChangeRequest(const isc::dhcp_ddns::NameChangeType chg_type,
  955. const Lease4Ptr& lease) {
  956. // The hostname must not be empty, and at least one type of update
  957. // should be requested.
  958. if (!lease || lease->hostname_.empty() ||
  959. (!lease->fqdn_rev_ && !lease->fqdn_fwd_)) {
  960. return;
  961. }
  962. // Create the DHCID for the NameChangeRequest.
  963. D2Dhcid dhcid;
  964. try {
  965. dhcid = computeDhcid(lease);
  966. } catch (const DhcidComputeError& ex) {
  967. LOG_ERROR(ddns_logger, DHCP4_DHCID_COMPUTE_ERROR)
  968. .arg(lease->toText())
  969. .arg(ex.what());
  970. return;
  971. }
  972. // Create NameChangeRequest
  973. NameChangeRequestPtr ncr(new NameChangeRequest(chg_type, lease->fqdn_fwd_,
  974. lease->fqdn_rev_,
  975. lease->hostname_,
  976. lease->addr_.toText(),
  977. dhcid,
  978. (lease->cltt_ +
  979. lease->valid_lft_),
  980. lease->valid_lft_));
  981. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUEUE_NCR)
  982. .arg(chg_type == CHG_ADD ? "add" : "remove")
  983. .arg(ncr->toText());
  984. // And pass it to the the manager.
  985. CfgMgr::instance().getD2ClientMgr().sendRequest(ncr);
  986. }
  987. void
  988. Dhcpv4Srv::assignLease(Dhcpv4Exchange& ex) {
  989. // Get the pointers to the query and the response messages.
  990. Pkt4Ptr query = ex.getQuery();
  991. Pkt4Ptr resp = ex.getResponse();
  992. // Get the context.
  993. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  994. // Subnet should have been already selected when the context was created.
  995. Subnet4Ptr subnet = ctx->subnet_;
  996. if (!subnet) {
  997. // This particular client is out of luck today. We do not have
  998. // information about the subnet he is connected to. This likely means
  999. // misconfiguration of the server (or some relays).
  1000. // Perhaps this should be logged on some higher level?
  1001. LOG_ERROR(bad_packet_logger, DHCP4_PACKET_NAK_0001)
  1002. .arg(query->getLabel())
  1003. .arg(query->getRemoteAddr().toText())
  1004. .arg(query->getName());
  1005. resp->setType(DHCPNAK);
  1006. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1007. return;
  1008. }
  1009. // Set up siaddr. Perhaps assignLease is not the best place to call this
  1010. // as siaddr has nothing to do with a lease, but otherwise we would have
  1011. // to select subnet twice (performance hit) or update too many functions
  1012. // at once.
  1013. /// @todo: move subnet selection to a common code
  1014. resp->setSiaddr(subnet->getSiaddr());
  1015. // Get client-id. It is not mandatory in DHCPv4.
  1016. ClientIdPtr client_id = ex.getContext()->clientid_;
  1017. // Get the server identifier. It will be used to determine the state
  1018. // of the client.
  1019. OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
  1020. OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  1021. // Check if the client has sent a requested IP address option or
  1022. // ciaddr.
  1023. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  1024. OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  1025. IOAddress hint(IOAddress::IPV4_ZERO_ADDRESS());
  1026. if (opt_requested_address) {
  1027. hint = opt_requested_address->readAddress();
  1028. } else if (!query->getCiaddr().isV4Zero()) {
  1029. hint = query->getCiaddr();
  1030. }
  1031. HWAddrPtr hwaddr = query->getHWAddr();
  1032. // "Fake" allocation is processing of DISCOVER message. We pretend to do an
  1033. // allocation, but we do not put the lease in the database. That is ok,
  1034. // because we do not guarantee that the user will get that exact lease. If
  1035. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  1036. // it should include this hint. That will help us during the actual lease
  1037. // allocation.
  1038. bool fake_allocation = (query->getType() == DHCPDISCOVER);
  1039. // If there is no server id and there is a Requested IP Address option
  1040. // the client is in the INIT-REBOOT state in which the server has to
  1041. // determine whether the client's notion of the address is correct
  1042. // and whether the client is known, i.e., has a lease.
  1043. if (!fake_allocation && !opt_serverid && opt_requested_address) {
  1044. LOG_DEBUG(lease_logger, DBG_DHCP4_DETAIL, DHCP4_INIT_REBOOT)
  1045. .arg(query->getLabel())
  1046. .arg(hint.toText());
  1047. Lease4Ptr lease;
  1048. if (hwaddr) {
  1049. lease = LeaseMgrFactory::instance().getLease4(*hwaddr,
  1050. subnet->getID());
  1051. }
  1052. if (!lease && client_id) {
  1053. lease = LeaseMgrFactory::instance().getLease4(*client_id,
  1054. subnet->getID());
  1055. }
  1056. // Got a lease so we can check the address.
  1057. if (lease && (lease->addr_ != hint)) {
  1058. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL,
  1059. DHCP4_PACKET_NAK_0002)
  1060. .arg(query->getLabel())
  1061. .arg(hint.toText());
  1062. resp->setType(DHCPNAK);
  1063. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1064. return;
  1065. }
  1066. // Now check the second error case: unknown client.
  1067. if (!lease) {
  1068. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL,
  1069. DHCP4_NO_LEASE_INIT_REBOOT)
  1070. .arg(query->getLabel())
  1071. .arg(hint.toText());
  1072. ex.deleteResponse();
  1073. return;
  1074. }
  1075. }
  1076. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1077. std::string hostname;
  1078. bool fqdn_fwd = false;
  1079. bool fqdn_rev = false;
  1080. OptionStringPtr opt_hostname;
  1081. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1082. Option4ClientFqdn>(resp->getOption(DHO_FQDN));
  1083. if (fqdn) {
  1084. hostname = fqdn->getDomainName();
  1085. CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn,
  1086. fqdn_fwd,
  1087. fqdn_rev);
  1088. } else {
  1089. opt_hostname = boost::dynamic_pointer_cast<OptionString>
  1090. (resp->getOption(DHO_HOST_NAME));
  1091. if (opt_hostname) {
  1092. hostname = opt_hostname->getValue();
  1093. // DHO_HOST_NAME is string option which cannot be blank,
  1094. // we use "." to know we should replace it with a fully
  1095. // generated name. The local string variable needs to be
  1096. // blank in logic below.
  1097. if (hostname == ".") {
  1098. hostname = "";
  1099. }
  1100. /// @todo It could be configurable what sort of updates the
  1101. /// server is doing when Hostname option was sent.
  1102. fqdn_fwd = true;
  1103. fqdn_rev = true;
  1104. }
  1105. }
  1106. // We need to set these values in the context as they haven't been set yet.
  1107. ctx->requested_address_ = hint;
  1108. ctx->fwd_dns_update_ = fqdn_fwd;
  1109. ctx->rev_dns_update_ = fqdn_rev;
  1110. ctx->hostname_ = hostname;
  1111. ctx->fake_allocation_ = fake_allocation;
  1112. ctx->callout_handle_ = callout_handle;
  1113. Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
  1114. if (lease) {
  1115. // We have a lease! Let's set it in the packet and send it back to
  1116. // the client.
  1117. LOG_DEBUG(lease_logger, DBG_DHCP4_BASIC_DATA, fake_allocation?
  1118. DHCP4_LEASE_ADVERT : DHCP4_LEASE_ALLOC)
  1119. .arg(query->getLabel())
  1120. .arg(lease->addr_.toText());
  1121. resp->setYiaddr(lease->addr_);
  1122. /// @todo The server should check what ciaddr the client has supplied
  1123. /// in ciaddr. Currently the ciaddr is ignored except for the subnet
  1124. /// selection. If the client supplied an invalid address, the server
  1125. /// will also return an invalid address here.
  1126. if (!fake_allocation) {
  1127. // If this is a renewing client it will set a ciaddr which the
  1128. // server may include in the response. If this is a new allocation
  1129. // the client will set ciaddr to 0 and this will also be propagated
  1130. // to the server's resp.
  1131. resp->setCiaddr(query->getCiaddr());
  1132. }
  1133. // If there has been Client FQDN or Hostname option sent, but the
  1134. // hostname is empty, it means that server is responsible for
  1135. // generating the entire hostname for the client. The example of the
  1136. // client's name, generated from the IP address is: host-192-0-2-3.
  1137. if ((fqdn || opt_hostname) && lease->hostname_.empty()) {
  1138. // Note that if we have received the hostname option, rather than
  1139. // Client FQDN the trailing dot is not appended to the generated
  1140. // hostname because some clients don't handle the trailing dot in
  1141. // the hostname. Whether the trailing dot is appended or not is
  1142. // controlled by the second argument to the generateFqdn().
  1143. lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
  1144. .generateFqdn(lease->addr_, static_cast<bool>(fqdn));
  1145. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL, DHCP4_RESPONSE_HOSTNAME_GENERATE)
  1146. .arg(query->getLabel())
  1147. .arg(lease->hostname_);
  1148. // The operations below are rather safe, but we want to catch
  1149. // any potential exceptions (e.g. invalid lease database backend
  1150. // implementation) and log an error.
  1151. try {
  1152. if (!fake_allocation) {
  1153. // The lease update should be safe, because the lease should
  1154. // be already in the database. In most cases the exception
  1155. // would be thrown if the lease was missing.
  1156. LeaseMgrFactory::instance().updateLease4(lease);
  1157. }
  1158. // The name update in the option should be also safe,
  1159. // because the generated name is well formed.
  1160. if (fqdn) {
  1161. fqdn->setDomainName(lease->hostname_,
  1162. Option4ClientFqdn::FULL);
  1163. } else if (opt_hostname) {
  1164. opt_hostname->setValue(lease->hostname_);
  1165. }
  1166. } catch (const Exception& ex) {
  1167. LOG_ERROR(ddns_logger, DHCP4_NAME_GEN_UPDATE_FAIL)
  1168. .arg(query->getLabel())
  1169. .arg(lease->hostname_)
  1170. .arg(ex.what());
  1171. }
  1172. }
  1173. // IP Address Lease time (type 51)
  1174. OptionPtr opt(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME,
  1175. lease->valid_lft_));
  1176. resp->addOption(opt);
  1177. // Subnet mask (type 1)
  1178. resp->addOption(getNetmaskOption(subnet));
  1179. // renewal-timer (type 58)
  1180. if (!subnet->getT1().unspecified()) {
  1181. OptionUint32Ptr t1(new OptionUint32(Option::V4,
  1182. DHO_DHCP_RENEWAL_TIME,
  1183. subnet->getT1()));
  1184. resp->addOption(t1);
  1185. }
  1186. // rebind timer (type 59)
  1187. if (!subnet->getT2().unspecified()) {
  1188. OptionUint32Ptr t2(new OptionUint32(Option::V4,
  1189. DHO_DHCP_REBINDING_TIME,
  1190. subnet->getT2()));
  1191. resp->addOption(t2);
  1192. }
  1193. // Create NameChangeRequests if DDNS is enabled and this is a
  1194. // real allocation.
  1195. if (!fake_allocation && CfgMgr::instance().ddnsEnabled()) {
  1196. try {
  1197. LOG_DEBUG(ddns_logger, DBG_DHCP4_DETAIL, DHCP4_NCR_CREATE)
  1198. .arg(query->getLabel());
  1199. createNameChangeRequests(lease, ctx->old_lease_);
  1200. } catch (const Exception& ex) {
  1201. LOG_ERROR(ddns_logger, DHCP4_NCR_CREATION_FAILED)
  1202. .arg(query->getLabel())
  1203. .arg(ex.what());
  1204. }
  1205. }
  1206. } else {
  1207. // Allocation engine did not allocate a lease. The engine logged
  1208. // cause of that failure.
  1209. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, fake_allocation ?
  1210. DHCP4_PACKET_NAK_0003 : DHCP4_PACKET_NAK_0004)
  1211. .arg(query->getLabel())
  1212. .arg(query->getCiaddr().toText())
  1213. .arg(opt_requested_address ?
  1214. opt_requested_address->readAddress().toText() : "(no address)");
  1215. resp->setType(DHCPNAK);
  1216. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1217. resp->delOption(DHO_FQDN);
  1218. resp->delOption(DHO_HOST_NAME);
  1219. }
  1220. }
  1221. void
  1222. Dhcpv4Srv::adjustIfaceData(Dhcpv4Exchange& ex) {
  1223. adjustRemoteAddr(ex);
  1224. // Initialize the pointers to the client's message and the server's
  1225. // response.
  1226. Pkt4Ptr query = ex.getQuery();
  1227. Pkt4Ptr response = ex.getResponse();
  1228. // For the non-relayed message, the destination port is the client's port.
  1229. // For the relayed message, the server/relay port is a destination.
  1230. // Note that the call to this function may throw if invalid combination
  1231. // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
  1232. // giaddr != 0). The exception will propagate down and eventually cause the
  1233. // packet to be discarded.
  1234. response->setRemotePort(query->isRelayed() ? DHCP4_SERVER_PORT :
  1235. DHCP4_CLIENT_PORT);
  1236. IOAddress local_addr = query->getLocalAddr();
  1237. // In many cases the query is sent to a broadcast address. This address
  1238. // apears as a local address in the query message. We can't simply copy
  1239. // this address to a response message and use it as a source address.
  1240. // Instead we will need to use the address assigned to the interface
  1241. // on which the query has been received. In other cases, we will just
  1242. // use this address as a source address for the response.
  1243. if (local_addr == IOAddress::IPV4_BCAST_ADDRESS()) {
  1244. SocketInfo sock_info = IfaceMgr::instance().getSocket(*query);
  1245. local_addr = sock_info.addr_;
  1246. }
  1247. // We assume that there is an appropriate socket bound to this address
  1248. // and that the address is correct. This is safe assumption because
  1249. // the local address of the query is set when the query is received.
  1250. // The query sent to an incorrect address wouldn't have been received.
  1251. // However, if socket is closed for this address between the reception
  1252. // of the query and sending a response, the IfaceMgr should detect it
  1253. // and return an error.
  1254. response->setLocalAddr(local_addr);
  1255. // In many cases the query is sent to a broadcast address. This address
  1256. // appears as a local address in the query message. Therefore we can't
  1257. // simply copy local address from the query and use it as a source
  1258. // address for the response. Instead, we have to check what address our
  1259. // socket is bound to and use it as a source address. This operation
  1260. // may throw if for some reason the socket is closed.
  1261. /// @todo Consider an optimization that we use local address from
  1262. /// the query if this address is not broadcast.
  1263. response->setLocalPort(DHCP4_SERVER_PORT);
  1264. response->setIface(query->getIface());
  1265. response->setIndex(query->getIndex());
  1266. }
  1267. void
  1268. Dhcpv4Srv::adjustRemoteAddr(Dhcpv4Exchange& ex) {
  1269. // Initialize the pointers to the client's message and the server's
  1270. // response.
  1271. Pkt4Ptr query = ex.getQuery();
  1272. Pkt4Ptr response = ex.getResponse();
  1273. // The DHCPINFORM is slightly different than other messages in a sense
  1274. // that the server should always unicast the response to the ciaddr.
  1275. // It appears however that some clients don't set the ciaddr. We still
  1276. // want to provision these clients and we do what we can't to send the
  1277. // packet to the address where client can receive it.
  1278. if (query->getType() == DHCPINFORM) {
  1279. // If client adheres to RFC2131 it will set the ciaddr and in this
  1280. // case we always unicast our response to this address.
  1281. if (query->getCiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1282. response->setRemoteAddr(query->getCiaddr());
  1283. // If we received DHCPINFORM via relay and the ciaddr is not set we
  1284. // will try to send the response via relay. The caveat is that the
  1285. // relay will not have any idea where to forward the packet because
  1286. // the yiaddr is likely not set. So, the broadcast flag is set so
  1287. // as the response may be broadcast.
  1288. } else if (query->isRelayed()) {
  1289. response->setRemoteAddr(query->getGiaddr());
  1290. response->setFlags(response->getFlags() | BOOTP_BROADCAST);
  1291. // If there is no ciaddr and no giaddr the only thing we can do is
  1292. // to use the source address of the packet.
  1293. } else {
  1294. response->setRemoteAddr(query->getRemoteAddr());
  1295. }
  1296. // Remote address is now set so return.
  1297. return;
  1298. }
  1299. // If received relayed message, server responds to the relay address.
  1300. if (query->isRelayed()) {
  1301. // The client should set the ciaddr when sending the DHCPINFORM
  1302. // but in case he didn't, the relay may not be able to determine the
  1303. // address of the client, because yiaddr is not set when responding
  1304. // to Confirm and the only address available was the source address
  1305. // of the client. The source address is however not used here because
  1306. // the message is relayed. Therefore, we set the BROADCAST flag so
  1307. // as the relay can broadcast the packet.
  1308. if ((query->getType() == DHCPINFORM) &&
  1309. (query->getCiaddr() == IOAddress::IPV4_ZERO_ADDRESS())) {
  1310. response->setFlags(BOOTP_BROADCAST);
  1311. }
  1312. response->setRemoteAddr(query->getGiaddr());
  1313. // If giaddr is 0 but client set ciaddr, server should unicast the
  1314. // response to ciaddr.
  1315. } else if (query->getCiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1316. response->setRemoteAddr(query->getCiaddr());
  1317. // We can't unicast the response to the client when sending NAK,
  1318. // because we haven't allocated address for him. Therefore,
  1319. // NAK is broadcast.
  1320. } else if (response->getType() == DHCPNAK) {
  1321. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1322. // If yiaddr is set it means that we have created a lease for a client.
  1323. } else if (response->getYiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1324. // If the broadcast bit is set in the flags field, we have to
  1325. // send the response to broadcast address. Client may have requested it
  1326. // because it doesn't support reception of messages on the interface
  1327. // which doesn't have an address assigned. The other case when response
  1328. // must be broadcasted is when our server does not support responding
  1329. // directly to a client without address assigned.
  1330. const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
  1331. if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
  1332. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1333. // Client cleared the broadcast bit and we support direct responses
  1334. // so we should unicast the response to a newly allocated address -
  1335. // yiaddr.
  1336. } else {
  1337. response->setRemoteAddr(response ->getYiaddr());
  1338. }
  1339. // In most cases, we should have the remote address found already. If we
  1340. // found ourselves at this point, the rational thing to do is to respond
  1341. // to the address we got the query from.
  1342. } else {
  1343. response->setRemoteAddr(query->getRemoteAddr());
  1344. }
  1345. }
  1346. OptionPtr
  1347. Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
  1348. uint32_t netmask = getNetmask4(subnet->get().second);
  1349. OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
  1350. DHO_SUBNET_MASK, netmask));
  1351. return (opt);
  1352. }
  1353. Pkt4Ptr
  1354. Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
  1355. sanityCheck(discover, FORBIDDEN);
  1356. Dhcpv4Exchange ex(alloc_engine_, discover, selectSubnet(discover));
  1357. // If DHCPDISCOVER message contains the FQDN or Hostname option, server
  1358. // may respond to the client with the appropriate FQDN or Hostname
  1359. // option to indicate that whether it will take responsibility for
  1360. // updating DNS when the client sends DHCPREQUEST message.
  1361. processClientName(ex);
  1362. assignLease(ex);
  1363. if (!ex.getResponse()) {
  1364. // The offer is empty so return it *now*!
  1365. return (Pkt4Ptr());
  1366. }
  1367. // Adding any other options makes sense only when we got the lease.
  1368. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1369. appendRequestedOptions(ex);
  1370. appendRequestedVendorOptions(ex);
  1371. // There are a few basic options that we always want to
  1372. // include in the response. If client did not request
  1373. // them we append them for him.
  1374. appendBasicOptions(ex);
  1375. } else {
  1376. // If the server can't offer an address, it drops the packet.
  1377. return (Pkt4Ptr());
  1378. }
  1379. // Set the src/dest IP address, port and interface for the outgoing
  1380. // packet.
  1381. adjustIfaceData(ex);
  1382. appendServerID(ex);
  1383. /// @todo: decide whether we want to add a new hook point for
  1384. /// doing class specific processing.
  1385. if (!classSpecificProcessing(ex)) {
  1386. /// @todo add more verbosity here
  1387. LOG_DEBUG(options_logger, DBG_DHCP4_DETAIL, DHCP4_DISCOVER_CLASS_PROCESSING_FAILED)
  1388. .arg(discover->getLabel());
  1389. }
  1390. return (ex.getResponse());
  1391. }
  1392. Pkt4Ptr
  1393. Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
  1394. /// @todo Uncomment this (see ticket #3116)
  1395. /// sanityCheck(request, MANDATORY);
  1396. Dhcpv4Exchange ex(alloc_engine_, request, selectSubnet(request));
  1397. // If DHCPREQUEST message contains the FQDN or Hostname option, server
  1398. // should respond to the client with the appropriate FQDN or Hostname
  1399. // option to indicate if it takes responsibility for the DNS updates.
  1400. // This is performed by the function below.
  1401. processClientName(ex);
  1402. // Note that we treat REQUEST message uniformly, regardless if this is a
  1403. // first request (requesting for new address), renewing existing address
  1404. // or even rebinding.
  1405. assignLease(ex);
  1406. if (!ex.getResponse()) {
  1407. // The ack is empty so return it *now*!
  1408. return (Pkt4Ptr());
  1409. }
  1410. // Adding any other options makes sense only when we got the lease.
  1411. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1412. appendRequestedOptions(ex);
  1413. appendRequestedVendorOptions(ex);
  1414. // There are a few basic options that we always want to
  1415. // include in the response. If client did not request
  1416. // them we append them for him.
  1417. appendBasicOptions(ex);
  1418. }
  1419. // Set the src/dest IP address, port and interface for the outgoing
  1420. // packet.
  1421. adjustIfaceData(ex);
  1422. appendServerID(ex);
  1423. /// @todo: decide whether we want to add a new hook point for
  1424. /// doing class specific processing.
  1425. if (!classSpecificProcessing(ex)) {
  1426. /// @todo add more verbosity here
  1427. LOG_DEBUG(options_logger, DBG_DHCP4_DETAIL, DHCP4_REQUEST_CLASS_PROCESSING_FAILED)
  1428. .arg(ex.getQuery()->getLabel());
  1429. }
  1430. return (ex.getResponse());
  1431. }
  1432. void
  1433. Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
  1434. /// @todo Uncomment this (see ticket #3116)
  1435. /// sanityCheck(release, MANDATORY);
  1436. // Try to find client-id
  1437. ClientIdPtr client_id;
  1438. OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1439. if (opt) {
  1440. client_id = ClientIdPtr(new ClientId(opt->getData()));
  1441. }
  1442. try {
  1443. // Do we have a lease for that particular address?
  1444. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
  1445. if (!lease) {
  1446. // No such lease - bogus release
  1447. LOG_DEBUG(lease_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_NO_LEASE)
  1448. .arg(release->getLabel())
  1449. .arg(release->getCiaddr().toText());
  1450. return;
  1451. }
  1452. // Does the hardware address match? We don't want one client releasing
  1453. // another client's leases. Note that we're comparing the hardware
  1454. // addresses only, not hardware types or sources of the hardware
  1455. // addresses. Thus we don't use HWAddr::equals().
  1456. if (lease->hwaddr_->hwaddr_ != release->getHWAddr()->hwaddr_) {
  1457. LOG_DEBUG(lease_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_HWADDR)
  1458. .arg(release->getLabel())
  1459. .arg(release->getCiaddr().toText())
  1460. .arg(lease->hwaddr_->toText(false));
  1461. return;
  1462. }
  1463. // Does the lease have client-id info? If it has, then check it with what
  1464. // the client sent us.
  1465. if (lease->client_id_ && client_id && *lease->client_id_ != *client_id) {
  1466. LOG_DEBUG(lease_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT_ID)
  1467. .arg(release->getLabel())
  1468. .arg(release->getCiaddr().toText())
  1469. .arg(lease->client_id_->toText());
  1470. return;
  1471. }
  1472. bool skip = false;
  1473. // Execute all callouts registered for lease4_release
  1474. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
  1475. CalloutHandlePtr callout_handle = getCalloutHandle(release);
  1476. // Delete all previous arguments
  1477. callout_handle->deleteAllArguments();
  1478. // Pass the original packet
  1479. callout_handle->setArgument("query4", release);
  1480. // Pass the lease to be updated
  1481. callout_handle->setArgument("lease4", lease);
  1482. // Call all installed callouts
  1483. HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
  1484. *callout_handle);
  1485. // Callouts decided to skip the next processing step. The next
  1486. // processing step would to send the packet, so skip at this
  1487. // stage means "drop response".
  1488. if (callout_handle->getSkip()) {
  1489. skip = true;
  1490. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  1491. DHCP4_HOOK_LEASE4_RELEASE_SKIP)
  1492. .arg(release->getLabel());
  1493. }
  1494. }
  1495. // Callout didn't indicate to skip the release process. Let's release
  1496. // the lease.
  1497. if (!skip) {
  1498. bool success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1499. if (success) {
  1500. // Release successful
  1501. LOG_DEBUG(lease_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE)
  1502. .arg(release->getLabel())
  1503. .arg(lease->addr_.toText());
  1504. if (CfgMgr::instance().ddnsEnabled()) {
  1505. // Remove existing DNS entries for the lease, if any.
  1506. queueNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE, lease);
  1507. }
  1508. } else {
  1509. // Release failed
  1510. LOG_ERROR(lease_logger, DHCP4_RELEASE_FAIL)
  1511. .arg(release->getLabel())
  1512. .arg(lease->addr_.toText());
  1513. }
  1514. }
  1515. } catch (const isc::Exception& ex) {
  1516. LOG_ERROR(lease_logger, DHCP4_RELEASE_EXCEPTION)
  1517. .arg(release->getLabel())
  1518. .arg(release->getCiaddr())
  1519. .arg(ex.what());
  1520. }
  1521. }
  1522. void
  1523. Dhcpv4Srv::processDecline(Pkt4Ptr&) {
  1524. /// @todo Implement this (also see ticket #3116)
  1525. }
  1526. Pkt4Ptr
  1527. Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
  1528. // DHCPINFORM MUST not include server identifier.
  1529. sanityCheck(inform, FORBIDDEN);
  1530. Dhcpv4Exchange ex(alloc_engine_, inform, selectSubnet(inform));
  1531. Pkt4Ptr ack = ex.getResponse();
  1532. appendRequestedOptions(ex);
  1533. appendRequestedVendorOptions(ex);
  1534. appendBasicOptions(ex);
  1535. adjustIfaceData(ex);
  1536. // There are cases for the DHCPINFORM that the server receives it via
  1537. // relay but will send the response to the client's unicast address
  1538. // carried in the ciaddr. In this case, the giaddr and hops field should
  1539. // be cleared (these fields were copied by the copyDefaultFields function).
  1540. // Also Relay Agent Options should be removed if present.
  1541. if (ack->getRemoteAddr() != inform->getGiaddr()) {
  1542. LOG_DEBUG(packet_logger, DBG_DHCP4_DETAIL, DHCP4_INFORM_DIRECT_REPLY)
  1543. .arg(inform->getLabel())
  1544. .arg(ack->getRemoteAddr())
  1545. .arg(ack->getIface());
  1546. ack->setHops(0);
  1547. ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1548. ack->delOption(DHO_DHCP_AGENT_OPTIONS);
  1549. }
  1550. // The DHCPACK must contain server id.
  1551. appendServerID(ex);
  1552. /// @todo: decide whether we want to add a new hook point for
  1553. /// doing class specific processing.
  1554. if (!classSpecificProcessing(ex)) {
  1555. LOG_DEBUG(options_logger, DBG_DHCP4_DETAIL,
  1556. DHCP4_INFORM_CLASS_PROCESSING_FAILED)
  1557. .arg(inform->getLabel());
  1558. }
  1559. return (ex.getResponse());
  1560. }
  1561. bool
  1562. Dhcpv4Srv::accept(const Pkt4Ptr& query) const {
  1563. // Check that the message type is accepted by the server. We rely on the
  1564. // function called to log a message if needed.
  1565. if (!acceptMessageType(query)) {
  1566. return (false);
  1567. }
  1568. // Check if the message from directly connected client (if directly
  1569. // connected) should be dropped or processed.
  1570. if (!acceptDirectRequest(query)) {
  1571. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0002)
  1572. .arg(query->getLabel())
  1573. .arg(query->getIface());
  1574. return (false);
  1575. }
  1576. // Check if the DHCPv4 packet has been sent to us or to someone else.
  1577. // If it hasn't been sent to us, drop it!
  1578. if (!acceptServerId(query)) {
  1579. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0003)
  1580. .arg(query->getLabel())
  1581. .arg(query->getIface());
  1582. return (false);
  1583. }
  1584. return (true);
  1585. }
  1586. bool
  1587. Dhcpv4Srv::acceptDirectRequest(const Pkt4Ptr& pkt) const {
  1588. // Accept all relayed messages.
  1589. if (pkt->isRelayed()) {
  1590. return (true);
  1591. }
  1592. // The source address must not be zero for the DHCPINFORM message from
  1593. // the directly connected client because the server will not know where
  1594. // to respond if the ciaddr was not present.
  1595. try {
  1596. if (pkt->getType() == DHCPINFORM) {
  1597. if ((pkt->getRemoteAddr() == IOAddress::IPV4_ZERO_ADDRESS()) &&
  1598. (pkt->getCiaddr() == IOAddress::IPV4_ZERO_ADDRESS())) {
  1599. return (false);
  1600. }
  1601. }
  1602. } catch (...) {
  1603. // If we got here, it is probably because the message type hasn't
  1604. // been set. But, this should not really happen assuming that
  1605. // we validate the message type prior to calling this function.
  1606. return (false);
  1607. }
  1608. return ((pkt->getLocalAddr() != IOAddress::IPV4_BCAST_ADDRESS()
  1609. || selectSubnet(pkt)));
  1610. }
  1611. bool
  1612. Dhcpv4Srv::acceptMessageType(const Pkt4Ptr& query) const {
  1613. // When receiving a packet without message type option, getType() will
  1614. // throw.
  1615. int type;
  1616. try {
  1617. type = query->getType();
  1618. } catch (...) {
  1619. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0004)
  1620. .arg(query->getLabel())
  1621. .arg(query->getIface());
  1622. return (false);
  1623. }
  1624. // If we receive a message with a non-existing type, we are logging it.
  1625. if (type > DHCPLEASEQUERYDONE) {
  1626. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0005)
  1627. .arg(query->getLabel())
  1628. .arg(type);
  1629. return (false);
  1630. }
  1631. // Once we know that the message type is within a range of defined DHCPv4
  1632. // messages, we do a detailed check to make sure that the received message
  1633. // is targeted at server. Note that we could have received some Offer
  1634. // message broadcasted by the other server to a relay. Even though, the
  1635. // server would rather unicast its response to a relay, let's be on the
  1636. // safe side. Also, we want to drop other messages which we don't support.
  1637. // All these valid messages that we are not going to process are dropped
  1638. // silently.
  1639. if ((type != DHCPDISCOVER) && (type != DHCPREQUEST) &&
  1640. (type != DHCPRELEASE) && (type != DHCPDECLINE) &&
  1641. (type != DHCPINFORM)) {
  1642. LOG_DEBUG(bad_packet_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0006)
  1643. .arg(query->getLabel())
  1644. .arg(type);
  1645. return (false);
  1646. }
  1647. return (true);
  1648. }
  1649. bool
  1650. Dhcpv4Srv::acceptServerId(const Pkt4Ptr& query) const {
  1651. // This function is meant to be called internally by the server class, so
  1652. // we rely on the caller to sanity check the pointer and we don't check
  1653. // it here.
  1654. // Check if server identifier option is present. If it is not present
  1655. // we accept the message because it is targeted to all servers.
  1656. // Note that we don't check cases that server identifier is mandatory
  1657. // but not present. This is meant to be sanity checked in other
  1658. // functions.
  1659. OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1660. if (!option) {
  1661. return (true);
  1662. }
  1663. // Server identifier is present. Let's convert it to 4-byte address
  1664. // and try to match with server identifiers used by the server.
  1665. OptionCustomPtr option_custom =
  1666. boost::dynamic_pointer_cast<OptionCustom>(option);
  1667. // Unable to convert the option to the option type which encapsulates it.
  1668. // We treat this as non-matching server id.
  1669. if (!option_custom) {
  1670. return (false);
  1671. }
  1672. // The server identifier option should carry exactly one IPv4 address.
  1673. // If the option definition for the server identifier doesn't change,
  1674. // the OptionCustom object should have exactly one IPv4 address and
  1675. // this check is somewhat redundant. On the other hand, if someone
  1676. // breaks option it may be better to check that here.
  1677. if (option_custom->getDataFieldsNum() != 1) {
  1678. return (false);
  1679. }
  1680. // The server identifier MUST be an IPv4 address. If given address is
  1681. // v6, it is wrong.
  1682. IOAddress server_id = option_custom->readAddress();
  1683. if (!server_id.isV4()) {
  1684. return (false);
  1685. }
  1686. // This function iterates over all interfaces on which the
  1687. // server is listening to find the one which has a socket bound
  1688. // to the address carried in the server identifier option.
  1689. // This has some performance implications. However, given that
  1690. // typically there will be just a few active interfaces the
  1691. // performance hit should be acceptable. If it turns out to
  1692. // be significant, we will have to cache server identifiers
  1693. // when sockets are opened.
  1694. return (IfaceMgr::instance().hasOpenSocket(server_id));
  1695. }
  1696. void
  1697. Dhcpv4Srv::sanityCheck(const Pkt4Ptr& query, RequirementLevel serverid) {
  1698. OptionPtr server_id = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1699. switch (serverid) {
  1700. case FORBIDDEN:
  1701. if (server_id) {
  1702. isc_throw(RFCViolation, "Server-id option was not expected, but "
  1703. << "received in "
  1704. << query->getName());
  1705. }
  1706. break;
  1707. case MANDATORY:
  1708. if (!server_id) {
  1709. isc_throw(RFCViolation, "Server-id option was expected, but not "
  1710. " received in message "
  1711. << query->getName());
  1712. }
  1713. break;
  1714. case OPTIONAL:
  1715. // do nothing here
  1716. ;
  1717. }
  1718. // If there is HWAddress set and it is non-empty, then we're good
  1719. if (query->getHWAddr() && !query->getHWAddr()->hwaddr_.empty()) {
  1720. return;
  1721. }
  1722. // There has to be something to uniquely identify the client:
  1723. // either non-zero MAC address or client-id option present (or both)
  1724. OptionPtr client_id = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1725. // If there's no client-id (or a useless one is provided, i.e. 0 length)
  1726. if (!client_id || client_id->len() == client_id->getHeaderLen()) {
  1727. isc_throw(RFCViolation, "Missing or useless client-id and no HW address "
  1728. " provided in message "
  1729. << query->getName());
  1730. }
  1731. }
  1732. size_t
  1733. Dhcpv4Srv::unpackOptions(const OptionBuffer& buf,
  1734. const std::string& option_space,
  1735. isc::dhcp::OptionCollection& options) {
  1736. size_t offset = 0;
  1737. OptionDefContainer option_defs;
  1738. if (option_space == "dhcp4") {
  1739. // Get the list of standard option definitions.
  1740. option_defs = LibDHCP::getOptionDefs(Option::V4);
  1741. } else if (!option_space.empty()) {
  1742. OptionDefContainerPtr option_defs_ptr = CfgMgr::instance()
  1743. .getCurrentCfg()->getCfgOptionDef()->getAll(option_space);
  1744. if (option_defs_ptr != NULL) {
  1745. option_defs = *option_defs_ptr;
  1746. }
  1747. }
  1748. // Get the search index #1. It allows to search for option definitions
  1749. // using option code.
  1750. const OptionDefContainerTypeIndex& idx = option_defs.get<1>();
  1751. // The buffer being read comprises a set of options, each starting with
  1752. // a one-byte type code and a one-byte length field.
  1753. while (offset + 1 <= buf.size()) {
  1754. uint8_t opt_type = buf[offset++];
  1755. // DHO_END is a special, one octet long option
  1756. if (opt_type == DHO_END)
  1757. return (offset); // just return. Don't need to add DHO_END option
  1758. // DHO_PAD is just a padding after DHO_END. Let's continue parsing
  1759. // in case we receive a message without DHO_END.
  1760. if (opt_type == DHO_PAD)
  1761. continue;
  1762. if (offset + 1 > buf.size()) {
  1763. // opt_type must be cast to integer so as it is not treated as
  1764. // unsigned char value (a number is presented in error message).
  1765. isc_throw(OutOfRange, "Attempt to parse truncated option "
  1766. << static_cast<int>(opt_type));
  1767. }
  1768. uint8_t opt_len = buf[offset++];
  1769. if (offset + opt_len > buf.size()) {
  1770. // We peeked at the option header of the next option, but discovered
  1771. // that it would end up beyond buffer end, so the option is
  1772. // truncated. Hence we can't parse it. Therefore we revert
  1773. // back by two bytes (as if we never parsed them).
  1774. return (offset - 2);
  1775. // isc_throw(OutOfRange, "Option parse failed. Tried to parse "
  1776. // << offset + opt_len << " bytes from " << buf.size()
  1777. // << "-byte long buffer.");
  1778. }
  1779. // Get all definitions with the particular option code. Note that option code
  1780. // is non-unique within this container however at this point we expect
  1781. // to get one option definition with the particular code. If more are
  1782. // returned we report an error.
  1783. const OptionDefContainerTypeRange& range = idx.equal_range(opt_type);
  1784. // Get the number of returned option definitions for the option code.
  1785. size_t num_defs = distance(range.first, range.second);
  1786. OptionPtr opt;
  1787. if (num_defs > 1) {
  1788. // Multiple options of the same code are not supported right now!
  1789. isc_throw(isc::Unexpected, "Internal error: multiple option definitions"
  1790. " for option type " << static_cast<int>(opt_type)
  1791. << " returned. Currently it is not supported to initialize"
  1792. << " multiple option definitions for the same option code."
  1793. << " This will be supported once support for option spaces"
  1794. << " is implemented");
  1795. } else if (num_defs == 0) {
  1796. opt = OptionPtr(new Option(Option::V4, opt_type,
  1797. buf.begin() + offset,
  1798. buf.begin() + offset + opt_len));
  1799. opt->setEncapsulatedSpace("dhcp4");
  1800. } else {
  1801. // The option definition has been found. Use it to create
  1802. // the option instance from the provided buffer chunk.
  1803. const OptionDefinitionPtr& def = *(range.first);
  1804. assert(def);
  1805. opt = def->optionFactory(Option::V4, opt_type,
  1806. buf.begin() + offset,
  1807. buf.begin() + offset + opt_len,
  1808. boost::bind(&Dhcpv4Srv::unpackOptions,
  1809. this, _1, _2, _3));
  1810. }
  1811. options.insert(std::make_pair(opt_type, opt));
  1812. offset += opt_len;
  1813. }
  1814. return (offset);
  1815. }
  1816. void Dhcpv4Srv::classifyPacket(const Pkt4Ptr& pkt) {
  1817. boost::shared_ptr<OptionString> vendor_class =
  1818. boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
  1819. string classes = "";
  1820. if (!vendor_class) {
  1821. return;
  1822. }
  1823. // DOCSIS specific section
  1824. // Let's keep this as a series of checks. So far we're supporting only
  1825. // docsis3.0, but there are also docsis2.0, docsis1.1 and docsis1.0. We
  1826. // may come up with adding several classes, e.g. for docsis2.0 we would
  1827. // add classes docsis2.0, docsis1.1 and docsis1.0.
  1828. // Also we are using find, because we have at least one traffic capture
  1829. // where the user class was followed by a space ("docsis3.0 ").
  1830. // For now, the code is very simple, but it is expected to get much more
  1831. // complex soon. One specific case is that the vendor class is an option
  1832. // sent by the client, so we should not trust it. To confirm that the device
  1833. // is indeed a modem, John B. suggested to check whether chaddr field
  1834. // quals subscriber-id option that was inserted by the relay (CMTS).
  1835. // This kind of logic will appear here soon.
  1836. if (vendor_class->getValue().find(DOCSIS3_CLASS_MODEM) != std::string::npos) {
  1837. pkt->addClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM);
  1838. classes += string(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM) + " ";
  1839. } else
  1840. if (vendor_class->getValue().find(DOCSIS3_CLASS_EROUTER) != std::string::npos) {
  1841. pkt->addClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER);
  1842. classes += string(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER) + " ";
  1843. } else {
  1844. classes += VENDOR_CLASS_PREFIX + vendor_class->getValue();
  1845. pkt->addClass(VENDOR_CLASS_PREFIX + vendor_class->getValue());
  1846. }
  1847. if (!classes.empty()) {
  1848. LOG_DEBUG(options_logger, DBG_DHCP4_BASIC, DHCP4_CLASS_ASSIGNED)
  1849. .arg(pkt->getLabel())
  1850. .arg(classes);
  1851. }
  1852. }
  1853. bool
  1854. Dhcpv4Srv::classSpecificProcessing(const Dhcpv4Exchange& ex) {
  1855. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1856. Pkt4Ptr query = ex.getQuery();
  1857. Pkt4Ptr rsp = ex.getResponse();
  1858. // If any of those is missing, there is nothing to do.
  1859. if (!subnet || !query || !rsp) {
  1860. return (true);
  1861. }
  1862. if (query->inClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM)) {
  1863. // Set next-server. This is TFTP server address. Cable modems will
  1864. // download their configuration from that server.
  1865. rsp->setSiaddr(subnet->getSiaddr());
  1866. // Now try to set up file field in DHCPv4 packet. We will just copy
  1867. // content of the boot-file option, which contains the same information.
  1868. OptionDescriptor desc = subnet->getCfgOption()->
  1869. get("dhcp4", DHO_BOOT_FILE_NAME);
  1870. if (desc.option_) {
  1871. boost::shared_ptr<OptionString> boot =
  1872. boost::dynamic_pointer_cast<OptionString>(desc.option_);
  1873. if (boot) {
  1874. std::string filename = boot->getValue();
  1875. rsp->setFile((const uint8_t*)filename.c_str(), filename.size());
  1876. }
  1877. }
  1878. }
  1879. if (query->inClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER)) {
  1880. // Do not set TFTP server address for eRouter devices.
  1881. rsp->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1882. }
  1883. return (true);
  1884. }
  1885. void
  1886. Dhcpv4Srv::startD2() {
  1887. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1888. if (d2_mgr.ddnsEnabled()) {
  1889. // Updates are enabled, so lets start the sender, passing in
  1890. // our error handler.
  1891. // This may throw so wherever this is called needs to ready.
  1892. d2_mgr.startSender(boost::bind(&Dhcpv4Srv::d2ClientErrorHandler,
  1893. this, _1, _2));
  1894. }
  1895. }
  1896. void
  1897. Dhcpv4Srv::d2ClientErrorHandler(const
  1898. dhcp_ddns::NameChangeSender::Result result,
  1899. dhcp_ddns::NameChangeRequestPtr& ncr) {
  1900. LOG_ERROR(ddns_logger, DHCP4_DDNS_REQUEST_SEND_FAILED).
  1901. arg(result).arg((ncr ? ncr->toText() : " NULL "));
  1902. // We cannot communicate with kea-dhcp-ddns, suspend further updates.
  1903. /// @todo We may wish to revisit this, but for now we will simply turn
  1904. /// them off.
  1905. CfgMgr::instance().getD2ClientMgr().suspendUpdates();
  1906. }
  1907. std::string
  1908. Daemon::getVersion(bool extended) {
  1909. std::stringstream tmp;
  1910. tmp << VERSION;
  1911. if (extended) {
  1912. tmp << endl << EXTENDED_VERSION;
  1913. // @todo print more details (is it Botan or OpenSSL build,
  1914. // with or without MySQL/Postgres? What compilation options were
  1915. // used? etc)
  1916. }
  1917. return (tmp.str());
  1918. }
  1919. void Dhcpv4Srv::processStatsReceived(const Pkt4Ptr& query) {
  1920. // Note that we're not bumping pkt4-received statistic as it was
  1921. // increased early in the packet reception code.
  1922. string stat_name = "pkt4-unknown-received";
  1923. try {
  1924. switch (query->getType()) {
  1925. case DHCPDISCOVER:
  1926. stat_name = "pkt4-discover-received";
  1927. break;
  1928. case DHCPOFFER:
  1929. // should not happen, but we'll keep a counter for it anyway
  1930. stat_name = "pkt4-offer-received";
  1931. break;
  1932. case DHCPREQUEST:
  1933. stat_name = "pkt4-request-received";
  1934. break;
  1935. case DHCPACK:
  1936. stat_name = "pkt4-ack-received";
  1937. break;
  1938. case DHCPNAK:
  1939. stat_name = "pkt4-nak-received";
  1940. break;
  1941. case DHCPRELEASE:
  1942. stat_name = "pkt4-release-received";
  1943. break;
  1944. case DHCPDECLINE:
  1945. stat_name = "pkt4-decline-received";
  1946. break;
  1947. case DHCPINFORM:
  1948. stat_name = "pkt4-inform-received";
  1949. break;
  1950. default:
  1951. ; // do nothing
  1952. }
  1953. }
  1954. catch (...) {
  1955. // If the incoming packet doesn't have option 53 (message type)
  1956. // or a hook set pkt4_receive_skip, then Pkt4::getType() may
  1957. // throw an exception. That's ok, we'll then use the default
  1958. // name of pkt4-unknown-received.
  1959. }
  1960. isc::stats::StatsMgr::instance().addValue(stat_name,
  1961. static_cast<uint64_t>(1));
  1962. }
  1963. void Dhcpv4Srv::processStatsSent(const Pkt4Ptr& response) {
  1964. // Increase generic counter for sent packets.
  1965. isc::stats::StatsMgr::instance().addValue("pkt4-sent", 1ul);
  1966. // Increase packet type specific counter for packets sent.
  1967. string stat_name;
  1968. switch (response->getType()) {
  1969. case DHCPOFFER:
  1970. // should not happen, but we'll keep a counter for it anyway
  1971. stat_name = "pkt4-offer-sent";
  1972. break;
  1973. case DHCPACK:
  1974. stat_name = "pkt4-ack-sent";
  1975. break;
  1976. case DHCPNAK:
  1977. stat_name = "pkt4-nak-sent";
  1978. break;
  1979. default:
  1980. // That should never happen
  1981. return;
  1982. }
  1983. isc::stats::StatsMgr::instance().addValue(stat_name, 1ul);
  1984. }
  1985. } // namespace dhcp
  1986. } // namespace isc