]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_dns.cpp
Add support for blocking tag messages with the deaf mode.
[user/henk/code/inspircd.git] / src / coremods / core_dns.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 Robby <robby@chatbelgie.be>
5  *   Copyright (C) 2015, 2017-2021 Sadie Powell <sadie@witchery.services>
6  *   Copyright (C) 2013-2016 Attila Molnar <attilamolnar@hush.com>
7  *   Copyright (C) 2013, 2015-2016 Adam <Adam@anope.org>
8  *
9  * This file is part of InspIRCd.  InspIRCd is free software: you can
10  * redistribute it and/or modify it under the terms of the GNU General Public
11  * License as published by the Free Software Foundation, version 2.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include "inspircd.h"
23 #include "modules/dns.h"
24 #include <iostream>
25 #include <fstream>
26
27 #ifdef _WIN32
28 #include <Iphlpapi.h>
29 #pragma comment(lib, "Iphlpapi.lib")
30 #endif
31
32 namespace DNS
33 {
34         /** Maximum value of a dns request id, 16 bits wide, 0xFFFF.
35          */
36         const unsigned int MAX_REQUEST_ID = 0xFFFF;
37 }
38
39 using namespace DNS;
40
41 /** A full packet sent or received to/from the nameserver
42  */
43 class Packet : public Query
44 {
45         void PackName(unsigned char* output, unsigned short output_size, unsigned short& pos, const std::string& name)
46         {
47                 if (pos + name.length() + 2 > output_size)
48                         throw Exception("Unable to pack name");
49
50                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Packing name " + name);
51
52                 irc::sepstream sep(name, '.');
53                 std::string token;
54
55                 while (sep.GetToken(token))
56                 {
57                         output[pos++] = token.length();
58                         memcpy(&output[pos], token.data(), token.length());
59                         pos += token.length();
60                 }
61
62                 output[pos++] = 0;
63         }
64
65         std::string UnpackName(const unsigned char* input, unsigned short input_size, unsigned short& pos)
66         {
67                 std::string name;
68                 unsigned short pos_ptr = pos, lowest_ptr = input_size;
69                 bool compressed = false;
70
71                 if (pos_ptr >= input_size)
72                         throw Exception("Unable to unpack name - no input");
73
74                 while (input[pos_ptr] > 0)
75                 {
76                         unsigned short offset = input[pos_ptr];
77
78                         if (offset & POINTER)
79                         {
80                                 if ((offset & POINTER) != POINTER)
81                                         throw Exception("Unable to unpack name - bogus compression header");
82                                 if (pos_ptr + 1 >= input_size)
83                                         throw Exception("Unable to unpack name - bogus compression header");
84
85                                 /* Place pos at the second byte of the first (farthest) compression pointer */
86                                 if (compressed == false)
87                                 {
88                                         ++pos;
89                                         compressed = true;
90                                 }
91
92                                 pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1];
93
94                                 /* Pointers can only go back */
95                                 if (pos_ptr >= lowest_ptr)
96                                         throw Exception("Unable to unpack name - bogus compression pointer");
97                                 lowest_ptr = pos_ptr;
98                         }
99                         else
100                         {
101                                 if (pos_ptr + offset + 1 >= input_size)
102                                         throw Exception("Unable to unpack name - offset too large");
103                                 if (!name.empty())
104                                         name += ".";
105                                 for (unsigned i = 1; i <= offset; ++i)
106                                         name += input[pos_ptr + i];
107
108                                 pos_ptr += offset + 1;
109                                 if (compressed == false)
110                                         /* Move up pos */
111                                         pos = pos_ptr;
112                         }
113                 }
114
115                 /* +1 pos either to one byte after the compression pointer or one byte after the ending \0 */
116                 ++pos;
117
118                 if (name.empty())
119                         throw Exception("Unable to unpack name - no name");
120
121                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unpack name " + name);
122
123                 return name;
124         }
125
126         Question UnpackQuestion(const unsigned char* input, unsigned short input_size, unsigned short& pos)
127         {
128                 Question q;
129
130                 q.name = this->UnpackName(input, input_size, pos);
131
132                 if (pos + 4 > input_size)
133                         throw Exception("Unable to unpack question");
134
135                 q.type = static_cast<QueryType>(input[pos] << 8 | input[pos + 1]);
136                 pos += 2;
137
138                 // Skip over query class code
139                 pos += 2;
140
141                 return q;
142         }
143
144         ResourceRecord UnpackResourceRecord(const unsigned char* input, unsigned short input_size, unsigned short& pos)
145         {
146                 ResourceRecord record = static_cast<ResourceRecord>(this->UnpackQuestion(input, input_size, pos));
147
148                 if (pos + 6 > input_size)
149                         throw Exception("Unable to unpack resource record");
150
151                 record.ttl = (input[pos] << 24) | (input[pos + 1] << 16) | (input[pos + 2] << 8) | input[pos + 3];
152                 pos += 4;
153
154                 uint16_t rdlength = input[pos] << 8 | input[pos + 1];
155                 pos += 2;
156
157                 switch (record.type)
158                 {
159                         case QUERY_A:
160                         {
161                                 if (pos + 4 > input_size)
162                                         throw Exception("Unable to unpack resource record");
163
164                                 irc::sockets::sockaddrs addrs;
165                                 memset(&addrs, 0, sizeof(addrs));
166
167                                 addrs.in4.sin_family = AF_INET;
168                                 addrs.in4.sin_addr.s_addr = input[pos] | (input[pos + 1] << 8) | (input[pos + 2] << 16)  | (input[pos + 3] << 24);
169                                 pos += 4;
170
171                                 record.rdata = addrs.addr();
172                                 break;
173                         }
174                         case QUERY_AAAA:
175                         {
176                                 if (pos + 16 > input_size)
177                                         throw Exception("Unable to unpack resource record");
178
179                                 irc::sockets::sockaddrs addrs;
180                                 memset(&addrs, 0, sizeof(addrs));
181
182                                 addrs.in6.sin6_family = AF_INET6;
183                                 for (int j = 0; j < 16; ++j)
184                                         addrs.in6.sin6_addr.s6_addr[j] = input[pos + j];
185                                 pos += 16;
186
187                                 record.rdata = addrs.addr();
188
189                                 break;
190                         }
191                         case QUERY_CNAME:
192                         case QUERY_PTR:
193                         {
194                                 record.rdata = this->UnpackName(input, input_size, pos);
195                                 if (!InspIRCd::IsHost(record.rdata))
196                                         throw Exception("Invalid name"); // XXX: Causes the request to time out
197
198                                 break;
199                         }
200                         case QUERY_TXT:
201                         {
202                                 if (pos + rdlength > input_size)
203                                         throw Exception("Unable to unpack txt resource record");
204
205                                 record.rdata = std::string(reinterpret_cast<const char *>(input + pos), rdlength);
206                                 pos += rdlength;
207
208                                 if (record.rdata.find_first_of("\r\n\0", 0, 3) != std::string::npos)
209                                         throw Exception("Invalid character in txt record");
210
211                                 break;
212                         }
213                         default:
214                                 break;
215                 }
216
217                 if (!record.name.empty() && !record.rdata.empty())
218                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, record.name + " -> " + record.rdata);
219
220                 return record;
221         }
222
223  public:
224         static const int POINTER = 0xC0;
225         static const int LABEL = 0x3F;
226         static const int HEADER_LENGTH = 12;
227
228         /* ID for this packet */
229         RequestId id;
230         /* Flags on the packet */
231         unsigned short flags;
232
233         Packet() : id(0), flags(0)
234         {
235         }
236
237         void Fill(const unsigned char* input, const unsigned short len)
238         {
239                 if (len < HEADER_LENGTH)
240                         throw Exception("Unable to fill packet");
241
242                 unsigned short packet_pos = 0;
243
244                 this->id = (input[packet_pos] << 8) | input[packet_pos + 1];
245                 packet_pos += 2;
246
247                 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
248                 packet_pos += 2;
249
250                 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
251                 packet_pos += 2;
252
253                 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
254                 packet_pos += 2;
255
256                 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
257                 packet_pos += 2;
258
259                 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
260                 packet_pos += 2;
261
262                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
263
264                 if (qdcount != 1)
265                         throw Exception("Question count != 1 in incoming packet");
266
267                 this->question = this->UnpackQuestion(input, len, packet_pos);
268
269                 for (unsigned i = 0; i < ancount; ++i)
270                         this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
271         }
272
273         unsigned short Pack(unsigned char* output, unsigned short output_size)
274         {
275                 if (output_size < HEADER_LENGTH)
276                         throw Exception("Unable to pack packet");
277
278                 unsigned short pos = 0;
279
280                 output[pos++] = this->id >> 8;
281                 output[pos++] = this->id & 0xFF;
282                 output[pos++] = this->flags >> 8;
283                 output[pos++] = this->flags & 0xFF;
284                 output[pos++] = 0; // Question count, high byte
285                 output[pos++] = 1; // Question count, low byte
286                 output[pos++] = 0; // Answer count, high byte
287                 output[pos++] = 0; // Answer count, low byte
288                 output[pos++] = 0;
289                 output[pos++] = 0;
290                 output[pos++] = 0;
291                 output[pos++] = 0;
292
293                 {
294                         Question& q = this->question;
295
296                         if (q.type == QUERY_PTR)
297                         {
298                                 irc::sockets::sockaddrs ip;
299                                 irc::sockets::aptosa(q.name, 0, ip);
300
301                                 if (q.name.find(':') != std::string::npos)
302                                 {
303                                         static const char* const hex = "0123456789abcdef";
304                                         char reverse_ip[128];
305                                         unsigned reverse_ip_count = 0;
306                                         for (int j = 15; j >= 0; --j)
307                                         {
308                                                 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
309                                                 reverse_ip[reverse_ip_count++] = '.';
310                                                 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
311                                                 reverse_ip[reverse_ip_count++] = '.';
312                                         }
313                                         reverse_ip[reverse_ip_count++] = 0;
314
315                                         q.name = reverse_ip;
316                                         q.name += "ip6.arpa";
317                                 }
318                                 else
319                                 {
320                                         unsigned long forward = ip.in4.sin_addr.s_addr;
321                                         ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
322
323                                         q.name = ip.addr() + ".in-addr.arpa";
324                                 }
325                         }
326
327                         this->PackName(output, output_size, pos, q.name);
328
329                         if (pos + 4 >= output_size)
330                                 throw Exception("Unable to pack packet");
331
332                         short s = htons(q.type);
333                         memcpy(&output[pos], &s, 2);
334                         pos += 2;
335
336                         // Query class, always IN
337                         output[pos++] = 0;
338                         output[pos++] = 1;
339                 }
340
341                 return pos;
342         }
343 };
344
345 class MyManager : public Manager, public Timer, public EventHandler
346 {
347         typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
348         cache_map cache;
349
350         irc::sockets::sockaddrs myserver;
351         bool unloading;
352
353         /** Maximum number of entries in cache
354          */
355         static const unsigned int MAX_CACHE_SIZE = 1000;
356
357         static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
358         {
359                 const ResourceRecord& req = record.answers[0];
360                 return (req.created + static_cast<time_t>(req.ttl) < now);
361         }
362
363         /** Check the DNS cache to see if request can be handled by a cached result
364          * @return true if a cached result was found.
365          */
366         bool CheckCache(DNS::Request* req, const DNS::Question& question)
367         {
368                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
369
370                 cache_map::iterator it = this->cache.find(question);
371                 if (it == this->cache.end())
372                         return false;
373
374                 Query& record = it->second;
375                 if (IsExpired(record))
376                 {
377                         this->cache.erase(it);
378                         return false;
379                 }
380
381                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
382                 record.cached = true;
383                 req->OnLookupComplete(&record);
384                 return true;
385         }
386
387         /** Add a record to the dns cache
388          * @param r The record
389          */
390         void AddCache(Query& r)
391         {
392                 if (cache.size() >= MAX_CACHE_SIZE)
393                         cache.clear();
394
395                 // Determine the lowest TTL value and use that as the TTL of the cache entry
396                 unsigned int cachettl = UINT_MAX;
397                 for (std::vector<ResourceRecord>::const_iterator i = r.answers.begin(); i != r.answers.end(); ++i)
398                 {
399                         const ResourceRecord& rr = *i;
400                         if (rr.ttl < cachettl)
401                                 cachettl = rr.ttl;
402                 }
403
404                 cachettl = std::min(cachettl, (unsigned int)5*60);
405                 ResourceRecord& rr = r.answers.front();
406                 // Set TTL to what we've determined to be the lowest
407                 rr.ttl = cachettl;
408                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
409                 this->cache[r.question] = r;
410         }
411
412  public:
413         DNS::Request* requests[MAX_REQUEST_ID+1];
414
415         MyManager(Module* c) : Manager(c), Timer(5*60, true)
416                 , unloading(false)
417         {
418                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
419                         requests[i] = NULL;
420                 ServerInstance->Timers.AddTimer(this);
421         }
422
423         ~MyManager()
424         {
425                 // Ensure Process() will fail for new requests
426                 Close();
427                 unloading = true;
428
429                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
430                 {
431                         DNS::Request* request = requests[i];
432                         if (!request)
433                                 continue;
434
435                         Query rr(request->question);
436                         rr.error = ERROR_UNKNOWN;
437                         request->OnError(&rr);
438
439                         delete request;
440                 }
441         }
442
443         void Close()
444         {
445                 // Shutdown the socket if it exists.
446                 if (HasFd())
447                 {
448                         SocketEngine::Shutdown(this, 2);
449                         SocketEngine::Close(this);
450                 }
451
452                 // Remove all entries from the cache.
453                 cache.clear();
454         }
455
456         void Process(DNS::Request* req) CXX11_OVERRIDE
457         {
458                 if ((unloading) || (req->creator->dying))
459                         throw Exception("Module is being unloaded");
460
461                 if (!HasFd())
462                 {
463                         Query rr(req->question);
464                         rr.error = ERROR_DISABLED;
465                         req->OnError(&rr);
466                         return;
467                 }
468
469                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->question.name + " of type " + ConvToStr(req->question.type) + " to " + this->myserver.addr());
470
471                 /* Create an id */
472                 unsigned int tries = 0;
473                 int id;
474                 do
475                 {
476                         id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
477
478                         if (++tries == DNS::MAX_REQUEST_ID*5)
479                         {
480                                 // If we couldn't find an empty slot this many times, do a sequential scan as a last
481                                 // resort. If an empty slot is found that way, go on, otherwise throw an exception
482                                 id = -1;
483                                 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
484                                 {
485                                         if (!this->requests[i])
486                                         {
487                                                 id = i;
488                                                 break;
489                                         }
490                                 }
491
492                                 if (id == -1)
493                                         throw Exception("DNS: All ids are in use");
494
495                                 break;
496                         }
497                 }
498                 while (this->requests[id]);
499
500                 req->id = id;
501                 this->requests[req->id] = req;
502
503                 Packet p;
504                 p.flags = QUERYFLAGS_RD;
505                 p.id = req->id;
506                 p.question = req->question;
507
508                 unsigned char buffer[524];
509                 unsigned short len = p.Pack(buffer, sizeof(buffer));
510
511                 /* Note that calling Pack() above can actually change the contents of p.question.name, if the query is a PTR,
512                  * to contain the value that would be in the DNS cache, which is why this is here.
513                  */
514                 if (req->use_cache && this->CheckCache(req, p.question))
515                 {
516                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
517                         delete req;
518                         return;
519                 }
520
521                 // Update name in the original request so question checking works for PTR queries
522                 req->question.name = p.question.name;
523
524                 if (SocketEngine::SendTo(this, buffer, len, 0, this->myserver) != len)
525                         throw Exception("DNS: Unable to send query");
526
527                 // Add timer for timeout
528                 ServerInstance->Timers.AddTimer(req);
529         }
530
531         void RemoveRequest(DNS::Request* req) CXX11_OVERRIDE
532         {
533                 if (requests[req->id] == req)
534                         requests[req->id] = NULL;
535         }
536
537         std::string GetErrorStr(Error e) CXX11_OVERRIDE
538         {
539                 switch (e)
540                 {
541                         case ERROR_UNLOADED:
542                                 return "Module is unloading";
543                         case ERROR_TIMEDOUT:
544                                 return "Request timed out";
545                         case ERROR_NOT_AN_ANSWER:
546                         case ERROR_NONSTANDARD_QUERY:
547                         case ERROR_FORMAT_ERROR:
548                         case ERROR_MALFORMED:
549                                 return "Malformed answer";
550                         case ERROR_SERVER_FAILURE:
551                         case ERROR_NOT_IMPLEMENTED:
552                         case ERROR_REFUSED:
553                         case ERROR_INVALIDTYPE:
554                                 return "Nameserver failure";
555                         case ERROR_DOMAIN_NOT_FOUND:
556                         case ERROR_NO_RECORDS:
557                                 return "Domain not found";
558                         case ERROR_DISABLED:
559                                 return "DNS lookups are disabled";
560                         case ERROR_NONE:
561                         case ERROR_UNKNOWN:
562                         default:
563                                 return "Unknown error";
564                 }
565         }
566
567         std::string GetTypeStr(QueryType qt) CXX11_OVERRIDE
568         {
569                 switch (qt)
570                 {
571                         case QUERY_A:
572                                 return "A";
573                         case QUERY_AAAA:
574                                 return "AAAA";
575                         case QUERY_CNAME:
576                                 return "CNAME";
577                         case QUERY_PTR:
578                                 return "PTR";
579                         case QUERY_TXT:
580                                 return "TXT";
581                         default:
582                                 return "UNKNOWN";
583                 }
584         }
585
586         void OnEventHandlerError(int errcode) CXX11_OVERRIDE
587         {
588                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
589         }
590
591         void OnEventHandlerRead() CXX11_OVERRIDE
592         {
593                 unsigned char buffer[524];
594                 irc::sockets::sockaddrs from;
595                 socklen_t x = sizeof(from);
596
597                 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
598
599                 if (length < Packet::HEADER_LENGTH)
600                         return;
601
602                 if (myserver != from)
603                 {
604                         std::string server1 = from.str();
605                         std::string server2 = myserver.str();
606                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
607                                 server1.c_str(), server2.c_str());
608                         return;
609                 }
610
611                 Packet recv_packet;
612                 bool valid = false;
613
614                 try
615                 {
616                         recv_packet.Fill(buffer, length);
617                         valid = true;
618                 }
619                 catch (Exception& ex)
620                 {
621                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
622                 }
623
624                 // recv_packet.id must be filled in here
625                 DNS::Request* request = this->requests[recv_packet.id];
626                 if (request == NULL)
627                 {
628                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
629                         return;
630                 }
631
632                 if (request->question != recv_packet.question)
633                 {
634                         // This can happen under high latency, drop it silently, do not fail the request
635                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer that isn't for a question we asked");
636                         return;
637                 }
638
639                 if (!valid)
640                 {
641                         ServerInstance->stats.DnsBad++;
642                         recv_packet.error = ERROR_MALFORMED;
643                         request->OnError(&recv_packet);
644                 }
645                 else if (recv_packet.flags & QUERYFLAGS_OPCODE)
646                 {
647                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
648                         ServerInstance->stats.DnsBad++;
649                         recv_packet.error = ERROR_NONSTANDARD_QUERY;
650                         request->OnError(&recv_packet);
651                 }
652                 else if (!(recv_packet.flags & QUERYFLAGS_QR) || (recv_packet.flags & QUERYFLAGS_RCODE))
653                 {
654                         Error error = ERROR_UNKNOWN;
655
656                         switch (recv_packet.flags & QUERYFLAGS_RCODE)
657                         {
658                                 case 1:
659                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
660                                         error = ERROR_FORMAT_ERROR;
661                                         break;
662                                 case 2:
663                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
664                                         error = ERROR_SERVER_FAILURE;
665                                         break;
666                                 case 3:
667                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
668                                         error = ERROR_DOMAIN_NOT_FOUND;
669                                         break;
670                                 case 4:
671                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
672                                         error = ERROR_NOT_IMPLEMENTED;
673                                         break;
674                                 case 5:
675                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
676                                         error = ERROR_REFUSED;
677                                         break;
678                                 default:
679                                         break;
680                         }
681
682                         ServerInstance->stats.DnsBad++;
683                         recv_packet.error = error;
684                         request->OnError(&recv_packet);
685                 }
686                 else if (recv_packet.answers.empty())
687                 {
688                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
689                         ServerInstance->stats.DnsBad++;
690                         recv_packet.error = ERROR_NO_RECORDS;
691                         request->OnError(&recv_packet);
692                 }
693                 else
694                 {
695                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->question.name);
696                         ServerInstance->stats.DnsGood++;
697                         request->OnLookupComplete(&recv_packet);
698                         this->AddCache(recv_packet);
699                 }
700
701                 ServerInstance->stats.Dns++;
702
703                 /* Request's destructor removes it from the request map */
704                 delete request;
705         }
706
707         bool Tick(time_t now) CXX11_OVERRIDE
708         {
709                 unsigned long expired = 0;
710                 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
711                 {
712                         const Query& query = it->second;
713                         if (IsExpired(query, now))
714                         {
715                                 expired++;
716                                 this->cache.erase(it++);
717                         }
718                         else
719                                 ++it;
720                 }
721
722                 if (expired)
723                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purged %lu expired DNS entries", expired);
724
725                 return true;
726         }
727
728         void Rehash(const std::string& dnsserver, std::string sourceaddr, unsigned int sourceport)
729         {
730                 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
731
732                 /* Initialize mastersocket */
733                 Close();
734                 int s = socket(myserver.family(), SOCK_DGRAM, 0);
735                 this->SetFd(s);
736
737                 /* Have we got a socket? */
738                 if (this->HasFd())
739                 {
740                         SocketEngine::SetReuse(s);
741                         SocketEngine::NonBlocking(s);
742
743                         irc::sockets::sockaddrs bindto;
744                         if (sourceaddr.empty())
745                         {
746                                 // set a sourceaddr for irc::sockets::aptosa() based on the servers af type
747                                 if (myserver.family() == AF_INET)
748                                         sourceaddr = "0.0.0.0";
749                                 else if (myserver.family() == AF_INET6)
750                                         sourceaddr = "::";
751                         }
752                         irc::sockets::aptosa(sourceaddr, sourceport, bindto);
753
754                         if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
755                         {
756                                 /* Failed to bind */
757                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
758                                 SocketEngine::Close(this->GetFd());
759                                 this->SetFd(-1);
760                         }
761                         else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
762                         {
763                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
764                                 SocketEngine::Close(this->GetFd());
765                                 this->SetFd(-1);
766                         }
767
768                         if (bindto.family() != myserver.family())
769                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Nameserver address family differs from source address family - hostnames might not resolve");
770                 }
771                 else
772                 {
773                         ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
774                 }
775         }
776 };
777
778 class ModuleDNS : public Module
779 {
780         MyManager manager;
781         std::string DNSServer;
782         std::string SourceIP;
783         unsigned int SourcePort;
784
785         void FindDNSServer()
786         {
787 #ifdef _WIN32
788                 // attempt to look up their nameserver from the system
789                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
790
791                 PFIXED_INFO pFixedInfo;
792                 DWORD dwBufferSize = sizeof(FIXED_INFO);
793                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
794
795                 if (pFixedInfo)
796                 {
797                         if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
798                         {
799                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
800                                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
801                         }
802
803                         if (pFixedInfo)
804                         {
805                                 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
806                                         DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
807
808                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
809                         }
810
811                         if (!DNSServer.empty())
812                         {
813                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
814                                 return;
815                         }
816                 }
817
818                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
819 #else
820                 // attempt to look up their nameserver from /etc/resolv.conf
821                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
822
823                 std::ifstream resolv("/etc/resolv.conf");
824
825                 while (resolv >> DNSServer)
826                 {
827                         if (DNSServer == "nameserver")
828                         {
829                                 resolv >> DNSServer;
830                                 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos || DNSServer.find_first_not_of("0123456789ABCDEFabcdef:") == std::string::npos)
831                                 {
832                                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
833                                         return;
834                                 }
835                         }
836                 }
837
838                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
839 #endif
840                 DNSServer = "127.0.0.1";
841         }
842
843  public:
844         ModuleDNS() : manager(this)
845                 , SourcePort(0)
846         {
847         }
848
849         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
850         {
851                 ConfigTag* tag = ServerInstance->Config->ConfValue("dns");
852                 if (!tag->getBool("enabled", true))
853                 {
854                         // Clear these so they get reset if DNS is enabled again.
855                         DNSServer.clear();
856                         SourceIP.clear();
857                         SourcePort = 0;
858
859                         this->manager.Close();
860                         return;
861                 }
862
863                 const std::string oldserver = DNSServer;
864                 DNSServer = tag->getString("server");
865
866                 const std::string oldip = SourceIP;
867                 SourceIP = tag->getString("sourceip");
868
869                 const unsigned int oldport = SourcePort;
870                 SourcePort = tag->getUInt("sourceport", 0, 0, UINT16_MAX);
871
872                 if (DNSServer.empty())
873                         FindDNSServer();
874
875                 if (oldserver != DNSServer || oldip != SourceIP || oldport != SourcePort)
876                         this->manager.Rehash(DNSServer, SourceIP, SourcePort);
877         }
878
879         void OnUnloadModule(Module* mod) CXX11_OVERRIDE
880         {
881                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
882                 {
883                         DNS::Request* req = this->manager.requests[i];
884                         if (!req)
885                                 continue;
886
887                         if (req->creator == mod)
888                         {
889                                 Query rr(req->question);
890                                 rr.error = ERROR_UNLOADED;
891                                 req->OnError(&rr);
892
893                                 delete req;
894                         }
895                 }
896         }
897
898         Version GetVersion() CXX11_OVERRIDE
899         {
900                 return Version("Provides support for DNS lookups", VF_CORE|VF_VENDOR);
901         }
902 };
903
904 MODULE_INIT(ModuleDNS)
905