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.
25 #include <boost/program_options.hpp>
26 #include <arpa/inet.h>
27 #include <sys/types.h>
35 #include <condition_variable>
37 #include "ixfrutils.hh"
38 #include "resolver.hh"
39 #include "dns_random.hh"
45 #include <yaml-cpp/yaml.h>
47 /* BEGIN Needed because of deeper dependencies */
48 #include "arguments.hh"
54 static ArgvMap theArg
;
57 /* END Needed because of deeper dependencies */
59 // Allows reading/writing ComboAddresses and DNSNames in YAML-cpp
62 struct convert
<ComboAddress
> {
63 static Node
encode(const ComboAddress
& rhs
) {
64 return Node(rhs
.toStringWithPort());
66 static bool decode(const Node
& node
, ComboAddress
& rhs
) {
67 if (!node
.IsScalar()) {
71 rhs
= ComboAddress(node
.as
<string
>(), 53);
73 } catch(const runtime_error
&e
) {
75 } catch (const PDNSException
&e
) {
82 struct convert
<DNSName
> {
83 static Node
encode(const DNSName
& rhs
) {
84 return Node(rhs
.toStringRootDot());
86 static bool decode(const Node
& node
, DNSName
& rhs
) {
87 if (!node
.IsScalar()) {
91 rhs
= DNSName(node
.as
<string
>());
93 } catch(const runtime_error
&e
) {
95 } catch (const PDNSException
&e
) {
103 shared_ptr
<SOARecordContent
> oldSOA
;
104 shared_ptr
<SOARecordContent
> newSOA
;
105 vector
<DNSRecord
> removals
;
106 vector
<DNSRecord
> additions
;
110 shared_ptr
<SOARecordContent
> soa
; // The SOA of the latestAXFR
111 records_t latestAXFR
; // The most recent AXFR
112 vector
<std::shared_ptr
<ixfrdiff_t
>> ixfrDiffs
;
115 // Why a struct? This way we can add more options to a domain in the future
116 struct ixfrdistdomain_t
{
117 set
<ComboAddress
> masters
; // A set so we can do multiple master addresses in the future
120 // This contains the configuration for each domain
121 static map
<DNSName
, ixfrdistdomain_t
> g_domainConfigs
;
123 // Map domains and their data
124 static std::map
<DNSName
, std::shared_ptr
<ixfrinfo_t
>> g_soas
;
125 static std::mutex g_soas_mutex
;
127 // Condition variable for TCP handling
128 static std::condition_variable g_tcpHandlerCV
;
129 static std::queue
<pair
<int, ComboAddress
>> g_tcpRequestFDs
;
130 static std::mutex g_tcpRequestFDsMutex
;
132 namespace po
= boost::program_options
;
134 static bool g_exiting
= false;
136 static NetmaskGroup g_acl
;
137 static bool g_compress
= false;
139 static void handleSignal(int signum
) {
140 g_log
<<Logger::Notice
<<"Got "<<strsignal(signum
)<<" signal";
142 g_log
<<Logger::Notice
<<", this is the second time we were asked to stop, forcefully exiting"<<endl
;
145 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
;
149 static void usage(po::options_description
&desc
) {
150 cerr
<< "Usage: ixfrdist [OPTION]..."<<endl
;
151 cerr
<< desc
<< "\n";
154 // The compiler does not like using rfc1982LessThan in std::sort directly
155 static bool sortSOA(uint32_t i
, uint32_t j
) {
156 return rfc1982LessThan(i
, j
);
159 static void cleanUpDomain(const DNSName
& domain
, const uint16_t& keep
, const string
& workdir
) {
160 string dir
= workdir
+ "/" + domain
.toString();
162 dp
= opendir(dir
.c_str());
166 vector
<uint32_t> zoneVersions
;
168 while ((d
= readdir(dp
)) != nullptr) {
169 if(!strcmp(d
->d_name
, ".") || !strcmp(d
->d_name
, "..")) {
172 zoneVersions
.push_back(std::stoi(d
->d_name
));
175 g_log
<<Logger::Info
<<"Found "<<zoneVersions
.size()<<" versions of "<<domain
<<", asked to keep "<<keep
<<", ";
176 if (zoneVersions
.size() <= keep
) {
177 g_log
<<Logger::Info
<<"not cleaning up"<<endl
;
180 g_log
<<Logger::Info
<<"cleaning up the oldest "<<zoneVersions
.size() - keep
<<endl
;
183 std::sort(zoneVersions
.begin(), zoneVersions
.end(), sortSOA
);
185 // And delete all the old ones
187 // Lock to ensure no one reads this.
188 std::lock_guard
<std::mutex
> guard(g_soas_mutex
);
189 for (auto iter
= zoneVersions
.cbegin(); iter
!= zoneVersions
.cend() - keep
; ++iter
) {
190 string fname
= dir
+ "/" + std::to_string(*iter
);
191 g_log
<<Logger::Debug
<<"Removing "<<fname
<<endl
;
192 unlink(fname
.c_str());
197 static shared_ptr
<SOARecordContent
> getSOAFromRecords(const records_t
& records
) {
198 for (const auto& dnsrecord
: records
) {
199 if (dnsrecord
.d_type
== QType::SOA
) {
200 auto soa
= getRR
<SOARecordContent
>(dnsrecord
);
201 if (soa
== nullptr) {
202 throw PDNSException("Unable to determine SOARecordContent from old records");
207 throw PDNSException("No SOA in supplied records");
210 static void makeIXFRDiff(const records_t
& from
, const records_t
& to
, std::shared_ptr
<ixfrdiff_t
>& diff
, const shared_ptr
<SOARecordContent
>& fromSOA
= nullptr, const shared_ptr
<SOARecordContent
>& toSOA
= nullptr) {
211 set_difference(from
.cbegin(), from
.cend(), to
.cbegin(), to
.cend(), back_inserter(diff
->removals
), from
.value_comp());
212 set_difference(to
.cbegin(), to
.cend(), from
.cbegin(), from
.cend(), back_inserter(diff
->additions
), from
.value_comp());
213 diff
->oldSOA
= fromSOA
;
214 if (fromSOA
== nullptr) {
215 diff
->oldSOA
= getSOAFromRecords(from
);
217 diff
->newSOA
= toSOA
;
218 if (toSOA
== nullptr) {
219 diff
->newSOA
= getSOAFromRecords(to
);
223 /* you can _never_ alter the content of the resulting shared pointer */
224 static std::shared_ptr
<ixfrinfo_t
> getCurrentZoneInfo(const DNSName
& domain
)
226 std::lock_guard
<std::mutex
> guard(g_soas_mutex
);
227 return g_soas
[domain
];
230 static void updateCurrentZoneInfo(const DNSName
& domain
, std::shared_ptr
<ixfrinfo_t
>& newInfo
)
232 std::lock_guard
<std::mutex
> guard(g_soas_mutex
);
233 g_soas
[domain
] = newInfo
;
236 void updateThread(const string
& workdir
, const uint16_t& keep
, const uint16_t& axfrTimeout
, const uint16_t& soaRetry
) {
237 std::map
<DNSName
, time_t> lastCheck
;
239 // Initialize the serials we have
240 for (const auto &domainConfig
: g_domainConfigs
) {
241 DNSName domain
= domainConfig
.first
;
242 lastCheck
[domain
] = 0;
243 string dir
= workdir
+ "/" + domain
.toString();
245 g_log
<<Logger::Info
<<"Trying to initially load domain "<<domain
<<" from disk"<<endl
;
246 auto serial
= getSerialsFromDir(dir
);
247 shared_ptr
<SOARecordContent
> soa
;
249 string fname
= workdir
+ "/" + domain
.toString() + "/" + std::to_string(serial
);
250 loadSOAFromDisk(domain
, fname
, soa
);
252 if (soa
!= nullptr) {
253 loadZoneFromDisk(records
, fname
, domain
);
255 auto zoneInfo
= std::make_shared
<ixfrinfo_t
>();
256 zoneInfo
->latestAXFR
= std::move(records
);
258 updateCurrentZoneInfo(domain
, zoneInfo
);
260 if (soa
!= nullptr) {
261 g_log
<<Logger::Notice
<<"Loaded zone "<<domain
<<" with serial "<<soa
->d_st
.serial
<<endl
;
263 cleanUpDomain(domain
, keep
, workdir
);
265 } catch (runtime_error
&e
) {
266 // Most likely, the directory does not exist.
267 g_log
<<Logger::Info
<<e
.what()<<", attempting to create"<<endl
;
268 // Attempt to create it, if _that_ fails, there is no hope
269 if (mkdir(dir
.c_str(), 0777) == -1 && errno
!= EEXIST
) {
270 g_log
<<Logger::Error
<<"Could not create '"<<dir
<<"': "<<strerror(errno
)<<endl
;
276 g_log
<<Logger::Notice
<<"Update Thread started"<<endl
;
280 g_log
<<Logger::Notice
<<"UpdateThread stopped"<<endl
;
283 time_t now
= time(nullptr);
284 for (const auto &domainConfig
: g_domainConfigs
) {
290 DNSName domain
= domainConfig
.first
;
291 shared_ptr
<SOARecordContent
> current_soa
;
292 const auto& zoneInfo
= getCurrentZoneInfo(domain
);
293 if (zoneInfo
!= nullptr) {
294 current_soa
= zoneInfo
->soa
;
297 auto& zoneLastCheck
= lastCheck
[domain
];
298 if ((current_soa
!= nullptr && now
- zoneLastCheck
< current_soa
->d_st
.refresh
) || // Only check if we have waited `refresh` seconds
299 (current_soa
== nullptr && now
- zoneLastCheck
< soaRetry
)) { // Or if we could not get an update at all still, every 30 seconds
303 // TODO Keep track of 'down' masters
304 set
<ComboAddress
>::const_iterator
it(domainConfig
.second
.masters
.begin());
305 std::advance(it
, random() % domainConfig
.second
.masters
.size());
306 ComboAddress master
= *it
;
308 string dir
= workdir
+ "/" + domain
.toString();
309 g_log
<<Logger::Info
<<"Attempting to retrieve SOA Serial update for '"<<domain
<<"' from '"<<master
.toStringWithPort()<<"'"<<endl
;
310 shared_ptr
<SOARecordContent
> sr
;
313 auto newSerial
= getSerialFromMaster(master
, domain
, sr
); // TODO TSIG
314 if(current_soa
!= nullptr) {
315 g_log
<<Logger::Info
<<"Got SOA Serial for "<<domain
<<" from "<<master
.toStringWithPort()<<": "<< newSerial
<<", had Serial: "<<current_soa
->d_st
.serial
;
316 if (newSerial
== current_soa
->d_st
.serial
) {
317 g_log
<<Logger::Info
<<", not updating."<<endl
;
320 g_log
<<Logger::Info
<<", will update."<<endl
;
322 } catch (runtime_error
&e
) {
323 g_log
<<Logger::Warning
<<"Unable to get SOA serial update for '"<<domain
<<"' from master "<<master
.toStringWithPort()<<": "<<e
.what()<<endl
;
326 // Now get the full zone!
327 g_log
<<Logger::Info
<<"Attempting to receive full zonedata for '"<<domain
<<"'"<<endl
;
328 ComboAddress local
= master
.isIPv4() ? ComboAddress("0.0.0.0") : ComboAddress("::");
332 shared_ptr
<SOARecordContent
> soa
;
335 AXFRRetriever
axfr(master
, domain
, tt
, &local
);
336 unsigned int nrecords
=0;
338 vector
<DNSRecord
> chunk
;
339 time_t t_start
= time(nullptr);
340 time_t axfr_now
= time(nullptr);
341 while(axfr
.getChunk(nop
, &chunk
, (axfr_now
- t_start
+ axfrTimeout
))) {
342 for(auto& dr
: chunk
) {
343 if(dr
.d_type
== QType::TSIG
)
345 if(!dr
.d_name
.isPartOf(domain
)) {
346 throw PDNSException("Out-of-zone data received during AXFR of "+domain
.toLogString());
348 dr
.d_name
.makeUsRelative(domain
);
351 if (dr
.d_type
== QType::SOA
) {
352 soa
= getRR
<SOARecordContent
>(dr
);
355 axfr_now
= time(nullptr);
356 if (axfr_now
- t_start
> axfrTimeout
) {
357 throw PDNSException("Total AXFR time exceeded!");
360 if (soa
== nullptr) {
361 g_log
<<Logger::Warning
<<"No SOA was found in the AXFR of "<<domain
<<endl
;
364 g_log
<<Logger::Notice
<<"Retrieved all zone data for "<<domain
<<". Received "<<nrecords
<<" records."<<endl
;
365 } catch (PDNSException
&e
) {
366 g_log
<<Logger::Warning
<<"Could not retrieve AXFR for '"<<domain
<<"': "<<e
.reason
<<endl
;
368 } catch (runtime_error
&e
) {
369 g_log
<<Logger::Warning
<<"Could not retrieve AXFR for zone '"<<domain
<<"': "<<e
.what()<<endl
;
375 writeZoneToDisk(records
, domain
, dir
);
376 g_log
<<Logger::Notice
<<"Wrote zonedata for "<<domain
<<" with serial "<<soa
->d_st
.serial
<<" to "<<dir
<<endl
;
378 const auto oldZoneInfo
= getCurrentZoneInfo(domain
);
379 auto zoneInfo
= std::make_shared
<ixfrinfo_t
>();
381 if (oldZoneInfo
&& !oldZoneInfo
->latestAXFR
.empty()) {
382 auto diff
= std::make_shared
<ixfrdiff_t
>();
383 zoneInfo
->ixfrDiffs
= oldZoneInfo
->ixfrDiffs
;
384 g_log
<<Logger::Debug
<<"Calculating diff for "<<domain
<<endl
;
385 makeIXFRDiff(oldZoneInfo
->latestAXFR
, records
, diff
, oldZoneInfo
->soa
, soa
);
386 g_log
<<Logger::Debug
<<"Calculated diff for "<<domain
<<", we had "<<diff
->removals
.size()<<" removals and "<<diff
->additions
.size()<<" additions"<<endl
;
387 zoneInfo
->ixfrDiffs
.push_back(std::move(diff
));
390 // Clean up the diffs
391 while (zoneInfo
->ixfrDiffs
.size() > keep
) {
392 zoneInfo
->ixfrDiffs
.erase(zoneInfo
->ixfrDiffs
.begin());
395 g_log
<<Logger::Debug
<<"Zone "<<domain
<<" previously contained "<<(oldZoneInfo
? oldZoneInfo
->latestAXFR
.size() : 0)<<" entries, "<<records
.size()<<" now"<<endl
;
396 zoneInfo
->latestAXFR
= std::move(records
);
398 updateCurrentZoneInfo(domain
, zoneInfo
);
399 } catch (PDNSException
&e
) {
400 g_log
<<Logger::Warning
<<"Could not save zone '"<<domain
<<"' to disk: "<<e
.reason
<<endl
;
401 } catch (runtime_error
&e
) {
402 g_log
<<Logger::Warning
<<"Could not save zone '"<<domain
<<"' to disk: "<<e
.what()<<endl
;
405 // Now clean up the directory
406 cleanUpDomain(domain
, keep
, workdir
);
407 } /* for (const auto &domain : domains) */
412 static bool checkQuery(const MOADNSParser
& mdp
, const ComboAddress
& saddr
, const bool udp
= true, const string
& logPrefix
="") {
413 vector
<string
> info_msg
;
415 g_log
<<Logger::Debug
<<logPrefix
<<"Had "<<mdp
.d_qname
<<"|"<<QType(mdp
.d_qtype
).getName()<<" query from "<<saddr
.toStringWithPort()<<endl
;
417 if (udp
&& mdp
.d_qtype
!= QType::SOA
&& mdp
.d_qtype
!= QType::IXFR
) {
418 info_msg
.push_back("QType is unsupported (" + QType(mdp
.d_qtype
).getName() + " is not in {SOA,IXFR})");
421 if (!udp
&& mdp
.d_qtype
!= QType::SOA
&& mdp
.d_qtype
!= QType::IXFR
&& mdp
.d_qtype
!= QType::AXFR
) {
422 info_msg
.push_back("QType is unsupported (" + QType(mdp
.d_qtype
).getName() + " is not in {SOA,IXFR,AXFR})");
426 if (g_domainConfigs
.find(mdp
.d_qname
) == g_domainConfigs
.end()) {
427 info_msg
.push_back("Domain name '" + mdp
.d_qname
.toLogString() + "' is not configured for distribution");
430 const auto zoneInfo
= getCurrentZoneInfo(mdp
.d_qname
);
431 if (zoneInfo
== nullptr) {
432 info_msg
.push_back("Domain has not been transferred yet");
437 if (!info_msg
.empty()) {
438 g_log
<<Logger::Warning
<<logPrefix
<<"Refusing "<<mdp
.d_qname
<<"|"<<QType(mdp
.d_qtype
).getName()<<" query from "<<saddr
.toStringWithPort();
439 g_log
<<Logger::Warning
<<": ";
441 for (const auto& s
: info_msg
) {
443 g_log
<<Logger::Warning
<<", ";
446 g_log
<<Logger::Warning
<<s
;
448 g_log
<<Logger::Warning
<<endl
;
456 * Returns a vector<uint8_t> that represents the full positive response to a SOA
457 * query. QNAME is read from mdp.
459 static bool makeSOAPacket(const MOADNSParser
& mdp
, vector
<uint8_t>& packet
) {
461 auto zoneInfo
= getCurrentZoneInfo(mdp
.d_qname
);
462 if (zoneInfo
== nullptr) {
466 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
467 pw
.getHeader()->id
= mdp
.d_header
.id
;
468 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
469 pw
.getHeader()->qr
= 1;
471 pw
.startRecord(mdp
.d_qname
, QType::SOA
);
472 zoneInfo
->soa
->toPacket(pw
);
479 * Returns a vector<uint8_t> that represents the full REFUSED response to a
480 * query. QNAME and type are read from mdp.
482 static bool makeRefusedPacket(const MOADNSParser
& mdp
, vector
<uint8_t>& packet
) {
483 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
484 pw
.getHeader()->id
= mdp
.d_header
.id
;
485 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
486 pw
.getHeader()->qr
= 1;
487 pw
.getHeader()->rcode
= RCode::Refused
;
492 static vector
<uint8_t> getSOAPacket(const MOADNSParser
& mdp
, const shared_ptr
<SOARecordContent
>& soa
) {
493 vector
<uint8_t> packet
;
494 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
495 pw
.getHeader()->id
= mdp
.d_header
.id
;
496 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
497 pw
.getHeader()->qr
= 1;
500 pw
.startRecord(mdp
.d_qname
, QType::SOA
);
506 static bool sendPacketOverTCP(int fd
, const std::vector
<uint8_t>& packet
)
509 sendBuf
[0]=packet
.size()/256;
510 sendBuf
[1]=packet
.size()%256;
512 ssize_t send
= writen2(fd
, sendBuf
, 2);
513 send
+= writen2(fd
, &packet
[0], packet
.size());
517 static bool addRecordToWriter(DNSPacketWriter
& pw
, const DNSName
& zoneName
, const DNSRecord
& record
, bool compress
)
519 pw
.startRecord(record
.d_name
+ zoneName
, record
.d_type
, record
.d_ttl
, QClass::IN
, DNSResourceRecord::ANSWER
, compress
);
520 record
.d_content
->toPacket(pw
);
521 if (pw
.size() > 65535) {
528 template <typename T
> static bool sendRecordsOverTCP(int fd
, const MOADNSParser
& mdp
, const T
& records
)
530 vector
<uint8_t> packet
;
532 for (auto it
= records
.cbegin(); it
!= records
.cend();) {
533 bool recordsAdded
= false;
535 DNSPacketWriter
pw(packet
, mdp
.d_qname
, mdp
.d_qtype
);
536 pw
.getHeader()->id
= mdp
.d_header
.id
;
537 pw
.getHeader()->rd
= mdp
.d_header
.rd
;
538 pw
.getHeader()->qr
= 1;
540 while (it
!= records
.cend()) {
541 if (it
->d_type
== QType::SOA
) {
546 if (addRecordToWriter(pw
, mdp
.d_qname
, *it
, g_compress
)) {
553 sendPacketOverTCP(fd
, packet
);
555 if (it
== records
.cbegin()) {
556 /* something is wrong */
564 if (it
== records
.cend() && recordsAdded
) {
566 sendPacketOverTCP(fd
, packet
);
574 static bool handleAXFR(int fd
, const MOADNSParser
& mdp
) {
575 /* we get a shared pointer of the zone info that we can't modify, ever.
576 A newer one may arise in the meantime, but this one will stay valid
579 auto zoneInfo
= getCurrentZoneInfo(mdp
.d_qname
);
580 if (zoneInfo
== nullptr) {
584 shared_ptr
<SOARecordContent
> soa
= zoneInfo
->soa
;
585 const records_t
& records
= zoneInfo
->latestAXFR
;
588 const auto soaPacket
= getSOAPacket(mdp
, soa
);
589 if (!sendPacketOverTCP(fd
, soaPacket
)) {
593 if (!sendRecordsOverTCP(fd
, mdp
, records
)) {
598 if (!sendPacketOverTCP(fd
, soaPacket
)) {
605 /* Produces an IXFR if one can be made according to the rules in RFC 1995 and
606 * creates a SOA or AXFR packet when required by the RFC.
608 static bool handleIXFR(int fd
, const ComboAddress
& destination
, const MOADNSParser
& mdp
, const shared_ptr
<SOARecordContent
>& clientSOA
) {
609 vector
<std::shared_ptr
<ixfrdiff_t
>> toSend
;
611 /* we get a shared pointer of the zone info that we can't modify, ever.
612 A newer one may arise in the meantime, but this one will stay valid
615 auto zoneInfo
= getCurrentZoneInfo(mdp
.d_qname
);
616 if (zoneInfo
== nullptr) {
620 uint32_t ourLatestSerial
= zoneInfo
->soa
->d_st
.serial
;
622 if (rfc1982LessThan(ourLatestSerial
, clientSOA
->d_st
.serial
) || ourLatestSerial
== clientSOA
->d_st
.serial
) {
623 /* RFC 1995 Section 2
624 * If an IXFR query with the same or newer version number than that of
625 * the server is received, it is replied to with a single SOA record of
626 * the server's current version, just as in AXFR.
628 vector
<uint8_t> packet
;
629 bool ret
= makeSOAPacket(mdp
, packet
);
631 sendPacketOverTCP(fd
, packet
);
636 // as we use push_back in the updater, we know the vector is sorted as oldest first
637 bool shouldAdd
= false;
638 // Get all relevant IXFR differences
639 for (const auto& diff
: zoneInfo
->ixfrDiffs
) {
641 toSend
.push_back(diff
);
644 if (diff
->oldSOA
->d_st
.serial
== clientSOA
->d_st
.serial
) {
645 toSend
.push_back(diff
);
646 // Add all consecutive diffs
651 if (toSend
.empty()) {
652 g_log
<<Logger::Warning
<<"No IXFR available from serial "<<clientSOA
->d_st
.serial
<<" for zone "<<mdp
.d_qname
<<", attempting to send AXFR"<<endl
;
653 return handleAXFR(fd
, mdp
);
656 std::vector
<std::vector
<uint8_t>> packets
;
657 for (const auto& diff
: toSend
) {
658 /* An IXFR packet's ANSWER section looks as follows:
661 * ... removed records ...
663 * ... added records ...
667 const auto newSOAPacket
= getSOAPacket(mdp
, diff
->newSOA
);
668 const auto oldSOAPacket
= getSOAPacket(mdp
, diff
->oldSOA
);
670 if (!sendPacketOverTCP(fd
, newSOAPacket
)) {
674 if (!sendPacketOverTCP(fd
, oldSOAPacket
)) {
678 if (!sendRecordsOverTCP(fd
, mdp
, diff
->removals
)) {
682 if (!sendPacketOverTCP(fd
, newSOAPacket
)) {
686 if (!sendRecordsOverTCP(fd
, mdp
, diff
->additions
)) {
690 if (!sendPacketOverTCP(fd
, newSOAPacket
)) {
698 static bool allowedByACL(const ComboAddress
& addr
) {
699 return g_acl
.match(addr
);
702 static void handleUDPRequest(int fd
, boost::any
&) {
703 // TODO make the buffer-size configurable
706 socklen_t fromlen
= sizeof(saddr
);
707 int res
= recvfrom(fd
, buf
, sizeof(buf
), 0, (struct sockaddr
*) &saddr
, &fromlen
);
710 g_log
<<Logger::Warning
<<"Got an empty message from "<<saddr
.toStringWithPort()<<endl
;
715 auto savedErrno
= errno
;
716 g_log
<<Logger::Warning
<<"Could not read message from "<<saddr
.toStringWithPort()<<": "<<strerror(savedErrno
)<<endl
;
720 if (saddr
== ComboAddress("0.0.0.0", 0)) {
721 g_log
<<Logger::Warning
<<"Could not determine source of message"<<endl
;
725 if (!allowedByACL(saddr
)) {
726 g_log
<<Logger::Warning
<<"UDP query from "<<saddr
.toString()<<" is not allowed, dropping"<<endl
;
730 MOADNSParser
mdp(true, string(buf
, res
));
731 vector
<uint8_t> packet
;
732 if (checkQuery(mdp
, saddr
)) {
733 /* RFC 1995 Section 2
734 * Transport of a query may be by either UDP or TCP. If an IXFR query
735 * is via UDP, the IXFR server may attempt to reply using UDP if the
736 * entire response can be contained in a single DNS packet. If the UDP
737 * reply does not fit, the query is responded to with a single SOA
738 * record of the server's current version to inform the client that a
739 * TCP query should be initiated.
741 * Let's not complicate this with IXFR over UDP (and looking if we need to truncate etc).
742 * Just send the current SOA and let the client try over TCP
744 makeSOAPacket(mdp
, packet
);
746 makeRefusedPacket(mdp
, packet
);
749 if(sendto(fd
, &packet
[0], packet
.size(), 0, (struct sockaddr
*) &saddr
, fromlen
) < 0) {
750 auto savedErrno
= errno
;
751 g_log
<<Logger::Warning
<<"Could not send reply for "<<mdp
.d_qname
<<"|"<<QType(mdp
.d_qtype
).getName()<<" to "<<saddr
.toStringWithPort()<<": "<<strerror(savedErrno
)<<endl
;
756 static void handleTCPRequest(int fd
, boost::any
&) {
761 cfd
= SAccept(fd
, saddr
);
763 } catch(runtime_error
&e
) {
764 g_log
<<Logger::Error
<<e
.what()<<endl
;
768 if (saddr
== ComboAddress("0.0.0.0", 0)) {
769 g_log
<<Logger::Warning
<<"Could not determine source of message"<<endl
;
774 if (!allowedByACL(saddr
)) {
775 g_log
<<Logger::Warning
<<"TCP query from "<<saddr
.toString()<<" is not allowed, dropping"<<endl
;
781 std::lock_guard
<std::mutex
> lg(g_tcpRequestFDsMutex
);
782 g_tcpRequestFDs
.push({cfd
, saddr
});
784 g_tcpHandlerCV
.notify_one();
787 /* Thread to handle TCP traffic
789 static void tcpWorker(int tid
) {
790 string prefix
= "TCP Worker " + std::to_string(tid
) + ": ";
793 g_log
<<Logger::Debug
<<prefix
<<"ready for a new request!"<<endl
;
794 std::unique_lock
<std::mutex
> lk(g_tcpRequestFDsMutex
);
795 g_tcpHandlerCV
.wait(lk
, []{return g_tcpRequestFDs
.size() || g_exiting
;});
797 g_log
<<Logger::Debug
<<prefix
<<"Stopping thread"<<endl
;
800 g_log
<<Logger::Debug
<<prefix
<<"Going to handle a query"<<endl
;
801 auto request
= g_tcpRequestFDs
.front();
802 g_tcpRequestFDs
.pop();
805 int cfd
= request
.first
;
806 ComboAddress saddr
= request
.second
;
812 readn2(cfd
, &toRead
, sizeof(toRead
));
813 toRead
= std::min(ntohs(toRead
), static_cast<uint16_t>(sizeof(buf
)));
814 res
= readn2WithTimeout(cfd
, &buf
, toRead
, 2);
815 g_log
<<Logger::Debug
<<prefix
<<"Had message of "<<std::to_string(toRead
)<<" bytes from "<<saddr
.toStringWithPort()<<endl
;
816 } catch (runtime_error
&e
) {
817 g_log
<<Logger::Warning
<<prefix
<<"Could not read message from "<<saddr
.toStringWithPort()<<": "<<e
.what()<<endl
;
823 MOADNSParser
mdp(true, string(buf
, res
));
825 if (!checkQuery(mdp
, saddr
, false, prefix
)) {
830 if (mdp
.d_qtype
== QType::SOA
) {
831 vector
<uint8_t> packet
;
832 bool ret
= makeSOAPacket(mdp
, packet
);
837 sendPacketOverTCP(cfd
, packet
);
839 else if (mdp
.d_qtype
== QType::AXFR
) {
840 if (!handleAXFR(cfd
, mdp
)) {
845 else if (mdp
.d_qtype
== QType::IXFR
) {
846 /* RFC 1995 section 3:
847 * The IXFR query packet format is the same as that of a normal DNS
848 * query, but with the query type being IXFR and the authority section
849 * containing the SOA record of client's version of the zone.
851 shared_ptr
<SOARecordContent
> clientSOA
;
852 for (auto &answer
: mdp
.d_answers
) {
853 // from dnsparser.hh:
854 // typedef vector<pair<DNSRecord, uint16_t > > answers_t;
855 if (answer
.first
.d_type
== QType::SOA
&& answer
.first
.d_place
== DNSResourceRecord::AUTHORITY
) {
856 clientSOA
= getRR
<SOARecordContent
>(answer
.first
);
857 if (clientSOA
!= nullptr) {
861 } /* for (auto const &answer : mdp.d_answers) */
863 if (clientSOA
== nullptr) {
864 g_log
<<Logger::Warning
<<prefix
<<"IXFR request packet did not contain a SOA record in the AUTHORITY section"<<endl
;
869 if (!handleIXFR(cfd
, saddr
, mdp
, clientSOA
)) {
873 } /* if (mdp.d_qtype == QType::IXFR) */
876 } catch (const MOADNSException
&mde
) {
877 g_log
<<Logger::Warning
<<prefix
<<"Could not parse DNS packet from "<<saddr
.toStringWithPort()<<": "<<mde
.what()<<endl
;
878 } catch (runtime_error
&e
) {
879 g_log
<<Logger::Warning
<<prefix
<<"Could not write reply to "<<saddr
.toStringWithPort()<<": "<<e
.what()<<endl
;
890 /* Parses the configuration file in configpath into config, adding defaults for
891 * missing parameters (if applicable), returning true if the config file was
892 * good, false otherwise. Will log all issues with the config
894 static bool parseAndCheckConfig(const string
& configpath
, YAML::Node
& config
) {
895 g_log
<<Logger::Info
<<"Loading configuration file from "<<configpath
<<endl
;
897 config
= YAML::LoadFile(configpath
);
898 } catch (const runtime_error
&e
) {
899 g_log
<<Logger::Error
<<"Unable to load configuration file '"<<configpath
<<"': "<<e
.what()<<endl
;
905 if (config
["keep"]) {
907 config
["keep"].as
<uint16_t>();
908 } catch (const runtime_error
&e
) {
909 g_log
<<Logger::Error
<<"Unable to read 'keep' value: "<<e
.what()<<endl
;
916 if (config
["axfr-timeout"]) {
918 config
["axfr-timeout"].as
<uint16_t>();
919 } catch (const runtime_error
&e
) {
920 g_log
<<Logger::Error
<<"Unable to read 'axfr-timeout' value: "<<e
.what()<<endl
;
923 config
["axfr-timeout"] = 20;
926 if (config
["failed-soa-retry"]) {
928 config
["failed-soa-retry"].as
<uint16_t>();
929 } catch (const runtime_error
&e
) {
930 g_log
<<Logger::Error
<<"Unable to read 'failed-soa-retry' value: "<<e
.what()<<endl
;
933 config
["failed-soa-retry"] = 30;
936 if (config
["tcp-in-threads"]) {
938 config
["tcp-in-threads"].as
<uint16_t>();
939 } catch (const runtime_error
&e
) {
940 g_log
<<Logger::Error
<<"Unable to read 'tcp-in-threads' value: "<<e
.what()<<endl
;
943 config
["tcp-in-threads"] = 10;
946 if (config
["listen"]) {
948 config
["listen"].as
<vector
<ComboAddress
>>();
949 } catch (const runtime_error
&e
) {
950 g_log
<<Logger::Error
<<"Unable to read 'listen' value: "<<e
.what()<<endl
;
954 config
["listen"].push_back("127.0.0.1:53");
955 config
["listen"].push_back("[::1]:53");
960 config
["acl"].as
<vector
<string
>>();
961 } catch (const runtime_error
&e
) {
962 g_log
<<Logger::Error
<<"Unable to read 'acl' value: "<<e
.what()<<endl
;
966 config
["acl"].push_back("127.0.0.0/8");
967 config
["acl"].push_back("::1/128");
970 if (config
["work-dir"]) {
972 config
["work-dir"].as
<string
>();
973 } catch(const runtime_error
&e
) {
974 g_log
<<Logger::Error
<<"Unable to read 'work-dir' value: "<<e
.what()<<endl
;
979 config
["work-dir"] = getcwd(tmp
, sizeof(tmp
)) ? string(tmp
) : "";;
984 config
["uid"].as
<string
>();
985 } catch(const runtime_error
&e
) {
986 g_log
<<Logger::Error
<<"Unable to read 'uid' value: "<<e
.what()<<endl
;
993 config
["gid"].as
<string
>();
994 } catch(const runtime_error
&e
) {
995 g_log
<<Logger::Error
<<"Unable to read 'gid' value: "<<e
.what()<<endl
;
1000 if (config
["domains"]) {
1001 if (config
["domains"].size() == 0) {
1002 g_log
<<Logger::Error
<<"No domains configured"<<endl
;
1005 for (auto const &domain
: config
["domains"]) {
1007 if (!domain
["domain"]) {
1008 g_log
<<Logger::Error
<<"An entry in 'domains' is missing a 'domain' key!"<<endl
;
1012 domain
["domain"].as
<DNSName
>();
1013 } catch (const runtime_error
&e
) {
1014 g_log
<<Logger::Error
<<"Unable to read domain '"<<domain
["domain"].as
<string
>()<<"': "<<e
.what()<<endl
;
1017 if (!domain
["master"]) {
1018 g_log
<<Logger::Error
<<"Domain '"<<domain
["domain"].as
<string
>()<<"' has no master configured!"<<endl
;
1022 domain
["master"].as
<ComboAddress
>();
1023 } catch (const runtime_error
&e
) {
1024 g_log
<<Logger::Error
<<"Unable to read domain '"<<domain
["domain"].as
<string
>()<<"' master address: "<<e
.what()<<endl
;
1029 g_log
<<Logger::Error
<<"No domains configured"<<endl
;
1033 if (config
["compress"]) {
1035 config
["compress"].as
<bool>();
1037 catch (const runtime_error
&e
) {
1038 g_log
<<Logger::Error
<<"Unable to read 'compress' value: "<<e
.what()<<endl
;
1043 config
["compress"] = false;
1049 int main(int argc
, char** argv
) {
1050 g_log
.setLoglevel(Logger::Notice
);
1051 g_log
.toConsole(Logger::Notice
);
1052 g_log
.setPrefixed(true);
1053 g_log
.disableSyslog(true);
1054 g_log
.setTimestamps(false);
1055 po::variables_map g_vm
;
1057 po::options_description
desc("IXFR distribution tool");
1059 ("help", "produce help message")
1060 ("version", "Display the version of ixfrdist")
1061 ("verbose", "Be verbose")
1062 ("debug", "Be even more verbose")
1063 ("config", po::value
<string
>()->default_value(SYSCONFDIR
+ string("/ixfrdist.yml")), "Configuration file to use")
1066 po::store(po::command_line_parser(argc
, argv
).options(desc
).run(), g_vm
);
1069 if (g_vm
.count("help") > 0) {
1071 return EXIT_SUCCESS
;
1074 if (g_vm
.count("version") > 0) {
1075 cout
<<"ixfrdist "<<VERSION
<<endl
;
1076 return EXIT_SUCCESS
;
1078 } catch (po::error
&e
) {
1079 g_log
<<Logger::Error
<<e
.what()<<". See `ixfrdist --help` for valid options"<<endl
;
1080 return(EXIT_FAILURE
);
1083 bool had_error
= false;
1085 if (g_vm
.count("verbose")) {
1086 g_log
.setLoglevel(Logger::Info
);
1087 g_log
.toConsole(Logger::Info
);
1090 if (g_vm
.count("debug") > 0) {
1091 g_log
.setLoglevel(Logger::Debug
);
1092 g_log
.toConsole(Logger::Debug
);
1095 g_log
<<Logger::Notice
<<"IXFR distributor version "<<VERSION
<<" starting up!"<<endl
;
1098 if (!parseAndCheckConfig(g_vm
["config"].as
<string
>(), config
)) {
1099 // parseAndCheckConfig already logged whatever was wrong
1100 return EXIT_FAILURE
;
1103 /* From hereon out, we known that all the values in config are valid. */
1105 for (auto const &domain
: config
["domains"]) {
1106 set
<ComboAddress
> s
;
1107 s
.insert(domain
["master"].as
<ComboAddress
>());
1108 g_domainConfigs
[domain
["domain"].as
<DNSName
>()].masters
= s
;
1111 for (const auto &addr
: config
["acl"].as
<vector
<string
>>()) {
1113 g_acl
.addMask(addr
);
1114 } catch (const NetmaskException
&e
) {
1115 g_log
<<Logger::Error
<<e
.reason
<<endl
;
1119 g_log
<<Logger::Notice
<<"ACL set to "<<g_acl
.toString()<<"."<<endl
;
1121 if (config
["compress"]) {
1122 g_compress
= config
["compress"].as
<bool>();
1124 g_log
<<Logger::Notice
<<"Record compression is enabled."<<endl
;
1128 FDMultiplexer
* fdm
= FDMultiplexer::getMultiplexerSilent();
1129 if (fdm
== nullptr) {
1130 g_log
<<Logger::Error
<<"Could not enable a multiplexer for the listen sockets!"<<endl
;
1131 return EXIT_FAILURE
;
1134 set
<int> allSockets
;
1135 for (const auto& addr
: config
["listen"].as
<vector
<ComboAddress
>>()) {
1136 for (const auto& stype
: {SOCK_DGRAM
, SOCK_STREAM
}) {
1138 int s
= SSocket(addr
.sin4
.sin_family
, stype
, 0);
1142 if (stype
== SOCK_STREAM
) {
1143 SListen(s
, 30); // TODO make this configurable
1145 fdm
->addReadFD(s
, stype
== SOCK_DGRAM
? handleUDPRequest
: handleTCPRequest
);
1146 allSockets
.insert(s
);
1147 } catch(runtime_error
&e
) {
1148 g_log
<<Logger::Error
<<e
.what()<<endl
;
1157 if (config
["gid"]) {
1158 string gid
= config
["gid"].as
<string
>();
1159 if (!(newgid
= atoi(gid
.c_str()))) {
1160 struct group
*gr
= getgrnam(gid
.c_str());
1161 if (gr
== nullptr) {
1162 g_log
<<Logger::Error
<<"Can not determine group-id for gid "<<gid
<<endl
;
1165 newgid
= gr
->gr_gid
;
1168 g_log
<<Logger::Notice
<<"Dropping effective group-id to "<<newgid
<<endl
;
1169 if (setgid(newgid
) < 0) {
1170 g_log
<<Logger::Error
<<"Could not set group id to "<<newgid
<<": "<<stringerror()<<endl
;
1177 if (config
["uid"]) {
1178 string uid
= config
["uid"].as
<string
>();
1179 if (!(newuid
= atoi(uid
.c_str()))) {
1180 struct passwd
*pw
= getpwnam(uid
.c_str());
1181 if (pw
== nullptr) {
1182 g_log
<<Logger::Error
<<"Can not determine user-id for uid "<<uid
<<endl
;
1185 newuid
= pw
->pw_uid
;
1189 struct passwd
*pw
= getpwuid(newuid
);
1190 if (pw
== nullptr) {
1191 if (setgroups(0, nullptr) < 0) {
1192 g_log
<<Logger::Error
<<"Unable to drop supplementary gids: "<<stringerror()<<endl
;
1196 if (initgroups(pw
->pw_name
, newgid
) < 0) {
1197 g_log
<<Logger::Error
<<"Unable to set supplementary groups: "<<stringerror()<<endl
;
1202 g_log
<<Logger::Notice
<<"Dropping effective user-id to "<<newuid
<<endl
;
1203 if (setuid(newuid
) < 0) {
1204 g_log
<<Logger::Error
<<"Could not set user id to "<<newuid
<<": "<<stringerror()<<endl
;
1210 // We have already sent the errors to stderr, just die
1211 return EXIT_FAILURE
;
1214 // It all starts here
1215 signal(SIGTERM
, handleSignal
);
1216 signal(SIGINT
, handleSignal
);
1217 signal(SIGPIPE
, SIG_IGN
);
1219 // Init the things we need
1224 std::thread
ut(updateThread
,
1225 config
["work-dir"].as
<string
>(),
1226 config
["keep"].as
<uint16_t>(),
1227 config
["axfr-timeout"].as
<uint16_t>(),
1228 config
["failed-soa-retry"].as
<uint16_t>());
1230 vector
<std::thread
> tcpHandlers
;
1231 tcpHandlers
.reserve(config
["tcp-in-threads"].as
<uint16_t>());
1232 for (size_t i
= 0; i
< tcpHandlers
.capacity(); ++i
) {
1233 tcpHandlers
.push_back(std::thread(tcpWorker
, i
));
1238 gettimeofday(&now
, 0);
1241 g_log
<<Logger::Debug
<<"Closing listening sockets"<<endl
;
1242 for (const int& fd
: allSockets
) {
1245 } catch(PDNSException
&e
) {
1246 g_log
<<Logger::Error
<<e
.reason
<<endl
;
1252 g_log
<<Logger::Debug
<<"Waiting for al threads to stop"<<endl
;
1253 g_tcpHandlerCV
.notify_all();
1255 for (auto &t
: tcpHandlers
) {
1258 g_log
<<Logger::Notice
<<"IXFR distributor stopped"<<endl
;
1259 return EXIT_SUCCESS
;