]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_dns.cpp
Update copyright headers.
[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, 2021 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                         {
215                                 if (pos + rdlength > input_size)
216                                         throw Exception("Unable to skip resource record");
217
218                                 pos += rdlength;
219                                 break;
220                         }
221                 }
222
223                 if (!record.name.empty() && !record.rdata.empty())
224                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, record.name + " -> " + record.rdata);
225
226                 return record;
227         }
228
229  public:
230         static const int POINTER = 0xC0;
231         static const int LABEL = 0x3F;
232         static const int HEADER_LENGTH = 12;
233
234         /* ID for this packet */
235         RequestId id;
236         /* Flags on the packet */
237         unsigned short flags;
238
239         Packet() : id(0), flags(0)
240         {
241         }
242
243         void Fill(const unsigned char* input, const unsigned short len)
244         {
245                 if (len < HEADER_LENGTH)
246                         throw Exception("Unable to fill packet");
247
248                 unsigned short packet_pos = 0;
249
250                 this->id = (input[packet_pos] << 8) | input[packet_pos + 1];
251                 packet_pos += 2;
252
253                 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
254                 packet_pos += 2;
255
256                 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
257                 packet_pos += 2;
258
259                 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
260                 packet_pos += 2;
261
262                 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
263                 packet_pos += 2;
264
265                 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
266                 packet_pos += 2;
267
268                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
269
270                 if (qdcount != 1)
271                         throw Exception("Question count != 1 in incoming packet");
272
273                 this->question = this->UnpackQuestion(input, len, packet_pos);
274
275                 for (unsigned i = 0; i < ancount; ++i)
276                         this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
277         }
278
279         unsigned short Pack(unsigned char* output, unsigned short output_size)
280         {
281                 if (output_size < HEADER_LENGTH)
282                         throw Exception("Unable to pack packet");
283
284                 unsigned short pos = 0;
285
286                 output[pos++] = this->id >> 8;
287                 output[pos++] = this->id & 0xFF;
288                 output[pos++] = this->flags >> 8;
289                 output[pos++] = this->flags & 0xFF;
290                 output[pos++] = 0; // Question count, high byte
291                 output[pos++] = 1; // Question count, low byte
292                 output[pos++] = 0; // Answer count, high byte
293                 output[pos++] = 0; // Answer count, low byte
294                 output[pos++] = 0;
295                 output[pos++] = 0;
296                 output[pos++] = 0;
297                 output[pos++] = 0;
298
299                 {
300                         Question& q = this->question;
301
302                         if (q.type == QUERY_PTR)
303                         {
304                                 irc::sockets::sockaddrs ip;
305                                 irc::sockets::aptosa(q.name, 0, ip);
306
307                                 if (q.name.find(':') != std::string::npos)
308                                 {
309                                         static const char* const hex = "0123456789abcdef";
310                                         char reverse_ip[128];
311                                         unsigned reverse_ip_count = 0;
312                                         for (int j = 15; j >= 0; --j)
313                                         {
314                                                 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
315                                                 reverse_ip[reverse_ip_count++] = '.';
316                                                 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
317                                                 reverse_ip[reverse_ip_count++] = '.';
318                                         }
319                                         reverse_ip[reverse_ip_count++] = 0;
320
321                                         q.name = reverse_ip;
322                                         q.name += "ip6.arpa";
323                                 }
324                                 else
325                                 {
326                                         unsigned long forward = ip.in4.sin_addr.s_addr;
327                                         ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
328
329                                         q.name = ip.addr() + ".in-addr.arpa";
330                                 }
331                         }
332
333                         this->PackName(output, output_size, pos, q.name);
334
335                         if (pos + 4 >= output_size)
336                                 throw Exception("Unable to pack packet");
337
338                         short s = htons(q.type);
339                         memcpy(&output[pos], &s, 2);
340                         pos += 2;
341
342                         // Query class, always IN
343                         output[pos++] = 0;
344                         output[pos++] = 1;
345                 }
346
347                 return pos;
348         }
349 };
350
351 class MyManager : public Manager, public Timer, public EventHandler
352 {
353         typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
354         cache_map cache;
355
356         irc::sockets::sockaddrs myserver;
357         bool unloading;
358
359         /** Maximum number of entries in cache
360          */
361         static const unsigned int MAX_CACHE_SIZE = 1000;
362
363         static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
364         {
365                 const ResourceRecord& req = record.answers[0];
366                 return (req.created + static_cast<time_t>(req.ttl) < now);
367         }
368
369         /** Check the DNS cache to see if request can be handled by a cached result
370          * @return true if a cached result was found.
371          */
372         bool CheckCache(DNS::Request* req, const DNS::Question& question)
373         {
374                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
375
376                 cache_map::iterator it = this->cache.find(question);
377                 if (it == this->cache.end())
378                         return false;
379
380                 Query& record = it->second;
381                 if (IsExpired(record))
382                 {
383                         this->cache.erase(it);
384                         return false;
385                 }
386
387                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
388                 record.cached = true;
389                 req->OnLookupComplete(&record);
390                 return true;
391         }
392
393         /** Add a record to the dns cache
394          * @param r The record
395          */
396         void AddCache(Query& r)
397         {
398                 if (cache.size() >= MAX_CACHE_SIZE)
399                         cache.clear();
400
401                 // Determine the lowest TTL value and use that as the TTL of the cache entry
402                 unsigned int cachettl = UINT_MAX;
403                 for (std::vector<ResourceRecord>::const_iterator i = r.answers.begin(); i != r.answers.end(); ++i)
404                 {
405                         const ResourceRecord& rr = *i;
406                         if (rr.ttl < cachettl)
407                                 cachettl = rr.ttl;
408                 }
409
410                 cachettl = std::min(cachettl, (unsigned int)5*60);
411                 ResourceRecord& rr = r.answers.front();
412                 // Set TTL to what we've determined to be the lowest
413                 rr.ttl = cachettl;
414                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
415                 this->cache[r.question] = r;
416         }
417
418  public:
419         DNS::Request* requests[MAX_REQUEST_ID+1];
420
421         MyManager(Module* c) : Manager(c), Timer(5*60, true)
422                 , unloading(false)
423         {
424                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
425                         requests[i] = NULL;
426                 ServerInstance->Timers.AddTimer(this);
427         }
428
429         ~MyManager()
430         {
431                 // Ensure Process() will fail for new requests
432                 Close();
433                 unloading = true;
434
435                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
436                 {
437                         DNS::Request* request = requests[i];
438                         if (!request)
439                                 continue;
440
441                         Query rr(request->question);
442                         rr.error = ERROR_UNKNOWN;
443                         request->OnError(&rr);
444
445                         delete request;
446                 }
447         }
448
449         void Close()
450         {
451                 // Shutdown the socket if it exists.
452                 if (HasFd())
453                 {
454                         SocketEngine::Shutdown(this, 2);
455                         SocketEngine::Close(this);
456                 }
457
458                 // Remove all entries from the cache.
459                 cache.clear();
460         }
461
462         void Process(DNS::Request* req) CXX11_OVERRIDE
463         {
464                 if ((unloading) || (req->creator->dying))
465                         throw Exception("Module is being unloaded");
466
467                 if (!HasFd())
468                 {
469                         Query rr(req->question);
470                         rr.error = ERROR_DISABLED;
471                         req->OnError(&rr);
472                         return;
473                 }
474
475                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->question.name + " of type " + ConvToStr(req->question.type) + " to " + this->myserver.addr());
476
477                 /* Create an id */
478                 unsigned int tries = 0;
479                 int id;
480                 do
481                 {
482                         id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
483
484                         if (++tries == DNS::MAX_REQUEST_ID*5)
485                         {
486                                 // If we couldn't find an empty slot this many times, do a sequential scan as a last
487                                 // resort. If an empty slot is found that way, go on, otherwise throw an exception
488                                 id = -1;
489                                 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
490                                 {
491                                         if (!this->requests[i])
492                                         {
493                                                 id = i;
494                                                 break;
495                                         }
496                                 }
497
498                                 if (id == -1)
499                                         throw Exception("DNS: All ids are in use");
500
501                                 break;
502                         }
503                 }
504                 while (this->requests[id]);
505
506                 req->id = id;
507                 this->requests[req->id] = req;
508
509                 Packet p;
510                 p.flags = QUERYFLAGS_RD;
511                 p.id = req->id;
512                 p.question = req->question;
513
514                 unsigned char buffer[524];
515                 unsigned short len = p.Pack(buffer, sizeof(buffer));
516
517                 /* Note that calling Pack() above can actually change the contents of p.question.name, if the query is a PTR,
518                  * to contain the value that would be in the DNS cache, which is why this is here.
519                  */
520                 if (req->use_cache && this->CheckCache(req, p.question))
521                 {
522                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
523                         delete req;
524                         return;
525                 }
526
527                 // Update name in the original request so question checking works for PTR queries
528                 req->question.name = p.question.name;
529
530                 if (SocketEngine::SendTo(this, buffer, len, 0, this->myserver) != len)
531                         throw Exception("DNS: Unable to send query");
532
533                 // Add timer for timeout
534                 ServerInstance->Timers.AddTimer(req);
535         }
536
537         void RemoveRequest(DNS::Request* req) CXX11_OVERRIDE
538         {
539                 if (requests[req->id] == req)
540                         requests[req->id] = NULL;
541         }
542
543         std::string GetErrorStr(Error e) CXX11_OVERRIDE
544         {
545                 switch (e)
546                 {
547                         case ERROR_UNLOADED:
548                                 return "Module is unloading";
549                         case ERROR_TIMEDOUT:
550                                 return "Request timed out";
551                         case ERROR_NOT_AN_ANSWER:
552                         case ERROR_NONSTANDARD_QUERY:
553                         case ERROR_FORMAT_ERROR:
554                         case ERROR_MALFORMED:
555                                 return "Malformed answer";
556                         case ERROR_SERVER_FAILURE:
557                         case ERROR_NOT_IMPLEMENTED:
558                         case ERROR_REFUSED:
559                         case ERROR_INVALIDTYPE:
560                                 return "Nameserver failure";
561                         case ERROR_DOMAIN_NOT_FOUND:
562                         case ERROR_NO_RECORDS:
563                                 return "Domain not found";
564                         case ERROR_DISABLED:
565                                 return "DNS lookups are disabled";
566                         case ERROR_NONE:
567                         case ERROR_UNKNOWN:
568                         default:
569                                 return "Unknown error";
570                 }
571         }
572
573         std::string GetTypeStr(QueryType qt) CXX11_OVERRIDE
574         {
575                 switch (qt)
576                 {
577                         case QUERY_A:
578                                 return "A";
579                         case QUERY_AAAA:
580                                 return "AAAA";
581                         case QUERY_CNAME:
582                                 return "CNAME";
583                         case QUERY_PTR:
584                                 return "PTR";
585                         case QUERY_TXT:
586                                 return "TXT";
587                         default:
588                                 return "UNKNOWN";
589                 }
590         }
591
592         void OnEventHandlerError(int errcode) CXX11_OVERRIDE
593         {
594                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
595         }
596
597         void OnEventHandlerRead() CXX11_OVERRIDE
598         {
599                 unsigned char buffer[524];
600                 irc::sockets::sockaddrs from;
601                 socklen_t x = sizeof(from);
602
603                 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
604
605                 if (length < Packet::HEADER_LENGTH)
606                         return;
607
608                 if (myserver != from)
609                 {
610                         std::string server1 = from.str();
611                         std::string server2 = myserver.str();
612                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
613                                 server1.c_str(), server2.c_str());
614                         return;
615                 }
616
617                 Packet recv_packet;
618                 bool valid = false;
619
620                 try
621                 {
622                         recv_packet.Fill(buffer, length);
623                         valid = true;
624                 }
625                 catch (Exception& ex)
626                 {
627                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
628                 }
629
630                 // recv_packet.id must be filled in here
631                 DNS::Request* request = this->requests[recv_packet.id];
632                 if (request == NULL)
633                 {
634                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
635                         return;
636                 }
637
638                 if (request->question != recv_packet.question)
639                 {
640                         // This can happen under high latency, drop it silently, do not fail the request
641                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer that isn't for a question we asked");
642                         return;
643                 }
644
645                 if (!valid)
646                 {
647                         ServerInstance->stats.DnsBad++;
648                         recv_packet.error = ERROR_MALFORMED;
649                         request->OnError(&recv_packet);
650                 }
651                 else if (recv_packet.flags & QUERYFLAGS_OPCODE)
652                 {
653                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
654                         ServerInstance->stats.DnsBad++;
655                         recv_packet.error = ERROR_NONSTANDARD_QUERY;
656                         request->OnError(&recv_packet);
657                 }
658                 else if (!(recv_packet.flags & QUERYFLAGS_QR) || (recv_packet.flags & QUERYFLAGS_RCODE))
659                 {
660                         Error error = ERROR_UNKNOWN;
661
662                         switch (recv_packet.flags & QUERYFLAGS_RCODE)
663                         {
664                                 case 1:
665                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
666                                         error = ERROR_FORMAT_ERROR;
667                                         break;
668                                 case 2:
669                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
670                                         error = ERROR_SERVER_FAILURE;
671                                         break;
672                                 case 3:
673                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
674                                         error = ERROR_DOMAIN_NOT_FOUND;
675                                         break;
676                                 case 4:
677                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
678                                         error = ERROR_NOT_IMPLEMENTED;
679                                         break;
680                                 case 5:
681                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
682                                         error = ERROR_REFUSED;
683                                         break;
684                                 default:
685                                         break;
686                         }
687
688                         ServerInstance->stats.DnsBad++;
689                         recv_packet.error = error;
690                         request->OnError(&recv_packet);
691                 }
692                 else if (recv_packet.answers.empty())
693                 {
694                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
695                         ServerInstance->stats.DnsBad++;
696                         recv_packet.error = ERROR_NO_RECORDS;
697                         request->OnError(&recv_packet);
698                 }
699                 else
700                 {
701                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->question.name);
702                         ServerInstance->stats.DnsGood++;
703                         request->OnLookupComplete(&recv_packet);
704                         this->AddCache(recv_packet);
705                 }
706
707                 ServerInstance->stats.Dns++;
708
709                 /* Request's destructor removes it from the request map */
710                 delete request;
711         }
712
713         bool Tick(time_t now) CXX11_OVERRIDE
714         {
715                 unsigned long expired = 0;
716                 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
717                 {
718                         const Query& query = it->second;
719                         if (IsExpired(query, now))
720                         {
721                                 expired++;
722                                 this->cache.erase(it++);
723                         }
724                         else
725                                 ++it;
726                 }
727
728                 if (expired)
729                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purged %lu expired DNS entries", expired);
730
731                 return true;
732         }
733
734         void Rehash(const std::string& dnsserver, std::string sourceaddr, unsigned int sourceport)
735         {
736                 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
737
738                 /* Initialize mastersocket */
739                 Close();
740                 int s = socket(myserver.family(), SOCK_DGRAM, 0);
741                 this->SetFd(s);
742
743                 /* Have we got a socket? */
744                 if (this->HasFd())
745                 {
746                         SocketEngine::SetReuse(s);
747                         SocketEngine::NonBlocking(s);
748
749                         irc::sockets::sockaddrs bindto;
750                         if (sourceaddr.empty())
751                         {
752                                 // set a sourceaddr for irc::sockets::aptosa() based on the servers af type
753                                 if (myserver.family() == AF_INET)
754                                         sourceaddr = "0.0.0.0";
755                                 else if (myserver.family() == AF_INET6)
756                                         sourceaddr = "::";
757                         }
758                         irc::sockets::aptosa(sourceaddr, sourceport, bindto);
759
760                         if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
761                         {
762                                 /* Failed to bind */
763                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
764                                 SocketEngine::Close(this->GetFd());
765                                 this->SetFd(-1);
766                         }
767                         else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
768                         {
769                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
770                                 SocketEngine::Close(this->GetFd());
771                                 this->SetFd(-1);
772                         }
773
774                         if (bindto.family() != myserver.family())
775                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Nameserver address family differs from source address family - hostnames might not resolve");
776                 }
777                 else
778                 {
779                         ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
780                 }
781         }
782 };
783
784 class ModuleDNS : public Module
785 {
786         MyManager manager;
787         std::string DNSServer;
788         std::string SourceIP;
789         unsigned int SourcePort;
790
791         void FindDNSServer()
792         {
793 #ifdef _WIN32
794                 // attempt to look up their nameserver from the system
795                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
796
797                 PFIXED_INFO pFixedInfo;
798                 DWORD dwBufferSize = sizeof(FIXED_INFO);
799                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
800
801                 if (pFixedInfo)
802                 {
803                         if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
804                         {
805                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
806                                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
807                         }
808
809                         if (pFixedInfo)
810                         {
811                                 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
812                                         DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
813
814                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
815                         }
816
817                         if (!DNSServer.empty())
818                         {
819                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
820                                 return;
821                         }
822                 }
823
824                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
825 #else
826                 // attempt to look up their nameserver from /etc/resolv.conf
827                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
828
829                 std::ifstream resolv("/etc/resolv.conf");
830
831                 while (resolv >> DNSServer)
832                 {
833                         if (DNSServer == "nameserver")
834                         {
835                                 resolv >> DNSServer;
836                                 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos || DNSServer.find_first_not_of("0123456789ABCDEFabcdef:") == std::string::npos)
837                                 {
838                                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
839                                         return;
840                                 }
841                         }
842                 }
843
844                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
845 #endif
846                 DNSServer = "127.0.0.1";
847         }
848
849  public:
850         ModuleDNS() : manager(this)
851                 , SourcePort(0)
852         {
853         }
854
855         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
856         {
857                 ConfigTag* tag = ServerInstance->Config->ConfValue("dns");
858                 if (!tag->getBool("enabled", true))
859                 {
860                         // Clear these so they get reset if DNS is enabled again.
861                         DNSServer.clear();
862                         SourceIP.clear();
863                         SourcePort = 0;
864
865                         this->manager.Close();
866                         return;
867                 }
868
869                 const std::string oldserver = DNSServer;
870                 DNSServer = tag->getString("server");
871
872                 const std::string oldip = SourceIP;
873                 SourceIP = tag->getString("sourceip");
874
875                 const unsigned int oldport = SourcePort;
876                 SourcePort = tag->getUInt("sourceport", 0, 0, UINT16_MAX);
877
878                 if (DNSServer.empty())
879                         FindDNSServer();
880
881                 if (oldserver != DNSServer || oldip != SourceIP || oldport != SourcePort)
882                         this->manager.Rehash(DNSServer, SourceIP, SourcePort);
883         }
884
885         void OnUnloadModule(Module* mod) CXX11_OVERRIDE
886         {
887                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
888                 {
889                         DNS::Request* req = this->manager.requests[i];
890                         if (!req)
891                                 continue;
892
893                         if (req->creator == mod)
894                         {
895                                 Query rr(req->question);
896                                 rr.error = ERROR_UNLOADED;
897                                 req->OnError(&rr);
898
899                                 delete req;
900                         }
901                 }
902         }
903
904         Version GetVersion() CXX11_OVERRIDE
905         {
906                 return Version("Provides support for DNS lookups", VF_CORE|VF_VENDOR);
907         }
908 };
909
910 MODULE_INIT(ModuleDNS)
911