1
0
mirror of https://github.com/danog/dns.git synced 2024-11-30 04:29:06 +01:00

Rename Record to DnsRecord

See #107.
This commit is contained in:
Niklas Keller 2023-01-09 23:33:46 +01:00
parent ce518ce058
commit 3dd4f4da6d
No known key found for this signature in database
GPG Key ID: AFA536ABA90C76A6
15 changed files with 81 additions and 81 deletions

View File

@ -34,15 +34,15 @@ Usually you don't have to change the resolver. If you want to use a custom confi
// Example without type restriction. Will return IPv4 and / or IPv6 addresses.
// What's returned depends on what's available for the given hostname.
/** @var Amp\Dns\Record[] $records */
/** @var Amp\Dns\DnsRecord[] $records */
$records = Amp\Dns\resolve("github.com");
```
```php
// Example with type restriction. Will throw an exception if there are no A records.
/** @var Amp\Dns\Record[] $records */
$records = Amp\Dns\resolve("github.com", Amp\Dns\Record::A);
/** @var Amp\Dns\DnsRecord[] $records */
$records = Amp\Dns\resolve("github.com", Amp\Dns\DnsRecord::A);
```
### Custom Queries
@ -50,13 +50,13 @@ $records = Amp\Dns\resolve("github.com", Amp\Dns\Record::A);
`Amp\Dns\query` supports the various other DNS record types such as `MX`, `PTR`, or `TXT`. It automatically rewrites passed IP addresses for `PTR` lookups.
```php
/** @var Amp\Dns\Record[] $records */
$records = Amp\Dns\query("google.com", Amp\Dns\Record::MX);
/** @var Amp\Dns\DnsRecord[] $records */
$records = Amp\Dns\query("google.com", Amp\Dns\DnsRecord::MX);
```
```php
/** @var Amp\Dns\Record[] $records */
$records = Amp\Dns\query("8.8.8.8", Amp\Dns\Record::PTR);
/** @var Amp\Dns\DnsRecord[] $records */
$records = Amp\Dns\query("8.8.8.8", Amp\Dns\DnsRecord::PTR);
```
### Caching
@ -96,6 +96,6 @@ pretty_print_records("google.com", $firstGoogleResult);
$combinedGoogleResult = Amp\Dns\resolve("google.com");
pretty_print_records("google.com", $combinedGoogleResult);
$googleMx = Amp\Dns\query("google.com", Amp\Dns\Record::MX);
$googleMx = Amp\Dns\query("google.com", Amp\Dns\DnsRecord::MX);
pretty_print_records("google.com", $googleMx);
```

View File

@ -1,6 +1,6 @@
<?php declare(strict_types=1);
use Amp\Dns\Record;
use Amp\Dns\DnsRecord;
require __DIR__ . "/../vendor/autoload.php";
@ -11,7 +11,7 @@ function pretty_print_records(string $queryName, array $records)
$format = "%-10s %-56s %-5d\r\n";
foreach ($records as $record) {
print sprintf($format, Record::getName($record->getType()), $record->getValue(), $record->getTtl());
print sprintf($format, DnsRecord::getName($record->getType()), $record->getValue(), $record->getTtl());
}
}

View File

@ -7,7 +7,7 @@ use Amp\Dns;
$ip = $argv[1] ?? "8.8.8.8";
try {
pretty_print_records($ip, Dns\query($ip, Dns\Record::PTR));
pretty_print_records($ip, Dns\query($ip, Dns\DnsRecord::PTR));
} catch (Dns\DnsException $e) {
pretty_print_error($ip, $e);
}

View File

