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