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