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