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