mirror of
https://github.com/danog/dns.git
synced 2024-11-30 04:29:06 +01:00
315e03ff54
Arrays are clearly not a good API and have resulted in bugs before, even within this package.
74 lines
2.2 KiB
PHP
74 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace Amp\Dns;
|
|
|
|
use Amp\File;
|
|
use Amp\Promise;
|
|
use function Amp\call;
|
|
|
|
class HostLoader {
|
|
private $path;
|
|
|
|
public function __construct(string $path = null) {
|
|
$this->path = $path ?? $this->getDefaultPath();
|
|
}
|
|
|
|
private function getDefaultPath(): string {
|
|
return \stripos(PHP_OS, "win") === 0
|
|
? 'C:\Windows\system32\drivers\etc\hosts'
|
|
: '/etc/hosts';
|
|
}
|
|
|
|
public function loadHosts(): Promise {
|
|
return call(function () {
|
|
$data = [];
|
|
|
|
try {
|
|
$contents = yield File\get($this->path);
|
|
} catch (File\FilesystemException $e) {
|
|
return [];
|
|
}
|
|
|
|
$lines = \array_filter(\array_map("trim", \explode("\n", $contents)));
|
|
|
|
foreach ($lines as $line) {
|
|
if ($line[0] === "#") { // Skip comments
|
|
continue;
|
|
}
|
|
|
|
$parts = \preg_split('/\s+/', $line);
|
|
|
|
if (!($ip = @\inet_pton($parts[0]))) {
|
|
continue;
|
|
} elseif (isset($ip[4])) {
|
|
$key = Record::TYPE_AAAA;
|
|
} else {
|
|
$key = Record::TYPE_A;
|
|
}
|
|
|
|
for ($i = 1, $l = \count($parts); $i < $l; $i++) {
|
|
try {
|
|
$normalizedName = normalizeDnsName($parts[$i]);
|
|
$data[$key][$normalizedName] = $parts[0];
|
|
} catch (InvalidNameError $e) {
|
|
// ignore invalid entries
|
|
}
|
|
}
|
|
}
|
|
|
|
// Windows does not include localhost in its host file. Fetch it from the system instead
|
|
if (!isset($data[Record::TYPE_A]["localhost"]) && !isset($data[Record::TYPE_AAAA]["localhost"])) {
|
|
// PHP currently provides no way to **resolve** IPv6 hostnames (not even with fallback)
|
|
$local = \gethostbyname("localhost");
|
|
if ($local !== "localhost") {
|
|
$data[Record::TYPE_A]["localhost"] = $local;
|
|
} else {
|
|
$data[Record::TYPE_AAAA]["localhost"] = "::1";
|
|
}
|
|
}
|
|
|
|
return $data;
|
|
});
|
|
}
|
|
}
|