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 // Skip over query class code
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++] = 0; // Answer count, high byte
260 output[pos++] = 0; // Answer count, low byte
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);
310 // Query class, always IN
319 class MyManager : public Manager, public Timer, public EventHandler
321 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
324 irc::sockets::sockaddrs myserver;
326 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
328 const ResourceRecord& req = record.answers[0];
329 return (req.created + static_cast<time_t>(req.ttl) < now);
332 /** Check the DNS cache to see if request can be handled by a cached result
333 * @return true if a cached result was found.
335 bool CheckCache(DNS::Request* req, const DNS::Question& question)
337 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
339 cache_map::iterator it = this->cache.find(question);
340 if (it == this->cache.end())
343 Query& record = it->second;
344 if (IsExpired(record))
346 this->cache.erase(it);
350 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
351 record.cached = true;
352 req->OnLookupComplete(&record);
356 /** Add a record to the dns cache
357 * @param r The record
359 void AddCache(Query& r)
361 const ResourceRecord& rr = r.answers[0];
362 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
363 this->cache[r.questions[0]] = r;
367 DNS::Request* requests[MAX_REQUEST_ID+1];
369 MyManager(Module* c) : Manager(c), Timer(3600, true)
371 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
373 ServerInstance->Timers.AddTimer(this);
378 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
380 DNS::Request* request = requests[i];
385 rr.error = ERROR_UNKNOWN;
386 request->OnError(&rr);
392 void Process(DNS::Request* req)
394 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->name + " of type " + ConvToStr(req->type) + " to " + this->myserver.addr());
397 unsigned int tries = 0;
401 id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
403 if (++tries == DNS::MAX_REQUEST_ID*5)
405 // If we couldn't find an empty slot this many times, do a sequential scan as a last
406 // resort. If an empty slot is found that way, go on, otherwise throw an exception
408 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
410 if (!this->requests[i])
418 throw Exception("DNS: All ids are in use");
423 while (this->requests[id]);
426 this->requests[req->id] = req;
429 p.flags = QUERYFLAGS_RD;
431 p.questions.push_back(*req);
433 unsigned char buffer[524];
434 unsigned short len = p.Pack(buffer, sizeof(buffer));
436 /* Note that calling Pack() above can actually change the contents of p.questions[0].name, if the query is a PTR,
437 * to contain the value that would be in the DNS cache, which is why this is here.
439 if (req->use_cache && this->CheckCache(req, p.questions[0]))
441 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
446 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
447 throw Exception("DNS: Unable to send query");
450 void RemoveRequest(DNS::Request* req)
452 this->requests[req->id] = NULL;
455 std::string GetErrorStr(Error e)
460 return "Module is unloading";
462 return "Request timed out";
463 case ERROR_NOT_AN_ANSWER:
464 case ERROR_NONSTANDARD_QUERY:
465 case ERROR_FORMAT_ERROR:
466 return "Malformed answer";
467 case ERROR_SERVER_FAILURE:
468 case ERROR_NOT_IMPLEMENTED:
470 case ERROR_INVALIDTYPE:
471 return "Nameserver failure";
472 case ERROR_DOMAIN_NOT_FOUND:
473 case ERROR_NO_RECORDS:
474 return "Domain not found";
478 return "Unknown error";
482 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
484 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
487 void OnEventHandlerRead() CXX11_OVERRIDE
489 unsigned char buffer[524];
490 irc::sockets::sockaddrs from;
491 socklen_t x = sizeof(from);
493 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
495 if (length < Packet::HEADER_LENGTH)
498 if (myserver != from)
500 std::string server1 = from.str();
501 std::string server2 = myserver.str();
502 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
503 server1.c_str(), server2.c_str());
511 recv_packet.Fill(buffer, length);
513 catch (Exception& ex)
515 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
519 DNS::Request* request = this->requests[recv_packet.id];
522 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
526 if (recv_packet.flags & QUERYFLAGS_OPCODE)
528 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
529 ServerInstance->stats.DnsBad++;
530 recv_packet.error = ERROR_NONSTANDARD_QUERY;
531 request->OnError(&recv_packet);
533 else if (recv_packet.flags & QUERYFLAGS_RCODE)
535 Error error = ERROR_UNKNOWN;
537 switch (recv_packet.flags & QUERYFLAGS_RCODE)
540 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
541 error = ERROR_FORMAT_ERROR;
544 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
545 error = ERROR_SERVER_FAILURE;
548 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
549 error = ERROR_DOMAIN_NOT_FOUND;
552 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
553 error = ERROR_NOT_IMPLEMENTED;
556 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
557 error = ERROR_REFUSED;
563 ServerInstance->stats.DnsBad++;
564 recv_packet.error = error;
565 request->OnError(&recv_packet);
567 else if (recv_packet.questions.empty() || recv_packet.answers.empty())
569 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
570 ServerInstance->stats.DnsBad++;
571 recv_packet.error = ERROR_NO_RECORDS;
572 request->OnError(&recv_packet);
576 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
577 ServerInstance->stats.DnsGood++;
578 request->OnLookupComplete(&recv_packet);
579 this->AddCache(recv_packet);
582 ServerInstance->stats.Dns++;
584 /* Request's destructor removes it from the request map */
588 bool Tick(time_t now)
590 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
592 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
594 const Query& query = it->second;
595 if (IsExpired(query, now))
596 this->cache.erase(it++);
603 void Rehash(const std::string& dnsserver)
605 if (this->GetFd() > -1)
607 SocketEngine::Shutdown(this, 2);
608 SocketEngine::Close(this);
610 /* Remove expired entries from the cache */
611 this->Tick(ServerInstance->Time());
614 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
616 /* Initialize mastersocket */
617 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
620 /* Have we got a socket? */
621 if (this->GetFd() != -1)
623 SocketEngine::SetReuse(s);
624 SocketEngine::NonBlocking(s);
626 irc::sockets::sockaddrs bindto;
627 memset(&bindto, 0, sizeof(bindto));
628 bindto.sa.sa_family = myserver.sa.sa_family;
630 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
633 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
634 SocketEngine::Close(this->GetFd());
637 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
639 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
640 SocketEngine::Close(this->GetFd());
646 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
651 class ModuleDNS : public Module
654 std::string DNSServer;
659 // attempt to look up their nameserver from the system
660 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
662 PFIXED_INFO pFixedInfo;
663 DWORD dwBufferSize = sizeof(FIXED_INFO);
664 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
668 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
670 HeapFree(GetProcessHeap(), 0, pFixedInfo);
671 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
676 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
677 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
679 HeapFree(GetProcessHeap(), 0, pFixedInfo);
682 if (!DNSServer.empty())
684 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
689 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
691 // attempt to look up their nameserver from /etc/resolv.conf
692 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
694 std::ifstream resolv("/etc/resolv.conf");
696 while (resolv >> DNSServer)
698 if (DNSServer == "nameserver")
701 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
703 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
709 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
711 DNSServer = "127.0.0.1";
715 ModuleDNS() : manager(this)
719 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
721 std::string oldserver = DNSServer;
722 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
723 if (DNSServer.empty())
726 if (oldserver != DNSServer)
727 this->manager.Rehash(DNSServer);
730 void OnUnloadModule(Module* mod)
732 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
734 DNS::Request* req = this->manager.requests[i];
738 if (req->creator == mod)
741 rr.error = ERROR_UNLOADED;
751 return Version("DNS support", VF_CORE|VF_VENDOR);
755 MODULE_INIT(ModuleDNS)