feat(dns): expose Xray fallback restriction for matched domains (#10602)

This commit is contained in:
Desaichk
2026-11-16 09:06:41 +03:00
committed by GitHub
parent f3d349b0a7
commit 917efefd5a
13 changed files with 201 additions and 1 deletions
@@ -0,0 +1,107 @@
namespace ServiceLib.Tests.CoreConfig.V2ray;
public class DnsFallbackTests
{
[Test]
[Arguments(null, false, false)]
[Arguments(false, false, false)]
[Arguments(true, false, false)]
[Arguments(null, true, false)]
[Arguments(false, true, false)]
[Arguments(true, true, false)]
[Arguments(null, false, true)]
[Arguments(false, false, true)]
[Arguments(true, false, true)]
[Arguments(null, true, true)]
[Arguments(false, true, true)]
[Arguments(true, true, true)]
public async Task SimpleDns_ShouldPersistAndApplyFallbackChoice(bool? disabled, bool parallel, bool tun)
{
var config = CoreConfigTestFactory.CreateConfig();
config.SimpleDNSItem.DisableFallbackIfMatch = disabled;
config.SimpleDNSItem.ParallelQuery = parallel;
config.SimpleDNSItem.DirectDNS = "8.8.8.8,8.8.4.4";
config.SimpleDNSItem.RemoteDNS = "1.1.1.1";
config.TunModeItem.EnableTun = tun;
config = JsonUtils.Deserialize<Config>(JsonUtils.Serialize(config))!;
await config.SimpleDNSItem.DisableFallbackIfMatch.Should().BeEqualTo(disabled);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray);
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RoutingItem = new RoutingItem
{
DomainStrategy = Global.AsIs,
RuleSet = JsonUtils.Serialize(new List<RulesItem>
{
new() { RuleType = ERuleType.DNS, Domain = ["domain:direct.example"], OutboundTag = Global.DirectTag },
}),
},
};
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
await result.Success.Should().BeTrue();
var dns = JsonNode.Parse(result.Data!.ToString()!)!["dns"]!;
await (dns["disableFallbackIfMatch"]?.GetValue<bool>()).Should().BeEqualTo(disabled == true ? true : (bool?)null);
await (dns["enableParallelQuery"]?.GetValue<bool>() == true).Should().BeEqualTo(parallel);
var servers = dns["servers"]!.AsArray();
var matched = servers.OfType<JsonObject>().Where(s => s["domains"] != null).ToList();
await matched.Count.Should().BeEqualTo(2);
await matched.All(s => s["skipFallback"]!.GetValue<bool>()).Should().BeTrue();
await servers.Last()!.GetValue<string>().Should().BeEqualTo("1.1.1.1");
}
[Test]
[Arguments(false, true, false)]
[Arguments(true, false, false)]
[Arguments(false, true, true)]
[Arguments(true, false, true)]
public async Task RawDns_ShouldUseItsOwnFallbackChoice(bool simpleChoice, bool rawChoice, bool tun)
{
var config = CoreConfigTestFactory.CreateConfig();
config.SimpleDNSItem.DisableFallbackIfMatch = simpleChoice;
config.TunModeItem.EnableTun = tun;
CoreConfigTestFactory.BindAppManagerConfig(config);
var raw = new JsonObject
{
["servers"] = new JsonArray("1.1.1.1"),
["disableFallbackIfMatch"] = rawChoice,
}.ToJsonString();
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray);
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray) with
{
RawDnsItem = new DNSItem { Enabled = true, NormalDNS = raw, TunDNS = raw },
};
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
await result.Success.Should().BeTrue();
var dns = JsonNode.Parse(result.Data!.ToString()!)!["dns"]!;
await dns["disableFallbackIfMatch"]!.GetValue<bool>().Should().BeEqualTo(rawChoice);
}
[Test]
public async Task ExistingSettings_ShouldKeepFallbackEnabledByDefault()
{
var simple = JsonUtils.Deserialize<SimpleDNSItem>("{\"DirectDNS\":\"8.8.8.8\",\"RemoteDNS\":\"1.1.1.1\"}")!;
await simple.DisableFallbackIfMatch.Should().BeNull();
}
[Test]
public async Task Singbox_ShouldGenerateTheSameDnsForBothFallbackChoices()
{
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
CoreConfigTestFactory.BindAppManagerConfig(config);
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box);
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box);
var before = new CoreConfigSingboxService(context).GenerateClientConfigContent();
config.SimpleDNSItem.DisableFallbackIfMatch = true;
var after = new CoreConfigSingboxService(context).GenerateClientConfigContent();
await before.Success.Should().BeTrue();
await after.Success.Should().BeTrue();
await JsonNode.DeepEquals(JsonNode.Parse(before.Data!.ToString()!)!["dns"],
JsonNode.Parse(after.Data!.ToString()!)!["dns"]).Should().BeTrue();
}
}
@@ -268,6 +268,7 @@ public class SimpleDNSItem
public string? Strategy4ProxyDial { get; set; } public string? Strategy4ProxyDial { get; set; }
public bool? ServeStale { get; set; } public bool? ServeStale { get; set; }
public bool? ParallelQuery { get; set; } public bool? ParallelQuery { get; set; }
public bool? DisableFallbackIfMatch { get; set; }
public string? Hosts { get; set; } public string? Hosts { get; set; }
public string? DirectExpectedIPs { get; set; } public string? DirectExpectedIPs { get; set; }
public bool? EnableHappyEyeballs { get; set; } public bool? EnableHappyEyeballs { get; set; }
@@ -203,6 +203,7 @@ public class Dns4Ray
public List<JsonNode> servers { get; set; } public List<JsonNode> servers { get; set; }
public bool? serveStale { get; set; } public bool? serveStale { get; set; }
public bool? enableParallelQuery { get; set; } public bool? enableParallelQuery { get; set; }
public bool? disableFallbackIfMatch { get; set; }
public string? queryStrategy { get; set; } public string? queryStrategy { get; set; }
public string? tag { get; set; } public string? tag { get; set; }
} }
+18
View File
@@ -3636,6 +3636,24 @@ namespace ServiceLib.Resx {
} }
} }
/// <summary>
/// Looks up the localized DNS fallback setting label.
/// </summary>
public static string TbDisableFallbackIfMatch {
get {
return ResourceManager.GetString("TbDisableFallbackIfMatch", resourceCulture);
}
}
/// <summary>
/// Looks up the localized DNS fallback setting explanation.
/// </summary>
public static string TbDisableFallbackIfMatchTip {
get {
return ResourceManager.GetString("TbDisableFallbackIfMatchTip", resourceCulture);
}
}
/// <summary> /// <summary>
/// 查找类似 Parallel Query 的本地化字符串。 /// 查找类似 Parallel Query 的本地化字符串。
/// </summary> /// </summary>
+6
View File
@@ -1974,4 +1974,10 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TransportPathTip6" xml:space="preserve"> <data name="TransportPathTip6" xml:space="preserve">
<value>XDRIVE remote folder</value> <value>XDRIVE remote folder</value>
</data> </data>
<data name="TbDisableFallbackIfMatch" xml:space="preserve">
<value>Restrict DNS fallback on domain match (Xray)</value>
</data>
<data name="TbDisableFallbackIfMatchTip" xml:space="preserve">
<value>Use only DNS servers with matching domain rules, including bootstrap. If all fail, resolution fails. Other domains use the default DNS servers.</value>
</data>
</root> </root>
+6
View File
@@ -1974,4 +1974,10 @@
<data name="TransportPathTip6" xml:space="preserve"> <data name="TransportPathTip6" xml:space="preserve">
<value>Удаленная папка XDRIVE</value> <value>Удаленная папка XDRIVE</value>
</data> </data>
<data name="TbDisableFallbackIfMatch" xml:space="preserve">
<value>Ограничить резервные DNS при совпадении домена (Xray)</value>
</data>
<data name="TbDisableFallbackIfMatchTip" xml:space="preserve">
<value>Только DNS с совпавшими доменными правилами, включая bootstrap. Если все они не сработают, разрешение завершится ошибкой. Для остальных доменов — DNS по умолчанию.</value>
</data>
</root> </root>
@@ -1966,4 +1966,10 @@
<data name="TransportPathTip6" xml:space="preserve"> <data name="TransportPathTip6" xml:space="preserve">
<value>XDRIVE 远端目录</value> <value>XDRIVE 远端目录</value>
</data> </data>
<data name="TbDisableFallbackIfMatch" xml:space="preserve">
<value>域名匹配时限制 DNS 回退(Xray)</value>
</data>
<data name="TbDisableFallbackIfMatchTip" xml:space="preserve">
<value>仅使用域名规则匹配的 DNS(包括引导 DNS)。若全部失败,解析失败。其他域名使用默认 DNS。</value>
</data>
</root> </root>
@@ -81,6 +81,7 @@ public partial class CoreConfigV2rayService
dnsItem.serveStale = simpleDnsItem?.ServeStale is true ? true : null; dnsItem.serveStale = simpleDnsItem?.ServeStale is true ? true : null;
dnsItem.enableParallelQuery = simpleDnsItem?.ParallelQuery is true ? true : null; dnsItem.enableParallelQuery = simpleDnsItem?.ParallelQuery is true ? true : null;
dnsItem.disableFallbackIfMatch = simpleDnsItem?.DisableFallbackIfMatch is true ? true : null;
if (simpleDnsItem.BlockAAAAQuery == true) if (simpleDnsItem.BlockAAAAQuery == true)
{ {
@@ -23,6 +23,7 @@ public partial class DNSSettingViewModel : MyReactiveObject, ICloseable
[Reactive] public partial string Hosts { get; set; } [Reactive] public partial string Hosts { get; set; }
[Reactive] public partial string DirectExpectedIPs { get; set; } [Reactive] public partial string DirectExpectedIPs { get; set; }
[Reactive] public partial bool ParallelQuery { get; set; } [Reactive] public partial bool ParallelQuery { get; set; }
[Reactive] public partial bool DisableFallbackIfMatch { get; set; }
[Reactive] public partial bool ServeStale { get; set; } [Reactive] public partial bool ServeStale { get; set; }
[Reactive] public partial bool EnableHappyEyeballs { get; set; } [Reactive] public partial bool EnableHappyEyeballs { get; set; }
@@ -101,6 +102,7 @@ public partial class DNSSettingViewModel : MyReactiveObject, ICloseable
Hosts = item.Hosts ?? string.Empty; Hosts = item.Hosts ?? string.Empty;
DirectExpectedIPs = item.DirectExpectedIPs ?? string.Empty; DirectExpectedIPs = item.DirectExpectedIPs ?? string.Empty;
ParallelQuery = item.ParallelQuery ?? false; ParallelQuery = item.ParallelQuery ?? false;
DisableFallbackIfMatch = item.DisableFallbackIfMatch ?? false;
ServeStale = item.ServeStale ?? false; ServeStale = item.ServeStale ?? false;
EnableHappyEyeballs = item.EnableHappyEyeballs ?? false; EnableHappyEyeballs = item.EnableHappyEyeballs ?? false;
var item1 = await ConfigDbQuery.GetDNSItem(ECoreType.Xray); var item1 = await ConfigDbQuery.GetDNSItem(ECoreType.Xray);
@@ -145,6 +147,7 @@ public partial class DNSSettingViewModel : MyReactiveObject, ICloseable
_config.SimpleDNSItem.Hosts = Hosts; _config.SimpleDNSItem.Hosts = Hosts;
_config.SimpleDNSItem.DirectExpectedIPs = DirectExpectedIPs; _config.SimpleDNSItem.DirectExpectedIPs = DirectExpectedIPs;
_config.SimpleDNSItem.ParallelQuery = ParallelQuery; _config.SimpleDNSItem.ParallelQuery = ParallelQuery;
_config.SimpleDNSItem.DisableFallbackIfMatch = DisableFallbackIfMatch;
_config.SimpleDNSItem.ServeStale = ServeStale; _config.SimpleDNSItem.ServeStale = ServeStale;
_config.SimpleDNSItem.EnableHappyEyeballs = EnableHappyEyeballs; _config.SimpleDNSItem.EnableHappyEyeballs = EnableHappyEyeballs;
if (NormalDNSCompatible.IsNotEmpty()) if (NormalDNSCompatible.IsNotEmpty())
@@ -42,7 +42,7 @@
x:Name="gridBasicDNSSettings" x:Name="gridBasicDNSSettings"
Margin="{StaticResource Margin8}" Margin="{StaticResource Margin8}"
ColumnDefinitions="Auto,Auto,*" ColumnDefinitions="Auto,Auto,*"
RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto"> RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto">
<TextBlock <TextBlock
x:Name="txtBasicDNSSettingsInvalid" x:Name="txtBasicDNSSettingsInvalid"
@@ -232,6 +232,29 @@
VerticalAlignment="Center" VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbEnableHappyEyeballsTip}" Text="{x:Static resx:ResUI.TbEnableHappyEyeballsTip}"
TextWrapping="Wrap" /> TextWrapping="Wrap" />
<TextBlock
Grid.Row="11"
Grid.Column="0"
MaxWidth="260"
HorizontalAlignment="Left"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbDisableFallbackIfMatch}"
TextWrapping="Wrap" />
<ToggleSwitch
x:Name="togDisableFallbackIfMatch"
Grid.Row="11"
Grid.Column="1"
Margin="{StaticResource Margin4}"
HorizontalAlignment="Left"
VerticalAlignment="Center" />
<TextBlock
Grid.Row="11"
Grid.Column="2"
Margin="{StaticResource Margin4}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbDisableFallbackIfMatchTip}"
TextWrapping="Wrap" />
</Grid> </Grid>
</ScrollViewer> </ScrollViewer>
</TabItem> </TabItem>
@@ -49,6 +49,8 @@ public partial class DNSSettingWindow : WindowBase<DNSSettingViewModel>
this.Bind(ViewModel, vm => vm.Hosts, v => v.txtHosts.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.Hosts, v => v.txtHosts.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DirectExpectedIPs, v => v.cmbDirectExpectedIPs.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.DirectExpectedIPs, v => v.cmbDirectExpectedIPs.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.ParallelQuery, v => v.togParallelQuery.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.ParallelQuery, v => v.togParallelQuery.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DisableFallbackIfMatch, v => v.togDisableFallbackIfMatch.IsChecked).DisposeWith(disposables);
this.OneWayBind(ViewModel, vm => vm.RayCustomDNSEnableCompatible, v => v.togDisableFallbackIfMatch.IsEnabled, enabled => !enabled).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.ServeStale, v => v.togServeStale.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.ServeStale, v => v.togServeStale.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.EnableHappyEyeballs, v => v.togEnableHappyEyeballs.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableHappyEyeballs, v => v.togEnableHappyEyeballs.IsChecked).DisposeWith(disposables);
+24
View File
@@ -54,6 +54,7 @@
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
@@ -264,6 +265,29 @@
Style="{StaticResource ToolbarTextBlock}" Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbEnableHappyEyeballsTip}" Text="{x:Static resx:ResUI.TbEnableHappyEyeballsTip}"
TextWrapping="Wrap" /> TextWrapping="Wrap" />
<TextBlock
Grid.Row="11"
Grid.Column="0"
MaxWidth="260"
HorizontalAlignment="Left"
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbDisableFallbackIfMatch}"
TextWrapping="Wrap" />
<ToggleButton
x:Name="togDisableFallbackIfMatch"
Grid.Row="11"
Grid.Column="1"
Margin="{StaticResource Margin8}"
HorizontalAlignment="Left"
VerticalAlignment="Center" />
<TextBlock
Grid.Row="11"
Grid.Column="2"
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbDisableFallbackIfMatchTip}"
TextWrapping="Wrap" />
</Grid> </Grid>
</ScrollViewer> </ScrollViewer>
</TabItem> </TabItem>
@@ -45,6 +45,8 @@ public partial class DNSSettingWindow
this.Bind(ViewModel, vm => vm.Hosts, v => v.txtHosts.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.Hosts, v => v.txtHosts.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DirectExpectedIPs, v => v.cmbDirectExpectedIPs.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.DirectExpectedIPs, v => v.cmbDirectExpectedIPs.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.ParallelQuery, v => v.togParallelQuery.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.ParallelQuery, v => v.togParallelQuery.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.DisableFallbackIfMatch, v => v.togDisableFallbackIfMatch.IsChecked).DisposeWith(disposables);
this.OneWayBind(ViewModel, vm => vm.RayCustomDNSEnableCompatible, v => v.togDisableFallbackIfMatch.IsEnabled, enabled => !enabled).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.ServeStale, v => v.togServeStale.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.ServeStale, v => v.togServeStale.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.EnableHappyEyeballs, v => v.togEnableHappyEyeballs.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableHappyEyeballs, v => v.togEnableHappyEyeballs.IsChecked).DisposeWith(disposables);