]> 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-2020 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                 unloading = true;
427
428                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
429                 {
430                         DNS::Request* request = requests[i];
431                         if (!request)
432                                 continue;
433
434                         Query rr(request->question);
435                         rr.error = ERROR_UNKNOWN;
436                         request->OnError(&rr);
437
438                         delete request;
439                 }
440         }
441
442         void Process(DNS::Request* req) CXX11_OVERRIDE
443         {
444                 if ((unloading) || (req->creator->dying))
445                         throw Exception("Module is being unloaded");
446
447                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->question.name + " of type " + ConvToStr(req->question.type) + " to " + this->myserver.addr());
448
449                 /* Create an id */
450                 unsigned int tries = 0;
451                 int id;
452                 do
453                 {
454                         id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
455
456                         if (++tries == DNS::MAX_REQUEST_ID*5)
457                         {
458                                 // If we couldn't find an empty slot this many times, do a sequential scan as a last
459                                 // resort. If an empty slot is found that way, go on, otherwise throw an exception
460                                 id = -1;
461                                 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
462                                 {
463                                         if (!this->requests[i])
464                                         {
465                                                 id = i;
466                                                 break;
467                                         }
468                                 }
469
470                                 if (id == -1)
471                                         throw Exception("DNS: All ids are in use");
472
473                                 break;
474                         }
475                 }
476                 while (this->requests[id]);
477
478                 req->id = id;
479                 this->requests[req->id] = req;
480
481                 Packet p;
482                 p.flags = QUERYFLAGS_RD;
483                 p.id = req->id;
484                 p.question = req->question;
485
486                 unsigned char buffer[524];
487                 unsigned short len = p.Pack(buffer, sizeof(buffer));
488
489                 /* Note that calling Pack() above can actually change the contents of p.question.name, if the query is a PTR,
490                  * to contain the value that would be in the DNS cache, which is why this is here.
491                  */
492                 if (req->use_cache && this->CheckCache(req, p.question))
493                 {
494                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
495                         delete req;
496                         return;
497                 }
498
499                 // Update name in the original request so question checking works for PTR queries
500                 req->question.name = p.question.name;
501
502                 if (SocketEngine::SendTo(this, buffer, len, 0, this->myserver) != len)
503                         throw Exception("DNS: Unable to send query");
504
505                 // Add timer for timeout
506                 ServerInstance->Timers.AddTimer(req);
507         }
508
509         void RemoveRequest(DNS::Request* req) CXX11_OVERRIDE
510         {
511                 if (requests[req->id] == req)
512                         requests[req->id] = NULL;
513         }
514
515         std::string GetErrorStr(Error e) CXX11_OVERRIDE
516         {
517                 switch (e)
518                 {
519                         case ERROR_UNLOADED:
520                                 return "Module is unloading";
521                         case ERROR_TIMEDOUT:
522                                 return "Request timed out";
523                         case ERROR_NOT_AN_ANSWER:
524                         case ERROR_NONSTANDARD_QUERY:
525                         case ERROR_FORMAT_ERROR:
526                         case ERROR_MALFORMED:
527                                 return "Malformed answer";
528                         case ERROR_SERVER_FAILURE:
529                         case ERROR_NOT_IMPLEMENTED:
530                         case ERROR_REFUSED:
531                         case ERROR_INVALIDTYPE:
532                                 return "Nameserver failure";
533                         case ERROR_DOMAIN_NOT_FOUND:
534                         case ERROR_NO_RECORDS:
535                                 return "Domain not found";
536                         case ERROR_NONE:
537                         case ERROR_UNKNOWN:
538                         default:
539                                 return "Unknown error";
540                 }
541         }
542
543         std::string GetTypeStr(QueryType qt) CXX11_OVERRIDE
544         {
545                 switch (qt)
546                 {
547                         case QUERY_A:
548                                 return "A";
549                         case QUERY_AAAA:
550                                 return "AAAA";
551                         case QUERY_CNAME:
552                                 return "CNAME";
553                         case QUERY_PTR:
554                                 return "PTR";
555                         case QUERY_TXT:
556                                 return "TXT";
557                         default:
558                                 return "UNKNOWN";
559                 }
560         }
561
562         void OnEventHandlerError(int errcode) CXX11_OVERRIDE
563         {
564                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
565         }
566
567         void OnEventHandlerRead() CXX11_OVERRIDE
568         {
569                 unsigned char buffer[524];
570                 irc::sockets::sockaddrs from;
571                 socklen_t x = sizeof(from);
572
573                 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
574
575                 if (length < Packet::HEADER_LENGTH)
576                         return;
577
578                 if (myserver != from)
579                 {
580                         std::string server1 = from.str();
581                         std::string server2 = myserver.str();
582                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
583                                 server1.c_str(), server2.c_str());
584                         return;
585                 }
586
587                 Packet recv_packet;
588                 bool valid = false;
589
590                 try
591                 {
592                         recv_packet.Fill(buffer, length);
593                         valid = true;
594                 }
595                 catch (Exception& ex)
596                 {
597                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
598                 }
599
600                 // recv_packet.id must be filled in here
601                 DNS::Request* request = this->requests[recv_packet.id];
602                 if (request == NULL)
603                 {
604                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
605                         return;
606                 }
607
608                 if (request->question != recv_packet.question)
609                 {
610                         // This can happen under high latency, drop it silently, do not fail the request
611                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer that isn't for a question we asked");
612                         return;
613                 }
614
615                 if (!valid)
616                 {
617                         ServerInstance->stats.DnsBad++;
618                         recv_packet.error = ERROR_MALFORMED;
619                         request->OnError(&recv_packet);
620                 }
621                 else if (recv_packet.flags & QUERYFLAGS_OPCODE)
622                 {
623                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
624                         ServerInstance->stats.DnsBad++;
625                         recv_packet.error = ERROR_NONSTANDARD_QUERY;
626                         request->OnError(&recv_packet);
627                 }
628                 else if (!(recv_packet.flags & QUERYFLAGS_QR) || (recv_packet.flags & QUERYFLAGS_RCODE))
629                 {
630                         Error error = ERROR_UNKNOWN;
631
632                         switch (recv_packet.flags & QUERYFLAGS_RCODE)
633                         {
634                                 case 1:
635                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
636                                         error = ERROR_FORMAT_ERROR;
637                                         break;
638                                 case 2:
639                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
640                                         error = ERROR_SERVER_FAILURE;
641                                         break;
642                                 case 3:
643                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
644                                         error = ERROR_DOMAIN_NOT_FOUND;
645                                         break;
646                                 case 4:
647                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
648                                         error = ERROR_NOT_IMPLEMENTED;
649                                         break;
650                                 case 5:
651                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
652                                         error = ERROR_REFUSED;
653                                         break;
654                                 default:
655                                         break;
656                         }
657
658                         ServerInstance->stats.DnsBad++;
659                         recv_packet.error = error;
660                         request->OnError(&recv_packet);
661                 }
662                 else if (recv_packet.answers.empty())
663                 {
664                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
665                         ServerInstance->stats.DnsBad++;
666                         recv_packet.error = ERROR_NO_RECORDS;
667                         request->OnError(&recv_packet);
668                 }
669                 else
670                 {
671                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->question.name);
672                         ServerInstance->stats.DnsGood++;
673                         request->OnLookupComplete(&recv_packet);
674                         this->AddCache(recv_packet);
675                 }
676
677                 ServerInstance->stats.Dns++;
678
679                 /* Request's destructor removes it from the request map */
680                 delete request;
681         }
682
683         bool Tick(time_t now) CXX11_OVERRIDE
684         {
685                 unsigned long expired = 0;
686                 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
687                 {
688                         const Query& query = it->second;
689                         if (IsExpired(query, now))
690                         {
691                                 expired++;
692                                 this->cache.erase(it++);
693                         }
694                         else
695                                 ++it;
696                 }
697
698                 if (expired)
699                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purged %lu expired DNS entries", expired);
700
701                 return true;
702         }
703
704         void Rehash(const std::string& dnsserver, std::string sourceaddr, unsigned int sourceport)
705         {
706                 if (this->GetFd() > -1)
707                 {
708                         SocketEngine::Shutdown(this, 2);
709                         SocketEngine::Close(this);
710
711                         /* Remove expired entries from the cache */
712                         this->Tick(ServerInstance->Time());
713                 }
714
715                 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
716
717                 /* Initialize mastersocket */
718                 int s = socket(myserver.family(), SOCK_DGRAM, 0);
719                 this->SetFd(s);
720
721                 /* Have we got a socket? */
722                 if (this->GetFd() != -1)
723                 {
724                         SocketEngine::SetReuse(s);
725                         SocketEngine::NonBlocking(s);
726
727                         irc::sockets::sockaddrs bindto;
728                         if (sourceaddr.empty())
729                         {
730                                 // set a sourceaddr for irc::sockets::aptosa() based on the servers af type
731                                 if (myserver.family() == AF_INET)
732                                         sourceaddr = "0.0.0.0";
733                                 else if (myserver.family() == AF_INET6)
734                                         sourceaddr = "::";
735                         }
736                         irc::sockets::aptosa(sourceaddr, sourceport, bindto);
737
738                         if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
739                         {
740                                 /* Failed to bind */
741                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
742                                 SocketEngine::Close(this->GetFd());
743                                 this->SetFd(-1);
744                         }
745                         else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
746                         {
747                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
748                                 SocketEngine::Close(this->GetFd());
749                                 this->SetFd(-1);
750                         }
751
752                         if (bindto.family() != myserver.family())
753                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Nameserver address family differs from source address family - hostnames might not resolve");
754                 }
755                 else
756                 {
757                         ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
758                 }
759         }
760 };
761
762 class ModuleDNS : public Module
763 {
764         MyManager manager;
765         std::string DNSServer;
766         std::string SourceIP;
767         unsigned int SourcePort;
768
769         void FindDNSServer()
770         {
771 #ifdef _WIN32
772                 // attempt to look up their nameserver from the system
773                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
774
775                 PFIXED_INFO pFixedInfo;
776                 DWORD dwBufferSize = sizeof(FIXED_INFO);
777                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
778
779                 if (pFixedInfo)
780                 {
781                         if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
782                         {
783                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
784                                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
785                         }
786
787                         if (pFixedInfo)
788                         {
789                                 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
790                                         DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
791
792                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
793                         }
794
795                         if (!DNSServer.empty())
796                         {
797                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
798                                 return;
799                         }
800                 }
801
802                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
803 #else
804                 // attempt to look up their nameserver from /etc/resolv.conf
805                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
806
807                 std::ifstream resolv("/etc/resolv.conf");
808
809                 while (resolv >> DNSServer)
810                 {
811                         if (DNSServer == "nameserver")
812                         {
813                                 resolv >> DNSServer;
814                                 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos || DNSServer.find_first_not_of("0123456789ABCDEFabcdef:") == std::string::npos)
815                                 {
816                                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
817                                         return;
818                                 }
819                         }
820                 }
821
822                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
823 #endif
824                 DNSServer = "127.0.0.1";
825         }
826
827  public:
828         ModuleDNS() : manager(this)
829                 , SourcePort(0)
830         {
831         }
832
833         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
834         {
835                 std::string oldserver = DNSServer;
836                 const std::string oldip = SourceIP;
837                 const unsigned int oldport = SourcePort;
838
839                 ConfigTag* tag = ServerInstance->Config->ConfValue("dns");
840                 DNSServer = tag->getString("server");
841                 SourceIP = tag->getString("sourceip");
842                 SourcePort = tag->getUInt("sourceport", 0, 0, UINT16_MAX);
843
844                 if (DNSServer.empty())
845                         FindDNSServer();
846
847                 if (oldserver != DNSServer || oldip != SourceIP || oldport != SourcePort)
848                         this->manager.Rehash(DNSServer, SourceIP, SourcePort);
849         }
850
851         void OnUnloadModule(Module* mod) CXX11_OVERRIDE
852         {
853                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
854                 {
855                         DNS::Request* req = this->manager.requests[i];
856                         if (!req)
857                                 continue;
858
859                         if (req->creator == mod)
860                         {
861                                 Query rr(req->question);
862                                 rr.error = ERROR_UNLOADED;
863                                 req->OnError(&rr);
864
865                                 delete req;
866                         }
867                 }
868         }
869
870         Version GetVersion() CXX11_OVERRIDE
871         {
872                 return Version("Provides support for DNS lookups", VF_CORE|VF_VENDOR);
873         }
874 };
875
876 MODULE_INIT(ModuleDNS)
877