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