]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/ixfrdist.cc
Merge remote-tracking branch 'origin/master' into thread-names
[thirdparty/pdns.git] / pdns / ixfrdist.cc
1 /*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
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.
8 *
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.
12 *
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.
17 *
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.
21 */
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25 #include <boost/program_options.hpp>
26 #include <arpa/inet.h>
27 #include <sys/types.h>
28 #include <grp.h>
29 #include <pwd.h>
30 #include <sys/stat.h>
31 #include <mutex>
32 #include <thread>
33 #include "threadname.hh"
34 #include <dirent.h>
35 #include <queue>
36 #include <condition_variable>
37 #include "ixfr.hh"
38 #include "ixfrutils.hh"
39 #include "resolver.hh"
40 #include "dns_random.hh"
41 #include "sstuff.hh"
42 #include "mplexer.hh"
43 #include "misc.hh"
44 #include "iputils.hh"
45 #include "logger.hh"
46 #include <yaml-cpp/yaml.h>
47
48 /* BEGIN Needed because of deeper dependencies */
49 #include "arguments.hh"
50 #include "statbag.hh"
51 StatBag S;
52
53 ArgvMap &arg()
54 {
55 static ArgvMap theArg;
56 return theArg;
57 }
58 /* END Needed because of deeper dependencies */
59
60 // Allows reading/writing ComboAddresses and DNSNames in YAML-cpp
61 namespace YAML {
62 template<>
63 struct convert<ComboAddress> {
64 static Node encode(const ComboAddress& rhs) {
65 return Node(rhs.toStringWithPort());
66 }
67 static bool decode(const Node& node, ComboAddress& rhs) {
68 if (!node.IsScalar()) {
69 return false;
70 }
71 try {
72 rhs = ComboAddress(node.as<string>(), 53);
73 return true;
74 } catch(const runtime_error &e) {
75 return false;
76 } catch (const PDNSException &e) {
77 return false;
78 }
79 }
80 };
81
82 template<>
83 struct convert<DNSName> {
84 static Node encode(const DNSName& rhs) {
85 return Node(rhs.toStringRootDot());
86 }
87 static bool decode(const Node& node, DNSName& rhs) {
88 if (!node.IsScalar()) {
89 return false;
90 }
91 try {
92 rhs = DNSName(node.as<string>());
93 return true;
94 } catch(const runtime_error &e) {
95 return false;
96 } catch (const PDNSException &e) {
97 return false;
98 }
99 }
100 };
101 } // namespace YAML
102
103 struct ixfrdiff_t {
104 shared_ptr<SOARecordContent> oldSOA;
105 shared_ptr<SOARecordContent> newSOA;
106 vector<DNSRecord> removals;
107 vector<DNSRecord> additions;
108 };
109
110 struct ixfrinfo_t {
111 shared_ptr<SOARecordContent> soa; // The SOA of the latestAXFR
112 records_t latestAXFR; // The most recent AXFR
113 vector<std::shared_ptr<ixfrdiff_t>> ixfrDiffs;
114 };
115
116 // Why a struct? This way we can add more options to a domain in the future
117 struct ixfrdistdomain_t {
118 set<ComboAddress> masters; // A set so we can do multiple master addresses in the future
119 };
120
121 // This contains the configuration for each domain
122 static map<DNSName, ixfrdistdomain_t> g_domainConfigs;
123
124 // Map domains and their data
125 static std::map<DNSName, std::shared_ptr<ixfrinfo_t>> g_soas;
126 static std::mutex g_soas_mutex;
127
128 // Condition variable for TCP handling
129 static std::condition_variable g_tcpHandlerCV;
130 static std::queue<pair<int, ComboAddress>> g_tcpRequestFDs;
131 static std::mutex g_tcpRequestFDsMutex;
132
133 namespace po = boost::program_options;
134
135 static bool g_exiting = false;
136
137 static NetmaskGroup g_acl;
138 static bool g_compress = false;
139
140 static void handleSignal(int signum) {
141 g_log<<Logger::Notice<<"Got "<<strsignal(signum)<<" signal";
142 if (g_exiting) {
143 g_log<<Logger::Notice<<", this is the second time we were asked to stop, forcefully exiting"<<endl;
144 exit(EXIT_FAILURE);
145 }
146 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;
147 g_exiting = true;
148 }
149
150 static void usage(po::options_description &desc) {
151 cerr << "Usage: ixfrdist [OPTION]..."<<endl;
152 cerr << desc << "\n";
153 }
154
155 // The compiler does not like using rfc1982LessThan in std::sort directly
156 static bool sortSOA(uint32_t i, uint32_t j) {
157 return rfc1982LessThan(i, j);
158 }
159
160 static void cleanUpDomain(const DNSName& domain, const uint16_t& keep, const string& workdir) {
161 string dir = workdir + "/" + domain.toString();
162 DIR *dp;
163 dp = opendir(dir.c_str());
164 if (dp == nullptr) {
165 return;
166 }
167 vector<uint32_t> zoneVersions;
168 struct dirent *d;
169 while ((d = readdir(dp)) != nullptr) {
170 if(!strcmp(d->d_name, ".") || !strcmp(d->d_name, "..")) {
171 continue;
172 }
173 zoneVersions.push_back(std::stoi(d->d_name));
174 }
175 closedir(dp);
176 g_log<<Logger::Info<<"Found "<<zoneVersions.size()<<" versions of "<<domain<<", asked to keep "<<keep<<", ";
177 if (zoneVersions.size() <= keep) {
178 g_log<<Logger::Info<<"not cleaning up"<<endl;
179 return;
180 }
181 g_log<<Logger::Info<<"cleaning up the oldest "<<zoneVersions.size() - keep<<endl;
182
183 // Sort the versions
184 std::sort(zoneVersions.begin(), zoneVersions.end(), sortSOA);
185
186 // And delete all the old ones
187 {
188 // Lock to ensure no one reads this.
189 std::lock_guard<std::mutex> guard(g_soas_mutex);
190 for (auto iter = zoneVersions.cbegin(); iter != zoneVersions.cend() - keep; ++iter) {
191 string fname = dir + "/" + std::to_string(*iter);
192 g_log<<Logger::Debug<<"Removing "<<fname<<endl;
193 unlink(fname.c_str());
194 }
195 }
196 }
197
198 static shared_ptr<SOARecordContent> getSOAFromRecords(const records_t& records) {
199 for (const auto& dnsrecord : records) {
200 if (dnsrecord.d_type == QType::SOA) {
201 auto soa = getRR<SOARecordContent>(dnsrecord);
202 if (soa == nullptr) {
203 throw PDNSException("Unable to determine SOARecordContent from old records");
204 }
205 return soa;
206 }
207 }
208 throw PDNSException("No SOA in supplied records");
209 }
210
211 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) {
212 set_difference(from.cbegin(), from.cend(), to.cbegin(), to.cend(), back_inserter(diff->removals), from.value_comp());
213 set_difference(to.cbegin(), to.cend(), from.cbegin(), from.cend(), back_inserter(diff->additions), from.value_comp());
214 diff->oldSOA = fromSOA;
215 if (fromSOA == nullptr) {
216 diff->oldSOA = getSOAFromRecords(from);
217 }
218 diff->newSOA = toSOA;
219 if (toSOA == nullptr) {
220 diff->newSOA = getSOAFromRecords(to);
221 }
222 }
223
224 /* you can _never_ alter the content of the resulting shared pointer */
225 static std::shared_ptr<ixfrinfo_t> getCurrentZoneInfo(const DNSName& domain)
226 {
227 std::lock_guard<std::mutex> guard(g_soas_mutex);
228 return g_soas[domain];
229 }
230
231 static void updateCurrentZoneInfo(const DNSName& domain, std::shared_ptr<ixfrinfo_t>& newInfo)
232 {
233 std::lock_guard<std::mutex> guard(g_soas_mutex);
234 g_soas[domain] = newInfo;
235 }
236
237 void updateThread(const string& workdir, const uint16_t& keep, const uint16_t& axfrTimeout, const uint16_t& soaRetry) {
238 setThreadName("ixfrdist/update");
239 std::map<DNSName, time_t> lastCheck;
240
241 // Initialize the serials we have
242 for (const auto &domainConfig : g_domainConfigs) {
243 DNSName domain = domainConfig.first;
244 lastCheck[domain] = 0;
245 string dir = workdir + "/" + domain.toString();
246 try {
247 g_log<<Logger::Info<<"Trying to initially load domain "<<domain<<" from disk"<<endl;
248 auto serial = getSerialsFromDir(dir);
249 shared_ptr<SOARecordContent> soa;
250 {
251 string fname = workdir + "/" + domain.toString() + "/" + std::to_string(serial);
252 loadSOAFromDisk(domain, fname, soa);
253 records_t records;
254 if (soa != nullptr) {
255 loadZoneFromDisk(records, fname, domain);
256 }
257 auto zoneInfo = std::make_shared<ixfrinfo_t>();
258 zoneInfo->latestAXFR = std::move(records);
259 zoneInfo->soa = soa;
260 updateCurrentZoneInfo(domain, zoneInfo);
261 }
262 if (soa != nullptr) {
263 g_log<<Logger::Notice<<"Loaded zone "<<domain<<" with serial "<<soa->d_st.serial<<endl;
264 // Initial cleanup
265 cleanUpDomain(domain, keep, workdir);
266 }
267 } catch (runtime_error &e) {
268 // Most likely, the directory does not exist.
269 g_log<<Logger::Info<<e.what()<<", attempting to create"<<endl;
270 // Attempt to create it, if _that_ fails, there is no hope
271 if (mkdir(dir.c_str(), 0777) == -1 && errno != EEXIST) {
272 g_log<<Logger::Error<<"Could not create '"<<dir<<"': "<<strerror(errno)<<endl;
273 exit(EXIT_FAILURE);
274 }
275 }
276 }
277
278 g_log<<Logger::Notice<<"Update Thread started"<<endl;
279
280 while (true) {
281 if (g_exiting) {
282 g_log<<Logger::Notice<<"UpdateThread stopped"<<endl;
283 break;
284 }
285 time_t now = time(nullptr);
286 for (const auto &domainConfig : g_domainConfigs) {
287
288 if (g_exiting) {
289 break;
290 }
291
292 DNSName domain = domainConfig.first;
293 shared_ptr<SOARecordContent> current_soa;
294 const auto& zoneInfo = getCurrentZoneInfo(domain);
295 if (zoneInfo != nullptr) {
296 current_soa = zoneInfo->soa;
297 }
298
299 auto& zoneLastCheck = lastCheck[domain];
300 if ((current_soa != nullptr && now - zoneLastCheck < current_soa->d_st.refresh) || // Only check if we have waited `refresh` seconds
301 (current_soa == nullptr && now - zoneLastCheck < soaRetry)) { // Or if we could not get an update at all still, every 30 seconds
302 continue;
303 }
304
305 // TODO Keep track of 'down' masters
306 set<ComboAddress>::const_iterator it(domainConfig.second.masters.begin());
307 std::advance(it, random() % domainConfig.second.masters.size());
308 ComboAddress master = *it;
309
310 string dir = workdir + "/" + domain.toString();
311 g_log<<Logger::Info<<"Attempting to retrieve SOA Serial update for '"<<domain<<"' from '"<<master.toStringWithPort()<<"'"<<endl;
312 shared_ptr<SOARecordContent> sr;
313 try {
314 zoneLastCheck = now;
315 auto newSerial = getSerialFromMaster(master, domain, sr); // TODO TSIG
316 if(current_soa != nullptr) {
317 g_log<<Logger::Info<<"Got SOA Serial for "<<domain<<" from "<<master.toStringWithPort()<<": "<< newSerial<<", had Serial: "<<current_soa->d_st.serial;
318 if (newSerial == current_soa->d_st.serial) {
319 g_log<<Logger::Info<<", not updating."<<endl;
320 continue;
321 }
322 g_log<<Logger::Info<<", will update."<<endl;
323 }
324 } catch (runtime_error &e) {
325 g_log<<Logger::Warning<<"Unable to get SOA serial update for '"<<domain<<"' from master "<<master.toStringWithPort()<<": "<<e.what()<<endl;
326 continue;
327 }
328 // Now get the full zone!
329 g_log<<Logger::Info<<"Attempting to receive full zonedata for '"<<domain<<"'"<<endl;
330 ComboAddress local = master.isIPv4() ? ComboAddress("0.0.0.0") : ComboAddress("::");
331 TSIGTriplet tt;
332
333 // The *new* SOA
334 shared_ptr<SOARecordContent> soa;
335 records_t records;
336 try {
337 AXFRRetriever axfr(master, domain, tt, &local);
338 unsigned int nrecords=0;
339 Resolver::res_t nop;
340 vector<DNSRecord> chunk;
341 time_t t_start = time(nullptr);
342 time_t axfr_now = time(nullptr);
343 while(axfr.getChunk(nop, &chunk, (axfr_now - t_start + axfrTimeout))) {
344 for(auto& dr : chunk) {
345 if(dr.d_type == QType::TSIG)
346 continue;
347 dr.d_name.makeUsRelative(domain);
348 records.insert(dr);
349 nrecords++;
350 if (dr.d_type == QType::SOA) {
351 soa = getRR<SOARecordContent>(dr);
352 }
353 }
354 axfr_now = time(nullptr);
355 if (axfr_now - t_start > axfrTimeout) {
356 throw PDNSException("Total AXFR time exceeded!");
357 }
358 }
359 if (soa == nullptr) {
360 g_log<<Logger::Warning<<"No SOA was found in the AXFR of "<<domain<<endl;
361 continue;
362 }
363 g_log<<Logger::Notice<<"Retrieved all zone data for "<<domain<<". Received "<<nrecords<<" records."<<endl;
364 } catch (PDNSException &e) {
365 g_log<<Logger::Warning<<"Could not retrieve AXFR for '"<<domain<<"': "<<e.reason<<endl;
366 continue;
367 } catch (runtime_error &e) {
368 g_log<<Logger::Warning<<"Could not retrieve AXFR for zone '"<<domain<<"': "<<e.what()<<endl;
369 continue;
370 }
371
372 try {
373
374 writeZoneToDisk(records, domain, dir);
375 g_log<<Logger::Notice<<"Wrote zonedata for "<<domain<<" with serial "<<soa->d_st.serial<<" to "<<dir<<endl;
376
377 const auto oldZoneInfo = getCurrentZoneInfo(domain);
378 auto zoneInfo = std::make_shared<ixfrinfo_t>();
379
380 if (oldZoneInfo && !oldZoneInfo->latestAXFR.empty()) {
381 auto diff = std::make_shared<ixfrdiff_t>();
382 zoneInfo->ixfrDiffs = oldZoneInfo->ixfrDiffs;
383 g_log<<Logger::Debug<<"Calculating diff for "<<domain<<endl;
384 makeIXFRDiff(oldZoneInfo->latestAXFR, records, diff, oldZoneInfo->soa, soa);
385 g_log<<Logger::Debug<<"Calculated diff for "<<domain<<", we had "<<diff->removals.size()<<" removals and "<<diff->additions.size()<<" additions"<<endl;
386 zoneInfo->ixfrDiffs.push_back(std::move(diff));
387 }
388
389 // Clean up the diffs
390 while (zoneInfo->ixfrDiffs.size() > keep) {
391 zoneInfo->ixfrDiffs.erase(zoneInfo->ixfrDiffs.begin());
392 }
393
394 g_log<<Logger::Debug<<"Zone "<<domain<<" previously contained "<<(oldZoneInfo ? oldZoneInfo->latestAXFR.size() : 0)<<" entries, "<<records.size()<<" now"<<endl;
395 zoneInfo->latestAXFR = std::move(records);
396 zoneInfo->soa = soa;
397 updateCurrentZoneInfo(domain, zoneInfo);
398 } catch (PDNSException &e) {
399 g_log<<Logger::Warning<<"Could not save zone '"<<domain<<"' to disk: "<<e.reason<<endl;
400 } catch (runtime_error &e) {
401 g_log<<Logger::Warning<<"Could not save zone '"<<domain<<"' to disk: "<<e.what()<<endl;
402 }
403
404 // Now clean up the directory
405 cleanUpDomain(domain, keep, workdir);
406 } /* for (const auto &domain : domains) */
407 sleep(1);
408 } /* while (true) */
409 } /* updateThread */
410
411 static bool checkQuery(const MOADNSParser& mdp, const ComboAddress& saddr, const bool udp = true, const string& logPrefix="") {
412 vector<string> info_msg;
413
414 g_log<<Logger::Debug<<logPrefix<<"Had "<<mdp.d_qname<<"|"<<QType(mdp.d_qtype).getName()<<" query from "<<saddr.toStringWithPort()<<endl;
415
416 if (udp && mdp.d_qtype != QType::SOA && mdp.d_qtype != QType::IXFR) {
417 info_msg.push_back("QType is unsupported (" + QType(mdp.d_qtype).getName() + " is not in {SOA,IXFR})");
418 }
419
420 if (!udp && mdp.d_qtype != QType::SOA && mdp.d_qtype != QType::IXFR && mdp.d_qtype != QType::AXFR) {
421 info_msg.push_back("QType is unsupported (" + QType(mdp.d_qtype).getName() + " is not in {SOA,IXFR,AXFR})");
422 }
423
424 {
425 if (g_domainConfigs.find(mdp.d_qname) == g_domainConfigs.end()) {
426 info_msg.push_back("Domain name '" + mdp.d_qname.toLogString() + "' is not configured for distribution");
427 }
428
429 const auto zoneInfo = getCurrentZoneInfo(mdp.d_qname);
430 if (zoneInfo == nullptr) {
431 info_msg.push_back("Domain has not been transferred yet");
432 }
433 }
434
435 if (!info_msg.empty()) {
436 g_log<<Logger::Warning<<logPrefix<<"Ignoring "<<mdp.d_qname<<"|"<<QType(mdp.d_qtype).getName()<<" query from "<<saddr.toStringWithPort();
437 g_log<<Logger::Warning<<": ";
438 bool first = true;
439 for (const auto& s : info_msg) {
440 if (!first) {
441 g_log<<Logger::Warning<<", ";
442 first = false;
443 }
444 g_log<<Logger::Warning<<s;
445 }
446 g_log<<Logger::Warning<<endl;
447 return false;
448 }
449
450 return true;
451 }
452
453 /*
454 * Returns a vector<uint8_t> that represents the full response to a SOA
455 * query. QNAME is read from mdp.
456 */
457 static bool makeSOAPacket(const MOADNSParser& mdp, vector<uint8_t>& packet) {
458
459 auto zoneInfo = getCurrentZoneInfo(mdp.d_qname);
460 if (zoneInfo == nullptr) {
461 return false;
462 }
463
464 DNSPacketWriter pw(packet, mdp.d_qname, mdp.d_qtype);
465 pw.getHeader()->id = mdp.d_header.id;
466 pw.getHeader()->rd = mdp.d_header.rd;
467 pw.getHeader()->qr = 1;
468
469 pw.startRecord(mdp.d_qname, QType::SOA);
470 zoneInfo->soa->toPacket(pw);
471 pw.commit();
472
473 return true;
474 }
475
476 static vector<uint8_t> getSOAPacket(const MOADNSParser& mdp, const shared_ptr<SOARecordContent>& soa) {
477 vector<uint8_t> packet;
478 DNSPacketWriter pw(packet, mdp.d_qname, mdp.d_qtype);
479 pw.getHeader()->id = mdp.d_header.id;
480 pw.getHeader()->rd = mdp.d_header.rd;
481 pw.getHeader()->qr = 1;
482
483 // Add the first SOA
484 pw.startRecord(mdp.d_qname, QType::SOA);
485 soa->toPacket(pw);
486 pw.commit();
487 return packet;
488 }
489
490 static bool sendPacketOverTCP(int fd, const std::vector<uint8_t>& packet)
491 {
492 char sendBuf[2];
493 sendBuf[0]=packet.size()/256;
494 sendBuf[1]=packet.size()%256;
495
496 ssize_t send = writen2(fd, sendBuf, 2);
497 send += writen2(fd, &packet[0], packet.size());
498 return true;
499 }
500
501 static bool addRecordToWriter(DNSPacketWriter& pw, const DNSName& zoneName, const DNSRecord& record, bool compress)
502 {
503 pw.startRecord(record.d_name + zoneName, record.d_type, record.d_ttl, QClass::IN, DNSResourceRecord::ANSWER, compress);
504 record.d_content->toPacket(pw);
505 if (pw.size() > 65535) {
506 pw.rollback();
507 return false;
508 }
509 return true;
510 }
511
512 template <typename T> static bool sendRecordsOverTCP(int fd, const MOADNSParser& mdp, const T& records)
513 {
514 vector<uint8_t> packet;
515
516 for (auto it = records.cbegin(); it != records.cend();) {
517 bool recordsAdded = false;
518 packet.clear();
519 DNSPacketWriter pw(packet, mdp.d_qname, mdp.d_qtype);
520 pw.getHeader()->id = mdp.d_header.id;
521 pw.getHeader()->rd = mdp.d_header.rd;
522 pw.getHeader()->qr = 1;
523
524 while (it != records.cend()) {
525 if (it->d_type == QType::SOA) {
526 it++;
527 continue;
528 }
529
530 if (addRecordToWriter(pw, mdp.d_qname, *it, g_compress)) {
531 recordsAdded = true;
532 it++;
533 }
534 else {
535 if (recordsAdded) {
536 pw.commit();
537 sendPacketOverTCP(fd, packet);
538 }
539 if (it == records.cbegin()) {
540 /* something is wrong */
541 return false;
542 }
543
544 break;
545 }
546 }
547
548 if (it == records.cend() && recordsAdded) {
549 pw.commit();
550 sendPacketOverTCP(fd, packet);
551 }
552 }
553
554 return true;
555 }
556
557
558 static bool handleAXFR(int fd, const MOADNSParser& mdp) {
559 /* we get a shared pointer of the zone info that we can't modify, ever.
560 A newer one may arise in the meantime, but this one will stay valid
561 until we release it.
562 */
563 auto zoneInfo = getCurrentZoneInfo(mdp.d_qname);
564 if (zoneInfo == nullptr) {
565 return false;
566 }
567
568 shared_ptr<SOARecordContent> soa = zoneInfo->soa;
569 const records_t& records = zoneInfo->latestAXFR;
570
571 // Initial SOA
572 const auto soaPacket = getSOAPacket(mdp, soa);
573 if (!sendPacketOverTCP(fd, soaPacket)) {
574 return false;
575 }
576
577 if (!sendRecordsOverTCP(fd, mdp, records)) {
578 return false;
579 }
580
581 // Final SOA
582 if (!sendPacketOverTCP(fd, soaPacket)) {
583 return false;
584 }
585
586 return true;
587 }
588
589 /* Produces an IXFR if one can be made according to the rules in RFC 1995 and
590 * creates a SOA or AXFR packet when required by the RFC.
591 */
592 static bool handleIXFR(int fd, const ComboAddress& destination, const MOADNSParser& mdp, const shared_ptr<SOARecordContent>& clientSOA) {
593 vector<std::shared_ptr<ixfrdiff_t>> toSend;
594
595 /* we get a shared pointer of the zone info that we can't modify, ever.
596 A newer one may arise in the meantime, but this one will stay valid
597 until we release it.
598 */
599 auto zoneInfo = getCurrentZoneInfo(mdp.d_qname);
600 if (zoneInfo == nullptr) {
601 return false;
602 }
603
604 uint32_t ourLatestSerial = zoneInfo->soa->d_st.serial;
605
606 if (rfc1982LessThan(ourLatestSerial, clientSOA->d_st.serial) || ourLatestSerial == clientSOA->d_st.serial) {
607 /* RFC 1995 Section 2
608 * If an IXFR query with the same or newer version number than that of
609 * the server is received, it is replied to with a single SOA record of
610 * the server's current version, just as in AXFR.
611 */
612 vector<uint8_t> packet;
613 bool ret = makeSOAPacket(mdp, packet);
614 if (ret) {
615 sendPacketOverTCP(fd, packet);
616 }
617 return ret;
618 }
619
620 // as we use push_back in the updater, we know the vector is sorted as oldest first
621 bool shouldAdd = false;
622 // Get all relevant IXFR differences
623 for (const auto& diff : zoneInfo->ixfrDiffs) {
624 if (shouldAdd) {
625 toSend.push_back(diff);
626 continue;
627 }
628 if (diff->oldSOA->d_st.serial == clientSOA->d_st.serial) {
629 toSend.push_back(diff);
630 // Add all consecutive diffs
631 shouldAdd = true;
632 }
633 }
634
635 if (toSend.empty()) {
636 g_log<<Logger::Warning<<"No IXFR available from serial "<<clientSOA->d_st.serial<<" for zone "<<mdp.d_qname<<", attempting to send AXFR"<<endl;
637 return handleAXFR(fd, mdp);
638 }
639
640 std::vector<std::vector<uint8_t>> packets;
641 for (const auto& diff : toSend) {
642 /* An IXFR packet's ANSWER section looks as follows:
643 * SOA new_serial
644 * SOA old_serial
645 * ... removed records ...
646 * SOA new_serial
647 * ... added records ...
648 * SOA new_serial
649 */
650
651 const auto newSOAPacket = getSOAPacket(mdp, diff->newSOA);
652 const auto oldSOAPacket = getSOAPacket(mdp, diff->oldSOA);
653
654 if (!sendPacketOverTCP(fd, newSOAPacket)) {
655 return false;
656 }
657
658 if (!sendPacketOverTCP(fd, oldSOAPacket)) {
659 return false;
660 }
661
662 if (!sendRecordsOverTCP(fd, mdp, diff->removals)) {
663 return false;
664 }
665
666 if (!sendPacketOverTCP(fd, newSOAPacket)) {
667 return false;
668 }
669
670 if (!sendRecordsOverTCP(fd, mdp, diff->additions)) {
671 return false;
672 }
673
674 if (!sendPacketOverTCP(fd, newSOAPacket)) {
675 return false;
676 }
677 }
678
679 return true;
680 }
681
682 static bool allowedByACL(const ComboAddress& addr) {
683 return g_acl.match(addr);
684 }
685
686 static void handleUDPRequest(int fd, boost::any&) {
687 // TODO make the buffer-size configurable
688 char buf[4096];
689 ComboAddress saddr;
690 socklen_t fromlen = sizeof(saddr);
691 int res = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*) &saddr, &fromlen);
692
693 if (res == 0) {
694 g_log<<Logger::Warning<<"Got an empty message from "<<saddr.toStringWithPort()<<endl;
695 return;
696 }
697
698 if(res < 0) {
699 auto savedErrno = errno;
700 g_log<<Logger::Warning<<"Could not read message from "<<saddr.toStringWithPort()<<": "<<strerror(savedErrno)<<endl;
701 return;
702 }
703
704 if (saddr == ComboAddress("0.0.0.0", 0)) {
705 g_log<<Logger::Warning<<"Could not determine source of message"<<endl;
706 return;
707 }
708
709 if (!allowedByACL(saddr)) {
710 g_log<<Logger::Warning<<"UDP query from "<<saddr.toString()<<" is not allowed, dropping"<<endl;
711 return;
712 }
713
714 MOADNSParser mdp(true, string(buf, res));
715 if (!checkQuery(mdp, saddr)) {
716 return;
717 }
718
719 /* RFC 1995 Section 2
720 * Transport of a query may be by either UDP or TCP. If an IXFR query
721 * is via UDP, the IXFR server may attempt to reply using UDP if the
722 * entire response can be contained in a single DNS packet. If the UDP
723 * reply does not fit, the query is responded to with a single SOA
724 * record of the server's current version to inform the client that a
725 * TCP query should be initiated.
726 *
727 * Let's not complicate this with IXFR over UDP (and looking if we need to truncate etc).
728 * Just send the current SOA and let the client try over TCP
729 */
730 vector<uint8_t> packet;
731 makeSOAPacket(mdp, packet);
732 if(sendto(fd, &packet[0], packet.size(), 0, (struct sockaddr*) &saddr, fromlen) < 0) {
733 auto savedErrno = errno;
734 g_log<<Logger::Warning<<"Could not send reply for "<<mdp.d_qname<<"|"<<QType(mdp.d_qtype).getName()<<" to "<<saddr.toStringWithPort()<<": "<<strerror(savedErrno)<<endl;
735 }
736 return;
737 }
738
739 static void handleTCPRequest(int fd, boost::any&) {
740 ComboAddress saddr;
741 int cfd = 0;
742
743 try {
744 cfd = SAccept(fd, saddr);
745 setBlocking(cfd);
746 } catch(runtime_error &e) {
747 g_log<<Logger::Error<<e.what()<<endl;
748 return;
749 }
750
751 if (saddr == ComboAddress("0.0.0.0", 0)) {
752 g_log<<Logger::Warning<<"Could not determine source of message"<<endl;
753 close(cfd);
754 return;
755 }
756
757 if (!allowedByACL(saddr)) {
758 g_log<<Logger::Warning<<"TCP query from "<<saddr.toString()<<" is not allowed, dropping"<<endl;
759 close(cfd);
760 return;
761 }
762
763 {
764 std::lock_guard<std::mutex> lg(g_tcpRequestFDsMutex);
765 g_tcpRequestFDs.push({cfd, saddr});
766 }
767 g_tcpHandlerCV.notify_one();
768 }
769
770 /* Thread to handle TCP traffic
771 */
772 static void tcpWorker(int tid) {
773 setThreadName("ixfrdist/tcpWor");
774 string prefix = "TCP Worker " + std::to_string(tid) + ": ";
775
776 while(true) {
777 g_log<<Logger::Debug<<prefix<<"ready for a new request!"<<endl;
778 std::unique_lock<std::mutex> lk(g_tcpRequestFDsMutex);
779 g_tcpHandlerCV.wait(lk, []{return g_tcpRequestFDs.size() || g_exiting ;});
780 if (g_exiting) {
781 g_log<<Logger::Debug<<prefix<<"Stopping thread"<<endl;
782 break;
783 }
784 g_log<<Logger::Debug<<prefix<<"Going to handle a query"<<endl;
785 auto request = g_tcpRequestFDs.front();
786 g_tcpRequestFDs.pop();
787 lk.unlock();
788
789 int cfd = request.first;
790 ComboAddress saddr = request.second;
791
792 char buf[4096];
793 ssize_t res;
794 try {
795 uint16_t toRead;
796 readn2(cfd, &toRead, sizeof(toRead));
797 toRead = std::min(ntohs(toRead), static_cast<uint16_t>(sizeof(buf)));
798 res = readn2WithTimeout(cfd, &buf, toRead, 2);
799 g_log<<Logger::Debug<<prefix<<"Had message of "<<std::to_string(toRead)<<" bytes from "<<saddr.toStringWithPort()<<endl;
800 } catch (runtime_error &e) {
801 g_log<<Logger::Warning<<prefix<<"Could not read message from "<<saddr.toStringWithPort()<<": "<<e.what()<<endl;
802 close(cfd);
803 continue;
804 }
805
806 try {
807 MOADNSParser mdp(true, string(buf, res));
808
809 if (!checkQuery(mdp, saddr, false, prefix)) {
810 close(cfd);
811 continue;
812 }
813
814 if (mdp.d_qtype == QType::SOA) {
815 vector<uint8_t> packet;
816 bool ret = makeSOAPacket(mdp, packet);
817 if (!ret) {
818 close(cfd);
819 continue;
820 }
821 sendPacketOverTCP(cfd, packet);
822 }
823 else if (mdp.d_qtype == QType::AXFR) {
824 if (!handleAXFR(cfd, mdp)) {
825 close(cfd);
826 continue;
827 }
828 }
829 else if (mdp.d_qtype == QType::IXFR) {
830 /* RFC 1995 section 3:
831 * The IXFR query packet format is the same as that of a normal DNS
832 * query, but with the query type being IXFR and the authority section
833 * containing the SOA record of client's version of the zone.
834 */
835 shared_ptr<SOARecordContent> clientSOA;
836 for (auto &answer : mdp.d_answers) {
837 // from dnsparser.hh:
838 // typedef vector<pair<DNSRecord, uint16_t > > answers_t;
839 if (answer.first.d_type == QType::SOA && answer.first.d_place == DNSResourceRecord::AUTHORITY) {
840 clientSOA = getRR<SOARecordContent>(answer.first);
841 if (clientSOA != nullptr) {
842 break;
843 }
844 }
845 } /* for (auto const &answer : mdp.d_answers) */
846
847 if (clientSOA == nullptr) {
848 g_log<<Logger::Warning<<prefix<<"IXFR request packet did not contain a SOA record in the AUTHORITY section"<<endl;
849 close(cfd);
850 continue;
851 }
852
853 if (!handleIXFR(cfd, saddr, mdp, clientSOA)) {
854 close(cfd);
855 continue;
856 }
857 } /* if (mdp.d_qtype == QType::IXFR) */
858
859 shutdown(cfd, 2);
860 } catch (MOADNSException &e) {
861 g_log<<Logger::Warning<<prefix<<"Could not parse DNS packet from "<<saddr.toStringWithPort()<<": "<<e.what()<<endl;
862 } catch (runtime_error &e) {
863 g_log<<Logger::Warning<<prefix<<"Could not write reply to "<<saddr.toStringWithPort()<<": "<<e.what()<<endl;
864 }
865 // bye!
866 close(cfd);
867
868 if (g_exiting) {
869 break;
870 }
871 }
872 }
873
874 /* Parses the configuration file in configpath into config, adding defaults for
875 * missing parameters (if applicable), returning true if the config file was
876 * good, false otherwise. Will log all issues with the config
877 */
878 static bool parseAndCheckConfig(const string& configpath, YAML::Node& config) {
879 g_log<<Logger::Info<<"Loading configuration file from "<<configpath<<endl;
880 try {
881 config = YAML::LoadFile(configpath);
882 } catch (const runtime_error &e) {
883 g_log<<Logger::Error<<"Unable to load configuration file '"<<configpath<<"': "<<e.what()<<endl;
884 return false;
885 }
886
887 bool retval = true;
888
889 if (config["keep"]) {
890 try {
891 config["keep"].as<uint16_t>();
892 } catch (const runtime_error &e) {
893 g_log<<Logger::Error<<"Unable to read 'keep' value: "<<e.what()<<endl;
894 retval = false;
895 }
896 } else {
897 config["keep"] = 20;
898 }
899
900 if (config["axfr-timeout"]) {
901 try {
902 config["axfr-timeout"].as<uint16_t>();
903 } catch (const runtime_error &e) {
904 g_log<<Logger::Error<<"Unable to read 'axfr-timeout' value: "<<e.what()<<endl;
905 }
906 } else {
907 config["axfr-timeout"] = 20;
908 }
909
910 if (config["failed-soa-retry"]) {
911 try {
912 config["failed-soa-retry"].as<uint16_t>();
913 } catch (const runtime_error &e) {
914 g_log<<Logger::Error<<"Unable to read 'failed-soa-retry' value: "<<e.what()<<endl;
915 }
916 } else {
917 config["failed-soa-retry"] = 30;
918 }
919
920 if (config["tcp-in-threads"]) {
921 try {
922 config["tcp-in-threads"].as<uint16_t>();
923 } catch (const runtime_error &e) {
924 g_log<<Logger::Error<<"Unable to read 'tcp-in-threads' value: "<<e.what()<<endl;
925 }
926 } else {
927 config["tcp-in-threads"] = 10;
928 }
929
930 if (config["listen"]) {
931 try {
932 config["listen"].as<vector<ComboAddress>>();
933 } catch (const runtime_error &e) {
934 g_log<<Logger::Error<<"Unable to read 'listen' value: "<<e.what()<<endl;
935 retval = false;
936 }
937 } else {
938 config["listen"].push_back("127.0.0.1:53");
939 config["listen"].push_back("[::1]:53");
940 }
941
942 if (config["acl"]) {
943 try {
944 config["acl"].as<vector<string>>();
945 } catch (const runtime_error &e) {
946 g_log<<Logger::Error<<"Unable to read 'acl' value: "<<e.what()<<endl;
947 retval = false;
948 }
949 } else {
950 config["acl"].push_back("127.0.0.0/8");
951 config["acl"].push_back("::1/128");
952 }
953
954 if (config["work-dir"]) {
955 try {
956 config["work-dir"].as<string>();
957 } catch(const runtime_error &e) {
958 g_log<<Logger::Error<<"Unable to read 'work-dir' value: "<<e.what()<<endl;
959 retval = false;
960 }
961 } else {
962 char tmp[512];
963 config["work-dir"] = getcwd(tmp, sizeof(tmp)) ? string(tmp) : "";;
964 }
965
966 if (config["uid"]) {
967 try {
968 config["uid"].as<string>();
969 } catch(const runtime_error &e) {
970 g_log<<Logger::Error<<"Unable to read 'uid' value: "<<e.what()<<endl;
971 retval = false;
972 }
973 }
974
975 if (config["gid"]) {
976 try {
977 config["gid"].as<string>();
978 } catch(const runtime_error &e) {
979 g_log<<Logger::Error<<"Unable to read 'gid' value: "<<e.what()<<endl;
980 retval = false;
981 }
982 }
983
984 if (config["domains"]) {
985 if (config["domains"].size() == 0) {
986 g_log<<Logger::Error<<"No domains configured"<<endl;
987 retval = false;
988 }
989 for (auto const &domain : config["domains"]) {
990 try {
991 if (!domain["domain"]) {
992 g_log<<Logger::Error<<"An entry in 'domains' is missing a 'domain' key!"<<endl;
993 retval = false;
994 continue;
995 }
996 domain["domain"].as<DNSName>();
997 } catch (const runtime_error &e) {
998 g_log<<Logger::Error<<"Unable to read domain '"<<domain["domain"].as<string>()<<"': "<<e.what()<<endl;
999 }
1000 try {
1001 if (!domain["master"]) {
1002 g_log<<Logger::Error<<"Domain '"<<domain["domain"].as<string>()<<"' has no master configured!"<<endl;
1003 retval = false;
1004 continue;
1005 }
1006 domain["master"].as<ComboAddress>();
1007 } catch (const runtime_error &e) {
1008 g_log<<Logger::Error<<"Unable to read domain '"<<domain["domain"].as<string>()<<"' master address: "<<e.what()<<endl;
1009 retval = false;
1010 }
1011 }
1012 } else {
1013 g_log<<Logger::Error<<"No domains configured"<<endl;
1014 retval = false;
1015 }
1016
1017 if (config["compress"]) {
1018 try {
1019 config["compress"].as<bool>();
1020 }
1021 catch (const runtime_error &e) {
1022 g_log<<Logger::Error<<"Unable to read 'compress' value: "<<e.what()<<endl;
1023 retval = false;
1024 }
1025 }
1026 else {
1027 config["compress"] = false;
1028 }
1029
1030 return retval;
1031 }
1032
1033 int main(int argc, char** argv) {
1034 g_log.setLoglevel(Logger::Notice);
1035 g_log.toConsole(Logger::Notice);
1036 g_log.setPrefixed(true);
1037 g_log.disableSyslog(true);
1038 g_log.setTimestamps(false);
1039 po::variables_map g_vm;
1040 try {
1041 po::options_description desc("IXFR distribution tool");
1042 desc.add_options()
1043 ("help", "produce help message")
1044 ("version", "Display the version of ixfrdist")
1045 ("verbose", "Be verbose")
1046 ("debug", "Be even more verbose")
1047 ("config", po::value<string>()->default_value(SYSCONFDIR + string("/ixfrdist.yml")), "Configuration file to use")
1048 ;
1049
1050 po::store(po::command_line_parser(argc, argv).options(desc).run(), g_vm);
1051 po::notify(g_vm);
1052
1053 if (g_vm.count("help") > 0) {
1054 usage(desc);
1055 return EXIT_SUCCESS;
1056 }
1057
1058 if (g_vm.count("version") > 0) {
1059 cout<<"ixfrdist "<<VERSION<<endl;
1060 return EXIT_SUCCESS;
1061 }
1062 } catch (po::error &e) {
1063 g_log<<Logger::Error<<e.what()<<". See `ixfrdist --help` for valid options"<<endl;
1064 return(EXIT_FAILURE);
1065 }
1066
1067 bool had_error = false;
1068
1069 if (g_vm.count("verbose")) {
1070 g_log.setLoglevel(Logger::Info);
1071 g_log.toConsole(Logger::Info);
1072 }
1073
1074 if (g_vm.count("debug") > 0) {
1075 g_log.setLoglevel(Logger::Debug);
1076 g_log.toConsole(Logger::Debug);
1077 }
1078
1079 g_log<<Logger::Notice<<"IXFR distributor version "<<VERSION<<" starting up!"<<endl;
1080
1081 YAML::Node config;
1082 if (!parseAndCheckConfig(g_vm["config"].as<string>(), config)) {
1083 // parseAndCheckConfig already logged whatever was wrong
1084 return EXIT_FAILURE;
1085 }
1086
1087 /* From hereon out, we known that all the values in config are valid. */
1088
1089 for (auto const &domain : config["domains"]) {
1090 set<ComboAddress> s;
1091 s.insert(domain["master"].as<ComboAddress>());
1092 g_domainConfigs[domain["domain"].as<DNSName>()].masters = s;
1093 }
1094
1095 for (const auto &addr : config["acl"].as<vector<string>>()) {
1096 try {
1097 g_acl.addMask(addr);
1098 } catch (const NetmaskException &e) {
1099 g_log<<Logger::Error<<e.reason<<endl;
1100 had_error = true;
1101 }
1102 }
1103 g_log<<Logger::Notice<<"ACL set to "<<g_acl.toString()<<"."<<endl;
1104
1105 if (config["compress"]) {
1106 g_compress = config["compress"].as<bool>();
1107 if (g_compress) {
1108 g_log<<Logger::Notice<<"Record compression is enabled."<<endl;
1109 }
1110 }
1111
1112 FDMultiplexer* fdm = FDMultiplexer::getMultiplexerSilent();
1113 if (fdm == nullptr) {
1114 g_log<<Logger::Error<<"Could not enable a multiplexer for the listen sockets!"<<endl;
1115 return EXIT_FAILURE;
1116 }
1117
1118 set<int> allSockets;
1119 for (const auto& addr : config["listen"].as<vector<ComboAddress>>()) {
1120 for (const auto& stype : {SOCK_DGRAM, SOCK_STREAM}) {
1121 try {
1122 int s = SSocket(addr.sin4.sin_family, stype, 0);
1123 setNonBlocking(s);
1124 setReuseAddr(s);
1125 SBind(s, addr);
1126 if (stype == SOCK_STREAM) {
1127 SListen(s, 30); // TODO make this configurable
1128 }
1129 fdm->addReadFD(s, stype == SOCK_DGRAM ? handleUDPRequest : handleTCPRequest);
1130 allSockets.insert(s);
1131 } catch(runtime_error &e) {
1132 g_log<<Logger::Error<<e.what()<<endl;
1133 had_error = true;
1134 continue;
1135 }
1136 }
1137 }
1138
1139 int newgid = 0;
1140
1141 if (config["gid"]) {
1142 string gid = config["gid"].as<string>();
1143 if (!(newgid = atoi(gid.c_str()))) {
1144 struct group *gr = getgrnam(gid.c_str());
1145 if (gr == nullptr) {
1146 g_log<<Logger::Error<<"Can not determine group-id for gid "<<gid<<endl;
1147 had_error = true;
1148 } else {
1149 newgid = gr->gr_gid;
1150 }
1151 }
1152 g_log<<Logger::Notice<<"Dropping effective group-id to "<<newgid<<endl;
1153 if (setgid(newgid) < 0) {
1154 g_log<<Logger::Error<<"Could not set group id to "<<newgid<<": "<<stringerror()<<endl;
1155 had_error = true;
1156 }
1157 }
1158
1159 int newuid = 0;
1160
1161 if (config["uid"]) {
1162 string uid = config["uid"].as<string>();
1163 if (!(newuid = atoi(uid.c_str()))) {
1164 struct passwd *pw = getpwnam(uid.c_str());
1165 if (pw == nullptr) {
1166 g_log<<Logger::Error<<"Can not determine user-id for uid "<<uid<<endl;
1167 had_error = true;
1168 } else {
1169 newuid = pw->pw_uid;
1170 }
1171 }
1172
1173 struct passwd *pw = getpwuid(newuid);
1174 if (pw == nullptr) {
1175 if (setgroups(0, nullptr) < 0) {
1176 g_log<<Logger::Error<<"Unable to drop supplementary gids: "<<stringerror()<<endl;
1177 had_error = true;
1178 }
1179 } else {
1180 if (initgroups(pw->pw_name, newgid) < 0) {
1181 g_log<<Logger::Error<<"Unable to set supplementary groups: "<<stringerror()<<endl;
1182 had_error = true;
1183 }
1184 }
1185
1186 g_log<<Logger::Notice<<"Dropping effective user-id to "<<newuid<<endl;
1187 if (setuid(newuid) < 0) {
1188 g_log<<Logger::Error<<"Could not set user id to "<<newuid<<": "<<stringerror()<<endl;
1189 had_error = true;
1190 }
1191 }
1192
1193 if (had_error) {
1194 // We have already sent the errors to stderr, just die
1195 return EXIT_FAILURE;
1196 }
1197
1198 // It all starts here
1199 signal(SIGTERM, handleSignal);
1200 signal(SIGINT, handleSignal);
1201 signal(SIGPIPE, SIG_IGN);
1202
1203 // Init the things we need
1204 reportAllTypes();
1205
1206 dns_random_init();
1207
1208 std::thread ut(updateThread,
1209 config["work-dir"].as<string>(),
1210 config["keep"].as<uint16_t>(),
1211 config["axfr-timeout"].as<uint16_t>(),
1212 config["failed-soa-retry"].as<uint16_t>());
1213
1214 vector<std::thread> tcpHandlers;
1215 tcpHandlers.reserve(config["tcp-in-threads"].as<uint16_t>());
1216 for (size_t i = 0; i < tcpHandlers.capacity(); ++i) {
1217 tcpHandlers.push_back(std::thread(tcpWorker, i));
1218 }
1219
1220 struct timeval now;
1221 for(;;) {
1222 gettimeofday(&now, 0);
1223 fdm->run(&now);
1224 if (g_exiting) {
1225 g_log<<Logger::Debug<<"Closing listening sockets"<<endl;
1226 for (const int& fd : allSockets) {
1227 try {
1228 closesocket(fd);
1229 } catch(PDNSException &e) {
1230 g_log<<Logger::Error<<e.reason<<endl;
1231 }
1232 }
1233 break;
1234 }
1235 }
1236 g_log<<Logger::Debug<<"Waiting for al threads to stop"<<endl;
1237 g_tcpHandlerCV.notify_all();
1238 ut.join();
1239 for (auto &t : tcpHandlers) {
1240 t.join();
1241 }
1242 g_log<<Logger::Notice<<"IXFR distributor stopped"<<endl;
1243 return EXIT_SUCCESS;
1244 }