2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "dnsparser.hh"
28 #include <boost/program_options.hpp>
29 #include <arpa/inet.h>
30 #include <sys/types.h>
36 #include "threadname.hh"
39 #include <condition_variable>
43 #include "ixfrutils.hh"
44 #include "axfr-retriever.hh"
45 #include "dns_random.hh"
51 #include "communicator.hh"
52 #include "query-local-address.hh"
54 #include "ixfrdist-stats.hh"
55 #include "ixfrdist-web.hh"
56 #pragma GCC diagnostic push
57 #pragma GCC diagnostic ignored "-Wshadow"
58 #include <yaml-cpp/yaml.h>
59 #pragma GCC diagnostic pop
60 #include "auth-packetcache.hh"
61 #include "auth-querycache.hh"
62 #include "auth-zonecache.hh"
64 /* BEGIN Needed because of deeper dependencies */
65 #include "arguments.hh"
68 // NOLINTNEXTLINE(readability-identifier-length)
70 // NOLINTNEXTLINE(readability-identifier-length)
72 AuthZoneCache g_zoneCache
;
76 static ArgvMap theArg
;
79 /* END Needed because of deeper dependencies */
81 // Allows reading/writing ComboAddresses and DNSNames in YAML-cpp
84 struct convert
<ComboAddress
> {
85 static Node
encode(const ComboAddress
& rhs
) {
86 return Node(rhs
.toStringWithPort());
88 static bool decode(const Node
& node
, ComboAddress
& rhs
) {
89 if (!node
.IsScalar()) {
93 rhs
= ComboAddress(node
.as
<string
>(), 53);
95 } catch(const runtime_error
&e
) {
97 } catch (const PDNSException
&e
) {
104 struct convert
<DNSName
> {
105 static Node
encode(const DNSName
& rhs
) {
106 return Node(rhs
.toStringRootDot());
108 static bool decode(const Node
& node
, DNSName
& rhs
) {
109 if (!node
.IsScalar()) {
113 rhs
= DNSName(node
.as
<string
>());
115 } catch(const runtime_error
&e
) {
117 } catch (const PDNSException
&e
) {
124 struct convert
<Netmask
> {
125 static Node
encode(const Netmask
& rhs
) {
126 return Node(rhs
.toString());
128 static bool decode(const Node
& node
, Netmask
& rhs
) {
129 if (!node
.IsScalar()) {
133 rhs
= Netmask(node
.as
<string
>());
135 } catch(const runtime_error
&e
) {
137 } catch (const PDNSException
&e
) {
145 shared_ptr
<const SOARecordContent
> oldSOA
;
146 shared_ptr
<const SOARecordContent
> newSOA
;
147 vector
<DNSRecord
> removals
;
148 vector
<DNSRecord
> additions
;
154 shared_ptr
<const SOARecordContent
> soa
; // The SOA of the latest AXFR
155 records_t latestAXFR
; // The most recent AXFR
156 vector
<std::shared_ptr
<ixfrdiff_t
>> ixfrDiffs
;
160 // Why a struct? This way we can add more options to a domain in the future
161 struct ixfrdistdomain_t
{
162 set
<ComboAddress
> primaries
; // A set so we can do multiple primary addresses in the future
163 std::set
<ComboAddress
> notify
; // Set of addresses to forward NOTIFY to
164 uint32_t maxSOARefresh
{0}; // Cap SOA refresh value to the given value in seconds
167 // This contains the configuration for each domain
168 static map
<DNSName
, ixfrdistdomain_t
> g_domainConfigs
;
170 // Map domains and their data
171 static LockGuarded
<std::map
<DNSName
, std::shared_ptr
<ixfrinfo_t
>>> g_soas
;
173 // Queue of received NOTIFYs, already verified against their primary IPs
174 // Lazily implemented as a set
175 static LockGuarded
<std::set
<DNSName
>> g_notifiesReceived
;
177 // Queue of outgoing NOTIFY
178 static LockGuarded
<NotificationQueue
> g_notificationQueue
;
180 // Condition variable for TCP handling
181 static std::condition_variable g_tcpHandlerCV
;
182 static std::queue
<pair
<int, ComboAddress
>> g_tcpRequestFDs
;
183 static std::mutex g_tcpRequestFDsMutex
;
185 namespace po
= boost::program_options
;
187 static bool g_exiting
= false;
189 static NetmaskGroup g_acl
; // networks that can QUERY us
190 static NetmaskGroup g_notifySources
; // networks (well, IPs) that can NOTIFY us
191 static bool g_compress
= false;
193 static ixfrdistStats g_stats
;
195 // g_stats is static, so local to this file. But the webserver needs this info
196 string
doGetStats() {
197 return g_stats
.getStats();
200 static void handleSignal(int signum
) {
201 g_log
<<Logger::Notice
<<"Got "<<strsignal(signum
)<<" signal";
203 g_log
<<Logger::Notice
<<", this is the second time we were asked to stop, forcefully exiting"<<endl
;
206 g_log
<<Logger::Notice
<<", stopping, this may take a few second due to in-progress transfers and cleanup. Send this signal again to forcefully stop"<<endl
;
210 static void usage(po::options_description
&desc
) {
211 cerr
<< "Usage: ixfrdist [OPTION]..."<<endl
;
212 cerr
<< desc
<< "\n";
215 // The compiler does not like using rfc1982LessThan in std::sort directly
216 static bool sortSOA(uint32_t i
, uint32_t j
) {
217 return rfc1982LessThan(i
, j
);
220 static void cleanUpDomain(const DNSName
& domain
, const uint16_t& keep
, const string
& workdir
) {
221 string dir
= workdir
+ "/" + domain
.toString();
222 vector
<uint32_t> zoneVersions
;
223 auto directoryError
= pdns::visit_directory(dir
, [&zoneVersions
]([[maybe_unused
]] ino_t inodeNumber
, const std::string_view
& name
) {
224 if (name
!= "." && name
!= "..") {
226 auto version
= pdns::checked_stoi
<uint32_t>(std::string(name
));
227 zoneVersions
.push_back(version
);
235 if (directoryError
) {
239 g_log
<<Logger::Info
<<"Found "<<zoneVersions
.size()<<" versions of "<<domain
<<", asked to keep "<<keep
<<", ";
240 if (zoneVersions
.size() <= keep
) {
241 g_log
<<Logger::Info
<<"not cleaning up"<<endl
;
244 g_log
<<Logger::Info
<<"cleaning up the oldest "<<zoneVersions
.size() - keep
<<endl
;
247 std::sort(zoneVersions
.begin(), zoneVersions
.end(), sortSOA
);
249 // And delete all the old ones
251 // Lock to ensure no one reads this.
252 auto lock
= g_soas
.lock();
253 for (auto iter
= zoneVersions
.cbegin(); iter
!= zoneVersions
.cend() - keep
; ++iter
) {
254 string fname
= dir
+ "/" + std::to_string(*iter
);
255 g_log
<<Logger::Debug
<<"Removing "<<fname
<<endl
;
256 unlink(fname
.c_str());
261 static void getSOAFromRecords(const records_t
& records
, shared_ptr
<const SOARecordContent
>& soa
, uint32_t& soaTTL
) {
262 for (const auto& dnsrecord
: records
) {
263 if (dnsrecord
.d_type
== QType::SOA
) {
264 soa
= getRR
<SOARecordContent
>(dnsrecord
);
265 if (soa
== nullptr) {
266 throw PDNSException("Unable to determine SOARecordContent from old records");
268 soaTTL
= dnsrecord
.d_ttl
;
272 throw PDNSException("No SOA in supplied records");
275 static void makeIXFRDiff(const records_t
& from
, const records_t
& to
, std::shared_ptr
<ixfrdiff_t
>& diff
, const shared_ptr
<const SOARecordContent
>& fromSOA
= nullptr, uint32_t fromSOATTL
=0, const shared_ptr
<const SOARecordContent
>& toSOA
= nullptr, uint32_t toSOATTL
= 0) {
276 set_difference(from
.cbegin(), from
.cend(), to
.cbegin(), to
.cend(), back_inserter(diff
->removals
), from
.value_comp());
277 set_difference(to
.cbegin(), to
.cend(), from
.cbegin(), from
.cend(), back_inserter(diff
->additions
), from
.value_comp());
278 diff
->oldSOA
= fromSOA
;
279 diff
->oldSOATTL
= fromSOATTL
;
280 if (fromSOA
== nullptr) {
281 getSOAFromRecords(from
, diff
->oldSOA
, diff
->oldSOATTL
);
283 diff
->newSOA
= toSOA
;
284 diff
->newSOATTL
= toSOATTL
;
285 if (toSOA
== nullptr) {
286 getSOAFromRecords(to
, diff
->newSOA
, diff
->newSOATTL
);
290 /* you can _never_ alter the content of the resulting shared pointer */
291 static std::shared_ptr
<ixfrinfo_t
> getCurrentZoneInfo(const DNSName
& domain
)
293 return (*g_soas
.lock())[domain
];
296 static void updateCurrentZoneInfo(const DNSName
& domain
, std::shared_ptr
<ixfrinfo_t
>& newInfo
)
298 auto soas
= g_soas
.lock();
299 (*soas
)[domain
] = newInfo
;
300 g_stats
.setSOASerial(domain
, newInfo
->soa
->d_st
.serial
);
301 // FIXME: also report zone size?
304 static void sendNotification(int sock
, const DNSName
& domain
, const ComboAddress
& remote
, uint16_t notificationId
)
306 std::vector
<std::string
> meta
;
307 std::vector
<uint8_t> packet
;
308 DNSPacketWriter
packetWriter(packet
, domain
, QType::SOA
, 1, Opcode::Notify
);
309 packetWriter
.getHeader()->id
= notificationId
;
310 packetWriter
.getHeader()->aa
= true;
312 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
313 if (sendto(sock
, packet
.data(), packet
.size(), 0, reinterpret_cast<const struct sockaddr
*>(&remote
), remote
.getSocklen()) < 0) {
314 throw std::runtime_error("Unable to send notify to " + remote
.toStringWithPort() + ": " + stringerror());
318 static void communicatorReceiveNotificationAnswers(const int sock4
, const int sock6
)
320 std::set
<int> fds
= {sock4
};
325 std::array
<char, 1500> buffer
{};
328 // receive incoming notification answers on the nonblocking sockets and take them off the list
329 while (waitForMultiData(fds
, 0, 0, &sock
) > 0) {
330 Utility::socklen_t fromlen
= sizeof(from
);
331 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
332 const auto size
= recvfrom(sock
, buffer
.data(), buffer
.size(), 0, reinterpret_cast<struct sockaddr
*>(&from
), &fromlen
);
336 DNSPacket
packet(true);
337 packet
.setRemote(&from
);
339 if (packet
.parse(buffer
.data(), (size_t)size
) < 0) {
340 g_log
<< Logger::Warning
<< "Unable to parse SOA notification answer from " << packet
.getRemote() << endl
;
344 if (packet
.d
.rcode
!= 0) {
345 g_log
<< Logger::Warning
<< "Received unsuccessful notification report for '" << packet
.qdomain
<< "' from " << from
.toStringWithPort() << ", error: " << RCode::to_s(packet
.d
.rcode
) << endl
;
348 if (g_notificationQueue
.lock()->removeIf(from
, packet
.d
.id
, packet
.qdomain
)) {
349 g_log
<< Logger::Notice
<< "Removed from notification list: '" << packet
.qdomain
<< "' to " << from
.toStringWithPort() << " " << (packet
.d
.rcode
!= 0 ? RCode::to_s(packet
.d
.rcode
) : "(was acknowledged)") << endl
;
352 g_log
<< Logger::Warning
<< "Received spurious notify answer for '" << packet
.qdomain
<< "' from " << from
.toStringWithPort() << endl
;
357 static void communicatorSendNotifications(const int sock4
, const int sock6
)
360 string destinationIp
;
361 uint16_t notificationId
= 0;
364 while (g_notificationQueue
.lock()->getOne(domain
, destinationIp
, ¬ificationId
, purged
)) {
366 ComboAddress
remote(destinationIp
, 53); // default to 53
367 if (remote
.sin4
.sin_family
== AF_INET
) {
368 sendNotification(sock4
, domain
, remote
, notificationId
);
369 } else if (sock6
> 0) {
370 sendNotification(sock6
, domain
, remote
, notificationId
);
372 g_log
<< Logger::Warning
<< "Unable to notify " << destinationIp
<< " for " << domain
<< " as v6 support is not enabled" << std::endl
;
375 g_log
<< Logger::Warning
<< "Notification for " << domain
<< " to " << destinationIp
<< " failed after retries" << std::endl
;
380 static void communicatorThread()
382 setThreadName("ixfrdist/communicator");
383 auto sock4
= makeQuerySocket(pdns::getQueryLocalAddress(AF_INET
, 0), true);
384 auto sock6
= makeQuerySocket(pdns::getQueryLocalAddress(AF_INET6
, 0), true);
387 throw std::runtime_error("Unable to create local query socket");
389 // sock6 can be negative if there is no v6 support, but this is handled later while sending notifications
393 g_log
<< Logger::Notice
<< "Communicator thread stopped" << std::endl
;
396 communicatorReceiveNotificationAnswers(sock4
, sock6
);
397 communicatorSendNotifications(sock4
, sock6
);
398 std::this_thread::sleep_for(std::chrono::seconds(1));
408 static void updateThread(const string
& workdir
, const uint16_t& keep
, const uint16_t& axfrTimeout
, const uint16_t& soaRetry
, const uint32_t axfrMaxRecords
) { // NOLINT(readability-function-cognitive-complexity) 13400 https://github.com/PowerDNS/pdns/issues/13400 Habbie: ixfrdist: reduce complexity
409 setThreadName("ixfrdist/update");
410 std::map
<DNSName
, time_t> lastCheck
;
412 // Initialize the serials we have
413 for (const auto &domainConfig
: g_domainConfigs
) {
414 DNSName domain
= domainConfig
.first
;
415 lastCheck
[domain
] = 0;
416 string dir
= workdir
+ "/" + domain
.toString();
418 g_log
<<Logger::Info
<<"Trying to initially load domain "<<domain
<<" from disk"<<endl
;
419 auto serial
= getSerialFromDir(dir
);
420 shared_ptr
<const SOARecordContent
> soa
;
423 string fname
= workdir
+ "/" + domain
.toString() + "/" + std::to_string(serial
);
424 loadSOAFromDisk(domain
, fname
, soa
, soaTTL
);
426 if (soa
== nullptr) {
427 g_log
<<Logger::Error
<<"Could not load SOA from disk for zone "<<domain
<<", removing file '"<<fname
<<"'"<<endl
;
428 unlink(fname
.c_str());
430 loadZoneFromDisk(records
, fname
, domain
);
431 auto zoneInfo
= std::make_shared
<ixfrinfo_t
>();
432 zoneInfo
->latestAXFR
= std::move(records
);
434 zoneInfo
->soaTTL
= soaTTL
;
435 updateCurrentZoneInfo(domain
, zoneInfo
);
437 if (soa
!= nullptr) {
438 g_log
<<Logger::Notice
<<"Loaded zone "<<domain
<<" with serial "<<soa
->d_st
.serial
<<endl
;
440 cleanUpDomain(domain
, keep
, workdir
);
442 } catch (runtime_error
&e
) {
443 // Most likely, the directory does not exist.
444 g_log
<<Logger::Info
<<e
.what()<<", attempting to create"<<endl
;
445 // Attempt to create it, if _that_ fails, there is no hope
446 if (mkdir(dir
.c_str(), 0777) == -1 && errno
!= EEXIST
) {
447 g_log
<<Logger::Error
<<"Could not create '"<<dir
<<"': "<<stringerror()<<endl
;
453 g_log
<<Logger::Notice
<<"Update Thread started"<<endl
;
457 g_log
<<Logger::Notice
<<"UpdateThread stopped"<<endl
;
460 time_t now
= time(nullptr);
461 for (const auto &domainConfig
: g_domainConfigs
) {
467 DNSName domain
= domainConfig
.first
;
468 shared_ptr
<const SOARecordContent
> current_soa
;
469 const auto& zoneInfo
= getCurrentZoneInfo(domain
);
470 if (zoneInfo
!= nullptr) {
471 current_soa
= zoneInfo
->soa
;
474 auto& zoneLastCheck
= lastCheck
[domain
];
475 uint32_t refresh
= soaRetry
; // default if we don't get an update at all
476 if (current_soa
!= nullptr) {
477 // Check every `refresh` seconds as advertised in the SOA record
478 refresh
= current_soa
->d_st
.refresh
;
479 if (domainConfig
.second
.maxSOARefresh
> 0) {
480 // Cap refresh value to the configured one if any
481 refresh
= std::min(refresh
, domainConfig
.second
.maxSOARefresh
);
486 if (now
- zoneLastCheck
< refresh
&& g_notifiesReceived
.lock()->erase(domain
) == 0) {
490 // TODO Keep track of 'down' primaries
491 set
<ComboAddress
>::const_iterator
it(domainConfig
.second
.primaries
.begin());
492 std::advance(it
, dns_random(domainConfig
.second
.primaries
.size()));
493 ComboAddress primary
= *it
;
495 string dir
= workdir
+ "/" + domain
.toString();
496 g_log
<< Logger::Info
<< "Attempting to retrieve SOA Serial update for '" << domain
<< "' from '" << primary
.toStringWithPort() << "'" << endl
;
497 shared_ptr
<const SOARecordContent
> sr
;
500 g_stats
.incrementSOAChecks(domain
);
501 auto newSerial
= getSerialFromPrimary(primary
, domain
, sr
); // TODO TSIG
502 if(current_soa
!= nullptr) {
503 g_log
<< Logger::Info
<< "Got SOA Serial for " << domain
<< " from " << primary
.toStringWithPort() << ": " << newSerial
<< ", had Serial: " << current_soa
->d_st
.serial
;
504 if (newSerial
== current_soa
->d_st
.serial
) {
505 g_log
<<Logger::Info
<<", not updating."<<endl
;
508 g_log
<<Logger::Info
<<", will update."<<endl
;
510 } catch (runtime_error
&e
) {
511 g_log
<< Logger::Warning
<< "Unable to get SOA serial update for '" << domain
<< "' from primary " << primary
.toStringWithPort() << ": " << e
.what() << endl
;
512 g_stats
.incrementSOAChecksFailed(domain
);
515 // Now get the full zone!
516 g_log
<<Logger::Info
<<"Attempting to receive full zonedata for '"<<domain
<<"'"<<endl
;
517 ComboAddress local
= primary
.isIPv4() ? ComboAddress("0.0.0.0") : ComboAddress("::");
521 shared_ptr
<const SOARecordContent
> soa
;
525 AXFRRetriever
axfr(primary
, domain
, tt
, &local
);
528 vector
<DNSRecord
> chunk
;
529 time_t t_start
= time(nullptr);
530 time_t axfr_now
= time(nullptr);
531 while(axfr
.getChunk(nop
, &chunk
, (axfr_now
- t_start
+ axfrTimeout
))) {
532 for(auto& dr
: chunk
) {
533 if(dr
.d_type
== QType::TSIG
)
535 if(!dr
.d_name
.isPartOf(domain
)) {
536 throw PDNSException("Out-of-zone data received during AXFR of "+domain
.toLogString());
538 dr
.d_name
.makeUsRelative(domain
);
541 if (dr
.d_type
== QType::SOA
) {
542 soa
= getRR
<SOARecordContent
>(dr
);
546 if (axfrMaxRecords
!= 0 && nrecords
> axfrMaxRecords
) {
547 throw PDNSException("Received more than " + std::to_string(axfrMaxRecords
) + " records in AXFR, aborted");
549 axfr_now
= time(nullptr);
550 if (axfr_now
- t_start
> axfrTimeout
) {
551 g_stats
.incrementAXFRFailures(domain
);
552 throw PDNSException("Total AXFR time exceeded!");
555 if (soa
== nullptr) {
556 g_stats
.incrementAXFRFailures(domain
);
557 g_log
<<Logger::Warning
<<"No SOA was found in the AXFR of "<<domain
<<endl
;
560 g_log
<<Logger::Notice
<<"Retrieved all zone data for "<<domain
<<". Received "<<nrecords
<<" records."<<endl
;
561 } catch (PDNSException
&e
) {
562 g_stats
.incrementAXFRFailures(domain
);
563 g_log
<<Logger::Warning
<<"Could not retrieve AXFR for '"<<domain
<<"': "<<e
.reason
<<endl
;
565 } catch (runtime_error
&e
) {
566 g_stats
.incrementAXFRFailures(domain
);
567 g_log
<<Logger::Warning
<<"Could not retrieve AXFR for zone '"<<domain
<<"': "<<e
.what()<<endl
;
573 writeZoneToDisk(records
, domain
, dir
);
574 g_log
<<Logger::Notice
<<"Wrote zonedata for "<<domain
<<" with serial "<<soa
->d_st
.serial
<<" to "<<dir
<<endl
;
576 const auto oldZoneInfo
= getCurrentZoneInfo(domain
);
577 auto ixfrInfo
= std::make_shared
<ixfrinfo_t
>();
579 if (oldZoneInfo
&& !oldZoneInfo
->latestAXFR
.empty()) {
580 auto diff
= std::make_shared
<ixfrdiff_t
>();
581 ixfrInfo
->ixfrDiffs
= oldZoneInfo
->ixfrDiffs
;
582 g_log
<<Logger::Debug
<<"Calculating diff for "<<domain
<<endl
;
583 makeIXFRDiff(oldZoneInfo
->latestAXFR
, records
, diff
, oldZoneInfo
->soa
, oldZoneInfo
->soaTTL
, soa
, soaTTL
);
584 g_log
<<Logger::Debug
<<"Calculated diff for "<<domain
<<", we had "<<diff
->removals
.size()<<" removals and "<<diff
->additions
.size()<<" additions"<<endl
;
585 ixfrInfo
->ixfrDiffs
.push_back(std::move(diff
));
588 // Clean up the diffs
589 while (ixfrInfo
->ixfrDiffs
.size() > keep
) {
590 ixfrInfo
->ixfrDiffs
.erase(ixfrInfo
->ixfrDiffs
.begin());
593 g_log
<<Logger::Debug
<<"Zone "<<domain
<<" previously contained "<<(oldZoneInfo
? oldZoneInfo
->latestAXFR
.size() : 0)<<" entries, "<<records
.size()<<" now"<<endl
;
594 ixfrInfo
->latestAXFR
= std::move(records
);
595 ixfrInfo
->soa
= std::move(soa
);
596 ixfrInfo
->soaTTL
= soaTTL
;
597 updateCurrentZoneInfo(domain
, ixfrInfo
);
598 } catch (PDNSException
&e
) {
599 g_stats
.incrementAXFRFailures(domain
);
600 g_log
<<Logger::Warning
<<"Could not save zone '"<<domain
<<"' to disk: "<<e
.reason
<<endl
;
601 } catch (runtime_error
&e
) {
602 g_stats
.incrementAXFRFailures(domain
);
603 g_log
<<Logger::Warning
<<"Could not save zone '"<<domain
<<"' to disk: "<<e
.what()<<endl
;
606 // Now clean up the directory
607 cleanUpDomain(domain
, keep
, workdir
);
608 } /* for (const auto &domain : domains) */
613 enum class ResponseType
{
621 static ResponseType
maybeHandleNotify(const MOADNSParser
& mdp
, const ComboAddress
& saddr
, const string
& logPrefix
="") {
622 if (mdp
.d_header
.opcode
!= Opcode::Notify
) { // NOLINT(bugprone-narrowing-conversions, cppcoreguidelines-narrowing-conversions) opcode is 4 bits, this is not a dangerous conversion
623 return ResponseType::Unknown
;
626 g_log
<<Logger::Info
<<logPrefix
<<"NOTIFY for "<<mdp
.d_qname
<<"|"<<QType(mdp
.d_qtype
).toString()<<" "<< Opcode::to_s(mdp
.d_header
.opcode
) <<" from "<<saddr
.toStringWithPort()<<endl
;
628 auto found
= g_domainConfigs
.find(mdp
.d_qname
);
629 if (found
== g_domainConfigs
.end()) {
630 g_log
<<Logger::Info
<<("Domain name '" + mdp
.d_qname
.toLogString() + "' is not configured for notification")<<endl
;
631 return ResponseType::RefusedQuery
;
634 auto primaries
= found
->second
.primaries
;
636 bool primaryFound
= false;
638 for (const auto& primary
: primaries
) {
639 if (ComboAddress::addressOnlyEqual()(saddr
, primary
)) {
646 g_notifiesReceived
.lock()->insert(mdp
.d_qname
);
648 if (!found
->second
.notify
.empty()) {
649 for (const auto& address
: found
->second
.notify
) {
650 g_log
<< Logger::Debug
<< logPrefix
<< "Queuing notification for " << mdp
.d_qname
<< " to " << address
.toStringWithPort() << std::endl
;
651 g_notificationQueue
.lock()->add(mdp
.d_qname
, address
);
654 return ResponseType::EmptyNoError
;
657 return ResponseType::RefusedQuery
;
660 static ResponseType
checkQuery(const MOADNSParser
& mdp
, const ComboAddress
& saddr
, const bool udp
= true, const string
& logPrefix
="") {
661 vector
<string
> info_msg
;
663 auto ret
= ResponseType::ValidQuery
;
665 g_log
<<Logger::Debug
<<logPrefix
<<"Had "<<mdp
.d_qname
<<"|"<<QType(mdp
.d_qtype
).toString()<<" query from "<<saddr
.toStringWithPort()<<endl
;
667 if (mdp
.d_header
.opcode
!= Opcode::Query
) { // NOLINT(bugprone-narrowing-conversions, cppcoreguidelines-narrowing-conversions) opcode is 4 bits, this is not a dangerous conversion
668 info_msg
.push_back("Opcode is unsupported (" + Opcode::to_s(mdp
.d_header
.opcode
) + "), expected QUERY"); // note that we also emit this for a NOTIFY from a wrong source
669 ret
= ResponseType::RefusedOpcode
;
672 if (udp
&& mdp
.d_qtype
!= QType::SOA
&& mdp
.d_qtype
!= QType::IXFR
) {
673 info_msg
.push_back("QType is unsupported (" + QType(mdp
.d_qtype
).toString() + " is not in {SOA,IXFR})");
674 ret
= ResponseType::RefusedQuery
;
677 if (!udp
&& mdp
.d_qtype
!= QType::SOA
&& mdp
.d_qtype
!= QType::IXFR
&& mdp
.d_qtype
!= QType::AXFR
) {
678 info_msg
.push_back("QType is unsupported (" + QType(mdp
.d_qtype
).toString() + " is not in {SOA,IXFR,AXFR})");
679 ret
= ResponseType::RefusedQuery
;
683 if (g_domainConfigs
.find(mdp
.d_qname
) == g_domainConfigs
.end()) {
684 info_msg
.push_back("Domain name '" + mdp
.d_qname
.toLogString() + "' is not configured for distribution");
685 ret
= ResponseType::RefusedQuery
;
688 const auto zoneInfo
= getCurrentZoneInfo(mdp
.d_qname
);
689 if (zoneInfo
== nullptr) {
690 info_msg
.emplace_back("Domain has not been transferred yet");
691 ret
= ResponseType::RefusedQuery
;
697 if (!info_msg
.empty()) { // which means ret is not SOA
698 g_log
<<Logger::Warning
<<logPrefix
<<"Refusing "<<mdp
.d_qname
<<"|"<<QType(mdp
.d_qtype
).toString()<<" "<< Opcode::to_s(mdp
.d_header
.opcode
) <<" from "<<saddr
.toStringWithPort();
699 g_log
<<Logger::Warning
<<": ";
701 for (const auto& s
: info_msg
) {
703 g_log
<<Logger::Warning
<<", ";
706 g_log
<<Logger::Warning
<<s
;
708 g_log
<<Logger::Warning
<<endl
;
709 // fall through to return below
716 * Returns a vector<uint8_t> that represents the full empty NOERROR response.
717 * QNAME is read from mdp.
719 static bool makeEmptyNoErrorPacket(const MOADNSParser
& mdp
, vector
<uint8_t>& packet
) {
720 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
721 pw
.getHeader()->opcode
= mdp
.d_header
.opcode
;
722 pw
.getHeader()->id
= mdp
.d_header
.id
;
723 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
724 pw
.getHeader()->qr
= 1;
725 pw
.getHeader()->aa
= 1;
733 * Returns a vector<uint8_t> that represents the full positive response to a SOA
734 * query. QNAME is read from mdp.
736 static bool makeSOAPacket(const MOADNSParser
& mdp
, vector
<uint8_t>& packet
) {
738 auto zoneInfo
= getCurrentZoneInfo(mdp
.d_qname
);
739 if (zoneInfo
== nullptr) {
743 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
744 pw
.getHeader()->opcode
= mdp
.d_header
.opcode
;
745 pw
.getHeader()->id
= mdp
.d_header
.id
;
746 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
747 pw
.getHeader()->qr
= 1;
748 pw
.getHeader()->aa
= 1;
750 pw
.startRecord(mdp
.d_qname
, QType::SOA
, zoneInfo
->soaTTL
);
751 zoneInfo
->soa
->toPacket(pw
);
758 * Returns a vector<uint8_t> that represents the full REFUSED response to a
759 * query. QNAME and type are read from mdp.
761 static bool makeRefusedPacket(const MOADNSParser
& mdp
, vector
<uint8_t>& packet
) {
762 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
763 pw
.getHeader()->opcode
= mdp
.d_header
.opcode
;
764 pw
.getHeader()->id
= mdp
.d_header
.id
;
765 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
766 pw
.getHeader()->qr
= 1;
767 pw
.getHeader()->rcode
= RCode::Refused
;
773 * Returns a vector<uint8_t> that represents the full NOTIMP response to a
774 * query. QNAME and type are read from mdp.
776 static bool makeNotimpPacket(const MOADNSParser
& mdp
, vector
<uint8_t>& packet
) {
777 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
778 pw
.getHeader()->opcode
= mdp
.d_header
.opcode
;
779 pw
.getHeader()->id
= mdp
.d_header
.id
;
780 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
781 pw
.getHeader()->qr
= 1;
782 pw
.getHeader()->rcode
= RCode::NotImp
;
787 static vector
<uint8_t> getSOAPacket(const MOADNSParser
& mdp
, const shared_ptr
<const SOARecordContent
>& soa
, uint32_t soaTTL
) {
788 vector
<uint8_t> packet
;
789 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
790 pw
.getHeader()->id
= mdp
.d_header
.id
;
791 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
792 pw
.getHeader()->qr
= 1;
795 pw
.startRecord(mdp
.d_qname
, QType::SOA
, soaTTL
);
801 static bool sendPacketOverTCP(int fd
, const std::vector
<uint8_t>& packet
)
804 sendBuf
[0]=packet
.size()/256;
805 sendBuf
[1]=packet
.size()%256;
807 writen2(fd
, sendBuf
, 2);
808 writen2(fd
, &packet
[0], packet
.size());
812 static bool addRecordToWriter(DNSPacketWriter
& pw
, const DNSName
& zoneName
, const DNSRecord
& record
, bool compress
)
814 pw
.startRecord(record
.d_name
+ zoneName
, record
.d_type
, record
.d_ttl
, QClass::IN
, DNSResourceRecord::ANSWER
, compress
);
815 record
.getContent()->toPacket(pw
);
816 if (pw
.size() > 16384) {
823 template <typename T
> static bool sendRecordsOverTCP(int fd
, const MOADNSParser
& mdp
, const T
& records
)
825 vector
<uint8_t> packet
;
827 for (auto it
= records
.cbegin(); it
!= records
.cend();) {
828 bool recordsAdded
= false;
830 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
831 pw
.getHeader()->id
= mdp
.d_header
.id
;
832 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
833 pw
.getHeader()->qr
= 1;
835 while (it
!= records
.cend()) {
836 if (it
->d_type
== QType::SOA
) {
841 if (addRecordToWriter(pw
, mdp
.d_qname
, *it
, g_compress
)) {
848 sendPacketOverTCP(fd
, packet
);
850 if (it
== records
.cbegin()) {
851 /* something is wrong */
859 if (it
== records
.cend() && recordsAdded
) {
861 sendPacketOverTCP(fd
, packet
);
869 static bool handleAXFR(int fd
, const MOADNSParser
& mdp
) {
870 /* we get a shared pointer of the zone info that we can't modify, ever.
871 A newer one may arise in the meantime, but this one will stay valid
875 g_stats
.incrementAXFRinQueries(mdp
.d_qname
);
877 auto zoneInfo
= getCurrentZoneInfo(mdp
.d_qname
);
878 if (zoneInfo
== nullptr) {
882 shared_ptr
<const SOARecordContent
> soa
= zoneInfo
->soa
;
883 uint32_t soaTTL
= zoneInfo
->soaTTL
;
884 const records_t
& records
= zoneInfo
->latestAXFR
;
887 const auto soaPacket
= getSOAPacket(mdp
, soa
, soaTTL
);
888 if (!sendPacketOverTCP(fd
, soaPacket
)) {
892 if (!sendRecordsOverTCP(fd
, mdp
, records
)) {
897 if (!sendPacketOverTCP(fd
, soaPacket
)) {
904 /* Produces an IXFR if one can be made according to the rules in RFC 1995 and
905 * creates a SOA or AXFR packet when required by the RFC.
907 static bool handleIXFR(int fd
, const MOADNSParser
& mdp
, const shared_ptr
<const SOARecordContent
>& clientSOA
) {
908 vector
<std::shared_ptr
<ixfrdiff_t
>> toSend
;
910 /* we get a shared pointer of the zone info that we can't modify, ever.
911 A newer one may arise in the meantime, but this one will stay valid
915 g_stats
.incrementIXFRinQueries(mdp
.d_qname
);
917 auto zoneInfo
= getCurrentZoneInfo(mdp
.d_qname
);
918 if (zoneInfo
== nullptr) {
922 uint32_t ourLatestSerial
= zoneInfo
->soa
->d_st
.serial
;
924 if (rfc1982LessThan(ourLatestSerial
, clientSOA
->d_st
.serial
) || ourLatestSerial
== clientSOA
->d_st
.serial
) {
925 /* RFC 1995 Section 2
926 * If an IXFR query with the same or newer version number than that of
927 * the server is received, it is replied to with a single SOA record of
928 * the server's current version.
930 vector
<uint8_t> packet
;
931 bool ret
= makeSOAPacket(mdp
, packet
);
933 sendPacketOverTCP(fd
, packet
);
938 // as we use push_back in the updater, we know the vector is sorted as oldest first
939 bool shouldAdd
= false;
940 // Get all relevant IXFR differences
941 for (const auto& diff
: zoneInfo
->ixfrDiffs
) {
943 toSend
.push_back(diff
);
946 if (diff
->oldSOA
->d_st
.serial
== clientSOA
->d_st
.serial
) {
947 toSend
.push_back(diff
);
948 // Add all consecutive diffs
953 if (toSend
.empty()) {
954 // FIXME: incrementIXFRFallbacks
955 g_log
<<Logger::Warning
<<"No IXFR available from serial "<<clientSOA
->d_st
.serial
<<" for zone "<<mdp
.d_qname
<<", attempting to send AXFR"<<endl
;
956 return handleAXFR(fd
, mdp
);
960 /* An IXFR packet's ANSWER section looks as follows:
961 * SOA latest_serial C
963 First set of changes:
964 * SOA requested_serial A
965 * ... removed records ...
966 * SOA intermediate_serial B
967 * ... added records ...
970 * SOA intermediate_serial B
971 * ... removed records ...
972 * SOA latest_serial C
973 * ... added records ...
975 * SOA latest_serial C
978 const auto latestSOAPacket
= getSOAPacket(mdp
, zoneInfo
->soa
, zoneInfo
->soaTTL
);
979 if (!sendPacketOverTCP(fd
, latestSOAPacket
)) {
983 for (const auto& diff
: toSend
) {
984 const auto newSOAPacket
= getSOAPacket(mdp
, diff
->newSOA
, diff
->newSOATTL
);
985 const auto oldSOAPacket
= getSOAPacket(mdp
, diff
->oldSOA
, diff
->oldSOATTL
);
987 if (!sendPacketOverTCP(fd
, oldSOAPacket
)) {
991 if (!sendRecordsOverTCP(fd
, mdp
, diff
->removals
)) {
995 if (!sendPacketOverTCP(fd
, newSOAPacket
)) {
999 if (!sendRecordsOverTCP(fd
, mdp
, diff
->additions
)) {
1004 if (!sendPacketOverTCP(fd
, latestSOAPacket
)) {
1011 static bool allowedByACL(const ComboAddress
& addr
, bool forNotify
= false) {
1013 return g_notifySources
.match(addr
);
1016 return g_acl
.match(addr
);
1019 static void handleUDPRequest(int fd
, boost::any
& /*unused*/)
1022 // TODO make the buffer-size configurable
1025 socklen_t fromlen
= sizeof(saddr
);
1026 int res
= recvfrom(fd
, buf
, sizeof(buf
), 0, (struct sockaddr
*) &saddr
, &fromlen
);
1029 g_log
<<Logger::Warning
<<"Got an empty message from "<<saddr
.toStringWithPort()<<endl
;
1034 auto savedErrno
= errno
;
1035 g_log
<<Logger::Warning
<<"Could not read message from "<<saddr
.toStringWithPort()<<": "<<strerror(savedErrno
)<<endl
;
1039 if (saddr
== ComboAddress("0.0.0.0", 0)) {
1040 g_log
<<Logger::Warning
<<"Could not determine source of message"<<endl
;
1044 if (!allowedByACL(saddr
, true) && !allowedByACL(saddr
, false)) {
1045 g_log
<<Logger::Warning
<<"UDP query from "<<saddr
.toString()<<" did not match any valid query or NOTIFY source, dropping"<<endl
;
1049 MOADNSParser
mdp(true, string(&buf
[0], static_cast<size_t>(res
)));
1050 vector
<uint8_t> packet
;
1052 ResponseType respt
= ResponseType::Unknown
;
1054 if (allowedByACL(saddr
, true)) {
1055 respt
= maybeHandleNotify(mdp
, saddr
);
1057 else if (!allowedByACL(saddr
)) {
1058 g_log
<<Logger::Warning
<<"UDP query from "<<saddr
.toString()<<" is not allowed, dropping"<<endl
;
1062 if (respt
== ResponseType::Unknown
) {
1063 // query was not handled yet (so not a valid NOTIFY)
1064 respt
= checkQuery(mdp
, saddr
);
1066 if (respt
== ResponseType::ValidQuery
) {
1067 /* RFC 1995 Section 2
1068 * Transport of a query may be by either UDP or TCP. If an IXFR query
1069 * is via UDP, the IXFR server may attempt to reply using UDP if the
1070 * entire response can be contained in a single DNS packet. If the UDP
1071 * reply does not fit, the query is responded to with a single SOA
1072 * record of the server's current version to inform the client that a
1073 * TCP query should be initiated.
1075 * Let's not complicate this with IXFR over UDP (and looking if we need to truncate etc).
1076 * Just send the current SOA and let the client try over TCP
1078 g_stats
.incrementSOAinQueries(mdp
.d_qname
); // FIXME: this also counts IXFR queries (but the response is the same as to a SOA query)
1079 makeSOAPacket(mdp
, packet
);
1080 } else if (respt
== ResponseType::EmptyNoError
) {
1081 makeEmptyNoErrorPacket(mdp
, packet
);
1082 } else if (respt
== ResponseType::RefusedQuery
) {
1083 g_stats
.incrementUnknownDomainInQueries(mdp
.d_qname
);
1084 makeRefusedPacket(mdp
, packet
);
1085 } else if (respt
== ResponseType::RefusedOpcode
) {
1086 g_stats
.incrementNotImplemented(mdp
.d_header
.opcode
);
1087 makeNotimpPacket(mdp
, packet
);
1090 if(sendto(fd
, &packet
[0], packet
.size(), 0, (struct sockaddr
*) &saddr
, fromlen
) < 0) {
1091 auto savedErrno
= errno
;
1092 g_log
<<Logger::Warning
<<"Could not send reply for "<<mdp
.d_qname
<<"|"<<QType(mdp
.d_qtype
).toString()<<" to "<<saddr
.toStringWithPort()<<": "<<strerror(savedErrno
)<<endl
;
1096 catch(std::exception
& e
) {
1101 static void handleTCPRequest(int fd
, boost::any
&) {
1106 cfd
= SAccept(fd
, saddr
);
1108 } catch(runtime_error
&e
) {
1109 g_log
<<Logger::Error
<<e
.what()<<endl
;
1113 if (saddr
== ComboAddress("0.0.0.0", 0)) {
1114 g_log
<<Logger::Warning
<<"Could not determine source of message"<<endl
;
1119 // we allow the connection if this is a legit client or a legit NOTIFY source
1120 // need to check per-operation later
1121 if (!allowedByACL(saddr
) && !allowedByACL(saddr
, true)) {
1122 g_log
<<Logger::Warning
<<"TCP query from "<<saddr
.toString()<<" is not allowed, dropping"<<endl
;
1128 std::lock_guard
<std::mutex
> lg(g_tcpRequestFDsMutex
);
1129 g_tcpRequestFDs
.push({cfd
, saddr
});
1131 g_tcpHandlerCV
.notify_one();
1134 /* Thread to handle TCP traffic
1136 static void tcpWorker(int tid
) {
1137 setThreadName("ixfrdist/tcpWor");
1138 string prefix
= "TCP Worker " + std::to_string(tid
) + ": ";
1141 g_log
<<Logger::Debug
<<prefix
<<"ready for a new request!"<<endl
;
1142 std::unique_lock
<std::mutex
> lk(g_tcpRequestFDsMutex
);
1143 g_tcpHandlerCV
.wait(lk
, []{return g_tcpRequestFDs
.size() || g_exiting
;});
1145 g_log
<<Logger::Debug
<<prefix
<<"Stopping thread"<<endl
;
1148 g_log
<<Logger::Debug
<<prefix
<<"Going to handle a query"<<endl
;
1149 auto request
= g_tcpRequestFDs
.front();
1150 g_tcpRequestFDs
.pop();
1153 int cfd
= request
.first
;
1154 ComboAddress saddr
= request
.second
;
1160 readn2(cfd
, &toRead
, sizeof(toRead
));
1161 toRead
= std::min(ntohs(toRead
), static_cast<uint16_t>(sizeof(buf
)));
1162 res
= readn2WithTimeout(cfd
, &buf
, toRead
, timeval
{2,0});
1163 g_log
<<Logger::Debug
<<prefix
<<"Had message of "<<std::to_string(toRead
)<<" bytes from "<<saddr
.toStringWithPort()<<endl
;
1164 } catch (runtime_error
&e
) {
1165 g_log
<<Logger::Warning
<<prefix
<<"Could not read message from "<<saddr
.toStringWithPort()<<": "<<e
.what()<<endl
;
1171 MOADNSParser
mdp(true, string(buf
, res
));
1173 ResponseType respt
= ResponseType::Unknown
;
1175 // this code is duplicated from the UDP path
1176 if (allowedByACL(saddr
, true)) {
1177 respt
= maybeHandleNotify(mdp
, saddr
);
1179 else if (!allowedByACL(saddr
)) {
1184 if (respt
== ResponseType::Unknown
) {
1185 respt
= checkQuery(mdp
, saddr
, false, prefix
);
1188 if (respt
!= ResponseType::ValidQuery
&& respt
!= ResponseType::EmptyNoError
) { // on TCP, we currently do not bother with sending useful errors
1193 vector
<uint8_t> packet
;
1195 if (respt
== ResponseType::EmptyNoError
) {
1196 bool ret
= makeEmptyNoErrorPacket(mdp
, packet
);
1201 sendPacketOverTCP(cfd
, packet
);
1203 else if (mdp
.d_qtype
== QType::SOA
) {
1204 bool ret
= makeSOAPacket(mdp
, packet
);
1209 sendPacketOverTCP(cfd
, packet
);
1211 else if (mdp
.d_qtype
== QType::AXFR
) {
1212 if (!handleAXFR(cfd
, mdp
)) {
1217 else if (mdp
.d_qtype
== QType::IXFR
) {
1218 /* RFC 1995 section 3:
1219 * The IXFR query packet format is the same as that of a normal DNS
1220 * query, but with the query type being IXFR and the authority section
1221 * containing the SOA record of client's version of the zone.
1223 shared_ptr
<const SOARecordContent
> clientSOA
;
1224 for (auto &answer
: mdp
.d_answers
) {
1225 // from dnsparser.hh:
1226 // typedef vector<pair<DNSRecord, uint16_t > > answers_t;
1227 if (answer
.first
.d_type
== QType::SOA
&& answer
.first
.d_place
== DNSResourceRecord::AUTHORITY
) {
1228 clientSOA
= getRR
<SOARecordContent
>(answer
.first
);
1229 if (clientSOA
!= nullptr) {
1233 } /* for (auto const &answer : mdp.d_answers) */
1235 if (clientSOA
== nullptr) {
1236 g_log
<<Logger::Warning
<<prefix
<<"IXFR request packet did not contain a SOA record in the AUTHORITY section"<<endl
;
1241 if (!handleIXFR(cfd
, mdp
, clientSOA
)) {
1245 } /* if (mdp.d_qtype == QType::IXFR) */
1248 } catch (const MOADNSException
&mde
) {
1249 g_log
<<Logger::Warning
<<prefix
<<"Could not parse DNS packet from "<<saddr
.toStringWithPort()<<": "<<mde
.what()<<endl
;
1250 } catch (runtime_error
&e
) {
1251 g_log
<<Logger::Warning
<<prefix
<<"Could not write reply to "<<saddr
.toStringWithPort()<<": "<<e
.what()<<endl
;
1262 /* Parses the configuration file in configpath into config, adding defaults for
1263 * missing parameters (if applicable), returning true if the config file was
1264 * good, false otherwise. Will log all issues with the config
1266 static bool parseAndCheckConfig(const string
& configpath
, YAML::Node
& config
) {
1267 g_log
<<Logger::Info
<<"Loading configuration file from "<<configpath
<<endl
;
1269 config
= YAML::LoadFile(configpath
);
1270 } catch (const runtime_error
&e
) {
1271 g_log
<<Logger::Error
<<"Unable to load configuration file '"<<configpath
<<"': "<<e
.what()<<endl
;
1277 if (config
["keep"]) {
1279 config
["keep"].as
<uint16_t>();
1280 } catch (const runtime_error
&e
) {
1281 g_log
<<Logger::Error
<<"Unable to read 'keep' value: "<<e
.what()<<endl
;
1285 config
["keep"] = 20;
1288 if (config
["axfr-max-records"]) {
1290 config
["axfr-max-records"].as
<uint32_t>();
1291 } catch (const runtime_error
&e
) {
1292 g_log
<<Logger::Error
<<"Unable to read 'axfr-max-records' value: "<<e
.what()<<endl
;
1295 config
["axfr-max-records"] = 0;
1298 if (config
["axfr-timeout"]) {
1300 config
["axfr-timeout"].as
<uint16_t>();
1301 } catch (const runtime_error
&e
) {
1302 g_log
<<Logger::Error
<<"Unable to read 'axfr-timeout' value: "<<e
.what()<<endl
;
1305 config
["axfr-timeout"] = 20;
1308 if (config
["failed-soa-retry"]) {
1310 config
["failed-soa-retry"].as
<uint16_t>();
1311 } catch (const runtime_error
&e
) {
1312 g_log
<<Logger::Error
<<"Unable to read 'failed-soa-retry' value: "<<e
.what()<<endl
;
1315 config
["failed-soa-retry"] = 30;
1318 if (config
["tcp-in-threads"]) {
1320 config
["tcp-in-threads"].as
<uint16_t>();
1321 } catch (const runtime_error
&e
) {
1322 g_log
<<Logger::Error
<<"Unable to read 'tcp-in-threads' value: "<<e
.what()<<endl
;
1325 config
["tcp-in-threads"] = 10;
1328 if (config
["listen"]) {
1330 config
["listen"].as
<vector
<ComboAddress
>>();
1331 } catch (const runtime_error
&e
) {
1332 g_log
<<Logger::Error
<<"Unable to read 'listen' value: "<<e
.what()<<endl
;
1336 config
["listen"].push_back("127.0.0.1:53");
1337 config
["listen"].push_back("[::1]:53");
1340 if (config
["acl"]) {
1342 config
["acl"].as
<vector
<string
>>();
1343 } catch (const runtime_error
&e
) {
1344 g_log
<<Logger::Error
<<"Unable to read 'acl' value: "<<e
.what()<<endl
;
1348 config
["acl"].push_back("127.0.0.0/8");
1349 config
["acl"].push_back("::1/128");
1352 if (config
["work-dir"]) {
1354 config
["work-dir"].as
<string
>();
1355 } catch(const runtime_error
&e
) {
1356 g_log
<<Logger::Error
<<"Unable to read 'work-dir' value: "<<e
.what()<<endl
;
1361 config
["work-dir"] = getcwd(tmp
, sizeof(tmp
)) ? string(tmp
) : "";;
1364 if (config
["uid"]) {
1366 config
["uid"].as
<string
>();
1367 } catch(const runtime_error
&e
) {
1368 g_log
<<Logger::Error
<<"Unable to read 'uid' value: "<<e
.what()<<endl
;
1373 if (config
["gid"]) {
1375 config
["gid"].as
<string
>();
1376 } catch(const runtime_error
&e
) {
1377 g_log
<<Logger::Error
<<"Unable to read 'gid' value: "<<e
.what()<<endl
;
1382 if (config
["domains"]) {
1383 if (config
["domains"].size() == 0) {
1384 g_log
<<Logger::Error
<<"No domains configured"<<endl
;
1387 for (auto const &domain
: config
["domains"]) {
1389 if (!domain
["domain"]) {
1390 g_log
<<Logger::Error
<<"An entry in 'domains' is missing a 'domain' key!"<<endl
;
1394 domain
["domain"].as
<DNSName
>();
1395 } catch (const runtime_error
&e
) {
1396 g_log
<<Logger::Error
<<"Unable to read domain '"<<domain
["domain"].as
<string
>()<<"': "<<e
.what()<<endl
;
1399 if (!domain
["master"]) {
1400 g_log
<< Logger::Error
<< "Domain '" << domain
["domain"].as
<string
>() << "' has no primary configured!" << endl
;
1404 domain
["master"].as
<ComboAddress
>();
1406 auto notifySource
= domain
["master"].as
<ComboAddress
>();
1408 g_notifySources
.addMask(notifySource
);
1409 } catch (const runtime_error
&e
) {
1410 g_log
<< Logger::Error
<< "Unable to read domain '" << domain
["domain"].as
<string
>() << "' primary address: " << e
.what() << endl
;
1413 if (domain
["max-soa-refresh"]) {
1415 domain
["max-soa-refresh"].as
<uint32_t>();
1416 } catch (const runtime_error
&e
) {
1417 g_log
<<Logger::Error
<<"Unable to read 'max-soa-refresh' value for domain '"<<domain
["domain"].as
<string
>()<<"': "<<e
.what()<<endl
;
1422 g_log
<<Logger::Error
<<"No domains configured"<<endl
;
1426 if (config
["compress"]) {
1428 config
["compress"].as
<bool>();
1430 catch (const runtime_error
&e
) {
1431 g_log
<<Logger::Error
<<"Unable to read 'compress' value: "<<e
.what()<<endl
;
1436 config
["compress"] = false;
1439 if (config
["webserver-address"]) {
1441 config
["webserver-address"].as
<ComboAddress
>();
1443 catch (const runtime_error
&e
) {
1444 g_log
<<Logger::Error
<<"Unable to read 'webserver-address' value: "<<e
.what()<<endl
;
1449 if (config
["webserver-acl"]) {
1451 config
["webserver-acl"].as
<vector
<Netmask
>>();
1453 catch (const runtime_error
&e
) {
1454 g_log
<<Logger::Error
<<"Unable to read 'webserver-acl' value: "<<e
.what()<<endl
;
1459 if (config
["webserver-loglevel"]) {
1461 config
["webserver-loglevel"].as
<string
>();
1463 catch (const runtime_error
&e
) {
1464 g_log
<<Logger::Error
<<"Unable to read 'webserver-loglevel' value: "<<e
.what()<<endl
;
1472 struct IXFRDistConfiguration
1474 set
<int> listeningSockets
;
1476 ComboAddress wsAddr
;
1477 std::string wsLogLevel
{"normal"};
1478 std::string workDir
;
1479 const struct passwd
* userInfo
{nullptr};
1480 uint32_t axfrMaxRecords
{0};
1482 uint16_t axfrTimeout
{0};
1483 uint16_t failedSOARetry
{0};
1484 uint16_t tcpInThreads
{0};
1487 bool shouldExit
{false};
1490 // NOLINTNEXTLINE(readability-function-cognitive-complexity)
1491 static std::optional
<IXFRDistConfiguration
> parseConfiguration(int argc
, char** argv
, FDMultiplexer
& fdm
)
1493 IXFRDistConfiguration configuration
;
1494 po::variables_map g_vm
;
1495 std::string configPath
;
1498 po::options_description
desc("IXFR distribution tool");
1500 ("help", "produce help message")
1501 ("version", "Display the version of ixfrdist")
1502 ("verbose", "Be verbose")
1503 ("debug", "Be even more verbose")
1504 ("config", po::value
<string
>()->default_value(SYSCONFDIR
+ string("/ixfrdist.yml")), "Configuration file to use")
1507 po::store(po::command_line_parser(argc
, argv
).options(desc
).run(), g_vm
);
1510 if (g_vm
.count("help") > 0) {
1512 configuration
.shouldExit
= true;
1513 return configuration
;
1516 if (g_vm
.count("version") > 0) {
1517 cout
<<"ixfrdist "<<VERSION
<<endl
;
1518 configuration
.shouldExit
= true;
1519 return configuration
;
1522 configPath
= g_vm
["config"].as
<string
>();
1524 catch (const po::error
&e
) {
1525 g_log
<<Logger::Error
<<e
.what()<<". See `ixfrdist --help` for valid options"<<endl
;
1526 return std::nullopt
;
1528 catch (const std::exception
& exp
) {
1529 g_log
<<Logger::Error
<<exp
.what()<<". See `ixfrdist --help` for valid options"<<endl
;
1530 return std::nullopt
;
1533 bool had_error
= false;
1535 if (g_vm
.count("verbose")) {
1536 g_log
.setLoglevel(Logger::Info
);
1537 g_log
.toConsole(Logger::Info
);
1540 if (g_vm
.count("debug") > 0) {
1541 g_log
.setLoglevel(Logger::Debug
);
1542 g_log
.toConsole(Logger::Debug
);
1545 g_log
<<Logger::Notice
<<"IXFR distributor version "<<VERSION
<<" starting up!"<<endl
;
1549 if (!parseAndCheckConfig(configPath
, config
)) {
1550 // parseAndCheckConfig already logged whatever was wrong
1551 return std::nullopt
;
1554 /* From hereon out, we known that all the values in config are valid. */
1556 for (auto const &domain
: config
["domains"]) {
1557 set
<ComboAddress
> s
;
1558 s
.insert(domain
["master"].as
<ComboAddress
>());
1559 g_domainConfigs
[domain
["domain"].as
<DNSName
>()].primaries
= s
;
1560 if (domain
["max-soa-refresh"].IsDefined()) {
1561 g_domainConfigs
[domain
["domain"].as
<DNSName
>()].maxSOARefresh
= domain
["max-soa-refresh"].as
<uint32_t>();
1563 if (domain
["notify"].IsDefined()) {
1564 auto& listset
= g_domainConfigs
[domain
["domain"].as
<DNSName
>()].notify
;
1565 if (domain
["notify"].IsScalar()) {
1566 auto remote
= domain
["notify"].as
<std::string
>();
1568 listset
.emplace(remote
, 53);
1570 catch (PDNSException
& e
) {
1571 g_log
<< Logger::Error
<< "Unparseable IP in notify directive " << remote
<< ". Error: " << e
.reason
<< endl
;
1573 } else if (domain
["notify"].IsSequence()) {
1574 for (const auto& entry
: domain
["notify"]) {
1575 auto remote
= entry
.as
<std::string
>();
1577 listset
.emplace(remote
, 53);
1579 catch (PDNSException
& e
) {
1580 g_log
<< Logger::Error
<< "Unparseable IP in notify directive " << remote
<< ". Error: " << e
.reason
<< endl
;
1585 g_stats
.registerDomain(domain
["domain"].as
<DNSName
>());
1588 for (const auto &addr
: config
["acl"].as
<vector
<string
>>()) {
1590 g_acl
.addMask(addr
);
1592 catch (const std::exception
& exp
) {
1593 g_log
<<Logger::Error
<<exp
.what()<<endl
;
1596 catch (const NetmaskException
&e
) {
1597 g_log
<<Logger::Error
<<e
.reason
<<endl
;
1603 g_log
<<Logger::Notice
<<"ACL set to "<<g_acl
.toString()<<"."<<endl
;
1605 catch (const std::exception
& exp
) {
1606 g_log
<<Logger::Error
<<"Error printing ACL: "<<exp
.what()<<endl
;
1609 g_log
<<Logger::Notice
<<"NOTIFY accepted from "<<g_notifySources
.toString()<<"."<<endl
;
1611 if (config
["compress"].IsDefined()) {
1612 g_compress
= config
["compress"].as
<bool>();
1614 g_log
<<Logger::Notice
<<"Record compression is enabled."<<endl
;
1618 for (const auto& addr
: config
["listen"].as
<vector
<ComboAddress
>>()) {
1619 for (const auto& stype
: {SOCK_DGRAM
, SOCK_STREAM
}) {
1621 int s
= SSocket(addr
.sin4
.sin_family
, stype
, 0);
1624 if (addr
.isIPv6()) {
1626 (void)setsockopt(s
, IPPROTO_IPV6
, IPV6_V6ONLY
, &one
, sizeof(one
));
1630 if (stype
== SOCK_STREAM
) {
1631 SListen(s
, 30); // TODO make this configurable
1633 fdm
.addReadFD(s
, stype
== SOCK_DGRAM
? handleUDPRequest
: handleTCPRequest
);
1634 configuration
.listeningSockets
.insert(s
);
1636 catch (const runtime_error
& exp
) {
1637 g_log
<<Logger::Error
<<exp
.what()<<endl
;
1641 catch (const PDNSException
& exp
) {
1642 g_log
<<Logger::Error
<<exp
.reason
<<endl
;
1649 if (config
["gid"].IsDefined()) {
1650 bool gidParsed
= false;
1651 auto gid
= config
["gid"].as
<string
>();
1653 configuration
.gid
= pdns::checked_stoi
<gid_t
>(gid
);
1656 catch (const std::exception
& e
) {
1657 configuration
.gid
= 0;
1660 //NOLINTNEXTLINE(concurrency-mt-unsafe): only one thread at this point
1661 const struct group
*gr
= getgrnam(gid
.c_str());
1662 if (gr
== nullptr) {
1663 g_log
<<Logger::Error
<<"Can not determine group-id for gid "<<gid
<<endl
;
1666 configuration
.gid
= gr
->gr_gid
;
1671 if (config
["webserver-address"].IsDefined()) {
1672 configuration
.wsAddr
= config
["webserver-address"].as
<ComboAddress
>();
1675 configuration
.wsACL
.addMask("127.0.0.0/8");
1676 configuration
.wsACL
.addMask("::1/128");
1678 if (config
["webserver-acl"].IsDefined()) {
1679 configuration
.wsACL
.clear();
1680 for (const auto &acl
: config
["webserver-acl"].as
<vector
<Netmask
>>()) {
1681 configuration
.wsACL
.addMask(acl
);
1685 catch (const NetmaskException
& ne
) {
1686 g_log
<<Logger::Error
<<"Could not set the webserver ACL: "<<ne
.reason
<<endl
;
1689 catch (const std::exception
& exp
) {
1690 g_log
<<Logger::Error
<<"Could not set the webserver ACL: "<<exp
.what()<<endl
;
1694 if (config
["webserver-loglevel"]) {
1695 configuration
.wsLogLevel
= config
["webserver-loglevel"].as
<string
>();
1699 if (config
["uid"].IsDefined()) {
1700 bool uidParsed
= false;
1701 auto uid
= config
["uid"].as
<string
>();
1703 configuration
.uid
= pdns::checked_stoi
<uid_t
>(uid
);
1706 catch (const std::exception
& e
) {
1707 configuration
.uid
= 0;
1710 //NOLINTNEXTLINE(concurrency-mt-unsafe): only one thread at this point
1711 const struct passwd
*pw
= getpwnam(uid
.c_str());
1712 if (pw
== nullptr) {
1713 g_log
<<Logger::Error
<<"Can not determine user-id for uid "<<uid
<<endl
;
1716 configuration
.uid
= pw
->pw_uid
;
1719 //NOLINTNEXTLINE(concurrency-mt-unsafe): only one thread at this point
1722 configuration
.userInfo
= getpwuid(configuration
.uid
);
1726 configuration
.workDir
= config
["work-dir"].as
<string
>();
1727 configuration
.keep
= config
["keep"].as
<uint16_t>();
1728 configuration
.axfrTimeout
= config
["axfr-timeout"].as
<uint16_t>();
1729 configuration
.failedSOARetry
= config
["failed-soa-retry"].as
<uint16_t>();
1730 configuration
.axfrMaxRecords
= config
["axfr-max-records"].as
<uint32_t>();
1731 configuration
.tcpInThreads
= config
["tcp-in-threads"].as
<uint16_t>();
1734 return std::nullopt
;
1736 return configuration
;
1738 catch (const YAML::Exception
& exp
) {
1740 g_log
<<Logger::Error
<<"Got an exception while applying our configuration: "<<exp
.msg
<<endl
;
1741 return std::nullopt
;
1745 int main(int argc
, char** argv
) {
1746 bool had_error
= false;
1747 std::optional
<IXFRDistConfiguration
> configuration
{std::nullopt
};
1748 std::unique_ptr
<FDMultiplexer
> fdm
{nullptr};
1751 g_log
.setLoglevel(Logger::Notice
);
1752 g_log
.toConsole(Logger::Notice
);
1753 g_log
.setPrefixed(true);
1754 g_log
.disableSyslog(true);
1755 g_log
.setTimestamps(false);
1757 fdm
= std::unique_ptr
<FDMultiplexer
>(FDMultiplexer::getMultiplexerSilent());
1759 g_log
<<Logger::Error
<<"Could not enable a multiplexer for the listen sockets!"<<endl
;
1760 return EXIT_FAILURE
;
1763 configuration
= parseConfiguration(argc
, argv
, *fdm
);
1764 if (!configuration
) {
1765 // We have already sent the errors to stderr, just die
1766 return EXIT_FAILURE
;
1769 if (configuration
->shouldExit
) {
1770 return EXIT_SUCCESS
;
1773 catch (const YAML::Exception
& exp
) {
1775 g_log
<<Logger::Error
<<"Got an exception while processing our configuration: "<<exp
.msg
<<endl
;
1779 if (configuration
->gid
!= 0) {
1780 g_log
<<Logger::Notice
<<"Dropping effective group-id to "<<configuration
->gid
<<endl
;
1781 if (setgid(configuration
->gid
) < 0) {
1782 g_log
<<Logger::Error
<<"Could not set group id to "<<configuration
->gid
<<": "<<stringerror()<<endl
;
1787 // It all starts here
1788 signal(SIGTERM
, handleSignal
);
1789 signal(SIGINT
, handleSignal
);
1790 //NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
1791 signal(SIGPIPE
, SIG_IGN
);
1793 // Launch the webserver!
1795 std::thread(&IXFRDistWebServer::go
, IXFRDistWebServer(configuration
->wsAddr
, configuration
->wsACL
, configuration
->wsLogLevel
)).detach();
1797 catch (const std::exception
& exp
) {
1798 g_log
<<Logger::Error
<<"Unable to start webserver: "<<exp
.what()<<endl
;
1801 catch (const PDNSException
&e
) {
1802 g_log
<<Logger::Error
<<"Unable to start webserver: "<<e
.reason
<<endl
;
1806 if (configuration
->uid
!= 0) {
1807 if (configuration
->userInfo
== nullptr) {
1808 if (setgroups(0, nullptr) < 0) {
1809 g_log
<<Logger::Error
<<"Unable to drop supplementary gids: "<<stringerror()<<endl
;
1813 if (initgroups(configuration
->userInfo
->pw_name
, configuration
->gid
) < 0) {
1814 g_log
<<Logger::Error
<<"Unable to set supplementary groups: "<<stringerror()<<endl
;
1819 g_log
<<Logger::Notice
<<"Dropping effective user-id to "<<configuration
->uid
<<endl
;
1820 if (setuid(configuration
->uid
) < 0) {
1821 g_log
<<Logger::Error
<<"Could not set user id to "<<configuration
->uid
<<": "<<stringerror()<<endl
;
1827 return EXIT_FAILURE
;
1830 catch (const YAML::Exception
& exp
) {
1832 g_log
<<Logger::Error
<<"Got an exception while applying our configuration: "<<exp
.msg
<<endl
;
1836 // Init the things we need
1839 std::thread
ut(updateThread
,
1840 configuration
->workDir
,
1841 configuration
->keep
,
1842 configuration
->axfrTimeout
,
1843 configuration
->failedSOARetry
,
1844 configuration
->axfrMaxRecords
);
1845 std::thread
communicator(communicatorThread
);
1847 vector
<std::thread
> tcpHandlers
;
1848 tcpHandlers
.reserve(configuration
->tcpInThreads
);
1849 for (size_t i
= 0; i
< tcpHandlers
.capacity(); ++i
) {
1850 tcpHandlers
.push_back(std::thread(tcpWorker
, i
));
1855 gettimeofday(&now
, 0);
1858 g_log
<<Logger::Debug
<<"Closing listening sockets"<<endl
;
1859 for (const int& fd
: configuration
->listeningSockets
) {
1862 } catch (const PDNSException
&e
) {
1863 g_log
<<Logger::Error
<<e
.reason
<<endl
;
1870 g_log
<<Logger::Debug
<<"Waiting for all threads to stop"<<endl
;
1871 g_tcpHandlerCV
.notify_all();
1873 communicator
.join();
1874 for (auto &t
: tcpHandlers
) {
1877 g_log
<<Logger::Notice
<<"IXFR distributor stopped"<<endl
;
1879 catch (const YAML::Exception
& exp
) {
1881 g_log
<<Logger::Error
<<"Got an exception: "<<exp
.msg
<<endl
;
1884 return had_error
? EXIT_FAILURE
: EXIT_SUCCESS
;