2017-06-17 12:30:38 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp\Dns;
|
|
|
|
|
|
|
|
use Amp\File;
|
|
|
|
use Amp\Promise;
|
2017-06-24 00:49:25 +02:00
|
|
|
use Amp\Uri\InvalidDnsNameException;
|
2017-06-17 12:30:38 +02:00
|
|
|
use function Amp\call;
|
2017-06-24 00:49:25 +02:00
|
|
|
use function Amp\Uri\normalizeDnsName;
|
2017-06-17 12:30:38 +02:00
|
|
|
|
|
|
|
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])) {
|
2017-06-22 20:08:27 +02:00
|
|
|
$key = Record::AAAA;
|
2017-06-17 12:30:38 +02:00
|
|
|
} else {
|
2017-06-22 20:08:27 +02:00
|
|
|
$key = Record::A;
|
2017-06-17 12:30:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
for ($i = 1, $l = \count($parts); $i < $l; $i++) {
|
|
|
|
try {
|
2017-06-22 19:22:45 +02:00
|
|
|
$normalizedName = normalizeDnsName($parts[$i]);
|
2017-06-17 12:30:38 +02:00
|
|
|
$data[$key][$normalizedName] = $parts[0];
|
2017-06-24 00:49:25 +02:00
|
|
|
} catch (InvalidDnsNameException $e) {
|
2017-06-17 12:30:38 +02:00
|
|
|
// ignore invalid entries
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $data;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|