diff --git a/src/DnsConfig.php b/src/DnsConfig.php index 3493f9d..fb8f718 100644 --- a/src/DnsConfig.php +++ b/src/DnsConfig.php @@ -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 @@ -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"); @@ -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; @@ -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"; } } diff --git a/test/DnsConfigTest.php b/test/DnsConfigTest.php index 20d5519..940af0c 100644 --- a/test/DnsConfigTest.php +++ b/test/DnsConfigTest.php @@ -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"]], @@ -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()); + } }