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));
240 throw Exception("Question count != 1 in incoming packet");
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++] = 0; // Answer count, high byte
263 output[pos++] = 0; // Answer count, low byte
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);
313 // Query class, always IN
322 class MyManager : public Manager, public Timer, public EventHandler
324 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
327 irc::sockets::sockaddrs myserver;
329 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
331 const ResourceRecord& req = record.answers[0];
332 return (req.created + static_cast<time_t>(req.ttl) < now);
335 /** Check the DNS cache to see if request can be handled by a cached result
336 * @return true if a cached result was found.
338 bool CheckCache(DNS::Request* req, const DNS::Question& question)
340 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
342 cache_map::iterator it = this->cache.find(question);
343 if (it == this->cache.end())
346 Query& record = it->second;
347 if (IsExpired(record))
349 this->cache.erase(it);
353 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
354 record.cached = true;
355 req->OnLookupComplete(&record);
359 /** Add a record to the dns cache
360 * @param r The record
362 void AddCache(Query& r)
364 const ResourceRecord& rr = r.answers[0];
365 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
366 this->cache[r.questions[0]] = r;
370 DNS::Request* requests[MAX_REQUEST_ID+1];
372 MyManager(Module* c) : Manager(c), Timer(3600, true)
374 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
376 ServerInstance->Timers.AddTimer(this);
381 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
383 DNS::Request* request = requests[i];
388 rr.error = ERROR_UNKNOWN;
389 request->OnError(&rr);
395 void Process(DNS::Request* req)
397 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->name + " of type " + ConvToStr(req->type) + " to " + this->myserver.addr());
400 unsigned int tries = 0;
404 id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
406 if (++tries == DNS::MAX_REQUEST_ID*5)
408 // If we couldn't find an empty slot this many times, do a sequential scan as a last
409 // resort. If an empty slot is found that way, go on, otherwise throw an exception
411 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
413 if (!this->requests[i])
421 throw Exception("DNS: All ids are in use");
426 while (this->requests[id]);
429 this->requests[req->id] = req;
432 p.flags = QUERYFLAGS_RD;
434 p.questions.push_back(*req);
436 unsigned char buffer[524];
437 unsigned short len = p.Pack(buffer, sizeof(buffer));
439 /* Note that calling Pack() above can actually change the contents of p.questions[0].name, if the query is a PTR,
440 * to contain the value that would be in the DNS cache, which is why this is here.
442 if (req->use_cache && this->CheckCache(req, p.questions[0]))
444 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
449 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
450 throw Exception("DNS: Unable to send query");
453 void RemoveRequest(DNS::Request* req)
455 this->requests[req->id] = NULL;
458 std::string GetErrorStr(Error e)
463 return "Module is unloading";
465 return "Request timed out";
466 case ERROR_NOT_AN_ANSWER:
467 case ERROR_NONSTANDARD_QUERY:
468 case ERROR_FORMAT_ERROR:
469 return "Malformed answer";
470 case ERROR_SERVER_FAILURE:
471 case ERROR_NOT_IMPLEMENTED:
473 case ERROR_INVALIDTYPE:
474 return "Nameserver failure";
475 case ERROR_DOMAIN_NOT_FOUND:
476 case ERROR_NO_RECORDS:
477 return "Domain not found";
481 return "Unknown error";
485 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
487 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
490 void OnEventHandlerRead() CXX11_OVERRIDE
492 unsigned char buffer[524];
493 irc::sockets::sockaddrs from;
494 socklen_t x = sizeof(from);
496 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
498 if (length < Packet::HEADER_LENGTH)
501 if (myserver != from)
503 std::string server1 = from.str();
504 std::string server2 = myserver.str();
505 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
506 server1.c_str(), server2.c_str());
514 recv_packet.Fill(buffer, length);
516 catch (Exception& ex)
518 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
522 DNS::Request* request = this->requests[recv_packet.id];
525 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
529 if (recv_packet.flags & QUERYFLAGS_OPCODE)
531 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
532 ServerInstance->stats.DnsBad++;
533 recv_packet.error = ERROR_NONSTANDARD_QUERY;
534 request->OnError(&recv_packet);
536 else if (recv_packet.flags & QUERYFLAGS_RCODE)
538 Error error = ERROR_UNKNOWN;
540 switch (recv_packet.flags & QUERYFLAGS_RCODE)
543 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
544 error = ERROR_FORMAT_ERROR;
547 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
548 error = ERROR_SERVER_FAILURE;
551 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
552 error = ERROR_DOMAIN_NOT_FOUND;
555 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
556 error = ERROR_NOT_IMPLEMENTED;
559 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
560 error = ERROR_REFUSED;
566 ServerInstance->stats.DnsBad++;
567 recv_packet.error = error;
568 request->OnError(&recv_packet);
570 else if (recv_packet.questions.empty() || recv_packet.answers.empty())
572 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
573 ServerInstance->stats.DnsBad++;
574 recv_packet.error = ERROR_NO_RECORDS;
575 request->OnError(&recv_packet);
579 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->name);
580 ServerInstance->stats.DnsGood++;
581 request->OnLookupComplete(&recv_packet);
582 this->AddCache(recv_packet);
585 ServerInstance->stats.Dns++;
587 /* Request's destructor removes it from the request map */
591 bool Tick(time_t now)
593 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
595 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
597 const Query& query = it->second;
598 if (IsExpired(query, now))
599 this->cache.erase(it++);
606 void Rehash(const std::string& dnsserver)
608 if (this->GetFd() > -1)
610 SocketEngine::Shutdown(this, 2);
611 SocketEngine::Close(this);
613 /* Remove expired entries from the cache */
614 this->Tick(ServerInstance->Time());
617 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
619 /* Initialize mastersocket */
620 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
623 /* Have we got a socket? */
624 if (this->GetFd() != -1)
626 SocketEngine::SetReuse(s);
627 SocketEngine::NonBlocking(s);
629 irc::sockets::sockaddrs bindto;
630 memset(&bindto, 0, sizeof(bindto));
631 bindto.sa.sa_family = myserver.sa.sa_family;
633 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
636 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
637 SocketEngine::Close(this->GetFd());
640 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
642 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
643 SocketEngine::Close(this->GetFd());
649 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
654 class ModuleDNS : public Module
657 std::string DNSServer;
662 // attempt to look up their nameserver from the system
663 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
665 PFIXED_INFO pFixedInfo;
666 DWORD dwBufferSize = sizeof(FIXED_INFO);
667 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
671 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
673 HeapFree(GetProcessHeap(), 0, pFixedInfo);
674 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
679 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
680 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
682 HeapFree(GetProcessHeap(), 0, pFixedInfo);
685 if (!DNSServer.empty())
687 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
692 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
694 // attempt to look up their nameserver from /etc/resolv.conf
695 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
697 std::ifstream resolv("/etc/resolv.conf");
699 while (resolv >> DNSServer)
701 if (DNSServer == "nameserver")
704 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos)
706 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
712 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
714 DNSServer = "127.0.0.1";
718 ModuleDNS() : manager(this)
722 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
724 std::string oldserver = DNSServer;
725 DNSServer = ServerInstance->Config->ConfValue("dns")->getString("server");
726 if (DNSServer.empty())
729 if (oldserver != DNSServer)
730 this->manager.Rehash(DNSServer);
733 void OnUnloadModule(Module* mod)
735 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
737 DNS::Request* req = this->manager.requests[i];
741 if (req->creator == mod)
744 rr.error = ERROR_UNLOADED;
754 return Version("DNS support", VF_CORE|VF_VENDOR);
758 MODULE_INIT(ModuleDNS)