2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2013 Adam <Adam@anope.org>
5 * Copyright (C) 2003-2013 Anope Team <team@anope.org>
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.
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
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/>.
21 #include "modules/dns.h"
27 #pragma comment(lib, "Iphlpapi.lib")
32 /** A full packet sent or recieved to/from the nameserver
34 class Packet : public Query
36 static bool IsValidName(const std::string& name)
38 return (name.find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-") == std::string::npos);
41 void PackName(unsigned char* output, unsigned short output_size, unsigned short& pos, const std::string& name)
43 if (pos + name.length() + 2 > output_size)
44 throw Exception("Unable to pack name");
46 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Packing name " + name);
48 irc::sepstream sep(name, '.');
51 while (sep.GetToken(token))
53 output[pos++] = token.length();
54 memcpy(&output[pos], token.data(), token.length());
55 pos += token.length();
61 std::string UnpackName(const unsigned char* input, unsigned short input_size, unsigned short& pos)
64 unsigned short pos_ptr = pos, lowest_ptr = input_size;
65 bool compressed = false;
67 if (pos_ptr >= input_size)
68 throw Exception("Unable to unpack name - no input");
70 while (input[pos_ptr] > 0)
72 unsigned short offset = input[pos_ptr];
76 if ((offset & POINTER) != POINTER)
77 throw Exception("Unable to unpack name - bogus compression header");
78 if (pos_ptr + 1 >= input_size)
79 throw Exception("Unable to unpack name - bogus compression header");
81 /* Place pos at the second byte of the first (farthest) compression pointer */
82 if (compressed == false)
88 pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1];
90 /* Pointers can only go back */
91 if (pos_ptr >= lowest_ptr)
92 throw Exception("Unable to unpack name - bogus compression pointer");
97 if (pos_ptr + offset + 1 >= input_size)
98 throw Exception("Unable to unpack name - offset too large");
101 for (unsigned i = 1; i <= offset; ++i)
102 name += input[pos_ptr + i];
104 pos_ptr += offset + 1;
105 if (compressed == false)
111 /* +1 pos either to one byte after the compression pointer or one byte after the ending \0 */
115 throw Exception("Unable to unpack name - no name");
117 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unpack name " + name);
122 Question UnpackQuestion(const unsigned char* input, unsigned short input_size, unsigned short& pos)
126 q.name = this->UnpackName(input, input_size, pos);
128 if (pos + 4 > input_size)
129 throw Exception("Unable to unpack question");
131 q.type = static_cast<QueryType>(input[pos] << 8 | input[pos + 1]);
134 // Skip over query class code
140 ResourceRecord UnpackResourceRecord(const unsigned char* input, unsigned short input_size, unsigned short& pos)
142 ResourceRecord record = static_cast<ResourceRecord>(this->UnpackQuestion(input, input_size, pos));
144 if (pos + 6 > input_size)
145 throw Exception("Unable to unpack resource record");
147 record.ttl = (input[pos] << 24) | (input[pos + 1] << 16) | (input[pos + 2] << 8) | input[pos + 3];
150 //record.rdlength = input[pos] << 8 | input[pos + 1];
157 if (pos + 4 > input_size)
158 throw Exception("Unable to unpack resource record");
160 irc::sockets::sockaddrs addrs;
161 memset(&addrs, 0, sizeof(addrs));
163 addrs.in4.sin_family = AF_INET;
164 addrs.in4.sin_addr.s_addr = input[pos] | (input[pos + 1] << 8) | (input[pos + 2] << 16) | (input[pos + 3] << 24);
167 record.rdata = addrs.addr();
172 if (pos + 16 > input_size)
173 throw Exception("Unable to unpack resource record");
175 irc::sockets::sockaddrs addrs;
176 memset(&addrs, 0, sizeof(addrs));
178 addrs.in6.sin6_family = AF_INET6;
179 for (int j = 0; j < 16; ++j)
180 addrs.in6.sin6_addr.s6_addr[j] = input[pos + j];
183 record.rdata = addrs.addr();
190 record.rdata = this->UnpackName(input, input_size, pos);
191 if (!IsValidName(record.rdata))
192 throw Exception("Invalid name"); // XXX: Causes the request to time out
200 if (!record.name.empty() && !record.rdata.empty())
201 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, record.name + " -> " + record.rdata);
207 static const int POINTER = 0xC0;
208 static const int LABEL = 0x3F;
209 static const int HEADER_LENGTH = 12;
211 /* ID for this packet */
213 /* Flags on the packet */
214 unsigned short flags;
216 Packet() : id(0), flags(0)
220 void Fill(const unsigned char* input, const unsigned short len)
222 if (len < HEADER_LENGTH)
223 throw Exception("Unable to fill packet");
225 unsigned short packet_pos = 0;
227 this->id = (input[packet_pos] << 8) | input[packet_pos + 1];
230 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
233 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
236 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
239 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
242 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
245 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
248 throw Exception("Question count != 1 in incoming packet");
250 this->question = this->UnpackQuestion(input, len, packet_pos);
252 for (unsigned i = 0; i < ancount; ++i)
253 this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
256 unsigned short Pack(unsigned char* output, unsigned short output_size)
258 if (output_size < HEADER_LENGTH)
259 throw Exception("Unable to pack packet");
261 unsigned short pos = 0;
263 output[pos++] = this->id >> 8;
264 output[pos++] = this->id & 0xFF;
265 output[pos++] = this->flags >> 8;
266 output[pos++] = this->flags & 0xFF;
267 output[pos++] = 0; // Question count, high byte
268 output[pos++] = 1; // Question count, low byte
269 output[pos++] = 0; // Answer count, high byte
270 output[pos++] = 0; // Answer count, low byte
277 Question& q = this->question;
279 if (q.type == QUERY_PTR)
281 irc::sockets::sockaddrs ip;
282 irc::sockets::aptosa(q.name, 0, ip);
284 if (q.name.find(':') != std::string::npos)
286 static const char* const hex = "0123456789abcdef";
287 char reverse_ip[128];
288 unsigned reverse_ip_count = 0;
289 for (int j = 15; j >= 0; --j)
291 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
292 reverse_ip[reverse_ip_count++] = '.';
293 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
294 reverse_ip[reverse_ip_count++] = '.';
296 reverse_ip[reverse_ip_count++] = 0;
299 q.name += "ip6.arpa";
303 unsigned long forward = ip.in4.sin_addr.s_addr;
304 ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
306 q.name = ip.addr() + ".in-addr.arpa";
310 this->PackName(output, output_size, pos, q.name);
312 if (pos + 4 >= output_size)
313 throw Exception("Unable to pack packet");
315 short s = htons(q.type);
316 memcpy(&output[pos], &s, 2);
319 // Query class, always IN
328 class MyManager : public Manager, public Timer, public EventHandler
330 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
333 irc::sockets::sockaddrs myserver;
335 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
337 const ResourceRecord& req = record.answers[0];
338 return (req.created + static_cast<time_t>(req.ttl) < now);
341 /** Check the DNS cache to see if request can be handled by a cached result
342 * @return true if a cached result was found.
344 bool CheckCache(DNS::Request* req, const DNS::Question& question)
346 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
348 cache_map::iterator it = this->cache.find(question);
349 if (it == this->cache.end())
352 Query& record = it->second;
353 if (IsExpired(record))
355 this->cache.erase(it);
359 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
360 record.cached = true;
361 req->OnLookupComplete(&record);
365 /** Add a record to the dns cache
366 * @param r The record
368 void AddCache(Query& r)
370 const ResourceRecord& rr = r.answers[0];
371 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
372 this->cache[r.question] = r;
376 DNS::Request* requests[MAX_REQUEST_ID+1];
378 MyManager(Module* c) : Manager(c), Timer(3600, true)
380 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
382 ServerInstance->Timers.AddTimer(this);
387 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
389 DNS::Request* request = requests[i];
394 rr.error = ERROR_UNKNOWN;
395 request->OnError(&rr);
401 void Process(DNS::Request* req)
403 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->name + " of type " + ConvToStr(req->type) + " to " + this->myserver.addr());
406 unsigned int tries = 0;
410 id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
412 if (++tries == DNS::MAX_REQUEST_ID*5)
414 // If we couldn't find an empty slot this many times, do a sequential scan as a last
415 // resort. If an empty slot is found that way, go on, otherwise throw an exception
417 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
419 if (!this->requests[i])
427 throw Exception("DNS: All ids are in use");
432 while (this->requests[id]);
435 this->requests[req->id] = req;
438 p.flags = QUERYFLAGS_RD;
442 unsigned char buffer[524];
443 unsigned short len = p.Pack(buffer, sizeof(buffer));
445 /* Note that calling Pack() above can actually change the contents of p.question.name, if the query is a PTR,
446 * to contain the value that would be in the DNS cache, which is why this is here.
448 if (req->use_cache && this->CheckCache(req, p.question))
450 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
455 // Update name in the original request so question checking works for PTR queries
456 req->name = p.question.name;
458 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
459 throw Exception("DNS: Unable to send query");
462 void RemoveRequest(DNS::Request* req)
464 this->requests[req->id] = NULL;
467 std::string GetErrorStr(Error e)
472 return "Module is unloading";
474 return "Request timed out";
475 case ERROR_NOT_AN_ANSWER:
476 case ERROR_NONSTANDARD_QUERY:
477 case ERROR_FORMAT_ERROR:
478 return "Malformed answer";
479 case ERROR_SERVER_FAILURE:
480 case ERROR_NOT_IMPLEMENTED:
482 case ERROR_INVALIDTYPE:
483 return "Nameserver failure";
484 case ERROR_DOMAIN_NOT_FOUND:
485 case ERROR_NO_RECORDS:
486 return "Domain not found";
490 return "Unknown error";
494 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
496 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
499 void OnEventHandlerRead() CXX11_OVERRIDE
501 unsigned char buffer[524];
502 irc::sockets::sockaddrs from;
503 socklen_t x = sizeof(from);
505 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
507 if (length < Packet::HEADER_LENGTH)
510 if (myserver != from)
512 std::string server1 = from.str();
513 std::string server2 = myserver.str();
514 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
515 server1.c_str(), server2.c_str());
523 recv_packet.Fill(buffer, length);
525 catch (Exception& ex)
527 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
531 DNS::Request* request = this->requests[recv_packet.id];
534 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
538 if (static_cast<Question&>(*request) != recv_packet.question)
540 // This can happen under high latency, drop it silently, do not fail the request
541 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer that isn't for a question we asked");
545 if (recv_packet.flags & QUERYFLAGS_OPCODE)
547 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
548 ServerInstance->stats.DnsBad++;
549 recv_packet.error = ERROR_NONSTANDARD_QUERY;
550 request->OnError(&recv_packet);
552 else if (recv_packet.flags & QUERYFLAGS_RCODE)
554 Error error = ERROR_UNKNOWN;
556 switch (recv_packet.flags & QUERYFLAGS_RCODE)
559 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
560 error = ERROR_FORMAT_ERROR;
563 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
564 error = ERROR_SERVER_FAILURE;
567 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
568 error = ERROR_DOMAIN_NOT_FOUND;
571 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
572 error = ERROR_NOT_IMPLEMENTED;
575 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
576 error = ERROR_REFUSED;
582 ServerInstance->stats.DnsBad++;
583 recv_packet.error = error;
584 request->OnError(&recv_packet);
586 else if (recv_packet.answers.empty())
588 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
589 ServerInstance->stats.DnsBad++;
590 recv_packet.error = ERROR_NO_RECORDS;
591 request->OnError(&recv_packet);
595 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
596 ServerInstance->stats.DnsGood++;
597 request->OnLookupComplete(&recv_packet);
598 this->AddCache(recv_packet);
601 ServerInstance->stats.Dns++;
603 /* Request's destructor removes it from the request map */
607 bool Tick(time_t now)
609 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
611 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
613 const Query& query = it->second;
614 if (IsExpired(query, now))
615 this->cache.erase(it++);
622 void Rehash(const std::string& dnsserver)
624 if (this->GetFd() > -1)
626 SocketEngine::Shutdown(this, 2);
627 SocketEngine::Close(this);
629 /* Remove expired entries from the cache */
630 this->Tick(ServerInstance->Time());
633 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
635 /* Initialize mastersocket */
636 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
639 /* Have we got a socket? */
640 if (this->GetFd() != -1)
642 SocketEngine::SetReuse(s);
643 SocketEngine::NonBlocking(s);
645 irc::sockets::sockaddrs bindto;
646 memset(&bindto, 0, sizeof(bindto));
647 bindto.sa.sa_family = myserver.sa.sa_family;
649 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
652 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
653 SocketEngine::Close(this->GetFd());
656 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
658 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
659 SocketEngine::Close(this->GetFd());
665 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
670 class ModuleDNS : public Module
673 std::string DNSServer;
678 // attempt to look up their nameserver from the system
679 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
681 PFIXED_INFO pFixedInfo;
682 DWORD dwBufferSize = sizeof(FIXED_INFO);
683 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
687 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
689 HeapFree(GetProcessHeap(), 0, pFixedInfo);
690 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
695 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
696 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
698 HeapFree(GetProcessHeap(), 0, pFixedInfo);
701 if (!DNSServer.empty())
703 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
708 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
710 // attempt to look up their nameserver from /etc/resolv.conf
711 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
713 std::ifstream resolv("/etc/resolv.conf");
715 while (resolv >> DNSServer)
717 if (DNSServer == "nameserver")
720 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
722 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
728 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
730 DNSServer = "127.0.0.1";
734 ModuleDNS() : manager(this)
738 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
740 std::string oldserver = DNSServer;
741 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
742 if (DNSServer.empty())
745 if (oldserver != DNSServer)
746 this->manager.Rehash(DNSServer);
749 void OnUnloadModule(Module* mod)
751 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
753 DNS::Request* req = this->manager.requests[i];
757 if (req->creator == mod)
760 rr.error = ERROR_UNLOADED;
770 return Version("DNS support", VF_CORE|VF_VENDOR);
774 MODULE_INIT(ModuleDNS)