Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replaced WMIC nameserver lookup with PowerShell equivalent #116

Merged
merged 3 commits into from
Jan 19, 2025
Merged
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
42 changes: 12 additions & 30 deletions src/WindowsDnsConfigLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Amp\ForbidSerialization;
use Amp\Process\Process;
use function Amp\ByteStream\buffer;
use function Amp\ByteStream\splitLines;

final class WindowsDnsConfigLoader implements DnsConfigLoader
{
Expand All @@ -19,15 +20,20 @@ public function __construct(

public function loadConfig(): DnsConfig
{
$wmic = Process::start(['wmic', 'NICCONFIG', 'GET', 'DNSServerSearchOrder']);

if ($wmic->join() !== 0) {
throw new DnsConfigException("Could not fetch DNS servers from WMI: " . buffer($wmic->getStderr()));
$powershell = Process::start([
'powershell',
'-Command',
'Get-WmiObject -Class Win32_NetworkAdapterConfiguration |
Select-Object -ExpandProperty DNSServerSearchOrder',
]);

if ($powershell->join() !== 0) {
throw new DnsConfigException("Could not fetch DNS servers from WMI: " . buffer($powershell->getStderr()));
}

$ips = self::parseWmicOutput(buffer($wmic->getStdout()));
$output = \iterator_to_array(splitLines($powershell->getStdout()));

$nameservers = \array_reduce($ips, static function (array $nameservers, string $address): array {
$nameservers = \array_reduce($output, static function (array $nameservers, string $address): array {
$ip = \inet_pton($address);

if (isset($ip[15])) { // IPv6
Expand All @@ -43,28 +49,4 @@ public function loadConfig(): DnsConfig

return new DnsConfig($nameservers, $hosts);
}

private static function parseWmicOutput(string $output): array
{
// Massage WMIC output into JSON format.
$json = \preg_replace(
[
// Convert header line into opening bracket.
'[^\V*\v+]',
// Convert closing braces into commas.
'[}]',
// Remove final comma.
'[,(?=[^,]*+$)]',
// Removing opening braces.
'[{]',
],
[
'[',
',',
],
$output,
);

return \json_decode("$json]", true, flags: \JSON_THROW_ON_ERROR);
}
}
Loading