/
m_dns.cpp
1125 lines (907 loc) · 26.7 KB
/
m_dns.cpp
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
/*
*
* (C) 2003-2024 Anope Team
* Contact us at team@anope.org
*
* Please read COPYING and README for further details.
*
* Based on the original code of Epona by Lara.
* Based on the original code of Services by Andy Church.
*/
#include "module.h"
#include "modules/dns.h"
using namespace DNS;
namespace
{
Anope::string admin, nameservers;
int refresh;
time_t timeout;
}
/** A full packet sent or received to/from the nameserver
*/
class Packet : public Query
{
static bool IsValidName(const Anope::string &name)
{
return name.find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-") == Anope::string::npos;
}
void PackName(unsigned char *output, unsigned short output_size, unsigned short &pos, const Anope::string &name)
{
if (pos + name.length() + 2 > output_size)
throw SocketException("Unable to pack name");
Log(LOG_DEBUG_2) << "Resolver: PackName packing " << name;
sepstream sep(name, '.');
Anope::string token;
while (sep.GetToken(token))
{
output[pos++] = token.length();
memcpy(&output[pos], token.c_str(), token.length());
pos += token.length();
}
output[pos++] = 0;
}
Anope::string UnpackName(const unsigned char *input, unsigned short input_size, unsigned short &pos)
{
Anope::string name;
unsigned short pos_ptr = pos, lowest_ptr = input_size;
bool compressed = false;
if (pos_ptr >= input_size)
throw SocketException("Unable to unpack name - no input");
while (input[pos_ptr] > 0)
{
unsigned short offset = input[pos_ptr];
if (offset & POINTER)
{
if ((offset & POINTER) != POINTER)
throw SocketException("Unable to unpack name - bogus compression header");
if (pos_ptr + 1 >= input_size)
throw SocketException("Unable to unpack name - bogus compression header");
/* Place pos at the second byte of the first (farthest) compression pointer */
if (compressed == false)
{
++pos;
compressed = true;
}
pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1];
/* Pointers can only go back */
if (pos_ptr >= lowest_ptr)
throw SocketException("Unable to unpack name - bogus compression pointer");
lowest_ptr = pos_ptr;
}
else
{
if (pos_ptr + offset + 1 >= input_size)
throw SocketException("Unable to unpack name - offset too large");
if (!name.empty())
name += ".";
for (unsigned i = 1; i <= offset; ++i)
name += input[pos_ptr + i];
pos_ptr += offset + 1;
if (compressed == false)
/* Move up pos */
pos = pos_ptr;
}
}
/* +1 pos either to one byte after the compression pointer or one byte after the ending \0 */
++pos;
/* Empty names are valid (root domain) */
Log(LOG_DEBUG_2) << "Resolver: UnpackName successfully unpacked " << name;
return name;
}
Question UnpackQuestion(const unsigned char *input, unsigned short input_size, unsigned short &pos)
{
Question question;
question.name = this->UnpackName(input, input_size, pos);
if (pos + 4 > input_size)
throw SocketException("Unable to unpack question");
if (!IsValidName(question.name))
throw SocketException("Invalid question name");
question.type = static_cast<QueryType>(input[pos] << 8 | input[pos + 1]);
pos += 2;
question.qclass = input[pos] << 8 | input[pos + 1];
pos += 2;
return question;
}
ResourceRecord UnpackResourceRecord(const unsigned char *input, unsigned short input_size, unsigned short &pos)
{
ResourceRecord record = static_cast<ResourceRecord>(this->UnpackQuestion(input, input_size, pos));
if (pos + 6 > input_size)
throw SocketException("Unable to unpack resource record");
record.ttl = (input[pos] << 24) | (input[pos + 1] << 16) | (input[pos + 2] << 8) | input[pos + 3];
pos += 4;
//record.rdlength = input[pos] << 8 | input[pos + 1];
pos += 2;
switch (record.type)
{
case QUERY_A:
{
if (pos + 4 > input_size)
throw SocketException("Unable to unpack resource record");
in_addr a;
a.s_addr = input[pos] | (input[pos + 1] << 8) | (input[pos + 2] << 16) | (input[pos + 3] << 24);
pos += 4;
sockaddrs addrs;
addrs.ntop(AF_INET, &a);
if (!addrs.valid())
throw SocketException("Invalid IP");
record.rdata = addrs.addr();
break;
}
case QUERY_AAAA:
{
if (pos + 16 > input_size)
throw SocketException("Unable to unpack resource record");
in6_addr a;
for (int j = 0; j < 16; ++j)
a.s6_addr[j] = input[pos + j];
pos += 16;
sockaddrs addrs;
addrs.ntop(AF_INET6, &a);
if (!addrs.valid())
throw SocketException("Invalid IP");
record.rdata = addrs.addr();
break;
}
case QUERY_CNAME:
case QUERY_PTR:
{
record.rdata = this->UnpackName(input, input_size, pos);
if (!IsValidName(record.rdata))
throw SocketException("Invalid cname/ptr record data");
break;
}
default:
break;
}
Log(LOG_DEBUG_2) << "Resolver: " << record.name << " -> " << record.rdata;
return record;
}
public:
static const int POINTER = 0xC0;
static const int LABEL = 0x3F;
static const int HEADER_LENGTH = 12;
Manager *manager;
/* Source or destination of the packet */
sockaddrs addr;
/* ID for this packet */
unsigned short id;
/* Flags on the packet */
unsigned short flags;
Packet(Manager *m, sockaddrs *a) : manager(m), id(0), flags(0)
{
if (a)
addr = *a;
}
void Fill(const unsigned char *input, const unsigned short len)
{
if (len < HEADER_LENGTH)
throw SocketException("Unable to fill packet");
unsigned short packet_pos = 0;
this->id = (input[packet_pos] << 8) | input[packet_pos + 1];
packet_pos += 2;
this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
packet_pos += 2;
unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
packet_pos += 2;
unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
packet_pos += 2;
unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
packet_pos += 2;
unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
packet_pos += 2;
Log(LOG_DEBUG_2) << "Resolver: qdcount: " << qdcount << " ancount: " << ancount << " nscount: " << nscount << " arcount: " << arcount;
for (unsigned i = 0; i < qdcount; ++i)
this->questions.push_back(this->UnpackQuestion(input, len, packet_pos));
for (unsigned i = 0; i < ancount; ++i)
this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
try
{
for (unsigned i = 0; i < nscount; ++i)
this->authorities.push_back(this->UnpackResourceRecord(input, len, packet_pos));
for (unsigned i = 0; i < arcount; ++i)
this->additional.push_back(this->UnpackResourceRecord(input, len, packet_pos));
}
catch (const SocketException &ex)
{
Log(LOG_DEBUG_2) << "Unable to parse ns/ar records: " << ex.GetReason();
}
}
unsigned short Pack(unsigned char *output, unsigned short output_size)
{
if (output_size < HEADER_LENGTH)
throw SocketException("Unable to pack packet");
unsigned short pos = 0;
output[pos++] = this->id >> 8;
output[pos++] = this->id & 0xFF;
output[pos++] = this->flags >> 8;
output[pos++] = this->flags & 0xFF;
output[pos++] = this->questions.size() >> 8;
output[pos++] = this->questions.size() & 0xFF;
output[pos++] = this->answers.size() >> 8;
output[pos++] = this->answers.size() & 0xFF;
output[pos++] = this->authorities.size() >> 8;
output[pos++] = this->authorities.size() & 0xFF;
output[pos++] = this->additional.size() >> 8;
output[pos++] = this->additional.size() & 0xFF;
for (unsigned i = 0; i < this->questions.size(); ++i)
{
Question &q = this->questions[i];
if (q.type == QUERY_PTR)
{
sockaddrs ip(q.name);
if (!ip.valid())
throw SocketException("Invalid IP");
switch (ip.family())
{
case AF_INET6:
q.name = ip.reverse() + ".ip6.arpa";
break;
case AF_INET:
q.name = ip.reverse() + ".in-addr.arpa";
break;
default:
throw SocketException("Unsupported IP Family");
}
}
this->PackName(output, output_size, pos, q.name);
if (pos + 4 >= output_size)
throw SocketException("Unable to pack packet");
short s = htons(q.type);
memcpy(&output[pos], &s, 2);
pos += 2;
s = htons(q.qclass);
memcpy(&output[pos], &s, 2);
pos += 2;
}
std::vector<ResourceRecord> types[] = { this->answers, this->authorities, this->additional };
for (int i = 0; i < 3; ++i)
for (unsigned j = 0; j < types[i].size(); ++j)
{
ResourceRecord &rr = types[i][j];
this->PackName(output, output_size, pos, rr.name);
if (pos + 8 >= output_size)
throw SocketException("Unable to pack packet");
short s = htons(rr.type);
memcpy(&output[pos], &s, 2);
pos += 2;
s = htons(rr.qclass);
memcpy(&output[pos], &s, 2);
pos += 2;
long l = htonl(rr.ttl);
memcpy(&output[pos], &l, 4);
pos += 4;
switch (rr.type)
{
case QUERY_A:
{
if (pos + 6 > output_size)
throw SocketException("Unable to pack packet");
sockaddrs a(rr.rdata);
if (!a.valid())
throw SocketException("Invalid IP");
s = htons(4);
memcpy(&output[pos], &s, 2);
pos += 2;
memcpy(&output[pos], &a.sa4.sin_addr, 4);
pos += 4;
break;
}
case QUERY_AAAA:
{
if (pos + 18 > output_size)
throw SocketException("Unable to pack packet");
sockaddrs a(rr.rdata);
if (!a.valid())
throw SocketException("Invalid IP");
s = htons(16);
memcpy(&output[pos], &s, 2);
pos += 2;
memcpy(&output[pos], &a.sa6.sin6_addr, 16);
pos += 16;
break;
}
case QUERY_NS:
case QUERY_CNAME:
case QUERY_PTR:
{
if (pos + 2 >= output_size)
throw SocketException("Unable to pack packet");
unsigned short packet_pos_save = pos;
pos += 2;
this->PackName(output, output_size, pos, rr.rdata);
s = htons(pos - packet_pos_save - 2);
memcpy(&output[packet_pos_save], &s, 2);
break;
}
case QUERY_SOA:
{
if (pos + 2 >= output_size)
throw SocketException("Unable to pack packet");
unsigned short packet_pos_save = pos;
pos += 2;
std::vector<Anope::string> ns;
spacesepstream(nameservers).GetTokens(ns);
this->PackName(output, output_size, pos, !ns.empty() ? ns[0] : "");
this->PackName(output, output_size, pos, admin.replace_all_cs('@', '.'));
if (pos + 20 >= output_size)
throw SocketException("Unable to pack SOA");
l = htonl(manager->GetSerial());
memcpy(&output[pos], &l, 4);
pos += 4;
l = htonl(refresh); // Refresh
memcpy(&output[pos], &l, 4);
pos += 4;
l = htonl(refresh); // Retry
memcpy(&output[pos], &l, 4);
pos += 4;
l = htonl(604800); // Expire
memcpy(&output[pos], &l, 4);
pos += 4;
l = htonl(0); // Minimum
memcpy(&output[pos], &l, 4);
pos += 4;
s = htons(pos - packet_pos_save - 2);
memcpy(&output[packet_pos_save], &s, 2);
break;
}
default:
break;
}
}
return pos;
}
};
namespace DNS
{
class ReplySocket : public virtual Socket
{
public:
virtual ~ReplySocket() { }
virtual void Reply(Packet *p) = 0;
};
}
/* Listens for TCP requests */
class TCPSocket : public ListenSocket
{
Manager *manager;
public:
/* A TCP client */
class Client : public ClientSocket, public Timer, public ReplySocket
{
Manager *manager;
Packet *packet;
unsigned char packet_buffer[524];
int length;
public:
Client(Manager *m, TCPSocket *l, int fd, const sockaddrs &addr) : Socket(fd, l->IsIPv6()), ClientSocket(l, addr), Timer(5),
manager(m), packet(NULL), length(0)
{
Log(LOG_DEBUG_2) << "Resolver: New client from " << addr.addr();
}
~Client()
{
Log(LOG_DEBUG_2) << "Resolver: Exiting client from " << clientaddr.addr();
delete packet;
}
/* Times out after a few seconds */
void Tick(time_t) anope_override { }
void Reply(Packet *p) anope_override
{
delete packet;
packet = p;
SocketEngine::Change(this, true, SF_WRITABLE);
}
bool ProcessRead() anope_override
{
Log(LOG_DEBUG_2) << "Resolver: Reading from DNS TCP socket";
int i = recv(this->GetFD(), reinterpret_cast<char *>(packet_buffer) + length, sizeof(packet_buffer) - length, 0);
if (i <= 0)
return false;
length += i;
unsigned short want_len = packet_buffer[0] << 8 | packet_buffer[1];
if (length >= want_len + 2)
{
int len = length - 2;
length -= want_len + 2;
return this->manager->HandlePacket(this, packet_buffer + 2, len, NULL);
}
return true;
}
bool ProcessWrite() anope_override
{
Log(LOG_DEBUG_2) << "Resolver: Writing to DNS TCP socket";
if (packet != NULL)
{
try
{
unsigned char buffer[65535];
unsigned short len = packet->Pack(buffer + 2, sizeof(buffer) - 2);
short s = htons(len);
memcpy(buffer, &s, 2);
len += 2;
send(this->GetFD(), reinterpret_cast<char *>(buffer), len, 0);
}
catch (const SocketException &) { }
delete packet;
packet = NULL;
}
SocketEngine::Change(this, false, SF_WRITABLE);
return true; /* Do not return false here, bind is unhappy we close the connection so soon after sending */
}
};
TCPSocket(Manager *m, const Anope::string &ip, int port) : Socket(-1, ip.find(':') != Anope::string::npos), ListenSocket(ip, port, ip.find(':') != Anope::string::npos), manager(m) { }
ClientSocket *OnAccept(int fd, const sockaddrs &addr) anope_override
{
return new Client(this->manager, this, fd, addr);
}
};
/* Listens for UDP requests */
class UDPSocket : public ReplySocket
{
Manager *manager;
std::deque<Packet *> packets;
public:
UDPSocket(Manager *m, const Anope::string &ip, int port) : Socket(-1, ip.find(':') != Anope::string::npos, SOCK_DGRAM), manager(m) { }
~UDPSocket()
{
for (unsigned i = 0; i < packets.size(); ++i)
delete packets[i];
}
void Reply(Packet *p) anope_override
{
packets.push_back(p);
SocketEngine::Change(this, true, SF_WRITABLE);
}
std::deque<Packet *>& GetPackets() { return packets; }
bool ProcessRead() anope_override
{
Log(LOG_DEBUG_2) << "Resolver: Reading from DNS UDP socket";
unsigned char packet_buffer[524];
sockaddrs from_server;
socklen_t x = sizeof(from_server);
int length = recvfrom(this->GetFD(), reinterpret_cast<char *>(&packet_buffer), sizeof(packet_buffer), 0, &from_server.sa, &x);
return this->manager->HandlePacket(this, packet_buffer, length, &from_server);
}
bool ProcessWrite() anope_override
{
Log(LOG_DEBUG_2) << "Resolver: Writing to DNS UDP socket";
Packet *r = !packets.empty() ? packets.front() : NULL;
if (r != NULL)
{
try
{
unsigned char buffer[524];
unsigned short len = r->Pack(buffer, sizeof(buffer));
sendto(this->GetFD(), reinterpret_cast<char *>(buffer), len, 0, &r->addr.sa, r->addr.size());
}
catch (const SocketException &) { }
delete r;
packets.pop_front();
}
if (packets.empty())
SocketEngine::Change(this, false, SF_WRITABLE);
return true;
}
};
class NotifySocket : public Socket
{
Packet *packet;
public:
NotifySocket(bool v6, Packet *p) : Socket(-1, v6, SOCK_DGRAM), packet(p)
{
SocketEngine::Change(this, false, SF_READABLE);
SocketEngine::Change(this, true, SF_WRITABLE);
}
bool ProcessWrite() anope_override
{
if (!packet)
return false;
Log(LOG_DEBUG_2) << "Resolver: Notifying slave " << packet->addr.addr();
try
{
unsigned char buffer[524];
unsigned short len = packet->Pack(buffer, sizeof(buffer));
sendto(this->GetFD(), reinterpret_cast<char *>(buffer), len, 0, &packet->addr.sa, packet->addr.size());
}
catch (const SocketException &) { }
delete packet;
packet = NULL;
return false;
}
};
class MyManager : public Manager, public Timer
{
uint32_t serial;
typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
cache_map cache;
TCPSocket *tcpsock;
UDPSocket *udpsock;
bool listen;
sockaddrs addrs;
std::vector<std::pair<Anope::string, short> > notify;
public:
std::map<unsigned short, Request *> requests;
MyManager(Module *creator) : Manager(creator), Timer(300, Anope::CurTime, true), serial(Anope::CurTime), tcpsock(NULL), udpsock(NULL),
listen(false), cur_id(rand())
{
}
~MyManager()
{
delete udpsock;
delete tcpsock;
for (std::map<unsigned short, Request *>::iterator it = this->requests.begin(), it_end = this->requests.end(); it != it_end;)
{
Request *request = it->second;
++it;
Query rr(*request);
rr.error = ERROR_UNKNOWN;
request->OnError(&rr);
delete request;
}
this->requests.clear();
this->cache.clear();
}
void SetIPPort(const Anope::string &nameserver, const Anope::string &ip, unsigned short port, std::vector<std::pair<Anope::string, short> > n)
{
delete udpsock;
delete tcpsock;
udpsock = NULL;
tcpsock = NULL;
try
{
this->addrs.pton(nameserver.find(':') != Anope::string::npos ? AF_INET6 : AF_INET, nameserver, 53);
udpsock = new UDPSocket(this, ip, port);
if (!ip.empty())
{
udpsock->Bind(ip, port);
tcpsock = new TCPSocket(this, ip, port);
listen = true;
}
}
catch (const SocketException &ex)
{
Log() << "Unable to bind dns to " << ip << ":" << port << ": " << ex.GetReason();
}
notify = n;
}
private:
unsigned short cur_id;
unsigned short GetID()
{
if (this->udpsock->GetPackets().size() == 65535)
throw SocketException("DNS queue full");
do
cur_id = (cur_id + 1) & 0xFFFF;
while (!cur_id || this->requests.count(cur_id));
return cur_id;
}
public:
void Process(Request *req) anope_override
{
Log(LOG_DEBUG_2) << "Resolver: Processing request to lookup " << req->name << ", of type " << req->type;
if (req->use_cache && this->CheckCache(req))
{
Log(LOG_DEBUG_2) << "Resolver: Using cached result";
delete req;
return;
}
if (!this->udpsock)
throw SocketException("No dns socket");
req->id = GetID();
this->requests[req->id] = req;
req->SetSecs(timeout);
Packet *p = new Packet(this, &this->addrs);
p->flags = QUERYFLAGS_RD;
p->id = req->id;
p->questions.push_back(*req);
this->udpsock->Reply(p);
}
void RemoveRequest(Request *req) anope_override
{
this->requests.erase(req->id);
}
bool HandlePacket(ReplySocket *s, const unsigned char *const packet_buffer, int length, sockaddrs *from) anope_override
{
if (length < Packet::HEADER_LENGTH)
return true;
Packet recv_packet(this, from);
try
{
recv_packet.Fill(packet_buffer, length);
}
catch (const SocketException &ex)
{
Log(LOG_DEBUG_2) << ex.GetReason();
return true;
}
if (!(recv_packet.flags & QUERYFLAGS_QR))
{
if (!listen)
return true;
else if (recv_packet.questions.empty())
{
Log(LOG_DEBUG_2) << "Resolver: Received a question with no questions?";
return true;
}
Packet *packet = new Packet(recv_packet);
packet->flags |= QUERYFLAGS_QR; /* This is a response */
packet->flags |= QUERYFLAGS_AA; /* And we are authoritative */
packet->answers.clear();
packet->authorities.clear();
packet->additional.clear();
for (unsigned i = 0; i < recv_packet.questions.size(); ++i)
{
const Question& q = recv_packet.questions[i];
if (q.type == QUERY_AXFR || q.type == QUERY_SOA)
{
ResourceRecord rr(q.name, QUERY_SOA);
packet->answers.push_back(rr);
if (q.type == QUERY_AXFR)
{
Anope::string token;
spacesepstream sep(nameservers);
while (sep.GetToken(token))
{
ResourceRecord rr2(q.name, QUERY_NS);
rr2.rdata = token;
packet->answers.push_back(rr2);
}
}
break;
}
}
FOREACH_MOD(OnDnsRequest, (recv_packet, packet));
for (unsigned i = 0; i < recv_packet.questions.size(); ++i)
{
const Question& q = recv_packet.questions[i];
if (q.type == QUERY_AXFR)
{
ResourceRecord rr(q.name, QUERY_SOA);
packet->answers.push_back(rr);
break;
}
}
if (packet->answers.empty() && packet->authorities.empty() && packet->additional.empty() && packet->error == ERROR_NONE)
packet->error = ERROR_REFUSED; // usually safe, won't cause an NXDOMAIN to get cached
s->Reply(packet);
return true;
}
if (from == NULL)
{
Log(LOG_DEBUG_2) << "Resolver: Received an answer over TCP. This is not supported.";
return true;
}
else if (this->addrs != *from)
{
Log(LOG_DEBUG_2) << "Resolver: Received an answer from the wrong nameserver, Bad NAT or DNS forging attempt? '" << this->addrs.addr() << "' != '" << from->addr() << "'";
return true;
}
std::map<unsigned short, Request *>::iterator it = this->requests.find(recv_packet.id);
if (it == this->requests.end())
{
Log(LOG_DEBUG_2) << "Resolver: Received an answer for something we didn't request";
return true;
}
Request *request = it->second;
if (recv_packet.flags & QUERYFLAGS_OPCODE)
{
Log(LOG_DEBUG_2) << "Resolver: Received a nonstandard query";
recv_packet.error = ERROR_NONSTANDARD_QUERY;
request->OnError(&recv_packet);
}
else if (recv_packet.flags & QUERYFLAGS_RCODE)
{
Error error = ERROR_UNKNOWN;
switch (recv_packet.flags & QUERYFLAGS_RCODE)
{
case 1:
Log(LOG_DEBUG_2) << "Resolver: format error";
error = ERROR_FORMAT_ERROR;
break;
case 2:
Log(LOG_DEBUG_2) << "Resolver: server error";
error = ERROR_SERVER_FAILURE;
break;
case 3:
Log(LOG_DEBUG_2) << "Resolver: domain not found";
error = ERROR_DOMAIN_NOT_FOUND;
break;
case 4:
Log(LOG_DEBUG_2) << "Resolver: not implemented";
error = ERROR_NOT_IMPLEMENTED;
break;
case 5:
Log(LOG_DEBUG_2) << "Resolver: refused";
error = ERROR_REFUSED;
break;
default:
break;
}
recv_packet.error = error;
request->OnError(&recv_packet);
}
else if (recv_packet.questions.empty() || recv_packet.answers.empty())
{
Log(LOG_DEBUG_2) << "Resolver: No resource records returned";
recv_packet.error = ERROR_NO_RECORDS;
request->OnError(&recv_packet);
}
else
{
Log(LOG_DEBUG_2) << "Resolver: Lookup complete for " << request->name;
request->OnLookupComplete(&recv_packet);
this->AddCache(recv_packet);
}
delete request;
return true;
}
void UpdateSerial() anope_override
{
serial = Anope::CurTime;
}
void Notify(const Anope::string &zone) anope_override
{
/* notify slaves of the update */
for (unsigned i = 0; i < notify.size(); ++i)
{
const Anope::string &ip = notify[i].first;
short port = notify[i].second;
sockaddrs addr;
addr.pton(ip.find(':') != Anope::string::npos ? AF_INET6 : AF_INET, ip, port);
if (!addr.valid())
return;
Packet *packet = new Packet(this, &addr);
packet->flags = QUERYFLAGS_AA | QUERYFLAGS_OPCODE_NOTIFY;
try
{
packet->id = GetID();
}
catch (const SocketException &)
{
delete packet;
continue;
}
packet->questions.push_back(Question(zone, QUERY_SOA));
new NotifySocket(ip.find(':') != Anope::string::npos, packet);
}
}
uint32_t GetSerial() const anope_override
{
return serial;
}
void Tick(time_t now) anope_override
{
Log(LOG_DEBUG_2) << "Resolver: Purging DNS cache";
for (cache_map::iterator it = this->cache.begin(), it_next; it != this->cache.end(); it = it_next)
{
const Query &q = it->second;
const ResourceRecord &req = q.answers[0];
it_next = it;
++it_next;
if (req.created + static_cast<time_t>(req.ttl) < now)
this->cache.erase(it);
}
}
private:
/** Add a record to the dns cache
* @param r The record
*/
void AddCache(Query &r)
{
const ResourceRecord &rr = r.answers[0];
Log(LOG_DEBUG_3) << "Resolver cache: added cache for " << rr.name << " -> " << rr.rdata << ", ttl: " << rr.ttl;
this->cache[r.questions[0]] = r;
}
/** Check the DNS cache to see if request can be handled by a cached result
* @return true if a cached result was found.
*/
bool CheckCache(Request *request)
{
cache_map::iterator it = this->cache.find(*request);
if (it != this->cache.end())
{
Query &record = it->second;
Log(LOG_DEBUG_3) << "Resolver: Using cached result for " << request->name;