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