Skip to content

Commit

Permalink
refactor: remove raw pointers from dns code
Browse files Browse the repository at this point in the history
  • Loading branch information
braindigitalis committed Dec 13, 2024
1 parent 31594f1 commit adb25d1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
3 changes: 2 additions & 1 deletion include/dpp/dns.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include <string>
#include <unordered_map>
#include <cstring>
#include <memory>
#include <dpp/socket.h>

namespace dpp {
Expand Down Expand Up @@ -83,7 +84,7 @@ namespace dpp {
/**
* @brief Cache container type
*/
using dns_cache_t = std::unordered_map<std::string, dns_cache_entry*>;
using dns_cache_t = std::unordered_map<std::string, std::unique_ptr<dns_cache_entry>>;

/**
* @brief Resolve a hostname to an addrinfo
Expand Down
11 changes: 6 additions & 5 deletions src/dpp/dns.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ const dns_cache_entry *resolve_hostname(const std::string &hostname, const std::
exists = true;
if (now < iter->second->expire_timestamp) {
/* there is a cached entry that is still valid, return it */
return iter->second;
return iter->second.get();
}
}
}
Expand All @@ -82,7 +82,6 @@ const dns_cache_entry *resolve_hostname(const std::string &hostname, const std::
std::unique_lock dns_cache_lock(dns_cache_mutex);
iter = dns_cache.find(hostname);
if (iter != dns_cache.end()) { /* re-validate iter */
delete iter->second;
dns_cache.erase(iter);
}
}
Expand All @@ -108,7 +107,7 @@ const dns_cache_entry *resolve_hostname(const std::string &hostname, const std::
{
/* Update cache, requires unique lock */
std::unique_lock dns_cache_lock(dns_cache_mutex);
dns_cache_entry* cache_entry = new dns_cache_entry();
auto cache_entry = std::make_unique<dns_cache_entry>();

for (struct addrinfo* rp = addrs; rp != nullptr; rp = rp->ai_next) {
/* Discord only support ipv4, so iterate over any ipv6 results */
Expand All @@ -127,11 +126,13 @@ const dns_cache_entry *resolve_hostname(const std::string &hostname, const std::
}

cache_entry->expire_timestamp = now + one_hour;
dns_cache[hostname] = cache_entry;
auto r = dns_cache.emplace(hostname, std::move(cache_entry));

/* Now we're done with this horrible struct, free it and return */
freeaddrinfo(addrs);
return cache_entry;

/* Return either the existing entry, or the newly inserted entry */
return r.first->second.get();
}
}

Expand Down

0 comments on commit adb25d1

Please sign in to comment.