]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_dns.cpp
core_dns Remove incomplete support for multiple questions per query
[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                 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
448                         throw Exception("DNS: Unable to send query");
449         }
450
451         void RemoveRequest(DNS::Request* req)
452         {
453                 this->requests[req->id] = NULL;
454         }
455
456         std::string GetErrorStr(Error e)
457         {
458                 switch (e)
459                 {
460                         case ERROR_UNLOADED:
461                                 return "Module is unloading";
462                         case ERROR_TIMEDOUT:
463                                 return "Request timed out";
464                         case ERROR_NOT_AN_ANSWER:
465                         case ERROR_NONSTANDARD_QUERY:
466                         case ERROR_FORMAT_ERROR:
467                                 return "Malformed answer";
468                         case ERROR_SERVER_FAILURE:
469                         case ERROR_NOT_IMPLEMENTED:
470                         case ERROR_REFUSED:
471                         case ERROR_INVALIDTYPE:
472                                 return "Nameserver failure";
473                         case ERROR_DOMAIN_NOT_FOUND:
474                         case ERROR_NO_RECORDS:
475                                 return "Domain not found";
476                         case ERROR_NONE:
477                         case ERROR_UNKNOWN:
478                         default:
479                                 return "Unknown error";
480                 }
481         }
482
483         void OnEventHandlerError(int errcode) CXX11_OVERRIDE
484         {
485                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
486         }
487
488         void OnEventHandlerRead() CXX11_OVERRIDE
489         {
490                 unsigned char buffer[524];
491                 irc::sockets::sockaddrs from;
492                 socklen_t x = sizeof(from);
493
494                 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
495
496                 if (length < Packet::HEADER_LENGTH)
497                         return;
498
499                 if (myserver != from)
500                 {
501                         std::string server1 = from.str();
502                         std::string server2 = myserver.str();
503                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
504                                 server1.c_str(), server2.c_str());
505                         return;
506                 }
507
508                 Packet recv_packet;
509
510                 try
511                 {
512                         recv_packet.Fill(buffer, length);
513                 }
514                 catch (Exception& ex)
515                 {
516                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
517                         return;
518                 }
519
520                 DNS::Request* request = this->requests[recv_packet.id];
521                 if (request == NULL)
522                 {
523                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
524                         return;
525                 }
526
527                 if (recv_packet.flags & QUERYFLAGS_OPCODE)
528                 {
529                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
530                         ServerInstance->stats.DnsBad++;
531                         recv_packet.error = ERROR_NONSTANDARD_QUERY;
532                         request->OnError(&recv_packet);
533                 }
534                 else if (recv_packet.flags & QUERYFLAGS_RCODE)
535                 {
536                         Error error = ERROR_UNKNOWN;
537
538                         switch (recv_packet.flags & QUERYFLAGS_RCODE)
539                         {
540                                 case 1:
541                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
542                                         error = ERROR_FORMAT_ERROR;
543                                         break;
544                                 case 2:
545                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
546                                         error = ERROR_SERVER_FAILURE;
547                                         break;
548                                 case 3:
549                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
550                                         error = ERROR_DOMAIN_NOT_FOUND;
551                                         break;
552                                 case 4:
553                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
554                                         error = ERROR_NOT_IMPLEMENTED;
555                                         break;
556                                 case 5:
557                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
558                                         error = ERROR_REFUSED;
559                                         break;
560                                 default:
561                                         break;
562                         }
563
564                         ServerInstance->stats.DnsBad++;
565                         recv_packet.error = error;
566                         request->OnError(&recv_packet);
567                 }
568                 else if (recv_packet.answers.empty())
569                 {
570                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
571                         ServerInstance->stats.DnsBad++;
572                         recv_packet.error = ERROR_NO_RECORDS;
573                         request->OnError(&recv_packet);
574                 }
575                 else
576                 {
577                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
578                         ServerInstance->stats.DnsGood++;
579                         request->OnLookupComplete(&recv_packet);
580                         this->AddCache(recv_packet);
581                 }
582
583                 ServerInstance->stats.Dns++;
584
585                 /* Request's destructor removes it from the request map */
586                 delete request;
587         }
588
589         bool Tick(time_t now)
590         {
591                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
592
593                 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
594                 {
595                         const Query& query = it->second;
596                         if (IsExpired(query, now))
597                                 this->cache.erase(it++);
598                         else
599                                 ++it;
600                 }
601                 return true;
602         }
603
604         void Rehash(const std::string& dnsserver)
605         {
606                 if (this->GetFd() > -1)
607                 {
608                         SocketEngine::Shutdown(this, 2);
609                         SocketEngine::Close(this);
610
611                         /* Remove expired entries from the cache */
612                         this->Tick(ServerInstance->Time());
613                 }
614
615                 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
616
617                 /* Initialize mastersocket */
618                 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
619                 this->SetFd(s);
620
621                 /* Have we got a socket? */
622                 if (this->GetFd() != -1)
623                 {
624                         SocketEngine::SetReuse(s);
625                         SocketEngine::NonBlocking(s);
626
627                         irc::sockets::sockaddrs bindto;
628                         memset(&bindto, 0, sizeof(bindto));
629                         bindto.sa.sa_family = myserver.sa.sa_family;
630
631                         if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
632                         {
633                                 /* Failed to bind */
634                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
635                                 SocketEngine::Close(this->GetFd());
636                                 this->SetFd(-1);
637                         }
638                         else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
639                         {
640                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
641                                 SocketEngine::Close(this->GetFd());
642                                 this->SetFd(-1);
643                         }
644                 }
645                 else
646                 {
647                         ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
648                 }
649         }
650 };
651
652 class ModuleDNS : public Module
653 {
654         MyManager manager;
655         std::string DNSServer;
656
657         void FindDNSServer()
658         {
659 #ifdef _WIN32
660                 // attempt to look up their nameserver from the system
661                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
662
663                 PFIXED_INFO pFixedInfo;
664                 DWORD dwBufferSize = sizeof(FIXED_INFO);
665                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
666
667                 if (pFixedInfo)
668                 {
669                         if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
670                         {
671                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
672                                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
673                         }
674
675                         if (pFixedInfo)
676                         {
677                                 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
678                                         DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
679
680                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
681                         }
682
683                         if (!DNSServer.empty())
684                         {
685                                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
686                                 return;
687                         }
688                 }
689
690                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
691 #else
692                 // attempt to look up their nameserver from /etc/resolv.conf
693                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
694
695                 std::ifstream resolv("/etc/resolv.conf");
696
697                 while (resolv >> DNSServer)
698                 {
699                         if (DNSServer == "nameserver")
700                         {
701                                 resolv >> DNSServer;
702                                 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
703                                 {
704                                         ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
705                                         return;
706                                 }
707                         }
708                 }
709
710                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
711 #endif
712                 DNSServer = "127.0.0.1";
713         }
714
715  public:
716         ModuleDNS() : manager(this)
717         {
718         }
719
720         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
721         {
722                 std::string oldserver = DNSServer;
723                 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
724                 if (DNSServer.empty())
725                         FindDNSServer();
726
727                 if (oldserver != DNSServer)
728                         this->manager.Rehash(DNSServer);
729         }
730
731         void OnUnloadModule(Module* mod)
732         {
733                 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
734                 {
735                         DNS::Request* req = this->manager.requests[i];
736                         if (!req)
737                                 continue;
738
739                         if (req->creator == mod)
740                         {
741                                 Query rr(*req);
742                                 rr.error = ERROR_UNLOADED;
743                                 req->OnError(&rr);
744
745                                 delete req;
746                         }
747                 }
748         }
749
750         Version GetVersion()
751         {
752                 return Version("DNS support", VF_CORE|VF_VENDOR);
753         }
754 };
755
756 MODULE_INIT(ModuleDNS)
757