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