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