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 void PackName(unsigned char* output, unsigned short output_size, unsigned short& pos, const std::string& name)
38 if (pos + name.length() + 2 > output_size)
39 throw Exception("Unable to pack name");
41 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Packing name " + name);
43 irc::sepstream sep(name, '.');
46 while (sep.GetToken(token))
48 output[pos++] = token.length();
49 memcpy(&output[pos], token.data(), token.length());
50 pos += token.length();
56 std::string UnpackName(const unsigned char* input, unsigned short input_size, unsigned short& pos)
59 unsigned short pos_ptr = pos, lowest_ptr = input_size;
60 bool compressed = false;
62 if (pos_ptr >= input_size)
63 throw Exception("Unable to unpack name - no input");
65 while (input[pos_ptr] > 0)
67 unsigned short offset = input[pos_ptr];
71 if ((offset & POINTER) != POINTER)
72 throw Exception("Unable to unpack name - bogus compression header");
73 if (pos_ptr + 1 >= input_size)
74 throw Exception("Unable to unpack name - bogus compression header");
76 /* Place pos at the second byte of the first (farthest) compression pointer */
77 if (compressed == false)
83 pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1];
85 /* Pointers can only go back */
86 if (pos_ptr >= lowest_ptr)
87 throw Exception("Unable to unpack name - bogus compression pointer");
92 if (pos_ptr + offset + 1 >= input_size)
93 throw Exception("Unable to unpack name - offset too large");
96 for (unsigned i = 1; i <= offset; ++i)
97 name += input[pos_ptr + i];
99 pos_ptr += offset + 1;
100 if (compressed == false)
106 /* +1 pos either to one byte after the compression pointer or one byte after the ending \0 */
110 throw Exception("Unable to unpack name - no name");
112 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unpack name " + name);
117 Question UnpackQuestion(const unsigned char* input, unsigned short input_size, unsigned short& pos)
121 question.name = this->UnpackName(input, input_size, pos);
123 if (pos + 4 > input_size)
124 throw Exception("Unable to unpack question");
126 question.type = static_cast<QueryType>(input[pos] << 8 | input[pos + 1]);
129 question.qclass = input[pos] << 8 | input[pos + 1];
135 ResourceRecord UnpackResourceRecord(const unsigned char* input, unsigned short input_size, unsigned short& pos)
137 ResourceRecord record = static_cast<ResourceRecord>(this->UnpackQuestion(input, input_size, pos));
139 if (pos + 6 > input_size)
140 throw Exception("Unable to unpack resource record");
142 record.ttl = (input[pos] << 24) | (input[pos + 1] << 16) | (input[pos + 2] << 8) | input[pos + 3];
145 //record.rdlength = input[pos] << 8 | input[pos + 1];
152 if (pos + 4 > input_size)
153 throw Exception("Unable to unpack resource record");
155 irc::sockets::sockaddrs addrs;
156 memset(&addrs, 0, sizeof(addrs));
158 addrs.in4.sin_family = AF_INET;
159 addrs.in4.sin_addr.s_addr = input[pos] | (input[pos + 1] << 8) | (input[pos + 2] << 16) | (input[pos + 3] << 24);
162 record.rdata = addrs.addr();
167 if (pos + 16 > input_size)
168 throw Exception("Unable to unpack resource record");
170 irc::sockets::sockaddrs addrs;
171 memset(&addrs, 0, sizeof(addrs));
173 addrs.in6.sin6_family = AF_INET6;
174 for (int j = 0; j < 16; ++j)
175 addrs.in6.sin6_addr.s6_addr[j] = input[pos + j];
178 record.rdata = addrs.addr();
185 record.rdata = this->UnpackName(input, input_size, pos);
192 if (!record.name.empty() && !record.rdata.empty())
193 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, record.name + " -> " + record.rdata);
199 static const int POINTER = 0xC0;
200 static const int LABEL = 0x3F;
201 static const int HEADER_LENGTH = 12;
203 /* ID for this packet */
205 /* Flags on the packet */
206 unsigned short flags;
208 Packet() : id(0), flags(0)
212 void Fill(const unsigned char* input, const unsigned short len)
214 if (len < HEADER_LENGTH)
215 throw Exception("Unable to fill packet");
217 unsigned short packet_pos = 0;
219 this->id = (input[packet_pos] << 8) | input[packet_pos + 1];
222 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
225 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
228 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
231 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
234 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
237 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
239 for (unsigned i = 0; i < qdcount; ++i)
240 this->questions.push_back(this->UnpackQuestion(input, len, packet_pos));
242 for (unsigned i = 0; i < ancount; ++i)
243 this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
246 unsigned short Pack(unsigned char* output, unsigned short output_size)
248 if (output_size < HEADER_LENGTH)
249 throw Exception("Unable to pack packet");
251 unsigned short pos = 0;
253 output[pos++] = this->id >> 8;
254 output[pos++] = this->id & 0xFF;
255 output[pos++] = this->flags >> 8;
256 output[pos++] = this->flags & 0xFF;
257 output[pos++] = this->questions.size() >> 8;
258 output[pos++] = this->questions.size() & 0xFF;
259 output[pos++] = this->answers.size() >> 8;
260 output[pos++] = this->answers.size() & 0xFF;
266 for (unsigned i = 0; i < this->questions.size(); ++i)
268 Question& q = this->questions[i];
270 if (q.type == QUERY_PTR)
272 irc::sockets::sockaddrs ip;
273 irc::sockets::aptosa(q.name, 0, ip);
275 if (q.name.find(':') != std::string::npos)
277 static const char* const hex = "0123456789abcdef";
278 char reverse_ip[128];
279 unsigned reverse_ip_count = 0;
280 for (int j = 15; j >= 0; --j)
282 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
283 reverse_ip[reverse_ip_count++] = '.';
284 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
285 reverse_ip[reverse_ip_count++] = '.';
287 reverse_ip[reverse_ip_count++] = 0;
290 q.name += "ip6.arpa";
294 unsigned long forward = ip.in4.sin_addr.s_addr;
295 ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
297 q.name = ip.addr() + ".in-addr.arpa";
301 this->PackName(output, output_size, pos, q.name);
303 if (pos + 4 >= output_size)
304 throw Exception("Unable to pack packet");
306 short s = htons(q.type);
307 memcpy(&output[pos], &s, 2);
311 memcpy(&output[pos], &s, 2);
315 for (unsigned int i = 0; i < answers.size(); i++)
317 ResourceRecord& rr = answers[i];
319 this->PackName(output, output_size, pos, rr.name);
321 if (pos + 8 >= output_size)
322 throw Exception("Unable to pack packet");
324 short s = htons(rr.type);
325 memcpy(&output[pos], &s, 2);
328 s = htons(rr.qclass);
329 memcpy(&output[pos], &s, 2);
332 long l = htonl(rr.ttl);
333 memcpy(&output[pos], &l, 4);
340 if (pos + 6 > output_size)
341 throw Exception("Unable to pack packet");
343 irc::sockets::sockaddrs a;
344 irc::sockets::aptosa(rr.rdata, 0, a);
347 memcpy(&output[pos], &s, 2);
350 memcpy(&output[pos], &a.in4.sin_addr, 4);
356 if (pos + 18 > output_size)
357 throw Exception("Unable to pack packet");
359 irc::sockets::sockaddrs a;
360 irc::sockets::aptosa(rr.rdata, 0, a);
363 memcpy(&output[pos], &s, 2);
366 memcpy(&output[pos], &a.in6.sin6_addr, 16);
373 if (pos + 2 >= output_size)
374 throw Exception("Unable to pack packet");
376 unsigned short packet_pos_save = pos;
379 this->PackName(output, output_size, pos, rr.rdata);
381 s = htons(pos - packet_pos_save - 2);
382 memcpy(&output[packet_pos_save], &s, 2);
394 class MyManager : public Manager, public Timer, public EventHandler
396 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
399 irc::sockets::sockaddrs myserver;
401 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
403 const ResourceRecord& req = record.answers[0];
404 return (req.created + static_cast<time_t>(req.ttl) < now);
407 /** Check the DNS cache to see if request can be handled by a cached result
408 * @return true if a cached result was found.
410 bool CheckCache(DNS::Request* req, const DNS::Question& question)
412 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
414 cache_map::iterator it = this->cache.find(question);
415 if (it == this->cache.end())
418 Query& record = it->second;
419 if (IsExpired(record))
421 this->cache.erase(it);
425 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
426 record.cached = true;
427 req->OnLookupComplete(&record);
431 /** Add a record to the dns cache
432 * @param r The record
434 void AddCache(Query& r)
436 const ResourceRecord& rr = r.answers[0];
437 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
438 this->cache[r.questions[0]] = r;
442 DNS::Request* requests[MAX_REQUEST_ID+1];
444 MyManager(Module* c) : Manager(c), Timer(3600, true)
446 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
448 ServerInstance->Timers.AddTimer(this);
453 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
455 DNS::Request* request = requests[i];
460 rr.error = ERROR_UNKNOWN;
461 request->OnError(&rr);
467 void Process(DNS::Request* req)
469 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->name + " of type " + ConvToStr(req->type) + " to " + this->myserver.addr());
472 unsigned int tries = 0;
476 id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
478 if (++tries == DNS::MAX_REQUEST_ID*5)
480 // If we couldn't find an empty slot this many times, do a sequential scan as a last
481 // resort. If an empty slot is found that way, go on, otherwise throw an exception
483 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
485 if (!this->requests[i])
493 throw Exception("DNS: All ids are in use");
498 while (this->requests[id]);
501 this->requests[req->id] = req;
504 p.flags = QUERYFLAGS_RD;
506 p.questions.push_back(*req);
508 unsigned char buffer[524];
509 unsigned short len = p.Pack(buffer, sizeof(buffer));
511 /* Note that calling Pack() above can actually change the contents of p.questions[0].name, if the query is a PTR,
512 * to contain the value that would be in the DNS cache, which is why this is here.
514 if (req->use_cache && this->CheckCache(req, p.questions[0]))
516 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
521 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
522 throw Exception("DNS: Unable to send query");
525 void RemoveRequest(DNS::Request* req)
527 this->requests[req->id] = NULL;
530 std::string GetErrorStr(Error e)
535 return "Module is unloading";
537 return "Request timed out";
538 case ERROR_NOT_AN_ANSWER:
539 case ERROR_NONSTANDARD_QUERY:
540 case ERROR_FORMAT_ERROR:
541 return "Malformed answer";
542 case ERROR_SERVER_FAILURE:
543 case ERROR_NOT_IMPLEMENTED:
545 case ERROR_INVALIDTYPE:
546 return "Nameserver failure";
547 case ERROR_DOMAIN_NOT_FOUND:
548 case ERROR_NO_RECORDS:
549 return "Domain not found";
553 return "Unknown error";
557 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
559 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
562 void OnEventHandlerRead() CXX11_OVERRIDE
564 unsigned char buffer[524];
565 irc::sockets::sockaddrs from;
566 socklen_t x = sizeof(from);
568 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
570 if (length < Packet::HEADER_LENGTH)
573 if (myserver != from)
575 std::string server1 = from.str();
576 std::string server2 = myserver.str();
577 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
578 server1.c_str(), server2.c_str());
586 recv_packet.Fill(buffer, length);
588 catch (Exception& ex)
590 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
594 DNS::Request* request = this->requests[recv_packet.id];
597 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
601 if (recv_packet.flags & QUERYFLAGS_OPCODE)
603 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
604 ServerInstance->stats.DnsBad++;
605 recv_packet.error = ERROR_NONSTANDARD_QUERY;
606 request->OnError(&recv_packet);
608 else if (recv_packet.flags & QUERYFLAGS_RCODE)
610 Error error = ERROR_UNKNOWN;
612 switch (recv_packet.flags & QUERYFLAGS_RCODE)
615 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
616 error = ERROR_FORMAT_ERROR;
619 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
620 error = ERROR_SERVER_FAILURE;
623 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
624 error = ERROR_DOMAIN_NOT_FOUND;
627 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
628 error = ERROR_NOT_IMPLEMENTED;
631 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
632 error = ERROR_REFUSED;
638 ServerInstance->stats.DnsBad++;
639 recv_packet.error = error;
640 request->OnError(&recv_packet);
642 else if (recv_packet.questions.empty() || recv_packet.answers.empty())
644 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
645 ServerInstance->stats.DnsBad++;
646 recv_packet.error = ERROR_NO_RECORDS;
647 request->OnError(&recv_packet);
651 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
652 ServerInstance->stats.DnsGood++;
653 request->OnLookupComplete(&recv_packet);
654 this->AddCache(recv_packet);
657 ServerInstance->stats.Dns++;
659 /* Request's destructor removes it from the request map */
663 bool Tick(time_t now)
665 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
667 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
669 const Query& query = it->second;
670 if (IsExpired(query, now))
671 this->cache.erase(it++);
678 void Rehash(const std::string& dnsserver)
680 if (this->GetFd() > -1)
682 SocketEngine::Shutdown(this, 2);
683 SocketEngine::Close(this);
685 /* Remove expired entries from the cache */
686 this->Tick(ServerInstance->Time());
689 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
691 /* Initialize mastersocket */
692 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
695 /* Have we got a socket? */
696 if (this->GetFd() != -1)
698 SocketEngine::SetReuse(s);
699 SocketEngine::NonBlocking(s);
701 irc::sockets::sockaddrs bindto;
702 memset(&bindto, 0, sizeof(bindto));
703 bindto.sa.sa_family = myserver.sa.sa_family;
705 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
708 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
709 SocketEngine::Close(this->GetFd());
712 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
714 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
715 SocketEngine::Close(this->GetFd());
721 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
726 class ModuleDNS : public Module
729 std::string DNSServer;
734 // attempt to look up their nameserver from the system
735 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
737 PFIXED_INFO pFixedInfo;
738 DWORD dwBufferSize = sizeof(FIXED_INFO);
739 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
743 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
745 HeapFree(GetProcessHeap(), 0, pFixedInfo);
746 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
751 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
752 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
754 HeapFree(GetProcessHeap(), 0, pFixedInfo);
757 if (!DNSServer.empty())
759 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
764 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
766 // attempt to look up their nameserver from /etc/resolv.conf
767 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
769 std::ifstream resolv("/etc/resolv.conf");
771 while (resolv >> DNSServer)
773 if (DNSServer == "nameserver")
776 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
778 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
784 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
786 DNSServer = "127.0.0.1";
790 ModuleDNS() : manager(this)
794 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
796 std::string oldserver = DNSServer;
797 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
798 if (DNSServer.empty())
801 if (oldserver != DNSServer)
802 this->manager.Rehash(DNSServer);
805 void OnUnloadModule(Module* mod)
807 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
809 DNS::Request* req = this->manager.requests[i];
813 if (req->creator == mod)
816 rr.error = ERROR_UNLOADED;
826 return Version("DNS support", VF_CORE|VF_VENDOR);
830 MODULE_INIT(ModuleDNS)