resolveHost: Check expected address family on returned address

The code as is never checks the requested address family when doing a DNS query,
so resolving an IPv6 only host with AddressFamily.INET would still return an IPv6.
This commit is contained in:
Steven Dwy 2020-03-16 05:04:40 -07:00 committed by Mathias LANG
parent eef6be673b
commit 467c6a0996
2 changed files with 47 additions and 4 deletions

View file

@ -58,10 +58,14 @@ NetworkAddress resolveHost(string host, ushort address_family, bool use_dns = tr
cb => eventDriver.dns.lookupHost(host, cb), cb => eventDriver.dns.lookupHost(host, cb),
(cb, id) => eventDriver.dns.cancelLookup(id), (cb, id) => eventDriver.dns.cancelLookup(id),
(DNSLookupID, DNSStatus status, scope RefAddress[] addrs) { (DNSLookupID, DNSStatus status, scope RefAddress[] addrs) {
if (status == DNSStatus.ok && addrs.length > 0) { if (status == DNSStatus.ok) {
try res = NetworkAddress(addrs[0]); foreach (addr; addrs) {
if (address_family != AddressFamily.UNSPEC && addr.addressFamily != address_family) continue;
try res = NetworkAddress(addr);
catch (Exception e) { logDiagnostic("Failed to store address from DNS lookup: %s", e.msg); } catch (Exception e) { logDiagnostic("Failed to store address from DNS lookup: %s", e.msg); }
success = true; success = true;
break;
}
} }
} }
); );

View file

@ -0,0 +1,39 @@
/+ dub.sdl:
name "test"
dependency "vibe-core" path=".."
+/
module test;
import std.socket: AddressFamily;
import vibe.core.core;
import vibe.core.net;
void main()
{
runTask({
scope(exit) exitEventLoop();
auto addr = resolveHost("ip6.me", AddressFamily.INET);
assert(addr.family == AddressFamily.INET);
addr = resolveHost("ip6.me", AddressFamily.INET6);
assert(addr.family == AddressFamily.INET6);
try
{
resolveHost("ip4only.me", AddressFamily.INET6);
assert(false);
}
catch(Exception) {}
try
{
resolveHost("ip6only.me", AddressFamily.INET);
assert(false);
}
catch(Exception) {}
});
runEventLoop();
}