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 question.name = this->UnpackName(input, input_size, pos);
128 if (pos + 4 > input_size)
129 throw Exception("Unable to unpack question");
131 question.type = static_cast<QueryType>(input[pos] << 8 | input[pos + 1]);
134 question.qclass = input[pos] << 8 | input[pos + 1];
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 if (this->id >= MAX_REQUEST_ID)
231 throw Exception("Query ID too large?");
233 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
236 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
239 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
242 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
245 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
248 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
250 for (unsigned i = 0; i < qdcount; ++i)
251 this->questions.push_back(this->UnpackQuestion(input, len, packet_pos));
253 for (unsigned i = 0; i < ancount; ++i)
254 this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
257 unsigned short Pack(unsigned char* output, unsigned short output_size)
259 if (output_size < HEADER_LENGTH)
260 throw Exception("Unable to pack packet");
262 unsigned short pos = 0;
264 output[pos++] = this->id >> 8;
265 output[pos++] = this->id & 0xFF;
266 output[pos++] = this->flags >> 8;
267 output[pos++] = this->flags & 0xFF;
268 output[pos++] = this->questions.size() >> 8;
269 output[pos++] = this->questions.size() & 0xFF;
270 output[pos++] = this->answers.size() >> 8;
271 output[pos++] = this->answers.size() & 0xFF;
277 for (unsigned i = 0; i < this->questions.size(); ++i)
279 Question& q = this->questions[i];
281 if (q.type == QUERY_PTR)
283 irc::sockets::sockaddrs ip;
284 irc::sockets::aptosa(q.name, 0, ip);
286 if (q.name.find(':') != std::string::npos)
288 static const char* const hex = "0123456789abcdef";
289 char reverse_ip[128];
290 unsigned reverse_ip_count = 0;
291 for (int j = 15; j >= 0; --j)
293 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
294 reverse_ip[reverse_ip_count++] = '.';
295 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
296 reverse_ip[reverse_ip_count++] = '.';
298 reverse_ip[reverse_ip_count++] = 0;
301 q.name += "ip6.arpa";
305 unsigned long forward = ip.in4.sin_addr.s_addr;
306 ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
308 q.name = ip.addr() + ".in-addr.arpa";
312 this->PackName(output, output_size, pos, q.name);
314 if (pos + 4 >= output_size)
315 throw Exception("Unable to pack packet");
317 short s = htons(q.type);
318 memcpy(&output[pos], &s, 2);
322 memcpy(&output[pos], &s, 2);
326 for (unsigned int i = 0; i < answers.size(); i++)
328 ResourceRecord& rr = answers[i];
330 this->PackName(output, output_size, pos, rr.name);
332 if (pos + 8 >= output_size)
333 throw Exception("Unable to pack packet");
335 short s = htons(rr.type);
336 memcpy(&output[pos], &s, 2);
339 s = htons(rr.qclass);
340 memcpy(&output[pos], &s, 2);
343 long l = htonl(rr.ttl);
344 memcpy(&output[pos], &l, 4);
351 if (pos + 6 > output_size)
352 throw Exception("Unable to pack packet");
354 irc::sockets::sockaddrs a;
355 irc::sockets::aptosa(rr.rdata, 0, a);
358 memcpy(&output[pos], &s, 2);
361 memcpy(&output[pos], &a.in4.sin_addr, 4);
367 if (pos + 18 > output_size)
368 throw Exception("Unable to pack packet");
370 irc::sockets::sockaddrs a;
371 irc::sockets::aptosa(rr.rdata, 0, a);
374 memcpy(&output[pos], &s, 2);
377 memcpy(&output[pos], &a.in6.sin6_addr, 16);
384 if (pos + 2 >= output_size)
385 throw Exception("Unable to pack packet");
387 unsigned short packet_pos_save = pos;
390 this->PackName(output, output_size, pos, rr.rdata);
392 s = htons(pos - packet_pos_save - 2);
393 memcpy(&output[packet_pos_save], &s, 2);
405 class MyManager : public Manager, public Timer, public EventHandler
407 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
410 irc::sockets::sockaddrs myserver;
412 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
414 const ResourceRecord& req = record.answers[0];
415 return (req.created + static_cast<time_t>(req.ttl) < now);
418 /** Check the DNS cache to see if request can be handled by a cached result
419 * @return true if a cached result was found.
421 bool CheckCache(DNS::Request* req, const DNS::Question& question)
423 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
425 cache_map::iterator it = this->cache.find(question);
426 if (it == this->cache.end())
429 Query& record = it->second;
430 if (IsExpired(record))
432 this->cache.erase(it);
436 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
437 record.cached = true;
438 req->OnLookupComplete(&record);
442 /** Add a record to the dns cache
443 * @param r The record
445 void AddCache(Query& r)
447 const ResourceRecord& rr = r.answers[0];
448 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
449 this->cache[r.questions[0]] = r;
453 DNS::Request* requests[MAX_REQUEST_ID];
455 MyManager(Module* c) : Manager(c), Timer(3600, true)
457 for (int i = 0; i < MAX_REQUEST_ID; ++i)
459 ServerInstance->Timers.AddTimer(this);
464 for (int i = 0; i < MAX_REQUEST_ID; ++i)
466 DNS::Request* request = requests[i];
471 rr.error = ERROR_UNKNOWN;
472 request->OnError(&rr);
478 void Process(DNS::Request* req)
480 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->name + " of type " + ConvToStr(req->type) + " to " + this->myserver.addr());
483 unsigned int tries = 0;
486 req->id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID);
488 if (++tries == DNS::MAX_REQUEST_ID*5)
490 // If we couldn't find an empty slot this many times, do a sequential scan as a last
491 // resort. If an empty slot is found that way, go on, otherwise throw an exception
493 for (int i = 1; i < DNS::MAX_REQUEST_ID; i++)
495 if (!this->requests[i])
503 throw Exception("DNS: All ids are in use");
508 while (!req->id || this->requests[req->id]);
510 this->requests[req->id] = req;
513 p.flags = QUERYFLAGS_RD;
515 p.questions.push_back(*req);
517 unsigned char buffer[524];
518 unsigned short len = p.Pack(buffer, sizeof(buffer));
520 /* Note that calling Pack() above can actually change the contents of p.questions[0].name, if the query is a PTR,
521 * to contain the value that would be in the DNS cache, which is why this is here.
523 if (req->use_cache && this->CheckCache(req, p.questions[0]))
525 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
530 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
531 throw Exception("DNS: Unable to send query");
534 void RemoveRequest(DNS::Request* req)
536 this->requests[req->id] = NULL;
539 std::string GetErrorStr(Error e)
544 return "Module is unloading";
546 return "Request timed out";
547 case ERROR_NOT_AN_ANSWER:
548 case ERROR_NONSTANDARD_QUERY:
549 case ERROR_FORMAT_ERROR:
550 return "Malformed answer";
551 case ERROR_SERVER_FAILURE:
552 case ERROR_NOT_IMPLEMENTED:
554 case ERROR_INVALIDTYPE:
555 return "Nameserver failure";
556 case ERROR_DOMAIN_NOT_FOUND:
557 case ERROR_NO_RECORDS:
558 return "Domain not found";
562 return "Unknown error";
566 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
568 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
571 void OnEventHandlerRead() CXX11_OVERRIDE
573 unsigned char buffer[524];
574 irc::sockets::sockaddrs from;
575 socklen_t x = sizeof(from);
577 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
579 if (length < Packet::HEADER_LENGTH)
586 recv_packet.Fill(buffer, length);
588 catch (Exception& ex)
590 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
594 if (myserver != from)
596 std::string server1 = from.str();
597 std::string server2 = myserver.str();
598 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
599 server1.c_str(), server2.c_str());
603 DNS::Request* request = this->requests[recv_packet.id];
606 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
610 if (recv_packet.flags & QUERYFLAGS_OPCODE)
612 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
613 ServerInstance->stats.DnsBad++;
614 recv_packet.error = ERROR_NONSTANDARD_QUERY;
615 request->OnError(&recv_packet);
617 else if (recv_packet.flags & QUERYFLAGS_RCODE)
619 Error error = ERROR_UNKNOWN;
621 switch (recv_packet.flags & QUERYFLAGS_RCODE)
624 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
625 error = ERROR_FORMAT_ERROR;
628 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
629 error = ERROR_SERVER_FAILURE;
632 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
633 error = ERROR_DOMAIN_NOT_FOUND;
636 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
637 error = ERROR_NOT_IMPLEMENTED;
640 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
641 error = ERROR_REFUSED;
647 ServerInstance->stats.DnsBad++;
648 recv_packet.error = error;
649 request->OnError(&recv_packet);
651 else if (recv_packet.questions.empty() || recv_packet.answers.empty())
653 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
654 ServerInstance->stats.DnsBad++;
655 recv_packet.error = ERROR_NO_RECORDS;
656 request->OnError(&recv_packet);
660 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
661 ServerInstance->stats.DnsGood++;
662 request->OnLookupComplete(&recv_packet);
663 this->AddCache(recv_packet);
666 ServerInstance->stats.Dns++;
668 /* Request's destructor removes it from the request map */
672 bool Tick(time_t now)
674 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
676 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
678 const Query& query = it->second;
679 if (IsExpired(query, now))
680 this->cache.erase(it++);
687 void Rehash(const std::string& dnsserver)
689 if (this->GetFd() > -1)
691 SocketEngine::Shutdown(this, 2);
692 SocketEngine::Close(this);
694 /* Remove expired entries from the cache */
695 this->Tick(ServerInstance->Time());
698 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
700 /* Initialize mastersocket */
701 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
704 /* Have we got a socket? */
705 if (this->GetFd() != -1)
707 SocketEngine::SetReuse(s);
708 SocketEngine::NonBlocking(s);
710 irc::sockets::sockaddrs bindto;
711 memset(&bindto, 0, sizeof(bindto));
712 bindto.sa.sa_family = myserver.sa.sa_family;
714 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
717 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
718 SocketEngine::Close(this->GetFd());
721 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
723 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
724 SocketEngine::Close(this->GetFd());
730 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
735 class ModuleDNS : public Module
738 std::string DNSServer;
743 // attempt to look up their nameserver from the system
744 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
746 PFIXED_INFO pFixedInfo;
747 DWORD dwBufferSize = sizeof(FIXED_INFO);
748 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
752 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
754 HeapFree(GetProcessHeap(), 0, pFixedInfo);
755 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
760 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
761 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
763 HeapFree(GetProcessHeap(), 0, pFixedInfo);
766 if (!DNSServer.empty())
768 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
773 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
775 // attempt to look up their nameserver from /etc/resolv.conf
776 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
778 std::ifstream resolv("/etc/resolv.conf");
780 while (resolv >> DNSServer)
782 if (DNSServer == "nameserver")
785 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
787 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
793 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
795 DNSServer = "127.0.0.1";
799 ModuleDNS() : manager(this)
803 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
805 std::string oldserver = DNSServer;
806 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
807 if (DNSServer.empty())
810 if (oldserver != DNSServer)
811 this->manager.Rehash(DNSServer);
814 void OnUnloadModule(Module* mod)
816 for (int i = 0; i < MAX_REQUEST_ID; ++i)
818 DNS::Request* req = this->manager.requests[i];
822 if (req->creator == mod)
825 rr.error = ERROR_UNLOADED;
835 return Version("DNS support", VF_CORE|VF_VENDOR);
839 MODULE_INIT(ModuleDNS)