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("RESOLVER", LOG_DEBUG, "Resolver: 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("RESOLVER", LOG_DEBUG, "Resolver: 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("RESOLVER", LOG_DEBUG, "Resolver: " + 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 if (this->id >= MAX_REQUEST_ID)
223 throw Exception("Query ID too large?");
225 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
228 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
231 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
234 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
237 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
240 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
242 for (unsigned i = 0; i < qdcount; ++i)
243 this->questions.push_back(this->UnpackQuestion(input, len, packet_pos));
245 for (unsigned i = 0; i < ancount; ++i)
246 this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
249 unsigned short Pack(unsigned char* output, unsigned short output_size)
251 if (output_size < HEADER_LENGTH)
252 throw Exception("Unable to pack packet");
254 unsigned short pos = 0;
256 output[pos++] = this->id >> 8;
257 output[pos++] = this->id & 0xFF;
258 output[pos++] = this->flags >> 8;
259 output[pos++] = this->flags & 0xFF;
260 output[pos++] = this->questions.size() >> 8;
261 output[pos++] = this->questions.size() & 0xFF;
262 output[pos++] = this->answers.size() >> 8;
263 output[pos++] = this->answers.size() & 0xFF;
269 for (unsigned i = 0; i < this->questions.size(); ++i)
271 Question& q = this->questions[i];
273 if (q.type == QUERY_PTR)
275 irc::sockets::sockaddrs ip;
276 irc::sockets::aptosa(q.name, 0, ip);
278 if (q.name.find(':') != std::string::npos)
280 static const char* const hex = "0123456789abcdef";
281 char reverse_ip[128];
282 unsigned reverse_ip_count = 0;
283 for (int j = 15; j >= 0; --j)
285 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
286 reverse_ip[reverse_ip_count++] = '.';
287 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
288 reverse_ip[reverse_ip_count++] = '.';
290 reverse_ip[reverse_ip_count++] = 0;
293 q.name += "ip6.arpa";
297 unsigned long forward = ip.in4.sin_addr.s_addr;
298 ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
300 q.name = ip.addr() + ".in-addr.arpa";
304 this->PackName(output, output_size, pos, q.name);
306 if (pos + 4 >= output_size)
307 throw Exception("Unable to pack packet");
309 short s = htons(q.type);
310 memcpy(&output[pos], &s, 2);
314 memcpy(&output[pos], &s, 2);
318 for (unsigned int i = 0; i < answers.size(); i++)
320 ResourceRecord& rr = answers[i];
322 this->PackName(output, output_size, pos, rr.name);
324 if (pos + 8 >= output_size)
325 throw Exception("Unable to pack packet");
327 short s = htons(rr.type);
328 memcpy(&output[pos], &s, 2);
331 s = htons(rr.qclass);
332 memcpy(&output[pos], &s, 2);
335 long l = htonl(rr.ttl);
336 memcpy(&output[pos], &l, 4);
343 if (pos + 6 > output_size)
344 throw Exception("Unable to pack packet");
346 irc::sockets::sockaddrs a;
347 irc::sockets::aptosa(rr.rdata, 0, a);
350 memcpy(&output[pos], &s, 2);
353 memcpy(&output[pos], &a.in4.sin_addr, 4);
359 if (pos + 18 > output_size)
360 throw Exception("Unable to pack packet");
362 irc::sockets::sockaddrs a;
363 irc::sockets::aptosa(rr.rdata, 0, a);
366 memcpy(&output[pos], &s, 2);
369 memcpy(&output[pos], &a.in6.sin6_addr, 16);
376 if (pos + 2 >= output_size)
377 throw Exception("Unable to pack packet");
379 unsigned short packet_pos_save = pos;
382 this->PackName(output, output_size, pos, rr.rdata);
384 s = htons(pos - packet_pos_save - 2);
385 memcpy(&output[packet_pos_save], &s, 2);
397 class MyManager : public Manager, public Timer, public EventHandler
399 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
402 irc::sockets::sockaddrs myserver;
404 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
406 const ResourceRecord& req = record.answers[0];
407 return (req.created + static_cast<time_t>(req.ttl) < now);
410 /** Check the DNS cache to see if request can be handled by a cached result
411 * @return true if a cached result was found.
413 bool CheckCache(DNS::Request* req, const DNS::Question& question)
415 ServerInstance->Logs->Log("RESOLVER", LOG_SPARSE, "Resolver: cache: Checking cache for " + question.name);
417 cache_map::iterator it = this->cache.find(question);
418 if (it == this->cache.end())
421 Query& record = it->second;
422 if (IsExpired(record))
424 this->cache.erase(it);
428 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: cache: Using cached result for " + question.name);
429 record.cached = true;
430 req->OnLookupComplete(&record);
434 /** Add a record to the dns cache
435 * @param r The record
437 void AddCache(Query& r)
439 const ResourceRecord& rr = r.answers[0];
440 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
441 this->cache[r.questions[0]] = r;
445 DNS::Request* requests[MAX_REQUEST_ID];
447 MyManager(Module* c) : Manager(c), Timer(3600, ServerInstance->Time(), true)
449 for (int i = 0; i < MAX_REQUEST_ID; ++i)
451 ServerInstance->Timers->AddTimer(this);
456 for (int i = 0; i < MAX_REQUEST_ID; ++i)
458 DNS::Request* request = requests[i];
463 rr.error = ERROR_UNKNOWN;
464 request->OnError(&rr);
470 void Process(DNS::Request* req)
472 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: Processing request to lookup " + req->name + " of type " + ConvToStr(req->type) + " to " + this->myserver.addr());
475 unsigned int tries = 0;
478 req->id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID);
480 if (++tries == DNS::MAX_REQUEST_ID*5)
482 // If we couldn't find an empty slot this many times, do a sequential scan as a last
483 // resort. If an empty slot is found that way, go on, otherwise throw an exception
485 for (int i = 1; i < DNS::MAX_REQUEST_ID; i++)
487 if (!this->requests[i])
495 throw Exception("DNS: All ids are in use");
500 while (!req->id || this->requests[req->id]);
502 this->requests[req->id] = req;
505 p.flags = QUERYFLAGS_RD;
507 p.questions.push_back(*req);
509 unsigned char buffer[524];
510 unsigned short len = p.Pack(buffer, sizeof(buffer));
512 /* Note that calling Pack() above can actually change the contents of p.questions[0].name, if the query is a PTR,
513 * to contain the value that would be in the DNS cache, which is why this is here.
515 if (req->use_cache && this->CheckCache(req, p.questions[0]))
517 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: Using cached result");
522 if (ServerInstance->SE->SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
523 throw Exception("DNS: Unable to send query");
526 void RemoveRequest(DNS::Request* req)
528 this->requests[req->id] = NULL;
531 std::string GetErrorStr(Error e)
536 return "Module is unloading";
538 return "Request timed out";
539 case ERROR_NOT_AN_ANSWER:
540 case ERROR_NONSTANDARD_QUERY:
541 case ERROR_FORMAT_ERROR:
542 return "Malformed answer";
543 case ERROR_SERVER_FAILURE:
544 case ERROR_NOT_IMPLEMENTED:
546 case ERROR_INVALIDTYPE:
547 return "Nameserver failure";
548 case ERROR_DOMAIN_NOT_FOUND:
549 case ERROR_NO_RECORDS:
550 return "Domain not found";
554 return "Unknown error";
558 void HandleEvent(EventType et, int)
560 if (et == EVENT_ERROR)
562 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: UDP socket got an error event");
566 unsigned char buffer[524];
567 irc::sockets::sockaddrs from;
568 socklen_t x = sizeof(from);
570 int length = ServerInstance->SE->RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
572 if (length < Packet::HEADER_LENGTH)
579 recv_packet.Fill(buffer, length);
581 catch (Exception& ex)
583 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, std::string(ex.GetReason()));
587 if (myserver != from)
589 std::string server1 = from.str();
590 std::string server2 = myserver.str();
591 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
592 server1.c_str(), server2.c_str());
596 DNS::Request* request = this->requests[recv_packet.id];
599 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: Received an answer for something we didn't request");
603 if (recv_packet.flags & QUERYFLAGS_OPCODE)
605 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: Received a nonstandard query");
606 ServerInstance->stats->statsDnsBad++;
607 recv_packet.error = ERROR_NONSTANDARD_QUERY;
608 request->OnError(&recv_packet);
610 else if (recv_packet.flags & QUERYFLAGS_RCODE)
612 Error error = ERROR_UNKNOWN;
614 switch (recv_packet.flags & QUERYFLAGS_RCODE)
617 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: format error");
618 error = ERROR_FORMAT_ERROR;
621 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: server error");
622 error = ERROR_SERVER_FAILURE;
625 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: domain not found");
626 error = ERROR_DOMAIN_NOT_FOUND;
629 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: not implemented");
630 error = ERROR_NOT_IMPLEMENTED;
633 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: refused");
634 error = ERROR_REFUSED;
640 ServerInstance->stats->statsDnsBad++;
641 recv_packet.error = error;
642 request->OnError(&recv_packet);
644 else if (recv_packet.questions.empty() || recv_packet.answers.empty())
646 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: No resource records returned");
647 ServerInstance->stats->statsDnsBad++;
648 recv_packet.error = ERROR_NO_RECORDS;
649 request->OnError(&recv_packet);
653 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: Lookup complete for " + request->name);
654 ServerInstance->stats->statsDnsGood++;
655 request->OnLookupComplete(&recv_packet);
656 this->AddCache(recv_packet);
659 ServerInstance->stats->statsDns++;
661 /* Request's destructor removes it from the request map */
665 bool Tick(time_t now)
667 ServerInstance->Logs->Log("RESOLVER", LOG_DEBUG, "Resolver: cache: purging DNS cache");
669 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
671 const Query& query = it->second;
672 if (IsExpired(query, now))
673 this->cache.erase(it++);
680 void Rehash(const std::string& dnsserver)
682 if (this->GetFd() > -1)
684 ServerInstance->SE->DelFd(this);
685 ServerInstance->SE->Shutdown(this, 2);
686 ServerInstance->SE->Close(this);
689 /* Remove expired entries from the cache */
690 this->Tick(ServerInstance->Time());
693 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
695 /* Initialize mastersocket */
696 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
699 /* Have we got a socket? */
700 if (this->GetFd() != -1)
702 ServerInstance->SE->SetReuse(s);
703 ServerInstance->SE->NonBlocking(s);
705 irc::sockets::sockaddrs bindto;
706 memset(&bindto, 0, sizeof(bindto));
707 bindto.sa.sa_family = myserver.sa.sa_family;
709 if (ServerInstance->SE->Bind(this->GetFd(), bindto) < 0)
712 ServerInstance->Logs->Log("RESOLVER", LOG_SPARSE, "Resolver: Error binding dns socket - hostnames will NOT resolve");
713 ServerInstance->SE->Close(this);
716 else if (!ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
718 ServerInstance->Logs->Log("RESOLVER", LOG_SPARSE, "Resolver: Internal error starting DNS - hostnames will NOT resolve.");
719 ServerInstance->SE->Close(this);
725 ServerInstance->Logs->Log("RESOLVER", LOG_SPARSE, "Resolver: Error creating DNS socket - hostnames will NOT resolve");
730 class ModuleDNS : public Module
733 std::string DNSServer;
738 // attempt to look up their nameserver from the system
739 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
741 PFIXED_INFO pFixedInfo;
742 DWORD dwBufferSize = sizeof(FIXED_INFO);
743 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
747 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
749 HeapFree(GetProcessHeap(), 0, pFixedInfo);
750 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
755 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
756 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
758 HeapFree(GetProcessHeap(), 0, pFixedInfo);
761 if (!DNSServer.empty())
763 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
768 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
770 // attempt to look up their nameserver from /etc/resolv.conf
771 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
773 std::ifstream resolv("/etc/resolv.conf");
775 while (resolv >> DNSServer)
777 if (DNSServer == "nameserver")
780 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
782 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
788 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
790 DNSServer = "127.0.0.1";
794 ModuleDNS() : manager(this)
800 ServerInstance->Modules->AddService(this->manager);
802 this->OnRehash(NULL);
805 void OnRehash(User* user)
807 std::string oldserver = DNSServer;
808 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
809 if (DNSServer.empty())
812 if (oldserver != DNSServer)
813 this->manager.Rehash(DNSServer);
816 void OnUnloadModule(Module* mod)
818 for (int i = 0; i < MAX_REQUEST_ID; ++i)
820 DNS::Request* req = this->manager.requests[i];
824 if (req->creator == mod)
827 rr.error = ERROR_UNLOADED;
837 return Version("DNS support", VF_CORE|VF_VENDOR);
841 MODULE_INIT(ModuleDNS)