]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_dns.cpp
de8dedd4ac41e260eb0f773d25ce261020275137
[user/henk/code/inspircd.git] / src / coremods / core_dns.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2013 Adam <Adam@anope.org>
5  *   Copyright (C) 2003-2013 Anope Team <team@anope.org>
6  *
7  * This file is part of InspIRCd.  InspIRCd is free software: you can
8  * redistribute it and/or modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation, version 2.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "inspircd.h"
21 #include "modules/dns.h"
22 #include <iostream>
23 #include <fstream>
24
25 #ifdef _WIN32
26 #include <Iphlpapi.h>
27 #pragma comment(lib, "Iphlpapi.lib")
28 #endif
29
30 using namespace DNS;
31
32 /** A full packet sent or recieved to/from the nameserver
33  */
34 class Packet : public Query
35 {
36         void PackName(unsigned char* output, unsigned short output_size, unsigned short& pos, const std::string& name)
37         {
38                 if (pos + name.length() + 2 > output_size)
39                         throw Exception("Unable to pack name");
40
41                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Packing name " + name);
42
43                 irc::sepstream sep(name, '.');
44                 std::string token;
45
46                 while (sep.GetToken(token))
47                 {
48                         output[pos++] = token.length();
49                         memcpy(&output[pos], token.data(), token.length());
50                         pos += token.length();
51                 }
52
53                 output[pos++] = 0;
54         }
55
56         std::string UnpackName(const unsigned char* input, unsigned short input_size, unsigned short& pos)
57         {
58                 std::string name;
59                 unsigned short pos_ptr = pos, lowest_ptr = input_size;
60                 bool compressed = false;
61
62                 if (pos_ptr >= input_size)
63                         throw Exception("Unable to unpack name - no input");
64
65                 while (input[pos_ptr] > 0)
66                 {
67                         unsigned short offset = input[pos_ptr];
68
69                         if (offset & POINTER)
70                         {
71                                 if ((offset & POINTER) != POINTER)
72                                         throw Exception("Unable to unpack name - bogus compression header");
73                                 if (pos_ptr + 1 >= input_size)
74                                         throw Exception("Unable to unpack name - bogus compression header");
75
76                                 /* Place pos at the second byte of the first (farthest) compression pointer */
77                                 if (compressed == false)
78                                 {
79                                         ++pos;
80                                         compressed = true;
81                                 }
82
83                                 pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1];
84
85                                 /* Pointers can only go back */
86                                 if (pos_ptr >= lowest_ptr)
87                                         throw Exception("Unable to unpack name - bogus compression pointer");
88                                 lowest_ptr = pos_ptr;
89                         }
90                         else
91                         {
92                                 if (pos_ptr + offset + 1 >= input_size)
93                                         throw Exception("Unable to unpack name - offset too large");
94                                 if (!name.empty())
95                                         name += ".";
96                                 for (unsigned i = 1; i <= offset; ++i)
97                                         name += input[pos_ptr + i];
98
99                                 pos_ptr += offset + 1;
100                                 if (compressed == false)
101                                         /* Move up pos */
102                                         pos = pos_ptr;
103                         }
104                 }
105
106                 /* +1 pos either to one byte after the compression pointer or one byte after the ending \0 */
107                 ++pos;
108
109                 if (name.empty())
110                         throw Exception("Unable to unpack name - no name");
111
112                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unpack name " + name);
113
114                 return name;
115         }
116
117         Question UnpackQuestion(const unsigned char* input, unsigned short input_size, unsigned short& pos)
118         {
119                 Question 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(MODNAME, LOG_DEBUG, record.name + " -> " + record.rdata);
194
195                 return record;
196         }
197
198  public:
199         static const int POINTER = 0xC0;
200         static const int LABEL = 0x3F;
201         static const int HEADER_LENGTH = 12;
202
203         /* ID for this packet */
204         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(MODNAME, LOG_DEBUG, "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(MODNAME, LOG_SPARSE, "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(MODNAME, LOG_DEBUG, "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(MODNAME, LOG_DEBUG, "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, 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(MODNAME, LOG_DEBUG, "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(MODNAME, LOG_DEBUG, "Using cached result");
518                         delete req;
519                         return;
520                 }
521
522                 if (SocketEngine::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 OnEventHandlerError(int errcode) CXX11_OVERRIDE
559         {
560                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
561         }
562
563         void OnEventHandlerRead() CXX11_OVERRIDE
564         {
565                 unsigned char buffer[524];
566                 irc::sockets::sockaddrs from;
567                 socklen_t x = sizeof(from);
568
569                 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
570
571                 if (length < Packet::HEADER_LENGTH)
572                         return;
573
574                 Packet recv_packet;
575
576                 try
577                 {
578                         recv_packet.Fill(buffer, length);
579                 }
580                 catch (Exception& ex)
581                 {
582                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
583                         return;
584                 }
585
586                 if (myserver != from)
587                 {
588                         std::string server1 = from.str();
589                         std::string server2 = myserver.str();
590                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
591                                 server1.c_str(), server2.c_str());
592                         return;
593                 }
594
595                 DNS::Request* request = this->requests[recv_packet.id];
596                 if (request == NULL)
597                 {
598                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
599                         return;
600                 }
601
602                 if (recv_packet.flags & QUERYFLAGS_OPCODE)
603                 {
604                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
605                         ServerInstance->stats.DnsBad++;
606                         recv_packet.error = ERROR_NONSTANDARD_QUERY;
607                         request->OnError(&recv_packet);
608                 }
609                 else if (recv_packet.flags & QUERYFLAGS_RCODE)
610                 {
611                         Error error = ERROR_UNKNOWN;
612
613                         switch (recv_packet.flags & QUERYFLAGS_RCODE)
614                         {
615                                 case 1:
616                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
617                                         error = ERROR_FORMAT_ERROR;
618                                         break;
619                                 case 2:
620                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
621                                         error = ERROR_SERVER_FAILURE;
622                                         break;
623                                 case 3:
624                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
625                                         error = ERROR_DOMAIN_NOT_FOUND;
626                                         break;
627                                 case 4:
628                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
629                                         error = ERROR_NOT_IMPLEMENTED;
630                                         break;
631                                 case 5:
632                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
633                                         error = ERROR_REFUSED;
634                                         break;
635                                 default:
636                                         break;
637                         }
638
639                         ServerInstance->stats.DnsBad++;
640                         recv_packet.error = error;
641                         request->OnError(&recv_packet);
642                 }
643                 else if (recv_packet.questions.empty() || recv_packet.answers.empty())
644                 {
645                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
646                         ServerInstance->stats.DnsBad++;
647                         recv_packet.error = ERROR_NO_RECORDS;
648                         request->OnError(&recv_packet);
649                 }
650                 else
651                 {
652                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
653                         ServerInstance->stats.DnsGood++;
654                         request->OnLookupComplete(&recv_packet);
655                         this->AddCache(recv_packet);
656                 }
657
658                 ServerInstance->stats.Dns++;
659
660                 /* Request's destructor removes it from the request map */
661                 delete request;
662         }
663
664         bool Tick(time_t now)
665         {
666                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
667
668                 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
669                 {
670                         const Query& query = it->second;
671                         if (IsExpired(query, now))
672                                 this->cache.erase(it++);
673                         else
674                                 ++it;
675                 }
676                 return true;
677         }
678
679         void Rehash(const std::string& dnsserver)
680         {
681                 if (this->GetFd() > -1)
682                 {
683                         SocketEngine::Shutdown(this, 2);
684                         SocketEngine::Close(this);
685
686                         /* Remove expired entries from the cache */
687                         this->Tick(ServerInstance->Time());
688                 }
689
690                 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
691
692                 /* Initialize mastersocket */
693                 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
694                 this->SetFd(s);
695
696                 /* Have we got a socket? */
697                 if (this->GetFd() != -1)
698                 {
699                         SocketEngine::SetReuse(s);
700                         SocketEngine::NonBlocking(s);
701
702                         irc::sockets::sockaddrs bindto;
703                         memset(&bindto, 0, sizeof(bindto));
704                         bindto.sa.sa_family = myserver.sa.sa_family;
705
706                         if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
707                         {
708                                 /* Failed to bind */
709                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
710                                 SocketEngine::Close(this->GetFd());
711                                 this->SetFd(-1);
712                         }
713                         else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
714                         {
715                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
716                                 SocketEngine::Close(this->GetFd());
717                                 this->SetFd(-1);
718                         }
719                 }
720                 else
721                 {
722                         ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
723                 }
724         }
725 };
726
727 class ModuleDNS : public Module
728 {
729         MyManager manager;
730         std::string DNSServer;
731
732         void FindDNSServer()
733         {
734 #ifdef _WIN32
735                 // attempt to look up their nameserver from the system
736                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
737
738                 PFIXED_INFO pFixedInfo;
739                 DWORD dwBufferSize = sizeof(FIXED_INFO);
740                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
741
742                 if (pFixedInfo)
743                 {
744                         if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
745                         {
746                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
747                                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
748                         }
749
750                         if (pFixedInfo)
751                         {
752                                 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
753                                         DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
754
755                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
756                         }
757
758                         if (!DNSServer.empty())
759                         {
760                                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
761                                 return;
762                         }
763                 }
764
765                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
766 #else
767                 // attempt to look up their nameserver from /etc/resolv.conf
768                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
769
770                 std::ifstream resolv("/etc/resolv.conf");
771
772                 while (resolv >> DNSServer)
773                 {
774                         if (DNSServer == "nameserver")
775                         {
776                                 resolv >> DNSServer;
777                                 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
778                                 {
779                                         ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
780                                         return;
781                                 }
782                         }
783                 }
784
785                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
786 #endif
787                 DNSServer = "127.0.0.1";
788         }
789
790  public:
791         ModuleDNS() : manager(this)
792         {
793         }
794
795         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
796         {
797                 std::string oldserver = DNSServer;
798                 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
799                 if (DNSServer.empty())
800                         FindDNSServer();
801
802                 if (oldserver != DNSServer)
803                         this->manager.Rehash(DNSServer);
804         }
805
806         void OnUnloadModule(Module* mod)
807         {
808                 for (int i = 0; i < MAX_REQUEST_ID; ++i)
809                 {
810                         DNS::Request* req = this->manager.requests[i];
811                         if (!req)
812                                 continue;
813
814                         if (req->creator == mod)
815                         {
816                                 Query rr(*req);
817                                 rr.error = ERROR_UNLOADED;
818                                 req->OnError(&rr);
819
820                                 delete req;
821                         }
822                 }
823         }
824
825         Version GetVersion()
826         {
827                 return Version("DNS support", VF_CORE|VF_VENDOR);
828         }
829 };
830
831 MODULE_INIT(ModuleDNS)
832