Skip to content

Commit

Permalink
Replaced WMIC nameserver lookup with PowerShell equivalent (#116)
Browse files Browse the repository at this point in the history
  • Loading branch information
Bilge authored Jan 19, 2025
1 parent 166c437 commit 78eb3db
Showing 1 changed file with 12 additions and 30 deletions.
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);
}
}

0 comments on commit 78eb3db

Please sign in to comment.