Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/DnsConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ public function __construct(array $nameservers, array $knownHosts = [])
throw new DnsConfigException("At least one nameserver is required for a valid config");
}

foreach ($nameservers as $nameserver) {
$this->validateNameserver($nameserver);
foreach ($nameservers as $key => $nameserver) {
$nameservers[$key] = $this->normalizeNameserver($nameserver);
}

// Windows does not include localhost in its host file. Fetch it from the system instead
Expand Down Expand Up @@ -141,13 +141,15 @@ public function isRotationEnabled(): bool
/**
* @throws DnsConfigException
*/
private function validateNameserver(string $nameserver): void
private function normalizeNameserver(string $nameserver): string
{
if ($nameserver === "") {
throw new DnsConfigException("Invalid nameserver: empty string");
}

if ($nameserver[0] === "[") { // IPv6
$isIpv6 = $nameserver[0] === "[";

if ($isIpv6) {
$addrEnd = \strrpos($nameserver, "]");
if ($addrEnd === false) {
throw new DnsConfigException("Invalid nameserver: $nameserver");
Expand All @@ -161,11 +163,15 @@ private function validateNameserver(string $nameserver): void
}

$port = $port === "" ? 53 : \substr($port, 1);
} else { // IPv4
} else {
$arr = \explode(":", $nameserver, 2);

if (\count($arr) === 2) {
[$addr, $port] = $arr;

if (!\preg_match("(^\\d+$)", $port)) {
throw new DnsConfigException("Invalid nameserver: $nameserver");
}
} else {
$addr = $arr[0];
$port = 53;
Expand All @@ -182,5 +188,7 @@ private function validateNameserver(string $nameserver): void
if ($port < 1 || $port > 65535) {
throw new DnsConfigException("Invalid server port: $port");
}

return $isIpv6 ? "[$addr]:$port" : "$addr:$port";
}
}
18 changes: 18 additions & 0 deletions test/DnsConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public function provideInvalidServers(): array
[["foobar.com"]],
[["127.1.1"]],
[["127.1.1.1.1"]],
[["127.1.1.1:invalid"]],
[["126.0.0.5", "foobar"]],
[["42"]],
[["::1"]],
Expand Down Expand Up @@ -108,4 +109,21 @@ public function testRotationDisabled(): void
$config = new DnsConfig(["127.0.0.1"]);
self::assertFalse($config->isRotationEnabled());
}

public function testNormalizesServers(): void
{
$config = new DnsConfig([
"127.0.0.1",
"127.0.0.1:5353",
"[::1]",
"[::1]:5353",
]);

self::assertSame([
"127.0.0.1:53",
"127.0.0.1:5353",
"[::1]:53",
"[::1]:5353",
], $config->getNameservers());
}
}
Loading