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