]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/coremods/core_dns.cpp
core_dns Allow usage of id 0
[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                 int id;
477                 do
478                 {
479                         id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID);
480
481                         if (++tries == DNS::MAX_REQUEST_ID*5)
482                         {
483                                 // If we couldn't find an empty slot this many times, do a sequential scan as a last
484                                 // resort. If an empty slot is found that way, go on, otherwise throw an exception
485                                 id = -1;
486                                 for (unsigned int i = 0; i < DNS::MAX_REQUEST_ID; i++)
487                                 {
488                                         if (!this->requests[i])
489                                         {
490                                                 id = i;
491                                                 break;
492                                         }
493                                 }
494
495                                 if (id == -1)
496                                         throw Exception("DNS: All ids are in use");
497
498                                 break;
499                         }
500                 }
501                 while (this->requests[id]);
502
503                 req->id = id;
504                 this->requests[req->id] = req;
505
506                 Packet p;
507                 p.flags = QUERYFLAGS_RD;
508                 p.id = req->id;
509                 p.questions.push_back(*req);
510
511                 unsigned char buffer[524];
512                 unsigned short len = p.Pack(buffer, sizeof(buffer));
513
514                 /* Note that calling Pack() above can actually change the contents of p.questions[0].name, if the query is a PTR,
515                  * to contain the value that would be in the DNS cache, which is why this is here.
516                  */
517                 if (req->use_cache && this->CheckCache(req, p.questions[0]))
518                 {
519                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
520                         delete req;
521                         return;
522                 }
523
524                 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
525                         throw Exception("DNS: Unable to send query");
526         }
527
528         void RemoveRequest(DNS::Request* req)
529         {
530                 this->requests[req->id] = NULL;
531         }
532
533         std::string GetErrorStr(Error e)
534         {
535                 switch (e)
536                 {
537                         case ERROR_UNLOADED:
538                                 return "Module is unloading";
539                         case ERROR_TIMEDOUT:
540                                 return "Request timed out";
541                         case ERROR_NOT_AN_ANSWER:
542                         case ERROR_NONSTANDARD_QUERY:
543                         case ERROR_FORMAT_ERROR:
544                                 return "Malformed answer";
545                         case ERROR_SERVER_FAILURE:
546                         case ERROR_NOT_IMPLEMENTED:
547                         case ERROR_REFUSED:
548                         case ERROR_INVALIDTYPE:
549                                 return "Nameserver failure";
550                         case ERROR_DOMAIN_NOT_FOUND:
551                         case ERROR_NO_RECORDS:
552                                 return "Domain not found";
553                         case ERROR_NONE:
554                         case ERROR_UNKNOWN:
555                         default:
556                                 return "Unknown error";
557                 }
558         }
559
560         void OnEventHandlerError(int errcode) CXX11_OVERRIDE
561         {
562                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
563         }
564
565         void OnEventHandlerRead() CXX11_OVERRIDE
566         {
567                 unsigned char buffer[524];
568                 irc::sockets::sockaddrs from;
569                 socklen_t x = sizeof(from);
570
571                 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
572
573                 if (length < Packet::HEADER_LENGTH)
574                         return;
575
576                 if (myserver != from)
577                 {
578                         std::string server1 = from.str();
579                         std::string server2 = myserver.str();
580                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
581                                 server1.c_str(), server2.c_str());
582                         return;
583                 }
584
585                 Packet recv_packet;
586
587                 try
588                 {
589                         recv_packet.Fill(buffer, length);
590                 }
591                 catch (Exception& ex)
592                 {
593                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
594                         return;
595                 }
596
597                 DNS::Request* request = this->requests[recv_packet.id];
598                 if (request == NULL)
599                 {
600                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
601                         return;
602                 }
603
604                 if (recv_packet.flags & QUERYFLAGS_OPCODE)
605                 {
606                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
607                         ServerInstance->stats.DnsBad++;
608                         recv_packet.error = ERROR_NONSTANDARD_QUERY;
609                         request->OnError(&recv_packet);
610                 }
611                 else if (recv_packet.flags & QUERYFLAGS_RCODE)
612                 {
613                         Error error = ERROR_UNKNOWN;
614
615                         switch (recv_packet.flags & QUERYFLAGS_RCODE)
616                         {
617                                 case 1:
618                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
619                                         error = ERROR_FORMAT_ERROR;
620                                         break;
621                                 case 2:
622                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
623                                         error = ERROR_SERVER_FAILURE;
624                                         break;
625                                 case 3:
626                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
627                                         error = ERROR_DOMAIN_NOT_FOUND;
628                                         break;
629                                 case 4:
630                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
631                                         error = ERROR_NOT_IMPLEMENTED;
632                                         break;
633                                 case 5:
634                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
635                                         error = ERROR_REFUSED;
636                                         break;
637                                 default:
638                                         break;
639                         }
640
641                         ServerInstance->stats.DnsBad++;
642                         recv_packet.error = error;
643                         request->OnError(&recv_packet);
644                 }
645                 else if (recv_packet.questions.empty() || recv_packet.answers.empty())
646                 {
647                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
648                         ServerInstance->stats.DnsBad++;
649                         recv_packet.error = ERROR_NO_RECORDS;
650                         request->OnError(&recv_packet);
651                 }
652                 else
653                 {
654                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
655                         ServerInstance->stats.DnsGood++;
656                         request->OnLookupComplete(&recv_packet);
657                         this->AddCache(recv_packet);
658                 }
659
660                 ServerInstance->stats.Dns++;
661
662                 /* Request's destructor removes it from the request map */
663                 delete request;
664         }
665
666         bool Tick(time_t now)
667         {
668                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
669
670                 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
671                 {
672                         const Query& query = it->second;
673                         if (IsExpired(query, now))
674                                 this->cache.erase(it++);
675                         else
676                                 ++it;
677                 }
678                 return true;
679         }
680
681         void Rehash(const std::string& dnsserver)
682         {
683                 if (this->GetFd() > -1)
684                 {
685                         SocketEngine::Shutdown(this, 2);
686                         SocketEngine::Close(this);
687
688                         /* Remove expired entries from the cache */
689                         this->Tick(ServerInstance->Time());
690                 }
691
692                 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
693
694                 /* Initialize mastersocket */
695                 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
696                 this->SetFd(s);
697
698                 /* Have we got a socket? */
699                 if (this->GetFd() != -1)
700                 {
701                         SocketEngine::SetReuse(s);
702                         SocketEngine::NonBlocking(s);
703
704                         irc::sockets::sockaddrs bindto;
705                         memset(&bindto, 0, sizeof(bindto));
706                         bindto.sa.sa_family = myserver.sa.sa_family;
707
708                         if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
709                         {
710                                 /* Failed to bind */
711                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
712                                 SocketEngine::Close(this->GetFd());
713                                 this->SetFd(-1);
714                         }
715                         else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
716                         {
717                                 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
718                                 SocketEngine::Close(this->GetFd());
719                                 this->SetFd(-1);
720                         }
721                 }
722                 else
723                 {
724                         ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
725                 }
726         }
727 };
728
729 class ModuleDNS : public Module
730 {
731         MyManager manager;
732         std::string DNSServer;
733
734         void FindDNSServer()
735         {
736 #ifdef _WIN32
737                 // attempt to look up their nameserver from the system
738                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
739
740                 PFIXED_INFO pFixedInfo;
741                 DWORD dwBufferSize = sizeof(FIXED_INFO);
742                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
743
744                 if (pFixedInfo)
745                 {
746                         if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
747                         {
748                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
749                                 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
750                         }
751
752                         if (pFixedInfo)
753                         {
754                                 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
755                                         DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
756
757                                 HeapFree(GetProcessHeap(), 0, pFixedInfo);
758                         }
759
760                         if (!DNSServer.empty())
761                         {
762                                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
763                                 return;
764                         }
765                 }
766
767                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
768 #else
769                 // attempt to look up their nameserver from /etc/resolv.conf
770                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
771
772                 std::ifstream resolv("/etc/resolv.conf");
773
774                 while (resolv >> DNSServer)
775                 {
776                         if (DNSServer == "nameserver")
777                         {
778                                 resolv >> DNSServer;
779                                 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
780                                 {
781                                         ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
782                                         return;
783                                 }
784                         }
785                 }
786
787                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
788 #endif
789                 DNSServer = "127.0.0.1";
790         }
791
792  public:
793         ModuleDNS() : manager(this)
794         {
795         }
796
797         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
798         {
799                 std::string oldserver = DNSServer;
800                 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
801                 if (DNSServer.empty())
802                         FindDNSServer();
803
804                 if (oldserver != DNSServer)
805                         this->manager.Rehash(DNSServer);
806         }
807
808         void OnUnloadModule(Module* mod)
809         {
810                 for (int i = 0; i < MAX_REQUEST_ID; ++i)
811                 {
812                         DNS::Request* req = this->manager.requests[i];
813                         if (!req)
814                                 continue;
815
816                         if (req->creator == mod)
817                         {
818                                 Query rr(*req);
819                                 rr.error = ERROR_UNLOADED;
820                                 req->OnError(&rr);
821
822                                 delete req;
823                         }
824                 }
825         }
826
827         Version GetVersion()
828         {
829                 return Version("DNS support", VF_CORE|VF_VENDOR);
830         }
831 };
832
833 MODULE_INIT(ModuleDNS)
834