/
rec-main.cc
3388 lines (2989 loc) · 143 KB
/
rec-main.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of PowerDNS or dnsdist.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <sys/stat.h>
#include "rec-main.hh"
#include "aggressive_nsec.hh"
#include "capabilities.hh"
#include "arguments.hh"
#include "dns_random.hh"
#include "rec_channel.hh"
#include "rec-tcpout.hh"
#include "version.hh"
#include "query-local-address.hh"
#include "validate-recursor.hh"
#include "pubsuffix.hh"
#include "opensslsigners.hh"
#include "ws-recursor.hh"
#include "rec-taskqueue.hh"
#include "secpoll-recursor.hh"
#include "logging.hh"
#include "dnsseckeeper.hh"
#ifdef NOD_ENABLED
#include "nod.hh"
#endif /* NOD_ENABLED */
#ifdef HAVE_LIBSODIUM
#include <sodium.h>
#include <cstddef>
#include <utility>
#endif
#ifdef HAVE_SYSTEMD
// All calls are coming form the same function, so no use for CODE_LINE, CODE_FUNC etc
#define SD_JOURNAL_SUPPRESS_LOCATION
#include <systemd/sd-daemon.h>
#include <systemd/sd-journal.h>
#endif
#ifdef HAVE_FSTRM
thread_local FrameStreamServersInfo t_frameStreamServersInfo;
thread_local FrameStreamServersInfo t_nodFrameStreamServersInfo;
#endif /* HAVE_FSTRM */
string g_programname = "pdns_recursor";
string g_pidfname;
RecursorControlChannel g_rcc; // only active in the handler thread
bool g_regressionTestMode;
#ifdef NOD_ENABLED
bool g_nodEnabled;
DNSName g_nodLookupDomain;
bool g_nodLog;
SuffixMatchNode g_nodDomainWL;
std::string g_nod_pbtag;
bool g_udrEnabled;
bool g_udrLog;
std::string g_udr_pbtag;
thread_local std::shared_ptr<nod::NODDB> t_nodDBp;
thread_local std::shared_ptr<nod::UniqueResponseDB> t_udrDBp;
#endif /* NOD_ENABLED */
std::atomic<bool> statsWanted;
uint32_t g_disthashseed;
bool g_useIncomingECS;
NetmaskGroup g_proxyProtocolACL;
boost::optional<ComboAddress> g_dns64Prefix{boost::none};
DNSName g_dns64PrefixReverse;
std::shared_ptr<SyncRes::domainmap_t> g_initialDomainMap; // new threads needs this to be setup
std::shared_ptr<NetmaskGroup> g_initialAllowFrom; // new thread needs to be setup with this
std::shared_ptr<NetmaskGroup> g_initialAllowNotifyFrom; // new threads need this to be setup
std::shared_ptr<notifyset_t> g_initialAllowNotifyFor; // new threads need this to be setup
bool g_logRPZChanges{false};
static time_t s_statisticsInterval;
static std::atomic<uint32_t> s_counter;
int g_argc;
char** g_argv;
static string s_structured_logger_backend;
static Logger::Urgency s_logUrgency;
std::shared_ptr<Logr::Logger> g_slogtcpin;
std::shared_ptr<Logr::Logger> g_slogudpin;
std::shared_ptr<Logr::Logger> g_slogudpout;
/* without reuseport, all listeners share the same sockets */
deferredAdd_t g_deferredAdds;
/* first we have the handler thread, t_id == 0 (some other
helper threads like SNMP might have t_id == 0 as well)
then the distributor threads if any
and finally the workers */
std::vector<RecThreadInfo> RecThreadInfo::s_threadInfos;
std::unique_ptr<ProxyMapping> g_proxyMapping; // new threads needs this to be setup
thread_local std::unique_ptr<ProxyMapping> t_proxyMapping;
bool RecThreadInfo::s_weDistributeQueries; // if true, 1 or more threads listen on the incoming query sockets and distribute them to workers
unsigned int RecThreadInfo::s_numDistributorThreads;
unsigned int RecThreadInfo::s_numWorkerThreads;
thread_local unsigned int RecThreadInfo::t_id;
static std::map<unsigned int, std::set<int>> parseCPUMap(Logr::log_t log)
{
std::map<unsigned int, std::set<int>> result;
const std::string value = ::arg()["cpu-map"];
if (!value.empty() && !isSettingThreadCPUAffinitySupported()) {
SLOG(g_log << Logger::Warning << "CPU mapping requested but not supported, skipping" << endl,
log->info(Logr::Warning, "CPU mapping requested but not supported, skipping"));
return result;
}
std::vector<std::string> parts;
stringtok(parts, value, " \t");
for (const auto& part : parts) {
if (part.find('=') == string::npos) {
continue;
}
try {
auto headers = splitField(part, '=');
boost::trim(headers.first);
boost::trim(headers.second);
auto threadId = pdns::checked_stoi<unsigned int>(headers.first);
std::vector<std::string> cpus;
stringtok(cpus, headers.second, ",");
for (const auto& cpu : cpus) {
int cpuId = std::stoi(cpu);
result[threadId].insert(cpuId);
}
}
catch (const std::exception& e) {
SLOG(g_log << Logger::Error << "Error parsing cpu-map entry '" << part << "': " << e.what() << endl,
log->error(Logr::Error, e.what(), "Error parsing cpu-map entry", "entry", Logging::Loggable(part)));
}
}
return result;
}
static void setCPUMap(const std::map<unsigned int, std::set<int>>& cpusMap, unsigned int n, pthread_t tid, Logr::log_t log)
{
const auto& cpuMapping = cpusMap.find(n);
if (cpuMapping == cpusMap.cend()) {
return;
}
int ret = mapThreadToCPUList(tid, cpuMapping->second);
if (ret == 0) {
if (!g_slogStructured) {
g_log << Logger::Info << "CPU affinity for thread " << n << " has been set to CPU map:";
for (const auto cpu : cpuMapping->second) {
g_log << Logger::Info << " " << cpu;
}
g_log << Logger::Info << endl;
}
else {
log->info(Logr::Info, "CPU affinity has been set", "thread", Logging::Loggable(n), "cpumap", Logging::IterLoggable(cpuMapping->second.begin(), cpuMapping->second.end()));
}
}
else {
if (!g_slogStructured) {
g_log << Logger::Warning << "Error setting CPU affinity for thread " << n << " to CPU map:";
for (const auto cpu : cpuMapping->second) {
g_log << Logger::Info << " " << cpu;
}
g_log << Logger::Info << ' ' << stringerror(ret) << endl;
}
else {
log->error(Logr::Warning, ret, "Error setting CPU affinity", "thread", Logging::Loggable(n), "cpumap", Logging::IterLoggable(cpuMapping->second.begin(), cpuMapping->second.end()));
}
}
}
static void recursorThread();
void RecThreadInfo::start(unsigned int tid, const string& tname, const std::map<unsigned int, std::set<int>>& cpusMap, Logr::log_t log)
{
name = tname;
thread = std::thread([tid, tname] {
t_id = tid;
const string threadPrefix = "rec/";
setThreadName(threadPrefix + tname);
recursorThread();
});
setCPUMap(cpusMap, tid, thread.native_handle(), log);
}
int RecThreadInfo::runThreads(Logr::log_t log)
{
int ret = EXIT_SUCCESS;
unsigned int currentThreadId = 1;
const auto cpusMap = parseCPUMap(log);
if (RecThreadInfo::numDistributors() + RecThreadInfo::numWorkers() == 1) {
SLOG(g_log << Logger::Warning << "Operating with single distributor/worker thread" << endl,
log->info(Logr::Notice, "Operating with single distributor/worker thread"));
/* This thread handles the web server, carbon, statistics and the control channel */
auto& handlerInfo = RecThreadInfo::info(0);
handlerInfo.setHandler();
handlerInfo.start(0, "web+stat", cpusMap, log);
auto& taskInfo = RecThreadInfo::info(2);
taskInfo.setTaskThread();
taskInfo.start(2, "task", cpusMap, log);
auto& info = RecThreadInfo::info(currentThreadId);
info.setListener();
info.setWorker();
RecThreadInfo::setThreadId(currentThreadId++);
recursorThread();
handlerInfo.thread.join();
if (handlerInfo.exitCode != 0) {
ret = handlerInfo.exitCode;
}
taskInfo.thread.join();
if (taskInfo.exitCode != 0) {
ret = taskInfo.exitCode;
}
}
else {
// Setup RecThreadInfo objects
unsigned int tmp = currentThreadId;
if (RecThreadInfo::weDistributeQueries()) {
for (unsigned int thread = 0; thread < RecThreadInfo::numDistributors(); ++thread) {
RecThreadInfo::info(tmp++).setListener();
}
}
for (unsigned int thread = 0; thread < RecThreadInfo::numWorkers(); ++thread) {
auto& info = RecThreadInfo::info(tmp++);
info.setListener(!RecThreadInfo::weDistributeQueries());
info.setWorker();
}
for (unsigned int thread = 0; thread < RecThreadInfo::numTaskThreads(); ++thread) {
auto& info = RecThreadInfo::info(tmp++);
info.setTaskThread();
}
// And now start the actual threads
if (RecThreadInfo::weDistributeQueries()) {
SLOG(g_log << Logger::Warning << "Launching " << RecThreadInfo::numDistributors() << " distributor threads" << endl,
log->info(Logr::Notice, "Launching distributor threads", "count", Logging::Loggable(RecThreadInfo::numDistributors())));
for (unsigned int thread = 0; thread < RecThreadInfo::numDistributors(); ++thread) {
auto& info = RecThreadInfo::info(currentThreadId);
info.start(currentThreadId++, "distr", cpusMap, log);
}
}
SLOG(g_log << Logger::Warning << "Launching " << RecThreadInfo::numWorkers() << " worker threads" << endl,
log->info(Logr::Notice, "Launching worker threads", "count", Logging::Loggable(RecThreadInfo::numWorkers())));
for (unsigned int thread = 0; thread < RecThreadInfo::numWorkers(); ++thread) {
auto& info = RecThreadInfo::info(currentThreadId);
info.start(currentThreadId++, "worker", cpusMap, log);
}
for (unsigned int thread = 0; thread < RecThreadInfo::numTaskThreads(); ++thread) {
auto& info = RecThreadInfo::info(currentThreadId);
info.start(currentThreadId++, "task", cpusMap, log);
}
/* This thread handles the web server, carbon, statistics and the control channel */
auto& info = RecThreadInfo::info(0);
info.setHandler();
info.start(0, "web+stat", cpusMap, log);
for (auto& tInfo : RecThreadInfo::infos()) {
tInfo.thread.join();
if (tInfo.exitCode != 0) {
ret = tInfo.exitCode;
}
}
}
return ret;
}
void RecThreadInfo::makeThreadPipes(Logr::log_t log)
{
auto pipeBufferSize = ::arg().asNum("distribution-pipe-buffer-size");
if (pipeBufferSize > 0) {
SLOG(g_log << Logger::Info << "Resizing the buffer of the distribution pipe to " << pipeBufferSize << endl,
log->info(Logr::Info, "Resizing the buffer of the distribution pipe", "size", Logging::Loggable(pipeBufferSize)));
}
/* thread 0 is the handler / SNMP, worker threads start at 1 */
for (unsigned int thread = 0; thread < numRecursorThreads(); ++thread) {
auto& threadInfo = info(thread);
std::array<int, 2> fileDesc{};
if (pipe(fileDesc.data()) < 0) {
unixDie("Creating pipe for inter-thread communications");
}
threadInfo.pipes.readToThread = fileDesc[0];
threadInfo.pipes.writeToThread = fileDesc[1];
// handler thread only gets first pipe, not the others
if (thread == 0) {
continue;
}
if (pipe(fileDesc.data()) < 0) {
unixDie("Creating pipe for inter-thread communications");
}
threadInfo.pipes.readFromThread = fileDesc[0];
threadInfo.pipes.writeFromThread = fileDesc[1];
if (pipe(fileDesc.data()) < 0) {
unixDie("Creating pipe for inter-thread communications");
}
threadInfo.pipes.readQueriesToThread = fileDesc[0];
threadInfo.pipes.writeQueriesToThread = fileDesc[1];
if (pipeBufferSize > 0) {
if (!setPipeBufferSize(threadInfo.pipes.writeQueriesToThread, pipeBufferSize)) {
int err = errno;
SLOG(g_log << Logger::Warning << "Error resizing the buffer of the distribution pipe for thread " << thread << " to " << pipeBufferSize << ": " << stringerror(err) << endl,
log->error(Logr::Warning, err, "Error resizing the buffer of the distribution pipe for thread", "thread", Logging::Loggable(thread), "size", Logging::Loggable(pipeBufferSize)));
auto existingSize = getPipeBufferSize(threadInfo.pipes.writeQueriesToThread);
if (existingSize > 0) {
SLOG(g_log << Logger::Warning << "The current size of the distribution pipe's buffer for thread " << thread << " is " << existingSize << endl,
log->info(Logr::Warning, "The current size of the distribution pipe's buffer for thread", "thread", Logging::Loggable(thread), "size", Logging::Loggable(existingSize)));
}
}
}
if (!setNonBlocking(threadInfo.pipes.writeQueriesToThread)) {
unixDie("Making pipe for inter-thread communications non-blocking");
}
}
}
ArgvMap& arg()
{
static ArgvMap theArg;
return theArg;
}
static FDMultiplexer* getMultiplexer(Logr::log_t log)
{
FDMultiplexer* ret = nullptr;
for (const auto& mplexer : FDMultiplexer::getMultiplexerMap()) {
try {
ret = mplexer.second(FDMultiplexer::s_maxevents);
return ret;
}
catch (FDMultiplexerException& fe) {
SLOG(g_log << Logger::Warning << "Non-fatal error initializing possible multiplexer (" << fe.what() << "), falling back" << endl,
log->error(Logr::Warning, fe.what(), "Non-fatal error initializing possible multiplexer, falling back"));
}
catch (...) {
SLOG(g_log << Logger::Warning << "Non-fatal error initializing possible multiplexer" << endl,
log->info(Logr::Warning, "Non-fatal error initializing possible multiplexer"));
}
}
SLOG(g_log << Logger::Error << "No working multiplexer found!" << endl,
log->info(Logr::Error, "No working multiplexer found!"));
_exit(1);
}
static std::shared_ptr<std::vector<std::unique_ptr<RemoteLogger>>> startProtobufServers(const ProtobufExportConfig& config, Logr::log_t log)
{
auto result = std::make_shared<std::vector<std::unique_ptr<RemoteLogger>>>();
for (const auto& server : config.servers) {
try {
auto logger = make_unique<RemoteLogger>(server, config.timeout, 100 * config.maxQueuedEntries, config.reconnectWaitTime, config.asyncConnect);
logger->setLogQueries(config.logQueries);
logger->setLogResponses(config.logResponses);
result->emplace_back(std::move(logger));
}
catch (const std::exception& e) {
SLOG(g_log << Logger::Error << "Error while starting protobuf logger to '" << server << ": " << e.what() << endl,
log->error(Logr::Error, e.what(), "Exception while starting protobuf logger", "exception", Logging::Loggable("std::exception"), "server", Logging::Loggable(server)));
}
catch (const PDNSException& e) {
SLOG(g_log << Logger::Error << "Error while starting protobuf logger to '" << server << ": " << e.reason << endl,
log->error(Logr::Error, e.reason, "Exception while starting protobuf logger", "exception", Logging::Loggable("PDNSException"), "server", Logging::Loggable(server)));
}
}
return result;
}
bool checkProtobufExport(LocalStateHolder<LuaConfigItems>& luaconfsLocal)
{
if (!luaconfsLocal->protobufExportConfig.enabled) {
if (t_protobufServers.servers) {
t_protobufServers.servers.reset();
t_protobufServers.config = luaconfsLocal->protobufExportConfig;
}
return false;
}
/* if the server was not running, or if it was running according to a
previous configuration */
if (t_protobufServers.generation < luaconfsLocal->generation && t_protobufServers.config != luaconfsLocal->protobufExportConfig) {
if (t_protobufServers.servers) {
t_protobufServers.servers.reset();
}
auto log = g_slog->withName("protobuf");
t_protobufServers.servers = startProtobufServers(luaconfsLocal->protobufExportConfig, log);
t_protobufServers.config = luaconfsLocal->protobufExportConfig;
t_protobufServers.generation = luaconfsLocal->generation;
}
return true;
}
bool checkOutgoingProtobufExport(LocalStateHolder<LuaConfigItems>& luaconfsLocal)
{
if (!luaconfsLocal->outgoingProtobufExportConfig.enabled) {
if (t_outgoingProtobufServers.servers) {
t_outgoingProtobufServers.servers.reset();
t_outgoingProtobufServers.config = luaconfsLocal->outgoingProtobufExportConfig;
}
return false;
}
/* if the server was not running, or if it was running according to a
previous configuration */
if (t_outgoingProtobufServers.generation < luaconfsLocal->generation && t_outgoingProtobufServers.config != luaconfsLocal->outgoingProtobufExportConfig) {
if (t_outgoingProtobufServers.servers) {
t_outgoingProtobufServers.servers.reset();
}
auto log = g_slog->withName("protobuf");
t_outgoingProtobufServers.servers = startProtobufServers(luaconfsLocal->outgoingProtobufExportConfig, log);
t_outgoingProtobufServers.config = luaconfsLocal->outgoingProtobufExportConfig;
t_outgoingProtobufServers.generation = luaconfsLocal->generation;
}
return true;
}
void protobufLogQuery(LocalStateHolder<LuaConfigItems>& luaconfsLocal, const boost::uuids::uuid& uniqueId, const ComboAddress& remote, const ComboAddress& local, const ComboAddress& mappedSource, const Netmask& ednssubnet, bool tcp, uint16_t queryID, size_t len, const DNSName& qname, uint16_t qtype, uint16_t qclass, const std::unordered_set<std::string>& policyTags, const std::string& requestorId, const std::string& deviceId, const std::string& deviceName, const std::map<std::string, RecursorLua4::MetaValue>& meta)
{
auto log = g_slog->withName("pblq");
if (!t_protobufServers.servers) {
return;
}
ComboAddress requestor;
if (!luaconfsLocal->protobufExportConfig.logMappedFrom) {
Netmask requestorNM(remote, remote.sin4.sin_family == AF_INET ? luaconfsLocal->protobufMaskV4 : luaconfsLocal->protobufMaskV6);
requestor = requestorNM.getMaskedNetwork();
requestor.setPort(remote.getPort());
}
else {
Netmask requestorNM(mappedSource, mappedSource.sin4.sin_family == AF_INET ? luaconfsLocal->protobufMaskV4 : luaconfsLocal->protobufMaskV6);
requestor = requestorNM.getMaskedNetwork();
requestor.setPort(mappedSource.getPort());
}
pdns::ProtoZero::RecMessage msg{128, std::string::size_type(policyTags.empty() ? 0 : 64)}; // It's a guess
msg.setType(pdns::ProtoZero::Message::MessageType::DNSQueryType);
msg.setRequest(uniqueId, requestor, local, qname, qtype, qclass, queryID, tcp ? pdns::ProtoZero::Message::TransportProtocol::TCP : pdns::ProtoZero::Message::TransportProtocol::UDP, len);
msg.setServerIdentity(SyncRes::s_serverID);
msg.setEDNSSubnet(ednssubnet, ednssubnet.isIPv4() ? luaconfsLocal->protobufMaskV4 : luaconfsLocal->protobufMaskV6);
msg.setRequestorId(requestorId);
msg.setDeviceId(deviceId);
msg.setDeviceName(deviceName);
if (!policyTags.empty()) {
msg.addPolicyTags(policyTags);
}
for (const auto& mit : meta) {
msg.setMeta(mit.first, mit.second.stringVal, mit.second.intVal);
}
std::string strMsg(msg.finishAndMoveBuf());
for (auto& server : *t_protobufServers.servers) {
remoteLoggerQueueData(*server, strMsg);
}
}
void protobufLogResponse(pdns::ProtoZero::RecMessage& message)
{
if (!t_protobufServers.servers) {
return;
}
std::string msg(message.finishAndMoveBuf());
for (auto& server : *t_protobufServers.servers) {
remoteLoggerQueueData(*server, msg);
}
}
void protobufLogResponse(const struct dnsheader* header, LocalStateHolder<LuaConfigItems>& luaconfsLocal,
const RecursorPacketCache::OptPBData& pbData, const struct timeval& tval,
bool tcp, const ComboAddress& source, const ComboAddress& destination,
const ComboAddress& mappedSource,
const EDNSSubnetOpts& ednssubnet,
const boost::uuids::uuid& uniqueId, const string& requestorId, const string& deviceId,
const string& deviceName, const std::map<std::string, RecursorLua4::MetaValue>& meta,
const RecEventTrace& eventTrace)
{
pdns::ProtoZero::RecMessage pbMessage(pbData ? pbData->d_message : "", pbData ? pbData->d_response : "", 64, 10); // The extra bytes we are going to add
// Normally we take the immutable string from the cache and append a few values, but if it's not there (can this happen?)
// we start with an empty string and append the minimal
if (!pbData) {
pbMessage.setType(pdns::ProtoZero::Message::MessageType::DNSResponseType);
pbMessage.setServerIdentity(SyncRes::s_serverID);
}
// In response part
if (g_useKernelTimestamp && tval.tv_sec != 0) {
pbMessage.setQueryTime(tval.tv_sec, tval.tv_usec);
}
else {
pbMessage.setQueryTime(g_now.tv_sec, g_now.tv_usec);
}
// In message part
if (!luaconfsLocal->protobufExportConfig.logMappedFrom) {
Netmask requestorNM(source, source.sin4.sin_family == AF_INET ? luaconfsLocal->protobufMaskV4 : luaconfsLocal->protobufMaskV6);
auto requestor = requestorNM.getMaskedNetwork();
pbMessage.setFrom(requestor);
pbMessage.setFromPort(source.getPort());
}
else {
Netmask requestorNM(mappedSource, mappedSource.sin4.sin_family == AF_INET ? luaconfsLocal->protobufMaskV4 : luaconfsLocal->protobufMaskV6);
auto requestor = requestorNM.getMaskedNetwork();
pbMessage.setFrom(requestor);
pbMessage.setFromPort(mappedSource.getPort());
}
pbMessage.setMessageIdentity(uniqueId);
pbMessage.setTo(destination);
pbMessage.setSocketProtocol(tcp ? pdns::ProtoZero::Message::TransportProtocol::TCP : pdns::ProtoZero::Message::TransportProtocol::UDP);
pbMessage.setId(header->id);
pbMessage.setTime();
pbMessage.setEDNSSubnet(ednssubnet.source, ednssubnet.source.isIPv4() ? luaconfsLocal->protobufMaskV4 : luaconfsLocal->protobufMaskV6);
pbMessage.setRequestorId(requestorId);
pbMessage.setDeviceId(deviceId);
pbMessage.setDeviceName(deviceName);
pbMessage.setToPort(destination.getPort());
for (const auto& metaItem : meta) {
pbMessage.setMeta(metaItem.first, metaItem.second.stringVal, metaItem.second.intVal);
}
#ifdef NOD_ENABLED
if (g_nodEnabled) {
pbMessage.setNewlyObservedDomain(false);
}
#endif
if (eventTrace.enabled() && (SyncRes::s_event_trace_enabled & SyncRes::event_trace_to_pb) != 0) {
pbMessage.addEvents(eventTrace);
}
protobufLogResponse(pbMessage);
}
#ifdef HAVE_FSTRM
static std::shared_ptr<std::vector<std::unique_ptr<FrameStreamLogger>>> startFrameStreamServers(const FrameStreamExportConfig& config, Logr::log_t log)
{
auto result = std::make_shared<std::vector<std::unique_ptr<FrameStreamLogger>>>();
for (const auto& server : config.servers) {
try {
std::unordered_map<string, unsigned> options;
options["bufferHint"] = config.bufferHint;
options["flushTimeout"] = config.flushTimeout;
options["inputQueueSize"] = config.inputQueueSize;
options["outputQueueSize"] = config.outputQueueSize;
options["queueNotifyThreshold"] = config.queueNotifyThreshold;
options["reopenInterval"] = config.reopenInterval;
unique_ptr<FrameStreamLogger> fsl = nullptr;
try {
ComboAddress address(server);
fsl = make_unique<FrameStreamLogger>(address.sin4.sin_family, address.toStringWithPort(), true, options);
}
catch (const PDNSException& e) {
fsl = make_unique<FrameStreamLogger>(AF_UNIX, server, true, options);
}
fsl->setLogQueries(config.logQueries);
fsl->setLogResponses(config.logResponses);
fsl->setLogNODs(config.logNODs);
fsl->setLogUDRs(config.logUDRs);
result->emplace_back(std::move(fsl));
}
catch (const std::exception& e) {
SLOG(g_log << Logger::Error << "Error while starting dnstap framestream logger to '" << server << ": " << e.what() << endl,
log->error(Logr::Error, e.what(), "Exception while starting dnstap framestream logger", "exception", Logging::Loggable("std::exception"), "server", Logging::Loggable(server)));
}
catch (const PDNSException& e) {
SLOG(g_log << Logger::Error << "Error while starting dnstap framestream logger to '" << server << ": " << e.reason << endl,
log->error(Logr::Error, e.reason, "Exception while starting dnstap framestream logger", "exception", Logging::Loggable("PDNSException"), "server", Logging::Loggable(server)));
}
}
return result;
}
static void asyncFrameStreamLoggersCleanup(std::shared_ptr<std::vector<std::unique_ptr<FrameStreamLogger>>>&& servers)
{
auto thread = std::thread([&] {
servers.reset();
});
thread.detach();
}
bool checkFrameStreamExport(LocalStateHolder<LuaConfigItems>& luaconfsLocal, const FrameStreamExportConfig& config, FrameStreamServersInfo& serverInfos)
{
if (!config.enabled) {
if (serverInfos.servers) {
// dt's take care of cleanup
asyncFrameStreamLoggersCleanup(std::move(serverInfos.servers));
serverInfos.config = config;
}
return false;
}
/* if the server was not running, or if it was running according to a previous
* configuration
*/
if (serverInfos.generation < luaconfsLocal->generation && serverInfos.config != config) {
if (serverInfos.servers) {
// dt's take care of cleanup
asyncFrameStreamLoggersCleanup(std::move(serverInfos.servers));
}
auto dnsTapLog = g_slog->withName("dnstap");
serverInfos.servers = startFrameStreamServers(config, dnsTapLog);
serverInfos.config = config;
serverInfos.generation = luaconfsLocal->generation;
}
return true;
}
#endif /* HAVE_FSTRM */
static void makeControlChannelSocket(int processNum = -1)
{
string sockname = ::arg()["socket-dir"] + "/" + g_programname;
if (processNum >= 0) {
sockname += "." + std::to_string(processNum);
}
sockname += ".controlsocket";
g_rcc.listen(sockname);
uid_t sockowner = -1;
gid_t sockgroup = -1;
if (!::arg().isEmpty("socket-group")) {
sockgroup = ::arg().asGid("socket-group");
}
if (!::arg().isEmpty("socket-owner")) {
sockowner = ::arg().asUid("socket-owner");
}
if (sockgroup != static_cast<gid_t>(-1) || sockowner != static_cast<uid_t>(-1)) {
if (chown(sockname.c_str(), sockowner, sockgroup) < 0) {
unixDie("Failed to chown control socket");
}
}
// do mode change if socket-mode is given
if (!::arg().isEmpty("socket-mode")) {
mode_t sockmode = ::arg().asMode("socket-mode");
if (chmod(sockname.c_str(), sockmode) < 0) {
unixDie("Failed to chmod control socket");
}
}
}
static void writePid(Logr::log_t log)
{
if (!::arg().mustDo("write-pid")) {
return;
}
ofstream ostr(g_pidfname.c_str(), std::ios_base::app);
if (ostr) {
ostr << Utility::getpid() << endl;
}
else {
int err = errno;
SLOG(g_log << Logger::Error << "Writing pid for " << Utility::getpid() << " to " << g_pidfname << " failed: " << stringerror(err) << endl,
log->error(Logr::Error, err, "Writing pid failed", "pid", Logging::Loggable(Utility::getpid()), "file", Logging::Loggable(g_pidfname)));
}
}
static void checkSocketDir(Logr::log_t log)
{
string dir(::arg()["socket-dir"]);
string msg;
struct stat dirStat = {};
if (stat(dir.c_str(), &dirStat) == -1) {
msg = "it does not exist or cannot access";
}
else if (!S_ISDIR(dirStat.st_mode)) {
msg = "it is not a directory";
}
else if (access(dir.c_str(), R_OK | W_OK | X_OK) != 0) {
msg = "cannot read, write or search";
}
else {
return;
}
dir = ::arg()["chroot"] + dir;
SLOG(g_log << Logger::Error << "Problem with socket directory " << dir << ": " << msg << "; see https://docs.powerdns.com/recursor/upgrade.html#x-to-4-3-0" << endl,
log->error(Logr::Error, msg, "Problem with socket directory, see https://docs.powerdns.com/recursor/upgrade.html#x-to-4-3-0", "dir", Logging::Loggable(dir)));
_exit(1);
}
#ifdef NOD_ENABLED
static void setupNODThread(Logr::log_t log)
{
if (g_nodEnabled) {
uint32_t num_cells = ::arg().asNum("new-domain-db-size");
t_nodDBp = std::make_shared<nod::NODDB>(num_cells);
try {
t_nodDBp->setCacheDir(::arg()["new-domain-history-dir"]);
}
catch (const PDNSException& e) {
SLOG(g_log << Logger::Error << "new-domain-history-dir (" << ::arg()["new-domain-history-dir"] << ") is not readable or does not exist" << endl,
log->error(Logr::Error, e.reason, "new-domain-history-dir is not readbale or does not exists", "dir", Logging::Loggable(::arg()["new-domain-history-dir"])));
_exit(1);
}
if (!t_nodDBp->init()) {
SLOG(g_log << Logger::Error << "Could not initialize domain tracking" << endl,
log->info(Logr::Error, "Could not initialize domain tracking"));
_exit(1);
}
std::thread thread(nod::NODDB::startHousekeepingThread, t_nodDBp, std::this_thread::get_id());
thread.detach();
}
if (g_udrEnabled) {
uint32_t num_cells = ::arg().asNum("unique-response-db-size");
t_udrDBp = std::make_shared<nod::UniqueResponseDB>(num_cells);
try {
t_udrDBp->setCacheDir(::arg()["unique-response-history-dir"]);
}
catch (const PDNSException& e) {
SLOG(g_log << Logger::Error << "unique-response-history-dir (" << ::arg()["unique-response-history-dir"] << ") is not readable or does not exist" << endl,
log->info(Logr::Error, "unique-response-history-dir is not readable or does not exist", "dir", Logging::Loggable(::arg()["unique-response-history-dir"])));
_exit(1);
}
if (!t_udrDBp->init()) {
SLOG(g_log << Logger::Error << "Could not initialize unique response tracking" << endl,
log->info(Logr::Error, "Could not initialize unique response tracking"));
_exit(1);
}
std::thread thread(nod::UniqueResponseDB::startHousekeepingThread, t_udrDBp, std::this_thread::get_id());
thread.detach();
}
}
static void parseNODIgnorelist(const std::string& wlist)
{
vector<string> parts;
stringtok(parts, wlist, ",; ");
for (const auto& part : parts) {
g_nodDomainWL.add(DNSName(part));
}
}
static void setupNODGlobal()
{
// Setup NOD subsystem
g_nodEnabled = ::arg().mustDo("new-domain-tracking");
g_nodLookupDomain = DNSName(::arg()["new-domain-lookup"]);
g_nodLog = ::arg().mustDo("new-domain-log");
parseNODIgnorelist(::arg()["new-domain-whitelist"]);
parseNODIgnorelist(::arg()["new-domain-ignore-list"]);
// Setup Unique DNS Response subsystem
g_udrEnabled = ::arg().mustDo("unique-response-tracking");
g_udrLog = ::arg().mustDo("unique-response-log");
g_nod_pbtag = ::arg()["new-domain-pb-tag"];
g_udr_pbtag = ::arg()["unique-response-pb-tag"];
}
#endif /* NOD_ENABLED */
static void daemonize(Logr::log_t log)
{
if (auto pid = fork(); pid != 0) {
if (pid < 0) {
int err = errno;
SLOG(g_log << Logger::Critical << "Fork failed: " << stringerror(err) << endl,
log->error(Logr::Critical, err, "Fork failed"));
exit(1); // NOLINT(concurrency-mt-unsafe)
}
exit(0); // NOLINT(concurrency-mt-unsafe)
}
setsid();
int devNull = open("/dev/null", O_RDWR); /* open stdin */
if (devNull < 0) {
int err = errno;
SLOG(g_log << Logger::Critical << "Unable to open /dev/null: " << stringerror(err) << endl,
log->error(Logr::Critical, err, "Unable to open /dev/null"));
}
else {
dup2(devNull, 0); /* stdin */
dup2(devNull, 1); /* stderr */
dup2(devNull, 2); /* stderr */
close(devNull);
}
}
static void termIntHandler([[maybe_unused]] int arg)
{
doExit();
}
static void usr1Handler([[maybe_unused]] int arg)
{
statsWanted = true;
}
static void usr2Handler([[maybe_unused]] int arg)
{
g_quiet = !g_quiet;
SyncRes::setDefaultLogMode(g_quiet ? SyncRes::LogNone : SyncRes::Log);
::arg().set("quiet") = g_quiet ? "" : "no";
}
static void checkLinuxIPv6Limits([[maybe_unused]] Logr::log_t log)
{
#ifdef __linux__
string line;
if (readFileIfThere("/proc/sys/net/ipv6/route/max_size", &line)) {
int lim = std::stoi(line);
if (lim < 16384) {
SLOG(g_log << Logger::Error << "If using IPv6, please raise sysctl net.ipv6.route.max_size, currently set to " << lim << " which is < 16384" << endl,
log->info(Logr::Error, "If using IPv6, please raise sysctl net.ipv6.route.max_size to a size >= 16384", "current", Logging::Loggable(lim)));
}
}
#endif
}
static void checkOrFixFDS(Logr::log_t log)
{
unsigned int availFDs = getFilenumLimit();
unsigned int wantFDs = g_maxMThreads * RecThreadInfo::numWorkers() + 25; // even healthier margin then before
wantFDs += RecThreadInfo::numWorkers() * TCPOutConnectionManager::s_maxIdlePerThread;
if (wantFDs > availFDs) {
unsigned int hardlimit = getFilenumLimit(true);
if (hardlimit >= wantFDs) {
setFilenumLimit(wantFDs);
SLOG(g_log << Logger::Warning << "Raised soft limit on number of filedescriptors to " << wantFDs << " to match max-mthreads and threads settings" << endl,
log->info(Logr::Warning, "Raised soft limit on number of filedescriptors to match max-mthreads and threads settings", "limit", Logging::Loggable(wantFDs)));
}
else {
auto newval = (hardlimit - 25 - TCPOutConnectionManager::s_maxIdlePerThread) / RecThreadInfo::numWorkers();
SLOG(g_log << Logger::Warning << "Insufficient number of filedescriptors available for max-mthreads*threads setting! (" << hardlimit << " < " << wantFDs << "), reducing max-mthreads to " << newval << endl,
log->info(Logr::Warning, "Insufficient number of filedescriptors available for max-mthreads*threads setting! Reducing max-mthreads", "hardlimit", Logging::Loggable(hardlimit), "want", Logging::Loggable(wantFDs), "max-mthreads", Logging::Loggable(newval)));
g_maxMThreads = newval;
setFilenumLimit(hardlimit);
}
}
}
// static std::string s_timestampFormat = "%m-%dT%H:%M:%S";
static std::string s_timestampFormat = "%s";
static const char* toTimestampStringMilli(const struct timeval& tval, std::array<char, 64>& buf)
{
size_t len = 0;
if (s_timestampFormat != "%s") {
// strftime is not thread safe, it can access locale information
static std::mutex mutex;
auto lock = std::lock_guard(mutex);
struct tm theTime // clang-format insists on formatting it like this
{
};
len = strftime(buf.data(), buf.size(), s_timestampFormat.c_str(), localtime_r(&tval.tv_sec, &theTime));
}
if (len == 0) {
len = snprintf(buf.data(), buf.size(), "%lld", static_cast<long long>(tval.tv_sec));
}
snprintf(&buf.at(len), buf.size() - len, ".%03ld", static_cast<long>(tval.tv_usec) / 1000);
return buf.data();
}
#ifdef HAVE_SYSTEMD
static void loggerSDBackend(const Logging::Entry& entry)
{
static const set<std::string, CIStringComparePOSIX> special = {
"message",
"message_id",
"priority",
"code_file",
"code_line",
"code_func",
"errno",
"invocation_id",
"user_invocation_id",
"syslog_facility",
"syslog_identifier",
"syslog_pid",
"syslog_timestamp",
"syslog_raw",
"documentation",
"tid",
"unit",
"user_unit",
"object_pid"};
// First map SL priority to syslog's Urgency
Logger::Urgency urgency = entry.d_priority != 0 ? Logger::Urgency(entry.d_priority) : Logger::Info;
if (urgency > s_logUrgency) {
// We do not log anything if the Urgency of the message is lower than the requested loglevel.
// Not that lower Urgency means higher number.
return;
}
// We need to keep the string in mem until sd_journal_sendv has ben called
vector<string> strings;
auto appendKeyAndVal = [&strings](const string& key, const string& value) {
strings.emplace_back(key + "=" + value);
};
appendKeyAndVal("MESSAGE", entry.message);
if (entry.error) {
appendKeyAndVal("ERROR", entry.error.get());
}
appendKeyAndVal("LEVEL", std::to_string(entry.level));
appendKeyAndVal("PRIORITY", std::to_string(entry.d_priority));
if (entry.name) {
appendKeyAndVal("SUBSYSTEM", entry.name.get());
}
std::array<char, 64> timebuf{};
appendKeyAndVal("TIMESTAMP", toTimestampStringMilli(entry.d_timestamp, timebuf));
for (const auto& value : entry.values) {
if (value.first.at(0) == '_' || special.count(value.first) != 0) {
string key{"PDNS"};
key.append(value.first);
appendKeyAndVal(toUpper(key), value.second);
}
else {
appendKeyAndVal(toUpper(value.first), value.second);
}
}
// Thread id filled in by backend, since the SL code does not know about RecursorThreads
// We use the Recursor thread, other threads get id 0. May need to revisit.
appendKeyAndVal("TID", std::to_string(RecThreadInfo::id()));
vector<iovec> iov;
iov.reserve(strings.size());
for (const auto& str : strings) {
// iovec has no 2 arg constructor, so make it explicit
iov.emplace_back(iovec{const_cast<void*>(reinterpret_cast<const void*>(str.data())), str.size()}); // NOLINT: it's the API
}
sd_journal_sendv(iov.data(), static_cast<int>(iov.size()));
}
#endif
static void loggerBackend(const Logging::Entry& entry)
{
static thread_local std::stringstream buf;
// First map SL priority to syslog's Urgency
Logger::Urgency urg = entry.d_priority != 0 ? Logger::Urgency(entry.d_priority) : Logger::Info;
if (urg > s_logUrgency) {
// We do not log anything if the Urgency of the message is lower than the requested loglevel.
// Not that lower Urgency means higher number.
return;
}
buf.str("");
buf << "msg=" << std::quoted(entry.message);
if (entry.error) {
buf << " error=" << std::quoted(entry.error.get());