@ -13,16 +13,16 @@ final class BlockingFallbackResolver implements Resolver
public function resolve(string $name, int $typeRestriction = null, ?Cancellation $cancellation = null): array
{
if (!\in_array($typeRestriction, [Record::A, null], true)) {
if (!\in_array($typeRestriction, [DnsRecord::A, null], true)) {
throw new DnsException("Query for '{$name}' failed, because loading the system's DNS configuration failed and querying records other than A records isn't supported in blocking fallback mode.");
}
return $this->query($name, Record::A);
return $this->query($name, DnsRecord::A);
}
public function query(string $name, int $type, ?Cancellation $cancellation = null): array
{
if ($type !== Record::A) {
if ($type !== DnsRecord::A) {
throw new DnsException("Query for '$name' failed, because loading the system's DNS configuration failed and querying records other than A records isn't supported in blocking fallback mode.");
}
@ -38,7 +38,7 @@ final class BlockingFallbackResolver implements Resolver
$records = [];
foreach ($result as $record) {
$records[] = new Record($record, Record::A, null);
$records[] = new DnsRecord($record, DnsRecord::A, null);
}
return $records;

View File

@ -32,13 +32,13 @@ final class DnsConfig
}
// Windows does not include localhost in its host file. Fetch it from the system instead
if (!isset($knownHosts[Record::A]["localhost"]) && !isset($knownHosts[Record::AAAA]["localhost"])) {
if (!isset($knownHosts[DnsRecord::A]["localhost"]) && !isset($knownHosts[DnsRecord::AAAA]["localhost"])) {
// PHP currently provides no way to **resolve** IPv6 hostnames (not even with fallback)
$local = \gethostbyname("localhost");
if ($local !== "localhost") {
$knownHosts[Record::A]["localhost"] = $local;
$knownHosts[DnsRecord::A]["localhost"] = $local;
} else {
$knownHosts[Record::AAAA]["localhost"] = '::1';
$knownHosts[DnsRecord::AAAA]["localhost"] = '::1';
}
}

View File

@ -5,7 +5,7 @@ namespace Amp\Dns;
use LibDNS\Records\ResourceQTypes;
use LibDNS\Records\ResourceTypes;
final class Record
final class DnsRecord
{
public const A = ResourceTypes::A;
public const AAAA = ResourceTypes::AAAA;

View File

@ -41,9 +41,9 @@ final class HostLoader
}
if (isset($ip[4])) {
$key = Record::AAAA;
$key = DnsRecord::AAAA;
} else {
$key = Record::A;
$key = DnsRecord::A;
}
for ($i = 1, $l = \count($parts); $i < $l; $i++) {

View File

@ -16,7 +16,7 @@ interface Resolver
* @param string $name The hostname to resolve.
* @param int|null $typeRestriction Optional type restriction to `Record::A` or `Record::AAAA`, otherwise `null`.
*
* @return array<Record>
* @return array<DnsRecord>
*
* @throws NoRecordException
* @throws DnsException
@ -31,7 +31,7 @@ interface Resolver
* @param string $name Record to question, A, AAAA and PTR queries are automatically normalized.
* @param int $type Use constants of Amp\Dns\Record.
*
* @return array<Record>
* @return array<DnsRecord>
*
* @throws DnsException
*/

View File

@ -93,7 +93,7 @@ final class Rfc1035StubResolver implements Resolver
/** @inheritdoc */
public function resolve(string $name, int $typeRestriction = null, ?Cancellation $cancellation = null): array
{
if ($typeRestriction !== null && $typeRestriction !== Record::A && $typeRestriction !== Record::AAAA) {
if ($typeRestriction !== null && $typeRestriction !== DnsRecord::A && $typeRestriction !== DnsRecord::AAAA) {
throw new \Error("Invalid value for parameter 2: null|Record::A|Record::AAAA expected");
}
@ -106,18 +106,18 @@ final class Rfc1035StubResolver implements Resolver
}
switch ($typeRestriction) {
case Record::A:
case DnsRecord::A:
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return [new Record($name, Record::A, null)];
return [new DnsRecord($name, DnsRecord::A, null)];
}
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
throw new DnsException("Got an IPv6 address, but type is restricted to IPv4");
}
break;
case Record::AAAA:
case DnsRecord::AAAA:
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return [new Record($name, Record::AAAA, null)];
return [new DnsRecord($name, DnsRecord::AAAA, null)];
}
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
@ -126,11 +126,11 @@ final class Rfc1035StubResolver implements Resolver
break;
default:
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return [new Record($name, Record::A, null)];
return [new DnsRecord($name, DnsRecord::A, null)];
}
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return [new Record($name, Record::AAAA, null)];
return [new DnsRecord($name, DnsRecord::AAAA, null)];
}
break;
}
@ -146,9 +146,9 @@ final class Rfc1035StubResolver implements Resolver
// Follow RFC 6761 and never send queries for localhost to the caching DNS server
// Usually, these queries are already resolved via queryHosts()
if ($name === 'localhost') {
return $typeRestriction === Record::AAAA
? [new Record('::1', Record::AAAA, null)]
: [new Record('127.0.0.1', Record::A, null)];
return $typeRestriction === DnsRecord::AAAA
? [new DnsRecord('::1', DnsRecord::AAAA, null)]
: [new DnsRecord('127.0.0.1', DnsRecord::A, null)];
}
\assert($this->config !== null);
@ -172,8 +172,8 @@ final class Rfc1035StubResolver implements Resolver
}
[$exceptions, $records] = Future\awaitAll([
async(fn () => $this->query($searchName, Record::A, $cancellation)),
async(fn () => $this->query($searchName, Record::AAAA, $cancellation)),
async(fn () => $this->query($searchName, DnsRecord::A, $cancellation)),
async(fn () => $this->query($searchName, DnsRecord::AAAA, $cancellation)),
]);
if (\count($exceptions) === 2) {
@ -201,11 +201,11 @@ final class Rfc1035StubResolver implements Resolver
return \array_merge(...$records);
} catch (NoRecordException) {
try {
$cnameRecords = $this->query($searchName, Record::CNAME, $cancellation);
$cnameRecords = $this->query($searchName, DnsRecord::CNAME, $cancellation);
$name = $cnameRecords[0]->getValue();
continue;
} catch (NoRecordException) {
$dnameRecords = $this->query($searchName, Record::DNAME, $cancellation);
$dnameRecords = $this->query($searchName, DnsRecord::DNAME, $cancellation);
$name = $dnameRecords[0]->getValue();
continue;
}
@ -302,7 +302,7 @@ final class Rfc1035StubResolver implements Resolver
$result = [];
foreach ($cachedValue as [$data, $type]) {
$result[] = new Record($data, $type);
$result[] = new DnsRecord($data, $type);
}
return $result;
@ -349,7 +349,7 @@ final class Rfc1035StubResolver implements Resolver
continue;
}
throw new DnsException("Server returned a truncated response for '{$name}' (" . Record::getName($type) . ")");
throw new DnsException("Server returned a truncated response for '{$name}' (" . DnsRecord::getName($type) . ")");
}
$answers = $response->getAnswerRecords();
@ -380,11 +380,11 @@ final class Rfc1035StubResolver implements Resolver
if (!isset($result[$type])) {
// "it MUST NOT cache it for longer than five (5) minutes" per RFC 2308 section 7.1
$this->cache->set($this->getCacheKey($name, $type), [], 300);
throw new NoRecordException("No records returned for '{$name}' (" . Record::getName($type) . ")");
throw new NoRecordException("No records returned for '{$name}' (" . DnsRecord::getName($type) . ")");
}
return \array_map(static function ($data) use ($type, $ttls) {
return new Record($data, $type, $ttls[$type]);
return new DnsRecord($data, $type, $ttls[$type]);
}, $result[$type]);
} catch (TimeoutException) {
unset($this->sockets[$uri]);
@ -400,7 +400,7 @@ final class Rfc1035StubResolver implements Resolver
throw new TimeoutException(\sprintf(
"No response for '%s' (%s) from any nameserver within %d ms after %d attempts, tried %s",
$name,
Record::getName($type),
DnsRecord::getName($type),
$this->config->getTimeout(),
$attempts,
\implode(", ", $attemptDescription)
@ -422,15 +422,15 @@ final class Rfc1035StubResolver implements Resolver
$hosts = $this->config->getKnownHosts();
$records = [];
$returnIPv4 = $typeRestriction === null || $typeRestriction === Record::A;
$returnIPv6 = $typeRestriction === null || $typeRestriction === Record::AAAA;
$returnIPv4 = $typeRestriction === null || $typeRestriction === DnsRecord::A;
$returnIPv6 = $typeRestriction === null || $typeRestriction === DnsRecord::AAAA;
if ($returnIPv4 && isset($hosts[Record::A][$name])) {
$records[] = new Record($hosts[Record::A][$name], Record::A, null);
if ($returnIPv4 && isset($hosts[DnsRecord::A][$name])) {
$records[] = new DnsRecord($hosts[DnsRecord::A][$name], DnsRecord::A, null);
}
if ($returnIPv6 && isset($hosts[Record::AAAA][$name])) {
$records[] = new Record($hosts[Record::AAAA][$name], Record::AAAA, null);
if ($returnIPv6 && isset($hosts[DnsRecord::AAAA][$name])) {
$records[] = new DnsRecord($hosts[DnsRecord::AAAA][$name], DnsRecord::AAAA, null);
}
return $records;
@ -438,7 +438,7 @@ final class Rfc1035StubResolver implements Resolver
private function normalizeName(string $name, int $type): string
{
if ($type === Record::PTR) {
if ($type === DnsRecord::PTR) {
if (($packedIp = @\inet_pton($name)) !== false) {
if (isset($packedIp[4])) { // IPv6
$name = \wordwrap(\strrev(\bin2hex($packedIp)), 1, ".", true) . ".ip6.arpa";
@ -446,7 +446,7 @@ final class Rfc1035StubResolver implements Resolver
$name = \inet_ntop(\strrev($packedIp)) . ".in-addr.arpa";
}
}
} elseif (\in_array($type, [Record::A, Record::AAAA], true)) {
} elseif (\in_array($type, [DnsRecord::A, DnsRecord::AAAA], true)) {
$name = normalizeName($name);
}

View File

@ -2,8 +2,8 @@
namespace Amp\Dns\Test;
use Amp\Dns\DnsRecord;
use Amp\Dns\HostLoader;
use Amp\Dns\Record;
use Amp\PHPUnit\AsyncTestCase;
class HostLoaderTest extends AsyncTestCase
@ -12,7 +12,7 @@ class HostLoaderTest extends AsyncTestCase
{
$loader = new HostLoader(__DIR__ . "/data/hosts");
self::assertSame([
Record::A => [
DnsRecord::A => [
"localhost" => "127.0.0.1",
],
], $loader->loadHosts());
@ -28,7 +28,7 @@ class HostLoaderTest extends AsyncTestCase
{
$loader = new HostLoader(__DIR__ . "/data/hosts.invalid.name");
self::assertSame([
Record::A => [
DnsRecord::A => [
"localhost" => "127.0.0.1",
],
], $loader->loadHosts());

View File

@ -5,7 +5,7 @@ namespace Amp\Dns\Test;
use Amp\Cache\NullCache;
use Amp\Dns;
use Amp\Dns\DnsException;
use Amp\Dns\Record;
use Amp\Dns\DnsRecord;
use Amp\Dns\UnixDnsConfigLoader;
use Amp\Dns\WindowsDnsConfigLoader;
use Amp\PHPUnit\AsyncTestCase;
@ -35,17 +35,17 @@ class IntegrationTest extends AsyncTestCase
*/
public function testWorksAfterConfigReload(): void
{
Dns\query("google.com", Record::A);
Dns\query("google.com", DnsRecord::A);
self::assertInstanceOf(Dns\DnsConfig::class, Dns\resolver()->reloadConfig());
self::assertIsArray(Dns\query("example.com", Record::A));
self::assertIsArray(Dns\query("example.com", DnsRecord::A));
}
public function testResolveIPv4only(): void
{
$records = Dns\resolve("google.com", Record::A);
$records = Dns\resolve("google.com", DnsRecord::A);
foreach ($records as $record) {
self::assertSame(Record::A, $record->getType());
self::assertSame(DnsRecord::A, $record->getType());
$inAddr = @\inet_pton($record->getValue());
self::assertNotFalse(
$inAddr,
@ -56,10 +56,10 @@ class IntegrationTest extends AsyncTestCase
public function testResolveIPv6only(): void
{
$records = Dns\resolve("google.com", Record::AAAA);
$records = Dns\resolve("google.com", DnsRecord::AAAA);
foreach ($records as $record) {
self::assertSame(Record::AAAA, $record->getType());
self::assertSame(DnsRecord::AAAA, $record->getType());
$inAddr = @\inet_pton($record->getValue());
self::assertNotFalse(
$inAddr,
@ -92,7 +92,7 @@ class IntegrationTest extends AsyncTestCase
"Server name blog.kelunik.com did not resolve to a valid IP address"
);
$result = Dns\query('blog.kelunik.com', Dns\Record::A);
$result = Dns\query('blog.kelunik.com', Dns\DnsRecord::A);
$record = $result[0];
self::assertSame($inAddr, @\inet_pton($record->getValue()));
}
@ -131,22 +131,22 @@ class IntegrationTest extends AsyncTestCase
$resolver = new Dns\Rfc1035StubResolver(new NullCache(), $configLoader);
/** @var Record $record1 */
[$record1] = $resolver->query('google.com', Dns\Record::A);
/** @var Record $record2 */
[$record2] = $resolver->query('google.com', Dns\Record::A);
/** @var DnsRecord $record1 */
[$record1] = $resolver->query('google.com', Dns\DnsRecord::A);
/** @var DnsRecord $record2 */
[$record2] = $resolver->query('google.com', Dns\DnsRecord::A);
self::assertNotSame($record1->getValue(), $record2->getValue());
}
public function testPtrLookup(): void
{
$result = Dns\query("8.8.4.4", Record::PTR);
$result = Dns\query("8.8.4.4", DnsRecord::PTR);
$record = $result[0];
self::assertSame("dns.google", $record->getValue());
self::assertNotNull($record->getTtl());
self::assertSame(Record::PTR, $record->getType());
self::assertSame(DnsRecord::PTR, $record->getType());
}
/**
@ -155,8 +155,8 @@ class IntegrationTest extends AsyncTestCase
*/
public function testRequestSharing(): void
{
$promise1 = async(fn () => Dns\query("example.com", Record::A));
$promise2 = async(fn () => Dns\query("example.com", Record::A));
$promise1 = async(fn () => Dns\query("example.com", DnsRecord::A));
$promise2 = async(fn () => Dns\query("example.com", DnsRecord::A));
self::assertSame($promise1->await(), $promise2->await());
}

View File

@ -2,14 +2,14 @@
namespace Amp\Dns\Test;
use Amp\Dns\Record;
use Amp\Dns\DnsRecord;
use Amp\PHPUnit\AsyncTestCase;
class RecordTest extends AsyncTestCase
{
public function testGetName(): void
{
self::assertSame("A", Record::getName(Record::A));
self::assertSame("A", DnsRecord::getName(DnsRecord::A));
}
public function testGetNameOnInvalidRecordType(): void
@ -17,11 +17,11 @@ class RecordTest extends AsyncTestCase
$this->expectException(\Error::class);
$this->expectExceptionMessage("65536 does not correspond to a valid record type (must be between 0 and 65535).");
Record::getName(65536);
DnsRecord::getName(65536);
}
public function testGetNameOnUnknownRecordType(): void
{
self::assertSame("unknown (1000)", Record::getName(1000));
self::assertSame("unknown (1000)", DnsRecord::getName(1000));
}
}

View File

@ -3,8 +3,8 @@
namespace Amp\Dns\Test;
use Amp\Dns\DnsException;
use Amp\Dns\DnsRecord;
use Amp\Dns\InvalidNameException;
use Amp\Dns\Record;
use Amp\Dns\Rfc1035StubResolver;
use Amp\PHPUnit\AsyncTestCase;
@ -13,24 +13,24 @@ class Rfc1035StubResolverTest extends AsyncTestCase
public function testResolveSecondParameterAcceptedValues(): void
{
$this->expectException(\Error::class);
(new Rfc1035StubResolver)->resolve("abc.de", Record::TXT);
(new Rfc1035StubResolver)->resolve("abc.de", DnsRecord::TXT);
}
public function testIpAsArgumentWithIPv4Restriction(): void
{
$this->expectException(DnsException::class);
(new Rfc1035StubResolver)->resolve("::1", Record::A);
(new Rfc1035StubResolver)->resolve("::1", DnsRecord::A);
}
public function testIpAsArgumentWithIPv6Restriction(): void
{
$this->expectException(DnsException::class);
(new Rfc1035StubResolver)->resolve("127.0.0.1", Record::AAAA);
(new Rfc1035StubResolver)->resolve("127.0.0.1", DnsRecord::AAAA);
}
public function testInvalidName(): void
{
$this->expectException(InvalidNameException::class);
(new Rfc1035StubResolver)->resolve("go@gle.com", Record::A);
(new Rfc1035StubResolver)->resolve("go@gle.com", DnsRecord::A);
}
}

View File

@ -13,7 +13,7 @@ abstract class SocketTest extends AsyncTestCase
{
public function testAsk(): void
{
$question = (new QuestionFactory)->create(Dns\Record::A);
$question = (new QuestionFactory)->create(Dns\DnsRecord::A);
$question->setName("google.com");
$socket = $this->connect();
@ -26,7 +26,7 @@ abstract class SocketTest extends AsyncTestCase
public function testGetLastActivity(): void
{
$question = (new QuestionFactory)->create(Dns\Record::A);
$question = (new QuestionFactory)->create(Dns\DnsRecord::A);
$question->setName("google.com");
$socket = $this->connect();

View File

@ -24,7 +24,7 @@ class TcpSocketTest extends SocketTest
public function testAfterConnectionTimedOut(): void
{
$question = (new QuestionFactory)->create(Dns\Record::A);
$question = (new QuestionFactory)->create(Dns\DnsRecord::A);
$question->setName("google.com");
$socket = $this->connect();