From 3a4da5aa0579c43c6126ddca11cd3f02205015a3 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Wed, 16 Oct 2019 12:10:16 +0200 Subject: [PATCH] LookupServer: Cache successful DNS lookup responses for 1 minute This reduces DNS traffic spam during web browsing. We can definitely do a lot better here, this is just a very low-hanging fruit. --- Servers/LookupServer/main.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Servers/LookupServer/main.cpp b/Servers/LookupServer/main.cpp index e636164122..c5c3821483 100644 --- a/Servers/LookupServer/main.cpp +++ b/Servers/LookupServer/main.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #define T_A 1 @@ -27,6 +28,13 @@ #define C_IN 1 +struct CachedLookup { + time_t timestamp { 0 }; + unsigned short record_type { 0 }; + Vector responses; +}; + +static HashMap lookup_cache; static HashMap dns_custom_hostnames; static Vector lookup(const String& hostname, bool& did_timeout, const String& DNS_IP, unsigned short record_type); @@ -207,6 +215,14 @@ static u16 get_next_id() Vector lookup(const String& hostname, bool& did_timeout, const String& DNS_IP, unsigned short record_type) { + if (auto it = lookup_cache.find(hostname); it != lookup_cache.end()) { + auto& cached_lookup = it->value; + if (cached_lookup.record_type == record_type && cached_lookup.timestamp < (time(nullptr) + 60)) { + return it->value.responses; + } + lookup_cache.remove(it); + } + DNSPacket request_header; request_header.set_id(get_next_id()); request_header.set_is_query(); @@ -335,6 +351,7 @@ Vector lookup(const String& hostname, bool& did_timeout, const String& D // FIXME: Parse some other record types perhaps? } + lookup_cache.set(hostname, { time(nullptr), record_type, addresses }); return addresses; }