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