]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_dns.cpp
core_dns Don't store query class code in Question
[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                 for (unsigned i = 0; i < qdcount; ++i)
240                         this->questions.push_back(this->UnpackQuestion(input, len, packet_pos));
241
242                 for (unsigned i = 0; i < ancount; ++i)
243                         this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
244         }
245
246         unsigned short Pack(unsigned char* output, unsigned short output_size)
247         {
248                 if (output_size < HEADER_LENGTH)
249                         throw Exception("Unable to pack packet");
250
251                 unsigned short pos = 0;
252
253                 output[pos++] = this->id >> 8;
254                 output[pos++] = this->id & 0xFF;
255                 output[pos++] = this->flags >> 8;
256                 output[pos++] = this->flags & 0xFF;
257                 output[pos++] = this->questions.size() >> 8;
258                 output[pos++] = this->questions.size() & 0xFF;
259                 output[pos++] = 0; // Answer count, high byte
260                 output[pos++] = 0; // Answer count, low byte
261                 output[pos++] = 0;
262                 output[pos++] = 0;
263                 output[pos++] = 0;
264                 output[pos++] = 0;
265
266                 for (unsigned i = 0; i < this->questions.size(); ++i)
267                 {
268                         Question& q = this->questions[i];
269
270                         if (q.type == QUERY_PTR)
271                         {
272                                 irc::sockets::sockaddrs ip;
273                                 irc::sockets::aptosa(q.name, 0, ip);
274
275                                 if (q.name.find(':') != std::string::npos)
276                                 {
277                                         static const char* const hex = "0123456789abcdef";
278                                         char reverse_ip[128];
279                                         unsigned reverse_ip_count = 0;
280                                         for (int j = 15; j >= 0; --j)
281                                         {
282                                                 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
283                                                 reverse_ip[reverse_ip_count++] = '.';
284                                                 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
285                                                 reverse_ip[reverse_ip_count++] = '.';
286                                         }
287                                         reverse_ip[reverse_ip_count++] = 0;
288
289                                         q.name = reverse_ip;
290                                         q.name += "ip6.arpa";
291                                 }
292                                 else
293                                 {
294                                         unsigned long forward = ip.in4.sin_addr.s_addr;
295                                         ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
296
297                                         q.name = ip.addr() + ".in-addr.arpa";
298                                 }
299                         }
300
301                         this->PackName(output, output_size, pos, q.name);
302
303                         if (pos + 4 >= output_size)
304                                 throw Exception("Unable to pack packet");
305
306                         short s = htons(q.type);
307                         memcpy(&output[pos], &s, 2);
308                         pos += 2;
309
310                         // Query class, always IN
311                         output[pos++] = 0;
312                         output[pos++] = 1;
313                 }
314
315                 return pos;
316         }
317 };
318
319 class MyManager : public Manager, public Timer, public EventHandler
320 {
321         typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
322         cache_map cache;
323
324         irc::sockets::sockaddrs myserver;
325
326         static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
327         {
328                 const ResourceRecord& req = record.answers[0];
329                 return (req.created + static_cast<time_t>(req.ttl) < now);
330         }
331
332         /** Check the DNS cache to see if request can be handled by a cached result
333          * @return true if a cached result was found.
334          */
335         bool CheckCache(DNS::Request* req, const DNS::Question& question)
336         {
337                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
338
339                 cache_map::iterator it = this->cache.find(question);
340                 if (it == this->cache.end())
341                         return false;
342
343                 Query& record = it->second;
344                 if (IsExpired(record))
345                 {
346                         this->cache.erase(it);
347                         return false;
348                 }
349
350                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
351                 record.cached = true;
352                 req->OnLookupComplete(&record);
353                 return true;
354         }
355
356         /** Add a record to the dns cache
357          * @param r The record
358          */
359         void AddCache(Query& r)
360         {
361                 const ResourceRecord& rr = r.answers[0];
362                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
363                 this->cache[r.questions[0]] = r;
364         }
365
366  public:
367         DNS::Request* requests[MAX_REQUEST_ID+1];
368
369         MyManager(Module* c) : Manager(c), Timer(3600, true)
370         {
371                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
372                         requests[i] = NULL;
373                 ServerInstance->Timers.AddTimer(this);
374         }
375
376         ~MyManager()
377         {
378                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
379                 {
380                         DNS::Request* request = requests[i];
381                         if (!request)
382                                 continue;
383
384                         Query rr(*request);
385                         rr.error = ERROR_UNKNOWN;
386                         request->OnError(&rr);
387
388                         delete request;
389                 }
390         }
391
392         void Process(DNS::Request* req)
393         {
394                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->name + " of type " + ConvToStr(req->type) + " to " + this->myserver.addr());
395
396                 /* Create an id */
397                 unsigned int tries = 0;
398                 int id;
399                 do
400                 {
401                         id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
402
403                         if (++tries == DNS::MAX_REQUEST_ID*5)
404                         {
405                                 // If we couldn't find an empty slot this many times, do a sequential scan as a last
406                                 // resort. If an empty slot is found that way, go on, otherwise throw an exception
407                                 id = -1;
408                                 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
409                                 {
410                                         if (!this->requests[i])
411                                         {
412                                                 id = i;
413                                                 break;
414                                         }
415                                 }
416
417                                 if (id == -1)
418                                         throw Exception("DNS: All ids are in use");
419
420                                 break;
421                         }
422                 }
423                 while (this->requests[id]);
424
425                 req->id = id;
426                 this->requests[req->id] = req;
427
428                 Packet p;
429                 p.flags = QUERYFLAGS_RD;
430                 p.id = req->id;
431                 p.questions.push_back(*req);
432
433                 unsigned char buffer[524];
434                 unsigned short len = p.Pack(buffer, sizeof(buffer));
435
436                 /* Note that calling Pack() above can actually change the contents of p.questions[0].name, if the query is a PTR,
437                  * to contain the value that would be in the DNS cache, which is why this is here.
438                  */
439                 if (req->use_cache && this->CheckCache(req, p.questions[0]))
440                 {
441                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
442                         delete req;
443                         return;
444                 }
445
446                 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
447                         throw Exception("DNS: Unable to send query");
448         }
449
450         void RemoveRequest(DNS::Request* req)
451         {
452                 this->requests[req->id] = NULL;
453         }
454
455         std::string GetErrorStr(Error e)
456         {
457                 switch (e)
458                 {
459                         case ERROR_UNLOADED:
460                                 return "Module is unloading";
461                         case ERROR_TIMEDOUT:
462                                 return "Request timed out";
463                         case ERROR_NOT_AN_ANSWER:
464                         case ERROR_NONSTANDARD_QUERY:
465                         case ERROR_FORMAT_ERROR:
466                                 return "Malformed answer";
467                         case ERROR_SERVER_FAILURE:
468                         case ERROR_NOT_IMPLEMENTED:
469                         case ERROR_REFUSED:
470                         case ERROR_INVALIDTYPE:
471                                 return "Nameserver failure";
472                         case ERROR_DOMAIN_NOT_FOUND:
473                         case ERROR_NO_RECORDS:
474                                 return "Domain not found";
475                         case ERROR_NONE:
476                         case ERROR_UNKNOWN:
477                         default:
478                                 return "Unknown error";
479                 }
480         }
481
482         void OnEventHandlerError(int errcode) CXX11_OVERRIDE
483         {
484                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
485         }
486
487         void OnEventHandlerRead() CXX11_OVERRIDE
488         {
489                 unsigned char buffer[524];
490                 irc::sockets::sockaddrs from;
491                 socklen_t x = sizeof(from);
492
493                 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
494
495                 if (length < Packet::HEADER_LENGTH)
496                         return;
497
498                 if (myserver != from)
499                 {
500                         std::string server1 = from.str();
501                         std::string server2 = myserver.str();
502                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
503                                 server1.c_str(), server2.c_str());
504                         return;
505                 }
506
507                 Packet recv_packet;
508
509                 try
510                 {
511                         recv_packet.Fill(buffer, length);
512                 }
513                 catch (Exception& ex)
514                 {
515                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
516                         return;
517                 }
518
519                 DNS::Request* request = this->requests[recv_packet.id];
520                 if (request == NULL)
521                 {
522                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
523                         return;
524                 }
525
526                 if (recv_packet.flags & QUERYFLAGS_OPCODE)
527                 {
528                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
529                         ServerInstance->stats.DnsBad++;
530                         recv_packet.error = ERROR_NONSTANDARD_QUERY;
531                         request->OnError(&recv_packet);
532                 }
533                 else if (recv_packet.flags & QUERYFLAGS_RCODE)
534                 {
535                         Error error = ERROR_UNKNOWN;
536
537                         switch (recv_packet.flags & QUERYFLAGS_RCODE)
538                         {
539                                 case 1:
540                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
541                                         error = ERROR_FORMAT_ERROR;
542                                         break;
543                                 case 2:
544                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
545                                         error = ERROR_SERVER_FAILURE;
546                                         break;
547                                 case 3:
548                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
549                                         error = ERROR_DOMAIN_NOT_FOUND;
550                                         break;
551                                 case 4:
552                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
553                                         error = ERROR_NOT_IMPLEMENTED;
554                                         break;
555                                 case 5:
556                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
557                                         error = ERROR_REFUSED;
558                                         break;
559                                 default:
560                                         break;
561                         }
562
563                         ServerInstance->stats.DnsBad++;
564                         recv_packet.error = error;
565                         request->OnError(&recv_packet);
566                 }
567                 else if (recv_packet.questions.empty() || recv_packet.answers.empty())
568                 {
569                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
570                         ServerInstance->stats.DnsBad++;
571                         recv_packet.error = ERROR_NO_RECORDS;
572                         request->OnError(&recv_packet);
573                 }
574                 else
575                 {
576                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
577                         ServerInstance->stats.DnsGood++;
578                         request->OnLookupComplete(&recv_packet);
579                         this->AddCache(recv_packet);
580                 }
581
582                 ServerInstance->stats.Dns++;
583
584                 /* Request's destructor removes it from the request map */
585                 delete request;
586         }
587
588         bool Tick(time_t now)
589         {
590                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
591
592                 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
593                 {
594                         const Query& query = it->second;
595                         if (IsExpired(query, now))
596                                 this->cache.erase(it++);
597                         else
598                                 ++it;
599                 }
600                 return true;
601         }
602
603         void Rehash(const std::string& dnsserver)
604         {
605                 if (this->GetFd() > -1)
606                 {
607                         SocketEngine::Shutdown(this, 2);
608                         SocketEngine::Close(this);
609
610                         /* Remove expired entries from the cache */
611                         this->Tick(ServerInstance->Time());
612                 }
613
614                 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
615
616                 /* Initialize mastersocket */
617                 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
618                 this->SetFd(s);
619
620                 /* Have we got a socket? */
621                 if (this->GetFd() != -1)
622                 {
623                         SocketEngine::SetReuse(s);
624                         SocketEngine::NonBlocking(s);
625
626                         irc::sockets::sockaddrs bindto;
627                         memset(&bindto, 0, sizeof(bindto));
628                         bindto.sa.sa_family = myserver.sa.sa_family;
629
630                         if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
631                         {
632                                 /* Failed to bind */
633                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
634                                 SocketEngine::Close(this->GetFd());
635                                 this->SetFd(-1);
636                         }
637                         else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
638                         {
639                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
640                                 SocketEngine::Close(this->GetFd());
641                                 this->SetFd(-1);
642                         }
643                 }
644                 else
645                 {
646                         ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
647                 }
648         }
649 };
650
651 class ModuleDNS : public Module
652 {
653         MyManager manager;
654         std::string DNSServer;
655
656         void FindDNSServer()
657         {
658 #ifdef _WIN32
659                 // attempt to look up their nameserver from the system
660                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
661
662                 PFIXED_INFO pFixedInfo;
663                 DWORD dwBufferSize = sizeof(FIXED_INFO);
664                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
665
666                 if (pFixedInfo)
667                 {
668                         if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
669                         {
670                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
671                                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
672                         }
673
674                         if (pFixedInfo)
675                         {
676                                 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
677                                         DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
678
679                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
680                         }
681
682                         if (!DNSServer.empty())
683                         {
684                                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
685                                 return;
686                         }
687                 }
688
689                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
690 #else
691                 // attempt to look up their nameserver from /etc/resolv.conf
692                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
693
694                 std::ifstream resolv("/etc/resolv.conf");
695
696                 while (resolv >> DNSServer)
697                 {
698                         if (DNSServer == "nameserver")
699                         {
700                                 resolv >> DNSServer;
701                                 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
702                                 {
703                                         ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
704                                         return;
705                                 }
706                         }
707                 }
708
709                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
710 #endif
711                 DNSServer = "127.0.0.1";
712         }
713
714  public:
715         ModuleDNS() : manager(this)
716         {
717         }
718
719         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
720         {
721                 std::string oldserver = DNSServer;
722                 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
723                 if (DNSServer.empty())
724                         FindDNSServer();
725
726                 if (oldserver != DNSServer)
727                         this->manager.Rehash(DNSServer);
728         }
729
730         void OnUnloadModule(Module* mod)
731         {
732                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
733                 {
734                         DNS::Request* req = this->manager.requests[i];
735                         if (!req)
736                                 continue;
737
738                         if (req->creator == mod)
739                         {
740                                 Query rr(*req);
741                                 rr.error = ERROR_UNLOADED;
742                                 req->OnError(&rr);
743
744                                 delete req;
745                         }
746                 }
747         }
748
749         Version GetVersion()
750         {
751                 return Version("DNS support", VF_CORE|VF_VENDOR);
752         }
753 };
754
755 MODULE_INIT(ModuleDNS)
756