Kea 2.7.7
dhcp4_srv.cc
Go to the documentation of this file.
1// Copyright (C) 2011-2025 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8#include <kea_version.h>
9
11#include <asiolink/io_address.h>
12#include <asiolink/io_service.h>
14#include <cc/data.h>
17#include <dhcp/classify.h>
18#include <dhcp/dhcp4.h>
20#include <dhcp/duid.h>
21#include <dhcp/hwaddr.h>
22#include <dhcp/iface_mgr.h>
23#include <dhcp/libdhcp++.h>
24#include <dhcp/option.h>
27#include <dhcp/option_custom.h>
30#include <dhcp/option_int.h>
32#include <dhcp/option_string.h>
33#include <dhcp/option_vendor.h>
35#include <dhcp/pkt.h>
36#include <dhcp/pkt4.h>
37#include <dhcp/pkt4o6.h>
38#include <dhcp/socket_info.h>
41#include <dhcp4/dhcp4_log.h>
42#include <dhcp4/dhcp4_srv.h>
43#include <dhcp4/dhcp4to6_ipc.h>
44#include <dhcp_ddns/ncr_io.h>
45#include <dhcp_ddns/ncr_msg.h>
51#include <dhcpsrv/cfg_globals.h>
53#include <dhcpsrv/cfg_iface.h>
54#include <dhcpsrv/cfg_option.h>
57#include <dhcpsrv/cfgmgr.h>
62#include <dhcpsrv/host.h>
64#include <dhcpsrv/host_mgr.h>
65#include <dhcpsrv/lease.h>
70#include <dhcpsrv/pool.h>
73#include <dhcpsrv/srv_config.h>
74#include <dhcpsrv/subnet.h>
75#include <dhcpsrv/subnet_id.h>
77#include <dhcpsrv/utils.h>
78#include <eval/evaluate.h>
79#include <eval/token.h>
82#include <hooks/hooks_log.h>
83#include <hooks/hooks_manager.h>
84#include <hooks/parking_lots.h>
85#include <hooks/server_hooks.h>
87#include <log/log_dbglevels.h>
88#include <log/log_formatter.h>
89#include <log/logger.h>
90#include <log/macros.h>
91#include <stats/stats_mgr.h>
93#include <util/optional.h>
95#include <util/thread_pool.h>
96#include <util/triplet.h>
97
98#include <algorithm>
99#include <cmath>
100#include <cstdint>
101#include <cstdlib>
102#include <exception>
103#include <functional>
104#include <list>
105#include <map>
106#include <memory>
107#include <set>
108#include <sstream>
109#include <string>
110#include <tuple>
111#include <utility>
112#include <vector>
113
114#include <boost/foreach.hpp>
115#include <boost/pointer_cast.hpp>
116#include <boost/range/adaptor/reversed.hpp>
117#include <boost/shared_ptr.hpp>
118
119using namespace isc;
120using namespace isc::asiolink;
121using namespace isc::cryptolink;
122using namespace isc::data;
123using namespace isc::dhcp;
124using namespace isc::dhcp_ddns;
125using namespace isc::hooks;
126using namespace isc::log;
127using namespace isc::log::interprocess;
128using namespace isc::stats;
129using namespace isc::util;
130using namespace std;
131namespace ph = std::placeholders;
132
133namespace {
134
136struct Dhcp4Hooks {
137 int hook_index_buffer4_receive_;
138 int hook_index_pkt4_receive_;
139 int hook_index_subnet4_select_;
140 int hook_index_leases4_committed_;
141 int hook_index_lease4_release_;
142 int hook_index_pkt4_send_;
143 int hook_index_buffer4_send_;
144 int hook_index_lease4_decline_;
145 int hook_index_host4_identifier_;
146 int hook_index_ddns4_update_;
147 int hook_index_lease4_offer_;
148 int hook_index_lease4_server_decline_;
149
151 Dhcp4Hooks() {
152 hook_index_buffer4_receive_ = HooksManager::registerHook("buffer4_receive");
153 hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
154 hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
155 hook_index_leases4_committed_ = HooksManager::registerHook("leases4_committed");
156 hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
157 hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
158 hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
159 hook_index_lease4_decline_ = HooksManager::registerHook("lease4_decline");
160 hook_index_host4_identifier_ = HooksManager::registerHook("host4_identifier");
161 hook_index_ddns4_update_ = HooksManager::registerHook("ddns4_update");
162 hook_index_lease4_offer_ = HooksManager::registerHook("lease4_offer");
163 hook_index_lease4_server_decline_ = HooksManager::registerHook("lease4_server_decline");
164 }
165};
166
169std::set<std::string> dhcp4_statistics = {
170 "pkt4-received",
171 "pkt4-discover-received",
172 "pkt4-offer-received",
173 "pkt4-request-received",
174 "pkt4-ack-received",
175 "pkt4-nak-received",
176 "pkt4-release-received",
177 "pkt4-decline-received",
178 "pkt4-inform-received",
179 "pkt4-unknown-received",
180 "pkt4-sent",
181 "pkt4-offer-sent",
182 "pkt4-ack-sent",
183 "pkt4-nak-sent",
184 "pkt4-parse-failed",
185 "pkt4-receive-drop",
186 "v4-allocation-fail",
187 "v4-allocation-fail-shared-network",
188 "v4-allocation-fail-subnet",
189 "v4-allocation-fail-no-pools",
190 "v4-allocation-fail-classes",
191 "v4-reservation-conflicts",
192 "v4-lease-reuses",
193};
194
195} // end of anonymous namespace
196
197// Declare a Hooks object. As this is outside any function or method, it
198// will be instantiated (and the constructor run) when the module is loaded.
199// As a result, the hook indexes will be defined before any method in this
200// module is called.
201Dhcp4Hooks Hooks;
202
203namespace isc {
204namespace dhcp {
205
207 const Pkt4Ptr& query,
209 const ConstSubnet4Ptr& subnet,
210 bool& drop)
211 : alloc_engine_(alloc_engine), query_(query), resp_(),
212 context_(context), ipv6_only_preferred_(false) {
213
214 if (!alloc_engine_) {
215 isc_throw(BadValue, "alloc_engine value must not be NULL"
216 " when creating an instance of the Dhcpv4Exchange");
217 }
218
219 if (!query_) {
220 isc_throw(BadValue, "query value must not be NULL when"
221 " creating an instance of the Dhcpv4Exchange");
222 }
223
224 // Reset the given context argument.
225 context.reset();
226
227 // Create response message.
228 initResponse();
229 // Select subnet for the query message.
230 context_->subnet_ = subnet;
231
232 // If subnet found, retrieve client identifier which will be needed
233 // for allocations and search for reservations associated with a
234 // subnet/shared network.
236 if (subnet && !context_->early_global_reservations_lookup_) {
237 OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
238 if (opt_clientid) {
239 context_->clientid_.reset(new ClientId(opt_clientid->getData()));
240 }
241 }
242
243 if (subnet) {
244 // Find static reservations if not disabled for our subnet.
245 if (subnet->getReservationsInSubnet() ||
246 subnet->getReservationsGlobal()) {
247 // Before we can check for static reservations, we need to prepare a set
248 // of identifiers to be used for this.
249 if (!context_->early_global_reservations_lookup_) {
250 setHostIdentifiers(context_);
251 }
252
253 // Check for static reservations.
254 alloc_engine->findReservation(*context_);
255
256 // Get shared network to see if it is set for a subnet.
257 subnet->getSharedNetwork(sn);
258 }
259 }
260
261 // Global host reservations are independent of a selected subnet. If the
262 // global reservations contain client classes we should use them in case
263 // they are meant to affect pool selection. Also, if the subnet does not
264 // belong to a shared network we can use the reserved client classes
265 // because there is no way our subnet could change. Such classes may
266 // affect selection of a pool within the selected subnet.
267 auto global_host = context_->globalHost();
268 auto current_host = context_->currentHost();
269 if ((!context_->early_global_reservations_lookup_ &&
270 global_host && !global_host->getClientClasses4().empty()) ||
271 (!sn && current_host && !current_host->getClientClasses4().empty())) {
272 // We have already evaluated client classes and some of them may
273 // be in conflict with the reserved classes. Suppose there are
274 // two classes defined in the server configuration: first_class
275 // and second_class and the test for the second_class it looks
276 // like this: "not member('first_class')". If the first_class
277 // initially evaluates to false, the second_class evaluates to
278 // true. If the first_class is now set within the hosts reservations
279 // and we don't remove the previously evaluated second_class we'd
280 // end up with both first_class and second_class evaluated to
281 // true. In order to avoid that, we have to remove the classes
282 // evaluated in the first pass and evaluate them again. As
283 // a result, the first_class set via the host reservation will
284 // replace the second_class because the second_class will this
285 // time evaluate to false as desired.
287 setReservedClientClasses(context_);
288 evaluateClasses(query, false);
289 }
290
291 // Set KNOWN builtin class if something was found, UNKNOWN if not.
292 if (!context_->hosts_.empty()) {
293 query->addClass("KNOWN");
295 .arg(query->getLabel())
296 .arg("KNOWN");
297 } else {
298 query->addClass("UNKNOWN");
300 .arg(query->getLabel())
301 .arg("UNKNOWN");
302 }
303
304 // Perform second pass of classification.
305 evaluateClasses(query, true);
306
307 const ClientClasses& classes = query_->getClasses();
309 .arg(query_->getLabel())
310 .arg(classes.toText());
311
312 // Check the DROP special class.
313 if (query_->inClass("DROP")) {
315 .arg(query_->getHWAddrLabel())
316 .arg(query_->toText());
317 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
318 static_cast<int64_t>(1));
319 drop = true;
320 }
321}
322
323void
325 uint8_t resp_type = 0;
326 switch (getQuery()->getType()) {
327 case DHCPDISCOVER:
328 resp_type = DHCPOFFER;
329 break;
330 case DHCPREQUEST:
331 case DHCPINFORM:
332 resp_type = DHCPACK;
333 break;
334 default:
335 ;
336 }
337 // Only create a response if one is required.
338 if (resp_type > 0) {
339 resp_.reset(new Pkt4(resp_type, getQuery()->getTransid()));
340 copyDefaultFields();
341 copyDefaultOptions();
342
343 if (getQuery()->isDhcp4o6()) {
345 }
346 }
347}
348
349void
351 Pkt4o6Ptr query = boost::dynamic_pointer_cast<Pkt4o6>(getQuery());
352 if (!query) {
353 return;
354 }
355 const Pkt6Ptr& query6 = query->getPkt6();
356 Pkt6Ptr resp6(new Pkt6(DHCPV6_DHCPV4_RESPONSE, query6->getTransid()));
357 // Don't add client-id or server-id
358 // But copy relay info
359 if (!query6->relay_info_.empty()) {
360 resp6->copyRelayInfo(query6);
361 }
362 // Copy interface, and remote address and port
363 resp6->setIface(query6->getIface());
364 resp6->setIndex(query6->getIndex());
365 resp6->setRemoteAddr(query6->getRemoteAddr());
366 resp6->setRemotePort(query6->getRemotePort());
367 resp_.reset(new Pkt4o6(resp_, resp6));
368}
369
370void
371Dhcpv4Exchange::copyDefaultFields() {
372 resp_->setIface(query_->getIface());
373 resp_->setIndex(query_->getIndex());
374
375 // explicitly set this to 0
376 resp_->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
377 // ciaddr is always 0, except for the Renew/Rebind state and for
378 // Inform when it may be set to the ciaddr sent by the client.
379 if (query_->getType() == DHCPINFORM) {
380 resp_->setCiaddr(query_->getCiaddr());
381 } else {
382 resp_->setCiaddr(IOAddress::IPV4_ZERO_ADDRESS());
383 }
384 resp_->setHops(query_->getHops());
385
386 // copy MAC address
387 resp_->setHWAddr(query_->getHWAddr());
388
389 // relay address
390 resp_->setGiaddr(query_->getGiaddr());
391
392 // If src/dest HW addresses are used by the packet filtering class
393 // we need to copy them as well. There is a need to check that the
394 // address being set is not-NULL because an attempt to set the NULL
395 // HW would result in exception. If these values are not set, the
396 // the default HW addresses (zeroed) should be generated by the
397 // packet filtering class when creating Ethernet header for
398 // outgoing packet.
399 HWAddrPtr src_hw_addr = query_->getLocalHWAddr();
400 if (src_hw_addr) {
401 resp_->setLocalHWAddr(src_hw_addr);
402 }
403 HWAddrPtr dst_hw_addr = query_->getRemoteHWAddr();
404 if (dst_hw_addr) {
405 resp_->setRemoteHWAddr(dst_hw_addr);
406 }
407
408 // Copy flags from the request to the response per RFC 2131
409 resp_->setFlags(query_->getFlags());
410}
411
412void
413Dhcpv4Exchange::copyDefaultOptions() {
414 // Let's copy client-id to response. See RFC6842.
415 // It is possible to disable RFC6842 to keep backward compatibility
416 bool echo = CfgMgr::instance().getCurrentCfg()->getEchoClientId();
417 OptionPtr client_id = query_->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
418 if (client_id && echo) {
419 resp_->addOption(client_id);
420 }
421
422 // RFC 3011 states about the Subnet Selection Option
423
424 // "Servers configured to support this option MUST return an
425 // identical copy of the option to any client that sends it,
426 // regardless of whether or not the client requests the option in
427 // a parameter request list. Clients using this option MUST
428 // discard DHCPOFFER or DHCPACK packets that do not contain this
429 // option."
430 OptionPtr subnet_sel = query_->getOption(DHO_SUBNET_SELECTION);
431 if (subnet_sel) {
432 resp_->addOption(subnet_sel);
433 }
434
435 // If this packet is relayed, we want to copy Relay Agent Info option
436 // when it is not empty.
437 OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
438 if (!rai || (rai->len() <= Option::OPTION4_HDR_LEN)) {
439 return;
440 }
441 // Do not copy recovered stashed RAI.
443 getConfiguredGlobal(CfgGlobals::STASH_AGENT_OPTIONS);
444 if (sao && (sao->getType() == Element::boolean) &&
445 sao->boolValue() && query_->inClass("STASH_AGENT_OPTIONS")) {
446 return;
447 }
448 resp_->addOption(rai);
449}
450
451void
453 const ConstCfgHostOperationsPtr cfg =
454 CfgMgr::instance().getCurrentCfg()->getCfgHostOperations4();
455
456 // Collect host identifiers. The identifiers are stored in order of preference.
457 // The server will use them in that order to search for host reservations.
458 for (auto const& id_type : cfg->getIdentifierTypes()) {
459 switch (id_type) {
461 if (context->hwaddr_ && !context->hwaddr_->hwaddr_.empty()) {
462 context->addHostIdentifier(id_type, context->hwaddr_->hwaddr_);
463 }
464 break;
465
466 case Host::IDENT_DUID:
467 if (context->clientid_) {
468 const std::vector<uint8_t>& vec = context->clientid_->getClientId();
469 if (!vec.empty()) {
470 // Client identifier type = DUID? Client identifier holding a DUID
471 // comprises Type (1 byte), IAID (4 bytes), followed by the actual
472 // DUID. Thus, the minimal length is 6.
473 if ((vec[0] == CLIENT_ID_OPTION_TYPE_DUID) && (vec.size() > 5)) {
474 // Extract DUID, skip IAID.
475 context->addHostIdentifier(id_type,
476 std::vector<uint8_t>(vec.begin() + 5,
477 vec.end()));
478 }
479 }
480 }
481 break;
482
484 {
485 OptionPtr rai = context->query_->getOption(DHO_DHCP_AGENT_OPTIONS);
486 if (rai) {
487 OptionPtr circuit_id_opt = rai->getOption(RAI_OPTION_AGENT_CIRCUIT_ID);
488 if (circuit_id_opt) {
489 const OptionBuffer& circuit_id_vec = circuit_id_opt->getData();
490 if (!circuit_id_vec.empty()) {
491 context->addHostIdentifier(id_type, circuit_id_vec);
492 }
493 }
494 }
495 }
496 break;
497
499 if (context->clientid_) {
500 const std::vector<uint8_t>& vec = context->clientid_->getClientId();
501 if (!vec.empty()) {
502 context->addHostIdentifier(id_type, vec);
503 }
504 }
505 break;
506 case Host::IDENT_FLEX:
507 {
508 if (!HooksManager::calloutsPresent(Hooks.hook_index_host4_identifier_)) {
509 break;
510 }
511
512 CalloutHandlePtr callout_handle = getCalloutHandle(context->query_);
513
515 std::vector<uint8_t> id;
516
517 // Use the RAII wrapper to make sure that the callout handle state is
518 // reset when this object goes out of scope. All hook points must do
519 // it to prevent possible circular dependency between the callout
520 // handle and its arguments.
521 ScopedCalloutHandleState callout_handle_state(callout_handle);
522
523 // Pass incoming packet as argument
524 callout_handle->setArgument("query4", context->query_);
525 callout_handle->setArgument("id_type", type);
526 callout_handle->setArgument("id_value", id);
527
528 // Call callouts
529 HooksManager::callCallouts(Hooks.hook_index_host4_identifier_,
530 *callout_handle);
531
532 callout_handle->getArgument("id_type", type);
533 callout_handle->getArgument("id_value", id);
534
535 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_CONTINUE) &&
536 !id.empty()) {
537
539 .arg(context->query_->getLabel())
540 .arg(Host::getIdentifierAsText(type, &id[0], id.size()));
541
542 context->addHostIdentifier(type, id);
543 }
544 break;
545 }
546 default:
547 ;
548 }
549 }
550}
551
552void
554 const ClientClassDictionaryPtr& dict =
555 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
556 const ClientClassDefListPtr& defs_ptr = dict->getClasses();
557 for (auto const& def : *defs_ptr) {
558 // Only remove evaluated classes. Other classes can be
559 // assigned via hooks libraries and we should not remove
560 // them because there is no way they can be added back.
561 if (def->getMatchExpr()) {
562 query->classes_.erase(def->getName());
563 }
564 }
565}
566
567void
569 if (context->currentHost() && context->query_) {
570 const ClientClasses& classes = context->currentHost()->getClientClasses4();
571 for (auto const& cclass : classes) {
572 context->query_->addClass(cclass);
573 }
574 }
575}
576
577void
579 if (context_->subnet_) {
580 SharedNetwork4Ptr shared_network;
581 context_->subnet_->getSharedNetwork(shared_network);
582 if (shared_network) {
583 ConstHostPtr host = context_->currentHost();
584 if (host && (host->getIPv4SubnetID() != SUBNET_ID_GLOBAL)) {
585 setReservedClientClasses(context_);
586 }
587 }
588 }
589}
590
591void
593 ConstHostPtr host = context_->currentHost();
594 // Nothing to do if host reservations not specified for this client.
595 if (host) {
596 if (!host->getNextServer().isV4Zero()) {
597 resp_->setSiaddr(host->getNextServer());
598 }
599
600 std::string sname = host->getServerHostname();
601 if (!sname.empty()) {
602 resp_->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
603 sname.size());
604 }
605
606 std::string bootfile = host->getBootFileName();
607 if (!bootfile.empty()) {
608 resp_->setFile(reinterpret_cast<const uint8_t*>(bootfile.c_str()),
609 bootfile.size());
610 }
611 }
612}
613
615 // Built-in vendor class processing
616 boost::shared_ptr<OptionString> vendor_class =
617 boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
618
619 if (!vendor_class) {
620 return;
621 }
622
623 pkt->addClass(Dhcpv4Srv::VENDOR_CLASS_PREFIX + vendor_class->getValue());
624}
625
627 // All packets belong to ALL.
628 pkt->addClass("ALL");
629
630 // First: built-in vendor class processing.
631 classifyByVendor(pkt);
632
633 // Run match expressions on classes not depending on KNOWN/UNKNOWN.
634 evaluateClasses(pkt, false);
635}
636
637void Dhcpv4Exchange::evaluateClasses(const Pkt4Ptr& pkt, bool depend_on_known) {
638 // Note getClientClassDictionary() cannot be null
639 const ClientClassDictionaryPtr& dict =
640 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
641 const ClientClassDefListPtr& defs_ptr = dict->getClasses();
642 for (auto const& it : *defs_ptr) {
643 // Note second cannot be null
644 const ExpressionPtr& expr_ptr = it->getMatchExpr();
645 // Nothing to do without an expression to evaluate
646 if (!expr_ptr) {
647 continue;
648 }
649 // Not the right time if only when additional
650 if (it->getAdditional()) {
651 continue;
652 }
653 // Not the right pass.
654 if (it->getDependOnKnown() != depend_on_known) {
655 continue;
656 }
657 it->test(pkt, expr_ptr);
658 }
659}
660
661const std::string Dhcpv4Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");
662
663Dhcpv4Srv::Dhcpv4Srv(uint16_t server_port, uint16_t client_port,
664 const bool use_bcast, const bool direct_response_desired)
665 : io_service_(new IOService()), server_port_(server_port),
666 client_port_(client_port), shutdown_(true),
667 alloc_engine_(), use_bcast_(use_bcast),
668 network_state_(new NetworkState()),
669 cb_control_(new CBControlDHCPv4()),
670 test_send_responses_to_source_(false) {
671
672 const char* env = std::getenv("KEA_TEST_SEND_RESPONSES_TO_SOURCE");
673 if (env) {
675 test_send_responses_to_source_ = true;
676 }
677
679 .arg(server_port);
680
681 try {
682 // Port 0 is used for testing purposes where we don't open broadcast
683 // capable sockets. So, set the packet filter handling direct traffic
684 // only if we are in non-test mode.
685 if (server_port) {
686 // First call to instance() will create IfaceMgr (it's a singleton)
687 // it may throw something if things go wrong.
688 // The 'true' value of the call to setMatchingPacketFilter imposes
689 // that IfaceMgr will try to use the mechanism to respond directly
690 // to the client which doesn't have address assigned. This capability
691 // may be lacking on some OSes, so there is no guarantee that server
692 // will be able to respond directly.
693 IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
694 }
695
696 // Instantiate allocation engine. The number of allocation attempts equal
697 // to zero indicates that the allocation engine will use the number of
698 // attempts depending on the pool size.
699 alloc_engine_.reset(new AllocEngine(0));
700
702
703 } catch (const std::exception &e) {
705 return;
706 }
707
708 // Initializing all observations with default value
710
711 // All done, so can proceed
712 shutdown_ = false;
713}
714
717
718 // Iterate over set of observed statistics
719 for (auto const& it : dhcp4_statistics) {
720 // Initialize them with default value 0
721 stats_mgr.setValue(it, static_cast<int64_t>(0));
722 }
723}
724
726 // Discard any parked packets
728
729 try {
730 stopD2();
731 } catch (const std::exception& ex) {
732 // Highly unlikely, but lets Report it but go on
734 }
735
736 try {
738 } catch (const std::exception& ex) {
739 // Highly unlikely, but lets Report it but go on
741 }
742
744
745 // The lease manager was instantiated during DHCPv4Srv configuration,
746 // so we should clean up after ourselves.
748
749 // Destroy the host manager before hooks unload.
751
752 // Explicitly unload hooks
755 auto names = HooksManager::getLibraryNames();
756 std::string msg;
757 if (!names.empty()) {
758 msg = names[0];
759 for (size_t i = 1; i < names.size(); ++i) {
760 msg += std::string(", ") + names[i];
761 }
762 }
764 }
766 io_service_->stopAndPoll();
767}
768
769void
774
776Dhcpv4Srv::selectSubnet(const Pkt4Ptr& query, bool& drop,
777 bool sanity_only, bool allow_answer_park) {
778
779 // DHCPv4-over-DHCPv6 is a special (and complex) case
780 if (query->isDhcp4o6()) {
781 return (selectSubnet4o6(query, drop, sanity_only, allow_answer_park));
782 }
783
784 ConstSubnet4Ptr subnet;
785
786 const SubnetSelector& selector = CfgSubnets4::initSelector(query);
787
788 CfgMgr& cfgmgr = CfgMgr::instance();
789 subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet(selector);
790
791 // Let's execute all callouts registered for subnet4_select
792 // (skip callouts if the selectSubnet was called to do sanity checks only)
793 if (!sanity_only &&
794 HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
795 CalloutHandlePtr callout_handle = getCalloutHandle(query);
796
797 // Use the RAII wrapper to make sure that the callout handle state is
798 // reset when this object goes out of scope. All hook points must do
799 // it to prevent possible circular dependency between the callout
800 // handle and its arguments.
801 shared_ptr<ScopedCalloutHandleState> callout_handle_state(
802 std::make_shared<ScopedCalloutHandleState>(callout_handle));
803
804 // Enable copying options from the packet within hook library.
805 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
806
807 // Set new arguments
808 callout_handle->setArgument("query4", query);
809 callout_handle->setArgument("subnet4", subnet);
810 callout_handle->setArgument("subnet4collection",
811 cfgmgr.getCurrentCfg()->
812 getCfgSubnets4()->getAll());
813
814 auto const tpl(parkingLimitExceeded("subnet4_select"));
815 bool const exceeded(get<0>(tpl));
816 if (exceeded) {
817 uint32_t const limit(get<1>(tpl));
818 // We can't park it so we're going to throw it on the floor.
821 .arg(limit)
822 .arg(query->getLabel());
823 return (ConstSubnet4Ptr());
824 }
825
826 // We proactively park the packet.
828 "subnet4_select", query, [this, query, allow_answer_park, callout_handle_state]() {
829 if (MultiThreadingMgr::instance().getMode()) {
830 boost::shared_ptr<function<void()>> callback(
831 boost::make_shared<function<void()>>(
832 [this, query, allow_answer_park]() mutable {
833 processLocalizedQuery4AndSendResponse(query, allow_answer_park);
834 }));
835 callout_handle_state->on_completion_ = [callback]() {
837 };
838 } else {
839 processLocalizedQuery4AndSendResponse(query, allow_answer_park);
840 }
841 });
842
843 // Call user (and server-side) callouts
844 try {
845 HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
846 *callout_handle);
847 } catch (...) {
848 // Make sure we don't orphan a parked packet.
849 HooksManager::drop("subnet4_select", query);
850 throw;
851 }
852
853 // Callouts parked the packet. Same as drop but callouts will resume
854 // processing or drop the packet later.
855 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK) {
858 .arg(query->getLabel());
859 drop = true;
860 return (ConstSubnet4Ptr());
861 } else {
862 HooksManager::drop("subnet4_select", query);
863 }
864
865 // Callouts decided to skip this step. This means that no subnet
866 // will be selected. Packet processing will continue, but it will
867 // be severely limited (i.e. only global options will be assigned)
868 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
871 .arg(query->getLabel());
872 return (ConstSubnet4Ptr());
873 }
874
875 // Callouts decided to drop the packet. It is a superset of the
876 // skip case so no subnet will be selected.
877 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
880 .arg(query->getLabel());
881 drop = true;
882 return (ConstSubnet4Ptr());
883 }
884
885 // Use whatever subnet was specified by the callout
886 callout_handle->getArgument("subnet4", subnet);
887 }
888
889 if (subnet) {
890 // Log at higher debug level that subnet has been found.
892 .arg(query->getLabel())
893 .arg(subnet->getID());
894 // Log detailed information about the selected subnet at the
895 // lower debug level.
897 .arg(query->getLabel())
898 .arg(subnet->toText());
899
900 } else {
903 .arg(query->getLabel());
904 }
905
906 return (subnet);
907}
908
910Dhcpv4Srv::selectSubnet4o6(const Pkt4Ptr& query, bool& drop,
911 bool sanity_only, bool allow_answer_park) {
912 ConstSubnet4Ptr subnet;
913
914 SubnetSelector selector;
915 selector.ciaddr_ = query->getCiaddr();
916 selector.giaddr_ = query->getGiaddr();
917 selector.local_address_ = query->getLocalAddr();
918 selector.client_classes_ = query->classes_;
919 selector.iface_name_ = query->getIface();
920 // Mark it as DHCPv4-over-DHCPv6
921 selector.dhcp4o6_ = true;
922 // Now the DHCPv6 part
923 selector.remote_address_ = query->getRemoteAddr();
924 selector.first_relay_linkaddr_ = IOAddress("::");
925
926 // Handle a DHCPv6 relayed query
927 Pkt4o6Ptr query4o6 = boost::dynamic_pointer_cast<Pkt4o6>(query);
928 if (!query4o6) {
929 isc_throw(Unexpected, "Can't get DHCP4o6 message");
930 }
931 const Pkt6Ptr& query6 = query4o6->getPkt6();
932
933 // Initialize fields specific to relayed messages.
934 if (query6 && !query6->relay_info_.empty()) {
935 for (auto const& relay : boost::adaptors::reverse(query6->relay_info_)) {
936 if (!relay.linkaddr_.isV6Zero() &&
937 !relay.linkaddr_.isV6LinkLocal()) {
938 selector.first_relay_linkaddr_ = relay.linkaddr_;
939 break;
940 }
941 }
942 selector.interface_id_ =
943 query6->getAnyRelayOption(D6O_INTERFACE_ID,
945 }
946
947 // If the Subnet Selection option is present, extract its value.
948 OptionPtr sbnsel = query->getOption(DHO_SUBNET_SELECTION);
949 if (sbnsel) {
950 OptionCustomPtr oc = boost::dynamic_pointer_cast<OptionCustom>(sbnsel);
951 if (oc) {
952 selector.option_select_ = oc->readAddress();
953 }
954 }
955
956 CfgMgr& cfgmgr = CfgMgr::instance();
957 subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet4o6(selector);
958
959 // Let's execute all callouts registered for subnet4_select.
960 // (skip callouts if the selectSubnet was called to do sanity checks only)
961 if (!sanity_only &&
962 HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
963 CalloutHandlePtr callout_handle = getCalloutHandle(query);
964
965 // Use the RAII wrapper to make sure that the callout handle state is
966 // reset when this object goes out of scope. All hook points must do
967 // it to prevent possible circular dependency between the callout
968 // handle and its arguments.
969 shared_ptr<ScopedCalloutHandleState> callout_handle_state(
970 std::make_shared<ScopedCalloutHandleState>(callout_handle));
971
972 // Enable copying options from the packet within hook library.
973 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
974
975 // Set new arguments
976 callout_handle->setArgument("query4", query);
977 callout_handle->setArgument("subnet4", subnet);
978 callout_handle->setArgument("subnet4collection",
979 cfgmgr.getCurrentCfg()->
980 getCfgSubnets4()->getAll());
981
982 auto const tpl(parkingLimitExceeded("subnet4_select"));
983 bool const exceeded(get<0>(tpl));
984 if (exceeded) {
985 uint32_t const limit(get<1>(tpl));
986 // We can't park it so we're going to throw it on the floor.
989 .arg(limit)
990 .arg(query->getLabel());
991 return (ConstSubnet4Ptr());
992 }
993
994 // We proactively park the packet.
996 "subnet4_select", query, [this, query, allow_answer_park, callout_handle_state]() {
997 if (MultiThreadingMgr::instance().getMode()) {
998 boost::shared_ptr<function<void()>> callback(
999 boost::make_shared<function<void()>>(
1000 [this, query, allow_answer_park]() mutable {
1001 processLocalizedQuery4AndSendResponse(query, allow_answer_park);
1002 }));
1003 callout_handle_state->on_completion_ = [callback]() {
1005 };
1006 } else {
1007 processLocalizedQuery4AndSendResponse(query, allow_answer_park);
1008 }
1009 });
1010
1011 // Call user (and server-side) callouts
1012 try {
1013 HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
1014 *callout_handle);
1015 } catch (...) {
1016 // Make sure we don't orphan a parked packet.
1017 HooksManager::drop("subnet4_select", query);
1018 throw;
1019 }
1020
1021 // Callouts parked the packet. Same as drop but callouts will resume
1022 // processing or drop the packet later.
1023 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK) {
1026 .arg(query->getLabel());
1027 drop = true;
1028 return (ConstSubnet4Ptr());
1029 } else {
1030 HooksManager::drop("subnet4_select", query);
1031 }
1032
1033 // Callouts decided to skip this step. This means that no subnet
1034 // will be selected. Packet processing will continue, but it will
1035 // be severely limited (i.e. only global options will be assigned)
1036 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
1039 .arg(query->getLabel());
1040 return (ConstSubnet4Ptr());
1041 }
1042
1043 // Callouts decided to drop the packet. It is a superset of the
1044 // skip case so no subnet will be selected.
1045 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1048 .arg(query->getLabel());
1049 drop = true;
1050 return (ConstSubnet4Ptr());
1051 }
1052
1053 // Use whatever subnet was specified by the callout
1054 callout_handle->getArgument("subnet4", subnet);
1055 }
1056
1057 if (subnet) {
1058 // Log at higher debug level that subnet has been found.
1061 .arg(query->getLabel())
1062 .arg(subnet->getID());
1063 // Log detailed information about the selected subnet at the
1064 // lower debug level.
1067 .arg(query->getLabel())
1068 .arg(subnet->toText());
1069
1070 } else {
1073 .arg(query->getLabel());
1074 }
1075
1076 return (subnet);
1077}
1078
1079Pkt4Ptr
1081 return (IfaceMgr::instance().receive4(timeout));
1082}
1083
1084void
1086 IfaceMgr::instance().send(packet);
1087}
1088
1089void
1092 // Pointer to client's query.
1093 ctx->query_ = query;
1094
1095 // Hardware address.
1096 ctx->hwaddr_ = query->getHWAddr();
1097}
1098
1099bool
1102
1103 // First part of context initialization.
1104 initContext0(query, ctx);
1105
1106 // Get the early-global-reservations-lookup flag value.
1109 if (egrl) {
1110 ctx->early_global_reservations_lookup_ = egrl->boolValue();
1111 }
1112
1113 // Perform early global reservations lookup when wanted.
1114 if (ctx->early_global_reservations_lookup_) {
1115 // Retrieve retrieve client identifier.
1116 OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
1117 if (opt_clientid) {
1118 ctx->clientid_.reset(new ClientId(opt_clientid->getData()));
1119 }
1120
1121 // Get the host identifiers.
1123
1124 // Check for global host reservations.
1125 ConstHostPtr global_host = alloc_engine_->findGlobalReservation(*ctx);
1126
1127 if (global_host && !global_host->getClientClasses4().empty()) {
1128 // Remove dependent evaluated classes.
1130
1131 // Add classes from the global reservations.
1132 const ClientClasses& classes = global_host->getClientClasses4();
1133 for (auto const& cclass : classes) {
1134 query->addClass(cclass);
1135 }
1136
1137 // Evaluate classes before KNOWN.
1138 Dhcpv4Exchange::evaluateClasses(query, false);
1139 }
1140
1141 if (global_host) {
1142 // Add the KNOWN class;
1143 query->addClass("KNOWN");
1145 .arg(query->getLabel())
1146 .arg("KNOWN");
1147
1148 // Evaluate classes after KNOWN.
1150
1151 // Check the DROP special class.
1152 if (query->inClass("DROP")) {
1155 .arg(query->getHWAddrLabel())
1156 .arg(query->toText());
1157 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1158 static_cast<int64_t>(1));
1159 return (false);
1160 }
1161
1162 // Store the reservation.
1163 ctx->hosts_[SUBNET_ID_GLOBAL] = global_host;
1164 }
1165 }
1166
1167 return (true);
1168}
1169
1170int
1172#ifdef HAVE_AFL
1173 // Get the values of the environment variables used to control the
1174 // fuzzing.
1175
1176 // Specfies the interface to be used to pass packets from AFL to Kea.
1177 const char* interface = getenv("KEA_AFL_INTERFACE");
1178 if (!interface) {
1179 isc_throw(FuzzInitFail, "no fuzzing interface has been set");
1180 }
1181
1182 // The address on the interface to be used.
1183 const char* address = getenv("KEA_AFL_ADDRESS");
1184 if (!address) {
1185 isc_throw(FuzzInitFail, "no fuzzing address has been set");
1186 }
1187
1188 // Set up structures needed for fuzzing.
1189 PacketFuzzer fuzzer(server_port_, interface, address);
1190
1191 // The next line is needed as a signature for AFL to recognize that we are
1192 // running persistent fuzzing. This has to be in the main image file.
1193 while (__AFL_LOOP(fuzzer.maxLoopCount())) {
1194 // Read from stdin and put the data read into an address/port on which
1195 // Kea is listening, read for Kea to read it via asynchronous I/O.
1196 fuzzer.transfer();
1197#else
1198 while (!shutdown_) {
1199#endif // HAVE_AFL
1200 try {
1201 runOne();
1202 // Handle events registered by hooks using external IOService objects.
1204 getIOService()->poll();
1205 } catch (const std::exception& e) {
1206 // General catch-all standard exceptions that are not caught by more
1207 // specific catches.
1209 .arg(e.what());
1210 } catch (...) {
1211 // General catch-all exception that are not caught by more specific
1212 // catches. This one is for other exceptions, not derived from
1213 // std::exception.
1215 }
1216 }
1217
1218 // Stop everything before we change into single-threaded mode.
1220
1221 // destroying the thread pool
1222 MultiThreadingMgr::instance().apply(false, 0, 0);
1223
1224 return (getExitValue());
1225}
1226
1227void
1229 // client's message and server's response
1230 Pkt4Ptr query;
1231
1232 try {
1233 // Set select() timeout to 1s. This value should not be modified
1234 // because it is important that the select() returns control
1235 // frequently so as the IOService can be polled for ready handlers.
1236 uint32_t timeout = 1;
1237 query = receivePacket(timeout);
1238
1239 // Log if packet has arrived. We can't log the detailed information
1240 // about the DHCP message because it hasn't been unpacked/parsed
1241 // yet, and it can't be parsed at this point because hooks will
1242 // have to process it first. The only information available at this
1243 // point are: the interface, source address and destination addresses
1244 // and ports.
1245 if (query) {
1247 .arg(query->getRemoteAddr().toText())
1248 .arg(query->getRemotePort())
1249 .arg(query->getLocalAddr().toText())
1250 .arg(query->getLocalPort())
1251 .arg(query->getIface());
1252 }
1253
1254 // We used to log that the wait was interrupted, but this is no longer
1255 // the case. Our wait time is 1s now, so the lack of query packet more
1256 // likely means that nothing new appeared within a second, rather than
1257 // we were interrupted. And we don't want to print a message every
1258 // second.
1259
1260 } catch (const SignalInterruptOnSelect&) {
1261 // Packet reception interrupted because a signal has been received.
1262 // This is not an error because we might have received a SIGTERM,
1263 // SIGINT, SIGHUP or SIGCHLD which are handled by the server. For
1264 // signals that are not handled by the server we rely on the default
1265 // behavior of the system.
1267 } catch (const std::exception& e) {
1268 // Log all other errors.
1270 .arg(e.what());
1271 }
1272
1273 // Timeout may be reached or signal received, which breaks select()
1274 // with no reception occurred. No need to log anything here because
1275 // we have logged right after the call to receivePacket().
1276 if (!query) {
1277 return;
1278 }
1279
1280 // If the DHCP service has been globally disabled, drop the packet.
1281 if (!network_state_->isServiceEnabled()) {
1283 .arg(query->getLabel());
1284 return;
1285 } else {
1286 if (MultiThreadingMgr::instance().getMode()) {
1287 query->addPktEvent("mt_queued");
1288 typedef function<void()> CallBack;
1289 boost::shared_ptr<CallBack> call_back =
1290 boost::make_shared<CallBack>(std::bind(&Dhcpv4Srv::processPacketAndSendResponseNoThrow,
1291 this, query));
1292 if (!MultiThreadingMgr::instance().getThreadPool().add(call_back)) {
1294 }
1295 } else {
1297 }
1298 }
1299}
1300
1301void
1303 try {
1305 } catch (const std::exception& e) {
1307 .arg(query->getLabel())
1308 .arg(e.what());
1309 } catch (...) {
1311 }
1312}
1313
1314void
1316 Pkt4Ptr rsp = processPacket(query);
1317 if (!rsp) {
1318 return;
1319 }
1320
1321 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1322
1323 processPacketBufferSend(callout_handle, rsp);
1324}
1325
1326Pkt4Ptr
1327Dhcpv4Srv::processPacket(Pkt4Ptr query, bool allow_answer_park) {
1328 query->addPktEvent("process_started");
1329
1330 // All packets belong to ALL.
1331 query->addClass("ALL");
1332
1333 // Log reception of the packet. We need to increase it early, as any
1334 // failures in unpacking will cause the packet to be dropped. We
1335 // will increase type specific statistic further down the road.
1336 // See processStatsReceived().
1337 isc::stats::StatsMgr::instance().addValue("pkt4-received",
1338 static_cast<int64_t>(1));
1339
1340 bool skip_unpack = false;
1341
1342 // The packet has just been received so contains the uninterpreted wire
1343 // data; execute callouts registered for buffer4_receive.
1344 if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
1345 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1346
1347 // Use the RAII wrapper to make sure that the callout handle state is
1348 // reset when this object goes out of scope. All hook points must do
1349 // it to prevent possible circular dependency between the callout
1350 // handle and its arguments.
1351 ScopedCalloutHandleState callout_handle_state(callout_handle);
1352
1353 // Enable copying options from the packet within hook library.
1354 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1355
1356 // Pass incoming packet as argument
1357 callout_handle->setArgument("query4", query);
1358
1359 // Call callouts
1360 HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_,
1361 *callout_handle);
1362
1363 // Callouts decided to drop the received packet.
1364 // The response (rsp) is null so the caller (runOne) will
1365 // immediately return too.
1366 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1369 .arg(query->getRemoteAddr().toText())
1370 .arg(query->getLocalAddr().toText())
1371 .arg(query->getIface());
1372 return (Pkt4Ptr());;
1373 }
1374
1375 // Callouts decided to skip the next processing step. The next
1376 // processing step would be to parse the packet, so skip at this
1377 // stage means that callouts did the parsing already, so server
1378 // should skip parsing.
1379 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
1382 .arg(query->getRemoteAddr().toText())
1383 .arg(query->getLocalAddr().toText())
1384 .arg(query->getIface());
1385 skip_unpack = true;
1386 }
1387
1388 callout_handle->getArgument("query4", query);
1389 }
1390
1391 // Unpack the packet information unless the buffer4_receive callouts
1392 // indicated they did it
1393 if (!skip_unpack) {
1394 try {
1396 .arg(query->getRemoteAddr().toText())
1397 .arg(query->getLocalAddr().toText())
1398 .arg(query->getIface());
1399 query->unpack();
1400 } catch (const SkipRemainingOptionsError& e) {
1401 // An option failed to unpack but we are to attempt to process it
1402 // anyway. Log it and let's hope for the best.
1405 .arg(query->getLabel())
1406 .arg(e.what());
1407 } catch (const std::exception& e) {
1408 // Failed to parse the packet.
1410 .arg(query->getLabel())
1411 .arg(query->getRemoteAddr().toText())
1412 .arg(query->getLocalAddr().toText())
1413 .arg(query->getIface())
1414 .arg(e.what())
1415 .arg(query->getHWAddrLabel());
1416
1417 // Increase the statistics of parse failures and dropped packets.
1418 isc::stats::StatsMgr::instance().addValue("pkt4-parse-failed",
1419 static_cast<int64_t>(1));
1420 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1421 static_cast<int64_t>(1));
1422 return (Pkt4Ptr());
1423 }
1424 }
1425
1426 // Classify can emit INFO logs so help to track the query.
1428 .arg(query->getLabel());
1429
1430 // Update statistics accordingly for received packet.
1431 processStatsReceived(query);
1432
1433 // Recover stashed RAI from client address lease.
1434 try {
1436 } catch (const std::exception&) {
1437 // Ignore exceptions.
1438 }
1439
1440 // Assign this packet to one or more classes if needed. We need to do
1441 // this before calling accept(), because getSubnet4() may need client
1442 // class information.
1443 classifyPacket(query);
1444
1445 // Now it is classified the deferred unpacking can be done.
1446 deferredUnpack(query);
1447
1448 // Check whether the message should be further processed or discarded.
1449 // There is no need to log anything here. This function logs by itself.
1450 if (!accept(query)) {
1451 // Increase the statistic of dropped packets.
1452 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1453 static_cast<int64_t>(1));
1454 return (Pkt4Ptr());
1455 }
1456
1457 // We have sanity checked (in accept() that the Message Type option
1458 // exists, so we can safely get it here.
1459 int type = query->getType();
1461 .arg(query->getLabel())
1462 .arg(query->getName())
1463 .arg(type)
1464 .arg(query->getRemoteAddr())
1465 .arg(query->getLocalAddr())
1466 .arg(query->getIface());
1468 .arg(query->getLabel())
1469 .arg(query->toText());
1470
1471 // Let's execute all callouts registered for pkt4_receive
1472 if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_receive_)) {
1473 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1474
1475 // Use the RAII wrapper to make sure that the callout handle state is
1476 // reset when this object goes out of scope. All hook points must do
1477 // it to prevent possible circular dependency between the callout
1478 // handle and its arguments.
1479 ScopedCalloutHandleState callout_handle_state(callout_handle);
1480
1481 // Enable copying options from the packet within hook library.
1482 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1483
1484 // Pass incoming packet as argument
1485 callout_handle->setArgument("query4", query);
1486
1487 // Call callouts
1488 HooksManager::callCallouts(Hooks.hook_index_pkt4_receive_,
1489 *callout_handle);
1490
1491 // Callouts decided to skip the next processing step. The next
1492 // processing step would be to process the packet, so skip at this
1493 // stage means drop.
1494 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
1495 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
1498 .arg(query->getLabel());
1499 return (Pkt4Ptr());
1500 }
1501
1502 callout_handle->getArgument("query4", query);
1503 }
1504
1505 // Check the DROP special class.
1506 if (query->inClass("DROP")) {
1508 .arg(query->getHWAddrLabel())
1509 .arg(query->toText());
1510 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1511 static_cast<int64_t>(1));
1512 return (Pkt4Ptr());
1513 }
1514
1515 return (processDhcp4Query(query, allow_answer_park));
1516}
1517
1518void
1520 bool allow_answer_park) {
1521 try {
1522 Pkt4Ptr rsp = processDhcp4Query(query, allow_answer_park);
1523 if (!rsp) {
1524 return;
1525 }
1526
1527 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1528 processPacketBufferSend(callout_handle, rsp);
1529 } catch (const std::exception& e) {
1531 .arg(query->getLabel())
1532 .arg(e.what());
1533 } catch (...) {
1535 }
1536}
1537
1538Pkt4Ptr
1539Dhcpv4Srv::processDhcp4Query(Pkt4Ptr query, bool allow_answer_park) {
1540 // Create a client race avoidance RAII handler.
1541 ClientHandler client_handler;
1542
1543 // Check for lease modifier queries from the same client being processed.
1544 if (MultiThreadingMgr::instance().getMode() &&
1545 ((query->getType() == DHCPDISCOVER) ||
1546 (query->getType() == DHCPREQUEST) ||
1547 (query->getType() == DHCPRELEASE) ||
1548 (query->getType() == DHCPDECLINE))) {
1549 ContinuationPtr cont =
1551 this, query, allow_answer_park));
1552 if (!client_handler.tryLock(query, cont)) {
1553 return (Pkt4Ptr());
1554 }
1555 }
1556
1558 if (!earlyGHRLookup(query, ctx)) {
1559 return (Pkt4Ptr());
1560 }
1561
1562 try {
1563 sanityCheck(query);
1564 if ((query->getType() == DHCPDISCOVER) ||
1565 (query->getType() == DHCPREQUEST) ||
1566 (query->getType() == DHCPINFORM)) {
1567 bool drop = false;
1568 ctx->subnet_ = selectSubnet(query, drop, false, allow_answer_park);
1569 // Stop here if selectSubnet decided to drop the packet
1570 if (drop) {
1571 return (Pkt4Ptr());
1572 }
1573 }
1574 } catch (const std::exception& e) {
1575
1576 // Catch-all exception (we used to call only isc::Exception, but
1577 // std::exception could potentially be raised and if we don't catch
1578 // it here, it would be caught in main() and the process would
1579 // terminate). Just log the problem and ignore the packet.
1580 // (The problem is logged as a debug message because debug is
1581 // disabled by default - it prevents a DDOS attack based on the
1582 // sending of problem packets.)
1584 .arg(query->getLabel())
1585 .arg(e.what());
1586
1587 // Increase the statistic of dropped packets.
1588 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1589 static_cast<int64_t>(1));
1590 }
1591
1592 return (processLocalizedQuery4(ctx, allow_answer_park));
1593}
1594
1595void
1598 bool allow_answer_park) {
1599 try {
1600 Pkt4Ptr rsp = processLocalizedQuery4(ctx, allow_answer_park);
1601 if (!rsp) {
1602 return;
1603 }
1604
1605 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1606
1607 processPacketBufferSend(callout_handle, rsp);
1608 } catch (const std::exception& e) {
1610 .arg(query->getLabel())
1611 .arg(e.what());
1612 } catch (...) {
1614 }
1615}
1616
1617void
1619 bool allow_answer_park) {
1620 // Initialize context.
1622 initContext0(query, ctx);
1623
1624 // Subnet is cached in the callout context associated to the query.
1625 try {
1626 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1627 callout_handle->getContext("subnet4", ctx->subnet_);
1628 } catch (const Exception&) {
1629 // No subnet, leave it to null...
1630 }
1631
1632 processLocalizedQuery4AndSendResponse(query, ctx, allow_answer_park);
1633}
1634
1635Pkt4Ptr
1637 bool allow_answer_park) {
1638 if (!ctx) {
1639 isc_throw(Unexpected, "null context");
1640 }
1641 Pkt4Ptr query = ctx->query_;
1642 Pkt4Ptr rsp;
1643 try {
1644 switch (query->getType()) {
1645 case DHCPDISCOVER:
1646 rsp = processDiscover(query, ctx);
1647 break;
1648
1649 case DHCPREQUEST:
1650 // Note that REQUEST is used for many things in DHCPv4: for
1651 // requesting new leases, renewing existing ones and even
1652 // for rebinding.
1653 rsp = processRequest(query, ctx);
1654 break;
1655
1656 case DHCPRELEASE:
1657 processRelease(query, ctx);
1658 break;
1659
1660 case DHCPDECLINE:
1661 processDecline(query, ctx);
1662 break;
1663
1664 case DHCPINFORM:
1665 rsp = processInform(query, ctx);
1666 break;
1667
1668 default:
1669 // Only action is to output a message if debug is enabled,
1670 // and that is covered by the debug statement before the
1671 // "switch" statement.
1672 ;
1673 }
1674 } catch (const std::exception& e) {
1675
1676 // Catch-all exception (we used to call only isc::Exception, but
1677 // std::exception could potentially be raised and if we don't catch
1678 // it here, it would be caught in main() and the process would
1679 // terminate). Just log the problem and ignore the packet.
1680 // (The problem is logged as a debug message because debug is
1681 // disabled by default - it prevents a DDOS attack based on the
1682 // sending of problem packets.)
1684 .arg(query->getLabel())
1685 .arg(e.what());
1686
1687 // Increase the statistic of dropped packets.
1688 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1689 static_cast<int64_t>(1));
1690 }
1691
1692 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1693 if (ctx) {
1694 // leases4_committed and lease4_offer callouts are treated in the same way,
1695 // so prepare correct set of variables basing on the packet context.
1696 int hook_idx = Hooks.hook_index_leases4_committed_;
1697 std::string hook_label = "leases4_committed";
1701 if (ctx->fake_allocation_) {
1702 hook_idx = Hooks.hook_index_lease4_offer_;
1703 hook_label = "lease4_offer";
1704 pkt_park_msg = DHCP4_HOOK_LEASE4_OFFER_PARK;
1705 pkt_drop_msg = DHCP4_HOOK_LEASE4_OFFER_DROP;
1706 parking_lot_full_msg = DHCP4_HOOK_LEASE4_OFFER_PARKING_LOT_FULL;
1707 }
1708
1709 if (HooksManager::calloutsPresent(hook_idx)) {
1710 // The ScopedCalloutHandleState class which guarantees that the task
1711 // is added to the thread pool after the response is reset (if needed)
1712 // and CalloutHandle state is reset. In ST it does nothing.
1713 // A smart pointer is used to store the ScopedCalloutHandleState so that
1714 // a copy of the pointer is created by the lambda and only on the
1715 // destruction of the last reference the task is added.
1716 // In MT there are 2 cases:
1717 // 1. packet is unparked before current thread smart pointer to
1718 // ScopedCalloutHandleState is destroyed:
1719 // - the lambda uses the smart pointer to set the callout which adds the
1720 // task, but the task is added after ScopedCalloutHandleState is
1721 // destroyed, on the destruction of the last reference which is held
1722 // by the current thread.
1723 // 2. packet is unparked after the current thread smart pointer to
1724 // ScopedCalloutHandleState is destroyed:
1725 // - the current thread reference to ScopedCalloutHandleState is
1726 // destroyed, but the reference in the lambda keeps it alive until
1727 // the lambda is called and the last reference is released, at which
1728 // time the task is actually added.
1729 // Use the RAII wrapper to make sure that the callout handle state is
1730 // reset when this object goes out of scope. All hook points must do
1731 // it to prevent possible circular dependency between the callout
1732 // handle and its arguments.
1733 std::shared_ptr<ScopedCalloutHandleState> callout_handle_state =
1734 std::make_shared<ScopedCalloutHandleState>(callout_handle);
1735
1736 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1737
1738 // Also pass the corresponding query packet as argument
1739 callout_handle->setArgument("query4", query);
1740
1741 // Also pass the corresponding response packet as argument
1742 ScopedEnableOptionsCopy<Pkt4> response4_options_copy(rsp);
1743 callout_handle->setArgument("response4", rsp);
1744
1745 Lease4CollectionPtr new_leases(new Lease4Collection());
1746 // Filter out the new lease if it was reused so not committed.
1747 if (ctx->new_lease_ && (ctx->new_lease_->reuseable_valid_lft_ == 0)) {
1748 new_leases->push_back(ctx->new_lease_);
1749 }
1750 callout_handle->setArgument("leases4", new_leases);
1751
1752 if (ctx->fake_allocation_) {
1753 // Arguments required only for lease4_offer callout.
1754 callout_handle->setArgument("offer_lifetime", ctx->offer_lft_);
1755 callout_handle->setArgument("old_lease", ctx->old_lease_);
1756 } else {
1757 // Arguments required only for leases4_committed callout.
1758 Lease4CollectionPtr deleted_leases(new Lease4Collection());
1759 if (ctx->old_lease_) {
1760 if ((!ctx->new_lease_) || (ctx->new_lease_->addr_ != ctx->old_lease_->addr_)) {
1761 deleted_leases->push_back(ctx->old_lease_);
1762 }
1763 }
1764 callout_handle->setArgument("deleted_leases4", deleted_leases);
1765 }
1766
1767 if (allow_answer_park) {
1768 auto const tpl(parkingLimitExceeded(hook_label));
1769 bool const exceeded(get<0>(tpl));
1770 if (exceeded) {
1771 uint32_t const limit(get<1>(tpl));
1772 // We can't park it so we're going to throw it on the floor.
1773 LOG_DEBUG(packet4_logger, DBGLVL_PKT_HANDLING, parking_lot_full_msg)
1774 .arg(limit)
1775 .arg(query->getLabel());
1776 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1777 static_cast<int64_t>(1));
1778 return (Pkt4Ptr());
1779 }
1780
1781 // We proactively park the packet. We'll unpark it without invoking
1782 // the callback (i.e. drop) unless the callout status is set to
1783 // NEXT_STEP_PARK. Otherwise the callback we bind here will be
1784 // executed when the hook library unparks the packet.
1786 hook_label, query,
1787 [this, callout_handle, query, rsp, callout_handle_state, hook_idx, ctx]() mutable {
1788 if (hook_idx == Hooks.hook_index_lease4_offer_) {
1789 bool offer_address_in_use = false;
1790 try {
1791 callout_handle->getArgument("offer_address_in_use", offer_address_in_use);
1792 } catch (const NoSuchArgument& ex) {
1794 .arg(query->getLabel())
1795 .arg(ex.what());
1796 }
1797
1798 if (offer_address_in_use) {
1799 Lease4Ptr lease = ctx->new_lease_;
1800 bool lease_exists = (ctx->offer_lft_ > 0);
1801 if (MultiThreadingMgr::instance().getMode()) {
1802 typedef function<void()> CallBack;
1803 // We need to pass in the lease and flag as the callback handle state
1804 // gets reset prior to the invocation of the on_completion_ callback.
1805 boost::shared_ptr<CallBack> call_back = boost::make_shared<CallBack>(
1806 std::bind(&Dhcpv4Srv::serverDeclineNoThrow, this,
1807 callout_handle, query, lease, lease_exists));
1808 callout_handle_state->on_completion_ = [call_back]() {
1810 };
1811 } else {
1812 serverDecline(callout_handle, query, lease, lease_exists);
1813 }
1814
1815 return;
1816 }
1817 }
1818
1819 // Send the response to the client.
1820 if (MultiThreadingMgr::instance().getMode()) {
1821 typedef function<void()> CallBack;
1822 boost::shared_ptr<CallBack> call_back = boost::make_shared<CallBack>(
1823 std::bind(&Dhcpv4Srv::sendResponseNoThrow, this, callout_handle,
1824 query, rsp, ctx->subnet_));
1825 callout_handle_state->on_completion_ = [call_back]() {
1827 };
1828 } else {
1829 processPacketPktSend(callout_handle, query, rsp, ctx->subnet_);
1830 processPacketBufferSend(callout_handle, rsp);
1831 }
1832 });
1833 }
1834
1835 try {
1836 // Call all installed callouts
1837 HooksManager::callCallouts(hook_idx, *callout_handle);
1838 } catch (...) {
1839 // Make sure we don't orphan a parked packet.
1840 if (allow_answer_park) {
1841 HooksManager::drop(hook_label, query);
1842 }
1843
1844 throw;
1845 }
1846
1847 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK) &&
1848 allow_answer_park) {
1849 LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS, pkt_park_msg)
1850 .arg(query->getLabel());
1851 // Since the hook library(ies) are going to do the unparking, then
1852 // reset the pointer to the response to indicate to the caller that
1853 // it should return, as the packet processing will continue via
1854 // the callback.
1855 rsp.reset();
1856 } else {
1857 // Drop the park job on the packet, it isn't needed.
1858 HooksManager::drop(hook_label, query);
1859 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1861 .arg(query->getLabel());
1862 rsp.reset();
1863 }
1864 }
1865 }
1866 }
1867
1868 // If we have a response prep it for shipment.
1869 if (rsp) {
1870 ConstSubnet4Ptr subnet = (ctx ? ctx->subnet_ : ConstSubnet4Ptr());
1871 processPacketPktSend(callout_handle, query, rsp, subnet);
1872 }
1873 return (rsp);
1874}
1875
1876void
1878 Pkt4Ptr& query, Pkt4Ptr& rsp,
1879 ConstSubnet4Ptr& subnet) {
1880 try {
1881 processPacketPktSend(callout_handle, query, rsp, subnet);
1882 processPacketBufferSend(callout_handle, rsp);
1883 } catch (const std::exception& e) {
1885 .arg(query->getLabel())
1886 .arg(e.what());
1887 } catch (...) {
1889 }
1890}
1891
1892void
1894 Pkt4Ptr& query, Pkt4Ptr& rsp,
1895 ConstSubnet4Ptr& subnet) {
1896 query->addPktEvent("process_completed");
1897 if (!rsp) {
1898 return;
1899 }
1900
1901 // Specifies if server should do the packing
1902 bool skip_pack = false;
1903
1904 // Execute all callouts registered for pkt4_send
1905 if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_send_)) {
1906
1907 // Use the RAII wrapper to make sure that the callout handle state is
1908 // reset when this object goes out of scope. All hook points must do
1909 // it to prevent possible circular dependency between the callout
1910 // handle and its arguments.
1911 ScopedCalloutHandleState callout_handle_state(callout_handle);
1912
1913 // Enable copying options from the query and response packets within
1914 // hook library.
1915 ScopedEnableOptionsCopy<Pkt4> query_resp_options_copy(query, rsp);
1916
1917 // Pass incoming packet as argument
1918 callout_handle->setArgument("query4", query);
1919
1920 // Set our response
1921 callout_handle->setArgument("response4", rsp);
1922
1923 // Pass in the selected subnet.
1924 callout_handle->setArgument("subnet4", subnet);
1925
1926 // Call all installed callouts
1927 HooksManager::callCallouts(Hooks.hook_index_pkt4_send_,
1928 *callout_handle);
1929
1930 // Callouts decided to skip the next processing step. The next
1931 // processing step would be to pack the packet (create wire data).
1932 // That step will be skipped if any callout sets skip flag.
1933 // It essentially means that the callout already did packing,
1934 // so the server does not have to do it again.
1935 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
1937 .arg(query->getLabel());
1938 skip_pack = true;
1939 }
1940
1942 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1944 .arg(rsp->getLabel());
1945 rsp.reset();
1946 return;
1947 }
1948 }
1949
1950 if (!skip_pack) {
1951 try {
1953 .arg(rsp->getLabel());
1954 rsp->pack();
1955 } catch (const std::exception& e) {
1957 .arg(rsp->getLabel())
1958 .arg(e.what());
1959 }
1960 }
1961}
1962
1963void
1965 Pkt4Ptr& rsp) {
1966 if (!rsp) {
1967 return;
1968 }
1969
1970 try {
1971 // Now all fields and options are constructed into output wire buffer.
1972 // Option objects modification does not make sense anymore. Hooks
1973 // can only manipulate wire buffer at this stage.
1974 // Let's execute all callouts registered for buffer4_send
1975 if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_send_)) {
1976
1977 // Use the RAII wrapper to make sure that the callout handle state is
1978 // reset when this object goes out of scope. All hook points must do
1979 // it to prevent possible circular dependency between the callout
1980 // handle and its arguments.
1981 ScopedCalloutHandleState callout_handle_state(callout_handle);
1982
1983 // Enable copying options from the packet within hook library.
1984 ScopedEnableOptionsCopy<Pkt4> resp4_options_copy(rsp);
1985
1986 // Pass incoming packet as argument
1987 callout_handle->setArgument("response4", rsp);
1988
1989 // Call callouts
1990 HooksManager::callCallouts(Hooks.hook_index_buffer4_send_,
1991 *callout_handle);
1992
1993 // Callouts decided to skip the next processing step. The next
1994 // processing step would be to parse the packet, so skip at this
1995 // stage means drop.
1996 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
1997 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
2000 .arg(rsp->getLabel());
2001 return;
2002 }
2003
2004 callout_handle->getArgument("response4", rsp);
2005 }
2006
2008 .arg(rsp->getLabel())
2009 .arg(rsp->getName())
2010 .arg(static_cast<int>(rsp->getType()))
2011 .arg(rsp->getLocalAddr().isV4Zero() ? "*" : rsp->getLocalAddr().toText())
2012 .arg(rsp->getLocalPort())
2013 .arg(rsp->getRemoteAddr())
2014 .arg(rsp->getRemotePort())
2015 .arg(rsp->getIface().empty() ? "to be determined from routing" :
2016 rsp->getIface());
2017
2020 .arg(rsp->getLabel())
2021 .arg(rsp->getName())
2022 .arg(static_cast<int>(rsp->getType()))
2023 .arg(rsp->toText());
2024 sendPacket(rsp);
2025
2026 // Update statistics accordingly for sent packet.
2027 processStatsSent(rsp);
2028
2029 } catch (const std::exception& e) {
2031 .arg(rsp->getLabel())
2032 .arg(e.what());
2033 }
2034}
2035
2036string
2038 if (!srvid) {
2039 isc_throw(BadValue, "NULL pointer passed to srvidToString()");
2040 }
2041 boost::shared_ptr<Option4AddrLst> generated =
2042 boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
2043 if (!srvid) {
2044 isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
2045 }
2046
2047 Option4AddrLst::AddressContainer addrs = generated->getAddresses();
2048 if (addrs.size() != 1) {
2049 isc_throw(BadValue, "Malformed option passed to srvidToString(). "
2050 << "Expected to contain a single IPv4 address.");
2051 }
2052
2053 return (addrs[0].toText());
2054}
2055
2056void
2058
2059 // Do not append generated server identifier if there is one appended already.
2060 // This is when explicitly configured server identifier option is present.
2061 if (ex.getResponse()->getOption(DHO_DHCP_SERVER_IDENTIFIER)) {
2062 return;
2063 }
2064
2065 // Use local address on which the packet has been received as a
2066 // server identifier. In some cases it may be a different address,
2067 // e.g. broadcast packet or DHCPv4o6 packet.
2068 IOAddress local_addr = ex.getQuery()->getLocalAddr();
2069 Pkt4Ptr query = ex.getQuery();
2070
2071 if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
2072 local_addr = IfaceMgr::instance().getSocket(query).addr_;
2073 }
2074
2075 static const OptionDefinition& server_id_def = LibDHCP::DHO_DHCP_SERVER_IDENTIFIER_DEF();
2076 OptionCustomPtr opt_srvid(new OptionCustom(server_id_def, Option::V4));
2077 opt_srvid->writeAddress(local_addr);
2078 ex.getResponse()->addOption(opt_srvid);
2079}
2080
2081void
2083 CfgOptionList& co_list = ex.getCfgOptionList();
2084
2085 // Retrieve subnet.
2086 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2087 if (!subnet) {
2088 // All methods using the CfgOptionList object return soon when
2089 // there is no subnet so do the same
2090 return;
2091 }
2092
2093 // Firstly, host specific options.
2094 const ConstHostPtr& host = ex.getContext()->currentHost();
2095 if (host && !host->getCfgOption4()->empty()) {
2096 co_list.push_back(host->getCfgOption4());
2097 }
2098
2099 // Secondly, pool specific options.
2100 Pkt4Ptr resp = ex.getResponse();
2102 if (resp) {
2103 addr = resp->getYiaddr();
2104 }
2105 if (!addr.isV4Zero()) {
2106 PoolPtr pool = subnet->getPool(Lease::TYPE_V4, addr, false);
2107 if (pool && !pool->getCfgOption()->empty()) {
2108 co_list.push_back(pool->getCfgOption());
2109 }
2110 }
2111
2112 // Thirdly, subnet configured options.
2113 if (!subnet->getCfgOption()->empty()) {
2114 co_list.push_back(subnet->getCfgOption());
2115 }
2116
2117 // Fourthly, shared network specific options.
2118 SharedNetwork4Ptr network;
2119 subnet->getSharedNetwork(network);
2120 if (network && !network->getCfgOption()->empty()) {
2121 co_list.push_back(network->getCfgOption());
2122 }
2123
2124 // Each class in the incoming packet
2125 const ClientClasses& classes = ex.getQuery()->getClasses();
2126 for (auto const& cclass : classes) {
2127 // Find the client class definition for this class
2129 getClientClassDictionary()->findClass(cclass);
2130 if (!ccdef) {
2131 // Not found: the class is built-in or not configured
2132 if (!isClientClassBuiltIn(cclass)) {
2134 .arg(ex.getQuery()->getLabel())
2135 .arg(cclass);
2136 }
2137 // Skip it
2138 continue;
2139 }
2140
2141 if (ccdef->getCfgOption()->empty()) {
2142 // Skip classes which don't configure options
2143 continue;
2144 }
2145
2146 co_list.push_back(ccdef->getCfgOption());
2147 }
2148
2149 // Last global options
2150 if (!CfgMgr::instance().getCurrentCfg()->getCfgOption()->empty()) {
2151 co_list.push_back(CfgMgr::instance().getCurrentCfg()->getCfgOption());
2152 }
2153}
2154
2155void
2157 // Get the subnet relevant for the client. We will need it
2158 // to get the options associated with it.
2159 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2160 // If we can't find the subnet for the client there is no way
2161 // to get the options to be sent to a client. We don't log an
2162 // error because it will be logged by the assignLease method
2163 // anyway.
2164 if (!subnet) {
2165 return;
2166 }
2167
2168 // Unlikely short cut
2169 const CfgOptionList& co_list = ex.getCfgOptionList();
2170 if (co_list.empty()) {
2171 return;
2172 }
2173
2174 Pkt4Ptr query = ex.getQuery();
2175 Pkt4Ptr resp = ex.getResponse();
2176 set<uint8_t> requested_opts;
2177
2178 // try to get the 'Parameter Request List' option which holds the
2179 // codes of requested options.
2180 OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
2182
2183 // Get the list of options that client requested.
2184 if (option_prl) {
2185 for (uint16_t code : option_prl->getValues()) {
2186 static_cast<void>(requested_opts.insert(code));
2187 }
2188 }
2189
2190 std::set<uint8_t> cancelled_opts;
2191 const auto& cclasses = query->getClasses();
2192
2193 // Iterate on the configured option list to add persistent and
2194 // cancelled options.
2195 for (auto const& copts : co_list) {
2196 const OptionContainerPtr& opts = copts->getAll(DHCP4_OPTION_SPACE);
2197 if (!opts) {
2198 continue;
2199 }
2200 // Get persistent options.
2201 const OptionContainerPersistIndex& pidx = opts->get<2>();
2202 const OptionContainerPersistRange& prange = pidx.equal_range(true);
2203 BOOST_FOREACH(auto const& desc, prange) {
2204 // Add the persistent option code to requested options.
2205 if (desc.option_) {
2206 uint8_t code = static_cast<uint8_t>(desc.option_->getType());
2207 static_cast<void>(requested_opts.insert(code));
2208 }
2209 }
2210 // Get cancelled options.
2211 const OptionContainerCancelIndex& cidx = opts->get<5>();
2212 const OptionContainerCancelRange& crange = cidx.equal_range(true);
2213 BOOST_FOREACH(auto const& desc, crange) {
2214 // Add the cancelled option code to cancelled options.
2215 if (desc.option_) {
2216 uint8_t code = static_cast<uint8_t>(desc.option_->getType());
2217 static_cast<void>(cancelled_opts.insert(code));
2218 }
2219 }
2220 }
2221
2222 // For each requested option code get the first instance of the option
2223 // to be returned to the client.
2224 for (uint8_t opt : requested_opts) {
2225 if (cancelled_opts.count(opt) > 0) {
2226 continue;
2227 }
2228 // Skip special cases: DHO_VIVSO_SUBOPTIONS.
2229 if (opt == DHO_VIVSO_SUBOPTIONS) {
2230 continue;
2231 }
2232 // Add nothing when it is already there.
2233 if (!resp->getOption(opt)) {
2234 // Iterate on the configured option list
2235 for (auto const& copts : co_list) {
2237 opt, cclasses);
2238 if (desc.option_) {
2239 // Got it: add it and jump to the outer loop
2240 resp->addOption(desc.option_);
2241 break;
2242 }
2243 }
2244 }
2245 }
2246
2247 // Special cases for vendor class and options which are identified
2248 // by the code/type and the vendor/enterprise id vs. the code/type only.
2249 if ((requested_opts.count(DHO_VIVCO_SUBOPTIONS) > 0) &&
2250 (cancelled_opts.count(DHO_VIVCO_SUBOPTIONS) == 0)) {
2251 // Keep vendor ids which are already in the response to insert
2252 // VIVCO options at most once per vendor.
2253 set<uint32_t> vendor_ids;
2254 // Get what already exists in the response.
2255 for (auto const& opt : resp->getOptions(DHO_VIVCO_SUBOPTIONS)) {
2256 OptionVendorClassPtr vendor_opts;
2257 vendor_opts = boost::dynamic_pointer_cast<OptionVendorClass>(opt.second);
2258 if (vendor_opts) {
2259 uint32_t vendor_id = vendor_opts->getVendorId();
2260 static_cast<void>(vendor_ids.insert(vendor_id));
2261 }
2262 }
2263 // Iterate on the configured option list.
2264 for (auto const& copts : co_list) {
2265 for (auto const& desc : copts->getList(DHCP4_OPTION_SPACE,
2267 if (!desc.option_ || !desc.allowedForClientClasses(cclasses)) {
2268 continue;
2269 }
2270 OptionVendorClassPtr vendor_opts =
2271 boost::dynamic_pointer_cast<OptionVendorClass>(desc.option_);
2272 if (!vendor_opts) {
2273 continue;
2274 }
2275 // Is the vendor id already in the response?
2276 uint32_t vendor_id = vendor_opts->getVendorId();
2277 if (vendor_ids.count(vendor_id) > 0) {
2278 continue;
2279 }
2280 // Got it: add it.
2281 resp->Pkt::addOption(desc.option_);
2282 static_cast<void>(vendor_ids.insert(vendor_id));
2283 }
2284 }
2285 }
2286
2287 if ((requested_opts.count(DHO_VIVSO_SUBOPTIONS) > 0) &&
2288 (cancelled_opts.count(DHO_VIVSO_SUBOPTIONS) == 0)) {
2289 // Keep vendor ids which are already in the response to insert
2290 // VIVSO options at most once per vendor.
2291 set<uint32_t> vendor_ids;
2292 // Get what already exists in the response.
2293 for (auto const& opt : resp->getOptions(DHO_VIVSO_SUBOPTIONS)) {
2294 OptionVendorPtr vendor_opts;
2295 vendor_opts = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
2296 if (vendor_opts) {
2297 uint32_t vendor_id = vendor_opts->getVendorId();
2298 static_cast<void>(vendor_ids.insert(vendor_id));
2299 }
2300 }
2301 // Iterate on the configured option list
2302 for (auto const& copts : co_list) {
2303 for (auto const& desc : copts->getList(DHCP4_OPTION_SPACE,
2305 if (!desc.option_ || !desc.allowedForClientClasses(cclasses)) {
2306 continue;
2307 }
2308 OptionVendorPtr vendor_opts =
2309 boost::dynamic_pointer_cast<OptionVendor>(desc.option_);
2310 if (!vendor_opts) {
2311 continue;
2312 }
2313 // Is the vendor id already in the response?
2314 uint32_t vendor_id = vendor_opts->getVendorId();
2315 if (vendor_ids.count(vendor_id) > 0) {
2316 continue;
2317 }
2318 // Append a fresh vendor option as the next method should
2319 // add suboptions to it.
2320 vendor_opts.reset(new OptionVendor(Option::V4, vendor_id));
2321 resp->Pkt::addOption(vendor_opts);
2322 static_cast<void>(vendor_ids.insert(vendor_id));
2323 }
2324 }
2325 }
2326}
2327
2328void
2330 // Get the configured subnet suitable for the incoming packet.
2331 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2332
2333 const CfgOptionList& co_list = ex.getCfgOptionList();
2334
2335 // Leave if there is no subnet matching the incoming packet.
2336 // There is no need to log the error message here because
2337 // it will be logged in the assignLease() when it fails to
2338 // pick the suitable subnet. We don't want to duplicate
2339 // error messages in such case.
2340 //
2341 // Also, if there's no options to possibly assign, give up.
2342 if (!subnet || co_list.empty()) {
2343 return;
2344 }
2345
2346 Pkt4Ptr query = ex.getQuery();
2347 Pkt4Ptr resp = ex.getResponse();
2348 set<uint32_t> vendor_ids;
2349
2350 // The server could have provided the option using client classification or
2351 // hooks. If there're vendor info options in the response already, use them.
2352 map<uint32_t, OptionVendorPtr> vendor_rsps;
2353 for (auto const& opt : resp->getOptions(DHO_VIVSO_SUBOPTIONS)) {
2354 OptionVendorPtr vendor_rsp;
2355 vendor_rsp = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
2356 if (vendor_rsp) {
2357 uint32_t vendor_id = vendor_rsp->getVendorId();
2358 vendor_rsps[vendor_id] = vendor_rsp;
2359 static_cast<void>(vendor_ids.insert(vendor_id));
2360 }
2361 }
2362
2363 // Next, try to get the vendor-id from the client packet's
2364 // vendor-specific information option (125).
2365 map<uint32_t, OptionVendorPtr> vendor_reqs;
2366 for (auto const& opt : query->getOptions(DHO_VIVSO_SUBOPTIONS)) {
2367 OptionVendorPtr vendor_req;
2368 vendor_req = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
2369 if (vendor_req) {
2370 uint32_t vendor_id = vendor_req->getVendorId();
2371 vendor_reqs[vendor_id] = vendor_req;
2372 static_cast<void>(vendor_ids.insert(vendor_id));
2373 }
2374 }
2375
2376 // Finally, try to get the vendor-id from the client packet's
2377 // vendor-specific class option (124).
2378 for (auto const& opt : query->getOptions(DHO_VIVCO_SUBOPTIONS)) {
2379 OptionVendorClassPtr vendor_class;
2380 vendor_class = boost::dynamic_pointer_cast<OptionVendorClass>(opt.second);
2381 if (vendor_class) {
2382 uint32_t vendor_id = vendor_class->getVendorId();
2383 static_cast<void>(vendor_ids.insert(vendor_id));
2384 }
2385 }
2386
2387 // If there's no vendor option in either request or response, then there's no way
2388 // to figure out what the vendor-id values are and we give up.
2389 if (vendor_ids.empty()) {
2390 return;
2391 }
2392
2393 map<uint32_t, set<uint8_t> > requested_opts;
2394
2395 // Let's try to get ORO within that vendor-option.
2396 // This is specific to vendor-id=4491 (Cable Labs). Other vendors may have
2397 // different policies.
2399 if (vendor_reqs.count(VENDOR_ID_CABLE_LABS) > 0) {
2400 OptionVendorPtr vendor_req = vendor_reqs[VENDOR_ID_CABLE_LABS];
2401 OptionPtr oro_generic = vendor_req->getOption(DOCSIS3_V4_ORO);
2402 if (oro_generic) {
2403 // Vendor ID 4491 makes Kea look at DOCSIS3_V4_OPTION_DEFINITIONS
2404 // when parsing options. Based on that, oro_generic will have been
2405 // created as an OptionUint8Array, but might not be for other
2406 // vendor IDs.
2407 oro = boost::dynamic_pointer_cast<OptionUint8Array>(oro_generic);
2408 }
2409 if (oro) {
2410 set<uint8_t> oro_req_opts;
2411 for (uint8_t code : oro->getValues()) {
2412 static_cast<void>(oro_req_opts.insert(code));
2413 }
2414 requested_opts[VENDOR_ID_CABLE_LABS] = oro_req_opts;
2415 }
2416 }
2417
2418 const auto& cclasses = query->getClasses();
2419 for (uint32_t vendor_id : vendor_ids) {
2420
2421 std::set<uint8_t> cancelled_opts;
2422
2423 // Iterate on the configured option list to add persistent and
2424 // cancelled options,
2425 for (auto const& copts : co_list) {
2426 const OptionContainerPtr& opts = copts->getAll(vendor_id);
2427 if (!opts) {
2428 continue;
2429 }
2430
2431 // Get persistent options.
2432 const OptionContainerPersistIndex& pidx = opts->get<2>();
2433 const OptionContainerPersistRange& prange = pidx.equal_range(true);
2434 BOOST_FOREACH(auto const& desc, prange) {
2435 // Add the persistent option code to requested options.
2436 if (desc.option_) {
2437 uint8_t code = static_cast<uint8_t>(desc.option_->getType());
2438 static_cast<void>(requested_opts[vendor_id].insert(code));
2439 }
2440 }
2441
2442 // Get cancelled options.
2443 const OptionContainerCancelIndex& cidx = opts->get<5>();
2444 const OptionContainerCancelRange& crange = cidx.equal_range(true);
2445 BOOST_FOREACH(auto const& desc, crange) {
2446 // Add the cancelled option code to cancelled options.
2447 if (desc.option_) {
2448 uint8_t code = static_cast<uint8_t>(desc.option_->getType());
2449 static_cast<void>(cancelled_opts.insert(code));
2450 }
2451 }
2452 }
2453
2454 // If there is nothing to add don't do anything with this vendor.
2455 // This will explicitly not echo back vendor options from the request
2456 // that either correspond to a vendor not known to Kea even if the
2457 // option encapsulates data or there are no persistent options
2458 // configured for this vendor so Kea does not send any option back.
2459 if (requested_opts[vendor_id].empty()) {
2460 continue;
2461 }
2462
2463
2464 // It's possible that vivso was inserted already by client class or
2465 // a hook. If that is so, let's use it.
2466 OptionVendorPtr vendor_rsp;
2467 if (vendor_rsps.count(vendor_id) > 0) {
2468 vendor_rsp = vendor_rsps[vendor_id];
2469 } else {
2470 vendor_rsp.reset(new OptionVendor(Option::V4, vendor_id));
2471 }
2472
2473 // Get the list of options that client requested.
2474 bool added = false;
2475
2476 for (uint8_t opt : requested_opts[vendor_id]) {
2477 if (cancelled_opts.count(opt) > 0) {
2478 continue;
2479 }
2480 if (!vendor_rsp->getOption(opt)) {
2481 for (auto const& copts : co_list) {
2482 OptionDescriptor desc = copts->allowedForClientClasses(vendor_id,
2483 opt, cclasses);
2484 if (desc.option_) {
2485 vendor_rsp->addOption(desc.option_);
2486 added = true;
2487 break;
2488 }
2489 }
2490 }
2491 }
2492
2493 // If we added some sub-options and the vendor opts option is not in
2494 // the response already, then add it.
2495 if (added && (vendor_rsps.count(vendor_id) == 0)) {
2496 resp->Pkt::addOption(vendor_rsp);
2497 }
2498 }
2499}
2500
2501void
2503 // Identify options that we always want to send to the
2504 // client (if they are configured).
2505 static const std::vector<uint16_t> required_options = {
2510
2511 // Get the subnet.
2512 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2513 if (!subnet) {
2514 return;
2515 }
2516
2517 // Unlikely short cut
2518 const CfgOptionList& co_list = ex.getCfgOptionList();
2519 if (co_list.empty()) {
2520 return;
2521 }
2522
2523 Pkt4Ptr resp = ex.getResponse();
2524 const auto& cclasses = ex.getQuery()->getClasses();
2525
2526 // Try to find all 'required' options in the outgoing
2527 // message. Those that are not present will be added.
2528 for (auto const& required : required_options) {
2529 OptionPtr opt = resp->getOption(required);
2530 if (!opt) {
2531 // Check whether option has been configured.
2532 for (auto const& copts : co_list) {
2534 required, cclasses);
2535 if (desc.option_) {
2536 resp->addOption(desc.option_);
2537 break;
2538 }
2539 }
2540 }
2541 }
2542}
2543
2544void
2546 // It is possible that client has sent both Client FQDN and Hostname
2547 // option. In that the server should prefer Client FQDN option and
2548 // ignore the Hostname option.
2549 try {
2550 Pkt4Ptr query = ex.getQuery();
2551 Pkt4Ptr resp = ex.getResponse();
2552 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
2553 (query->getOption(DHO_FQDN));
2554 if (fqdn) {
2556 .arg(query->getLabel());
2557 processClientFqdnOption(ex);
2558
2559 } else {
2562 .arg(query->getLabel());
2563 processHostnameOption(ex);
2564 }
2565
2566 // Based on the output option added to the response above, we figure out
2567 // the values for the hostname and dns flags to set in the context. These
2568 // will be used to populate the lease.
2569 std::string hostname;
2570 bool fqdn_fwd = false;
2571 bool fqdn_rev = false;
2572
2573 OptionStringPtr opt_hostname;
2574 fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>(resp->getOption(DHO_FQDN));
2575 if (fqdn) {
2576 hostname = fqdn->getDomainName();
2577 CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn, fqdn_fwd, fqdn_rev);
2578 } else {
2579 opt_hostname = boost::dynamic_pointer_cast<OptionString>
2580 (resp->getOption(DHO_HOST_NAME));
2581
2582 if (opt_hostname) {
2583 hostname = opt_hostname->getValue();
2584 // DHO_HOST_NAME is string option which cannot be blank,
2585 // we use "." to know we should replace it with a fully
2586 // generated name. The local string variable needs to be
2587 // blank in logic below.
2588 if (hostname == ".") {
2589 hostname = "";
2590 }
2591
2594 if (ex.getContext()->getDdnsParams()->getEnableUpdates()) {
2595 fqdn_fwd = true;
2596 fqdn_rev = true;
2597 }
2598 }
2599 }
2600
2601 // Optionally, call a hook that may possibly override the decisions made
2602 // earlier.
2603 if (HooksManager::calloutsPresent(Hooks.hook_index_ddns4_update_)) {
2604 CalloutHandlePtr callout_handle = getCalloutHandle(query);
2605
2606 // Use the RAII wrapper to make sure that the callout handle state is
2607 // reset when this object goes out of scope. All hook points must do
2608 // it to prevent possible circular dependency between the callout
2609 // handle and its arguments.
2610 ScopedCalloutHandleState callout_handle_state(callout_handle);
2611
2612 // Setup the callout arguments.
2613 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2614 callout_handle->setArgument("query4", query);
2615 callout_handle->setArgument("response4", resp);
2616 callout_handle->setArgument("subnet4", subnet);
2617 callout_handle->setArgument("hostname", hostname);
2618 callout_handle->setArgument("fwd-update", fqdn_fwd);
2619 callout_handle->setArgument("rev-update", fqdn_rev);
2620 callout_handle->setArgument("ddns-params", ex.getContext()->getDdnsParams());
2621
2622 // Call callouts
2623 HooksManager::callCallouts(Hooks.hook_index_ddns4_update_, *callout_handle);
2624
2625 // Let's get the parameters returned by hook.
2626 string hook_hostname;
2627 bool hook_fqdn_fwd = false;
2628 bool hook_fqdn_rev = false;
2629 callout_handle->getArgument("hostname", hook_hostname);
2630 callout_handle->getArgument("fwd-update", hook_fqdn_fwd);
2631 callout_handle->getArgument("rev-update", hook_fqdn_rev);
2632
2633 // If there's anything changed by the hook, log it and then update
2634 // the parameters.
2635 if ((hostname != hook_hostname) || (fqdn_fwd != hook_fqdn_fwd) ||
2636 (fqdn_rev != hook_fqdn_rev)) {
2638 .arg(hostname).arg(hook_hostname).arg(fqdn_fwd).arg(hook_fqdn_fwd)
2639 .arg(fqdn_rev).arg(hook_fqdn_rev);
2640 hostname = hook_hostname;
2641 fqdn_fwd = hook_fqdn_fwd;
2642 fqdn_rev = hook_fqdn_rev;
2643
2644 // If there's an outbound host-name option in the response we
2645 // need to updated it with the new host name.
2646 OptionStringPtr hostname_opt = boost::dynamic_pointer_cast<OptionString>
2647 (resp->getOption(DHO_HOST_NAME));
2648 if (hostname_opt) {
2649 hostname_opt->setValue(hook_hostname);
2650 }
2651
2652 // If there's an outbound FQDN option in the response we need
2653 // to update it with the new host name.
2654 fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>(resp->getOption(DHO_FQDN));
2655 if (fqdn) {
2656 fqdn->setDomainName(hook_hostname, Option4ClientFqdn::FULL);
2657 // Hook disabled updates, Set flags back to client accordingly.
2658 fqdn->setFlag(Option4ClientFqdn::FLAG_S, 0);
2659 fqdn->setFlag(Option4ClientFqdn::FLAG_N, 1);
2660 }
2661 }
2662 }
2663
2664 // Update the context
2665 auto ctx = ex.getContext();
2666 ctx->fwd_dns_update_ = fqdn_fwd;
2667 ctx->rev_dns_update_ = fqdn_rev;
2668 ctx->hostname_ = hostname;
2669
2670 } catch (const Exception& e) {
2671 // In some rare cases it is possible that the client's name processing
2672 // fails. For example, the Hostname option may be malformed, or there
2673 // may be an error in the server's logic which would cause multiple
2674 // attempts to add the same option to the response message. This
2675 // error message aggregates all these errors so they can be diagnosed
2676 // from the log. We don't want to throw an exception here because,
2677 // it will impact the processing of the whole packet. We rather want
2678 // the processing to continue, even if the client's name is wrong.
2680 .arg(ex.getQuery()->getLabel())
2681 .arg(e.what());
2682 }
2683}
2684
2685void
2686Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
2687 // Obtain the FQDN option from the client's message.
2688 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
2689 Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
2690
2692 .arg(ex.getQuery()->getLabel())
2693 .arg(fqdn->toText());
2694
2695 // Create the DHCPv4 Client FQDN Option to be included in the server's
2696 // response to a client.
2697 Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
2698
2699 // Set the server S, N, and O flags based on client's flags and
2700 // current configuration.
2702 d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp,
2703 *(ex.getContext()->getDdnsParams()));
2704 // Carry over the client's E flag.
2707
2708 if (ex.getContext()->currentHost() &&
2709 !ex.getContext()->currentHost()->getHostname().empty()) {
2710 fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->currentHost()->getHostname(),
2711 *(ex.getContext()->getDdnsParams()), true),
2713
2714 } else {
2715 // Adjust the domain name based on domain name value and type sent by the
2716 // client and current configuration.
2717 d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp,
2718 *(ex.getContext()->getDdnsParams()));
2719 }
2720
2721 // Add FQDN option to the response message. Note that, there may be some
2722 // cases when server may choose not to include the FQDN option in a
2723 // response to a client. In such cases, the FQDN should be removed from the
2724 // outgoing message. In theory we could cease to include the FQDN option
2725 // in this function until it is confirmed that it should be included.
2726 // However, we include it here for simplicity. Functions used to acquire
2727 // lease for a client will scan the response message for FQDN and if it
2728 // is found they will take necessary actions to store the FQDN information
2729 // in the lease database as well as to generate NameChangeRequests to DNS.
2730 // If we don't store the option in the response message, we will have to
2731 // propagate it in the different way to the functions which acquire the
2732 // lease. This would require modifications to the API of this class.
2734 .arg(ex.getQuery()->getLabel())
2735 .arg(fqdn_resp->toText());
2736 ex.getResponse()->addOption(fqdn_resp);
2737}
2738
2739void
2740Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
2741 // Fetch D2 configuration.
2743
2744 // Obtain the Hostname option from the client's message.
2745 OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
2746 (ex.getQuery()->getOption(DHO_HOST_NAME));
2747
2748 if (opt_hostname) {
2750 .arg(ex.getQuery()->getLabel())
2751 .arg(opt_hostname->getValue());
2752 }
2753
2755
2756 // Hostname reservations take precedence over any other configuration,
2757 // i.e. DDNS configuration. If we have a reserved hostname we should
2758 // use it and send it back.
2759 if (ctx->currentHost() && !ctx->currentHost()->getHostname().empty()) {
2760 // Qualify if there is a suffix configured.
2761 std::string hostname = d2_mgr.qualifyName(ctx->currentHost()->getHostname(),
2762 *(ex.getContext()->getDdnsParams()), false);
2763 // Convert it to lower case.
2764 boost::algorithm::to_lower(hostname);
2766 .arg(ex.getQuery()->getLabel())
2767 .arg(hostname);
2768
2769 // Add it to the response
2770 OptionStringPtr opt_hostname_resp(new OptionString(Option::V4, DHO_HOST_NAME, hostname));
2771 ex.getResponse()->addOption(opt_hostname_resp);
2772
2773 // We're done here.
2774 return;
2775 }
2776
2777 // There is no reservation for this client however there is still a
2778 // possibility that we'll have to send hostname option to this client
2779 // if the client has included hostname option or the configuration of
2780 // the server requires that we send the option regardless.
2781 D2ClientConfig::ReplaceClientNameMode replace_name_mode =
2782 ex.getContext()->getDdnsParams()->getReplaceClientNameMode();
2783
2784 // If we don't have a hostname then either we'll supply it or do nothing.
2785 if (!opt_hostname) {
2786 // If we're configured to supply it then add it to the response.
2787 // Use the root domain to signal later on that we should replace it.
2788 if (replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
2789 replace_name_mode == D2ClientConfig::RCM_WHEN_NOT_PRESENT) {
2792 .arg(ex.getQuery()->getLabel());
2793 OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
2795 "."));
2796 ex.getResponse()->addOption(opt_hostname_resp);
2797 }
2798
2799 return;
2800 }
2801
2802 // Client sent us a hostname option so figure out what to do with it.
2804 .arg(ex.getQuery()->getLabel())
2805 .arg(opt_hostname->getValue());
2806
2807 std::string hostname = isc::util::str::trim(opt_hostname->getValue());
2808 unsigned int label_count;
2809
2810 try {
2811 // Parsing into labels can throw on malformed content so we're
2812 // going to explicitly catch that here.
2813 label_count = OptionDataTypeUtil::getLabelCount(hostname);
2814 } catch (const std::exception& exc) {
2816 .arg(ex.getQuery()->getLabel())
2817 .arg(exc.what());
2818 return;
2819 }
2820
2821 // The hostname option sent by the client should be at least 1 octet long.
2822 // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
2825 if (label_count == 0) {
2827 .arg(ex.getQuery()->getLabel());
2828 return;
2829 }
2830
2831 // Stores the value we eventually use, so we can send it back.
2832 OptionStringPtr opt_hostname_resp;
2833
2834 // The hostname option may be unqualified or fully qualified. The lab_count
2835 // holds the number of labels for the name. The number of 1 means that
2836 // there is only root label "." (even for unqualified names, as the
2837 // getLabelCount function treats each name as a fully qualified one).
2838 // By checking the number of labels present in the hostname we may infer
2839 // whether client has sent the fully qualified or unqualified hostname.
2840
2841 if ((replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
2842 replace_name_mode == D2ClientConfig::RCM_WHEN_PRESENT)
2843 || label_count < 2) {
2844 // Set to root domain to signal later on that we should replace it.
2845 // DHO_HOST_NAME is a string option which cannot be empty.
2853 opt_hostname_resp.reset(new OptionString(Option::V4, DHO_HOST_NAME, "."));
2854 } else {
2855 // Sanitize the name the client sent us, if we're configured to do so.
2857 ex.getContext()->getDdnsParams()->getHostnameSanitizer();
2858
2859 if (sanitizer) {
2860 hostname = sanitizer->scrub(hostname);
2861 }
2862
2863 // Convert hostname to lower case.
2864 boost::algorithm::to_lower(hostname);
2865
2866 if (label_count == 2) {
2867 // If there are two labels, it means that the client has specified
2868 // the unqualified name. We have to concatenate the unqualified name
2869 // with the domain name. The false value passed as a second argument
2870 // indicates that the trailing dot should not be appended to the
2871 // hostname. We don't want to append the trailing dot because
2872 // we don't know whether the hostname is partial or not and some
2873 // clients do not handle the hostnames with the trailing dot.
2874 opt_hostname_resp.reset(
2876 d2_mgr.qualifyName(hostname, *(ex.getContext()->getDdnsParams()),
2877 false)));
2878 } else {
2879 opt_hostname_resp.reset(new OptionString(Option::V4, DHO_HOST_NAME, hostname));
2880 }
2881 }
2882
2884 .arg(ex.getQuery()->getLabel())
2885 .arg(opt_hostname_resp->getValue());
2886 ex.getResponse()->addOption(opt_hostname_resp);
2887}
2888
2889void
2891 const Lease4Ptr& old_lease,
2892 const DdnsParams& ddns_params) {
2893 if (!lease) {
2895 "NULL lease specified when creating NameChangeRequest");
2896 }
2897
2898 // Nothing to do if updates are not enabled.
2899 if (!ddns_params.getEnableUpdates()) {
2900 return;
2901 }
2902
2903 if ((lease->reuseable_valid_lft_ == 0) &&
2904 (!old_lease || ddns_params.getUpdateOnRenew() ||
2905 !lease->hasIdenticalFqdn(*old_lease))) {
2906 if (old_lease) {
2907 // Queue's up a remove of the old lease's DNS (if needed)
2908 queueNCR(CHG_REMOVE, old_lease);
2909 }
2910
2911 // We may need to generate the NameChangeRequest for the new lease. It
2912 // will be generated only if hostname is set and if forward or reverse
2913 // update has been requested.
2914 queueNCR(CHG_ADD, lease);
2915 }
2916}
2917
2918bool
2920 const ClientClasses& client_classes) {
2921 ConstSubnet4Ptr current_subnet = subnet;
2922 // Try subnets.
2923 while (current_subnet) {
2924 const ConstCfgOptionPtr& co = current_subnet->getCfgOption();
2925 if (!co->empty()) {
2926 OptionDescriptor desc = co->get(DHCP4_OPTION_SPACE,
2928 if (desc.option_) {
2929 subnet = current_subnet;
2930 return (true);
2931 }
2932 }
2933 current_subnet = current_subnet->getNextSubnet(subnet, client_classes);
2934 }
2935 // Try the shared network.
2936 SharedNetwork4Ptr network;
2937 subnet->getSharedNetwork(network);
2938 if (network) {
2939 const ConstCfgOptionPtr& co = network->getCfgOption();
2940 if (!co->empty()) {
2941 OptionDescriptor desc = co->get(DHCP4_OPTION_SPACE,
2943 if (desc.option_) {
2944 return (true);
2945 }
2946 }
2947 }
2948 return (false);
2949}
2950
2951void
2953 // Get the pointers to the query and the response messages.
2954 Pkt4Ptr query = ex.getQuery();
2955 Pkt4Ptr resp = ex.getResponse();
2956
2957 // Get the context.
2959
2960 // Subnet should have been already selected when the context was created.
2961 ConstSubnet4Ptr subnet = ctx->subnet_;
2962
2963 // "Fake" allocation is processing of DISCOVER message. We pretend to do an
2964 // allocation, but we do not put the lease in the database. That is ok,
2965 // because we do not guarantee that the user will get that exact lease. If
2966 // the user selects this server to do actual allocation (i.e. sends REQUEST)
2967 // it should include this hint. That will help us during the actual lease
2968 // allocation.
2969 bool fake_allocation = (query->getType() == DHCPDISCOVER);
2970
2971 // Check if IPv6-Only Preferred was requested.
2972 OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
2974 if (option_prl) {
2975 auto const& requested_opts = option_prl->getValues();
2976 if ((std::find(requested_opts.cbegin(), requested_opts.cend(),
2977 DHO_V6_ONLY_PREFERRED) != requested_opts.cend()) &&
2978 assignZero(subnet, query->getClasses())) {
2979 ex.setIPv6OnlyPreferred(true);
2980 ctx->subnet_ = subnet;
2981 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
2982 if (!fake_allocation) {
2983 resp->setCiaddr(query->getCiaddr());
2984 }
2985 return;
2986 }
2987 }
2988
2989 // Get the server identifier. It will be used to determine the state
2990 // of the client.
2991 OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
2992 OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
2993
2994 // Check if the client has sent a requested IP address option or
2995 // ciaddr.
2996 OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
2997 OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
2999 if (opt_requested_address) {
3000 hint = opt_requested_address->readAddress();
3001
3002 } else if (!query->getCiaddr().isV4Zero()) {
3003 hint = query->getCiaddr();
3004
3005 }
3006
3007 // This flag controls whether or not the server should respond to the clients
3008 // in the INIT-REBOOT state. We will initialize it to a configured value only
3009 // when the client is in that state.
3010 auto authoritative = false;
3011
3012 // If there is no server id and there is a Requested IP Address option
3013 // the client is in the INIT-REBOOT state in which the server has to
3014 // determine whether the client's notion of the address is correct
3015 // and whether the client is known, i.e., has a lease.
3016 auto init_reboot = (!fake_allocation && !opt_serverid && opt_requested_address);
3017 if (init_reboot) {
3019 .arg(query->getLabel())
3020 .arg(hint.toText());
3021
3022 // Find the authoritative flag configuration.
3023 if (subnet) {
3024 authoritative = subnet->getAuthoritative();
3025 } else {
3026 // If there is no subnet, use the global value.
3027 auto flag = CfgMgr::instance().getCurrentCfg()->getConfiguredGlobals()->
3029 if (flag && (flag->getType() == data::Element::boolean)) {
3030 authoritative = flag->boolValue();
3031 }
3032 }
3033 } else if (fake_allocation) {
3035 .arg(query->getLabel())
3036 .arg(hint != IOAddress::IPV4_ZERO_ADDRESS() ? hint.toText() : "(no hint)");
3037 } else {
3039 .arg(query->getLabel())
3040 .arg(hint != IOAddress::IPV4_ZERO_ADDRESS() ? hint.toText() : "(no hint)");
3041 }
3042
3043 // If there is no subnet configuration for that client we ignore the
3044 // request from the INIT-REBOOT client if we're not authoritative, because
3045 // we don't know whether the network configuration is correct for this
3046 // client. We return DHCPNAK if we're authoritative, though.
3047 if (!subnet && (!init_reboot || authoritative)) {
3048 // This particular client is out of luck today. We do not have
3049 // information about the subnet he is connected to. This likely means
3050 // misconfiguration of the server (or some relays).
3051
3052 // Perhaps this should be logged on some higher level?
3054 .arg(query->getLabel())
3055 .arg(query->getRemoteAddr().toText())
3056 .arg(query->getName());
3057 resp->setType(DHCPNAK);
3058 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3059 return;
3060 }
3061
3062 HWAddrPtr hwaddr = query->getHWAddr();
3063
3064 ConstSubnet4Ptr original_subnet = subnet;
3065
3066 // Get client-id. It is not mandatory in DHCPv4.
3067 ClientIdPtr client_id = ex.getContext()->clientid_;
3068
3069 // In the INIT-REBOOT state, a client remembering its previously assigned
3070 // address is trying to confirm whether or not this address is still usable.
3071 if (init_reboot) {
3072 Lease4Ptr lease;
3073
3074 auto const& classes = query->getClasses();
3075
3076 // We used to issue a separate query (two actually: one for client-id
3077 // and another one for hw-addr for) each subnet in the shared network.
3078 // That was horribly inefficient if the client didn't have any lease
3079 // (or there were many subnets and the client happened to be in one
3080 // of the last subnets).
3081 //
3082 // We now issue at most two queries: get all the leases for specific
3083 // client-id and then get all leases for specific hw-address.
3084 if (original_subnet && client_id) {
3085
3086 // Get all the leases for this client-id
3087 Lease4Collection leases_client_id = LeaseMgrFactory::instance().getLease4(*client_id);
3088 if (!leases_client_id.empty()) {
3089 ConstSubnet4Ptr s = original_subnet;
3090
3091 // Among those returned try to find a lease that belongs to
3092 // current shared network.
3093 while (s) {
3094 for (auto const& l : leases_client_id) {
3095 if (l->subnet_id_ == s->getID()) {
3096 lease = l;
3097 break;
3098 }
3099 }
3100
3101 if (lease) {
3102 break;
3103
3104 } else {
3105 s = s->getNextSubnet(original_subnet, classes);
3106 }
3107 }
3108 }
3109 }
3110
3111 // If we haven't found a lease yet, try again by hardware-address.
3112 // The logic is the same.
3113 if (original_subnet && !lease && hwaddr) {
3114
3115 // Get all leases for this particular hw-address.
3116 Lease4Collection leases_hwaddr = LeaseMgrFactory::instance().getLease4(*hwaddr);
3117 if (!leases_hwaddr.empty()) {
3118 ConstSubnet4Ptr s = original_subnet;
3119
3120 // Pick one that belongs to a subnet in this shared network.
3121 while (s) {
3122 for (auto const& l : leases_hwaddr) {
3123 if (l->subnet_id_ == s->getID()) {
3124 lease = l;
3125 break;
3126 }
3127 }
3128
3129 if (lease) {
3130 break;
3131
3132 } else {
3133 s = s->getNextSubnet(original_subnet, classes);
3134 }
3135 }
3136 }
3137 }
3138
3139 // Check the first error case: unknown client. We check this before
3140 // validating the address sent because we don't want to respond if
3141 // we don't know this client, except if we're authoritative.
3142 bool known_client = lease && lease->belongsToClient(hwaddr, client_id);
3143 if (!authoritative && !known_client) {
3146 .arg(query->getLabel())
3147 .arg(hint.toText());
3148
3149 ex.deleteResponse();
3150 return;
3151 }
3152
3153 // If we know this client, check if his notion of the IP address is
3154 // correct, if we don't know him, check if we are authoritative.
3155 if ((known_client && (lease->addr_ != hint)) ||
3156 (!known_client && authoritative) ||
3157 (!original_subnet)) {
3160 .arg(query->getLabel())
3161 .arg(hint.toText());
3162
3163 resp->setType(DHCPNAK);
3164 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3165 return;
3166 }
3167 }
3168
3169 CalloutHandlePtr callout_handle = getCalloutHandle(query);
3170
3171 // We need to set these values in the context as they haven't been set yet.
3172 ctx->requested_address_ = hint;
3173 ctx->fake_allocation_ = fake_allocation;
3174 ctx->callout_handle_ = callout_handle;
3175
3176 // If client query contains an FQDN or Hostname option, server
3177 // should respond to the client with the appropriate FQDN or Hostname
3178 // option to indicate if it takes responsibility for the DNS updates.
3179 // This is also the source for the hostname and dns flags that are
3180 // initially added to the lease. In most cases, this information is
3181 // good now. If we end up changing subnets in allocation we'll have to
3182 // do it again and then update the lease.
3184
3185 // Get a lease.
3186 Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
3187
3188 bool reprocess_client_name = false;
3189 if (lease) {
3190 // Since we have a lease check for pool-level DDNS parameters.
3191 // If there are any we need to call processClientName() again.
3192 auto ddns_params = ex.getContext()->getDdnsParams();
3193 auto pool = ddns_params->setPoolFromAddress(lease->addr_);
3194 if (pool) {
3195 reprocess_client_name = pool->hasDdnsParameters();
3196 }
3197 }
3198
3199 // Subnet may be modified by the allocation engine, if the initial subnet
3200 // belongs to a shared network.
3201 if (subnet && ctx->subnet_ && subnet->getID() != ctx->subnet_->getID()) {
3202 // We changed subnets and that means DDNS parameters might be different
3203 // so we need to rerun client name processing logic. Arguably we could
3204 // compare DDNS parameters for both subnets and then decide if we need
3205 // to rerun the name logic, but that's not likely to be any faster than
3206 // just re-running the name logic. @todo When inherited parameter
3207 // performance is improved this argument could be revisited.
3208 // Another case is the new subnet has a reserved hostname.
3209 SharedNetwork4Ptr network;
3210 subnet->getSharedNetwork(network);
3212 .arg(query->getLabel())
3213 .arg(subnet->toText())
3214 .arg(ctx->subnet_->toText())
3215 .arg(network ? network->getName() : "<no network?>");
3216
3217 subnet = ctx->subnet_;
3218 if (lease) {
3219 reprocess_client_name = true;
3220 }
3221 }
3222
3223 // Tracks whether or not the client name (FQDN or host) has changed since
3224 // the lease was allocated.
3225 bool client_name_changed = false;
3226
3227 if (reprocess_client_name) {
3228 // First, we need to remove the prior values from the response and reset
3229 // those in context, to give processClientName a clean slate.
3230 resp->delOption(DHO_FQDN);
3231 resp->delOption(DHO_HOST_NAME);
3232 ctx->hostname_ = "";
3233 ctx->fwd_dns_update_ = false;
3234 ctx->rev_dns_update_ = false;
3235
3236 // Regenerate the name and dns flags.
3238
3239 // If the results are different from the values already on the
3240 // lease, flag it so the lease gets updated down below.
3241 if ((lease->hostname_ != ctx->hostname_) ||
3242 (lease->fqdn_fwd_ != ctx->fwd_dns_update_) ||
3243 (lease->fqdn_rev_ != ctx->rev_dns_update_)) {
3244 lease->hostname_ = ctx->hostname_;
3245 lease->fqdn_fwd_ = ctx->fwd_dns_update_;
3246 lease->fqdn_rev_ = ctx->rev_dns_update_;
3247 client_name_changed = true;
3248 }
3249 }
3250
3251 if (lease) {
3252 // We have a lease! Let's set it in the packet and send it back to
3253 // the client.
3254 if (fake_allocation) {
3256 .arg(query->getLabel())
3257 .arg(lease->addr_.toText());
3258 } else {
3260 .arg(query->getLabel())
3261 .arg(lease->addr_.toText())
3262 .arg(Lease::lifetimeToText(lease->valid_lft_));
3263 }
3264
3265 // We're logging this here, because this is the place where we know
3266 // which subnet has been actually used for allocation. If the
3267 // client identifier matching is disabled, we want to make sure that
3268 // the user is notified.
3269 if (!ctx->subnet_->getMatchClientId()) {
3271 .arg(ctx->query_->getLabel())
3272 .arg(ctx->subnet_->getID());
3273 }
3274
3275 resp->setYiaddr(lease->addr_);
3276
3281 if (!fake_allocation) {
3282 // If this is a renewing client it will set a ciaddr which the
3283 // server may include in the response. If this is a new allocation
3284 // the client will set ciaddr to 0 and this will also be propagated
3285 // to the server's resp.
3286 resp->setCiaddr(query->getCiaddr());
3287 }
3288
3289 // We may need to update FQDN or hostname if the server is to generate
3290 // a new name from the allocated IP address or if the allocation engine
3291 // switched to a different subnet within a shared network.
3292 postAllocateNameUpdate(ctx, lease, query, resp, client_name_changed);
3293
3294 // Reuse the lease if possible.
3295 if (lease->reuseable_valid_lft_ > 0) {
3296 lease->valid_lft_ = lease->reuseable_valid_lft_;
3298 .arg(query->getLabel())
3299 .arg(lease->addr_.toText())
3300 .arg(Lease::lifetimeToText(lease->valid_lft_));
3301
3302 // Increment the reuse statistics.
3303 StatsMgr::instance().addValue("v4-lease-reuses", int64_t(1));
3304 StatsMgr::instance().addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
3305 "v4-lease-reuses"),
3306 int64_t(1));
3307 }
3308
3309 // IP Address Lease time (type 51)
3310 // If we're not allocating on discover then we just sent the lifetime on the lease.
3311 // Otherwise (i.e. offer_lft > 0), the lease's lifetime has been set to offer_lft but
3312 // we want to send the client the proper valid lifetime so we have to fetch it.
3313 auto send_lft = (ctx->offer_lft_ ? AllocEngine::getValidLft(*ctx) : lease->valid_lft_);
3315
3316 resp->addOption(opt);
3317
3318 // Subnet mask (type 1)
3319 resp->addOption(getNetmaskOption(subnet));
3320
3321 // Set T1 and T2 per configuration.
3322 setTeeTimes(lease, subnet, resp);
3323
3324 // Create NameChangeRequests if this is a real allocation.
3325 if (!fake_allocation) {
3326 try {
3327 createNameChangeRequests(lease, ctx->old_lease_,
3328 *ex.getContext()->getDdnsParams());
3329 } catch (const Exception& ex) {
3331 .arg(query->getLabel())
3332 .arg(ex.what());
3333 }
3334 }
3335
3336 } else {
3337 // Allocation engine did not allocate a lease. The engine logged
3338 // cause of that failure.
3339 if (ctx->unknown_requested_addr_) {
3340 ConstSubnet4Ptr s = original_subnet;
3341 // Address might have been rejected via class guard (i.e. not
3342 // allowed for this client). We need to determine if we truly
3343 // do not know about the address or whether this client just
3344 // isn't allowed to have that address. We should only DHCPNAK
3345 // For the latter.
3346 while (s) {
3347 if (s->inPool(Lease::TYPE_V4, hint)) {
3348 break;
3349 }
3350
3351 s = s->getNextSubnet(original_subnet);
3352 }
3353
3354 // If we didn't find a subnet, it's not an address we know about
3355 // so we drop the DHCPNAK.
3356 if (!s) {
3359 .arg(query->getLabel())
3360 .arg(query->getCiaddr().toText())
3361 .arg(opt_requested_address ?
3362 opt_requested_address->readAddress().toText() : "(no address)");
3363 ex.deleteResponse();
3364 return;
3365 }
3366 }
3367
3370 .arg(query->getLabel())
3371 .arg(query->getCiaddr().toText())
3372 .arg(opt_requested_address ?
3373 opt_requested_address->readAddress().toText() : "(no address)");
3374
3375 resp->setType(DHCPNAK);
3376 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3377
3378 resp->delOption(DHO_FQDN);
3379 resp->delOption(DHO_HOST_NAME);
3380 }
3381}
3382
3383void
3385 const Pkt4Ptr& query, const Pkt4Ptr& resp, bool client_name_changed) {
3386 // We may need to update FQDN or hostname if the server is to generate
3387 // new name from the allocated IP address or if the allocation engine
3388 // has switched to a different subnet within a shared network. Get
3389 // FQDN and hostname options from the response.
3390 OptionStringPtr opt_hostname;
3391 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
3392 Option4ClientFqdn>(resp->getOption(DHO_FQDN));
3393 if (!fqdn) {
3394 opt_hostname = boost::dynamic_pointer_cast<OptionString>(resp->getOption(DHO_HOST_NAME));
3395 if (!opt_hostname) {
3396 // We don't have either one, nothing to do.
3397 return;
3398 }
3399 }
3400
3401 // Empty hostname on the lease means we need to generate it.
3402 if (lease->hostname_.empty()) {
3403 // Note that if we have received the hostname option, rather than
3404 // Client FQDN the trailing dot is not appended to the generated
3405 // hostname because some clients don't handle the trailing dot in
3406 // the hostname. Whether the trailing dot is appended or not is
3407 // controlled by the second argument to the generateFqdn().
3408 lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
3409 .generateFqdn(lease->addr_, *(ctx->getDdnsParams()), static_cast<bool>(fqdn));
3410
3412 .arg(query->getLabel())
3413 .arg(lease->hostname_);
3414
3415 client_name_changed = true;
3416 }
3417
3418 if (client_name_changed) {
3419 // The operations below are rather safe, but we want to catch
3420 // any potential exceptions (e.g. invalid lease database backend
3421 // implementation) and log an error.
3422 try {
3424 if (!ctx->fake_allocation_ || (ctx->offer_lft_ > 0)) {
3425 // The lease can't be reused.
3426 lease->reuseable_valid_lft_ = 0;
3427
3428 // The lease update should be safe, because the lease should
3429 // be already in the database. In most cases the exception
3430 // would be thrown if the lease was missing.
3432 }
3433
3434 // The name update in the outbound option should be also safe,
3435 // because the generated name is well formed.
3436 if (fqdn) {
3437 fqdn->setDomainName(lease->hostname_, Option4ClientFqdn::FULL);
3438 } else {
3439 opt_hostname->setValue(lease->hostname_);
3440 }
3441 } catch (const Exception& ex) {
3443 .arg(query->getLabel())
3444 .arg(lease->hostname_)
3445 .arg(ex.what());
3446 }
3447 }
3448}
3449
3451void
3452Dhcpv4Srv::setTeeTimes(const Lease4Ptr& lease, const ConstSubnet4Ptr& subnet, Pkt4Ptr resp) {
3453
3454 uint32_t t2_time = 0;
3455 // If T2 is explicitly configured we'll use try value.
3456 if (!subnet->getT2().unspecified()) {
3457 t2_time = subnet->getT2();
3458 } else if (subnet->getCalculateTeeTimes()) {
3459 // Calculating tee times is enabled, so calculated it.
3460 t2_time = static_cast<uint32_t>(round(subnet->getT2Percent() * (lease->valid_lft_)));
3461 }
3462
3463 // Send the T2 candidate value only if it's sane: to be sane it must be less than
3464 // the valid life time.
3465 uint32_t timer_ceiling = lease->valid_lft_;
3466 if (t2_time > 0 && t2_time < timer_ceiling) {
3468 resp->addOption(t2);
3469 // When we send T2, timer ceiling for T1 becomes T2.
3470 timer_ceiling = t2_time;
3471 }
3472
3473 uint32_t t1_time = 0;
3474 // If T1 is explicitly configured we'll use try value.
3475 if (!subnet->getT1().unspecified()) {
3476 t1_time = subnet->getT1();
3477 } else if (subnet->getCalculateTeeTimes()) {
3478 // Calculating tee times is enabled, so calculate it.
3479 t1_time = static_cast<uint32_t>(round(subnet->getT1Percent() * (lease->valid_lft_)));
3480 }
3481
3482 // Send T1 if it's sane: If we sent T2, T1 must be less than that. If not it must be
3483 // less than the valid life time.
3484 if (t1_time > 0 && t1_time < timer_ceiling) {
3486 resp->addOption(t1);
3487 }
3488}
3489
3490uint16_t
3492
3493 // Look for a relay-port RAI sub-option in the query.
3494 const Pkt4Ptr& query = ex.getQuery();
3495 const OptionPtr& rai = query->getOption(DHO_DHCP_AGENT_OPTIONS);
3496 if (rai && rai->getOption(RAI_OPTION_RELAY_PORT)) {
3497 // Got the sub-option so use the remote port set by the relay.
3498 return (query->getRemotePort());
3499 }
3500 return (0);
3501}
3502
3503void
3505 adjustRemoteAddr(ex);
3506
3507 // Initialize the pointers to the client's message and the server's
3508 // response.
3509 Pkt4Ptr query = ex.getQuery();
3510 Pkt4Ptr response = ex.getResponse();
3511
3512 // The DHCPINFORM is generally unicast to the client. The only situation
3513 // when the server is unable to unicast to the client is when the client
3514 // doesn't include ciaddr and the message is relayed. In this case the
3515 // server has to reply via relay agent. For other messages we send back
3516 // through relay if message is relayed, and unicast to the client if the
3517 // message is not relayed.
3518 // If client port was set from the command line enforce all responses
3519 // to it. Of course it is only for testing purposes.
3520 // Note that the call to this function may throw if invalid combination
3521 // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
3522 // giaddr != 0). The exception will propagate down and eventually cause the
3523 // packet to be discarded.
3524 if (client_port_) {
3525 response->setRemotePort(client_port_);
3526 } else if (((query->getType() == DHCPINFORM) &&
3527 ((!query->getCiaddr().isV4Zero()) ||
3528 (!query->isRelayed() && !query->getRemoteAddr().isV4Zero()))) ||
3529 ((query->getType() != DHCPINFORM) && !query->isRelayed())) {
3530 response->setRemotePort(DHCP4_CLIENT_PORT);
3531
3532 } else {
3533 // RFC 8357 section 5.1
3534 uint16_t relay_port = checkRelayPort(ex);
3535 response->setRemotePort(relay_port ? relay_port : DHCP4_SERVER_PORT);
3536 }
3537
3538 CfgIfacePtr cfg_iface = CfgMgr::instance().getCurrentCfg()->getCfgIface();
3539 if (query->isRelayed() &&
3540 (cfg_iface->getSocketType() == CfgIface::SOCKET_UDP) &&
3541 (cfg_iface->getOutboundIface() == CfgIface::USE_ROUTING)) {
3542
3543 // Mark the response to follow routing
3544 response->setLocalAddr(IOAddress::IPV4_ZERO_ADDRESS());
3545 response->resetIndex();
3546 // But keep the interface name
3547 response->setIface(query->getIface());
3548
3549 } else {
3550
3551 IOAddress local_addr = query->getLocalAddr();
3552
3553 // In many cases the query is sent to a broadcast address. This address
3554 // appears as a local address in the query message. We can't simply copy
3555 // this address to a response message and use it as a source address.
3556 // Instead we will need to use the address assigned to the interface
3557 // on which the query has been received. In other cases, we will just
3558 // use this address as a source address for the response.
3559 // Do the same for DHCPv4-over-DHCPv6 exchanges.
3560 if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
3561 local_addr = IfaceMgr::instance().getSocket(query).addr_;
3562 }
3563
3564 // We assume that there is an appropriate socket bound to this address
3565 // and that the address is correct. This is safe assumption because
3566 // the local address of the query is set when the query is received.
3567 // The query sent to an incorrect address wouldn't have been received.
3568 // However, if socket is closed for this address between the reception
3569 // of the query and sending a response, the IfaceMgr should detect it
3570 // and return an error.
3571 response->setLocalAddr(local_addr);
3572 // In many cases the query is sent to a broadcast address. This address
3573 // appears as a local address in the query message. Therefore we can't
3574 // simply copy local address from the query and use it as a source
3575 // address for the response. Instead, we have to check what address our
3576 // socket is bound to and use it as a source address. This operation
3577 // may throw if for some reason the socket is closed.
3580 response->setIndex(query->getIndex());
3581 response->setIface(query->getIface());
3582 }
3583
3584 if (server_port_) {
3585 response->setLocalPort(server_port_);
3586 } else {
3587 response->setLocalPort(DHCP4_SERVER_PORT);
3588 }
3589}
3590
3591void
3593 // Initialize the pointers to the client's message and the server's
3594 // response.
3595 Pkt4Ptr query = ex.getQuery();
3596 Pkt4Ptr response = ex.getResponse();
3597
3598 // DHCPv4-over-DHCPv6 is simple
3599 if (query->isDhcp4o6()) {
3600 response->setRemoteAddr(query->getRemoteAddr());
3601 return;
3602 }
3603
3604 // The DHCPINFORM is slightly different than other messages in a sense
3605 // that the server should always unicast the response to the ciaddr.
3606 // It appears however that some clients don't set the ciaddr. We still
3607 // want to provision these clients and we do what we can't to send the
3608 // packet to the address where client can receive it.
3609 if (query->getType() == DHCPINFORM) {
3610 // If client adheres to RFC2131 it will set the ciaddr and in this
3611 // case we always unicast our response to this address.
3612 if (!query->getCiaddr().isV4Zero()) {
3613 response->setRemoteAddr(query->getCiaddr());
3614
3615 // If we received DHCPINFORM via relay and the ciaddr is not set we
3616 // will try to send the response via relay. The caveat is that the
3617 // relay will not have any idea where to forward the packet because
3618 // the yiaddr is likely not set. So, the broadcast flag is set so
3619 // as the response may be broadcast.
3620 } else if (query->isRelayed()) {
3621 response->setRemoteAddr(query->getGiaddr());
3622 response->setFlags(response->getFlags() | BOOTP_BROADCAST);
3623
3624 // If there is no ciaddr and no giaddr the only thing we can do is
3625 // to use the source address of the packet.
3626 } else {
3627 response->setRemoteAddr(query->getRemoteAddr());
3628 }
3629 // Remote address is now set so return.
3630 return;
3631 }
3632
3633 // If received relayed message, server responds to the relay address.
3634 if (query->isRelayed()) {
3635 // The client should set the ciaddr when sending the DHCPINFORM
3636 // but in case he didn't, the relay may not be able to determine the
3637 // address of the client, because yiaddr is not set when responding
3638 // to Confirm and the only address available was the source address
3639 // of the client. The source address is however not used here because
3640 // the message is relayed. Therefore, we set the BROADCAST flag so
3641 // as the relay can broadcast the packet.
3642 if ((query->getType() == DHCPINFORM) &&
3643 query->getCiaddr().isV4Zero()) {
3644 response->setFlags(BOOTP_BROADCAST);
3645 }
3646 response->setRemoteAddr(query->getGiaddr());
3647
3648 // If giaddr is 0 but client set ciaddr, server should unicast the
3649 // response to ciaddr.
3650 } else if (!query->getCiaddr().isV4Zero()) {
3651 response->setRemoteAddr(query->getCiaddr());
3652
3653 // We can't unicast the response to the client when sending DHCPNAK,
3654 // because we haven't allocated address for him. Therefore,
3655 // DHCPNAK is broadcast.
3656 } else if (response->getType() == DHCPNAK) {
3657 response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
3658
3659 // If yiaddr is set it means that we have created a lease for a client.
3660 } else if (!response->getYiaddr().isV4Zero()) {
3661 // If the broadcast bit is set in the flags field, we have to
3662 // send the response to broadcast address. Client may have requested it
3663 // because it doesn't support reception of messages on the interface
3664 // which doesn't have an address assigned. The other case when response
3665 // must be broadcasted is when our server does not support responding
3666 // directly to a client without address assigned.
3667 const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
3668 if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
3669 response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
3670
3671 // Client cleared the broadcast bit and we support direct responses
3672 // so we should unicast the response to a newly allocated address -
3673 // yiaddr.
3674 } else {
3675 response->setRemoteAddr(response ->getYiaddr());
3676
3677 }
3678
3679 // In most cases, we should have the remote address found already. If we
3680 // found ourselves at this point, the rational thing to do is to respond
3681 // to the address we got the query from.
3682 } else {
3683 response->setRemoteAddr(query->getRemoteAddr());
3684 }
3685
3686 // For testing *only*.
3688 response->setRemoteAddr(query->getRemoteAddr());
3689 }
3690}
3691
3692void
3694 Pkt4Ptr query = ex.getQuery();
3695 Pkt4Ptr response = ex.getResponse();
3696
3697 // Step 1: Start with fixed fields defined on subnet level.
3698 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
3699 if (subnet) {
3700 IOAddress subnet_next_server = subnet->getSiaddr();
3701 if (!subnet_next_server.isV4Zero()) {
3702 response->setSiaddr(subnet_next_server);
3703 }
3704
3705 const string& sname = subnet->getSname();
3706 if (!sname.empty()) {
3707 // Converting string to (const uint8_t*, size_t len) format is
3708 // tricky. reinterpret_cast is not the most elegant solution,
3709 // but it does avoid us making unnecessary copy. We will convert
3710 // sname and file fields in Pkt4 to string one day and life
3711 // will be easier.
3712 response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
3713 sname.size());
3714 }
3715
3716 const string& filename = subnet->getFilename();
3717 if (!filename.empty()) {
3718 // Converting string to (const uint8_t*, size_t len) format is
3719 // tricky. reinterpret_cast is not the most elegant solution,
3720 // but it does avoid us making unnecessary copy. We will convert
3721 // sname and file fields in Pkt4 to string one day and life
3722 // will be easier.
3723 response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
3724 filename.size());
3725 }
3726 }
3727
3728 // Step 2: Try to set the values based on classes.
3729 // Any values defined in classes will override those from subnet level.
3730 const ClientClasses& classes = query->getClasses();
3731 if (!classes.empty()) {
3732
3733 // Let's get class definitions
3734 const ClientClassDictionaryPtr& dict =
3735 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
3736
3737 // Now we need to iterate over the classes assigned to the
3738 // query packet and find corresponding class definitions for it.
3739 // We want the first value found for each field. We track how
3740 // many we've found so we can stop if we have all three.
3742 string sname;
3743 string filename;
3744 size_t found_cnt = 0; // How many fields we have found.
3745 for (auto const& name : classes) {
3746
3747 if (found_cnt >= 3) {
3748 break;
3749 }
3750
3751 ClientClassDefPtr cl = dict->findClass(name);
3752 if (!cl) {
3753 // Let's skip classes that don't have definitions. Currently
3754 // these are automatic classes VENDOR_CLASS_something, but there
3755 // may be other classes assigned under other circumstances, e.g.
3756 // by hooks.
3757 continue;
3758 }
3759
3760 if (next_server == IOAddress::IPV4_ZERO_ADDRESS()) {
3761 next_server = cl->getNextServer();
3762 if (!next_server.isV4Zero()) {
3763 response->setSiaddr(next_server);
3764 found_cnt++;
3765 }
3766 }
3767
3768 if (sname.empty()) {
3769 sname = cl->getSname();
3770 if (!sname.empty()) {
3771 // Converting string to (const uint8_t*, size_t len) format is
3772 // tricky. reinterpret_cast is not the most elegant solution,
3773 // but it does avoid us making unnecessary copy. We will convert
3774 // sname and file fields in Pkt4 to string one day and life
3775 // will be easier.
3776 response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
3777 sname.size());
3778 found_cnt++;
3779 }
3780 }
3781
3782 if (filename.empty()) {
3783 filename = cl->getFilename();
3784 if (!filename.empty()) {
3785 // Converting string to (const uint8_t*, size_t len) format is
3786 // tricky. reinterpret_cast is not the most elegant solution,
3787 // but it does avoid us making unnecessary copy. We will convert
3788 // sname and file fields in Pkt4 to string one day and life
3789 // will be easier.
3790 response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
3791 filename.size());
3792 found_cnt++;
3793 }
3794 }
3795 }
3796 }
3797
3798 // Step 3: try to set values using HR. Any values coming from there will override
3799 // the subnet or class values.
3801}
3802
3804Dhcpv4Srv::getNetmaskOption(const ConstSubnet4Ptr& subnet) {
3805 uint32_t netmask = getNetmask4(subnet->get().second).toUint32();
3806
3808 DHO_SUBNET_MASK, netmask));
3809
3810 return (opt);
3811}
3812
3813tuple<bool, uint32_t>
3814Dhcpv4Srv::parkingLimitExceeded(string const& hook_label) {
3815 // Get the parking limit. Parsing should ensure the value is present.
3816 uint32_t parked_packet_limit(0);
3817 ConstElementPtr const& ppl(
3818 CfgMgr::instance().getCurrentCfg()->getConfiguredGlobal(CfgGlobals::PARKED_PACKET_LIMIT));
3819 if (ppl) {
3820 parked_packet_limit = ppl->intValue();
3821 }
3822
3823 if (parked_packet_limit) {
3824 ParkingLotPtr const& parking_lot(
3825 ServerHooks::getServerHooks().getParkingLotPtr(hook_label));
3826
3827 if (parking_lot && parked_packet_limit <= parking_lot->size()) {
3828 return make_tuple(true, parked_packet_limit);
3829 }
3830 }
3831 return make_tuple(false, parked_packet_limit);
3832}
3833
3834Pkt4Ptr
3836 bool drop = false;
3837 Dhcpv4Exchange ex(alloc_engine_, discover, context, context->subnet_, drop);
3838
3839 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
3840 if (drop) {
3841 return (Pkt4Ptr());
3842 }
3843
3844 if (MultiThreadingMgr::instance().getMode()) {
3845 // The lease reclamation cannot run at the same time.
3846 ReadLockGuard share(alloc_engine_->getReadWriteMutex());
3847
3848 assignLease(ex);
3849 } else {
3850 assignLease(ex);
3851 }
3852
3853 if (!ex.getResponse()) {
3854 // The offer is empty so return it *now*!
3855 return (Pkt4Ptr());
3856 }
3857
3858 // Adding any other options makes sense only when we got the lease
3859 // or it is for an IPv6-Only client.
3860 if (!ex.getResponse()->getYiaddr().isV4Zero() || ex.getIPv6OnlyPreferred()) {
3861 // If this is global reservation or the subnet doesn't belong to a shared
3862 // network we have already fetched it and evaluated the classes.
3864
3865 // Evaluate additional classes.
3867
3869 .arg(discover->getLabel())
3870 .arg(discover->getName())
3871 .arg(discover->getClasses().toText());
3872
3875 // Sanity check for IPv6-Only clients.
3876 if (ex.getIPv6OnlyPreferred()) {
3877 if (!ex.getResponse()->getOption(DHO_V6_ONLY_PREFERRED)) {
3878 // Better to drop the packet than to send an insane response.
3880 .arg(discover->getLabel());
3881 return (Pkt4Ptr());
3882 }
3883 }
3885 // There are a few basic options that we always want to
3886 // include in the response. If client did not request
3887 // them we append them for him.
3889
3890 // Set fixed fields (siaddr, sname, filename) if defined in
3891 // the reservation, class or subnet specific configuration.
3892 setFixedFields(ex);
3893
3894 } else {
3895 // If the server can't offer an address, it drops the packet.
3896 return (Pkt4Ptr());
3897
3898 }
3899
3900 // Set the src/dest IP address, port and interface for the outgoing
3901 // packet.
3902 adjustIfaceData(ex);
3903
3904 appendServerID(ex);
3905
3906 // Return the pointer to the context, which will be required by the
3907 // lease4_offer callouts.
3908 context = ex.getContext();
3909
3910 return (ex.getResponse());
3911}
3912
3913Pkt4Ptr
3915 bool drop = false;
3916 Dhcpv4Exchange ex(alloc_engine_, request, context, context->subnet_, drop);
3917
3918 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
3919 if (drop) {
3920 return (Pkt4Ptr());
3921 }
3922
3923 // Note that we treat REQUEST message uniformly, regardless if this is a
3924 // first request (requesting for new address), renewing existing address
3925 // or even rebinding.
3926 if (MultiThreadingMgr::instance().getMode()) {
3927 // The lease reclamation cannot run at the same time.
3928 ReadLockGuard share(alloc_engine_->getReadWriteMutex());
3929
3930 assignLease(ex);
3931 } else {
3932 assignLease(ex);
3933 }
3934
3935 Pkt4Ptr response = ex.getResponse();
3936 if (!response) {
3937 // The ack is empty so return it *now*!
3938 return (Pkt4Ptr());
3939 } else if (request->inClass("BOOTP")) {
3940 // Put BOOTP responses in the BOOTP class.
3941 response->addClass("BOOTP");
3942 }
3943
3944 // Adding any other options makes sense only when we got the lease
3945 // or it is for an IPv6-Only client.
3946 if (!response->getYiaddr().isV4Zero() || ex.getIPv6OnlyPreferred()) {
3947 // If this is global reservation or the subnet doesn't belong to a shared
3948 // network we have already fetched it and evaluated the classes.
3950
3951 // Evaluate additional classes.
3953
3955 .arg(request->getLabel())
3956 .arg(request->getName())
3957 .arg(request->getClasses().toText());
3958
3961 // Sanity check for IPv6-Only clients.
3962 if (ex.getIPv6OnlyPreferred()) {
3963 if (!response->getOption(DHO_V6_ONLY_PREFERRED)) {
3964 // Better to drop the packet than to send an insane response.
3966 .arg(request->getLabel());
3967 return (Pkt4Ptr());
3968 }
3969 }
3971 // There are a few basic options that we always want to
3972 // include in the response. If client did not request
3973 // them we append them for him.
3975
3976 // Set fixed fields (siaddr, sname, filename) if defined in
3977 // the reservation, class or subnet specific configuration.
3978 setFixedFields(ex);
3979 }
3980
3981 // Set the src/dest IP address, port and interface for the outgoing
3982 // packet.
3983 adjustIfaceData(ex);
3984
3985 appendServerID(ex);
3986
3987 // Return the pointer to the context, which will be required by the
3988 // leases4_committed callouts.
3989 context = ex.getContext();
3990
3991 return (ex.getResponse());
3992}
3993
3994void
3996 // Try to find client-id. Note that for the DHCPRELEASE we don't check if the
3997 // match-client-id configuration parameter is disabled because this parameter
3998 // is configured for subnets and we don't select subnet for the DHCPRELEASE.
3999 // Bogus clients usually generate new client identifiers when they first
4000 // connect to the network, so whatever client identifier has been used to
4001 // acquire the lease, the client identifier carried in the DHCPRELEASE is
4002 // likely to be the same and the lease will be correctly identified in the
4003 // lease database. If supplied client identifier differs from the one used
4004 // to acquire the lease then the lease will remain in the database and
4005 // simply expire.
4006 ClientIdPtr client_id;
4007 OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
4008 if (opt) {
4009 client_id = ClientIdPtr(new ClientId(opt->getData()));
4010 }
4011
4012 try {
4013 // Do we have a lease for that particular address?
4014 Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
4015
4016 if (!lease) {
4017 // No such lease - bogus release
4019 .arg(release->getLabel())
4020 .arg(release->getCiaddr().toText());
4021 return;
4022 }
4023
4024 if (!lease->belongsToClient(release->getHWAddr(), client_id)) {
4026 .arg(release->getLabel())
4027 .arg(release->getCiaddr().toText());
4028 return;
4029 }
4030
4031 bool skip = false;
4032
4033 // Execute all callouts registered for lease4_release
4034 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
4035 CalloutHandlePtr callout_handle = getCalloutHandle(release);
4036
4037 // Use the RAII wrapper to make sure that the callout handle state is
4038 // reset when this object goes out of scope. All hook points must do
4039 // it to prevent possible circular dependency between the callout
4040 // handle and its arguments.
4041 ScopedCalloutHandleState callout_handle_state(callout_handle);
4042
4043 // Enable copying options from the packet within hook library.
4044 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(release);
4045
4046 // Pass the original packet
4047 callout_handle->setArgument("query4", release);
4048
4049 // Pass the lease to be updated
4050 callout_handle->setArgument("lease4", lease);
4051
4052 // Call all installed callouts
4053 HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
4054 *callout_handle);
4055
4056 // Callouts decided to skip the next processing step. The next
4057 // processing step would be to send the packet, so skip at this
4058 // stage means "drop response".
4059 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
4060 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
4061 skip = true;
4064 .arg(release->getLabel());
4065 }
4066 }
4067
4068 // Callout didn't indicate to skip the release process. Let's release
4069 // the lease.
4070 if (!skip) {
4071 // Ok, we've passed all checks. Let's release this address.
4072 bool success = false; // was the removal operation successful?
4073 bool expired = false; // explicitly expired instead of removed?
4074 auto expiration_cfg = CfgMgr::instance().getCurrentCfg()->getCfgExpiration();
4075
4076 // Delete lease only if affinity is disabled.
4077 if (expiration_cfg->getFlushReclaimedTimerWaitTime() &&
4078 expiration_cfg->getHoldReclaimedTime() &&
4079 lease->valid_lft_ != Lease::INFINITY_LFT) {
4080 // Expire the lease.
4081 lease->valid_lft_ = 0;
4082 // Set the lease state to released to indicate that this lease
4083 // must be preserved in the database. It is particularly useful
4084 // in HA to differentiate between the leases that should be
4085 // updated in the partner's database and deleted from the partner's
4086 // database.
4087 lease->state_ = Lease4::STATE_RELEASED;
4089 expired = true;
4090 success = true;
4091 } else {
4092 success = LeaseMgrFactory::instance().deleteLease(lease);
4093 }
4094
4095 if (success) {
4096 context.reset(new AllocEngine::ClientContext4());
4097 context->old_lease_ = lease;
4098
4099 // Release successful
4101 .arg(release->getLabel())
4102 .arg(lease->addr_.toText());
4103
4104 if (expired) {
4106 .arg(release->getLabel())
4107 .arg(lease->addr_.toText());
4108 } else {
4110 .arg(release->getLabel())
4111 .arg(lease->addr_.toText());
4112
4113 // Remove existing DNS entries for the lease, if any.
4114 queueNCR(CHG_REMOVE, lease);
4115 }
4116
4117 // Need to decrease statistic for assigned addresses.
4119 StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-addresses"),
4120 static_cast<int64_t>(-1));
4121
4122 auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease->subnet_id_);
4123 if (subnet) {
4124 auto const& pool = subnet->getPool(Lease::TYPE_V4, lease->addr_, false);
4125 if (pool) {
4127 StatsMgr::generateName("subnet", subnet->getID(),
4128 StatsMgr::generateName("pool", pool->getID(), "assigned-addresses")),
4129 static_cast<int64_t>(-1));
4130 }
4131 }
4132
4133 } else {
4134 // Release failed
4136 .arg(release->getLabel())
4137 .arg(lease->addr_.toText());
4138 }
4139 }
4140 } catch (const isc::Exception& ex) {
4142 .arg(release->getLabel())
4143 .arg(release->getCiaddr())
4144 .arg(ex.what());
4145 }
4146}
4147
4148void
4150 // Client is supposed to specify the address being declined in
4151 // Requested IP address option, but must not set its ciaddr.
4152 // (again, see table 5 in RFC2131).
4153
4154 OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
4155 OptionCustom>(decline->getOption(DHO_DHCP_REQUESTED_ADDRESS));
4156 if (!opt_requested_address) {
4157
4158 isc_throw(RFCViolation, "Mandatory 'Requested IP address' option missing"
4159 " in DHCPDECLINE sent from " << decline->getLabel());
4160 }
4161 IOAddress addr(opt_requested_address->readAddress());
4162
4163 // We could also extract client's address from ciaddr, but that's clearly
4164 // against RFC2131.
4165
4166 // Now we need to check whether this address really belongs to the client
4167 // that attempts to decline it.
4168 const Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(addr);
4169
4170 if (!lease) {
4171 // Client tried to decline an address, but we don't have a lease for
4172 // that address. Let's ignore it.
4173 //
4174 // We could assume that we're recovering from a mishandled migration
4175 // to a new server and mark the address as declined, but the window of
4176 // opportunity for that to be useful is small and the attack vector
4177 // would be pretty severe.
4179 .arg(addr.toText()).arg(decline->getLabel());
4180 return;
4181 }
4182
4183 // Get client-id, if available.
4184 OptionPtr opt_clientid = decline->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
4185 ClientIdPtr client_id;
4186 if (opt_clientid) {
4187 client_id.reset(new ClientId(opt_clientid->getData()));
4188 }
4189
4190 // Check if the client attempted to decline an expired lease or a lease
4191 // it doesn't own. Declining expired leases is typically a client
4192 // misbehavior and may lead to pool exhaustion in case of a storm of
4193 // such declines. Only decline the lease if the lease has been recently
4194 // allocated to the client.
4195 if (lease->expired() || lease->state_ != Lease::STATE_DEFAULT ||
4196 !lease->belongsToClient(decline->getHWAddr(), client_id)) {
4197
4198 // Get printable hardware addresses
4199 string client_hw = decline->getHWAddr() ?
4200 decline->getHWAddr()->toText(false) : "(none)";
4201 string lease_hw = lease->hwaddr_ ?
4202 lease->hwaddr_->toText(false) : "(none)";
4203
4204 // Get printable client-ids
4205 string client_id_txt = client_id ? client_id->toText() : "(none)";
4206 string lease_id_txt = lease->client_id_ ?
4207 lease->client_id_->toText() : "(none)";
4208
4209 // Print the warning and we're done here.
4211 .arg(addr.toText()).arg(decline->getLabel())
4212 .arg(client_hw).arg(lease_hw).arg(client_id_txt).arg(lease_id_txt);
4213
4214 return;
4215 }
4216
4217 // Ok, all is good. The client is reporting its own address. Let's
4218 // process it.
4219 declineLease(lease, decline, context);
4220}
4221
4222void
4223Dhcpv4Srv::declineLease(const Lease4Ptr& lease, const Pkt4Ptr& decline,
4225
4226 // Let's check if there are hooks installed for decline4 hook point.
4227 // If they are, let's pass the lease and client's packet. If the hook
4228 // sets status to drop, we reject this Decline.
4229 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_decline_)) {
4230 CalloutHandlePtr callout_handle = getCalloutHandle(decline);
4231
4232 // Use the RAII wrapper to make sure that the callout handle state is
4233 // reset when this object goes out of scope. All hook points must do
4234 // it to prevent possible circular dependency between the callout
4235 // handle and its arguments.
4236 ScopedCalloutHandleState callout_handle_state(callout_handle);
4237
4238 // Enable copying options from the packet within hook library.
4239 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(decline);
4240
4241 // Pass the original packet
4242 callout_handle->setArgument("query4", decline);
4243
4244 // Pass the lease to be updated
4245 callout_handle->setArgument("lease4", lease);
4246
4247 // Call callouts
4248 HooksManager::callCallouts(Hooks.hook_index_lease4_decline_,
4249 *callout_handle);
4250
4251 // Check if callouts decided to skip the next processing step.
4252 // If any of them did, we will drop the packet.
4253 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
4254 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
4256 .arg(decline->getLabel()).arg(lease->addr_.toText());
4257 return;
4258 }
4259 }
4260
4261 Lease4Ptr old_values = boost::make_shared<Lease4>(*lease);
4262
4263 // @todo: Call hooks.
4264
4265 // We need to disassociate the lease from the client. Once we move a lease
4266 // to declined state, it is no longer associated with the client in any
4267 // way.
4268 lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());
4269
4270 try {
4272 } catch (const Exception& ex) {
4273 // Update failed.
4275 .arg(decline->getLabel())
4276 .arg(lease->addr_.toText())
4277 .arg(ex.what());
4278 return;
4279 }
4280
4281 // Remove existing DNS entries for the lease, if any.
4282 // queueNCR will do the necessary checks and will skip the update, if not needed.
4283 queueNCR(CHG_REMOVE, old_values);
4284
4285 // Bump up the statistics.
4286
4287 // Per subnet declined addresses counter.
4289 StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
4290 static_cast<int64_t>(1));
4291
4292 auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease->subnet_id_);
4293 if (subnet) {
4294 auto const& pool = subnet->getPool(Lease::TYPE_V4, lease->addr_, false);
4295 if (pool) {
4297 StatsMgr::generateName("subnet", subnet->getID(),
4298 StatsMgr::generateName("pool", pool->getID(), "declined-addresses")),
4299 static_cast<int64_t>(1));
4300 }
4301 }
4302
4303 // Global declined addresses counter.
4304 StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));
4305
4306 // We do not want to decrease the assigned-addresses at this time. While
4307 // technically a declined address is no longer allocated, the primary usage
4308 // of the assigned-addresses statistic is to monitor pool utilization. Most
4309 // people would forget to include declined-addresses in the calculation,
4310 // and simply do assigned-addresses/total-addresses. This would have a bias
4311 // towards under-representing pool utilization, if we decreased allocated
4312 // immediately after receiving DHCPDECLINE, rather than later when we recover
4313 // the address.
4314
4315 context.reset(new AllocEngine::ClientContext4());
4316 context->new_lease_ = lease;
4317
4318 LOG_INFO(lease4_logger, DHCP4_DECLINE_LEASE).arg(lease->addr_.toText())
4319 .arg(decline->getLabel()).arg(lease->valid_lft_);
4320}
4321
4322void
4324 Lease4Ptr lease, bool lease_exists) {
4326 .arg(query->getLabel())
4327 .arg(lease->addr_.toText())
4328 .arg(lease->valid_lft_);
4329
4330 {
4331 // Check if the resource is busy i.e. can be modified by another thread
4332 // for another client. Highly unlikely.
4333 ResourceHandler4 resource_handler;
4334 if (MultiThreadingMgr::instance().getMode() && !resource_handler.tryLock4(lease->addr_)) {
4336 .arg(query->getLabel())
4337 .arg(lease->addr_.toText());
4338 return;
4339 }
4340
4341 // We need to disassociate the lease from the client. Once we move a lease
4342 // to declined state, it is no longer associated with the client in any
4343 // way.
4344 lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());
4345
4346 // If the lease already exists, update it in the database.
4347 if (lease_exists) {
4348 try {
4350 } catch (const NoSuchLease& ex) {
4351 // We expected the lease to exist but it doesn't so let's try
4352 // to add it.
4353 lease_exists = false;
4354 } catch (const Exception& ex) {
4355 // Update failed.
4357 .arg(query->getLabel())
4358 .arg(lease->addr_.toText());
4359 return;
4360 }
4361 }
4362
4363 if (!lease_exists) {
4364 try {
4366 } catch (const Exception& ex) {
4368 .arg(query->getLabel())
4369 .arg(lease->addr_.toText());
4370 return;
4371 }
4372 }
4373 }
4374
4375 // Bump up the statistics. If the lease does not exist (i.e. offer-lifetime == 0) we
4376 // need to increment assigned address stats, otherwise the accounting will be off.
4377 // This saves us from having to determine later, when declined leases are reclaimed,
4378 // whether or not we need to decrement assigned stats. In other words, this keeps
4379 // a declined lease always counted also as an assigned lease, regardless of how
4380 // it was declined, until it is reclaimed at which point both groups of stats
4381 // are decremented.
4382
4383 // Per subnet declined addresses counter.
4385 StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
4386 static_cast<int64_t>(1));
4387
4388 if (!lease_exists) {
4390 StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-addresses"),
4391 static_cast<int64_t>(1));
4392 }
4393
4394 auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease->subnet_id_);
4395 if (subnet) {
4396 auto const& pool = subnet->getPool(Lease::TYPE_V4, lease->addr_, false);
4397 if (pool) {
4399 StatsMgr::generateName("subnet", subnet->getID(),
4400 StatsMgr::generateName("pool", pool->getID(), "declined-addresses")),
4401 static_cast<int64_t>(1));
4402 if (!lease_exists) {
4404 StatsMgr::generateName("subnet", subnet->getID(),
4405 StatsMgr::generateName("pool", pool->getID(), "assigned-addresses")),
4406 static_cast<int64_t>(1));
4407 }
4408 }
4409 }
4410
4411 // Global declined addresses counter.
4412 StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));
4413 if (!lease_exists) {
4414 StatsMgr::instance().addValue("assigned-addresses", static_cast<int64_t>(1));
4415 }
4416
4417 // Let's check if there are hooks installed for server decline hook point.
4418 // If there are, let's pass the DHCPDISCOVER and the declined lease .
4419 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_server_decline_)) {
4420 // Use the RAII wrapper to make sure that the callout handle state is
4421 // reset when this object goes out of scope. All hook points must do
4422 // it to prevent possible circular dependency between the callout
4423 // handle and its arguments.
4424 ScopedCalloutHandleState callout_handle_state(callout_handle);
4425
4426 // Pass in the original DHCPDISCOVER
4427 callout_handle->setArgument("query4", query);
4428
4429 // Pass in the declined lease.
4430 callout_handle->setArgument("lease4", lease);
4431
4432 // Call callouts
4433 HooksManager::callCallouts(Hooks.hook_index_lease4_server_decline_,
4434 *callout_handle);
4435 }
4436}
4437
4438void
4440 Lease4Ptr lease, bool lease_exists) {
4441 try {
4442 serverDecline(callout_handle, query, lease, lease_exists);
4443 } catch (...) {
4445 }
4446}
4447
4448Pkt4Ptr
4450 bool drop = false;
4451 Dhcpv4Exchange ex(alloc_engine_, inform, context, context->subnet_, drop);
4452
4453 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
4454 if (drop) {
4455 return (Pkt4Ptr());
4456 }
4457
4458 Pkt4Ptr ack = ex.getResponse();
4459
4460 // If this is global reservation or the subnet doesn't belong to a shared
4461 // network we have already fetched it and evaluated the classes.
4463
4464 // Evaluate additional classes.
4466
4468 .arg(inform->getLabel())
4469 .arg(inform->getName())
4470 .arg(inform->getClasses().toText());
4471
4476 adjustIfaceData(ex);
4477
4478 // Set fixed fields (siaddr, sname, filename) if defined in
4479 // the reservation, class or subnet specific configuration.
4480 setFixedFields(ex);
4481
4482 // There are cases for the DHCPINFORM that the server receives it via
4483 // relay but will send the response to the client's unicast address
4484 // carried in the ciaddr. In this case, the giaddr and hops field should
4485 // be cleared (these fields were copied by the copyDefaultFields function).
4486 // Also Relay Agent Options should be removed if present.
4487 if (ack->getRemoteAddr() != inform->getGiaddr()) {
4489 .arg(inform->getLabel())
4490 .arg(ack->getRemoteAddr())
4491 .arg(ack->getIface());
4492 ack->setHops(0);
4493 ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
4494 ack->delOption(DHO_DHCP_AGENT_OPTIONS);
4495 }
4496
4497 // The DHCPACK must contain server id.
4498 appendServerID(ex);
4499
4500 return (ex.getResponse());
4501}
4502
4503void
4505 if (query->getCiaddr().isV4Zero() || !query->getGiaddr().isV4Zero()) {
4506 return;
4507 }
4509 getConfiguredGlobal(CfgGlobals::STASH_AGENT_OPTIONS);
4510 if (!sao || (sao->getType() != Element::boolean) || !sao->boolValue()) {
4511 return;
4512 }
4513 if (query->getType() != DHCPREQUEST) {
4514 return;
4515 }
4516 OptionPtr rai_opt = query->getOption(DHO_DHCP_AGENT_OPTIONS);
4517 if (rai_opt && (rai_opt->len() > Option::OPTION4_HDR_LEN)) {
4518 return;
4519 }
4520 // Should not happen but makes sense to check and gives a trivial way
4521 // to disable the feature from previous callout points.
4522 if (query->inClass("STASH_AGENT_OPTIONS")) {
4523 return;
4524 }
4525 Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(query->getCiaddr());
4526 if (!lease || lease->expired()) {
4527 return;
4528 }
4529 ConstElementPtr user_context = lease->getContext();
4530 if (!user_context || (user_context->getType() != Element::map)) {
4531 return;
4532 }
4533 ConstElementPtr isc = user_context->get("ISC");
4534 if (!isc || (isc->getType() != Element::map)) {
4535 return;
4536 }
4537 ConstElementPtr relay_agent_info = isc->get("relay-agent-info");
4538 if (!relay_agent_info) {
4539 return;
4540 }
4541 // Compatibility with the old layout.
4542 if (relay_agent_info->getType() == Element::map) {
4543 relay_agent_info = relay_agent_info->get("sub-options");
4544 if (!relay_agent_info) {
4545 return;
4546 }
4547 }
4548 if (relay_agent_info->getType() != Element::string) {
4549 return;
4550 }
4551 // Check ownership before going further.
4552 ClientIdPtr client_id;
4553 OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
4554 if (opt_clientid) {
4555 client_id.reset(new ClientId(opt_clientid->getData()));
4556 }
4557 if (!lease->belongsToClient(query->getHWAddr(), client_id)) {
4558 return;
4559 }
4560 // Extract the RAI.
4561 string rai_hex = relay_agent_info->stringValue();
4562 if (rai_hex.empty()) {
4563 return;
4564 }
4565 vector<uint8_t> rai_data;
4566 str::decodeFormattedHexString(rai_hex, rai_data);
4567 static const OptionDefinition& rai_def = LibDHCP::DHO_DHCP_AGENT_OPTIONS_DEF();
4568 OptionCustomPtr rai(new OptionCustom(rai_def, Option::V4, rai_data));
4569 // unpackOptions is a bit too flexible so check if it got something...
4570 if (!rai || rai->getOptions().empty()) {
4571 return;
4572 }
4573 // Remove an existing empty RAI.
4574 if (rai_opt) {
4575 query->delOption(DHO_DHCP_AGENT_OPTIONS);
4576 }
4577 query->addOption(rai);
4578 query->addClass("STASH_AGENT_OPTIONS");
4581 .arg(query->getLabel())
4582 .arg(query->getCiaddr())
4583 .arg(rai->toText());
4584}
4585
4586bool
4588 // Check that the message type is accepted by the server. We rely on the
4589 // function called to log a message if needed.
4590 if (!acceptMessageType(query)) {
4591 return (false);
4592 }
4593 // Check if the message from directly connected client (if directly
4594 // connected) should be dropped or processed.
4595 if (!acceptDirectRequest(query)) {
4597 .arg(query->getLabel())
4598 .arg(query->getIface());
4599 return (false);
4600 }
4601
4602 // Check if the DHCPv4 packet has been sent to us or to someone else.
4603 // If it hasn't been sent to us, drop it!
4604 if (!acceptServerId(query)) {
4606 .arg(query->getLabel())
4607 .arg(query->getIface());
4608 return (false);
4609 }
4610
4611 return (true);
4612}
4613
4614bool
4616 // Accept all relayed messages.
4617 if (pkt->isRelayed()) {
4618 return (true);
4619 }
4620
4621 // Accept all DHCPv4-over-DHCPv6 messages.
4622 if (pkt->isDhcp4o6()) {
4623 return (true);
4624 }
4625
4626 // The source address must not be zero for the DHCPINFORM message from
4627 // the directly connected client because the server will not know where
4628 // to respond if the ciaddr was not present.
4629 try {
4630 if (pkt->getType() == DHCPINFORM) {
4631 if (pkt->getRemoteAddr().isV4Zero() &&
4632 pkt->getCiaddr().isV4Zero()) {
4633 return (false);
4634 }
4635 }
4636 } catch (...) {
4637 // If we got here, it is probably because the message type hasn't
4638 // been set. But, this should not really happen assuming that
4639 // we validate the message type prior to calling this function.
4640 return (false);
4641 }
4642 bool drop = false;
4643 bool result = (!pkt->getLocalAddr().isV4Bcast() ||
4644 selectSubnet(pkt, drop, true));
4645 if (drop) {
4646 // The packet must be dropped but as sanity_only is true it is dead code.
4647 return (false);
4648 }
4649 return (result);
4650}
4651
4652bool
4654 // When receiving a packet without message type option, getType() will
4655 // throw.
4656 int type;
4657 try {
4658 type = query->getType();
4659
4660 } catch (...) {
4662 .arg(query->getLabel())
4663 .arg(query->getIface());
4664 return (false);
4665 }
4666
4667 // Once we know that the message type is within a range of defined DHCPv4
4668 // messages, we do a detailed check to make sure that the received message
4669 // is targeted at server. Note that we could have received some Offer
4670 // message broadcasted by the other server to a relay. Even though, the
4671 // server would rather unicast its response to a relay, let's be on the
4672 // safe side. Also, we want to drop other messages which we don't support.
4673 // All these valid messages that we are not going to process are dropped
4674 // silently.
4675
4676 switch(type) {
4677 case DHCPDISCOVER:
4678 case DHCPREQUEST:
4679 case DHCPRELEASE:
4680 case DHCPDECLINE:
4681 case DHCPINFORM:
4682 return (true);
4683 break;
4684
4685 case DHCP_NOTYPE:
4687 .arg(query->getLabel());
4688 break;
4689
4690 default:
4691 // If we receive a message with a non-existing type, we are logging it.
4692 if (type >= DHCP_TYPES_EOF) {
4694 .arg(query->getLabel())
4695 .arg(type);
4696 } else {
4697 // Exists but we don't support it.
4699 .arg(query->getLabel())
4700 .arg(type);
4701 }
4702 break;
4703 }
4704
4705 return (false);
4706}
4707
4708bool
4710 // This function is meant to be called internally by the server class, so
4711 // we rely on the caller to sanity check the pointer and we don't check
4712 // it here.
4713
4714 // Check if server identifier option is present. If it is not present
4715 // we accept the message because it is targeted to all servers.
4716 // Note that we don't check cases that server identifier is mandatory
4717 // but not present. This is meant to be sanity checked in other
4718 // functions.
4719 OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
4720 if (!option) {
4721 return (true);
4722 }
4723 // Server identifier is present. Let's convert it to 4-byte address
4724 // and try to match with server identifiers used by the server.
4725 OptionCustomPtr option_custom =
4726 boost::dynamic_pointer_cast<OptionCustom>(option);
4727 // Unable to convert the option to the option type which encapsulates it.
4728 // We treat this as non-matching server id.
4729 if (!option_custom) {
4730 return (false);
4731 }
4732 // The server identifier option should carry exactly one IPv4 address.
4733 // If the option definition for the server identifier doesn't change,
4734 // the OptionCustom object should have exactly one IPv4 address and
4735 // this check is somewhat redundant. On the other hand, if someone
4736 // breaks option it may be better to check that here.
4737 if (option_custom->getDataFieldsNum() != 1) {
4738 return (false);
4739 }
4740
4741 // The server identifier MUST be an IPv4 address. If given address is
4742 // v6, it is wrong.
4743 IOAddress server_id = option_custom->readAddress();
4744 if (!server_id.isV4()) {
4745 return (false);
4746 }
4747
4748 // According to RFC5107, the RAI_OPTION_SERVER_ID_OVERRIDE option if
4749 // present, should match DHO_DHCP_SERVER_IDENTIFIER option.
4750 OptionPtr rai_option = query->getOption(DHO_DHCP_AGENT_OPTIONS);
4751 if (rai_option) {
4752 OptionPtr rai_suboption = rai_option->getOption(RAI_OPTION_SERVER_ID_OVERRIDE);
4753 if (rai_suboption && (server_id.toBytes() == rai_suboption->toBinary())) {
4754 return (true);
4755 }
4756 }
4757
4758 // Skip address check if configured to ignore the server id.
4760 if (cfg->getIgnoreServerIdentifier()) {
4761 return (true);
4762 }
4763
4764 // This function iterates over all interfaces on which the
4765 // server is listening to find the one which has a socket bound
4766 // to the address carried in the server identifier option.
4767 // This has some performance implications. However, given that
4768 // typically there will be just a few active interfaces the
4769 // performance hit should be acceptable. If it turns out to
4770 // be significant, we will have to cache server identifiers
4771 // when sockets are opened.
4772 if (IfaceMgr::instance().hasOpenSocket(server_id)) {
4773 return (true);
4774 }
4775
4776 // There are some cases when an administrator explicitly sets server
4777 // identifier (option 54) that should be used for a given, subnet,
4778 // network etc. It doesn't have to be an address assigned to any of
4779 // the server interfaces. Thus, we have to check if the server
4780 // identifier received is the one that we explicitly set in the
4781 // server configuration. At this point, we don't know which subnet
4782 // the client belongs to so we can't match the server id with any
4783 // subnet. We simply check if this server identifier is configured
4784 // anywhere. This should be good enough to eliminate exchanges
4785 // with other servers in the same network.
4786
4794
4795 // Check if there is at least one subnet configured with this server
4796 // identifier.
4797 ConstCfgSubnets4Ptr cfg_subnets = cfg->getCfgSubnets4();
4798 if (cfg_subnets->hasSubnetWithServerId(server_id)) {
4799 return (true);
4800 }
4801
4802 // This server identifier is not configured for any of the subnets, so
4803 // check on the shared network level.
4804 CfgSharedNetworks4Ptr cfg_networks = cfg->getCfgSharedNetworks4();
4805 if (cfg_networks->hasNetworkWithServerId(server_id)) {
4806 return (true);
4807 }
4808
4809 // Check if the server identifier is configured at client class level.
4810 const ClientClasses& classes = query->getClasses();
4811 for (auto const& cclass : classes) {
4812 // Find the client class definition for this class
4814 getClientClassDictionary()->findClass(cclass);
4815 if (!ccdef) {
4816 continue;
4817 }
4818
4819 if (ccdef->getCfgOption()->empty()) {
4820 // Skip classes which don't configure options
4821 continue;
4822 }
4823
4824 OptionCustomPtr context_opt_server_id = boost::dynamic_pointer_cast<OptionCustom>
4825 (ccdef->getCfgOption()->get(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER).option_);
4826 if (context_opt_server_id && (context_opt_server_id->readAddress() == server_id)) {
4827 return (true);
4828 }
4829 }
4830
4831 // Finally, it is possible that the server identifier is specified
4832 // on the global level.
4833 ConstCfgOptionPtr cfg_global_options = cfg->getCfgOption();
4834 OptionCustomPtr opt_server_id = boost::dynamic_pointer_cast<OptionCustom>
4835 (cfg_global_options->get(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER).option_);
4836
4837 return (opt_server_id && (opt_server_id->readAddress() == server_id));
4838}
4839
4840void
4842 switch (query->getType()) {
4843 case DHCPDISCOVER:
4844 // server-id is forbidden.
4845 sanityCheck(query, FORBIDDEN);
4846 break;
4847 case DHCPREQUEST:
4848 // Since we cannot distinguish between client states
4849 // we'll make server-id is optional for REQUESTs.
4850 sanityCheck(query, OPTIONAL);
4851 break;
4852 case DHCPRELEASE:
4853 // Server-id is mandatory in DHCPRELEASE (see table 5, RFC2131)
4854 // but ISC DHCP does not enforce this, so we'll follow suit.
4855 sanityCheck(query, OPTIONAL);
4856 break;
4857 case DHCPDECLINE:
4858 // Server-id is mandatory in DHCPDECLINE (see table 5, RFC2131)
4859 // but ISC DHCP does not enforce this, so we'll follow suit.
4860 sanityCheck(query, OPTIONAL);
4861 break;
4862 case DHCPINFORM:
4863 // server-id is supposed to be forbidden (as is requested address)
4864 // but ISC DHCP does not enforce either. So neither will we.
4865 sanityCheck(query, OPTIONAL);
4866 break;
4867 }
4868}
4869
4870void
4872 OptionPtr server_id = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
4873 switch (serverid) {
4874 case FORBIDDEN:
4875 if (server_id) {
4876 isc_throw(RFCViolation, "Server-id option was not expected, but"
4877 << " received in message "
4878 << query->getName());
4879 }
4880 break;
4881
4882 case MANDATORY:
4883 if (!server_id) {
4884 isc_throw(RFCViolation, "Server-id option was expected, but not"
4885 " received in message "
4886 << query->getName());
4887 }
4888 break;
4889
4890 case OPTIONAL:
4891 // do nothing here
4892 ;
4893 }
4894
4895 // If there is HWAddress set and it is non-empty, then we're good
4896 if (query->getHWAddr() && !query->getHWAddr()->hwaddr_.empty()) {
4897 return;
4898 }
4899
4900 // There has to be something to uniquely identify the client:
4901 // either non-zero MAC address or client-id option present (or both)
4902 OptionPtr client_id = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
4903
4904 // If there's no client-id (or a useless one is provided, i.e. 0 length)
4905 if (!client_id || client_id->len() == client_id->getHeaderLen()) {
4906 isc_throw(RFCViolation, "Missing or useless client-id and no HW address"
4907 " provided in message "
4908 << query->getName());
4909 }
4910}
4911
4915
4917 // First collect required classes
4918 Pkt4Ptr query = ex.getQuery();
4919 ClientClasses classes = query->getAdditionalClasses();
4920 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
4921
4922 if (subnet) {
4923 // host reservation???
4924
4925 // Begin by the pool
4926 Pkt4Ptr resp = ex.getResponse();
4928 if (resp) {
4929 addr = resp->getYiaddr();
4930 }
4931 if (!addr.isV4Zero()) {
4932 PoolPtr pool = subnet->getPool(Lease::TYPE_V4, addr, false);
4933 if (pool) {
4934 const ClientClasses& pool_to_add = pool->getAdditionalClasses();
4935 for (auto const& cclass : pool_to_add) {
4936 classes.insert(cclass);
4937 }
4938 }
4939 }
4940
4941 // Followed by the subnet
4942 const ClientClasses& to_add = subnet->getAdditionalClasses();
4943 for (auto const& cclass : to_add) {
4944 classes.insert(cclass);
4945 }
4946
4947 // And finish by the shared-network
4948 SharedNetwork4Ptr network;
4949 subnet->getSharedNetwork(network);
4950 if (network) {
4951 const ClientClasses& net_to_add = network->getAdditionalClasses();
4952 for (auto const& cclass : net_to_add) {
4953 classes.insert(cclass);
4954 }
4955 }
4956 }
4957
4958 // Run match expressions
4959 // Note getClientClassDictionary() cannot be null
4960 const ClientClassDictionaryPtr& dict =
4961 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
4962 for (auto const& cclass : classes) {
4963 const ClientClassDefPtr class_def = dict->findClass(cclass);
4964 if (!class_def) {
4967 .arg(cclass);
4968 // Ignore it as it can't have an attached action
4969 continue;
4970 }
4971 const ExpressionPtr& expr_ptr = class_def->getMatchExpr();
4972 // Add a class without an expression to evaluate
4973 if (!expr_ptr) {
4976 .arg(cclass);
4977 query->addClass(cclass);
4978 continue;
4979 }
4980 // Evaluate the expression which can return false (no match),
4981 // true (match) or raise an exception (error)
4982 try {
4983 bool status = evaluateBool(*expr_ptr, *query);
4985 .arg(query->getLabel())
4986 .arg(cclass)
4987 .arg(status ? "true" : "false");
4988 if (status) {
4989 // Matching: add the class
4990 query->addClass(cclass);
4991 }
4992 } catch (const Exception& ex) {
4994 .arg(query->getLabel())
4995 .arg(cclass)
4996 .arg(ex.what());
4997 }
4998 }
4999}
5000
5001void
5003 // Iterate on the list of deferred option codes
5004 for (auto const& code : query->getDeferredOptions()) {
5006 // Iterate on client classes
5007 const ClientClasses& classes = query->getClasses();
5008 for (auto const& cclass : classes) {
5009 // Get the client class definition for this class
5010 const ClientClassDefPtr& ccdef =
5012 getClientClassDictionary()->findClass(cclass);
5013 // If not found skip it
5014 if (!ccdef) {
5015 continue;
5016 }
5017 // If there is no option definition skip it
5018 if (!ccdef->getCfgOptionDef()) {
5019 continue;
5020 }
5021 def = ccdef->getCfgOptionDef()->get(DHCP4_OPTION_SPACE, code);
5022 // Stop at the first client class with a definition
5023 if (def) {
5024 break;
5025 }
5026 }
5027 // If not found try the global definition
5028 if (!def) {
5030 }
5031 if (!def) {
5033 }
5034 // Finish by last resort definition
5035 if (!def) {
5037 }
5038 // If not defined go to the next option
5039 if (!def) {
5040 continue;
5041 }
5042 // Get the existing option for its content and remove all
5043 OptionPtr opt = query->getOption(code);
5044 if (!opt) {
5045 // should not happen but do not crash anyway
5048 .arg(query->getLabel())
5049 .arg(code);
5050 continue;
5051 }
5052 // Because options have already been fused, the buffer contains entire
5053 // data.
5054 const OptionBuffer buf = opt->getData();
5055 try {
5056 // Unpack the option
5057 opt = def->optionFactory(Option::V4, code, buf);
5058 } catch (const std::exception& e) {
5059 // Failed to parse the option.
5062 .arg(query->getLabel())
5063 .arg(code)
5064 .arg(e.what());
5065 continue;
5066 }
5067 while (query->delOption(code)) {
5068 // continue
5069 }
5070 // Add the unpacked option.
5071 query->addOption(opt);
5072 }
5073}
5074
5075void
5078 if (d2_mgr.ddnsEnabled()) {
5079 // Updates are enabled, so lets start the sender, passing in
5080 // our error handler.
5081 // This may throw so wherever this is called needs to ready.
5083 this, ph::_1, ph::_2));
5084 }
5085}
5086
5087void
5090 if (d2_mgr.ddnsEnabled()) {
5091 // Updates are enabled, so lets stop the sender
5092 d2_mgr.stop();
5093 d2_mgr.stopSender();
5094 }
5095}
5096
5097void
5102 arg(result).arg((ncr ? ncr->toText() : " NULL "));
5103 // We cannot communicate with kea-dhcp-ddns, suspend further updates.
5107}
5108
5109std::string
5111 std::stringstream tmp;
5112
5113 tmp << VERSION;
5114 if (extended) {
5115 tmp << " (" << EXTENDED_VERSION << ")" << endl;
5116 tmp << "premium: " << PREMIUM_EXTENDED_VERSION << endl;
5117 tmp << "linked with:" << endl;
5118 tmp << "- " << Logger::getVersion() << endl;
5119 tmp << "- " << CryptoLink::getVersion();
5121 if (info.size()) {
5122 tmp << endl << "lease backends:";
5123 for (auto const& version : info) {
5124 tmp << endl << "- " << version;
5125 }
5126 }
5128 if (info.size()) {
5129 tmp << endl << "host backends:";
5130 for (auto const& version : info) {
5131 tmp << endl << "- " << version;
5132 }
5133 }
5135 if (info.size()) {
5136 tmp << endl << "forensic backends:";
5137 for (auto const& version : info) {
5138 tmp << endl << "- " << version;
5139 }
5140 }
5141 // @todo: more details about database runtime
5142 }
5143
5144 return (tmp.str());
5145}
5146
5148 // Note that we're not bumping pkt4-received statistic as it was
5149 // increased early in the packet reception code.
5150
5151 string stat_name = "pkt4-unknown-received";
5152 try {
5153 switch (query->getType()) {
5154 case DHCPDISCOVER:
5155 stat_name = "pkt4-discover-received";
5156 break;
5157 case DHCPOFFER:
5158 // Should not happen, but let's keep a counter for it
5159 stat_name = "pkt4-offer-received";
5160 break;
5161 case DHCPREQUEST:
5162 stat_name = "pkt4-request-received";
5163 break;
5164 case DHCPACK:
5165 // Should not happen, but let's keep a counter for it
5166 stat_name = "pkt4-ack-received";
5167 break;
5168 case DHCPNAK:
5169 // Should not happen, but let's keep a counter for it
5170 stat_name = "pkt4-nak-received";
5171 break;
5172 case DHCPRELEASE:
5173 stat_name = "pkt4-release-received";
5174 break;
5175 case DHCPDECLINE:
5176 stat_name = "pkt4-decline-received";
5177 break;
5178 case DHCPINFORM:
5179 stat_name = "pkt4-inform-received";
5180 break;
5181 default:
5182 ; // do nothing
5183 }
5184 }
5185 catch (...) {
5186 // If the incoming packet doesn't have option 53 (message type)
5187 // or a hook set pkt4_receive_skip, then Pkt4::getType() may
5188 // throw an exception. That's ok, we'll then use the default
5189 // name of pkt4-unknown-received.
5190 }
5191
5193 static_cast<int64_t>(1));
5194}
5195
5197 // Increase generic counter for sent packets.
5199 static_cast<int64_t>(1));
5200
5201 // Increase packet type specific counter for packets sent.
5202 string stat_name;
5203 switch (response->getType()) {
5204 case DHCPOFFER:
5205 stat_name = "pkt4-offer-sent";
5206 break;
5207 case DHCPACK:
5208 stat_name = "pkt4-ack-sent";
5209 break;
5210 case DHCPNAK:
5211 stat_name = "pkt4-nak-sent";
5212 break;
5213 default:
5214 // That should never happen
5215 return;
5216 }
5217
5219 static_cast<int64_t>(1));
5220}
5221
5223 return (Hooks.hook_index_buffer4_receive_);
5224}
5225
5227 return (Hooks.hook_index_pkt4_receive_);
5228}
5229
5231 return (Hooks.hook_index_subnet4_select_);
5232}
5233
5235 return (Hooks.hook_index_lease4_release_);
5236}
5237
5239 return (Hooks.hook_index_pkt4_send_);
5240}
5241
5243 return (Hooks.hook_index_buffer4_send_);
5244}
5245
5247 return (Hooks.hook_index_lease4_decline_);
5248}
5249
5251 // Dump all of our current packets, anything that is mid-stream
5253}
5254
5256#ifdef FUZZING
5257 char const* const rotate(getenv("KEA_DHCP4_FUZZING_ROTATE_PORT"));
5258 if (rotate) {
5259 InterprocessSyncFile file("kea-dhcp4-fuzzing-rotate-port");
5260 InterprocessSyncLocker locker(file);
5261 while (!locker.lock()) {
5262 this_thread::sleep_for(1s);
5263 }
5264 fstream port_file;
5265 port_file.open("/tmp/port4.txt", ios::in);
5266 string line;
5267 int port;
5268 getline(port_file, line);
5269 port_file.close();
5270 if (line.empty()) {
5271 port = 2000;
5272 } else {
5273 port = stoi(line);
5274 if (port < 3000) {
5275 ++port;
5276 } else {
5277 port = 2000;
5278 }
5279 }
5280 port_file.open("/tmp/port4.txt", ios::out | ios::trunc);
5281 port_file << to_string(port) << endl;
5282 port_file.close();
5283 locker.unlock();
5284 return port;
5285 }
5286#endif // FUZZING
5287 return server_port_;
5288}
5289
5290std::list<std::list<std::string>> Dhcpv4Srv::jsonPathsToRedact() const {
5291 static std::list<std::list<std::string>> const list({
5292 {"config-control", "config-databases", "[]"},
5293 {"hooks-libraries", "[]", "parameters", "*"},
5294 {"hosts-database"},
5295 {"hosts-databases", "[]"},
5296 {"lease-database"},
5297 });
5298 return list;
5299}
5300
5301} // namespace dhcp
5302} // namespace isc
int version()
returns Kea hooks version.
CtrlAgentHooks Hooks
Defines elements for storing the names of client classes.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
This is a base class for exceptions thrown from the DNS library module.
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown when an unexpected error condition occurs.
DHCPv4 and DHCPv6 allocation engine.
static uint32_t getValidLft(const ClientContext4 &ctx)
Returns the valid lifetime based on the v4 context.
boost::shared_ptr< ClientContext4 > ClientContext4Ptr
Pointer to the ClientContext4.
Implementation of the mechanisms to control the use of the Configuration Backends by the DHCPv4 serve...
@ USE_ROUTING
Server uses routing to determine the right interface to send response.
Definition cfg_iface.h:148
@ SOCKET_UDP
Datagram socket, i.e. IP/UDP socket.
Definition cfg_iface.h:139
Configuration Manager.
Definition cfgmgr.h:70
D2ClientMgr & getD2ClientMgr()
Fetches the DHCP-DDNS manager.
Definition cfgmgr.cc:68
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition cfgmgr.cc:28
SrvConfigPtr getCurrentCfg()
Returns a pointer to the current configuration.
Definition cfgmgr.cc:115
static SubnetSelector initSelector(const Pkt4Ptr &query)
Build selector from a client's message.
Container for storing client class names.
Definition classify.h:109
void insert(const ClientClass &class_name)
Insert an element.
Definition classify.h:159
bool empty() const
Check if classes is empty.
Definition classify.h:169
std::string toText(const std::string &separator=", ") const
Returns all class names as text.
Definition classify.cc:80
Client race avoidance RAII handler.
bool tryLock(Pkt4Ptr query, ContinuationPtr cont=ContinuationPtr())
Tries to acquires a client.
Holds Client identifier or client IPv4 address.
Definition duid.h:222
ReplaceClientNameMode
Defines the client name replacement modes.
D2ClientMgr isolates Kea from the details of being a D2 client.
std::string generateFqdn(const asiolink::IOAddress &address, const DdnsParams &ddns_params, const bool trailing_dot=true) const
Builds a FQDN based on the configuration and given IP address.
bool ddnsEnabled()
Convenience method for checking if DHCP-DDNS is enabled.
void getUpdateDirections(const T &fqdn_resp, bool &forward, bool &reverse)
Get directional update flags based on server FQDN flags.
void stop()
Stop the sender.
void suspendUpdates()
Suspends sending requests.
void adjustDomainName(const T &fqdn, T &fqdn_resp, const DdnsParams &ddns_params)
Set server FQDN name based on configuration and a given FQDN.
void stopSender()
Disables sending NameChangeRequests to kea-dhcp-ddns.
void adjustFqdnFlags(const T &fqdn, T &fqdn_resp, const DdnsParams &ddns_params)
Set server FQDN flags based on configuration and a given FQDN.
std::string qualifyName(const std::string &partial_name, const DdnsParams &ddns_params, const bool trailing_dot) const
Adds a qualifying suffix to a given domain name.
void startSender(D2ClientErrorHandler error_handler, const isc::asiolink::IOServicePtr &io_service)
Enables sending NameChangeRequests to kea-dhcp-ddns.
Convenience container for conveying DDNS behavioral parameters It is intended to be created per Packe...
Definition ddns_params.h:23
bool getUpdateOnRenew() const
Returns whether or not DNS should be updated when leases renew.
bool getEnableUpdates() const
Returns whether or not DHCP DDNS updating is enabled.
void close()
Close communication socket.
static Dhcp4to6Ipc & instance()
Returns pointer to the sole instance of Dhcp4to6Ipc.
DHCPv4 message exchange.
Definition dhcp4_srv.h:62
AllocEngine::ClientContext4Ptr getContext() const
Returns the copy of the context for the Allocation engine.
Definition dhcp4_srv.h:113
void deleteResponse()
Removes the response message by resetting the pointer to null.
Definition dhcp4_srv.h:108
Pkt4Ptr getQuery() const
Returns the pointer to the query from the client.
Definition dhcp4_srv.h:96
static void setHostIdentifiers(AllocEngine::ClientContext4Ptr context)
Set host identifiers within a context.
Definition dhcp4_srv.cc:452
static void classifyByVendor(const Pkt4Ptr &pkt)
Assign class using vendor-class-identifier option.
Definition dhcp4_srv.cc:614
void initResponse()
Initializes the instance of the response message.
Definition dhcp4_srv.cc:324
void setReservedMessageFields()
Sets reserved values of siaddr, sname and file in the server's response.
Definition dhcp4_srv.cc:592
CfgOptionList & getCfgOptionList()
Returns the configured option list (non-const version)
Definition dhcp4_srv.h:118
Pkt4Ptr getResponse() const
Returns the pointer to the server's response.
Definition dhcp4_srv.h:103
static void setReservedClientClasses(AllocEngine::ClientContext4Ptr context)
Assigns classes retrieved from host reservation database.
Definition dhcp4_srv.cc:568
void initResponse4o6()
Initializes the DHCPv6 part of the response message.
Definition dhcp4_srv.cc:350
static void evaluateClasses(const Pkt4Ptr &pkt, bool depend_on_known)
Evaluate classes.
Definition dhcp4_srv.cc:637
void setIPv6OnlyPreferred(bool ipv6_only_preferred)
Set the IPv6-Only Preferred flag.
Definition dhcp4_srv.h:135
Dhcpv4Exchange(const AllocEnginePtr &alloc_engine, const Pkt4Ptr &query, AllocEngine::ClientContext4Ptr &context, const ConstSubnet4Ptr &subnet, bool &drop)
Constructor.
Definition dhcp4_srv.cc:206
static void classifyPacket(const Pkt4Ptr &pkt)
Assigns incoming packet to zero or more classes.
Definition dhcp4_srv.cc:626
static void removeDependentEvaluatedClasses(const Pkt4Ptr &query)
Removed evaluated client classes.
Definition dhcp4_srv.cc:553
bool getIPv6OnlyPreferred() const
Returns the IPv6-Only Preferred flag.
Definition dhcp4_srv.h:128
void conditionallySetReservedClientClasses()
Assigns classes retrieved from host reservation database if they haven't been yet set.
Definition dhcp4_srv.cc:578
void initContext0(const Pkt4Ptr &query, AllocEngine::ClientContext4Ptr ctx)
Initialize client context (first part).
int run()
Main server processing loop.
void declineLease(const Lease4Ptr &lease, const Pkt4Ptr &decline, AllocEngine::ClientContext4Ptr &context)
Marks lease as declined.
void processPacketAndSendResponse(Pkt4Ptr query)
Process a single incoming DHCPv4 packet and sends the response.
void classifyPacket(const Pkt4Ptr &pkt)
Assigns incoming packet to zero or more classes.
void appendRequestedVendorOptions(Dhcpv4Exchange &ex)
Appends requested vendor options as requested by client.
void adjustIfaceData(Dhcpv4Exchange &ex)
Set IP/UDP and interface parameters for the DHCPv4 response.
static uint16_t checkRelayPort(const Dhcpv4Exchange &ex)
Check if the relay port RAI sub-option was set in the query.
virtual ~Dhcpv4Srv()
Destructor. Used during DHCPv4 service shutdown.
Definition dhcp4_srv.cc:725
virtual Pkt4Ptr receivePacket(int timeout)
dummy wrapper around IfaceMgr::receive4
isc::dhcp::ConstSubnet4Ptr selectSubnet4o6(const Pkt4Ptr &query, bool &drop, bool sanity_only=false, bool allow_answer_park=true)
Selects a subnet for a given client's DHCP4o6 packet.
Definition dhcp4_srv.cc:910
bool accept(const Pkt4Ptr &query)
Checks whether received message should be processed or discarded.
void setTeeTimes(const Lease4Ptr &lease, const ConstSubnet4Ptr &subnet, Pkt4Ptr resp)
Adds the T1 and T2 timers to the outbound response as appropriate.
static void appendServerID(Dhcpv4Exchange &ex)
Adds server identifier option to the server's response.
void postAllocateNameUpdate(const AllocEngine::ClientContext4Ptr &ctx, const Lease4Ptr &lease, const Pkt4Ptr &query, const Pkt4Ptr &resp, bool client_name_changed)
Update client name and DNS flags in the lease and response.
void runOne()
Main server processing step.
void startD2()
Starts DHCP_DDNS client IO if DDNS updates are enabled.
static int getHookIndexBuffer4Receive()
Returns the index for "buffer4_receive" hook point.
Pkt4Ptr processRequest(Pkt4Ptr &request, AllocEngine::ClientContext4Ptr &context)
Processes incoming REQUEST and returns REPLY response.
static void processStatsReceived(const Pkt4Ptr &query)
Class methods for DHCPv4-over-DHCPv6 handler.
static int getHookIndexPkt4Send()
Returns the index for "pkt4_send" hook point.
void processDecline(Pkt4Ptr &decline, AllocEngine::ClientContext4Ptr &context)
Process incoming DHCPDECLINE messages.
Dhcpv4Srv(uint16_t server_port=DHCP4_SERVER_PORT, uint16_t client_port=0, const bool use_bcast=true, const bool direct_response_desired=true)
Default constructor.
Definition dhcp4_srv.cc:663
isc::dhcp::ConstSubnet4Ptr selectSubnet(const Pkt4Ptr &query, bool &drop, bool sanity_only=false, bool allow_answer_park=true)
Selects a subnet for a given client's packet.
Definition dhcp4_srv.cc:776
static int getHookIndexSubnet4Select()
Returns the index for "subnet4_select" hook point.
static void processStatsSent(const Pkt4Ptr &response)
Updates statistics for transmitted packets.
void shutdown() override
Instructs the server to shut down.
Definition dhcp4_srv.cc:770
static int getHookIndexLease4Release()
Returns the index for "lease4_release" hook point.
void adjustRemoteAddr(Dhcpv4Exchange &ex)
Sets remote addresses for outgoing packet.
static int getHookIndexPkt4Receive()
Returns the index for "pkt4_receive" hook point.
void assignLease(Dhcpv4Exchange &ex)
Assigns a lease and appends corresponding options.
void evaluateAdditionalClasses(Dhcpv4Exchange &ex)
Evaluates classes in the additional classes lists.
Pkt4Ptr processDhcp4Query(Pkt4Ptr query, bool allow_answer_park)
Process a single incoming DHCPv4 query.
asiolink::IOServicePtr & getIOService()
Returns pointer to the IO service used by the server.
Definition dhcp4_srv.h:319
void setFixedFields(Dhcpv4Exchange &ex)
Sets fixed fields of the outgoing packet.
void appendBasicOptions(Dhcpv4Exchange &ex)
Append basic options if they are not present.
void recoverStashedAgentOption(const Pkt4Ptr &query)
Recover stashed agent options from client address lease.
void processClientName(Dhcpv4Exchange &ex)
Processes Client FQDN and Hostname Options sent by a client.
boost::shared_ptr< AllocEngine > alloc_engine_
Allocation Engine.
Definition dhcp4_srv.h:1279
void serverDecline(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Lease4Ptr lease, bool lease_exists)
Renders a lease declined after the server has detected, via ping-check or other means,...
Pkt4Ptr processInform(Pkt4Ptr &inform, AllocEngine::ClientContext4Ptr &context)
Processes incoming DHCPINFORM messages.
uint16_t client_port_
UDP port number to which server sends all responses.
Definition dhcp4_srv.h:1269
void serverDeclineNoThrow(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Lease4Ptr lease, bool lease_exists)
Exception safe wrapper around serverDecline()
void processPacketPktSend(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Pkt4Ptr &rsp, ConstSubnet4Ptr &subnet)
Executes pkt4_send callout.
void processPacketAndSendResponseNoThrow(Pkt4Ptr query)
Process a single incoming DHCPv4 packet and sends the response.
std::list< std::list< std::string > > jsonPathsToRedact() const final override
Return a list of all paths that contain passwords or secrets for kea-dhcp4.
static std::string srvidToString(const OptionPtr &opt)
converts server-id to text Converts content of server-id option to a text representation,...
bool acceptServerId(const Pkt4Ptr &pkt) const
Verifies if the server id belongs to our server.
static const std::string VENDOR_CLASS_PREFIX
this is a prefix added to the content of vendor-class option
Definition dhcp4_srv.h:933
void createNameChangeRequests(const Lease4Ptr &lease, const Lease4Ptr &old_lease, const DdnsParams &ddns_params)
Creates NameChangeRequests which correspond to the lease which has been acquired.
void appendRequestedOptions(Dhcpv4Exchange &ex)
Appends options requested by client.
void setPacketStatisticsDefaults()
This function sets statistics related to DHCPv4 packets processing to their initial values.
Definition dhcp4_srv.cc:715
void processLocalizedQuery4AndSendResponse(Pkt4Ptr query, AllocEngine::ClientContext4Ptr &ctx, bool allow_answer_park)
Process a localized incoming DHCPv4 query.
static std::string getVersion(bool extended)
returns Kea version on stdout and exit.
void buildCfgOptionList(Dhcpv4Exchange &ex)
Build the configured option list.
volatile bool shutdown_
Indicates if shutdown is in progress.
Definition dhcp4_srv.h:1273
uint16_t server_port_
UDP port number on which server listens.
Definition dhcp4_srv.h:1266
void sendResponseNoThrow(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Pkt4Ptr &rsp, ConstSubnet4Ptr &subnet)
Process an unparked DHCPv4 packet and sends the response.
bool earlyGHRLookup(const Pkt4Ptr &query, AllocEngine::ClientContext4Ptr ctx)
Initialize client context and perform early global reservations lookup.
NetworkStatePtr network_state_
Holds information about disabled DHCP service and/or disabled subnet/network scopes.
Definition dhcp4_srv.h:1286
void processDhcp4QueryAndSendResponse(Pkt4Ptr query, bool allow_answer_park)
Process a single incoming DHCPv4 query.
bool getSendResponsesToSource() const
Returns value of the test_send_responses_to_source_ flag.
Definition dhcp4_srv.h:509
Pkt4Ptr processDiscover(Pkt4Ptr &discover, AllocEngine::ClientContext4Ptr &context)
Processes incoming DISCOVER and returns response.
virtual void d2ClientErrorHandler(const dhcp_ddns::NameChangeSender::Result result, dhcp_ddns::NameChangeRequestPtr &ncr)
Implements the error handler for DHCP_DDNS IO errors.
uint16_t getServerPort() const
Get UDP port on which server should listen.
virtual void sendPacket(const Pkt4Ptr &pkt)
dummy wrapper around IfaceMgr::send()
static int getHookIndexBuffer4Send()
Returns the index for "buffer4_send" hook point.
void stopD2()
Stops DHCP_DDNS client IO if DDNS updates are enabled.
static void sanityCheck(const Pkt4Ptr &query)
Verifies if specified packet meets RFC requirements.
bool acceptMessageType(const Pkt4Ptr &query) const
Check if received message type is valid for the server to process.
void discardPackets()
Discards parked packets Clears the packet parking lots of all packets.
static int getHookIndexLease4Decline()
Returns the index for "lease4_decline" hook point.
void processRelease(Pkt4Ptr &release, AllocEngine::ClientContext4Ptr &context)
Processes incoming DHCPRELEASE messages.
bool acceptDirectRequest(const Pkt4Ptr &query)
Check if a message sent by directly connected client should be accepted or discarded.
RequirementLevel
defines if certain option may, must or must not appear
Definition dhcp4_srv.h:277
Pkt4Ptr processPacket(Pkt4Ptr query, bool allow_answer_park=true)
Process a single incoming DHCPv4 packet.
void processPacketBufferSend(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &rsp)
Executes buffer4_send callout and sends the response.
bool assignZero(ConstSubnet4Ptr &subnet, const ClientClasses &client_classes)
Assign the 0.0.0.0 address to an IPv6-Only client.
void deferredUnpack(Pkt4Ptr &query)
Perform deferred option unpacking.
Pkt4Ptr processLocalizedQuery4(AllocEngine::ClientContext4Ptr &ctx, bool allow_answer_park)
Process a localized incoming DHCPv4 query.
static std::list< std::string > getDBVersions()
Return extended version info for registered backends.
static void create()
Creates new instance of the HostMgr.
Definition host_mgr.cc:52
IdentifierType
Type of the host identifier.
Definition host.h:337
@ IDENT_FLEX
Flexible host identifier.
Definition host.h:342
@ IDENT_CLIENT_ID
Definition host.h:341
@ IDENT_CIRCUIT_ID
Definition host.h:340
std::string getIdentifierAsText() const
Returns host identifier in a textual form.
Definition host.cc:312
static IfaceMgr & instance()
IfaceMgr is a singleton class.
Definition iface_mgr.cc:54
bool send(const Pkt6Ptr &pkt)
Sends an IPv6 packet.
void closeSockets()
Closes all open sockets.
Definition iface_mgr.cc:286
void setMatchingPacketFilter(const bool direct_response_desired=false)
Set Packet Filter object to handle send/receive packets.
uint16_t getSocket(const isc::dhcp::Pkt6Ptr &pkt)
Return most suitable socket for transmitting specified IPv6 packet.
static TrackingLeaseMgr & instance()
Return current lease manager.
static std::list< std::string > getDBVersions()
Return extended version info for registered backends.
static void destroy()
Destroy lease manager.
virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress &addr) const =0
Returns an IPv4 lease for specified IPv4 address.
virtual bool addLease(const Lease4Ptr &lease)=0
Adds an IPv4 lease.
virtual bool deleteLease(const Lease4Ptr &lease)=0
Deletes an IPv4 lease.
virtual void updateLease4(const Lease4Ptr &lease4)=0
Updates IPv4 lease.
static std::list< std::string > getDBVersions()
Return extended version info for registered backends.
static OptionDefinitionPtr getOptionDef(const std::string &space, const uint16_t code)
Return the first option definition matching a particular option code.
Definition libdhcp++.cc:132
static const OptionDefinition & DHO_DHCP_SERVER_IDENTIFIER_DEF()
Get definition of DHO_DHCP_SERVER_IDENTIFIER option.
static const OptionDefinition & DHO_DHCP_AGENT_OPTIONS_DEF()
Get definition of DHO_DHCP_AGENT_OPTIONS option.
static OptionDefinitionPtr getRuntimeOptionDef(const std::string &space, const uint16_t code)
Returns runtime (non-standard) option definition by space and option code.
Definition libdhcp++.cc:195
static OptionDefinitionPtr getLastResortOptionDef(const std::string &space, const uint16_t code)
Returns last resort option definition by space and option code.
Definition libdhcp++.cc:253
Controls the DHCP service enabling status.
Attempt to update lease that was not there.
std::vector< isc::asiolink::IOAddress > AddressContainer
Defines a collection of IPv4 addresses.
Represents DHCPv4 Client FQDN Option (code 81).
static const uint8_t FLAG_N
Bit N.
bool getFlag(const uint8_t flag) const
Checks if the specified flag of the DHCPv4 Client FQDN Option is set.
static const uint8_t FLAG_S
Bit S.
void setDomainName(const std::string &domain_name, const DomainNameType domain_name_type)
Set new domain-name.
void setFlag(const uint8_t flag, const bool set)
Modifies the value of the specified DHCPv4 Client Fqdn Option flag.
static const uint8_t FLAG_E
Bit E.
virtual std::string toText(int indent=0) const
Returns string representation of the option.
Option with defined data fields represented as buffers that can be accessed using data field index.
static unsigned int getLabelCount(const std::string &text_name)
Return the number of labels in the Name.
Base class representing a DHCP option definition.
Option descriptor.
Definition cfg_option.h:48
OptionPtr option_
Option instance.
Definition cfg_option.h:51
bool allowedForClientClasses(const ClientClasses &cclasses) const
Validates an OptionDescriptor's client-classes against a list of classes.
Definition cfg_option.cc:63
Forward declaration to OptionIntArray.
Forward declaration to OptionInt.
Definition option_int.h:49
Class which represents an option carrying a single string value.
This class represents vendor-specific information option.
static const size_t OPTION4_HDR_LEN
length of the usual DHCPv4 option header (there are exceptions)
Definition option.h:84
Represents DHCPv4 packet.
Definition pkt4.h:37
static const uint16_t FLAG_BROADCAST_MASK
Mask for the value of flags field in the DHCPv4 message to check whether client requested broadcast r...
Definition pkt4.h:54
Represents DHCPv4-over-DHCPv6 packet.
Definition pkt4o6.h:30
Represents a DHCPv6 packet.
Definition pkt6.h:44
@ RELAY_GET_FIRST
Definition pkt6.h:77
An exception that is thrown if a DHCPv6 protocol violation occurs while processing a message (e....
Definition utils.h:17
Resource race avoidance RAII handler for DHCPv4.
bool tryLock4(const asiolink::IOAddress &addr)
Tries to acquires a resource.
RAII object enabling copying options retrieved from the packet.
Definition pkt.h:46
Exception thrown when a call to select is interrupted by a signal.
Definition iface_mgr.h:55
Exception thrown during option unpacking This exception is thrown when an error has occurred,...
Definition option.h:52
Result
Defines the outcome of an asynchronous NCR send.
Definition ncr_io.h:478
@ NEXT_STEP_PARK
park the packet
@ NEXT_STEP_CONTINUE
continue normally
@ NEXT_STEP_DROP
drop the packet
@ NEXT_STEP_SKIP
skip the next processing step
static int registerHook(const std::string &name)
Register Hook.
static bool calloutsPresent(int index)
Are callouts present?
static std::vector< std::string > getLibraryNames()
Return list of loaded libraries.
static bool unloadLibraries()
Unload libraries.
static void park(const std::string &hook_name, T parked_object, std::function< void()> unpark_callback)
Park an object (packet).
static void callCallouts(int index, CalloutHandle &handle)
Calls the callouts for a given hook.
static void prepareUnloadLibraries()
Prepare the unloading of libraries.
static bool drop(const std::string &hook_name, T parked_object)
Removes parked object without calling a callback.
static void clearParkingLots()
Clears any parking packets.
Wrapper class around callout handle which automatically resets handle's state.
static ServerHooks & getServerHooks()
Return ServerHooks object.
static std::string getVersion()
Version.
Definition log/logger.cc:60
bool lock()
Acquire the lock (blocks if something else has acquired a lock on the same task name)
int getExitValue()
Fetches the exit value.
Definition daemon.h:220
Statistics Manager class.
static StatsMgr & instance()
Statistics Manager accessor method.
static std::string generateName(const std::string &context, Type index, const std::string &stat_name)
Generates statistic name in a given context.
RAII class creating a critical section.
static MultiThreadingMgr & instance()
Returns a single instance of Multi Threading Manager.
ThreadPool< std::function< void()> > & getThreadPool()
Get the dhcp thread pool.
void apply(bool enabled, uint32_t thread_count, uint32_t queue_size)
Apply the multi-threading related settings.
Read mutex RAII handler.
Defines classes for storing client class definitions.
Defines the D2ClientConfig class.
Defines the D2ClientMgr class.
Contains declarations for loggers used by the DHCPv4 server component.
Dhcp4Hooks Hooks
Definition dhcp4_srv.cc:201
Defines the Dhcp4o6Ipc class.
@ D6O_INTERFACE_ID
Definition dhcp6.h:38
@ DHCPV6_DHCPV4_RESPONSE
Definition dhcp6.h:232
#define DOCSIS3_V4_ORO
#define VENDOR_ID_CABLE_LABS
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
boost::shared_ptr< OptionUint8Array > OptionUint8ArrayPtr
OptionInt< uint32_t > OptionUint32
Definition option_int.h:34
boost::shared_ptr< OptionUint32 > OptionUint32Ptr
Definition option_int.h:35
void setValue(const std::string &name, const int64_t value)
Records absolute integer observation.
void addValue(const std::string &name, const int64_t value)
Records incremental integer observation.
When a message is logged with DEBUG severity, the debug level associated with the message is also spe...
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition macros.h:32
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition macros.h:20
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
Definition macros.h:26
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition macros.h:14
boost::shared_ptr< const Element > ConstElementPtr
Definition data.h:29
@ info
Definition db_log.h:120
boost::shared_ptr< NameChangeRequest > NameChangeRequestPtr
Defines a pointer to a NameChangeRequest.
Definition ncr_msg.h:241
const isc::log::MessageID DHCP4_BUFFER_RECEIVE_FAIL
boost::shared_ptr< OptionVendor > OptionVendorPtr
Pointer to a vendor option.
isc::log::Logger ddns4_logger(DHCP4_DDNS_LOGGER_NAME)
Logger for Hostname or FQDN processing.
Definition dhcp4_log.h:115
const isc::log::MessageID DHCP4_PACKET_DROP_0004
const isc::log::MessageID DHCP4_SRV_DHCP4O6_ERROR
const isc::log::MessageID DHCP4_RELEASE_EXCEPTION
const isc::log::MessageID DHCP4_SUBNET_DATA
const isc::log::MessageID DHCP4_INIT_REBOOT
const isc::log::MessageID DHCP4_HOOK_PACKET_SEND_SKIP
const isc::log::MessageID DHCP4_FLEX_ID
const isc::log::MessageID DHCP4_PACKET_DROP_0003
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_PARKING_LOT_FULL
const isc::log::MessageID DHCP4_DEFERRED_OPTION_UNPACK_FAIL
const isc::log::MessageID DHCP4_PACKET_DROP_0001
const isc::log::MessageID DHCP4_QUERY_DATA
const isc::log::MessageID DHCP4_NO_LEASE_INIT_REBOOT
const isc::log::MessageID DHCP4_INFORM_DIRECT_REPLY
const isc::log::MessageID DHCP4_SERVER_INITIATED_DECLINE_ADD_FAILED
boost::shared_ptr< Lease4Collection > Lease4CollectionPtr
A shared pointer to the collection of IPv4 leases.
Definition lease.h:523
const isc::log::MessageID DHCP4_HOOK_LEASE4_OFFER_ARGUMENT_MISSING
void queueNCR(const NameChangeType &chg_type, const Lease4Ptr &lease)
Creates name change request from the DHCPv4 lease.
const isc::log::MessageID DHCP4_CLIENT_FQDN_PROCESS
const isc::log::MessageID DHCP4_DEFERRED_OPTION_MISSING
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_DROP
@ DHO_SUBNET_MASK
Definition dhcp4.h:70
@ DHO_ROUTERS
Definition dhcp4.h:72
@ DHO_DOMAIN_NAME
Definition dhcp4.h:84
@ DHO_DOMAIN_NAME_SERVERS
Definition dhcp4.h:75
@ DHO_VENDOR_CLASS_IDENTIFIER
Definition dhcp4.h:129
@ DHO_DHCP_REBINDING_TIME
Definition dhcp4.h:128
@ DHO_V6_ONLY_PREFERRED
Definition dhcp4.h:172
@ DHO_DHCP_SERVER_IDENTIFIER
Definition dhcp4.h:123
@ DHO_HOST_NAME
Definition dhcp4.h:81
@ DHO_VIVCO_SUBOPTIONS
Definition dhcp4.h:188
@ DHO_DHCP_REQUESTED_ADDRESS
Definition dhcp4.h:119
@ DHO_DHCP_AGENT_OPTIONS
Definition dhcp4.h:151
@ DHO_SUBNET_SELECTION
Definition dhcp4.h:182
@ DHO_DHCP_PARAMETER_REQUEST_LIST
Definition dhcp4.h:124
@ DHO_FQDN
Definition dhcp4.h:150
@ DHO_VIVSO_SUBOPTIONS
Definition dhcp4.h:189
@ DHO_DHCP_RENEWAL_TIME
Definition dhcp4.h:127
@ DHO_DHCP_LEASE_TIME
Definition dhcp4.h:120
const isc::log::MessageID DHCP4_PACKET_PROCESS_EXCEPTION_MAIN
const isc::log::MessageID DHCP4_PACKET_DROP_0008
const isc::log::MessageID DHCP4_RELEASE_EXPIRED
const isc::log::MessageID DHCP4_HOOK_LEASES4_COMMITTED_DROP
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_4O6_PARKING_LOT_FULL
const isc::log::MessageID DHCP4_DHCP4O6_SUBNET_SELECTION_FAILED
const isc::log::MessageID DHCP4_RELEASE_FAIL_WRONG_CLIENT
const isc::log::MessageID DHCP4_HOOK_LEASES4_COMMITTED_PARKING_LOT_FULL
const isc::log::MessageID DHCP4_HOOK_BUFFER_RCVD_DROP
boost::shared_ptr< const Subnet4 > ConstSubnet4Ptr
A const pointer to a Subnet4 object.
Definition subnet.h:458
boost::shared_ptr< OptionCustom > OptionCustomPtr
A pointer to the OptionCustom object.
const isc::log::MessageID DHCP4_HOOK_PACKET_RCVD_SKIP
const int DBG_DHCP4_BASIC_DATA
Debug level used to log the traces with some basic data.
Definition dhcp4_log.h:45
const isc::log::MessageID DHCP4_LEASE_ALLOC
const int DBG_DHCP4_DETAIL
Debug level used to trace detailed errors.
Definition dhcp4_log.h:53
boost::shared_ptr< Pkt4 > Pkt4Ptr
A pointer to Pkt4 object.
Definition pkt4.h:555
isc::log::Logger lease4_logger(DHCP4_LEASE_LOGGER_NAME)
Logger for lease allocation logic.
Definition dhcp4_log.h:120
const isc::log::MessageID DHCP4_NCR_CREATION_FAILED
isc::log::Logger options4_logger(DHCP4_OPTIONS_LOGGER_NAME)
Logger for options parser.
Definition dhcp4_log.h:109
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_SKIP
const int DBG_DHCP4_DETAIL_DATA
This level is used to log the contents of packets received and sent.
Definition dhcp4_log.h:56
const isc::log::MessageID DHCP4_PACKET_PACK
boost::shared_ptr< AllocEngine > AllocEnginePtr
A pointer to the AllocEngine object.
ContinuationPtr makeContinuation(Continuation &&cont)
Continuation factory.
const isc::log::MessageID DHCP4_DECLINE_FAIL
const isc::log::MessageID DHCP4_RECOVERED_STASHED_RELAY_AGENT_INFO
const isc::log::MessageID DHCP4_LEASE_REUSE
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_PARK
boost::shared_ptr< const CfgHostOperations > ConstCfgHostOperationsPtr
Pointer to the const object.
boost::shared_ptr< CfgIface > CfgIfacePtr
A pointer to the CfgIface .
Definition cfg_iface.h:501
const isc::log::MessageID DHCP4_PACKET_PACK_FAIL
boost::shared_ptr< ClientClassDef > ClientClassDefPtr
a pointer to an ClientClassDef
const isc::log::MessageID DHCP4_DDNS_REQUEST_SEND_FAILED
const isc::log::MessageID DHCP4_GENERATE_FQDN
const isc::log::MessageID DHCP4_CLASS_ASSIGNED
const isc::log::MessageID DHCP4_PACKET_PROCESS_STD_EXCEPTION
boost::shared_ptr< SrvConfig > SrvConfigPtr
Non-const pointer to the SrvConfig.
const isc::log::MessageID DHCP4_RESPONSE_HOSTNAME_DATA
const isc::log::MessageID DHCP4_BUFFER_WAIT_SIGNAL
const isc::log::MessageID DHCP4_HOOK_LEASE4_RELEASE_SKIP
const isc::log::MessageID DHCP4_POST_ALLOCATION_NAME_UPDATE_FAIL
const isc::log::MessageID DHCP4_PACKET_NAK_0001
const isc::log::MessageID DHCP4_HOOK_DECLINE_SKIP
const isc::log::MessageID DHCP4_HOOK_LEASE4_OFFER_PARK
const isc::log::MessageID DHCP4_DECLINE_LEASE_MISMATCH
const isc::log::MessageID DHCP4_SRV_UNLOAD_LIBRARIES_ERROR
const isc::log::MessageID DHCP4_ADDITIONAL_CLASS_EVAL_ERROR
const isc::log::MessageID DHCP4_RESPONSE_HOSTNAME_GENERATE
boost::shared_ptr< HWAddr > HWAddrPtr
Shared pointer to a hardware address structure.
Definition hwaddr.h:154
const isc::log::MessageID DHCP4_PACKET_DROP_0013
const isc::log::MessageID DHCP4_PACKET_QUEUE_FULL
const isc::log::MessageID DHCP4_LEASE_OFFER
const isc::log::MessageID DHCP4_PACKET_DROP_0009
const isc::log::MessageID DHCP4_PACKET_RECEIVED
boost::shared_ptr< Pkt4o6 > Pkt4o6Ptr
A pointer to Pkt4o6 object.
Definition pkt4o6.h:82
const isc::log::MessageID DHCP4_RELEASE_DELETED
const isc::log::MessageID DHCP4_BUFFER_UNPACK
const isc::log::MessageID DHCP4_CLIENT_HOSTNAME_DATA
OptionContainer::nth_index< 5 >::type OptionContainerCancelIndex
Type of the index #5 - option cancellation flag.
Definition cfg_option.h:339
const isc::log::MessageID DHCP4_CLASSES_ASSIGNED_AFTER_SUBNET_SELECTION
const isc::log::MessageID DHCP4_PACKET_SEND_FAIL
std::pair< OptionContainerPersistIndex::const_iterator, OptionContainerPersistIndex::const_iterator > OptionContainerPersistRange
Pair of iterators to represent the range of options having the same persistency flag.
Definition cfg_option.h:337
boost::shared_ptr< OptionDefinition > OptionDefinitionPtr
Pointer to option definition object.
const isc::log::MessageID DHCP4_DHCP4O6_SUBNET_DATA
boost::shared_ptr< Option4ClientFqdn > Option4ClientFqdnPtr
A pointer to the Option4ClientFqdn object.
const isc::log::MessageID DHCP4_CLIENTID_IGNORED_FOR_LEASES
const isc::log::MessageID DHCP4_CLIENT_NAME_PROC_FAIL
const isc::log::MessageID DHCP4_CLIENT_HOSTNAME_PROCESS
const isc::log::MessageID DHCP4_HOOK_DDNS_UPDATE
const isc::log::MessageID DHCP4_SRV_CONSTRUCT_ERROR
const isc::log::MessageID DHCP4_SERVER_INITIATED_DECLINE
boost::shared_ptr< Expression > ExpressionPtr
Definition token.h:31
const isc::log::MessageID DHCP4_RELEASE_FAIL
const isc::log::MessageID DHCP4_RELEASE_FAIL_NO_LEASE
const isc::log::MessageID DHCP4_CLIENT_HOSTNAME_MALFORMED
boost::shared_ptr< Pool > PoolPtr
a pointer to either IPv4 or IPv6 Pool
Definition pool.h:726
boost::shared_ptr< OptionString > OptionStringPtr
Pointer to the OptionString object.
isc::log::Logger bad_packet4_logger(DHCP4_BAD_PACKET_LOGGER_NAME)
Logger for rejected packets.
Definition dhcp4_log.h:97
isc::hooks::CalloutHandlePtr getCalloutHandle(const T &pktptr)
CalloutHandle Store.
const isc::log::MessageID DHCP4_V6_ONLY_PREFERRED_MISSING_IN_ACK
const isc::log::MessageID DHCP4_PACKET_DROP_0006
const int DBG_DHCP4_BASIC
Debug level used to trace basic operations within the code.
Definition dhcp4_log.h:33
boost::shared_ptr< ClientClassDictionary > ClientClassDictionaryPtr
Defines a pointer to a ClientClassDictionary.
const isc::log::MessageID DHCP4_SRV_D2STOP_ERROR
const isc::log::MessageID DHCP4_SERVER_INITIATED_DECLINE_UPDATE_FAILED
const isc::log::MessageID DHCP4_RESPONSE_FQDN_DATA
boost::shared_ptr< ClientId > ClientIdPtr
Shared pointer to a Client ID.
Definition duid.h:216
boost::shared_ptr< Continuation > ContinuationPtr
Define the type of shared pointers to continuations.
const isc::log::MessageID DHCP4_DECLINE_LEASE_NOT_FOUND
boost::shared_ptr< OptionContainer > OptionContainerPtr
Pointer to the OptionContainer object.
Definition cfg_option.h:323
boost::shared_ptr< ClientClassDefList > ClientClassDefListPtr
Defines a pointer to a ClientClassDefList.
const isc::log::MessageID DHCP4_PACKET_DROP_0005
const isc::log::MessageID DHCP4_SUBNET_DYNAMICALLY_CHANGED
const isc::log::MessageID DHCP4_SHUTDOWN_REQUEST
@ DHCPREQUEST
Definition dhcp4.h:237
@ DHCP_TYPES_EOF
Definition dhcp4.h:253
@ DHCPOFFER
Definition dhcp4.h:236
@ DHCPDECLINE
Definition dhcp4.h:238
@ DHCPNAK
Definition dhcp4.h:240
@ DHCPRELEASE
Definition dhcp4.h:241
@ DHCPDISCOVER
Definition dhcp4.h:235
@ DHCP_NOTYPE
Message Type option missing.
Definition dhcp4.h:234
@ DHCPINFORM
Definition dhcp4.h:242
@ DHCPACK
Definition dhcp4.h:239
const isc::log::MessageID DHCP4_PACKET_NAK_0003
const isc::log::MessageID DHCP4_TESTING_MODE_SEND_TO_SOURCE_ENABLED
boost::shared_ptr< const CfgSubnets4 > ConstCfgSubnets4Ptr
Const pointer.
const isc::log::MessageID DHCP4_BUFFER_RECEIVED
bool evaluateBool(const Expression &expr, Pkt &pkt)
Evaluate a RPN expression for a v4 or v6 packet and return a true or false decision.
Definition evaluate.cc:34
const isc::log::MessageID DHCP4_SUBNET_SELECTION_FAILED
boost::shared_ptr< const Host > ConstHostPtr
Const pointer to the Host object.
Definition host.h:840
const isc::log::MessageID DHCP4_RESPONSE_DATA
const isc::log::MessageID DHCP4_ADDITIONAL_CLASS_NO_TEST
isc::log::Logger packet4_logger(DHCP4_PACKET_LOGGER_NAME)
Logger for processed packets.
Definition dhcp4_log.h:103
OptionContainer::nth_index< 2 >::type OptionContainerPersistIndex
Type of the index #2 - option persistency flag.
Definition cfg_option.h:332
const isc::log::MessageID DHCP4_DECLINE_LEASE
const isc::log::MessageID DHCP4_PACKET_SEND
boost::shared_ptr< OptionVendorClass > OptionVendorClassPtr
Defines a pointer to the OptionVendorClass.
const isc::log::MessageID DHCP4_RELEASE
const isc::log::MessageID DHCP4_HOOK_LEASE4_OFFER_DROP
const isc::log::MessageID DHCP4_HOOK_BUFFER_RCVD_SKIP
const isc::log::MessageID DHCP4_UNKNOWN_ADDRESS_REQUESTED
boost::shared_ptr< Pkt6 > Pkt6Ptr
A pointer to Pkt6 packet.
Definition pkt6.h:31
const isc::log::MessageID DHCP4_PACKET_PROCESS_STD_EXCEPTION_MAIN
const isc::log::MessageID DHCP4_DHCP4O6_HOOK_SUBNET4_SELECT_DROP
std::vector< uint8_t > OptionBuffer
buffer types used in DHCP code.
Definition option.h:24
const isc::log::MessageID DHCP4_OPEN_SOCKET
const isc::log::MessageID DHCP4_PACKET_DROP_0007
boost::shared_ptr< CfgSharedNetworks4 > CfgSharedNetworks4Ptr
Pointer to the configuration of IPv4 shared networks.
const isc::log::MessageID DHCP4_HOOK_PACKET_SEND_DROP
const isc::log::MessageID DHCP4_RESERVED_HOSTNAME_ASSIGNED
isc::log::Logger dhcp4_logger(DHCP4_APP_LOGGER_NAME)
Base logger for DHCPv4 server.
Definition dhcp4_log.h:90
const isc::log::MessageID DHCP4_CLASSES_ASSIGNED
@ RAI_OPTION_SERVER_ID_OVERRIDE
Definition dhcp4.h:275
@ RAI_OPTION_AGENT_CIRCUIT_ID
Definition dhcp4.h:265
@ RAI_OPTION_RELAY_PORT
Definition dhcp4.h:283
const isc::log::MessageID DHCP4_QUERY_LABEL
bool isClientClassBuiltIn(const ClientClass &client_class)
Check if a client class name is builtin.
const isc::log::MessageID DHCP4_PACKET_NAK_0002
const int DBG_DHCP4_HOOKS
Debug level used to trace hook related operations.
Definition dhcp4_log.h:36
boost::shared_ptr< SharedNetwork4 > SharedNetwork4Ptr
Pointer to SharedNetwork4 object.
std::vector< Lease4Ptr > Lease4Collection
A collection of IPv4 leases.
Definition lease.h:520
const isc::log::MessageID DHCP4_HOOK_BUFFER_SEND_SKIP
const isc::log::MessageID DHCP4_PACKET_PROCESS_EXCEPTION
const isc::log::MessageID DHCP4_V6_ONLY_PREFERRED_MISSING_IN_OFFER
std::pair< OptionContainerCancelIndex::const_iterator, OptionContainerCancelIndex::const_iterator > OptionContainerCancelRange
Pair of iterators to represent the range of options having the same cancellation flag.
Definition cfg_option.h:344
const isc::log::MessageID DHCP4_PACKET_OPTIONS_SKIPPED
const isc::log::MessageID DHCP4_EMPTY_HOSTNAME
const isc::log::MessageID DHCP4_REQUEST
const isc::log::MessageID DHCP4_SUBNET_SELECTED
const isc::log::MessageID DHCP4_PACKET_DROP_0010
boost::shared_ptr< Lease4 > Lease4Ptr
Pointer to a Lease4 structure.
Definition lease.h:315
const isc::log::MessageID DHCP4_SERVER_INITIATED_DECLINE_RESOURCE_BUSY
const isc::log::MessageID DHCP4_CLASS_UNCONFIGURED
const isc::log::MessageID DHCP4_DHCP4O6_SUBNET_SELECTED
boost::shared_ptr< Option > OptionPtr
Definition option.h:37
const isc::log::MessageID DHCP4_HOOK_LEASE4_OFFER_PARKING_LOT_FULL
const int DBG_DHCP4_START
Debug level used to log information during server startup.
Definition dhcp4_log.h:24
const isc::log::MessageID DHCP4_HOOK_LEASES4_COMMITTED_PARK
const isc::log::MessageID DHCP4_ADDITIONAL_CLASS_UNDEFINED
const isc::log::MessageID DHCP4_ADDITIONAL_CLASS_EVAL_RESULT
const isc::log::MessageID DHCP4_DHCP4O6_HOOK_SUBNET4_SELECT_SKIP
const isc::log::MessageID DHCP4_PACKET_DROP_0014
std::list< ConstCfgOptionPtr > CfgOptionList
Const pointer list.
Definition cfg_option.h:898
const isc::log::MessageID DHCP4_DISCOVER
boost::shared_ptr< const CfgOption > ConstCfgOptionPtr
Const pointer.
Definition cfg_option.h:895
const isc::log::MessageID DHCP4_PACKET_NAK_0004
const isc::log::MessageID DHCP4_CLIENT_FQDN_DATA
const isc::log::MessageID DHCP4_PACKET_DROP_0002
isc::log::Logger hooks_logger("hooks")
Hooks Logger.
Definition hooks_log.h:37
boost::shared_ptr< CalloutHandle > CalloutHandlePtr
A shared pointer to a CalloutHandle object.
boost::shared_ptr< ParkingLot > ParkingLotPtr
Type of the pointer to the parking lot.
const int DBGLVL_TRACE_BASIC
Trace basic operations.
const int DBGLVL_PKT_HANDLING
This debug level is reserved for logging the details of packet handling, such as dropping the packet ...
const char * MessageID
std::unique_ptr< StringSanitizer > StringSanitizerPtr
Type representing the pointer to the StringSanitizer.
Definition str.h:263
void decodeFormattedHexString(const string &hex_string, vector< uint8_t > &binary)
Converts a formatted string of hexadecimal digits into a vector.
Definition str.cc:212
string trim(const string &input)
Trim leading and trailing spaces.
Definition str.cc:32
Defines the logger used by the top-level component of kea-lfc.
This file defines abstract classes for exchanging NameChangeRequests.
This file provides the classes needed to embody, compose, and decompose DNS update requests that are ...
Standard implementation of read-write mutexes with writer preference using C++11 mutex and condition ...
#define DHCP4_OPTION_SPACE
global std option spaces
Context information for the DHCPv4 lease allocation.
static const uint32_t INFINITY_LFT
Infinity (means static, i.e. never expire)
Definition lease.h:34
static std::string lifetimeToText(uint32_t lifetime)
Print lifetime.
Definition lease.cc:34
static const uint32_t STATE_DEFAULT
A lease in the default state.
Definition lease.h:69
static const uint32_t STATE_RELEASED
Released lease held in the database for lease affinity.
Definition lease.h:78
@ TYPE_V4
IPv4 lease.
Definition lease.h:50
Subnet selector used to specify parameters used to select a subnet.
asiolink::IOAddress local_address_
Address on which the message was received.
bool dhcp4o6_
Specifies if the packet is DHCP4o6.
asiolink::IOAddress option_select_
RAI link select or subnet select option.
std::string iface_name_
Name of the interface on which the message was received.
asiolink::IOAddress ciaddr_
ciaddr from the client's message.
ClientClasses client_classes_
Classes that the client belongs to.
asiolink::IOAddress remote_address_
Source address of the message.
OptionPtr interface_id_
Interface id option.
asiolink::IOAddress first_relay_linkaddr_
First relay link address.
asiolink::IOAddress giaddr_
giaddr from the client's message.
bool add(const WorkItemPtr &item)
add a work item to the thread pool
Definition thread_pool.h:97